@heyputer/puter.js 2.0.10 → 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,16 +12,37 @@ npm install @heyputer/puter.js
12
12
 
13
13
  ### Importing
14
14
 
15
+ ### Node.js (with Auth Token)
16
+
17
+ ```js
18
+ const {init} = require("@heyputer/puter.js/src/init.cjs"); // NODE JS ONLY
19
+ // or
20
+ import {init} from "@heyputer/puter.js/src/init.cjs";
21
+
22
+ const puter = init(process.env.puterAuthToken); // uses your auth token
23
+ const puter2 = init(process.env.puterAuthToken2); // use some other auth token
24
+ ```
25
+
26
+ ### Browser (without Auth Token)
27
+
15
28
  #### ES Modules
16
29
 
17
30
  ```js
18
- import '@heyputer/puter.js';
31
+ import {puter} from '@heyputer/puter.js';
32
+ // or
33
+ import puter from '@heyputer/puter.js';
34
+ // or
35
+ import '@heyputer/puter.js'; // puter will be available globally
19
36
  ```
20
37
 
21
38
  #### CommonJS
22
39
 
23
40
  ```js
41
+ const {puter} = require('@heyputer/puter.js');
42
+ // or
24
43
  const puter = require('@heyputer/puter.js');
44
+ // or
45
+ require('@heyputer/puter.js'); // puter will be available globally
25
46
  ```
26
47
 
27
48
  #### CDN
package/dist/puter.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Copyright 2024-present Puter Technologies Inc. All rights reserved.
2
- // Generated on 2025-09-19 16:55
2
+ // Generated on 2025-09-19 17:12
3
3
 
4
4
  (()=>{var e={9:e=>{e.exports=class{static ensure_array(e){return Array.isArray(e)?e:[e]}static add(...e){return e.reduce((e,t)=>e+t,0)}static split(e,t,s={}){s=s||{};const{trim:n,discard_empty:r}=s,i=[];s.trim&&i.push(e=>e.map(e=>e.trim())),s.discard_empty&&i.push(e=>e.filter(e=>e.length>0));let o=e.split(t);for(const e of i)o=e(o);return o}}},73:(e,t,s)=>{const{RemoveFromArrayDetachable:n}=s(498),{TTopics:r}=s(868),{install_in_instance:i}=s(912);e.exports={install_in_instance:(e,{parameters:t})=>{const s=e._get_merged_static_array("TOPICS");e._.topics={};for(const t of s)e._.topics[t]={listeners_:[]};e.mixin(r,{pub:(t,s)=>{if(t.includes("!"))throw new Error('"!" in event name reserved for future use');const n=e._.topics[t];if(n)for(const e of n.listeners_)e();else console.warn("missing topic: "+n)},sub:(t,s)=>{const r=e._.topics[t];if(r)return r.listeners_.push(s),new n(r.listeners_,s);console.warn("missing topic: "+r)}})}}},140:(e,t,s)=>{const{AdvancedBase:n}=s(952),r=s(891);class i extends n{static FEATURES=[r()]}e.exports={Emitter:i}},155:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unescape=void 0,t.unescape=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")},178:e=>{e.exports={install_in_instance_:(e,{parameters:t})=>{const s=e._get_merged_static_object("IMPLEMENTS");e._.impls={};for(const t in s){const n=s[t],r={};for(const t in n){const s=n[t];r[t]=s.bind(e)}e._.impls[t]=r}e.as=t=>e._.impls[t],e.list_traits=()=>Object.keys(e._.impls)},install_in_instance:(e,{parameters:t})=>{const s=e._get_inheritance_chain();e._.impls={},e.as=t=>e._.impls[t],e.list_traits=()=>Object.keys(e._.impls),e.mixin=(t,s)=>e._.impls[t]=s;for(const t of s){const s=t.IMPLEMENTS;if(!s)continue;const n=[...Object.getOwnPropertySymbols(s),...Object.keys(s)];for(const t of n){const n=e._.impls[t]??(e._.impls[t]={}),r=s[t];for(const t in r){const s=r[t];n[t]=s.bind(e)}}}}}},259:e=>{class t{static valueOf(){return this.value}}class s extends t{static value=1}class n extends t{static value=1e3*s}class r extends t{static value=60*n}class i extends t{static value=60*r}e.exports={MILLISECOND:s,SECOND:n,MINUTE:r,HOUR:i,DAY:class extends t{static value=24*i}}},274:e=>{function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=274,e.exports=t},294:(e,t,s)=>{const{AdvancedBase:n}=s(952),{Service:r}=s(866),{ServiceManager:i}=s(875),o=s(868);e.exports={AdvancedBase:n,system:{ServiceManager:i},libs:{promise:s(717),context:s(475),listener:s(498),log:s(346),string:s(519),time:s(259),smol:s(9),event:s(140)},features:{EmitterFeature:s(891)},concepts:{Service:r},traits:o}},314:e=>{e.exports={name:"Properties",depends:["Listeners"],install_in_instance:(e,{parameters:t})=>{const s=e._get_merged_static_object("PROPERTIES");e.onchange=(t,s)=>{e._.properties[t].listeners.push(s)},e._.properties={};for(const n in s){const r={definition:s[n],listeners:[],value:void 0};e._.properties[n]=r;let i=null;if("object"==typeof s[n]?(i=s[n],i.factory&&(i.value=i.factory({parameters:t}))):"function"==typeof s[n]&&(i={},i.value=s[n]()),null===i)throw new Error("this will never happen");if(Object.defineProperty(e,n,{get:()=>r.value,set:t=>{for(const s of e._.properties[n].listeners)s(t,{old_value:e[n]});const s=e[n],o=t;i.adapt&&(t=i.adapt(t)),r.value=t,i.post_set&&i.post_set.call(e,t,{intermediate_value:o,old_value:s})}}),r.value=i.value,s[n].construct){const r="string"==typeof s[n].construct?s[n].construct:n;e[n]=t[r]}}}}},346:(e,t,s)=>{const{AdvancedBase:n}=s(952),{TLogger:r,AS:i}=s(868);class o extends n{static MODULES={util:{inspect:e=>e}};static PROPERTIES={console:{construct:!0,factory:()=>console},format:()=>({info:{ansii:""},warn:{ansii:""},error:{ansii:"",err:!0},debug:{ansii:""}})};static IMPLEMENTS={[r]:{log(e,t,s,n){const r=(0,this.require)("util"),i=this.format[e];let o="";o+=`${i.ansii}[${e.toUpperCase()}] `,o+=t,Object.keys(s).length&&(o+=" ",o+=Object.entries(s).map(([e,t])=>`\n ${e}=${r.inspect(t)}`).join(" ")+"\n"),(this.console??console)[i.err?"error":"log"](o,...n)}}}}class a extends n{static PROPERTIES={fields:{construct:!0,factory:()=>({})},delegate:{construct:!0,value:null,adapt:e=>i(e,r)}};static IMPLEMENTS={[r]:{log(e,t,s,n){return this.delegate.log(e,t,Object.assign({},this.fields,s),n)}}}}class c extends n{static PROPERTIES={impl:{value:()=>new o,adapt:e=>i(e,r),construct:!0},cat:{construct:!0}};static IMPLEMENTS={[r]:{log(e,t,s,n){console.log()}}};fields(e){const t=new a({fields:e,delegate:this.impl});return new c({impl:t})}info(e,...t){this.impl.log("info",e,{},t)}on(e){this.cat.on(e)}off(e){this.cat.off(e)}}e.exports={ArrayLogger:class extends n{static PROPERTIES={buffer:{factory:()=>[]}};static IMPLEMENTS={[r]:{log(e,t,s,n){this.buffer.push({level:e,message:t,fields:s,values:n})}}}},CategorizedToggleLogger:class extends n{static PROPERTIES={categories:{description:"categories that are enabled",factory:()=>({})},delegate:{construct:!0,value:null,adapt:e=>i(e,r)}};static IMPLEMENTS={[r]:{log(e,t,s,n){const r=s.category;if(this.categories[r])return this.delegate.log(e,t,s,n)}}};on(e){this.categories[e]=!0}off(e){delete this.categories[e]}},ToggleLogger:class extends n{static PROPERTIES={enabled:{construct:!0,value:!0},delegate:{construct:!0,value:null,adapt:e=>i(e,r)}};static IMPLEMENTS={[r]:{log(e,t,s,n){if(this.enabled)return this.delegate.log(e,t,s,n)}}}},ConsoleLogger:o,PrefixLogger:class extends n{static PROPERTIES={prefix:{construct:!0,value:""},delegate:{construct:!0,value:null,adapt:e=>i(e,r)}};static IMPLEMENTS={[r]:{log(e,t,s,n){return this.delegate.log(e,this.prefix+t,s,n)}}}},FieldsLogger:a,LoggerFacade:c}},385:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertValidPattern=void 0,t.assertValidPattern=e=>{if("string"!=typeof e)throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")}},473:(e,t,s)=>{var n=s(986);e.exports=function(e){return e?("{}"===e.substr(0,2)&&(e="\\{\\}"+e.substr(2)),m(function(e){return e.split("\\\\").join(r).split("\\{").join(i).split("\\}").join(o).split("\\,").join(a).split("\\.").join(c)}(e),!0).map(l)):[]};var r="\0SLASH"+Math.random()+"\0",i="\0OPEN"+Math.random()+"\0",o="\0CLOSE"+Math.random()+"\0",a="\0COMMA"+Math.random()+"\0",c="\0PERIOD"+Math.random()+"\0";function h(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function l(e){return e.split(r).join("\\").split(i).join("{").split(o).join("}").split(a).join(",").split(c).join(".")}function u(e){if(!e)return[""];var t=[],s=n("{","}",e);if(!s)return e.split(",");var r=s.pre,i=s.body,o=s.post,a=r.split(",");a[a.length-1]+="{"+i+"}";var c=u(o);return o.length&&(a[a.length-1]+=c.shift(),a.push.apply(a,c)),t.push.apply(t,a),t}function p(e){return"{"+e+"}"}function d(e){return/^-?0\d/.test(e)}function g(e,t){return e<=t}function f(e,t){return e>=t}function m(e,t){var s=[],r=n("{","}",e);if(!r)return[e];var i=r.pre,a=r.post.length?m(r.post,!1):[""];if(/\$$/.test(r.pre))for(var c=0;c<a.length;c++){var l=i+"{"+r.body+"}"+a[c];s.push(l)}else{var y,b,w=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),v=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),_=w||v,k=r.body.indexOf(",")>=0;if(!_&&!k)return r.post.match(/,(?!,).*\}/)?m(e=r.pre+"{"+r.body+o+r.post):[e];if(_)y=r.body.split(/\.\./);else if(1===(y=u(r.body)).length&&1===(y=m(y[0],!1).map(p)).length)return a.map(function(e){return r.pre+y[0]+e});if(_){var A=h(y[0]),T=h(y[1]),E=Math.max(y[0].length,y[1].length),x=3==y.length?Math.abs(h(y[2])):1,S=g;T<A&&(x*=-1,S=f);var I=y.some(d);b=[];for(var P=A;S(P,T);P+=x){var O;if(v)"\\"===(O=String.fromCharCode(P))&&(O="");else if(O=String(P),I){var R=E-O.length;if(R>0){var C=new Array(R+1).join("0");O=P<0?"-"+C+O.slice(1):C+O}}b.push(O)}}else{b=[];for(var L=0;L<y.length;L++)b.push.apply(b,m(y[L],!1))}for(L=0;L<b.length;L++)for(c=0;c<a.length;c++)l=i+b[L]+a[c],(!t||_||l)&&s.push(l)}return s}},475:e=>{class t{constructor(e={}){const t=Object.getOwnPropertyDescriptors(e);for(const e in t)Object.defineProperty(this,e,t[e])}follow(e,t){const s={};for(const n of t)Object.defineProperty(s,n,{get:()=>e[n]});return this.sub(s)}sub(e){void 0===e&&(e={});const s=Object.create(this),n={};for(const r in s)if(s[r]instanceof t){const t=e.hasOwnProperty(r)?e[r]:void 0;s[r]=s[r].sub(t),n[r]=!0}const r=Object.getOwnPropertyDescriptors(e);for(const e in r)n[e]||Object.defineProperty(s,e,r[e]);return s}}e.exports={Context:t}},498:(e,t,s)=>{const{FeatureBase:n}=s(533),{TDetachable:r}=s(868);class i extends n{static FEATURES=[s(178)];constructor(){super(),this.delegates=[],this.detached_=!1}add(e){this.detached_?e.detach():this.delegates.push(e)}static IMPLEMENTS={[r]:{detach(){this.detached_=!0;for(const e of this.delegates)e.detach()}}}}class o extends n{static FEATURES=[s(178)];constructor(){super(),this.also=()=>{}}also(e){return this.also=e,this}static IMPLEMENTS={[r]:{detach(){this.detach_(),this.also()}}}}e.exports={MultiDetachable:i,RemoveFromArrayDetachable:class extends o{constructor(e,t){super(),this.array=new WeakRef(e),this.element=t}detach_(){const e=this.array.deref();if(!e)return;const t=e.indexOf(this.element);-1!==t&&e.splice(t,1)}}}},504:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.escape=void 0,t.escape=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&")},519:e=>{e.exports={quot:e=>void 0===e?"[undefined]":null===e?"[null]":"function"==typeof e?"[function]":"object"==typeof e?"[object]":"number"==typeof e?"("+e+")":(e=(e=""+e).replace(/["`]/g,e=>'"'===e?"`":'"'),e=(e=JSON.stringify(""+e)).replace(/["`]/g,e=>'"'===e?"`":'"')),osclink:(e,t)=>(t||(t=e),`]8;;${e}\\${t}]8;;\\`),format_as_usd:e=>e<.01?e<1e-5?"$"+e.toExponential(2):"$"+e.toFixed(5):"$"+e.toFixed(2)}},533:(e,t,s)=>{const{BasicBase:n}=s(777);e.exports={FeatureBase:class extends n{constructor(e,...t){super(e,...t),this._={features:this._get_merged_static_array("FEATURES")};for(const t of this._.features)t.install_in_instance(this,{parameters:e||{}})}}}},577:e=>{"use strict";class t{#e;constructor(e=[]){this.#e=[new Map(e)]}get size(){return this.#e.reduce((e,t)=>e+t.size,0)}clear(){this.#e=[new Map]}delete(e){return this.#e.some(t=>t.delete(e))}get(e){for(const t of this.#e)if(t.has(e))return t.get(e)}has(e){return this.#e.some(t=>t.has(e))}set(e,t){let s=this.#e[0];if(this.#e.length>1)for(const t of this.#e)if(t.has(e)){s=t;break}return s.set(e,t),16777215===this.#e[0].size&&this.#e.unshift(new Map),this}*[Symbol.iterator](){for(const e of this.#e)yield*e}*keys(){for(const e of this.#e)yield*e.keys()}*values(){for(const e of this.#e)yield*e.values()}*entries(){for(const e of this.#e)yield*e.entries()}forEach(e,t){for(const[s,n]of this)e.call(t,n,s,this)}}e.exports=t},579:function(e,t,s){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.unescape=t.escape=t.AST=t.Minimatch=t.match=t.makeRe=t.braceExpand=t.defaults=t.filter=t.GLOBSTAR=t.sep=t.minimatch=void 0;const r=n(s(473)),i=s(385),o=s(899),a=s(504),c=s(155);t.minimatch=(e,t,s={})=>((0,i.assertValidPattern)(t),!(!s.nocomment&&"#"===t.charAt(0))&&new C(t,s).match(e));const h=/^\*+([^+@!?\*\[\(]*)$/,l=e=>t=>!t.startsWith(".")&&t.endsWith(e),u=e=>t=>t.endsWith(e),p=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),d=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),g=/^\*+\.\*+$/,f=e=>!e.startsWith(".")&&e.includes("."),m=e=>"."!==e&&".."!==e&&e.includes("."),y=/^\.\*+$/,b=e=>"."!==e&&".."!==e&&e.startsWith("."),w=/^\*+$/,v=e=>0!==e.length&&!e.startsWith("."),_=e=>0!==e.length&&"."!==e&&".."!==e,k=/^\?+([^+@!?\*\[\(]*)?$/,A=([e,t=""])=>{const s=S([e]);return t?(t=t.toLowerCase(),e=>s(e)&&e.toLowerCase().endsWith(t)):s},T=([e,t=""])=>{const s=I([e]);return t?(t=t.toLowerCase(),e=>s(e)&&e.toLowerCase().endsWith(t)):s},E=([e,t=""])=>{const s=I([e]);return t?e=>s(e)&&e.endsWith(t):s},x=([e,t=""])=>{const s=S([e]);return t?e=>s(e)&&e.endsWith(t):s},S=([e])=>{const t=e.length;return e=>e.length===t&&!e.startsWith(".")},I=([e])=>{const t=e.length;return e=>e.length===t&&"."!==e&&".."!==e},P="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";t.sep="win32"===P?"\\":"/",t.minimatch.sep=t.sep,t.GLOBSTAR=Symbol("globstar **"),t.minimatch.GLOBSTAR=t.GLOBSTAR,t.filter=(e,s={})=>n=>(0,t.minimatch)(n,e,s),t.minimatch.filter=t.filter;const O=(e,t={})=>Object.assign({},e,t);t.defaults=e=>{if(!e||"object"!=typeof e||!Object.keys(e).length)return t.minimatch;const s=t.minimatch;return Object.assign((t,n,r={})=>s(t,n,O(e,r)),{Minimatch:class extends s.Minimatch{constructor(t,s={}){super(t,O(e,s))}static defaults(t){return s.defaults(O(e,t)).Minimatch}},AST:class extends s.AST{constructor(t,s,n={}){super(t,s,O(e,n))}static fromGlob(t,n={}){return s.AST.fromGlob(t,O(e,n))}},unescape:(t,n={})=>s.unescape(t,O(e,n)),escape:(t,n={})=>s.escape(t,O(e,n)),filter:(t,n={})=>s.filter(t,O(e,n)),defaults:t=>s.defaults(O(e,t)),makeRe:(t,n={})=>s.makeRe(t,O(e,n)),braceExpand:(t,n={})=>s.braceExpand(t,O(e,n)),match:(t,n,r={})=>s.match(t,n,O(e,r)),sep:s.sep,GLOBSTAR:t.GLOBSTAR})},t.minimatch.defaults=t.defaults,t.braceExpand=(e,t={})=>((0,i.assertValidPattern)(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:(0,r.default)(e)),t.minimatch.braceExpand=t.braceExpand,t.makeRe=(e,t={})=>new C(e,t).makeRe(),t.minimatch.makeRe=t.makeRe,t.match=(e,t,s={})=>{const n=new C(t,s);return e=e.filter(e=>n.match(e)),n.options.nonull&&!e.length&&e.push(t),e},t.minimatch.match=t.match;const R=/[?*]|[+@!]\(.*?\)|\[|\]/;class C{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){(0,i.assertValidPattern)(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||P,this.isWindows="win32"===this.platform,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||!1===t.allowWindowsEscape,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=void 0!==t.windowsNoMagicRoot?t.windowsNoMagicRoot:!(!this.isWindows||!this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const e of this.set)for(const t of e)if("string"!=typeof t)return!0;return!1}debug(...e){}make(){const e=this.pattern,t=this.options;if(!t.nocomment&&"#"===e.charAt(0))return void(this.comment=!0);if(!e)return void(this.empty=!0);this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);const s=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let n=this.globParts.map((e,t,s)=>{if(this.isWindows&&this.windowsNoMagicRoot){const t=!(""!==e[0]||""!==e[1]||"?"!==e[2]&&R.test(e[2])||R.test(e[3])),s=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(s)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,n),this.set=n.filter(e=>-1===e.indexOf(!1)),this.isWindows)for(let e=0;e<this.set.length;e++){const t=this.set[e];""===t[0]&&""===t[1]&&"?"===this.globParts[e][2]&&"string"==typeof t[3]&&/^[a-z]:$/i.test(t[3])&&(t[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t=0;t<e.length;t++)for(let s=0;s<e[t].length;s++)"**"===e[t][s]&&(e[t][s]="*");const{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;-1!==(t=e.indexOf("**",t+1));){let s=t;for(;"**"===e[s+1];)s++;s!==t&&e.splice(t,s-t)}return e})}levelOneOptimize(e){return e.map(e=>0===(e=e.reduce((e,t)=>{const s=e[e.length-1];return"**"===t&&"**"===s?e:".."===t&&s&&".."!==s&&"."!==s&&"**"!==s?(e.pop(),e):(e.push(t),e)},[])).length?[""]:e)}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){const n=e[s];1===s&&""===n&&""===e[0]||"."!==n&&""!==n||(t=!0,e.splice(s,1),s--)}"."!==e[0]||2!==e.length||"."!==e[1]&&""!==e[1]||(t=!0,e.pop())}let s=0;for(;-1!==(s=e.indexOf("..",s+1));){const n=e[s-1];n&&"."!==n&&".."!==n&&"**"!==n&&(t=!0,e.splice(s-1,2),s-=2)}}while(t);return 0===e.length?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let s of e){let n=-1;for(;-1!==(n=s.indexOf("**",n+1));){let r=n;for(;"**"===s[r+1];)r++;r>n&&s.splice(n+1,r-n);let i=s[n+1];const o=s[n+2],a=s[n+3];if(".."!==i)continue;if(!o||"."===o||".."===o||!a||"."===a||".."===a)continue;t=!0,s.splice(n,1);const c=s.slice(0);c[n]="**",e.push(c),n--}if(!this.preserveMultipleSlashes){for(let e=1;e<s.length-1;e++){const n=s[e];1===e&&""===n&&""===s[0]||"."!==n&&""!==n||(t=!0,s.splice(e,1),e--)}"."!==s[0]||2!==s.length||"."!==s[1]&&""!==s[1]||(t=!0,s.pop())}let r=0;for(;-1!==(r=s.indexOf("..",r+1));){const e=s[r-1];if(e&&"."!==e&&".."!==e&&"**"!==e){t=!0;const e=1===r&&"**"===s[r+1]?["."]:[];s.splice(r-1,2,...e),0===s.length&&s.push(""),r-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++){const n=this.partsMatch(e[t],e[s],!this.preserveMultipleSlashes);if(n){e[t]=[],e[s]=n;break}}return e.filter(e=>e.length)}partsMatch(e,t,s=!1){let n=0,r=0,i=[],o="";for(;n<e.length&&r<t.length;)if(e[n]===t[r])i.push("b"===o?t[r]:e[n]),n++,r++;else if(s&&"**"===e[n]&&t[r]===e[n+1])i.push(e[n]),n++;else if(s&&"**"===t[r]&&e[n]===t[r+1])i.push(t[r]),r++;else if("*"!==e[n]||!t[r]||!this.options.dot&&t[r].startsWith(".")||"**"===t[r]){if("*"!==t[r]||!e[n]||!this.options.dot&&e[n].startsWith(".")||"**"===e[n])return!1;if("a"===o)return!1;o="b",i.push(t[r]),n++,r++}else{if("b"===o)return!1;o="a",i.push(e[n]),n++,r++}return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;const e=this.pattern;let t=!1,s=0;for(let n=0;n<e.length&&"!"===e.charAt(n);n++)t=!t,s++;s&&(this.pattern=e.slice(s)),this.negate=t}matchOne(e,s,n=!1){const r=this.options;if(this.isWindows){const t="string"==typeof e[0]&&/^[a-z]:$/i.test(e[0]),n=!t&&""===e[0]&&""===e[1]&&"?"===e[2]&&/^[a-z]:$/i.test(e[3]),r="string"==typeof s[0]&&/^[a-z]:$/i.test(s[0]),i=n?3:t?0:void 0,o=!r&&""===s[0]&&""===s[1]&&"?"===s[2]&&"string"==typeof s[3]&&/^[a-z]:$/i.test(s[3])?3:r?0:void 0;if("number"==typeof i&&"number"==typeof o){const[t,n]=[e[i],s[o]];t.toLowerCase()===n.toLowerCase()&&(s[o]=t,o>i?s=s.slice(o):i>o&&(e=e.slice(i)))}}const{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:s}),this.debug("matchOne",e.length,s.length);for(var o=0,a=0,c=e.length,h=s.length;o<c&&a<h;o++,a++){this.debug("matchOne loop");var l=s[a],u=e[o];if(this.debug(s,l,u),!1===l)return!1;if(l===t.GLOBSTAR){this.debug("GLOBSTAR",[s,l,u]);var p=o,d=a+1;if(d===h){for(this.debug("** at the end");o<c;o++)if("."===e[o]||".."===e[o]||!r.dot&&"."===e[o].charAt(0))return!1;return!0}for(;p<c;){var g=e[p];if(this.debug("\nglobstar while",e,p,s,d,g),this.matchOne(e.slice(p),s.slice(d),n))return this.debug("globstar found match!",p,c,g),!0;if("."===g||".."===g||!r.dot&&"."===g.charAt(0)){this.debug("dot detected!",e,p,s,d);break}this.debug("globstar swallow a segment, and continue"),p++}return!(!n||(this.debug("\n>>> no match, partial?",e,p,s,d),p!==c))}let i;if("string"==typeof l?(i=u===l,this.debug("string match",l,u,i)):(i=l.test(u),this.debug("pattern match",l,u,i)),!i)return!1}if(o===c&&a===h)return!0;if(o===c)return n;if(a===h)return o===c-1&&""===e[o];throw new Error("wtf?")}braceExpand(){return(0,t.braceExpand)(this.pattern,this.options)}parse(e){(0,i.assertValidPattern)(e);const s=this.options;if("**"===e)return t.GLOBSTAR;if(""===e)return"";let n,r=null;(n=e.match(w))?r=s.dot?_:v:(n=e.match(h))?r=(s.nocase?s.dot?d:p:s.dot?u:l)(n[1]):(n=e.match(k))?r=(s.nocase?s.dot?T:A:s.dot?E:x)(n):(n=e.match(g))?r=s.dot?m:f:(n=e.match(y))&&(r=b);const a=o.AST.fromGlob(e,this.options).toMMPattern();return r&&"object"==typeof a&&Reflect.defineProperty(a,"test",{value:r}),a}makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;const e=this.set;if(!e.length)return this.regexp=!1,this.regexp;const s=this.options,n=s.noglobstar?"[^/]*?":s.dot?"(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?":"(?:(?!(?:\\/|^)\\.).)*?",r=new Set(s.nocase?["i"]:[]);let i=e.map(e=>{const s=e.map(e=>{if(e instanceof RegExp)for(const t of e.flags.split(""))r.add(t);return"string"==typeof e?e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"):e===t.GLOBSTAR?t.GLOBSTAR:e._src});return s.forEach((e,r)=>{const i=s[r+1],o=s[r-1];e===t.GLOBSTAR&&o!==t.GLOBSTAR&&(void 0===o?void 0!==i&&i!==t.GLOBSTAR?s[r+1]="(?:\\/|"+n+"\\/)?"+i:s[r]=n:void 0===i?s[r-1]=o+"(?:\\/|"+n+")?":i!==t.GLOBSTAR&&(s[r-1]=o+"(?:\\/|\\/"+n+"\\/)"+i,s[r+1]=t.GLOBSTAR))}),s.filter(e=>e!==t.GLOBSTAR).join("/")}).join("|");const[o,a]=e.length>1?["(?:",")"]:["",""];i="^"+o+i+a+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...r].join(""))}catch(e){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return""===e;if("/"===e&&t)return!0;const s=this.options;this.isWindows&&(e=e.split("\\").join("/"));const n=this.slashSplit(e);this.debug(this.pattern,"split",n);const r=this.set;this.debug(this.pattern,"set",r);let i=n[n.length-1];if(!i)for(let e=n.length-2;!i&&e>=0;e--)i=n[e];for(let e=0;e<r.length;e++){const o=r[e];let a=n;if(s.matchBase&&1===o.length&&(a=[i]),this.matchOne(a,o,t))return!!s.flipNegate||!this.negate}return!s.flipNegate&&this.negate}static defaults(e){return t.minimatch.defaults(e).Minimatch}}t.Minimatch=C;var L=s(899);Object.defineProperty(t,"AST",{enumerable:!0,get:function(){return L.AST}});var D=s(504);Object.defineProperty(t,"escape",{enumerable:!0,get:function(){return D.escape}});var M=s(155);Object.defineProperty(t,"unescape",{enumerable:!0,get:function(){return M.unescape}}),t.minimatch.AST=o.AST,t.minimatch.Minimatch=C,t.minimatch.escape=a.escape,t.minimatch.unescape=c.unescape},618:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseClass=void 0;const s={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},n=e=>e.replace(/[[\]\\-]/g,"\\$&"),r=e=>e.join("");t.parseClass=(e,t)=>{const i=t;if("["!==e.charAt(i))throw new Error("not in a brace expression");const o=[],a=[];let c=i+1,h=!1,l=!1,u=!1,p=!1,d=i,g="";e:for(;c<e.length;){const t=e.charAt(c);if("!"!==t&&"^"!==t||c!==i+1){if("]"===t&&h&&!u){d=c+1;break}if(h=!0,"\\"!==t||u){if("["===t&&!u)for(const[t,[n,r,h]]of Object.entries(s))if(e.startsWith(t,c)){if(g)return["$.",!1,e.length-i,!0];c+=t.length,h?a.push(n):o.push(n),l=l||r;continue e}u=!1,g?(t>g?o.push(n(g)+"-"+n(t)):t===g&&o.push(n(t)),g="",c++):e.startsWith("-]",c+1)?(o.push(n(t+"-")),c+=2):e.startsWith("-",c+1)?(g=t,c+=2):(o.push(n(t)),c++)}else u=!0,c++}else p=!0,c++}if(d<c)return["",!1,0,!1];if(!o.length&&!a.length)return["$.",!1,e.length-i,!0];if(0===a.length&&1===o.length&&/^\\?.$/.test(o[0])&&!p){return[(f=2===o[0].length?o[0].slice(-1):o[0],f.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")),!1,d-i,!1]}var f;const m="["+(p?"^":"")+r(o)+"]",y="["+(p?"":"^")+r(a)+"]";return[o.length&&a.length?"("+m+"|"+y+")":o.length?m:y,l,d-i,!0]}},659:e=>{e.exports={readme:"\n Normalized Asynchronous Request Invocation (NARI) Methods Feature\n\n This feature allows a class to define \"Nari methods\", which are methods\n that support both async/await and callback-style invocation, have\n positional arguments, and an options argument.\n\n \"the expected interface for methods in puter.js\"\n\n The underlying method will receive parameters as an object, with the\n positional arguments as keys in the object. The options argument will\n be merged into the parameters object unless the method spec specifies\n `separate_options: true`.\n\n Example:\n\n ```\n class MyClass extends AdvancedBase {\n static NARI_METHODS = {\n myMethod: {\n positional: ['param1', 'param2'],\n fn: ({ param1, param2 }) => {\n return param1 + param2;\n }\n }\n }\n }\n\n const instance = new MyClass();\n const result = instance.myMethod(1, 2); // returns 3\n ```\n\n The method can also be called with options and callbacks:\n\n ```\n instance.myMethod(1, 2, { option1: 'value' }, (result) => {\n console.log('success', result);\n }, (error) => {\n console.error('error', error);\n });\n ```\n ",install_in_instance:e=>{const t=e._get_merged_static_object("NARI_METHODS");e._.nariMethods={};for(const s in t){const n=t[s],r=n.fn.bind(e);e._.nariMethods[s]=r,e[s]=async(...e)=>{const t=n.firstarg_options&&"object"==typeof e[0]?0:n.positional.length,s=e.slice(0,t),i=e.slice(t),o={},a={},c={};for(const[e,t]of s.entries())o[n.positional[e]]=t;let h;"object"==typeof i[0]&&(Object.assign(a,i[0]),i.shift()),"function"==typeof i[0]?(c.success=i[0],i.shift()):a.success&&(c.success=a.success),"function"==typeof i[0]?(c.error=i[0],i.shift()):a.error&&(c.error=a.error),n.separate_options?o.options=a:Object.assign(o,a);try{h=await r(o)}catch(e){if(!c.error)throw e;c.error(e)}return c.success&&c.success(h),h}}}}},696:(e,t,s)=>{const{TTopics:n}=s(868);e.exports={install_in_instance:(e,{parameters:t})=>{const s=e._get_merged_static_array("HOOKS");e._.init_hooks=e._.init_hooks??[];for(const t of s)e._.init_hooks.push(()=>{e._.context.services.info(t.service).instance.as(n).sub(t.event,t.do.bind(e))})}}},717:e=>{class t{static STATUS_PENDING=Symbol("pending");static STATUS_RUNNING={};static STATUS_DONE=Symbol("done");constructor(){this.status_=this.constructor.STATUS_PENDING,this.donePromise=new Promise((e,t)=>{this.doneResolve=e,this.doneReject=t})}get status(){return this.status_}set status(e){this.status_=e,e===this.constructor.STATUS_DONE&&this.doneResolve()}resolve(e){this.status_=this.constructor.STATUS_DONE,this.doneResolve(e)}awaitDone(){return this.donePromise}then(e,...t){return this.donePromise.then(e,...t)}reject(e){this.status_=this.constructor.STATUS_DONE,this.doneReject(e)}onComplete(e){return this.then(e)}}class s{static TYPE_READ=Symbol("read");static TYPE_WRITE=Symbol("write");constructor(){this.queue=[],this.readers_=0,this.writer_=!1,this.on_empty_=()=>{},this.mode=this.constructor.TYPE_READ}get effective_mode(){return this.readers_>0?this.constructor.TYPE_READ:this.writer_?this.constructor.TYPE_WRITE:void 0}push_(e){0!==this.readers_||this.writer_||(this.mode=e.type),this.queue.push(e),this.check_queue_()}check_queue_(){if(0===this.queue.length)return void(0!==this.readers_||this.writer_||this.on_empty_());const e=()=>this.queue[0];if(0!==this.readers_||this.writer_||(this.mode=e().type),this.mode===this.constructor.TYPE_READ){for(;e()?.type===this.constructor.TYPE_READ;){const e=this.queue.shift();this.readers_++,(async()=>{await e.p_unlock,this.readers_--,this.check_queue_()})(),e.p_operation.resolve()}return}if(this.writer_)return;const t=this.queue.shift();this.writer_=!0,(async()=>{await t.p_unlock,this.writer_=!1,this.check_queue_()})(),t.p_operation.resolve()}async rlock(){const e=new t,s=new t,n={unlock:()=>{s.resolve()}};return this.push_({type:this.constructor.TYPE_READ,p_operation:e,p_unlock:s}),await e,n}async wlock(){const e=new t,s=new t,n={unlock:()=>{s.resolve()}};return this.push_({type:this.constructor.TYPE_WRITE,p_operation:e,p_unlock:s}),await e,n}}e.exports={TeePromise:t,Lock:class{constructor(){this._locked=!1,this._waiting=[]}async acquire(e){if(await new Promise(e=>{this._locked?this._waiting.push({resolve:e}):(this._locked=!0,e())}),e){let t;try{t=await e()}finally{this.release()}return t}}release(){if(this._waiting.length>0){const{resolve:e}=this._waiting.shift();e()}else this._locked=!1}},RWLock:s,asyncSafeSetInterval:async(e,t,s,n)=>{s=s??[],n=n??{};const{onBehindSchedule:r}=n,i=e=>new Promise(t=>setTimeout(t,e));for(;;){await i(t);const n=Date.now();await e(...s);const o=t-(Date.now()-n);if(o<0){if(r&&await r(-o))return}else await i(o)}},raceCase:async e=>Promise.race(Object.entries(e).map(([e,t])=>t.then(t=>[e,t])))}},777:e=>{class t{_get_inheritance_chain(){const e=[];let s=this.constructor;for(;s&&s!==t;)e.push(s),s=s.__proto__;return e.reverse()}_get_merged_static_array(e){const t=this._get_inheritance_chain(),s=[];let n=null;for(const r of t)r[e]&&r[e]!==n&&(n=r[e],s.push(...r[e]));return s}_get_merged_static_object(e){const t=this._get_inheritance_chain(),s={};for(const n of t)n[e]&&Object.assign(s,n[e]);return s}}e.exports={BasicBase:t}},866:(e,t,s)=>{const{AdvancedBase:n}=s(952),r=s(696),i=async()=>{},o=Symbol("TService");e.exports={TService:o,Service:class extends n{static FEATURES=[r];async __on(e,t){const s=this.__get_event_handler(e);return await s(e,...t)}__get_event_handler(e){return this[`__on_${e}`]?.bind?.(this)||this.constructor[`__on_${e}`]?.bind?.(this.constructor)||i}static create({parameters:e,context:t}){const s=new this;return s._.context=t,s.as(o).construct(e),s}static IMPLEMENTS={[o]:{init(...e){if(this._.init_hooks)for(const e of this._.init_hooks)e.call(this);if(this._init)return this._init(...e)},construct(e){this.$parameters={};for(const t in e)this.$parameters[t]=e[t];if(this._construct)return this._construct(e)},get_depends(){return[...this.constructor.DEPENDS??[],...this.get_depends?.()??[]]}}}}}},868:e=>{e.exports={TTopics:Symbol("TTopics"),TDetachable:Symbol("TDetachable"),TLogger:Symbol("TLogger"),AS:(e,t)=>e.constructor&&e.constructor.IMPLEMENTS&&e.constructor.IMPLEMENTS[t]?e.as(t):e}},875:(e,t,s)=>{const{AdvancedBase:n}=s(952),{TService:r}=s(866),i="running";e.exports={ServiceManager:class extends n{constructor({context:e}={}){super(),this.context=e,this.services_l_=[],this.services_m_={},this.service_infos_={},this.init_listeners_=[],this.waiting_={}}async register(e,t,s={}){await new Promise(e=>setTimeout(e,0));const n={name:e,instance:t.create({parameters:s.parameters??{},context:this.context}),status:"registering"};this.services_l_.push(n),this.services_m_[e]=n,await this.maybe_init_(e)}info(e){return this.services_m_[e]}get(e){const t=this.services_m_[e];if(!t)throw new Error(`Service not registered: ${e}`);if(t.status===i)return t.instance}async aget(e){return await this.wait_for_init([e]),this.get(e)}async wait_for_init(e){let t;await new Promise(s=>{t=()=>{if(0===this.get_waiting_for_(e).length){const e=this.init_listeners_.indexOf(t);return-1!==e&&this.init_listeners_.splice(e,1),s(),!0}},t()||this.init_listeners_.push(t)})}get_waiting_for_(e){const t=[];for(const s of e){const e=this.services_m_[s];e?e.status!==i&&t.push(s):t.push(s)}return t}async maybe_init_(e){const t=this.services_m_[e],s=t.instance.as(r).get_depends(),n=this.get_waiting_for_(s);if(0!==n.length){for(const t of n)this.waiting_[t]||(this.waiting_[t]=new Set),this.waiting_[t].add(e);t.status="pending",t.statusWaitingFor=n}else await this.init_service_(e)}async init_service_(e,t={}){const s=this.services_m_[e];s.status="initializing";const n=s.instance.as(r);await n.init(),s.status=i,s.statusStartTS=new Date;const o=this.waiting_[e],a=[];if(o)for(const e of o.values())a.push(this.maybe_init_(e,{no_init_listeners:!0}));if(await Promise.all(a),!t.no_init_listeners)for(const e of this.init_listeners_)await e()}}}},891:e=>{e.exports=({decorators:e}={})=>({install_in_instance(t,{parameters:s}){const n=t._.emitterFeature={};n.listeners_={},n.global_listeners_=[],n.callbackDecorators=e||[],t.emit=async(e,t,s)=>{s=s??{};const r=e.split("."),i=[];for(let r=0;r<n.global_listeners_.length;r++){let o=n.global_listeners_[r];for(const e of n.callbackDecorators)o=e(o);i.push(o(e,t,{...s,key:e}))}for(let o=0;o<r.length;o++){const a=o===r.length-1?r.join("."):r.slice(0,o+1).join(".")+".*",c=n.listeners_[a];if(c)for(let r=0;r<c.length;r++){let o=c[r];for(const e of n.callbackDecorators)o=e(o);i.push(o(t,{...s,key:e}))}}return await Promise.all(i)},t.on=(e,t)=>{const s=n.listeners_[e]||(n.listeners_[e]=[]);return s.push(t),{detach:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}},t.on_all=e=>{n.global_listeners_.push(e)}}})},899:(e,t,s)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AST=void 0;const n=s(618),r=s(155),i=new Set(["!","?","+","*","@"]),o=e=>i.has(e),a="(?!\\.)",c=new Set(["[","."]),h=new Set(["..","."]),l=new Set("().*{}+?[]^$\\!"),u=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),p="[^/]",d=p+"*?",g=p+"+?";class f{type;#t;#s;#n=!1;#r=[];#i;#o;#a;#c=!1;#h;#l;#u=!1;constructor(e,t,s={}){this.type=e,e&&(this.#s=!0),this.#i=t,this.#t=this.#i?this.#i.#t:this,this.#h=this.#t===this?s:this.#t.#h,this.#a=this.#t===this?[]:this.#t.#a,"!"!==e||this.#t.#c||this.#a.push(this),this.#o=this.#i?this.#i.#r.length:0}get hasMagic(){if(void 0!==this.#s)return this.#s;for(const e of this.#r)if("string"!=typeof e&&(e.type||e.hasMagic))return this.#s=!0;return this.#s}toString(){return void 0!==this.#l?this.#l:this.type?this.#l=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#l=this.#r.map(e=>String(e)).join("")}#p(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;let e;for(this.toString(),this.#c=!0;e=this.#a.pop();){if("!"!==e.type)continue;let t=e,s=t.#i;for(;s;){for(let n=t.#o+1;!s.type&&n<s.#r.length;n++)for(const t of e.#r){if("string"==typeof t)throw new Error("string part in extglob AST??");t.copyIn(s.#r[n])}t=s,s=t.#i}}return this}push(...e){for(const t of e)if(""!==t){if("string"!=typeof t&&!(t instanceof f&&t.#i===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){const e=null===this.type?this.#r.slice().map(e=>"string"==typeof e?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&"!"===this.#i?.type)&&e.push({}),e}isStart(){if(this.#t===this)return!0;if(!this.#i?.isStart())return!1;if(0===this.#o)return!0;const e=this.#i;for(let t=0;t<this.#o;t++){const s=e.#r[t];if(!(s instanceof f&&"!"===s.type))return!1}return!0}isEnd(){if(this.#t===this)return!0;if("!"===this.#i?.type)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();const e=this.#i?this.#i.#r.length:0;return this.#o===e-1}copyIn(e){"string"==typeof e?this.push(e):this.push(e.clone(this))}clone(e){const t=new f(this.type,e);for(const e of this.#r)t.copyIn(e);return t}static#d(e,t,s,n){let r=!1,i=!1,a=-1,c=!1;if(null===t.type){let h=s,l="";for(;h<e.length;){const s=e.charAt(h++);if(r||"\\"===s)r=!r,l+=s;else if(i)h===a+1?"^"!==s&&"!"!==s||(c=!0):"]"!==s||h===a+2&&c||(i=!1),l+=s;else if("["!==s){if(!n.noext&&o(s)&&"("===e.charAt(h)){t.push(l),l="";const r=new f(s,t);h=f.#d(e,r,h,n),t.push(r);continue}l+=s}else i=!0,a=h,c=!1,l+=s}return t.push(l),h}let h=s+1,l=new f(null,t);const u=[];let p="";for(;h<e.length;){const s=e.charAt(h++);if(r||"\\"===s)r=!r,p+=s;else if(i)h===a+1?"^"!==s&&"!"!==s||(c=!0):"]"!==s||h===a+2&&c||(i=!1),p+=s;else if("["!==s){if(o(s)&&"("===e.charAt(h)){l.push(p),p="";const t=new f(s,l);l.push(t),h=f.#d(e,t,h,n);continue}if("|"!==s){if(")"===s)return""===p&&0===t.#r.length&&(t.#u=!0),l.push(p),p="",t.push(...u,l),h;p+=s}else l.push(p),p="",u.push(l),l=new f(null,t)}else i=!0,a=h,c=!1,p+=s}return t.type=null,t.#s=void 0,t.#r=[e.substring(s-1)],h}static fromGlob(e,t={}){const s=new f(null,void 0,t);return f.#d(e,s,0,t),s}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();const e=this.toString(),[t,s,n,r]=this.toRegExpSource();if(!(n||this.#s||this.#h.nocase&&!this.#h.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;const i=(this.#h.nocase?"i":"")+(r?"u":"");return Object.assign(new RegExp(`^${t}$`,i),{_src:t,_glob:e})}get options(){return this.#h}toRegExpSource(e){const t=e??!!this.#h.dot;if(this.#t===this&&this.#p(),!this.type){const s=this.isStart()&&this.isEnd(),n=this.#r.map(t=>{const[n,r,i,o]="string"==typeof t?f.#g(t,this.#s,s):t.toRegExpSource(e);return this.#s=this.#s||i,this.#n=this.#n||o,n}).join("");let i="";if(this.isStart()&&"string"==typeof this.#r[0]&&(1!==this.#r.length||!h.has(this.#r[0]))){const s=c,r=t&&s.has(n.charAt(0))||n.startsWith("\\.")&&s.has(n.charAt(2))||n.startsWith("\\.\\.")&&s.has(n.charAt(4)),o=!t&&!e&&s.has(n.charAt(0));i=r?"(?!(?:^|/)\\.\\.?(?:$|/))":o?a:""}let o="";return this.isEnd()&&this.#t.#c&&"!"===this.#i?.type&&(o="(?:$|\\/)"),[i+n+o,(0,r.unescape)(n),this.#s=!!this.#s,this.#n]}const s="*"===this.type||"+"===this.type,n="!"===this.type?"(?:(?!(?:":"(?:";let i=this.#f(t);if(this.isStart()&&this.isEnd()&&!i&&"!"!==this.type){const e=this.toString();return this.#r=[e],this.type=null,this.#s=void 0,[e,(0,r.unescape)(this.toString()),!1,!1]}let o=!s||e||t?"":this.#f(!0);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let l="";return l="!"===this.type&&this.#u?(this.isStart()&&!t?a:"")+g:n+i+("!"===this.type?"))"+(!this.isStart()||t||e?"":a)+d+")":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&o?")":"*"===this.type&&o?")?":`)${this.type}`),[l,(0,r.unescape)(i),this.#s=!!this.#s,this.#n]}#f(e){return this.#r.map(t=>{if("string"==typeof t)throw new Error("string type in extglob ast??");const[s,n,r,i]=t.toRegExpSource(e);return this.#n=this.#n||i,s}).filter(e=>!(this.isStart()&&this.isEnd()&&!e)).join("|")}static#g(e,t,s=!1){let i=!1,o="",a=!1;for(let r=0;r<e.length;r++){const c=e.charAt(r);if(i)i=!1,o+=(l.has(c)?"\\":"")+c;else if("\\"!==c){if("["===c){const[s,i,c,h]=(0,n.parseClass)(e,r);if(c){o+=s,a=a||i,r+=c-1,t=t||h;continue}}"*"!==c?"?"!==c?o+=u(c):(o+=p,t=!0):(o+=s&&"*"===e?g:d,t=!0)}else r===e.length-1?o+="\\\\":i=!0}return[o,(0,r.unescape)(e),!!t,a]}}t.AST=f},910:(e,t,s)=>{"use strict";const{minimatch:n}=s(579),r=s(577);e.exports=class{constructor(){this.store=new r,this.expireTimes=new r,this.storeSet=(e,t)=>{this.store.set(e,t),this._initCleanupLoop(20)}}set(e,t,s={}){const{NX:n=!1,XX:r=!1,GET:i=!1,EX:o,PX:a,EXAT:c,PXAT:h,KEEPTTL:l=!1}=s,u=n,p=r,d=i;let g=o?parseInt(o,10):void 0,f=a?parseInt(a,10):void 0,m=c?parseInt(c,10):void 0,y=h?parseInt(h,10):void 0;const b=l,w=this.store.has(e);if(p&&!w)return;if(u&&w)return;let v;if(d&&w&&(v=this.store.get(e)),this.storeSet(e,t),void 0!==g||void 0!==f||void 0!==m||void 0!==y||b){let t;void 0!==g?t=Date.now()+1e3*g:void 0!==f?t=Date.now()+f:void 0!==m?t=1e3*m:void 0!==y?t=y:b&&w&&(t=this.expireTimes.get(e)),void 0!==t&&this.expireTimes.set(e,t)}else this.expireTimes.delete(e);return!d||v}get(e){if(!this._checkAndRemoveExpiredKey(e))return this.store.get(e)}del(...e){let t=0;for(const s of e)this._checkAndRemoveExpiredKey(s)||this.store.delete(s)&&(this.expireTimes.delete(s),t++);return t}exists(...e){let t=0;for(const s of e)this._checkAndRemoveExpiredKey(s)||this.store.has(s)&&t++;return t}incr(e){return this.incrby(e,1)}incrby(e,t){let s=this.store.get(e);if(void 0===s)s=0;else if(!Number.isInteger(Number(s)))throw new Error("ERR value is not an integer");const n=Number(s)+t;return this.storeSet(e,n.toString()),n}decr(e){try{return this.decrby(e,1)}catch(e){throw e}}decrby(e,t){let s=this.store.get(e);if(void 0===s)s=0;else if(!Number.isInteger(Number(s)))throw new Error("ERR value is not an integer");const n=Number(s)-t;return this.storeSet(e,n.toString()),n}expire(e,t,s={}){if(!this.store.has(e))return 0;const{NX:n=!1,XX:r=!1,GT:i=!1,LT:o=!1}=s,a=Date.now(),c=this.expireTimes.get(e);return n&&void 0!==c||r&&void 0===c||i&&(void 0===c||c<=a+1e3*t)||o&&(void 0===c||c>=a+1e3*t)?0:(this.expireTimes.set(e,a+1e3*t),1)}keys(e){const t=[];for(const[s,r]of this.store.entries())if(n(s,e,{nocase:!0})){const e=this.expireTimes.get(s);(void 0===e||e>Date.now())&&t.push(s)}return t}mget(...e){return e.map(e=>this.get(e))}mset(...e){if(e.length%2!=0)throw new Error("MSET requires an even number of arguments");for(let t=0;t<e.length;t+=2)this.set(e[t],e[t+1]);return!0}renamenx(e,t){if(!this.store.has(e)||this.store.has(t))return 0;const s=this.store.get(e);if(this.store.delete(e),this.storeSet(t,s),this.expireTimes.has(e)){const s=this.expireTimes.get(e);this.expireTimes.delete(e),this.expireTimes.set(t,s)}return 1}randomkey(){const e=Array.from(this.store.keys());if(0!==e.length)return e[Math.floor(Math.random()*e.length)]}expireat(e,t,s={}){if("number"!=typeof t||isNaN(t))throw new Error("ERR invalid expire time in SETEX");if(!this.store.has(e))return 0;const{NX:n=!1,XX:r=!1,GT:i=!1,LT:o=!1}=s,a=1e3*t-Date.now();if(a<=0)return this.store.delete(e),this.expireTimes.delete(e),0;const c=this.pttl(e);return r&&-1===c||n&&-1!==c||i&&-1!==c&&a<=c||o&&-1!==c&&a>=c?0:this.pexpire(e,a)}pexpire(e,t,s={}){const{NX:n=!1,XX:r=!1,GT:i=!1,LT:o=!1}=s;if(n&&this.store.has(e)||r&&!this.store.has(e))return 0;if(i||o){const s=this.pttl(e);if(i&&s>=t||o&&s<=t)return 0}return this.expireTimes.set(e,Date.now()+t),1}pexpireat(e,t){const s=t-Date.now();return s<=0?(this.store.delete(e),this.expireTimes.delete(e),0):this.pexpire(e,s)}pttl(e){if(!this.store.has(e))return-2;if(!this.expireTimes.has(e))return-1;const t=this.expireTimes.get(e)-Date.now();return t>0?t:-2}ttl(e){if(!this.store.has(e))return-2;if(!this.expireTimes.has(e))return-1;const t=Math.floor((this.expireTimes.get(e)-Date.now())/1e3);return t>0?t:-2}persist(e){return this.store.has(e)&&this.expireTimes.has(e)?(this.expireTimes.delete(e),1):0}getrange(e,t,s){const n=this.get(e);return"string"!=typeof n?"":n.slice(t,s+1)}getset(e,t){const s=this.get(e);return this.set(e,t),s}setex(e,t,s){if(this.store.has(e))return this.set(e,t),this.expire(e,s),!0}setrange(e,t,s){if("number"!=typeof t||t<0)throw new Error("Invalid offset value");if("string"!=typeof s)throw new Error("Value must be a string");let n=this.get(e);void 0!==n&&void 0!==n||(n="");const r=n.slice(0,t)+s+n.slice(t+s.length);return this.set(e,r),r.length}strlen(e){const t=this.get(e);return void 0===t?0:t.length}msetnx(...e){if(e.length%2!=0)throw new Error("MSETNX requires an even number of arguments");for(let t=0;t<e.length;t+=2)if(this.store.has(e[t]))return 0;for(let t=0;t<e.length;t+=2)this.set(e[t],e[t+1]);return 1}incrbyfloat(e,t){let s=this.store.get(e);if(void 0===s)s=0;else if(isNaN(parseFloat(s)))throw new Error("ERR value is not a valid float");const n=parseFloat(s)+t;return this.storeSet(e,n.toString()),n}append(e,t){const s=this.get(e),n=void 0===s?t:s+t;return this.set(e,n),n.length}getbit(e,t){const s=this.get(e);if(void 0===s||t>=8*s.length)return 0;const n=Math.floor(t/8),r=7-t%8;return s.charCodeAt(n)>>r&1}setbit(e,t,s){if(0!==s&&1!==s)throw new Error("ERR bit is not an integer or out of range");let n=this.get(e);void 0===n&&(n="");const r=Math.floor(t/8),i=7-t%8;for(;r>=n.length;)n+="\0";const o=n.charCodeAt(r),a=o>>i&1,c=o&~(1<<i)|s<<i,h=String.fromCharCode(c),l=n.slice(0,r)+h+n.slice(r+1);return this.set(e,l),a}copy(e,t){const s=this.get(e);return void 0===s?0:(this.set(t,s),1)}rename(e,t){if(!this.store.has(e))throw new Error("ERR no such key");if(e===t)return!0;const s=this.store.get(e),n=this.expireTimes.get(e);return this.storeSet(t,s),this.store.delete(e),void 0!==n&&(this.expireTimes.set(t,n),this.expireTimes.delete(e)),!0}type(e){return this.store.has(e)?typeof this.store.get(e):"none"}sadd(e,...t){this.store.has(e)||this.storeSet(e,new Set);const s=this.store.get(e);if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");let n=0;for(const e of t)s.has(e)||(s.add(e),n++);return n}scard(e){const t=this.store.get(e);if(void 0===t)return 0;if(!(t instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");return t.size}sdiff(e,...t){const s=this.store.get(e)||new Set;if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");const n=new Set(s);for(const e of t){const t=this.store.get(e)||new Set;if(!(t instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");for(const e of t)n.delete(e)}return Array.from(n)}sdiffstore(e,t,...s){const n=this.sdiff(t,...s),r=new Set(n);return this.storeSet(e,r),r.size}sinter(...e){if(0===e.length)return[];const t=e.map(e=>{const t=this.store.get(e);if(void 0===t)return new Set;if(!(t instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");return t}),s=new Set(t[0]);for(let e=1;e<t.length;e++)for(const n of s)t[e].has(n)||s.delete(n);return Array.from(s)}sintercard(...e){return this.sinter(...e).length}sinterstore(e,...t){const s=this.sinter(...t),n=new Set(s);return this.storeSet(e,n),n.size}sismember(e,t){const s=this.store.get(e);if(void 0===s)return!1;if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");return!!s.has(t)}smembers(e){const t=this.store.get(e);if(void 0===t)return[];if(!(t instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");return Array.from(t)}smismember(e,...t){const s=this.store.get(e)||new Set;if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");return t.map(e=>s.has(e)?1:0)}smove(e,t,s){const n=this.store.get(e);if(void 0===n||!n.has(s))return 0;if(!(n instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");const r=this.store.get(t)||new Set;if(!(r instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");return n.delete(s),r.add(s),this.storeSet(t,r),1}spop(e,t=1){const s=this.store.get(e);if(void 0===s)return[];if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");const n=[];for(const e of s){if(n.length>=t)break;n.push(e),s.delete(e)}return n}srandmember(e,t=1){const s=this.store.get(e);if(void 0===s)return[];if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");const n=Array.from(s),r=[];for(let e=0;e<t&&e<n.length;e++){const e=Math.floor(Math.random()*n.length);r.push(n[e]),n.splice(e,1)}return r}srem(e,...t){const s=this.store.get(e);if(void 0===s)return 0;if(!(s instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");let n=0;for(const e of t)s.delete(e)&&n++;return n}sscan(e,t,s={}){const{match:n="*",count:r=10}=s,i=this.store.get(e);if(void 0===i)return[0,[]];if(!(i instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");const o=new RegExp(n.replace("*",".*")),a=Array.from(i),c=[];let h=t;for(let e=t;e<a.length&&c.length<r;e++)o.test(a[e])&&c.push(a[e]),h=e+1;return[h>=a.length?0:h,c]}sunion(...e){const t=new Set;for(const s of e){const e=this.store.get(s)||new Set;if(!(e instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");for(const s of e)t.add(s)}return Array.from(t)}sunionstore(e,...t){const s=new Set;for(const e of t){const t=this.store.get(e)||new Set;if(!(t instanceof Set))throw new Error("ERR Operation against a key holding the wrong kind of value");for(const e of t)s.add(e)}return this.storeSet(e,s),s.size}lset(e,t,s){const n=this.store.get(e);if(void 0===n)throw new Error("ERR no such key");if(!Array.isArray(n))throw new Error("ERR Operation against a key holding the wrong kind of value");if(t<0||t>=n.length)throw new Error("ERR index out of range");return n[t]=s,!0}ltrim(e,t,s){const n=this.store.get(e);if(void 0===n)return!0;if(!Array.isArray(n))throw new Error("ERR Operation against a key holding the wrong kind of value");const r=n.length,i=t>=0?t:Math.max(r+t,0),o=s>=0?s:Math.max(r+s,-1),a=n.slice(i,o+1);return this.storeSet(e,a),!0}rpop(e){const t=this.store.get(e);return void 0!==t&&Array.isArray(t)?t.pop():null}rpoplpush(e,t){const s=this.rpop(e);return void 0===s?null:(this.lpush(t,s),s)}rpush(e,...t){let s=this.store.get(e);if(void 0===s)s=[],this.storeSet(e,s);else if(!Array.isArray(s))throw new Error("ERR Operation against a key holding the wrong kind of value");return s.push(...t),s.length}rpushx(e,t){const s=this.store.get(e);return void 0!==s&&Array.isArray(s)?(s.push(t),s.length):0}lpush(e,...t){let s=this.store.get(e);if(void 0===s)s=[],this.storeSet(e,s);else if(!Array.isArray(s))throw new Error("ERR Operation against a key holding the wrong kind of value");return s.unshift(...t),s.length}lpushx(e,...t){const s=this.store.get(e);return void 0!==s&&Array.isArray(s)?(s.unshift(...t),s.length):0}lrange(e,t,s){const n=this.store.get(e);if(void 0===n||!Array.isArray(n))return[];const r=n.length,i=t>=0?t:Math.max(r+t,0),o=s>=0?s:Math.max(r+s,-1);return n.slice(i,o+1)}lrem(e,t,s){const n=this.store.get(e);if(void 0===n||!Array.isArray(n))return 0;let r=0;if(t>0)for(let e=0;e<n.length&&r<t;e++)n[e]===s&&(n.splice(e,1),r++,e--);else if(t<0)for(let e=n.length-1;e>=0&&r<-t;e--)n[e]===s&&(n.splice(e,1),r++);else r=n.filter(e=>e===s).length,this.storeSet(e,n.filter(e=>e!==s));return r}lmove(e,t,s,n){const r="LEFT"===n?"lpush":"rpush",i=this["LEFT"===s?"lpop":"rpop"](e);return void 0===i?null:(this[r](t,i),i)}lmpop(e,t,s){const n="LEFT"===s?"lpop":"rpop",r=[];for(let s=0;s<e;s++){const e=this[n](t);if(void 0===e)break;r.push(e)}return r}lpop(e){const t=this.store.get(e);return void 0!==t&&Array.isArray(t)?t.shift():null}lpos(e,t,s={}){const{rank:n=0,start:r=0,stop:i=-1}=s,o=this.store.get(e);if(void 0===o||!Array.isArray(o))return;let a=0;const c=o.length,h=r>=0?r:Math.max(c+r,0),l=i>=0?i:Math.max(c+i,-1);for(let e=h;e<=l;e++)if(o[e]===t){if(a===n)return e;a++}}brpoplpush(e,t,s){const n=this.brpop(e,s);return void 0===n?null:(this.lpush(t,n),n)}lindex(e,t){const s=this.store.get(e);return void 0!==s&&Array.isArray(s)?(t<0&&(t=s.length+t),void 0!==s[t]?s[t]:null):null}linsert(e,t,s,n){const r=this.store.get(e);if(void 0===r)return 0;if(!Array.isArray(r))throw new Error("ERR Operation against a key holding the wrong kind of value");const i=r.indexOf(s);if(-1===i)return 0;if("BEFORE"===t)r.splice(i,0,n);else{if("AFTER"!==t)throw new Error("ERR syntax error");r.splice(i+1,0,n)}return r.length}llen(e){const t=this.store.get(e);return void 0===t?0:t.length}blmove(e,t,s,n,r){const i="LEFT"===n?"lpush":"rpush",o=this["LEFT"===s?"blpop":"brpop"]([e],r);return void 0===o?null:(this[i](t,o[1]),o[1])}blmpop(e,t,...s){const n=[],r=1e3*t,i=1===s.length?"brpop":"brpoplpush",o=s.concat(r);for(let t=0;t<e;t++){const e=this[i](o);if(void 0===e)break;n.push(e)}return n}blpop(e,...t){return this.blmpop(1,e,...t)[0]}brpop(e,...t){const s=1e3*e,n=Date.now()+s;for(;Date.now()<n;)for(let e=0;e<t.length;e++){const s=t[e],n=this.store.get(s);if(void 0!==n&&Array.isArray(n)&&n.length>0){const e=n.pop();return 0===n.length&&this.store.delete(s),[s,e]}}return null}expiretime(e){return this.expireTimes.get(e)}pexpiretime(e){const t=this.expireTimes.get(e);return t?1e3*t:null}zadd(e,t,s){return this._checkAndRemoveExpiredKey(e)?0:(this.store.has(e)||this.storeSet(e,new r),this.store.get(e).set(s,Number(t)),1)}zcard(e){return this._checkAndRemoveExpiredKey(e)?0:this.store.has(e)?this.store.get(e).size:0}zcount(e,t,s){if(this._checkAndRemoveExpiredKey(e))return 0;if(!this.store.has(e))return 0;const n=this.store.get(e);let r=0;for(const e of n.values())e>=t&&e<=s&&r++;return r}zdiff(...e){if(0===e.length)return new Set;const t=e.map(e=>this._checkAndRemoveExpiredKey(e)?new r:this.store.get(e)||new r),s=new Set(t[0].keys());for(let e=1;e<t.length;e++)for(const n of t[e].keys())s.delete(n);return s}zdiffstore(e,...t){const s=this.ZDIFF(...t),n=new r;for(const e of s){const s=t.map(t=>{const s=this.store.get(t);return s?s.get(e):void 0}).filter(e=>void 0!==e);s.length>0&&n.set(e,Math.min(...s))}return this.storeSet(e,n),n.size}bzmpop(e,...t){const s=[];for(const n of t){const t=this.store.get(n);if(t&&t.size>0){const r=Array.from(t.entries()).sort((e,t)=>e[1]-t[1]).slice(0,e).map(([e,s])=>(t.delete(e),[e,s]));s.push([n,...r]);break}}return s}bzpopmax(e,t){const s=this.store.get(e);return s&&0!==s.size?[e,...Array.from(s.entries()).sort((e,t)=>t[1]-e[1]).slice(0,t).map(([e,t])=>(s.delete(e),[e,t]))]:[]}bzpopmin(e,t){const s=this.store.get(e);return s&&0!==s.size?[e,...Array.from(s.entries()).sort((e,t)=>e[1]-t[1]).slice(0,t).map(([e,t])=>(s.delete(e),[e,t]))]:[]}zincrby(e,t,s){this.store.has(e)||this.storeSet(e,new r);const n=this.store.get(e),i=(n.get(s)||0)+Number(t);return n.set(s,i),i}zinter(...e){if(0===e.length)return new Set;const t=e.map(e=>this.store.get(e)||new r),s=new Set(t[0].keys());for(let e=1;e<t.length;e++){const n=new Set;for(const r of t[e].keys())s.has(r)&&n.add(r);s.clear();for(const e of n)s.add(e)}return s}zintercard(...e){return this.ZINTER(...e).size}zinterstore(e,...t){const s=this.ZINTER(...t),n=new r;for(const e of s){const s=t.map(t=>{const s=this.store.get(t);return s?s.get(e):void 0}).filter(e=>void 0!==e);s.length>0&&n.set(e,Math.max(...s))}return this.storeSet(e,n),n.size}zlexcount(e,t,s){const n=this.store.get(e)||new r,i=Array.from(n.keys()).sort();let o=0;for(const e of i)e>=t&&e<=s&&o++;return o}zmpop(e,...t){const s=[];for(const n of t){const t=this.store.get(n);if(t&&t.size>0){const r=Array.from(t.entries()).sort((e,t)=>e[1]-t[1]).slice(0,e).map(([e,s])=>(t.delete(e),[e,s]));s.push([n,...r]);break}}return s}zmscore(e,...t){const s=this.store.get(e)||new r;return t.map(e=>s.get(e))}zpopmax(e,t){const s=this.store.get(e);return s&&0!==s.size?Array.from(s.entries()).sort((e,t)=>t[1]-e[1]).slice(0,t).map(([e,t])=>(s.delete(e),[e,t])):[]}zpopmin(e,t){const s=this.store.get(e);return s&&0!==s.size?Array.from(s.entries()).sort((e,t)=>e[1]-t[1]).slice(0,t).map(([e,t])=>(s.delete(e),[e,t])):[]}zrandmember(e,t=1){const s=this.store.get(e);if(!s||0===s.size)return[];const n=Array.from(s.keys()),r=[];for(let e=0;e<t;e++){const e=Math.floor(Math.random()*n.length);r.push(n[e])}return r}zrange(e,t,s){const n=this.store.get(e)||new r,i=Array.from(n.entries()).sort((e,t)=>e[1]-t[1]);return t<0&&(t=i.length+t),s<0&&(s=i.length+s),i.slice(t,s+1).map(([e,t])=>[e,t])}zrangebylex(e,t,s,n={}){const i=this.store.get(e)||new r;let o=Array.from(i.keys()).sort().filter(e=>e>=t&&e<=s);if(n.limit){const{offset:e,count:t}=n.limit;o=o.slice(e,e+t)}return o}zrangebyscore(e,t,s,n={}){const i=this.store.get(e)||new r;let o=Array.from(i.entries()).sort((e,t)=>e[1]-t[1]).filter(([,e])=>e>=t&&e<=s);if(o=n.withscores?o.map(([e,t])=>[e,t]):o.map(([e])=>e),n.limit){const{offset:e,count:t}=n.limit;o=o.slice(e,e+t)}return o}zrangestore(e,t,s,n){const i=this.store.get(t)||new r,o=Array.from(i.entries()).sort((e,t)=>e[1]-t[1]);s<0&&(s=o.length+s),n<0&&(n=o.length+n);const a=new r(o.slice(s,n+1));return this.storeSet(e,a),a.size}zrank(e,t){const s=this.store.get(e);if(!s)return;const n=Array.from(s.entries()).sort((e,t)=>e[1]-t[1]);for(let e=0;e<n.length;e++)if(n[e][0]===t)return e}zrem(e,...t){const s=this.store.get(e);if(!s)return 0;let n=0;for(const e of t)s.delete(e)&&n++;return n}zremrangebylex(e,t,s){const n=this.store.get(e);if(!n)return 0;const r=Array.from(n.keys()).sort();let i=0;for(const e of r)e>=t&&e<=s&&(n.delete(e),i++);return i}zremrangebyrank(e,t,s){const n=this.store.get(e);if(!n)return 0;const r=Array.from(n.entries()).sort((e,t)=>e[1]-t[1]);t<0&&(t=r.length+t),s<0&&(s=r.length+s);let i=0;for(let e=t;e<=s;e++)n.delete(r[e][0])&&i++;return i}zremrangebyscore(e,t,s){const n=this.store.get(e);if(!n)return 0;const r=Array.from(n.entries()).sort((e,t)=>e[1]-t[1]);let i=0;for(const[e,o]of r)o>=t&&o<=s&&(n.delete(e),i++);return i}zrevrange(e,t,s){const n=this.store.get(e)||new r,i=Array.from(n.entries()).sort((e,t)=>t[1]-e[1]);return t<0&&(t=i.length+t),s<0&&(s=i.length+s),i.slice(t,s+1).map(([e,t])=>[e,t])}zrevrangebylex(e,t,s,n={}){const i=this.store.get(e)||new r;let o=Array.from(i.keys()).sort().reverse().filter(e=>e>=s&&e<=t);if(n.limit){const{offset:e,count:t}=n.limit;o=o.slice(e,e+t)}return o}zrevrangebyscore(e,t,s,n={}){const i=this.store.get(e)||new r;let o=Array.from(i.entries()).sort((e,t)=>t[1]-e[1]).filter(([,e])=>e>=s&&e<=t);if(o=n.withscores?o.map(([e,t])=>[e,t]):o.map(([e])=>e),n.limit){const{offset:e,count:t}=n.limit;o=o.slice(e,e+t)}return o}zrevrank(e,t){const s=this.store.get(e);if(!s)return;const n=Array.from(s.entries()).sort((e,t)=>t[1]-e[1]);for(let e=0;e<n.length;e++)if(n[e][0]===t)return e}zscan(e,t,s={}){const n=this.store.get(e)||new r,i=Array.from(n.entries()).sort((e,t)=>e[1]-t[1]),o=[];let a=s.count||10,c=t;for(;a>0&&c<i.length;)s.match&&!new RegExp(s.match.replace("*",".*")).test(i[c][0])||(o.push(i[c]),a--),c++;return[c>=i.length?0:c,o]}zscore(e,t){const s=this.store.get(e);if(s)return s.get(t)}zunion(e){const t=new r;for(const s of e){const e=this.store.get(s);if(e)for(const[s,n]of e.entries())t.set(s,(t.get(s)||0)+n)}return Array.from(t.entries()).sort((e,t)=>e[1]-t[1])}zunionstore(e,t){const s=this.zunion(t),n=new r(s);return this.storeSet(e,n),n.size}geoadd(e,t,s,n){if("number"!=typeof t||"number"!=typeof s)throw new Error("Invalid longitude or latitude value");const i=this.store.get(e)||new r;if(!i.get(n)){const r={longitude:t,latitude:s};return i.set(n,r),this.storeSet(e,i),1}return 0}geodist(e,t,s,n="m"){const r=this.store.get(e);if(!r)return;const i=r.get(t),o=r.get(s);if(!i||!o)return;const a=this._haversineDistance(i.latitude,i.longitude,o.latitude,o.longitude);return this._convertDistance(a,n)}geohash(e,...t){const s=this.store.get(e);return s?t.map(e=>{const t=s.get(e);return t?this._encodeGeohash(t.latitude,t.longitude):null}):[]}geopos(e,...t){const s=this.store.get(e);return s?t.map(e=>{const t=s.get(e);return t?[t.latitude,t.longitude]:null}):[]}georadius(e,t,s,n,r="m"){const i=this.store.get(e);if(!i)return[];const o=this._convertDistance(n,r,"m"),a=[];for(const[e,n]of i.entries())this._haversineDistance(s,t,n.latitude,n.longitude)<=o&&a.push(e);return a}georadius_ro(e,t,s,n){return this.georadius(e,t,s,n,!0)}georadiusbymember(e,t,s){const n=this.geopos(e,t);if(n)return this.georadius(n[0],n[1],s,e)}georadiusbymember_ro(e,t,s){const n=this.geopos(e,t);if(n)return this.georadius(n[0],n[1],s,e,!0)}geosearch(e,t,s,n){return this.georadius(t,s,n,e)}geosearchstore(e,t,s,n,r){const i=this.georadius(s,n,r,t);return this.set(e,i),i.length}scan(e,t="*",s=10){const n=this.keys(t),r=Math.min(e+s,n.length);return[r===n.length?0:r,n.slice(e,r)]}sort(e,t="ASC",s=!1){const n=this.store.get(e);return Array.isArray(n)?n.slice().sort((e,n)=>s?"ASC"===t?e.localeCompare(n):n.localeCompare(e):"ASC"===t?e-n:n-e):[]}touch(...e){return e.reduce((e,t)=>e+(this.exists(t)?1:0),0)}sort_ro(e,t="ASC",s=!1){return this.sort(e,t,s)}unlink(...e){let t=0;for(const s of e)this.del(s)&&t++;return t}hset(e,t,s){this.store.has(e)||this.storeSet(e,new r);const n=this.store.get(e),i=!n.has(t);return n.set(t,s),i?1:0}hdel(e,...t){const s=this.store.get(e);if(!s)return 0;let n=0;for(const e of t)s.delete(e)&&n++;return n}hget(e,t){const s=this.store.get(e);return s?s.get(t):void 0}hgetall(e){const t=this.store.get(e);if(!t)return{};const s={};for(const[e,n]of t)s[e]=n;return s}hincrby(e,t,s){const n=this.store.get(e)||new r,i=parseInt(n.get(t)||0,10)+s;return n.set(t,i.toString()),this.storeSet(e,n),i}hincrbyfloat(e,t,s){const n=this.store.get(e)||new r,i=parseFloat(n.get(t)||0)+s;return n.set(t,i.toString()),this.storeSet(e,n),i}hkeys(e){const t=this.store.get(e);return t?Array.from(t.keys()):[]}hlen(e){const t=this.store.get(e);return t?t.size:0}hmget(e,...t){const s=this.store.get(e)||new r;return t.map(e=>s.get(e))}hmset(e,...t){const s=this.store.get(e)||new r;for(let e=0;e<t.length;e+=2){const n=t[e],r=t[e+1];s.set(n,r)}return this.storeSet(e,s),!0}hsetnx(e,t,s){const n=this.store.get(e)||new r;return n.has(t)?0:(n.set(t,s),this.storeSet(e,n),1)}hstrlen(e,t){const s=this.store.get(e),n=s?s.get(t):null;return n?n.length:0}hvals(e){const t=this.store.get(e);return t?Array.from(t.values()):[]}hscan(e,t,s="*",n=10){const i=this.store.get(e)||new r,o=Array.from(i.keys()).filter(e=>e.includes(s)),a=Math.min(t+n,o.length);return[a===o.length?0:a,o.slice(t,a).map(e=>[e,i.get(e)])]}hexists(e,t){const s=this.store.get(e);return s&&s.has(t)?1:0}hrandfield(e,t=1){const s=this.store.get(e);if(!s)return[];const n=Array.from(s.keys()),r=[];for(let e=0;e<t;e++){const e=Math.floor(Math.random()*n.length);r.push(n[e])}return r}_checkAndRemoveExpiredKey(e){const t=this.expireTimes.get(e);return!!(t&&Date.now()>t)&&(this.store.delete(e),this.expireTimes.delete(e),!0)}_initCleanupLoop(e){1===this.store.size&&(this.cleanupLoop=setInterval(()=>{if(0===this.store.size&&this.cleanupLoop)clearInterval(this.cleanupLoop);else for(const e of this.expireTimes.keys())this._checkAndRemoveExpiredKey(e)},e),"object"==typeof this.cleanupLoop&&"function"==typeof this.cleanupLoop.unref&&this.cleanupLoop.unref())}_haversineDistance(e,t,s,n){const r=e=>e*Math.PI/180,i=r(s-e),o=r(n-t),a=Math.sin(i/2)*Math.sin(i/2)+Math.cos(r(e))*Math.cos(r(s))*Math.sin(o/2)*Math.sin(o/2);return 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))*6371e3}_convertDistance(e,t,s){const n={m:1,km:.001,mi:621371e-9,ft:3.28084};if(!n[t]||!n[s])throw new Error("Invalid distance unit");return e*n[t]/n[s]}_encodeGeohash(e,t){let s="",n=-90,r=90,i=-180,o=180,a=!0,c=0,h=0;for(;s.length<12;){if(a){const e=(i+o)/2;t>e?(h=1+(h<<1),i=e):(h<<=1,o=e)}else{const t=(n+r)/2;e>t?(h=1+(h<<1),n=t):(h<<=1,r=t)}a=!a,c<4?c++:(s+="0123456789bcdefghjkmnpqrstuvwxyz"[h],c=0,h=0)}return s}flushall(){return this.store.clear(),this.expireTimes.clear(),!0}}},912:(e,t,s)=>{e.exports={install_in_instance:(e,{parameters:t})=>{const n=e._get_merged_static_object("MODULES");if(t.modules)for(const e in t.modules)n[e]=t.modules[e];e.modules=n,e.require=t=>e.modules[t]?e.modules[t]:s(274)(t)}}},952:(e,t,s)=>{const{FeatureBase:n}=s(533);class r extends n{static FEATURES=[s(912),s(314),s(178),s(659),s(73)]}e.exports={AdvancedBase:r}},986:e=>{"use strict";function t(e,t,r){e instanceof RegExp&&(e=s(e,r)),t instanceof RegExp&&(t=s(t,r));var i=n(e,t,r);return i&&{start:i[0],end:i[1],pre:r.slice(0,i[0]),body:r.slice(i[0]+e.length,i[1]),post:r.slice(i[1]+t.length)}}function s(e,t){var s=t.match(e);return s?s[0]:null}function n(e,t,s){var n,r,i,o,a,c=s.indexOf(e),h=s.indexOf(t,c+1),l=c;if(c>=0&&h>0){if(e===t)return[c,h];for(n=[],i=s.length;l>=0&&!a;)l==c?(n.push(l),c=s.indexOf(e,l+1)):1==n.length?a=[n.pop(),h]:((r=n.pop())<i&&(i=r,o=h),h=s.indexOf(t,l+1)),l=c<h&&c>=0?c:h;n.length&&(a=[i,o])}return a}e.exports=t,t.range=n}},t={};function s(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,s),i.exports}s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";var e=s(294),t=s(910);const n=class{constructor(e={}){this.config={enabled:e.enabled??!1,...e}}updateConfig(e){this.config={...this.config,...e}}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}isEnabled(){return this.config.enabled}logRequest(e={}){if(!this.isEnabled())return;const{service:t="unknown",operation:s="unknown",params:n={},result:r=null,error:i=null}=e;let o="{}";if(n&&Object.keys(n).length>0)try{o=JSON.stringify(n)}catch(e){o="[Unable to serialize params]"}const a=`${t} - ${s} - ${o}`;i?console.error(a,{error:i.message||i,result:r}):console.log(a,r)}getStats(){return{enabled:this.config.enabled,config:{...this.config}}}},r=47;function i(e){return e===r}function o(e,t,s,n){let i="",o=0,a=-1,c=0,h=0;for(let l=0;l<=e.length;++l){if(l<e.length)h=e.charCodeAt(l);else{if(n(h))break;h=r}if(n(h)){if(a===l-1||1===c);else if(2===c){if(i.length<2||2!==o||46!==i.charCodeAt(i.length-1)||46!==i.charCodeAt(i.length-2)){if(i.length>2){const e=i.lastIndexOf(s);-1===e?(i="",o=0):(i=i.slice(0,e),o=i.length-1-i.lastIndexOf(i,s)),a=l,c=0;continue}if(0!==i.length){i="",o=0,a=l,c=0;continue}}t&&(i+=i.length>0?`${s}..`:"..",o=2)}else i.length>0?i+=`${s}${e.slice(a+1,l)}`:i=e.slice(a+1,l),o=l-a-1;a=l,c=0}else 46===h&&-1!==c?++c:c=-1}return i}const a={resolve(...e){let t="",s=!1;for(let n=e.length-1;n>=-1&&!s;n--){const i=n>=0?e[n]:"/";0!==i.length&&(t=`${i}/${t}`,s=i.charCodeAt(0)===r)}return t=o(t,!s,"/",i),s?`/${t}`:t.length>0?t:"."},normalize(e){if(0===e.length)return".";const t=e.charCodeAt(0)===r,s=e.charCodeAt(e.length-1)===r;return 0===(e=o(e,!t,"/",i)).length?t?"/":s?"./":".":(s&&(e+="/"),t?`/${e}`:e)},isAbsolute:e=>e.length>0&&e.charCodeAt(0)===r,join(...e){if(0===e.length)return".";let t;for(let s=0;s<e.length;++s){const n=e[s];n.length>0&&(void 0===t?t=n:t+=`/${n}`)}return void 0===t?".":a.normalize(t)},relative(e,t){if(e===t)return"";if((e=a.resolve(e))===(t=a.resolve(t)))return"";const s=e.length,n=s-1,i=t.length-1,o=n<i?n:i;let c=-1,h=0;for(;h<o;h++){const s=e.charCodeAt(1+h);if(s!==t.charCodeAt(1+h))break;s===r&&(c=h)}if(h===o)if(i>o){if(t.charCodeAt(1+h)===r)return t.slice(1+h+1);if(0===h)return t.slice(1+h)}else n>o&&(e.charCodeAt(1+h)===r?c=h:0===h&&(c=0));let l="";for(h=1+c+1;h<=s;++h)h!==s&&e.charCodeAt(h)!==r||(l+=0===l.length?"..":"/..");return`${l}${t.slice(1+c)}`},toNamespacedPath:e=>e,dirname(e){if(0===e.length)return".";const t=e.charCodeAt(0)===r;let s=-1,n=!0;for(let t=e.length-1;t>=1;--t)if(e.charCodeAt(t)===r){if(!n){s=t;break}}else n=!1;return-1===s?t?"/":".":t&&1===s?"//":e.slice(0,s)},basename(e,t){let s=0,n=-1,i=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t===e)return"";let o=t.length-1,a=-1;for(let c=e.length-1;c>=0;--c){const h=e.charCodeAt(c);if(h===r){if(!i){s=c+1;break}}else-1===a&&(i=!1,a=c+1),o>=0&&(h===t.charCodeAt(o)?-1===--o&&(n=c):(o=-1,n=a))}return s===n?n=a:-1===n&&(n=e.length),e.slice(s,n)}for(let t=e.length-1;t>=0;--t)if(e.charCodeAt(t)===r){if(!i){s=t+1;break}}else-1===n&&(i=!1,n=t+1);return-1===n?"":e.slice(s,n)},extname(e){let t=-1,s=0,n=-1,i=!0,o=0;for(let a=e.length-1;a>=0;--a){const c=e.charCodeAt(a);if(c!==r)-1===n&&(i=!1,n=a+1),46===c?-1===t?t=a:1!==o&&(o=1):-1!==t&&(o=-1);else if(!i){s=a+1;break}}return-1===t||-1===n||0===o||1===o&&t===n-1&&t===s+1?"":e.slice(t,n)},format:function(e,t){validateObject(t,"pathObject");const s=t.dir||t.root,n=t.base||`${t.name||""}${t.ext||""}`;return s?s===t.root?`${s}${n}`:`${s}${e}${n}`:n}.bind(null,"/"),parse(e){const t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;const s=e.charCodeAt(0)===r;let n;s?(t.root="/",n=1):n=0;let i=-1,o=0,a=-1,c=!0,h=e.length-1,l=0;for(;h>=n;--h){const t=e.charCodeAt(h);if(t!==r)-1===a&&(c=!1,a=h+1),46===t?-1===i?i=h:1!==l&&(l=1):-1!==i&&(l=-1);else if(!c){o=h+1;break}}if(-1!==a){const n=0===o&&s?1:o;-1===i||0===l||1===l&&i===a-1&&i===o+1?t.base=t.name=e.slice(n,a):(t.name=e.slice(n,i),t.base=e.slice(n,a),t.ext=e.slice(i,a))}return o>0?t.dir=e.slice(0,o-1):s&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null},c=a;var h={},l={};h.length=0,h.getItem=function(e){return e in l?l[e]:null},h.setItem=function(e,t){void 0===t?h.removeItem(e):(l.hasOwnProperty(e)||h.length++,l[e]=""+t)},h.removeItem=function(e){l.hasOwnProperty(e)&&(delete l[e],h.length--)},h.key=function(e){return Object.keys(l)[e]||null},h.clear=function(){l={},h.length=0},"object"==typeof exports&&(module.exports=h);const u=h,p=Symbol("readyState"),d=Symbol("headers"),g=Symbol("response headers"),f=Symbol("AbortController"),m=Symbol("method"),y=Symbol("URL"),b=Symbol("MIME"),w=Symbol("dispatch"),v=Symbol("errored"),_=Symbol("timeout"),k=Symbol("timedOut"),A=Symbol("isResponseText");function T(...e){const t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t);return e.forEach((e,t,n)=>{const r=n.slice(0,t).reduce((e,t)=>e+t.length,0);s.set(e,r)}),s}async function E(e){const t=this.responseType||"text",s=new TextDecoder,n=this[b]||this[g].get("content-type")||"text/plain";switch(t){case"text":this.response=s.decode(e);break;case"blob":this.response=new Blob([e],{type:n});break;case"arraybuffer":this.response=e.buffer;break;case"json":this.response=JSON.parse(s.decode(e))}}const x=class extends EventTarget{onreadystatechange(){}set readyState(e){this[p]!==e&&(this[p]=e,this.dispatchEvent(new Event("readystatechange")),this.onreadystatechange(new Event("readystatechange")))}get readyState(){return this[p]}constructor(){super(),this.readyState=this.constructor.UNSENT,this.response=null,this.responseType="",this.responseURL="",this.status=0,this.statusText="",this.timeout=0,this.withCredentials=!1,this[d]=Object.create(null),this[d].accept="*/*",this[g]=Object.create(null),this[f]=new AbortController,this[m]="",this[y]="",this[b]="",this[v]=!1,this[_]=0,this[k]=!1,this[A]=!0}static get UNSENT(){return 0}static get OPENED(){return 1}static get HEADERS_RECEIVED(){return 2}static get LOADING(){return 3}static get DONE(){return 4}upload={addEventListener(){}};get responseText(){if(this[v])return null;if(this.readyState<this.constructor.HEADERS_RECEIVED)return"";if(this[A])return this.response;throw new DOMException("Response type not set to text","InvalidStateError")}get responseXML(){throw new Error("XML not supported")}[w](e){const t=`on${e.type}`;"function"==typeof this[t]&&this.addEventListener(e.type,this[t].bind(this),{once:!0}),this.dispatchEvent(e)}abort(){this[f].abort(),this.status=0,this.readyState=this.constructor.UNSENT}open(e,t){this.status=0,this[m]=e,this[y]=t,this.readyState=this.constructor.OPENED}setRequestHeader(e,t){e=String(e).toLowerCase(),void 0===this[d][e]?this[d][e]=String(t):this[d][e]+=`, ${t}`}overrideMimeType(e){this[b]=String(e)}getAllResponseHeaders(){return this[v]||this.readyState<this.constructor.HEADERS_RECEIVED?"":Array.from(this[g].entries().map(([e,t])=>`${e}: ${t}`)).join("\r\n")}getResponseHeader(e){const t=this[g].get(String(e).toLowerCase());return"string"==typeof t?t:null}send(e=null){this.timeout>0&&(this[_]=setTimeout(()=>{this[k]=!0,this[f].abort()},this.timeout));const t=this.responseType||"text";this[A]="text"===t,this.setRequestHeader("user-agent","puter-js/1.0"),this.setRequestHeader("origin","https://puter.work"),this.setRequestHeader("referer","https://puter.work/"),fetch(this[y],{method:this[m]||"GET",signal:this[f].signal,headers:this[d],credentials:this.withCredentials?"include":"same-origin",body:e}).then(async e=>{if(this.responseURL=e.url,this.status=e.status,this.statusText=e.statusText,this[g]=e.headers,this.readyState=this.constructor.HEADERS_RECEIVED,e.headers.get("content-type").includes("application/x-ndjson")||this.streamRequestBadForPerformance){let t=new Uint8Array;for await(const s of e.body)this.readyState=this.constructor.LOADING,t=T(t,s),E.call(this,t),this[w](new CustomEvent("progress"))}else{const t=[];for await(const s of e.body)t.push(s);E.call(this,T(...t))}this.readyState=this.constructor.DONE,this[w](new CustomEvent("load"))},e=>{let t="abort";"AbortError"!==e.name?(this[v]=!0,t="error"):this[k]&&(t="timeout"),this.readyState=this.constructor.DONE,this[w](new CustomEvent(t))}).finally(()=>this[w](new CustomEvent("loadend"))).finally(()=>{clearTimeout(this[_]),this[w](new CustomEvent("loadstart"))})}};"object"==typeof module&&module.exports?module.exports=x:(globalThis||self).XMLHttpRequestShim=x;const S=x;async function I(e){if("blob"===e.responseType){const t=e.getResponseHeader("content-type");if(t.startsWith("application/json")){const t=await e.response.text();try{return JSON.parse(t)}catch(e){return t}}else if(t.startsWith("application/octet-stream"))return e.response;return{success:!0,result:e.response}}const t=e.responseText;try{return JSON.parse(t)}catch(e){return t}}function P(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}function O(e,t,s,n="post",r="text/plain;actually=json",i=void 0){const o=new XMLHttpRequest;return o.open(n,t+e,!0),s&&o.setRequestHeader("Authorization","Bearer "+s),o.setRequestHeader("Content-Type",r),o.responseType=i??"",globalThis.puter?.apiCallLogger?.isEnabled()&&(o._puterRequestId={method:n,service:"xhr",operation:e.replace(/^\//,""),params:{endpoint:e,contentType:r,responseType:i}}),o}function R(e,t,s){return e&&"function"==typeof e&&e(s),t(s)}function C(e,t,s,n,r){e.addEventListener("load",async function(e){if(globalThis.puter?.apiCallLogger?.isEnabled()&&this._puterRequestId){const e=await I(this).catch(()=>null);globalThis.puter.apiCallLogger.logRequest({service:this._puterRequestId.service,operation:this._puterRequestId.operation,params:this._puterRequestId.params,result:this.status>=400?null:e,error:this.status>=400?{message:this.statusText,status:this.status}:null})}return async function(e,t,s,n,r){const i=await I(r);return 401===r.status?(t&&"function"==typeof t&&t({status:401,message:"Unauthorized"}),n({status:401,message:"Unauthorized"})):200!==r.status?(t&&"function"==typeof t&&t(i),n(i)):(!1===i.success&&"permission_denied"===i.error?.code&&(await puter.ui.requestPermission({permission:"driver:puter-image-generation:generate"})).granted,e&&"function"==typeof e&&e(i),s(i))}(t,s,n,r,this)}),e.addEventListener("error",function(e){return globalThis.puter?.apiCallLogger?.isEnabled()&&this._puterRequestId&&globalThis.puter.apiCallLogger.logRequest({service:this._puterRequestId.service,operation:this._puterRequestId.operation,params:this._puterRequestId.params,error:{message:"Network error occurred",event:e.type}}),R(s,r,this)})}const L=()=>{};class D{static callback(e){return e&&"function"==typeof e?e:void 0}}function M(e,t,s,n,r={}){return async function(...i){let o={},a={};return 1!==i.length||"object"!=typeof i[0]||Array.isArray(i[0])?(e.forEach((e,t)=>{o[e]=i[t]}),a={success:i[e.length],error:i[e.length+1]}):(o={...i[0]},a={success:o.success,error:o.error},delete o.success,delete o.error),r.preprocess&&"function"==typeof r.preprocess&&(o=r.preprocess(o)),await async function(e,t,s,n,r,i){const o=new U;return N(e,o.resolve.bind(o),o.reject.bind(o),t,s,n,r,void 0,void 0,i),await o}(a,t,s,n,o,r)}}async function N(e={},t,s,n,r,i,o,a,c="text/plain;actually=json",h={}){let l=null;if(globalThis.puter?.apiCallLogger?.isEnabled()&&(l={interface:n,driver:r,method:i,args:o}),!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){return l&&globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:`${n}::${i}`,params:{interface:n,driver:r,method:i,args:o},error:{code:"auth_canceled",message:"Authentication canceled"}}),s({error:{code:"auth_canceled",message:"Authentication canceled"}})}const u=D.callback(e.success)??L,p=D.callback(e.error)??L,d=O("/drivers/call",puter.APIOrigin,void 0,"POST",c);l&&(d._puterDriverRequestInfo=l),h.responseType&&(d.responseType=h.responseType);let g=!1,f=null,m=0,y=!1,b="";const w=[];d.onreadystatechange=()=>{if(2===d.readyState){if("application/x-ndjson"!==d.getResponseHeader("Content-Type"))return;g=!0;const e=async function*(){for(;!y;){const e=new U;if(f=e.resolve.bind(e),await e,y)break;for(;w.length>0;){const e=w.shift();if(""===e.trim())continue;const t=JSON.parse(e);"string"==typeof t.text&&Object.defineProperty(t,"toString",{enumerable:!1,value:()=>t.text}),yield t}}}();return Object.defineProperty(e,"start",{enumerable:!1,value:async t=>{const s=new TextEncoder;for await(const n of e)t.enqueue(s.encode(n));t.close()}}),t(e)}4===d.readyState&&(y=!0,g&&f?.())},d.onprogress=function(){if(!f)return;const e=d.responseText.slice(m);m=d.responseText.length;let t=!1;for(let s=0;s<e.length;s++)b+=e[s],"\n"===e[s]&&(t=!0,w.push(b),b="");t&&f()},d.addEventListener("load",async function(r){if(g)return;const l=await I(r.target);if(this._puterDriverRequestInfo&&globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:`${this._puterDriverRequestInfo.interface}::${this._puterDriverRequestInfo.method}`,params:{interface:this._puterDriverRequestInfo.interface,driver:this._puterDriverRequestInfo.driver,method:this._puterDriverRequestInfo.method,args:this._puterDriverRequestInfo.args},result:r.status>=400||!1===l?.success?null:l,error:r.status>=400||!1===l?.success?l:null}),401===r.status||"token_auth_failed"===l?.code){if("token_auth_failed"===l?.code&&"web"===puter.env)try{puter.resetAuthToken(),await puter.ui.authenticateWithPuter()}catch(e){return s({error:{code:"auth_canceled",message:"Authentication canceled"}})}return p&&"function"==typeof p&&p({status:401,message:"Unauthorized"}),s({status:401,message:"Unauthorized"})}if(r.status&&200!==r.status)return p(l),s(l);{if(!1===l.success&&"permission_denied"===l.error?.code)return(await puter.ui.requestPermission({permission:"driver:"+n+":"+i})).granted?N(e,t,s,n,i,o,a,c,h):(p(l),s(l));if(!1===l.success)return p(l),s(l);let r=void 0!==l.result?l.result:l;return h.transform&&(r=await h.transform(r)),t.success&&u(r),t(r)}}),d.addEventListener("error",function(e){return this._puterDriverRequestInfo&&globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:`${this._puterDriverRequestInfo.interface}::${this._puterDriverRequestInfo.method}`,params:{interface:this._puterDriverRequestInfo.interface,driver:this._puterDriverRequestInfo.driver,method:this._puterDriverRequestInfo.method,args:this._puterDriverRequestInfo.args},error:{message:"Network error occurred",event:e.type}}),R(p,s,this)}),d.send(JSON.stringify({interface:n,driver:r,test_mode:h?.test_mode,method:i,args:o,auth_token:puter.authToken}))}class U{static STATUS_PENDING={};static STATUS_RUNNING={};static STATUS_DONE={};constructor(){this.status_=this.constructor.STATUS_PENDING,this.donePromise=new Promise((e,t)=>{this.doneResolve=e,this.doneReject=t})}get status(){return this.status_}set status(e){this.status_=e,e===this.constructor.STATUS_DONE&&this.doneResolve()}resolve(e){this.status_=this.constructor.STATUS_DONE,this.doneResolve(e)}awaitDone(){return this.donePromise}then(e,t){return this.donePromise.then(e,t)}reject(e){this.status_=this.constructor.STATUS_DONE,this.doneReject(e)}onComplete(e){return this.then(e)}}async function q(e){const t=new U,s=new FileReader;return s.onloadend=()=>t.resolve(s.result),s.readAsDataURL(e),await t}function j(e){return new Promise((t,s)=>{const n=new FileReader;n.onload=function(e){t(e.target.result)},n.onerror=function(e){s(e)},n.readAsDataURL(e)})}const z=class{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}async listModels(e){const t={},s=await puter.drivers.call("puter-chat-completion","ai-chat","models");return s&&s.result&&Array.isArray(s.result)?(s.result.forEach(s=>{s.provider&&s.id&&(e&&s.provider!==e||(t[s.provider]||(t[s.provider]=[]),t[s.provider].push(s.id)))}),t):t}async listModelProviders(){let e=[];const t=await puter.drivers.call("puter-chat-completion","ai-chat","models");return t&&t.result&&Array.isArray(t.result)?(e=new Set,t.result.forEach(t=>{t.provider&&e.add(t.provider)}),e=Array.from(e),e):e}img2txt=async(...e)=>{let t={},s=!1;if(!e)throw{message:"Arguments are required",code:"arguments_required"};if(("string"==typeof e[0]||e[0]instanceof Blob)&&(t.source=e[0]),e[0].source instanceof Blob&&(t.source=await j(e[0].source)),t.source.length>this.MAX_INPUT_SIZE)throw{message:"Input size cannot be larger than 10485760",code:"input_too_large"};return("boolean"==typeof e[1]&&!0===e[1]||"boolean"==typeof e[2]&&!0===e[2]||"boolean"==typeof e[3]&&!0===e[3])&&(s=!0),await M(["source"],"puter-ocr","aws-textract","recognize",{test_mode:s??!1,transform:async e=>{let t="";for(let s=0;s<e?.blocks?.length;s++)"text/textract:LINE"===e.blocks[s].type&&(t+=e.blocks[s].text+"\n");return t}}).call(this,t)};txt2speech=async(...e)=>{let t={},s=!1;if(!e)throw{message:"Arguments are required",code:"arguments_required"};if("string"==typeof e[0]&&(t={text:e[0]}),e[1]&&"object"==typeof e[1]&&!Array.isArray(e[1]))Object.assign(t,e[1]);else if(e[1]&&"string"==typeof e[1])t.language=e[1],e[2]&&"string"==typeof e[2]&&(t.voice=e[2]),e[3]&&"string"==typeof e[3]&&(t.engine=e[3]);else if(e[1]&&"boolean"!=typeof e[1])throw{message:'Second argument must be an options object or language string. Use: txt2speech("text", { voice: "name", engine: "type", language: "code" }) or txt2speech("text", "language", "voice", "engine")',code:"invalid_arguments"};if(!t.text)throw{message:"Text parameter is required",code:"text_required"};if(t.engine){const e=["standard","neural","long-form","generative"];if(!e.includes(t.engine))throw{message:"Invalid engine. Must be one of: "+e.join(", "),code:"invalid_engine"}}if(t.voice||(t.voice="Joanna"),t.engine||(t.engine="standard"),t.language||(t.language="en-US"),t.text.length>3e3)throw{message:"Input size cannot be larger than 3000",code:"input_too_large"};for(let t=0;t<e.length;t++)if("boolean"==typeof e[t]&&!0===e[t]){s=!0;break}return await M(["source"],"puter-tts","aws-polly","synthesize",{responseType:"blob",test_mode:s??!1,transform:async e=>{const t=await q(e),s=new Audio(t);return s.toString=()=>t,s.valueOf=()=>t,s}}).call(this,t)};txt2speech=Object.assign(this.txt2speech,{listEngines:async()=>await M(["source"],"puter-tts","aws-polly","list_engines",{responseType:"text"}).call(this,{}),listVoices:async e=>{const t={};return e&&(t.engine=e),M(["source"],"puter-tts","aws-polly","list_voices",{responseType:"text"}).call(this,t)}});chat=async(...e)=>{let t={},s={},n=!1,r="openai-completion";if(!e)throw{message:"Arguments are required",code:"arguments_required"};if("string"==typeof e[0]&&(t={messages:[{content:e[0]}]}),"string"!=typeof e[0]||e[1]&&"boolean"!=typeof e[1])if("string"==typeof e[0]&&("string"==typeof e[1]||e[1]instanceof File))e[1]instanceof File&&(e[1]=await j(e[1])),t={vision:!0,messages:[{content:[e[0],{image_url:{url:e[1]}}]}]};else if("string"==typeof e[0]&&Array.isArray(e[1])){for(let t=0;t<e[1].length;t++)e[1][t]={image_url:{url:e[1][t]}};t={vision:!0,messages:[{content:[e[0],...e[1]]}]}}else Array.isArray(e[0])&&(t={messages:e[0]});else t={messages:[{content:e[0]}]};("boolean"==typeof e[1]&&!0===e[1]||"boolean"==typeof e[2]&&!0===e[2]||"boolean"==typeof e[3]&&!0===e[3])&&(n=!0);const i=e=>"object"==typeof e&&!Array.isArray(e)&&null!==e;for(let t=0;t<e.length;t++)if(i(e[t])){s=e[t];break}s.model&&(t.model=s.model),s.temperature&&(t.temperature=s.temperature),s.max_tokens&&(t.max_tokens=s.max_tokens),t.model=t.model??"",t.model&&t.model.startsWith("anthropic/")&&(t.model=t.model.replace("anthropic/","")),"claude-3-5-sonnet"===t.model&&(t.model="claude-3-5-sonnet-latest"),"claude-3-7-sonnet"!==t.model&&"claude"!==t.model||(t.model="claude-3-7-sonnet-latest"),"claude-sonnet-4"!==t.model&&"claude-sonnet-4-latest"!==t.model||(t.model="claude-sonnet-4-20250514"),"claude-opus-4"!==t.model&&"claude-opus-4-latest"!==t.model||(t.model="claude-opus-4-20250514"),"mistral"===t.model&&(t.model="mistral-large-latest"),"groq"===t.model&&(t.model="llama3-8b-8192"),"deepseek"===t.model&&(t.model="deepseek-chat"),"o1-mini"===t.model&&(t.model="openrouter:openai/o1-mini"),t.model&&t.model.startsWith("openai/")&&(t.model=t.model.replace("openai/",""),r="openai-completion"),(t.model.startsWith("agentica-org/")||t.model.startsWith("ai21/")||t.model.startsWith("aion-labs/")||t.model.startsWith("alfredpros/")||t.model.startsWith("alpindale/")||t.model.startsWith("amazon/")||t.model.startsWith("anthracite-org/")||t.model.startsWith("arcee-ai/")||t.model.startsWith("arliai/")||t.model.startsWith("baidu/")||t.model.startsWith("bytedance/")||t.model.startsWith("cognitivecomputations/")||t.model.startsWith("cohere/")||t.model.startsWith("deepseek/")||t.model.startsWith("eleutherai/")||t.model.startsWith("google/")||t.model.startsWith("gryphe/")||t.model.startsWith("inception/")||t.model.startsWith("infermatic/")||t.model.startsWith("liquid/")||t.model.startsWith("mancer/")||t.model.startsWith("meta-llama/")||t.model.startsWith("microsoft/")||t.model.startsWith("minimax/")||t.model.startsWith("mistralai/")||t.model.startsWith("moonshotai/")||t.model.startsWith("morph/")||t.model.startsWith("neversleep/")||t.model.startsWith("nousresearch/")||t.model.startsWith("nvidia/")||t.model.startsWith("openrouter/")||t.model.startsWith("perplexity/")||t.model.startsWith("pygmalionai/")||t.model.startsWith("qwen/")||t.model.startsWith("raifle/")||t.model.startsWith("rekaai/")||t.model.startsWith("sao10k/")||t.model.startsWith("sarvamai/")||t.model.startsWith("scb10x/")||t.model.startsWith("shisa-ai/")||t.model.startsWith("sophosympatheia/")||t.model.startsWith("switchpoint/")||t.model.startsWith("tencent/")||t.model.startsWith("thedrummer/")||t.model.startsWith("thudm/")||t.model.startsWith("tngtech/")||t.model.startsWith("undi95/")||t.model.startsWith("x-ai/")||t.model.startsWith("z-ai/"))&&(t.model="openrouter:"+t.model),!t.model||t.model.startsWith("gpt-")?r="openai-completion":t.model.startsWith("claude-")?r="claude":"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"===t.model||"meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"===t.model||"meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo"===t.model||"google/gemma-2-27b-it"===t.model?r="together-ai":t.model.startsWith("mistral-")||t.model.startsWith("codestral-")||t.model.startsWith("pixtral-")||t.model.startsWith("magistral-")||t.model.startsWith("devstral-")||t.model.startsWith("mistral-ocr-")||t.model.startsWith("open-mistral-")?r="mistral":["distil-whisper-large-v3-en","gemma2-9b-it","gemma-7b-it","llama-3.1-70b-versatile","llama-3.1-8b-instant","llama3-70b-8192","llama3-8b-8192","llama3-groq-70b-8192-tool-use-preview","llama3-groq-8b-8192-tool-use-preview","llama-guard-3-8b","mixtral-8x7b-32768","whisper-large-v3"].includes(t.model)?r="groq":"grok-beta"===t.model?r="xai":t.model.startsWith("grok-")?r="openrouter":"deepseek-chat"===t.model||"deepseek-reasoner"===t.model?r="deepseek":"gemini-1.5-flash"===t.model||"gemini-2.0-flash"===t.model?r="gemini":t.model.startsWith("openrouter:")&&(r="openrouter"),void 0!==s.stream&&"boolean"==typeof s.stream&&(t.stream=s.stream),s.driver&&(r=s.driver);const o=["tools","response"];for(const e of o)s[e]&&(t[e]=s[e]);return""===t.model&&delete t.model,await M(["messages"],"puter-chat-completion",r,"complete",{test_mode:n??!1,transform:async e=>(e.toString=()=>e.message?.content,e.valueOf=()=>e.message?.content,e)}).call(this,t)};txt2img=async(...e)=>{let t={},s=!1;if(!e)throw{message:"Arguments are required",code:"arguments_required"};"string"==typeof e[0]&&(t={prompt:e[0]}),"boolean"==typeof e[1]&&!0===e[1]&&(s=!0),"string"==typeof e[0]&&"object"==typeof e[1]&&(t=e[1],t.prompt=e[0]),"object"==typeof e[0]&&(t=e[0]);let n="openai-image-generation";return"nano-banana"===t.model&&(t.model="gemini-2.5-flash-image-preview"),"gemini-2.5-flash-image-preview"===t.model&&(n="gemini-image-generation"),await M(["prompt"],"puter-image-generation",n,"generate",{responseType:"blob",test_mode:s??!1,transform:async e=>{let t=new Image;return t.src=await q(e),t.toString=()=>t.src,t.valueOf=()=>t.src,t}}).call(this,t)}},B=class{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}list=async(...e)=>{let t={};return"object"==typeof e[0]&&null!==e[0]&&(t.params=e[0]),t.predicate=["user-can-edit"],M(["uid"],"puter-apps",void 0,"select").call(this,t)};create=async(...e)=>{let t={};if("string"==typeof e[0]){let s=e[1],n=e[2]??e[0];t={object:{name:e[0],index_url:s,title:n}}}else if("object"==typeof e[0]&&null!==e[0]){let s=e[0];t={object:{name:s.name,index_url:s.indexURL,title:s.title??s.name,description:s.description,icon:s.icon,maximize_on_start:s.maximizeOnStart,background:s.background,filetype_associations:s.filetypeAssociations,metadata:s.metadata},options:{dedupe_name:s.dedupeName??!1}}}if(!t.object.name)throw{success:!1,error:{code:"invalid_request",message:"Name is required"}};if(!t.object.index_url)throw{success:!1,error:{code:"invalid_request",message:"Index URL is required"}};return await M(["object"],"puter-apps",void 0,"create").call(this,t)};update=async(...e)=>{let t={};if(Array.isArray(e)&&"string"==typeof e[0]){let s=e[1],n={name:s.name,index_url:s.indexURL,title:s.title,description:s.description,icon:s.icon,maximize_on_start:s.maximizeOnStart,background:s.background,filetype_associations:s.filetypeAssociations,metadata:s.metadata};t={id:{name:e[0]},object:n}}return await M(["object"],"puter-apps",void 0,"update").call(this,t)};get=async(...e)=>{let t={};return Array.isArray(e)&&"string"==typeof e[0]&&("object"==typeof e[1]&&null!==e[1]&&(t.params=e[1]),t.id={name:e[0]}),"object"==typeof e[0]&&null!==e[0]&&(t.params=e[0]),M(["uid"],"puter-apps",void 0,"read").call(this,t)};delete=async(...e)=>{let t={};return Array.isArray(e)&&"string"==typeof e[0]&&(t={id:{name:e[0]}}),M(["uid"],"puter-apps",void 0,"delete").call(this,t)};getDeveloperProfile=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]},new Promise((t,s)=>{let n;return n="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]},new Promise((e,t)=>{const s=O("/get-dev-profile",puter.APIOrigin,puter.authToken,"get");C(s,n.success,n.error,e,t),s.send()})})}},F=class{#m=1;constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}signIn=e=>(e=e||{},new Promise((t,s)=>{let n=this.#m++;var r=screen.width/2-300,i=screen.height/2-300;const o=window.open(puter.defaultGUIOrigin+"/action/sign-in?embedded_in_popup=true&msg_id="+n+(window.crossOriginIsolated?"&cross_origin_isolated=true":"")+(e.attempt_temp_user_creation?"&attempt_temp_user_creation=true":""),"Puter","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=600, height=600, top="+i+", left="+r),a=setInterval(()=>{o.closed&&(clearInterval(a),window.removeEventListener("message",c),s({error:"auth_window_closed",msg:"Authentication window was closed by the user without completing the process."}))},100);function c(e){e.data.msg_id==n&&(clearInterval(a),delete e.data.msg_id,delete e.data.msg,e.data.success?(puter.setAuthToken(e.data.token),t(e.data)):s(e.data),window.removeEventListener("message",c))}window.addEventListener("message",c)}));isSignedIn=()=>!!puter.authToken;getUser=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]},new Promise((e,s)=>{const n=O("/whoami",puter.APIOrigin,puter.authToken,"get");C(n,t.success,t.error,e,s),n.send()})};signOut=()=>{puter.resetAuthToken()};async whoami(){try{const e=await fetch(this.APIOrigin+"/whoami",{headers:{Authorization:`Bearer ${this.authToken}`}}),t=await e.json();return globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"auth",operation:"whoami",params:{},result:t}),t}catch(e){throw globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"auth",operation:"whoami",params:{},error:{message:e.message||e.toString(),stack:e.stack}}),e}}};class W{constructor(e,t){this.context=e,this.parameters=t,this._init()}_init(){let e=new URL(location.href).searchParams.get("enabled_logs");e||(e=""),e=e.split(";");for(const t of e)""!==t&&this.context.puter.logger.on(t);globalThis.addEventListener("message",async e=>{e.source===globalThis.parent&&e.data.$&&"puterjs-debug"===e.data.$&&(console.log("Got a puter.js debug event!",e.data),"log.on"===e.data.cmd&&(console.log("Got instruction to turn logs on!"),this.context.puter.logger.on(e.data.category)))})}}class X{constructor({context:e}){this.context=e,this.response_handlers=this.constructor.response_handlers}static response_handlers={"application/x-ndjson":async e=>async function*(e){const t=e.getReader();let s,n;for(;!n&&(({value:s,done:n}=await t.read()),!n);){const e=(new TextDecoder).decode(s).split("\n");for(const t of e)""!==t.trim()&&(yield JSON.parse(t))}}(e.body),"application/json":async e=>await e.json(),"application/octet-stream":async e=>await e.blob()};async call({driver:e,method_name:t,parameters:s}){try{const n=await fetch(`${this.context.APIOrigin}/drivers/call`,{headers:{"Content-Type":"text/plain;actually=json"},method:"POST",body:JSON.stringify({interface:e.iface_name,...e.service_name?{service:e.service_name}:{},method:t,args:s,auth_token:this.context.authToken})}),r=n.headers.get("content-type").split(";")[0].trim(),i=this.response_handlers[r];if(!i){const i=`unrecognized content type: ${r}`;throw console.error(i),console.error("creating blob so dev tools shows response..."),await n.blob(),globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:`${e.iface_name}::${t}`,params:{interface:e.iface_name,driver:e.service_name||e.iface_name,method:t,args:s},error:{message:i}}),new Error(i)}const o=await i(n);return globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:`${e.iface_name}::${t}`,params:{interface:e.iface_name,driver:e.service_name||e.iface_name,method:t,args:s},result:o}),o}catch(n){throw globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:`${e.iface_name}::${t}`,params:{interface:e.iface_name,driver:e.service_name||e.iface_name,method:t,args:s},error:{message:n.message||n.toString(),stack:n.stack}}),n}}}class G{constructor({iface:e,iface_name:t,service_name:s,call_backend:n}){this.iface=e,this.iface_name=t,this.service_name=s,this.call_backend=n}async call(e,t){return await this.call_backend.call({driver:this,method_name:e,parameters:t})}}const V=class{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID,this.drivers_={},this.context={},Object.defineProperty(this.context,"authToken",{get:()=>this.authToken}),Object.defineProperty(this.context,"APIOrigin",{get:()=>this.APIOrigin})}_init({puter:e}){e.call=this.call.bind(this)}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}async list(){try{const e=await fetch(`${this.APIOrigin}/lsmod`,{headers:{Authorization:"Bearer "+this.authToken},method:"POST"}),t=await e.json();return globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:"list",params:{},result:t.interfaces}),t.interfaces}catch(e){throw globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"drivers",operation:"list",params:{},error:{message:e.message||e.toString(),stack:e.stack}}),e}}async get(e,t){t||(t=e);const s=`${e}:${t}`;return this.drivers_[s]?this.drivers_[s]:this.drivers_[s]=new G({call_backend:new X({context:this.context}),iface_name:e,service_name:t})}async call(...e){let t,s,n,r;4===e.length?[t,s,n,r]=e:3===e.length?[t,n,r]=e:2===e.length&&([t,r]=e,n=t);const i=await this.get(t,s);return await i.call(n,r)}},K=Object.create(null);K.open="0",K.close="1",K.ping="2",K.pong="3",K.message="4",K.upgrade="5",K.noop="6";const H=Object.create(null);Object.keys(K).forEach(e=>{H[K[e]]=e});const Y={type:"error",data:"parser error"},Q="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Z="function"==typeof ArrayBuffer,J=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,$=({type:e,data:t},s,n)=>Q&&t instanceof Blob?s?n(t):ee(t,n):Z&&(t instanceof ArrayBuffer||J(t))?s?n(t):ee(new Blob([t]),n):n(K[e]+(t||"")),ee=(e,t)=>{const s=new FileReader;return s.onload=function(){const e=s.result.split(",")[1];t("b"+(e||""))},s.readAsDataURL(e)};function te(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let se;const ne="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)ne["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;const re="function"==typeof ArrayBuffer,ie=(e,t)=>{if("string"!=typeof e)return{type:"message",data:ae(e,t)};const s=e.charAt(0);return"b"===s?{type:"message",data:oe(e.substring(1),t)}:H[s]?e.length>1?{type:H[s],data:e.substring(1)}:{type:H[s]}:Y},oe=(e,t)=>{if(re){const s=(e=>{let t,s,n,r,i,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const h=new ArrayBuffer(o),l=new Uint8Array(h);for(t=0;t<a;t+=4)s=ne[e.charCodeAt(t)],n=ne[e.charCodeAt(t+1)],r=ne[e.charCodeAt(t+2)],i=ne[e.charCodeAt(t+3)],l[c++]=s<<2|n>>4,l[c++]=(15&n)<<4|r>>2,l[c++]=(3&r)<<6|63&i;return h})(e);return ae(s,t)}return{base64:!0,data:e}},ae=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ce=String.fromCharCode(30);function he(){return new TransformStream({transform(e,t){!function(e,t){Q&&e.data instanceof Blob?e.data.arrayBuffer().then(te).then(t):Z&&(e.data instanceof ArrayBuffer||J(e.data))?t(te(e.data)):$(e,!1,e=>{se||(se=new TextEncoder),t(se.encode(e))})}(e,s=>{const n=s.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const e=new DataView(r.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{r=new Uint8Array(9);const e=new DataView(r.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(s)})}})}let le;function ue(e){return e.reduce((e,t)=>e+t.length,0)}function pe(e,t){if(e[0].length===t)return e.shift();const s=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)s[r]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),s}function de(e){if(e)return function(e){for(var t in de.prototype)e[t]=de.prototype[t];return e}(e)}de.prototype.on=de.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},de.prototype.once=function(e,t){function s(){this.off(e,s),t.apply(this,arguments)}return s.fn=t,this.on(e,s),this},de.prototype.off=de.prototype.removeListener=de.prototype.removeAllListeners=de.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<n.length;r++)if((s=n[r])===t||s.fn===t){n.splice(r,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},de.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),s=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(s){n=0;for(var r=(s=s.slice(0)).length;n<r;++n)s[n].apply(this,t)}return this},de.prototype.emitReserved=de.prototype.emit,de.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},de.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ge="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function fe(e,...t){return t.reduce((t,s)=>(e.hasOwnProperty(s)&&(t[s]=e[s]),t),{})}const me=ge.setTimeout,ye=ge.clearTimeout;function be(e,t){t.useNativeTimers?(e.setTimeoutFn=me.bind(ge),e.clearTimeoutFn=ye.bind(ge)):(e.setTimeoutFn=ge.setTimeout.bind(ge),e.clearTimeoutFn=ge.clearTimeout.bind(ge))}class we extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class ve extends de{constructor(e){super(),this.writable=!1,be(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,s){return super.emitReserved("error",new we(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ie(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let s in e)e.hasOwnProperty(s)&&(t.length&&(t+="&"),t+=encodeURIComponent(s)+"="+encodeURIComponent(e[s]));return t}(e);return t.length?"?"+t:""}}const _e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ke={};let Ae,Te=0,Ee=0;function xe(e){let t="";do{t=_e[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function Se(){const e=xe(+new Date);return e!==Ae?(Te=0,Ae=e):e+"."+xe(Te++)}for(;Ee<64;Ee++)ke[_e[Ee]]=Ee;let Ie=!1;try{Ie="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(K){}const Pe=Ie;function Oe(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Pe))return new XMLHttpRequest}catch(e){}if(!t)try{return new(ge[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Re(){}const Ce=null!=new Oe({xdomain:!1}).responseType;class Le extends de{constructor(e,t){super(),be(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=fe(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const s=this.xhr=new Oe(t);try{s.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&s.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{s.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(s.timeout=this.opts.requestTimeout),s.onreadystatechange=()=>{var e;3===s.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(s)),4===s.readyState&&(200===s.status||1223===s.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof s.status?s.status:0)},0))},s.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=Le.requestsCount++,Le.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Re,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Le.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function De(){for(let e in Le.requests)Le.requests.hasOwnProperty(e)&&Le.requests[e].abort()}Le.requestsCount=0,Le.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",De):"function"==typeof addEventListener&&addEventListener("onpagehide"in ge?"pagehide":"unload",De,!1));const Me="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ne=ge.WebSocket||ge.MozWebSocket,Ue="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),qe={websocket:class extends ve{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,s=Ue?{}:fe(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=Ue?new Ne(e,t,s):t?new Ne(e,t):new Ne(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],n=t===e.length-1;$(s,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}n&&Me(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Se()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Ne}},webtransport:class extends ve{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){le||(le=new TextDecoder);const s=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===n){if(ue(s)<1)break;const e=pe(s,1);i=!(128&~e[0]),r=127&e[0],n=r<126?3:126===r?1:2}else if(1===n){if(ue(s)<2)break;const e=pe(s,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(ue(s)<8)break;const e=pe(s,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(Y);break}r=i*Math.pow(2,32)+t.getUint32(4),n=3}else{if(ue(s)<r)break;const e=pe(s,r);a.enqueue(ie(i?e:le.decode(e),t)),n=0}if(0===r||r>e){a.enqueue(Y);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),n=he();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const r=()=>{s.read().then(({done:e,value:t})=>{e||(this.onPacket(t),r())}).catch(e=>{})};r();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this.writer.write(i).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],n=t===e.length-1;this.writer.write(s).then(()=>{n&&Me(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends ve{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let s=location.port;s||(s=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||s!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Ce&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const s=e.split(ce),n=[];for(let e=0;e<s.length;e++){const r=ie(s[e],t);if(n.push(r),"error"===r.type)break}return n})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const s=e.length,n=new Array(s);let r=0;e.forEach((e,i)=>{$(e,!1,e=>{n[i]=e,++r===s&&t(n.join(ce))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Se()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Le(this.uri(),e)}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},je=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ze=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Be(e){const t=e,s=e.indexOf("["),n=e.indexOf("]");-1!=s&&-1!=n&&(e=e.substring(0,s)+e.substring(s,n).replace(/:/g,";")+e.substring(n,e.length));let r=je.exec(e||""),i={},o=14;for(;o--;)i[ze[o]]=r[o]||"";return-1!=s&&-1!=n&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const s=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||s.splice(0,1),"/"==t.slice(-1)&&s.splice(s.length-1,1),s}(0,i.path),i.queryKey=function(e,t){const s={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(s[t]=n)}),s}(0,i.query),i}class Fe extends de{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Be(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Be(t.host).host),be(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},s=e.split("&");for(let e=0,n=s.length;e<n;e++){let n=s[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new qe[e](s)}open(){let e;if(this.opts.rememberUpgrade&&Fe.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(e){let t=this.createTransport(e),s=!1;Fe.priorWebsocketSuccess=!1;const n=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!s)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Fe.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function r(){s||(s=!0,h(),t.close(),t=null)}const i=e=>{const s=new Error("probe error: "+e);s.transport=t.name,r(),this.emitReserved("upgradeError",s)};function o(){i("transport closed")}function a(){i("socket closed")}function c(e){t&&e.name!==t.name&&r()}const h=()=>{t.removeListener("open",n),t.removeListener("error",i),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",i),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onOpen(){if(this.readyState="open",Fe.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let s=0;s<this.writeBuffer.length;s++){const n=this.writeBuffer[s].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,s=0;for(let n=0,r=e.length;n<r;n++)t=e.charCodeAt(n),t<128?s+=1:t<2048?s+=2:t<55296||t>=57344?s+=3:(n++,s+=4);return s}(t):Math.ceil(1.33*(t.byteLength||t.size))),s>0&&e>this.maxPayload)return this.writeBuffer.slice(0,s);e+=2}var t;return this.writeBuffer}write(e,t,s){return this.sendPacket("message",e,t,s),this}send(e,t,s){return this.sendPacket("message",e,t,s),this}sendPacket(e,t,s,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}onError(e){Fe.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let s=0;const n=e.length;for(;s<n;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}Fe.protocol=4;const We="function"==typeof ArrayBuffer,Xe=Object.prototype.toString,Ge="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Xe.call(Blob),Ve="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Xe.call(File);function Ke(e){return We&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Ge&&e instanceof Blob||Ve&&e instanceof File}function He(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,s=e.length;t<s;t++)if(He(e[t]))return!0;return!1}if(Ke(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return He(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&He(e[t]))return!0;return!1}function Ye(e){const t=[],s=e.data,n=e;return n.data=Qe(s,t),n.attachments=t.length,{packet:n,buffers:t}}function Qe(e,t){if(!e)return e;if(Ke(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}if(Array.isArray(e)){const s=new Array(e.length);for(let n=0;n<e.length;n++)s[n]=Qe(e[n],t);return s}if("object"==typeof e&&!(e instanceof Date)){const s={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(s[n]=Qe(e[n],t));return s}return e}function Ze(e,t){return e.data=Je(e.data,t),delete e.attachments,e}function Je(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let s=0;s<e.length;s++)e[s]=Je(e[s],t);else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e[s]=Je(e[s],t));return e}const $e=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var et;function tt(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(et||(et={}));class st extends de{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===et.BINARY_EVENT;s||t.type===et.BINARY_ACK?(t.type=s?et.EVENT:et.ACK,this.reconstructor=new nt(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Ke(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(void 0===et[s.type])throw new Error("unknown packet type "+s.type);if(s.type===et.BINARY_EVENT||s.type===et.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const r=e.substring(n,t);if(r!=Number(r)||"-"!==e.charAt(t))throw new Error("Illegal attachments");s.attachments=Number(r)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);s.nsp=e.substring(n,t)}else s.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const s=e.charAt(t);if(null==s||Number(s)!=s){--t;break}if(t===e.length)break}s.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!st.isPayloadValid(s.type,n))throw new Error("invalid payload");s.data=n}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case et.CONNECT:return tt(t);case et.DISCONNECT:return void 0===t;case et.CONNECT_ERROR:return"string"==typeof t||tt(t);case et.EVENT:case et.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===$e.indexOf(t[0]));case et.ACK:case et.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class nt{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Ze(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var rt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return et},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==et.EVENT&&e.type!==et.ACK||!He(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===et.EVENT?et.BINARY_EVENT:et.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==et.BINARY_EVENT&&e.type!==et.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Ye(e),s=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(s),n}},Decoder:st});function it(e,t,s){return e.on(t,s),function(){e.off(t,s)}}const ot=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class at extends de{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[it(e,"open",this.onopen.bind(this)),it(e,"packet",this.onpacket.bind(this)),it(e,"error",this.onerror.bind(this)),it(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(ot.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const s={type:et.EVENT,data:t,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),s.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(e,t){var s;const n=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,[null,...e])}}emitWithAck(e,...t){const s=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((n,r)=>{t.push((e,t)=>s?e?r(e):n(t):n(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(s===this._queue[0])return null!==e?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),s.pending=!1,this._drainQueue()}),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:et.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case et.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case et.EVENT:case et.BINARY_EVENT:this.onevent(e);break;case et.ACK:case et.BINARY_ACK:this.onack(e);break;case et.DISCONNECT:this.ondisconnect();break;case et.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...n){s||(s=!0,t.packet({type:et.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:et.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function ct(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ct.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),s=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+s:e-s}return 0|Math.min(e,this.max)},ct.prototype.reset=function(){this.attempts=0},ct.prototype.setMin=function(e){this.ms=e},ct.prototype.setMax=function(e){this.max=e},ct.prototype.setJitter=function(e){this.jitter=e};class ht extends de{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,be(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=t.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new ct({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||rt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Fe(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const n=it(t,"open",function(){s.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=it(t,"error",r);if(!1!==this._timeout){const e=this._timeout,s=this.setTimeoutFn(()=>{n(),r(new Error("timeout")),t.close()},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(n),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(it(e,"ping",this.onping.bind(this)),it(e,"data",this.ondata.bind(this)),it(e,"error",this.onerror.bind(this)),it(e,"close",this.onclose.bind(this)),it(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Me(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new at(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const lt={};function ut(e,t){"object"==typeof e&&(t=e,e=void 0);const s=function(e,t="",s){let n=e;s=s||"undefined"!=typeof location&&location,null==e&&(e=s.protocol+"//"+s.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?s.protocol+e:s.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==s?s.protocol+"//"+e:"https://"+e),n=Be(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const r=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port+t,n.href=n.protocol+"://"+r+(s&&s.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=s.source,r=s.id,i=s.path,o=lt[r]&&i in lt[r].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ht(n,t):(lt[r]||(lt[r]=new ht(n,t)),a=lt[r]),s.query&&!t.query&&(t.query=s.queryKey),a.socket(s.path,t)}Object.assign(ut,{Manager:ht,Socket:at,io:ut,connect:ut});const pt=e=>("gui"===puter.env||(e||(e="."),e&&(e.startsWith("/")||e.startsWith("~")||!puter.appID)||(e=c.join("~/AppData",puter.appID,e))),e),dt=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{source:e[0],destination:e[1],overwrite:e[2]?.overwrite,new_name:e[2]?.newName||e[2]?.new_name,create_missing_parents:e[2]?.createMissingParents||e[2]?.create_missing_parents,new_metadata:e[2]?.newMetadata||e[2]?.new_metadata,original_client_socket_id:e[2]?.excludeSocketID||e[2]?.original_client_socket_id,success:e[3],error:e[4]},new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}t.source=pt(t.source),t.destination=pt(t.destination);const n=O("/copy",this.APIOrigin,this.authToken);C(n,t.success,t.error,e,s),n.send(JSON.stringify({original_client_socket_id:this.socket.id,socket_id:this.socket.id,source:t.source,destination:t.destination,overwrite:t.overwrite,new_name:t.new_name||t.newName,dedupe_name:t.dedupe_name||t.dedupeName})),puter._cache.flushall()})},gt=function(...e){let t={};return"string"==typeof e[0]&&"object"==typeof e[1]&&!(e[1]instanceof Function)||"object"==typeof e[0]&&null!==e[0]?"string"==typeof e[0]?(t.path=e[0],Object.assign(t,e[1]),t.success=e[2],t.error=e[3]):t=e[0]:"string"==typeof e[0]&&(t.path=e[0],t.success=e[1],t.error=e[2]),new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}const n=O("/mkdir",this.APIOrigin,this.authToken);C(n,t.success,t.error,e,s),t.path=pt(t.path),n.send(JSON.stringify({parent:c.dirname(t.path),path:c.basename(t.path),overwrite:t.overwrite??!1,dedupe_name:(t.rename||t.dedupeName)??!1,shortcut_to:t.shortcutTo,original_client_socket_id:this.socket.id,create_missing_parents:(t.recursive||t.createMissingParents)??!1})),puter._cache.flushall()})},ft=async function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{path:e[0],options:"object"==typeof e[1]?e[1]:{},success:"object"==typeof e[1]?e[2]:e[1],error:"object"==typeof e[1]?e[3]:e[2]},new Promise(async(e,s)=>{if(t.consistency||(t.consistency="strong"),!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}let n;if(t.path?n="item:"+t.path:t.uid&&(n="item:"+t.uid),!("eventual"!==t.consistency||t.returnSubdomains||t.returnPermissions||t.returnVersions||t.returnSize)){const t=await puter._cache.get(n);if(t)return void e(t)}const r=O("/stat",this.APIOrigin,void 0,"post","text/plain;actually=json");C(r,t.success,t.error,async t=>{JSON.stringify(t).length<=20971520&&(await puter._cache.set("item:"+t.path,t,{EX:3600}),await puter._cache.set("item:"+t.uid,t,{EX:3600})),e(t)},s);let i={};void 0!==t.uid?i.uid=t.uid:void 0!==t.path&&(i.path=pt(t.path)),i.return_subdomains=t.returnSubdomains,i.return_permissions=t.returnPermissions,i.return_versions=t.returnVersions,i.return_size=t.returnSize,i.auth_token=this.authToken,r.send(JSON.stringify(i))})},mt=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{source:e[0],destination:e[1],overwrite:e[2]?.overwrite,new_name:e[2]?.newName||e[2]?.new_name,create_missing_parents:e[2]?.createMissingParents||e[2]?.create_missing_parents,new_metadata:e[2]?.newMetadata||e[2]?.new_metadata,original_client_socket_id:e[2]?.excludeSocketID||e[2]?.original_client_socket_id},new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}if(t.source=pt(t.source),t.destination=pt(t.destination),!t.new_name)try{if(!(await ft.bind(this)(t.destination)).is_dir)throw"is not directory"}catch(e){t.new_name=c.basename(t.destination),t.destination=c.dirname(t.destination)}const n=O("/move",this.APIOrigin,this.authToken);C(n,t.success,t.error,e,s),n.send(JSON.stringify({source:t.source,destination:t.destination,overwrite:t.overwrite,new_name:t.new_name||t.newName,create_missing_parents:t.create_missing_parents||t.createMissingParents,new_metadata:t.new_metadata||t.newMetadata,original_client_socket_id:t.excludeSocketID})),puter._cache.flushall()})},yt=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{path:"string"==typeof e[0]?e[0]:"object"==typeof e[0]&&null!==e[0]?e[0].path:e[0],..."object"==typeof e[1]?e[1]:{success:e[1],error:e[2]}},new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}t.path=pt(t.path);const n=O("/read?"+new URLSearchParams({file:t.path,...t.offset?{offset:t.offset}:{},...t.byte_count?{byte_count:t.byte_count}:{}}).toString(),this.APIOrigin,this.authToken,"get","application/json;charset=UTF-8","blob");C(n,t.success,t.error,e,s),n.send()})},bt=async function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{path:e[0],success:e[1],error:e[2]},new Promise(async(e,s)=>{if(t.consistency||(t.consistency="strong"),!t.path&&!t.uid)throw new Error({code:"NO_PATH_OR_UID",message:"Either path or uid must be provided."});let n;if(t.path?n="readdir:"+t.path:t.uid&&(n="readdir:"+t.uid),"eventual"===t.consistency){const t=await puter._cache.get(n);if(t)return void e(t)}if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}const r=O("/readdir",this.APIOrigin,void 0,"post","text/plain;actually=json");C(r,t.success,t.error,async t=>{const s=3600;JSON.stringify(t).length<=20971520&&await puter._cache.set(n,t,{EX:s});for(const e of t)await puter._cache.set("item:"+e.id,e,{EX:s}),await puter._cache.set("item:"+e.path,e,{EX:s});e(t)},s);const i={no_thumbs:t.no_thumbs,no_assocs:t.no_assocs,auth_token:this.authToken};t.uid?i.uid=t.uid:t.path&&(i.path=pt(t.path)),r.send(JSON.stringify(i))})},wt=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{path:e[0],new_name:e[1],success:e[2],error:e[3]},new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}const n=O("/rename",this.APIOrigin,this.authToken);C(n,t.success,t.error,e,s);let r={original_client_socket_id:t.excludeSocketID||t.original_client_socket_id,new_name:t.new_name||t.newName};void 0!==t.uid?r.uid=t.uid:void 0!==t.path&&(r.path=pt(t.path)),n.send(JSON.stringify(r)),puter._cache.flushall()})},vt=function(...e){let t;return t={app_uid:e[0],items:e[1],success:e[2],error:e[3]},new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}let n=t.items;Array.isArray(n)||(n=[n]);const r=O("/sign",this.APIOrigin,this.authToken);r.addEventListener("load",async function(r){const i=await I(this);if(200!==this.status)return t.error&&"function"==typeof t.error&&t.error(i),s(i);{let s,r=i,o=r.token;if(1==n.length)s={...r.signatures[0]};else{let e=[];for(let t=0;t<r.signatures.length;t++)e.push({...r.signatures[t]});s=e}return t.success&&"function"==typeof t.success&&t.success({token:o,items:s}),e({token:o,items:s})}}),r.upload.addEventListener("progress",function(e){}),r.addEventListener("error",function(e){return R(t.error,s,this)}),r.send(JSON.stringify({app_uid:t.app_uid,items:n}))})},_t=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]},new Promise(async(e,s)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){s("Authentication failed.")}const n=O("/df",this.APIOrigin,this.authToken);C(n,t.success,t.error,e,s),n.send()})},kt=async function(e,t){if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){throw"Authentication failed."}t=pt(t),e=pt(e);const s=c.basename(t),n={op:"symlink",path:c.dirname(t),name:s,target:e},r=new FormData;r.append("operation",JSON.stringify(n));try{const e=await fetch(this.APIOrigin+"/batch",{method:"POST",headers:{Authorization:`Bearer ${puter.authToken}`},body:r});if(200!==e.status){const t=await e.text();throw console.error("[symlink] fetch error: ",t),t}}catch(e){throw console.error("[symlink] fetch error: ",e),e}},At=async function(e,t,s={}){return new Promise(async(n,r)=>{const i=globalThis.DataTransfer||class{},o=globalThis.FileList||class{},a=globalThis.DataTransferItemList||class{};if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){r(e)}const h=e=>(s.error&&"function"==typeof s.error&&s.error(e),r(e));let l=new XMLHttpRequest;if("/"===t)return h("Can not upload to root directory.");t=pt(t);const u=P();s.init&&"function"==typeof s.init&&s.init(u,l);let p,d=0,g=0,f=0,m=!1;if(Array.isArray(e)&&e.length>0)for(let t=0;t<e.length;t++)(e[t]instanceof i||e[t]instanceof a)&&(m=!0);if(e instanceof a||e instanceof i||e[0]instanceof i||s.parsedDataTransferItems)p=s.parsedDataTransferItems?e:await puter.ui.getEntriesFromDataTransferItems(e),p.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.isDirectory&&t.isDirectory?0:e.size-t.size);else if(e instanceof File||e[0]instanceof File||e instanceof o||e[0]instanceof o){p=Array.isArray(e)?e:e instanceof o?Array.from(e):[e],p.sort((e,t)=>e.size-t.size);for(let e=0;e<p.length;e++)p[e].filepath=p[e].name,p[e].fullPath=p[e].name}else if(e instanceof Blob){p=[new File([e],s.name,{type:"application/octet-stream"})];for(let e=0;e<p.length;e++)p[e].filepath=p[e].name,p[e].fullPath=p[e].name}else{if("string"!=typeof e)return h({code:"field_invalid",message:"upload() items parameter is an invalid type"});p=[new File([e],"default.txt",{type:"text/plain"})];for(let e=0;e<p.length;e++)p[e].filepath=p[e].name,p[e].fullPath=p[e].name}let y,b=[],w={},v=[];for(let e=0;e<p.length;e++)if(p[e]){if(p[e].isDirectory)b.push({path:c.join(t,p[e].finalPath?p[e].finalPath:p[e].fullPath)});else{let n=p[e].finalPath?p[e].finalPath:p[e].fullPath,[r,i]=[n?.slice(0,n?.lastIndexOf("/")),n?.slice(n?.lastIndexOf("/")+1)];if(""!=i&&v.push(p[e]),s.createFileParent&&n.includes("/")){let e;r.split("/").forEach(s=>{e=e?e+"/"+s:s;let n=c.join(t,e);w[n]||(w[n]=!0,b.push({path:n}))})}}void 0!==p[e].size&&(f+=p[e].size)}if(0===b.length&&0===v.length)return h({code:"EMPTY_UPLOAD",message:"No files or directories to upload."});if("web"!==puter.env)try{if(y=await this.space(),y.capacity-y.used<f)return h({code:"NOT_ENOUGH_SPACE",message:"Not enough storage space available."})}catch(e){}f*=2;const _=new FormData;b.sort((e,t)=>t.path.length-e.path.length);let k=[];for(let e=0;e<b.length;e++){for(let s=0;s<v.length;s++)!v[s].puter_path_param&&c.join(t,v[s].filepath).startsWith(b[e].path+"/")&&(v[s].puter_path_param=`$dir_${e}/`+c.basename(v[s].filepath));for(let t=0;t<b.length;t++)!b[t].puter_path_param&&b[t].path.startsWith(b[e].path+"/")&&(b[t].puter_path_param=`$dir_${e}/`+c.basename(b[t].path))}for(let e=0;e<b.length;e++){let t=c.dirname(b[e].puter_path_param||b[e].path),n=b[e].puter_path_param||b[e].path;"/"!==t&&(n=n.replace(t,"")),k.push({op:"mkdir",parent:t,path:n,overwrite:s.overwrite??!1,dedupe_name:s.dedupeName??!0,create_missing_ancestors:s.createMissingAncestors??!0,as:`dir_${e}`})}k.reverse(),_.append("operation_id",u),_.append("socket_id",this.socket.id),_.append("original_client_socket_id",this.socket.id);for(let e=0;e<k.length;e++)_.append("operation",JSON.stringify(k[e]));if(!s.shortcutTo)for(let e=0;e<v.length;e++)_.append("fileinfo",JSON.stringify({name:v[e].name,type:v[e].type,size:v[e].size}));for(let e=0;e<v.length;e++)_.append("operation",JSON.stringify({op:s.shortcutTo?"shortcut":"write",dedupe_name:s.dedupeName??!0,overwrite:s.overwrite??!1,create_missing_ancestors:s.createMissingAncestors||s.createMissingParents,operation_id:u,path:v[e].puter_path_param&&c.dirname(v[e].puter_path_param??"")||v[e].filepath&&c.join(t,c.dirname(v[e].filepath))||"",name:c.basename(v[e].filepath),item_upload_id:e,shortcut_to:s.shortcutTo,shortcut_to_uid:s.shortcutTo,app_uid:s.appUID}));if(!s.shortcutTo)for(let e=0;e<v.length;e++)_.append("file",v[e]??"");const A=e=>{e.operation_id===u&&(g+=e.loaded_diff)};this.socket.on("upload.progress",A);let T=null;l.open("post",this.APIOrigin+"/batch",!0),l.setRequestHeader("Authorization","Bearer "+this.authToken),l.upload.addEventListener("progress",function(e){let t;null===T?(t=e.loaded,T=0):t=e.loaded-T,T+=t,d+=t;let n=((g+d)/f*100).toFixed(2);n=n>100?100:n,s.progress&&"function"==typeof s.progress&&s.progress(u,n)});let E=setInterval(function(){let e=((g+d)/f*100).toFixed(2);e=e>100?100:e,s.progress&&"function"==typeof s.progress&&s.progress(u,e)},100);l.onabort=()=>{clearInterval(E),this.socket.off("upload.progress",A),s.abort&&"function"==typeof s.abort&&s.abort(u)},l.onreadystatechange=async e=>{if(4===l.readyState){const e=await I(l);if(l.status>=400&&l.status<600||s.strict&&218===l.status){if(clearInterval(E),this.socket.off("upload.progress",A),s.strict&&218===l.status){let t;for(let s=0;s<e.results?.length;s++)if(200!==e.results[s].status){t=e.results[s];break}return h(t)}return h(e)}{e&&e.results&&0!==e.results.length||puter.debugMode&&console.log("no results");let t=e.results;return t=1===t.length?t[0]:t,s.success&&"function"==typeof s.success&&s.success(t),clearInterval(E),this.socket.off("upload.progress",A),n(t)}}},s.start&&"function"==typeof s.start&&s.start(),puter._cache.flushall(),l.send(_)})},Tt=async function(e,t,s={}){if(!e)throw new Error({code:"NO_TARGET_PATH",message:"No target path provided."});e instanceof File&&void 0===t&&(e=(t=e).name),s.strict=!0,s.overwrite=s.overwrite??!0,s.overwrite&&void 0===s.dedupeName&&(s.dedupeName=!1),e=pt(e);const n=c.basename(e),r=c.dirname(e);if("string"==typeof t?t=new File([t??""],n??"Untitled.txt",{type:"text/plain"}):t instanceof Blob?t=new File([t??""],n??"Untitled",{type:t.type}):(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t=new File([t],n??"Untitled",{type:"application/octet-stream"})),t||(t=new File([t??""],n)),!(t instanceof File))throw new Error({code:"field_invalid",message:"write() data parameter is an invalid type"});return puter._cache.flushall(),this.upload(t,r,s)},Et=class{constructor(e){this.readURL=e.readURL??e.read_url,this.writeURL=e.writeURL??e.write_url,this.metadataURL=e.metadataURL??e.metadata_url,this.name=e.name??e.fsentry_name,this.uid=e.uid??e.uuid??e.fsentry_uid??e.fsentry_id??e.fsentry_uuid??e.id,this.id=this.uid,this.uuid=this.uid,this.path=e.path??e.fsentry_path,this.size=e.size??e.fsentry_size,this.accessed=e.accessed??e.fsentry_accessed,this.modified=e.modified??e.fsentry_modified,this.created=e.created??e.fsentry_created,this.isDirectory=!!(e.isDirectory||e.is_dir||e.fsentry_is_dir);const t={};Object.defineProperty(this,"_internalProperties",{enumerable:!1,value:t}),t.signature=e.signature??(()=>new URL(this.writeURL??this.readURL).searchParams.get("signature"))(),t.expires=e.expires??(()=>new URL(this.writeURL??this.readURL).searchParams.get("expires"))(),Object.defineProperty(t,"file_signature",{get:()=>({read_url:this.readURL,write_url:this.writeURL,metadata_url:this.metadataURL,fsentry_accessed:this.accessed,fsentry_modified:this.modified,fsentry_created:this.created,fsentry_is_dir:this.isDirectory,fsentry_size:this.size,fsentry_name:this.name,path:this.path,uid:this.uid})})}write=async function(e){return puter.fs.write(this.path,new File([e],this.name),{overwrite:!0,dedupeName:!1})};watch=function(e){};open=function(e){};setAsWallpaper=function(e,t){};rename=function(e){return puter.fs.rename(this.uid,e)};move=function(e,t=!1,s){return puter.fs.move(this.path,e,t,s)};copy=function(e,t=!1,s=!1){return puter.fs.copy(this.path,e,t,s)};delete=function(){return puter.fs.delete(this.path)};versions=async function(){};trash=function(){};mkdir=async function(e,t=!1){if(!this.isDirectory)throw new Error("mkdir() can only be called on a directory");return puter.fs.mkdir(c.join(this.path,e))};metadata=async function(){};readdir=async function(){if(!this.isDirectory)throw new Error("readdir() can only be called on a directory");return puter.fs.readdir(this.path)};read=async function(){return puter.fs.read(this.path)}},xt=async function(...e){let t;t="object"==typeof e[0]&&null!==e[0]?e[0]:{paths:e[0],recursive:e[1]?.recursive??!0,descendantsOnly:e[1]?.descendantsOnly??!1};let s=t.paths;return"string"==typeof s&&(s=[s]),new Promise(async(e,n)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){n("Authentication failed.")}const r=O("/delete",this.APIOrigin,this.authToken);C(r,t.success,t.error,e,n),s=s.map(e=>pt(e)),r.send(JSON.stringify({paths:s,descendants_only:(t.descendants_only||t.descendantsOnly)??!1,recursive:t.recursive??!0}))})},St=async function(e,t="24h"){return new Promise(async(s,n)=>{if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){n("Authentication failed.")}try{const{uid:r,is_dir:i}=await ft.call(this,e);if(i)return void n("Cannot create readUrl for directory");const o=O("/auth/create-access-token",this.APIOrigin,this.authToken);C(o,()=>{},()=>{},({token:e})=>{s(`${this.APIOrigin}/token-read?uid=${encodeURIComponent(r)}&token=${encodeURIComponent(e)}`)},n),o.send(JSON.stringify({expiresIn:t,permissions:[`fs:${r}:read`]}))}catch(e){n(e)}})};class It extends e.AdvancedBase{space=_t;mkdir=gt;copy=dt;rename=wt;upload=At;read=yt;delete=xt;move=mt;write=Tt;sign=vt;symlink=kt;getReadURL=St;readdir=bt;stat=ft;FSItem=Et;static NARI_METHODS={};constructor(e){super(),this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID,this.context=e,this.initializeSocket();const t={};Object.defineProperty(t,"authToken",{get:()=>this.authToken}),Object.defineProperty(t,"APIOrigin",{get:()=>this.APIOrigin})}initializeSocket(){this.socket&&this.socket.disconnect(),this.socket=ut(this.APIOrigin,{auth:{auth_token:this.authToken},autoUnref:"nodejs"===this.context.env}),this.bindSocketEvents()}bindSocketEvents(){this.socket.on("item.added",e=>{puter._cache.flushall()}),this.socket.on("item.renamed",e=>{puter._cache.flushall()}),this.socket.on("item.moved",e=>{puter._cache.flushall()}),this.socket.on("connect",()=>{puter.debugMode&&console.log("FileSystem Socket: Connected",this.socket.id)}),this.socket.on("disconnect",()=>{puter.debugMode&&console.log("FileSystem Socket: Disconnected"),puter._cache.flushall()}),this.socket.on("reconnect",e=>{puter.debugMode&&console.log("FileSystem Socket: Reconnected",this.socket.id)}),this.socket.on("reconnect_attempt",e=>{puter.debugMode&&console.log("FileSystem Socket: Reconnection Attemps",e)}),this.socket.on("reconnect_error",e=>{puter.debugMode&&console.log("FileSystem Socket: Reconnection Error",e)}),this.socket.on("reconnect_failed",()=>{puter.debugMode&&console.log("FileSystem Socket: Reconnection Failed")}),this.socket.on("error",e=>{puter.debugMode&&console.error("FileSystem Socket Error:",e)})}setAuthToken(e){this.authToken=e,this.initializeSocket()}setAPIOrigin(e){this.APIOrigin=e,this.initializeSocket()}}const Pt=class{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}list=async(...e)=>(await M([],"puter-subdomains",void 0,"select")(...e)).filter(e=>!e.subdomain.startsWith("workers.puter."));create=async(...e)=>{let t={};return"string"==typeof e[0]&&1===e.length?(e[0].match(/^[a-z0-9]+\.puter\.(site|com)$/)&&(e[0]=e[0].split(".")[0]),t={object:{subdomain:e[0]}}):Array.isArray(e)&&2===e.length&&"string"==typeof e[0]?(e[0].match(/^[a-z0-9]+\.puter\.(site|com)$/)&&(e[0]=e[0].split(".")[0]),e[1]&&(e[1]=pt(e[1])),t={object:{subdomain:e[0],root_dir:e[1]}}):"object"==typeof e[0]&&(t={object:e[0]}),await M(["object"],"puter-subdomains",void 0,"create").call(this,t)};update=async(...e)=>{let t={};return Array.isArray(e)&&"string"==typeof e[0]&&(e[0].match(/^[a-z0-9]+\.puter\.(site|com)$/)&&(e[0]=e[0].split(".")[0]),e[1]&&(e[1]=pt(e[1])),t={id:{subdomain:e[0]},object:{root_dir:e[1]??null}}),await M(["object"],"puter-subdomains",void 0,"update").call(this,t)};get=async(...e)=>{let t={};return Array.isArray(e)&&"string"==typeof e[0]&&(e[0].match(/^[a-z0-9]+\.puter\.(site|com)$/)&&(e[0]=e[0].split(".")[0]),t={id:{subdomain:e[0]}}),M(["uid"],"puter-subdomains",void 0,"read").call(this,t)};delete=async(...e)=>{let t={};return Array.isArray(e)&&"string"==typeof e[0]&&(e[0].match(/^[a-z0-9]+\.puter\.(site|com)$/)&&(e[0]=e[0].split(".")[0]),t={id:{subdomain:e[0]}}),M(["uid"],"puter-subdomains",void 0,"delete").call(this,t)}};var Ot=s(717);const Rt=["has_set_default_app_user_permissions","window_sidebar_width","sidebar_items","menubar_style","user_preferences.auto_arrange_desktop","user_preferences.show_hidden_files","user_preferences.language","user_preferences.clock_visible","toolbar_auto_hide_enabled","has_seen_welcome_window","desktop_item_positions","desktop_icons_hidden","taskbar_position","has_seen_toolbar_animation"];function Ct(e,t){let s=(n=e,n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[/g,"[").replace(/\\\]/g,"]").replace(/\\\^/g,"^");var n;return new RegExp("^"+s+"$").test(t)}const Lt=class{MAX_KEY_SIZE=1024;MAX_VALUE_SIZE=409600;constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID,this.gui_cached=new Ot.TeePromise,this.gui_cache_init=new Ot.TeePromise,(async()=>{await this.gui_cache_init,this.gui_cache_init=null;const e=await fetch(`${this.APIOrigin}/drivers/call`,{method:"POST",headers:{"Content-Type":"text/plain;actually=json"},body:JSON.stringify({interface:"puter-kvstore",method:"get",args:{key:Rt},auth_token:this.authToken})}),t=await e.json();if(!Array.isArray(t?.result))return this.gui_cached.resolve({}),void setTimeout(()=>{this.gui_cached=null},4e3);const s={};for(let e=0;e<Rt.length;e++)s[Rt[e]]=t.result[e];this.gui_cached.resolve(s),setTimeout(()=>{this.gui_cached=null},4e3)})()}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}set=M(["key","value","expireAt"],"puter-kvstore",void 0,"set",{preprocess:e=>{if(console.log(e),void 0===e.key||null===e.key)throw{message:"Key cannot be undefined",code:"key_undefined"};if(e.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};if(e.value&&e.value.length>this.MAX_VALUE_SIZE)throw{message:"Value size cannot be larger than "+this.MAX_VALUE_SIZE,code:"value_too_large"};return e}});async get(...e){return"string"==typeof e[0]&&Rt.includes(e[0])&&null!==this.gui_cached?(this.gui_cache_init&&this.gui_cache_init.resolve(),(await this.gui_cached)[e[0]]):await this.get_(...e)}get_=M(["key"],"puter-kvstore",void 0,"get",{preprocess:e=>{if(e.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};return e},transform:e=>e});incr=async(...e)=>{let t={};if(!e||0===e.length)throw{message:"Arguments are required",code:"arguments_required"};if(t.key=e[0],t.amount=e[1]??1,t.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};return M(["key"],"puter-kvstore",void 0,"incr").call(this,t)};decr=async(...e)=>{let t={};if(!e||0===e.length)throw{message:"Arguments are required",code:"arguments_required"};if(t.key=e[0],t.amount=e[1]??1,t.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};return M(["key"],"puter-kvstore",void 0,"decr").call(this,t)};expire=async(...e)=>{let t={};if(t.key=e[0],t.ttl=e[1],t.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};return M(["key","ttl"],"puter-kvstore",void 0,"expire").call(this,t)};expireAt=async(...e)=>{let t={};if(t.key=e[0],t.timestamp=e[1],t.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};return M(["key","timestamp"],"puter-kvstore",void 0,"expireAt").call(this,t)};del=M(["key"],"puter-kvstore",void 0,"del",{preprocess:e=>{if(e.key.length>this.MAX_KEY_SIZE)throw{message:"Key size cannot be larger than "+this.MAX_KEY_SIZE,code:"key_too_large"};return e}});list=async(...e)=>{let t,s={},n=!1;return e&&1===e.length&&!0===e[0]||e&&2===e.length&&!0===e[1]?(s={},n=!0):s={as:"keys"},(e&&1===e.length&&"string"==typeof e[0]||e&&2===e.length&&"string"==typeof e[0]&&!0===e[1])&&(t=e[0]),M([],"puter-kvstore",void 0,"list",{transform:e=>t?n?e.filter(e=>Ct(t,e.key)):e.filter(e=>Ct(t,e)):e}).call(this,s)};flush=M([],"puter-kvstore",void 0,"flush");clear=this.flush};class Dt{#y;#b;constructor(e){this.#y=e,this.#b=(()=>{const e=new Map;for(let t of this.#y)e[t]=[];return e})()}emit(e,t){this.#y.includes(e)?this.#b[e].forEach(e=>{e(t)}):console.error(`Event name '${e}' not supported`)}on(e,t){if(this.#y.includes(e))return this.#b[e].push(t),this;console.error(`Event name '${e}' not supported`)}off(e,t){if(!this.#y.includes(e))return void console.error(`Event name '${e}' not supported`);const s=this.#b[e],n=s.indexOf(t);return-1!==n&&s.splice(n,1),this}}const Mt=new TextDecoder,Nt=new TextEncoder,Ut={1:"Reason unspecified or unknown. Returning a more specific reason should be preferred.",3:"Unexpected stream closure due to a network error.",65:"Stream creation failed due to invalid information. This could be sent if the destination was a reserved address or the port is invalid.",66:"Stream creation failed due to an unreachable destination host. This could be sent if the destination is an domain which does not resolve to anything.",67:"Stream creation timed out due to the destination server not responding.",68:"Stream creation failed due to the destination server refusing the connection.",71:"TCP data transfer timed out.",72:"Stream destination address/domain is intentionally blocked by the proxy server.",73:"Connection throttled by the server."};function qt(e){let t=5;switch(e.packetType){case 1:e.hostEncoded=Nt.encode(e.hostname),t+=3+e.hostEncoded.length;break;case 2:t+=e.payload.byteLength;break;case 3:t+=4;break;case 4:t+=1;break;case 5:t+=2,e.password&&(t+=6),e.puterAuth&&(e.passwordEncoded=Nt.encode(e.puterAuth),t+=8+e.passwordEncoded.length);break;default:throw new Error("Not supported")}let s=new Uint8Array(t);const n=new DataView(s.buffer);switch(n.setUint8(0,e.packetType),n.setUint32(1,e.streamID,!0),e.packetType){case 1:n.setUint8(5,e.streamType),n.setUint16(6,e.port,!0),s.set(e.hostEncoded,8);break;case 2:s.set(e.payload,5);break;case 3:n.setUint32(5,e.remainingBuffer,!0);break;case 4:n.setUint8(5,e.reason);break;case 5:n.setUint8(5,2),n.setUint8(6,0),e.password&&(n.setUint8(7,2),n.setUint32(8,1,!0),n.setUint8(12,0)),e.puterAuth&&(n.setUint8(7,2),n.setUint32(8,5+e.passwordEncoded.length,!0),n.setUint8(12,0),n.setUint16(13,e.passwordEncoded.length,!0),s.set(e.passwordEncoded,15))}return s}class jt{_ws;_nextStreamID=1;_bufferMax;onReady=void 0;streamMap=new Map;constructor(e,t){const s=()=>{this._ws=new WebSocket(e),this._ws.binaryType="arraybuffer",this._ws.onmessage=e=>{const n=function(e){const t=new DataView(e.buffer,e.byteOffset),s=t.getUint8(0),n=t.getUint32(1,!0);switch(s){case 1:return{packetType:s,streamID:n,streamType:t.getUint8(5),port:t.getUint16(6,!0),hostname:Mt.decode(e.subarray(8,e.length))};case 2:return{packetType:s,streamID:n,payload:e.subarray(5,e.length)};case 3:return{packetType:s,streamID:n,remainingBuffer:t.getUint32(5,!0)};case 4:return{packetType:s,streamID:n,reason:t.getUint8(5)};case 5:const r={};r.version_major=t.getUint8(5),r.version_minor=t.getUint8(6);let i=7;for(;i<e.length;){const s=t.getUint8(i),n=t.getUint32(i+1,!0),o=e.subarray(i+5,i+5+n);r[s]=o,i+=5+n}return{packetType:s,streamID:n,infoObj:r}}}(new Uint8Array(e.data));switch(n.packetType){case 2:this.streamMap.get(n.streamID).dataCallBack(n.payload.slice(0));break;case 3:if(0===n.streamID)return this._bufferMax=n.remainingBuffer,this._ws.onclose=()=>{setTimeout(s(),1e3)},void(this.onReady&&this.onReady());this.streamMap.get(n.streamID).buffer=n.remainingBuffer,this._continue();break;case 4:0!==n.streamID&&this.streamMap.get(n.streamID).closeCallBack(n.reason);break;case 5:t&&this._ws.send(qt({packetType:5,streamID:0,puterAuth:t}))}}};s()}_continue(e){const t=this.streamMap.get(e).queue;for(let s=0;s<t.length;s++)this.write(e,t.shift())}register(e,t,s){const n=this._nextStreamID++;return this.streamMap.set(n,{queue:[],streamID:n,buffer:this._bufferMax,dataCallBack:s.dataCallBack,closeCallBack:s.closeCallBack}),this._ws.send(qt({packetType:1,streamType:1,streamID:n,hostname:e,port:t})),n}write(e,t){const s=this.streamMap.get(e);s.buffer>0?(s.buffer--,this._ws.send(qt({packetType:2,streamID:e,payload:t}))):s.queue.push(t)}close(e){this._ws.send(qt({packetType:4,streamID:e,reason:2}))}}const zt=new TextEncoder;let Bt,Ft={server:"wss://puter.cafe/",handler:void 0};class Wt extends Dt{_events=new Map;_streamID;constructor(e,t){super(["data","drain","open","error","close","tlsdata","tlsopen","tlsclose"]),(async()=>{if(!puter.authToken&&puter.env,!Ft.handler){const{token:e,server:t}=await(await fetch(puter.APIOrigin+"/wisp/relay-token/create",{method:"POST",headers:{Authorization:puter.authToken?`Bearer ${puter.authToken}`:"","Content-Type":"application/json"},body:JSON.stringify({})})).json();Ft.handler=new jt(t,e),await new Promise((e,t)=>{Ft.handler.onReady=e})}const s={dataCallBack:e=>{this.emit("data",e)},closeCallBack:e=>{if(2!==e)return this.emit("error",new Error(Ut[e])),void this.emit("close",!0);this.emit("close",!1)}};this._streamID=Ft.handler.register(e,t,s),setTimeout(()=>{this.emit("open",void 0)},0)})()}addListener(...e){this.on(...e)}write(e,t){if(e.buffer)Ft.handler.write(this._streamID,e),t&&t();else if(e.resize)e.write(this._streamID,new Uint8Array(e)),t&&t();else{if("string"!=typeof e)throw new Error("Invalid data type (not TypedArray, ArrayBuffer or String!!)");Ft.handler.write(this._streamID,zt.encode(e)),t&&t()}}close(){Ft.handler.close(this._streamID)}}class Xt extends Wt{constructor(...e){super(...e),super.on("open",async()=>{Bt||(Bt=await import("https://puter-net.b-cdn.net/rustls.js"),await Bt.default("https://puter-net.b-cdn.net/rustls.wasm"));let t=!1;const s=new ReadableStream({start:e=>{super.on("data",t=>{e.enqueue(t.buffer)}),super.on("close",()=>{t||e.close()})},pull:e=>{},cancel:()=>{t=!0}}),n=new WritableStream({write:e=>{super.write(e)},abort:()=>{super.close()},close:()=>{super.close()}});let r,i;try{const t=await Bt.connect_tls(s,n,e[0]);r=t.read,i=t.write}catch(e){return void this.emit("error",new Error("TLS Handshake failed: "+e))}this.writer=i.getWriter();let o=r.getReader(),a=!1;this.emit("tlsopen",void 0);try{for(;!a;){const{done:e,value:t}=await o.read();a=e,a||this.emit("tlsdata",t)}this.emit("tlsclose",!1)}catch(e){this.emit("error",e),this.emit("tlsclose",!0)}})}on(e,t){return"data"===e||"open"===e||"close"===e?super.on("tls"+e,t):super.on(e,t)}write(e,t){if(e.buffer)this.writer.write(e.slice(0).buffer).then(t);else if(e.resize)this.writer.write(e).then(t);else{if("string"!=typeof e)throw new Error("Invalid data type (not TypedArray, ArrayBuffer or String!!)");this.writer.write(e).then(t)}}}function Gt(...e){return new Promise(async(t,s)=>{try{const n=new Request(...e),r=new URL(n.url);let i,o=new Headers(n.headers);if("http:"===r.protocol)i=new puter.net.Socket(r.hostname,r.port||80);else{if("https:"!==r.protocol){const e=`Failed to fetch. URL scheme "${r.protocol}" is not supported.`;return globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"network",operation:"pFetch",params:{url:n.url,method:n.method},error:{message:e}}),void s(e)}i=new puter.net.tls.TLSSocket(r.hostname,r.port||443)}o.get("user-agent")||o.set("user-agent",navigator.userAgent);let a,c=`${n.method} ${r.pathname}${r.search} HTTP/1.1\r\nHost: ${r.host}\r\nConnection: close\r\n`;for(const[e,t]of o)c+=`${e}: ${t}\r\n`;if(n.body){if(a=new Uint8Array(await n.arrayBuffer()),o.has("content-length")){if(o.get("content-length")!==String(a.length))return s("Content-Length header does not match the body length. Please check your request.")}else o.set("content-length",a.length);c+=`Content-Length: ${a.length}\r\n`}c+="\r\n",i.on("open",async()=>{i.write(c),a&&i.write(a)});const h=new TextDecoder;let l="",u=-1;const p=[];let d=!1,g=-1,f=0,m=!1,y=-1,b=new Uint8Array(0);const w=new ReadableStream({start(e){function r(t){const s=new Uint8Array(b.length+t.length);for(s.set(b,0),s.set(t,b.length),b=s;;)if(y>0){if(!(b.length>=y+2)){e.enqueue(b),y-=b.length,b=new Uint8Array(0);break}{const t=b.slice(0,y);e.enqueue(t),b=b.slice(y+2),y=0}}else{let t=-1;for(let e=0;e+1<b.length;e++)if(13===b[e]&&10===b[e+1]){t=e;break}if(t<0)break;const s=h.decode(b.slice(0,t)).trim();if(y=parseInt(s,16),isNaN(y)&&e.error("Invalid chunk length from server"),b=b.slice(t+2),0===y)return d=!0,void e.close()}}i.on("data",s=>{if(-1===u||m||(e.enqueue(s),f+=s.length),-1===u&&(p.push(s),l+=h.decode(s,{stream:!0})),m&&r(s),-1!==l.indexOf("\r\n\r\n")){u=l.indexOf("\r\n\r\n"),l=l.slice(0,u);const s=function(e){const t=e.split("\r\n"),s=t.shift().split(" "),n=Number(s[1]),r=s.slice(2).join(" ")||"",i=[];for(const e of t){const t=e.split(": "),s=t[0],n=t.slice(1).join(": ");i.push([s,n])}return new Headers(i),{headers:new Headers(i),statusText:r,status:n}}(l);g=Number(s.headers.get("content-length")),m="chunked"===s.headers.get("transfer-encoding"),globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"network",operation:"pFetch",params:{url:n.url,method:n.method},result:{status:s.status,statusText:s.statusText}}),t(new Response(w,s));const i=function(...e){const t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t);return e.forEach((e,t,n)=>{const r=n.slice(0,t).reduce((e,t)=>e+t.length,0);s.set(e,r)}),s}(...p).slice(u+4);m?r(i):(f+=i.length,e.enqueue(i))}-1===g||f!==g||m||d||(d=!0,e.close())}),i.on("close",()=>{d||(d=!0,e.close())}),i.on("error",e=>{globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"network",operation:"pFetch",params:{url:n.url,method:n.method},error:{message:"Socket errored with the following reason: "+e}}),s("Socket errored with the following reason: "+e)})}})}catch(e){globalThis.puter?.apiCallLogger?.isEnabled()&&globalThis.puter.apiCallLogger.logRequest({service:"network",operation:"pFetch",params:{url:reqObj.url,method:reqObj.method},error:{message:e.message||e.toString(),stack:e.stack}}),s(e)}})}const Vt=class{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin,this.appID=e.appID}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}user=function(...e){let t;t="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]};let s="";return t?.query&&(s="?"+new URLSearchParams(t.query).toString()),new Promise((e,n)=>{const r=O("/whoami"+s,this.APIOrigin,this.authToken,"get");C(r,t.success,t.error,e,n),r.send()})};version=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]},new Promise((e,s)=>{const n=O("/version",this.APIOrigin,this.authToken,"get");C(n,t.success,t.error,e,s),n.send()})}};class Kt{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}async req_(e,t){const s=await fetch(this.APIOrigin+e,{method:t?"POST":"GET",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},...t?{body:JSON.stringify(t)}:{}});return await s.json()}async grantUser(e,t){return await this.req_("/auth/grant-user-user",{target_username:e,permission:t})}async grantGroup(e,t){return await this.req_("/auth/grant-user-group",{group_uid:e,permission:t})}async grantApp(e,t){return await this.req_("/auth/grant-user-app",{app_uid:e,permission:t})}async grantAppAnyUser(e,t){return await this.req_("/auth/grant-dev-app",{app_uid:e,permission:t})}async grantOrigin(e,t){return await this.req_("/auth/grant-user-app",{origin:e,permission:t})}async revokeUser(e,t){return await this.req_("/auth/revoke-user-user",{target_username:e,permission:t})}async revokeGroup(e,t){return await this.req_("/auth/revoke-user-group",{group_uid:e,permission:t})}async revokeApp(e,t){return await this.req_("/auth/revoke-user-app",{app_uid:e,permission:t})}async revokeAppAnyUser(e,t){return await this.req_("/auth/revoke-dev-app",{app_uid:e,permission:t})}async revokeOrigin(e,t){return await this.req_("/auth/revoke-user-app",{origin:e,permission:t})}async createGroup(e={},t={}){return await this.req_("/group/create",{metadata:e,extra:t})}async addUsersToGroup(e,t){return await this.req_("/group/add-users",{uid:e,users:t??[]})}async removeUsersFromGroup(e,t){return await this.req_("/group/remove-users",{uid:e,users:t??[]})}async listGroups(){return await this.req_("/group/list")}}class Ht extends Error{constructor(e){super(e),this.name="RequestError"}}class Yt{constructor(e){this.authToken=e.authToken,this.APIOrigin=e.APIOrigin}setAuthToken(e){this.authToken=e}setAPIOrigin(e){this.APIOrigin=e}async req_(e,t,s){const n=await fetch(this.APIOrigin+t,{method:e,headers:{Authorization:`Bearer ${this.authToken}`,...s?{"Content-Type":"application/json"}:{}},...s?{body:JSON.stringify(s)}:{}});if(!n.ok){const e=await n.json(),t=new Ht(e.message);throw t.response=e,t}return await n.json()}async create(e,t){return"string"==typeof e&&(e={text:e}),await this.req_("POST","/threads/create",{...e,...t?{parent:t}:{}})}async edit(e,t={}){"string"==typeof t&&(t={text:t}),await this.req_("PUT","/threads/edit/"+encodeURIComponent(e),{...t})}async delete(e){await this.req_("DELETE","/threads/"+encodeURIComponent(e))}async list(e,t,s){return await this.req_("POST","/threads/list/"+encodeURIComponent(e)+"/"+t,s??{})}async subscribe(e,t){puter.fs.socket.emit("thread.sub-request",{uid:e});const s=["post","edit","delete","child-edit","child-delete"];for(const n of s)puter.fs.socket.on(`thread.${n}`,s=>{s.subscription===e&&t(n,s)})}}class Qt extends(globalThis.HTMLElement||Object){isUsingFileProtocol=()=>"file:"===window.location.protocol;constructor(e,t){let s;super(),this.reject=t,this.resolve=e,this.popupLaunched=!1,this.hasUserActivation=()=>{if(navigator.userActivation)return navigator.userActivation.hasBeenActive&&navigator.userActivation.isActive;try{const e=window.open("","_blank","width=1,height=1,left=-1000,top=-1000");return!!e&&(e.close(),!0)}catch(e){return!1}},this.launchPopup=()=>{try{let s=600,n=400,r="Puter";var e=screen.width/2-s/2,t=screen.height/2-n/2;return window.open(puter.defaultGUIOrigin+"/?embedded_in_popup=true&request_auth=true"+(window.crossOriginIsolated?"&cross_origin_isolated=true":""),r,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+s+", height="+n+", top="+t+", left="+e)}catch(e){return console.error("Failed to open popup:",e),null}},this.attachShadow({mode:"open"}),s="\n <style>\n dialog{\n background: transparent; \n border: none; \n box-shadow: none; \n outline: none;\n }\n .puter-dialog-content {\n border: 1px solid #e8e8e8;\n border-radius: 8px;\n padding: 20px;\n background: white;\n box-shadow: 0 0 9px 1px rgb(0 0 0 / 21%);\n padding: 80px 20px;\n -webkit-font-smoothing: antialiased;\n color: #575762;\n position: relative;\n background-image: url('data:image/webp;base64,UklGRlAbAABXRUJQVlA4WAoAAAAwAAAA8AIArQEAQUxQSB0AAAABB1ChiAgAKNL//xTR/9T//ve///3vf//73/+ZAwBWUDggDBsAAHAjAZ0BKvECrgE+nUyfTKWkMKsjk3mqEBOJaW6WwjzR/6prSfc95r2ztLOrL7Qmk8WYj6B+qfKm8C//+ufPmvfz/L6dZ/lf/79Rn1D/u8lf1n/h51GW/9DvL9u3/+z8//rLz8rv/Ho91qL//9Tf3+Dt29xsjEB3trEAO1CpmGKEcxEE0NTCpyVf/lDAyEBRUXwgPowMARkOmIbfb4Qzf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BHjmHRoLIe/Woh58xTbLtb7IrXITJgvZmFXeSbhjd7ms2Kb0DyyDFPDz1pxEk2VO13dfjgNzw4rRZXDGNxKdW4V8x0ZqfMrs48cLI/j1eOqmLvo3k6gkaYRfrs1ngoVMqazzJrkJYFz8WmsD+K1eEp/LqNxUkodWrAq885E8VeIULxp0u3xb1m7uUnyrHzshPXSnGCDUaxFj6UxoYG6a3Ga7OYz0Sdnw+dQk230G0weEIt9GN3BpWOiGAJZ69w4jr2D+6RkhzNmnY9n1qV05DE1BflAzIDxsPW78jJAFiz5aARulRgVFwgBnMuPWxvLmIXBvAAHy65muvCAsGfVex4ZHKCCv6XnQ2OW9EURTQsdw7Gb8bz9teGINBk3/fz0oAJ5e9QAAAA==');\n background-repeat: no-repeat;\n background-position: center center;\n background-size: 100% 100%;\n background-color: #fff;\n }\n \n dialog * {\n max-width: 500px;\n font-family: \"Helvetica Neue\", HelveticaNeue, Helvetica, Arial, sans-serif;\n }\n \n dialog p.about{\n text-align: center;\n font-size: 17px;\n padding: 10px 30px;\n font-weight: 400;\n -webkit-font-smoothing: antialiased;\n color: #404048;\n box-sizing: border-box;\n }\n \n dialog .buttons{\n display: flex;\n justify-content: center;\n align-items: center;\n flex-wrap: wrap;\n margin-top: 20px;\n text-align: center;\n margin-bottom: 20px;\n }\n \n .launch-auth-popup-footnote{\n font-size: 11px;\n color: #666;\n margin-top: 10px;\n /* footer at the bottom */\n position: absolute;\n left: 0;\n right: 0;\n bottom: 10px;\n text-align: center;\n margin: 0 10px;\n }\n \n dialog .close-btn{\n position: absolute;\n right: 15px;\n top: 10px;\n font-size: 17px;\n color: #8a8a8a;\n cursor: pointer;\n }\n \n dialog .close-btn:hover{\n color: #000;\n }\n \n /* ------------------------------------\n Button\n ------------------------------------*/\n \n dialog .button {\n color: #666666;\n background-color: #eeeeee;\n border-color: #eeeeee;\n font-size: 14px;\n text-decoration: none;\n text-align: center;\n line-height: 40px;\n height: 35px;\n padding: 0 30px;\n margin: 0;\n display: inline-block;\n appearance: none;\n cursor: pointer;\n border: none;\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n border-color: #b9b9b9;\n border-style: solid;\n border-width: 1px;\n line-height: 35px;\n background: -webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#e1e1e1));\n background: linear-gradient(#f6f6f6, #e1e1e1);\n -webkit-box-shadow: inset 0px 1px 0px rgb(255 255 255 / 30%), 0 1px 2px rgb(0 0 0 / 15%);\n box-shadow: inset 0px 1px 0px rgb(255 255 255 / 30%), 0 1px 2px rgb(0 0 0 / 15%);\n border-radius: 4px;\n outline: none;\n -webkit-font-smoothing: antialiased;\n }\n \n dialog .button:focus-visible {\n border-color: rgb(118 118 118);\n }\n \n dialog .button:active, dialog .button.active, dialog .button.is-active, dialog .button.has-open-contextmenu {\n text-decoration: none;\n background-color: #eeeeee;\n border-color: #cfcfcf;\n color: #a9a9a9;\n -webkit-transition-duration: 0s;\n transition-duration: 0s;\n -webkit-box-shadow: inset 0 1px 3px rgb(0 0 0 / 20%);\n box-shadow: inset 0px 2px 3px rgb(0 0 0 / 36%), 0px 1px 0px white;\n }\n \n dialog .button.disabled, dialog .button.is-disabled, dialog .button:disabled {\n top: 0 !important;\n background: #EEE !important;\n border: 1px solid #DDD !important;\n text-shadow: 0 1px 1px white !important;\n color: #CCC !important;\n cursor: default !important;\n appearance: none !important;\n pointer-events: none;\n }\n \n dialog .button-action.disabled, dialog .button-action.is-disabled, dialog .button-action:disabled {\n background: #55a975 !important;\n border: 1px solid #60ab7d !important;\n text-shadow: none !important;\n color: #CCC !important;\n }\n \n dialog .button-primary.disabled, dialog .button-primary.is-disabled, dialog .button-primary:disabled {\n background: #8fc2e7 !important;\n border: 1px solid #98adbd !important;\n text-shadow: none !important;\n color: #f5f5f5 !important;\n }\n \n dialog .button-block {\n width: 100%;\n }\n \n dialog .button-primary {\n border-color: #088ef0;\n background: -webkit-gradient(linear, left top, left bottom, from(#34a5f8), to(#088ef0));\n background: linear-gradient(#34a5f8, #088ef0);\n color: white;\n }\n \n dialog .button-danger {\n border-color: #f00808;\n background: -webkit-gradient(linear, left top, left bottom, from(#f83434), to(#f00808));\n background: linear-gradient(#f83434, #f00808);\n color: white;\n }\n \n dialog .button-primary:active, dialog .button-primary.active, dialog .button-primary.is-active, dialog .button-primary-flat:active, dialog .button-primary-flat.active, dialog .button-primary-flat.is-active {\n background-color: #2798eb;\n border-color: #2798eb;\n color: #bedef5;\n }\n \n dialog .button-action {\n border-color: #08bf4e;\n background: -webkit-gradient(linear, left top, left bottom, from(#29d55d), to(#1ccd60));\n background: linear-gradient(#29d55d, #1ccd60);\n color: white;\n }\n \n dialog .button-action:active, dialog .button-action.active, dialog .button-action.is-active, dialog .button-action-flat:active, dialog .button-action-flat.active, dialog .button-action-flat.is-active {\n background-color: #27eb41;\n border-color: #27eb41;\n color: #bef5ca;\n }\n \n dialog .button-giant {\n font-size: 28px;\n height: 70px;\n line-height: 70px;\n padding: 0 70px;\n }\n \n dialog .button-jumbo {\n font-size: 24px;\n height: 60px;\n line-height: 60px;\n padding: 0 60px;\n }\n \n dialog .button-large {\n font-size: 20px;\n height: 50px;\n line-height: 50px;\n padding: 0 50px;\n }\n \n dialog .button-normal {\n font-size: 16px;\n height: 40px;\n line-height: 38px;\n padding: 0 40px;\n }\n \n dialog .button-small {\n height: 30px;\n line-height: 29px;\n padding: 0 30px;\n }\n \n dialog .button-tiny {\n font-size: 9.6px;\n height: 24px;\n line-height: 24px;\n padding: 0 24px;\n }\n \n #launch-auth-popup{\n margin-left: 10px; \n width: 200px; \n font-weight: 500; \n font-size: 15px;\n }\n dialog .button-auth{\n margin-bottom: 10px;\n }\n dialog a, dialog a:visited{\n color: rgb(0 69 238);\n text-decoration: none;\n }\n dialog a:hover{\n text-decoration: underline;\n }\n \n @media (max-width:480px) { \n .puter-dialog-content{\n padding: 50px 20px;\n }\n dialog .buttons{\n flex-direction: column-reverse;\n }\n dialog p.about{\n padding: 10px 0;\n }\n dialog .button-auth{\n width: 100% !important;\n margin:0 !important;\n margin-bottom: 10px !important;\n }\n }\n .error-container h1 {\n color: #e74c3c;\n font-size: 20px;\n text-align: center;\n }\n\n .puter-dialog-content a:focus{\n outline: none;\n }\n </style>","file:"===window.location.protocol?s+='<dialog>\n <div class="puter-dialog-content" style="padding: 20px 40px; background:white !important; font-size: 15px;">\n <span class="close-btn">&#x2715</span>\n <div class="error-container">\n <h1>Puter.js Error: Unsupported Protocol</h1>\n <p>It looks like you\'ve opened this file directly in your browser (using the <code style="font-family: monospace;">file:///</code> protocol) which is not supported by Puter.js for security reasons.</p>\n <p>To view this content properly, you need to serve it through a web server. Here are some options:</p>\n <ul>\n <li>Use a local development server (e.g., Python\'s built-in server or Node.js http-server)</li>\n <li>Upload the files to a web hosting service</li>\n <li>Use a local server application like XAMPP or MAMP</li>\n </ul>\n <p class="help-text">If you\'re not familiar with these options, consider reaching out to your development team or IT support for assistance.</p>\n </div>\n <p style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 10px; text-align: center; font-size:13px;">\n <a href="https://docs.puter.com" target="_blank">Docs</a><span style="margin:10px; color: #CCC;">|</span>\n <a href="https://github.com/heyPuter/puter/" target="_blank">Github</a><span style="margin:10px; color: #CCC;">|</span>\n <a href="https://discord.com/invite/PQcx7Teh8u" target="_blank">Discord</a>\n </p>\n </div>\n </dialog>':s+='<dialog>\n <div class="puter-dialog-content">\n <span class="close-btn">&#x2715</span>\n <a href="https://puter.com" target="_blank" style="border:none; outline:none; display: block; width: 70px; height: 70px; margin: 0 auto; border-radius: 4px;"><img style="display: block; width: 70px; height: 70px; margin: 0 auto; border-radius: 4px;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAKCJJREFUeJztnQl0U3X2x5VNFFGBAqVUFlkEZAcFFdlUkEHcYEYcBQSVRREEUUQZt1EUBGEQBxUYFkFZZF+KQBf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GkXJ7mcXnnza4I/+bKgNfsnFXMXfAVNl/bxkoSLlnrvCgGN5o8+K6pzCQHhpsBX0KS5rQu1+4DRG8aWWDdekBopSwyL3ylq2YmU/Y0MvoKmTouO1CsLy8o1znCqAmgSWCodicnKx57izpR6ToOvoHnQqbdk0TsqXnGl2+0JaPfCv8HvXW6PTmc5ebZkxouiO7qRgj9a4CtoTrSKoYY9Knv97dJtP2nO/a5Pz9JfSdcdO1W+fnPJ3+dJ+o4Qhz7+jNDw4CsgEBDBV0AgIIKvgEBABF8BgYAIvgICARF8BQQCIvgKCARE8BUQCIjgKyAQEMFXQCAggq+AQEAEXwGBgAi+AgIBEXwFBAIi+AoIBETwFRAIiOArIBAQwVdAICCCr4BAQARfAYGACL4CAgERfAUEAiL4CggERPAVEAiI4CsgEBDBV0AgIIKvgEBABF8BgYAIvgICARF8BQQCIvgKCARE8BUQCIjgKyAQEMFXQCAggq+AQEAEXwGBgAi+AgIBEXwFBAIi+AoIBETwFRAIiOArIBAQwVdAIODxf/VVGcawPhaZAAAAAElFTkSuQmCC"/></a>\n <p class="about">This website uses Puter to bring you safe, secure, and private AI and Cloud features.</p>\n <div class="buttons">\n <button class="button button-auth" id="launch-auth-popup-cancel">Cancel</button>\n <button class="button button-primary button-auth" id="launch-auth-popup" style="margin-left:10px;">Continue</button>\n </div>\n <p style="text-align: center; margin-top: -15px; font-size: 14px;">Powered by <a href="https://developer.puter.com/?utm_source=sdk-splash" target="_blank">Puter</a></p>\n <p class="launch-auth-popup-footnote">By clicking \'Continue\' you agree to Puter\'s <a href="https://puter.com/terms" target="_blank">Terms of Service</a> and <a href="https://puter.com/privacy" target="_blank">Privacy Policy</a>.</p>\n </div>\n </dialog>',this.shadowRoot.innerHTML=s,this.messageListener=async e=>{"puter.token"===e.data.msg&&(this.close(),puter.setAuthToken(e.data.token),puter.setAppID(e.data.app_uid),window.removeEventListener("message",this.messageListener),puter.puterAuthState.authGranted=!0,this.resolve(),puter.onAuth&&"function"==typeof puter.onAuth&&puter.getUser().then(e=>{puter.onAuth(e)}),puter.puterAuthState.isPromptOpen=!1,puter.puterAuthState.resolver&&(puter.puterAuthState.authGranted?puter.puterAuthState.resolver.resolve():puter.puterAuthState.resolver.reject(),puter.puterAuthState.resolver=null))}}cancelListener=()=>{this.close(),window.removeEventListener("message",this.messageListener),puter.puterAuthState.authGranted=!1,puter.puterAuthState.isPromptOpen=!1,this.reject(new Error("User cancelled the authentication")),puter.puterAuthState.resolver&&(puter.puterAuthState.resolver.reject(new Error("User cancelled the authentication")),puter.puterAuthState.resolver=null)};connectedCallback(){this.shadowRoot.querySelector("#launch-auth-popup")?.addEventListener("click",()=>{var e=screen.width/2-300,t=screen.height/2-200;window.open(puter.defaultGUIOrigin+"/?embedded_in_popup=true&request_auth=true"+(window.crossOriginIsolated?"&cross_origin_isolated=true":""),"Puter","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=600, height=400, top="+t+", left="+e)}),window.addEventListener("message",this.messageListener),this.shadowRoot.querySelector("#launch-auth-popup-cancel")?.addEventListener("click",this.cancelListener),this.shadowRoot.querySelector(".close-btn")?.addEventListener("click",this.cancelListener)}open(){if(this.hasUserActivation()){let s=600,n=400,r="Puter";var e=screen.width/2-s/2,t=screen.height/2-n/2;window.open(puter.defaultGUIOrigin+"/?embedded_in_popup=true&request_auth=true"+(window.crossOriginIsolated?"&cross_origin_isolated=true":""),r,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+s+", height="+n+", top="+t+", left="+e)}else this.shadowRoot.querySelector("dialog").showModal()}close(){this.shadowRoot.querySelector("dialog").close()}}Qt.__proto__===globalThis.HTMLElement&&customElements.define("puter-dialog",Qt);const Zt=Qt,Jt=Symbol("FILE_SAVE_CANCELLED"),$t=Symbol("FILE_OPEN_CANCELLED");class es extends Dt{#w="*";#v;#_;static from(e,t){const s=new es(t,{target:e.appInstanceID,usesSDK:e.usesSDK});return s.response=e.response,s}constructor(e,{target:t,usesSDK:s}){super(["message","close"]),this.messageTarget=e.messageTarget,this.appInstanceID=e.appInstanceID,this.targetAppInstanceID=t,this.#v=!0,this.#_=s,this.log=e.puter.logger.fields({category:"ipc"}),this.log.fields({cons_source:e.appInstanceID,source:e.puter.appInstanceID,target:t}).info(`AppConnection created to ${t}`,this),globalThis.document&&window.addEventListener("message",e=>{if("messageToApp"===e.data.msg){if(e.data.appInstanceID!==this.targetAppInstanceID)return;return e.data.targetAppInstanceID!==this.appInstanceID?void console.error(`AppConnection received message intended for wrong app! appInstanceID=${this.appInstanceID}, target=${e.data.targetAppInstanceID}`):void this.emit("message",e.data.contents)}if("appClosed"===e.data.msg){if(e.data.appInstanceID!==this.targetAppInstanceID)return;this.#v=!1,this.emit("close",{appInstanceID:this.targetAppInstanceID,statusCode:e.data.statusCode})}})}get usesSDK(){return this.#_}postMessage(e){this.#v?this.#_?this.messageTarget.postMessage({msg:"messageToApp",appInstanceID:this.appInstanceID,targetAppInstanceID:this.targetAppInstanceID,targetAppOrigin:"*",contents:e},this.#w):console.warn("Trying to post message to a non-SDK app"):console.warn("Trying to post message on a closed AppConnection")}close(){this.#v?this.messageTarget.postMessage({msg:"closeApp",appInstanceID:this.appInstanceID,targetAppInstanceID:this.targetAppInstanceID},this.#w):console.warn("Trying to close an app on a closed AppConnection")}}const ts=class extends Dt{#m=1;itemWatchCallbackFunctions=[];appInstanceID;parentInstanceID;#k=null;#A=[];#T;#E;#x;#y;#S=new Map;#I=!1;#P=null;#O=function(e,t,s={}){const n=this.#m++;this.messageTarget?.postMessage({msg:e,env:this.env,appInstanceID:this.appInstanceID,uuid:n,...s},"*"),this.#A[n]=t};#R=function(e,t){const s=this.util.rpc.getDehydrator({target:this.messageTarget});this.messageTarget?.postMessage({msg:e,env:this.env,appInstanceID:this.appInstanceID,value:s.dehydrate(t)},"*")};#C=async function({callback:e,method:t,parameters:s}){let n,r;await new Promise(e=>{n=new Promise(t=>{r=t,e()})});const i=this.util.rpc.registerCallback(r);this.messageTarget?.postMessage({$:"puter-ipc",v:2,appInstanceID:this.appInstanceID,env:this.env,msg:t,parameters:s,uuid:i},"*");const o=await n;return e&&e(o),o};constructor(e,{appInstanceID:t,parentInstanceID:s}){const n=["localeChanged","themeChanged","connection"];if(super(n),this.#y=n,this.context=e,this.appInstanceID=t,this.parentInstanceID=s,this.appID=e.appID,this.env=e.env,this.util=e.util,"app"===this.env)this.messageTarget=window.parent;else if("gui"===this.env)return;this.context=this.context.sub({appInstanceID:this.appInstanceID,messageTarget:this.messageTarget}),this.parentInstanceID&&(this.#k=new es(this.context,{target:this.parentInstanceID,usesSDK:!0})),this.messageTarget?.postMessage({msg:"READY",appInstanceID:this.appInstanceID},"*"),globalThis.document&&window.addEventListener("focus",e=>{this.messageTarget?.postMessage({msg:"windowFocused",appInstanceID:this.appInstanceID},"*")});let r=null;globalThis.document&&window.addEventListener("message",async e=>{if(e.data.error)throw e.data.error;if(e.data.msg&&"focus"===e.data.msg)window.focus();else if(e.data.msg&&"click"===e.data.msg){const t=document.elementFromPoint(e.data.x,e.data.y);null!==t&&t.click()}else if(e.data.msg&&"drag"===e.data.msg){const t=document.elementFromPoint(e.data.x,e.data.y);if(t!==r){if(r){const t=new Event("dragleave",{bubbles:!0,cancelable:!0,clientX:e.data.x,clientY:e.data.y});r.dispatchEvent(t)}if(t){const s=new Event("dragenter",{bubbles:!0,cancelable:!0,clientX:e.data.x,clientY:e.data.y});t.dispatchEvent(s)}r=t}}else if(e.data.msg&&"drop"===e.data.msg){if(r){const t=new CustomEvent("drop",{bubbles:!0,cancelable:!0,detail:{clientX:e.data.x,clientY:e.data.y,items:e.data.items}});r.dispatchEvent(t),r=null}}else if("windowWillClose"===e.data.msg)void 0===this.#T?this.messageTarget?.postMessage({msg:!0,appInstanceID:this.appInstanceID,original_msg_id:e.data.msg_id},"*"):(this.messageTarget?.postMessage({msg:!1,appInstanceID:this.appInstanceID,original_msg_id:e.data.msg_id},"*"),this.#T());else if("itemsOpened"===e.data.msg)if(void 0===this.#E)this.messageTarget?.postMessage({msg:!0,appInstanceID:this.appInstanceID,original_msg_id:e.data.msg_id},"*");else{this.messageTarget?.postMessage({msg:!1,appInstanceID:this.appInstanceID,original_msg_id:e.data.msg_id},"*");let t=[];if(e.data.items.length>0)for(let s=0;s<e.data.items.length;s++)t.push(new Et(e.data.items[s]));this.#E(t)}else if("getAppDataSucceeded"===e.data.msg){let t=new Et(e.data.item);e.data.original_msg_id&&this.#A[e.data.original_msg_id]&&this.#A[e.data.original_msg_id](t)}else if("readAppDataFileSucceeded"===e.data.msg){let t=new Et(e.data.item);e.data.original_msg_id&&this.#A[e.data.original_msg_id]&&this.#A[e.data.original_msg_id](t)}else if("readAppDataFileFailed"===e.data.msg)e.data.original_msg_id&&this.#A[e.data.original_msg_id]&&this.#A[e.data.original_msg_id](null);else if(void 0!==e.data.original_msg_id&&this.#A[e.data.original_msg_id]){if("fileOpenPicked"===e.data.msg){if(1===e.data.items.length)this.#A[e.data.original_msg_id](new Et(e.data.items[0]));else if(e.data.items.length>1){let t=[];for(let s=0;s<e.data.items.length;s++)t.push(new Et(e.data.items[s]));this.#A[e.data.original_msg_id](t)}}else if("directoryPicked"===e.data.msg){if(1===e.data.items.length)this.#A[e.data.original_msg_id](new Et({uid:e.data.items[0].uid,name:e.data.items[0].fsentry_name,path:e.data.items[0].path,readURL:e.data.items[0].read_url,writeURL:e.data.items[0].write_url,metadataURL:e.data.items[0].metadata_url,isDirectory:!0,size:e.data.items[0].fsentry_size,accessed:e.data.items[0].fsentry_accessed,modified:e.data.items[0].fsentry_modified,created:e.data.items[0].fsentry_created}));else if(e.data.items.length>1){let t=[];for(let s=0;s<e.data.items.length;s++)t.push(new Et(e.data.items[s]));this.#A[e.data.original_msg_id](t)}}else"colorPicked"===e.data.msg?this.#A[e.data.original_msg_id](e.data.color):"fontPicked"===e.data.msg?this.#A[e.data.original_msg_id](e.data.font):"alertResponded"===e.data.msg||"promptResponded"===e.data.msg?this.#A[e.data.original_msg_id](e.data.response):"languageReceived"===e.data.msg?this.#A[e.data.original_msg_id](e.data.language):"fileSaved"===e.data.msg?this.#A[e.data.original_msg_id](new Et(e.data.saved_file)):"fileSaveCancelled"===e.data.msg?this.#A[e.data.original_msg_id](Jt):"fileOpenCancelled"===e.data.msg?this.#A[e.data.original_msg_id]($t):this.#A[e.data.original_msg_id](e.data);delete this.#A[e.data.original_msg_id]}else if("itemChanged"===e.data.msg&&e.data.data&&e.data.data.uid)this.itemWatchCallbackFunctions[e.data.data.uid]&&"function"==typeof this.itemWatchCallbackFunctions[e.data.data.uid]&&this.itemWatchCallbackFunctions[e.data.data.uid](e.data.data);else if("broadcast"===e.data.msg){const{name:t,data:s}=e.data;if(!this.#y.includes(t))return;this.emit(t,s),this.#S.set(t,s)}else if("connection"===e.data.msg){e.data.usesSDK=!0;const t=es.from(e.data,this.context),s=t=>{this.messageTarget?.postMessage({$:"connection-resp",connection:e.data.appInstanceID,accept:!0,value:t},"*")},n=t=>{this.messageTarget?.postMessage({$:"connection-resp",connection:e.data.appInstanceID,accept:!1,value:t},"*")};this.emit("connection",{conn:t,accept:s,reject:n})}}),globalThis.document?.addEventListener("mousemove",async e=>{this.mouseX=e.clientX,this.mouseY=e.clientY,this.messageTarget?.postMessage({msg:"mouseMoved",appInstanceID:this.appInstanceID,x:this.mouseX,y:this.mouseY},"*")}),globalThis.document?.addEventListener("click",async e=>{this.mouseX=e.clientX,this.mouseY=e.clientY,this.messageTarget?.postMessage({msg:"mouseClicked",appInstanceID:this.appInstanceID,x:this.mouseX,y:this.mouseY},"*")})}onWindowClose=function(e){this.#T=e};onItemsOpened=function(e){if(!this.#E){let t=new URLSearchParams(globalThis.location.search);if(t.has("puter.item.name")&&t.has("puter.item.uid")&&t.has("puter.item.read_url")){let s=t.get("puter.item.path");s.startsWith("~/")||s.startsWith("/")||(s="~/"+s),e([new Et({name:t.get("puter.item.name"),path:s,uid:t.get("puter.item.uid"),readURL:t.get("puter.item.read_url"),writeURL:t.get("puter.item.write_url"),metadataURL:t.get("puter.item.metadata_url"),size:t.get("puter.item.size"),accessed:t.get("puter.item.accessed"),modified:t.get("puter.item.modified"),created:t.get("puter.item.created")})])}}this.#E=e};wasLaunchedWithItems=function(){const e=new URLSearchParams(globalThis.location.search);return e.has("puter.item.name")&&e.has("puter.item.uid")&&e.has("puter.item.read_url")};onLaunchedWithItems=function(e){if(!this.#x){let t=new URLSearchParams(globalThis.location.search);if(t.has("puter.item.name")&&t.has("puter.item.uid")&&t.has("puter.item.read_url")){let s=t.get("puter.item.path");s.startsWith("~/")||s.startsWith("/")||(s="~/"+s),e([new Et({name:t.get("puter.item.name"),path:s,uid:t.get("puter.item.uid"),readURL:t.get("puter.item.read_url"),writeURL:t.get("puter.item.write_url"),metadataURL:t.get("puter.item.metadata_url"),size:t.get("puter.item.size"),accessed:t.get("puter.item.accessed"),modified:t.get("puter.item.modified"),created:t.get("puter.item.created")})])}}this.#x=e};requestEmailConfirmation=function(){return new Promise((e,t)=>{this.#O("requestEmailConfirmation",e,{})})};alert=function(e,t,s,n){return new Promise(n=>{this.#O("ALERT",n,{message:e,buttons:t,options:s})})};socialShare=function(e,t,s,n){return new Promise(n=>{this.#O("socialShare",n,{url:e,message:t,options:s})})};prompt=function(e,t,s,n){return new Promise(n=>{this.#O("PROMPT",n,{message:e,placeholder:t,options:s})})};showDirectoryPicker=function(e,t){return new Promise((t,s)=>{if(!globalThis.open)return s("This API is not compatible in Web Workers.");const n=this.#m++;if("app"===this.env)this.messageTarget?.postMessage({msg:"showDirectoryPicker",appInstanceID:this.appInstanceID,uuid:n,options:e,env:this.env},"*");else{let t=700,s=400,o="Puter: Open Directory";var r=screen.width/2-t/2,i=screen.height/2-s/2;window.open(`${puter.defaultGUIOrigin}/action/show-directory-picker?embedded_in_popup=true&msg_id=${n}&appInstanceID=${this.appInstanceID}&env=${this.env}&options=${JSON.stringify(e)}`,o,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+t+", height="+s+", top="+i+", left="+r)}this.#A[n]=t})};showOpenFilePicker=function(t,s){const n=new e.libs.promise.TeePromise,r=new Promise((e,s)=>{if(!globalThis.open)return s("This API is not compatible in Web Workers.");const r=this.#m++;if("app"===this.env)this.messageTarget?.postMessage({msg:"showOpenFilePicker",appInstanceID:this.appInstanceID,uuid:r,options:t??{},env:this.env},"*");else{let e=700,s=400,n="Puter: Open File";var i=screen.width/2-e/2,o=screen.height/2-s/2;window.open(`${puter.defaultGUIOrigin}/action/show-open-file-picker?embedded_in_popup=true&msg_id=${r}&appInstanceID=${this.appInstanceID}&env=${this.env}&options=${JSON.stringify(t??{})}`,n,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+e+", height="+s+", top="+o+", left="+i)}this.#A[r]=t=>{t!==$t?(n.resolve(t),e(t)):n.resolve(void 0)}});return r.undefinedOnCancel=n,r};showFontPicker=function(e){return new Promise(t=>{this.#O("showFontPicker",t,{options:e??{}})})};showColorPicker=function(e){return new Promise(t=>{this.#O("showColorPicker",t,{options:e??{}})})};showSaveFilePicker=function(t,s,n){const r=new e.libs.promise.TeePromise,i=new Promise((e,i)=>{if(!globalThis.open)return i("This API is not compatible in Web Workers.");const o=this.#m++;n||"[object URL]"!==Object.prototype.toString.call(t)||(n="url");const a="url"===n?t.toString():void 0,c=["move","copy"].includes(n)?t:void 0;if("app"===this.env)this.messageTarget?.postMessage({msg:"showSaveFilePicker",appInstanceID:this.appInstanceID,content:a?void 0:t,save_type:n,url:a,source_path:c,suggestedName:s??"",env:this.env,uuid:o},"*");else{window.addEventListener("message",async e=>{"sendMeFileData"===e.data?.msg&&(e.source.postMessage({msg:"showSaveFilePickerPopup",content:a?void 0:t,url:a?a.toString():void 0,suggestedName:s??"",env:this.env,uuid:o},"*"),window.removeEventListener("message",this))});let e=new Blob([t],{type:"application/octet-stream"}),n=URL.createObjectURL(e),r=700,i=400,c="Puter: Save File";var h=screen.width/2-r/2,l=screen.height/2-i/2;window.open(`${puter.defaultGUIOrigin}/action/show-save-file-picker?embedded_in_popup=true&msg_id=${o}&appInstanceID=${this.appInstanceID}&env=${this.env}&blobUrl=${encodeURIComponent(n)}`,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+r+", height="+i+", top="+l+", left="+h)}this.#A[o]=t=>{t!==Jt?(r.resolve(t),e(t)):r.resolve(void 0)}});return i.undefinedOnCancel=r,i};setWindowTitle=function(e,t,s){return"function"==typeof t?t=void 0:"object"==typeof t&&null!==t&&(t=t.id),new Promise(s=>{this.#O("setWindowTitle",s,{new_title:e,window_id:t})})};setWindowWidth=function(e,t,s){return"function"==typeof t?t=void 0:"object"==typeof t&&null!==t&&(t=t.id),new Promise(s=>{this.#O("setWindowWidth",s,{width:e,window_id:t})})};setWindowHeight=function(e,t,s){return"function"==typeof t?t=void 0:"object"==typeof t&&null!==t&&(t=t.id),new Promise(s=>{this.#O("setWindowHeight",s,{height:e,window_id:t})})};setWindowSize=function(e,t,s,n){return"function"==typeof s?s=void 0:"object"==typeof s&&null!==s&&(s=s.id),new Promise(n=>{this.#O("setWindowSize",n,{width:e,height:t,window_id:s})})};setWindowPosition=function(e,t,s,n){return"function"==typeof s?s=void 0:"object"==typeof s&&null!==s&&(s=s.id),new Promise(n=>{this.#O("setWindowPosition",n,{x:e,y:t,window_id:s})})};setWindowY=function(e,t,s){return"function"==typeof t?t=void 0:"object"==typeof t&&null!==t&&(t=t.id),new Promise(s=>{this.#O("setWindowY",s,{y:e,window_id:t})})};setWindowX=function(e,t,s){return"function"==typeof t?t=void 0:"object"==typeof t&&null!==t&&(t=t.id),new Promise(s=>{this.#O("setWindowX",s,{x:e,window_id:t})})};setMenubar=function(e){this.#R("setMenubar",e)};requestPermission=function(e){return new Promise(t=>{if("app"===this.env)return new Promise(t=>{this.#O("requestPermission",t,{options:e})});t(!1)})};disableMenuItem=function(e){this.#R("disableMenuItem",{id:e})};enableMenuItem=function(e){this.#R("enableMenuItem",{id:e})};setMenuItemIcon=function(e,t){this.#R("setMenuItemIcon",{id:e,icon:t})};setMenuItemIconActive=function(e,t){this.#R("setMenuItemIconActive",{id:e,icon:t})};setMenuItemChecked=function(e,t){this.#R("setMenuItemChecked",{id:e,checked:t})};contextMenu=function(e){this.#R("contextMenu",e)};getEntriesFromDataTransferItems=async function(e,t={raw:!1}){const s=e=>{if(this.getEntriesFromDataTransferItems.didShowInfo)return;if("EncodingError"!==e.name)return;this.getEntriesFromDataTransferItems.didShowInfo=!0;const t=`${e.name} occurred within datatransfer-files-promise module\nError message: "${e.message}"\nTry serving html over http if currently you are running it from the filesystem.`;console.warn(t)},n=(e,t)=>new Promise((n,i)=>{e.readEntries(async e=>{let s=[];for(let n of e){const e=await r(n,t);s=s.concat(e)}n(s)},e=>{s(e),i(e)})}),r=async(e,r="")=>{if(null!==e){if(e.isFile){const n=await((e,n="")=>new Promise((r,i)=>{e.file(e=>{t.raw||(e.filepath=n+e.name),r(e)},e=>{s(e),i(e)})}))(e,r);return[n]}if(e.isDirectory){const t=await(async(e,t)=>{const s=e.createReader(),r=t+e.name+"/";let i,o=[];do{i=await n(s,r),o=o.concat(i)}while(i.length>0);return o})(e,r);return t.push(e),t}}};let i=[],o=[];for(let t=0,s=e.length;t<s;t++)o.push(e[t].webkitGetAsEntry());for(let e of o){const t=await r(e);i=i.concat(t)}return i};authenticateWithPuter=function(){if("web"===this.env)return this.authToken?new Promise(e=>{e()}):puter.puterAuthState.isPromptOpen?new Promise((e,t)=>{puter.puterAuthState.resolver={resolve:e,reject:t}}):(puter.puterAuthState.isPromptOpen=!0,puter.puterAuthState.authGranted=null,new Promise((e,t)=>{if(puter.authToken)e();else{const s=new Zt(e,t);document.body.appendChild(s),s.open()}}))};launchApp=async function(e,t,s){let n,r,i,o=e;if("object"==typeof o&&null!==o){const e=o;o=e.name||e.app_name,r=e.file_paths,t=t||e.args,s=s||e.callback,n=e.pseudonym,i=e.items}if(i){Array.isArray(i)||(i=[]);for(let e=0;e<i.length;e++)i[e]instanceof Et&&(i[e]=i[e]._internalProperties.file_signature)}o&&o.includes("#(as)")&&([o,n]=o.split("#(as)")),o||(o=puter.appName);const a=await this.#C({method:"launchApp",callback:s,parameters:{app_name:o,file_paths:r,items:i,pseudonym:n,args:t}});return es.from(a,this.context)};connectToInstance=async function(e){const t=await this.#C({method:"connectToInstance",parameters:{app_name:e}});return es.from(t,this.context)};parentApp(){return this.#k}createWindow=function(e,t){return new Promise(t=>{this.#O("createWindow",e=>{t(e.window)},{options:e??{}})})};menubar=function(){document.querySelectorAll("style.puter-stylesheet").forEach(function(e){e.remove()});const e=document.createElement("style");e.classList.add("puter-stylesheet"),e.innerHTML="\n .--puter-menubar {\n border-bottom: 1px solid #e9e9e9;\n background-color: #fbf9f9;\n padding-top: 3px;\n padding-bottom: 2px;\n display: inline-block;\n position: fixed;\n top: 0;\n width: 100%;\n margin: 0;\n padding: 0;\n height: 31px;\n font-family: Arial, Helvetica, sans-serif;\n font-size: 13px;\n z-index: 9999;\n }\n \n .--puter-menubar, .--puter-menubar * {\n user-select: none;\n -webkit-user-select: none;\n cursor: default;\n }\n \n .--puter-menubar .dropdown-item-divider>hr {\n margin-top: 5px;\n margin-bottom: 5px;\n border-bottom: none;\n border-top: 1px solid #00000033;\n }\n \n .--puter-menubar>li {\n display: inline-block;\n padding: 10px 5px;\n }\n \n .--puter-menubar>li>ul {\n display: none;\n z-index: 999999999999;\n list-style: none;\n background-color: rgb(233, 233, 233);\n width: 200px;\n border: 1px solid #e4ebf3de;\n box-shadow: 0px 0px 5px #00000066;\n padding-left: 6px;\n padding-right: 6px;\n padding-top: 4px;\n padding-bottom: 4px;\n color: #333;\n border-radius: 4px;\n padding: 2px;\n min-width: 200px;\n margin-top: 5px;\n position: absolute;\n }\n \n .--puter-menubar .menubar-item {\n display: block;\n line-height: 24px;\n margin-top: -7px;\n text-align: center;\n border-radius: 3px;\n padding: 0 5px;\n }\n \n .--puter-menubar .menubar-item-open {\n background-color: rgb(216, 216, 216);\n }\n \n .--puter-menubar .dropdown-item {\n padding: 5px;\n padding: 5px 30px;\n list-style-type: none;\n user-select: none;\n font-size: 13px;\n }\n \n .--puter-menubar .dropdown-item-icon, .--puter-menubar .dropdown-item-icon-active {\n pointer-events: none;\n width: 18px;\n height: 18px;\n margin-left: -23px;\n margin-bottom: -4px;\n margin-right: 5px;\n }\n .--puter-menubar .dropdown-item-disabled .dropdown-item-icon{\n display: inline-block !important;\n }\n .--puter-menubar .dropdown-item-disabled .dropdown-item-icon-active{\n display: none !important;\n }\n .--puter-menubar .dropdown-item-icon-active {\n display:none;\n }\n .--puter-menubar .dropdown-item:hover .dropdown-item-icon{\n display: none;\n }\n .--puter-menubar .dropdown-item:hover .dropdown-item-icon-active{\n display: inline-block;\n }\n .--puter-menubar .dropdown-item-hide-icon .dropdown-item-icon, .--puter-menubar .dropdown-item-hide-icon .dropdown-item-icon-active{\n display: none !important;\n }\n .--puter-menubar .dropdown-item a {\n color: #333;\n text-decoration: none;\n }\n \n .--puter-menubar .dropdown-item:hover, .--puter-menubar .dropdown-item:hover a {\n background-color: rgb(59 134 226);\n color: white;\n border-radius: 4px;\n }\n \n .--puter-menubar .dropdown-item-disabled, .--puter-menubar .dropdown-item-disabled:hover {\n opacity: 0.5;\n background-color: transparent;\n color: initial;\n cursor: initial;\n pointer-events: none;\n }\n \n .--puter-menubar .menubar * {\n user-select: none;\n } \n ",(document.head||document.getElementsByTagName("head")[0]).appendChild(e),document.addEventListener("click",function(e){if(e.target.classList.contains("dropdown-item-disabled"))return!1;e.target.classList.contains("menubar-item")||(document.querySelectorAll(".menubar-item.menubar-item-open").forEach(function(e){e.classList.remove("menubar-item-open")}),document.querySelectorAll(".dropdown").forEach(e=>e.style.display="none"))}),window.addEventListener("blur",function(e){document.querySelectorAll(".dropdown").forEach(function(e){e.style.display="none"}),document.querySelectorAll(".menubar-item.menubar-item-open").forEach(e=>e.classList.remove("menubar-item-open"))}),document.querySelectorAll(".menubar-item").forEach(e=>e.addEventListener("mousedown",function(e){document.querySelectorAll(".dropdown").forEach(function(e){e.style.display="none"}),document.querySelectorAll(".menubar-item.menubar-item-open").forEach(function(t){t!=e.target&&t.classList.remove("menubar-item-open")}),this.classList.contains("menubar-item-open")?document.querySelectorAll(".menubar-item.menubar-item-open").forEach(function(e){e.classList.remove("menubar-item-open")}):e.target.classList.contains("dropdown-item")||(this.classList.add("menubar-item-open"),function(e){const t=[];if(!e.parentNode)return t;let s=e.parentNode.firstChild;for(;s;)1===s.nodeType&&s!==e&&t.push(s),s=s.nextSibling;return t}(this).forEach(function(e){e.style.display="block"}))})),document.querySelectorAll(".--puter-menubar .menubar-item").forEach(e=>e.addEventListener("mouseover",function(e){const t=document.querySelectorAll(".menubar-item.menubar-item-open");t.length>0&&t[0]!==e.target&&e.target.dispatchEvent(new Event("mousedown"))}))};on(e,t){super.on(e,t),this.#y.includes(e)&&this.#S.has(e)&&t(this.#S.get(e))}#L=null;#D=null;showSpinner(e){if(this.#I)return;if(!document.getElementById("puter-spinner-styles")){const e=document.createElement("style");e.id="puter-spinner-styles",e.textContent="\n .puter-loading-spinner {\n width: 50px;\n height: 50px;\n border: 5px solid #f3f3f3;\n border-top: 5px solid #3498db;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-bottom: 10px;\n }\n \n .puter-loading-text {\n font-family: Arial, sans-serif;\n font-size: 16px;\n margin-top: 10px;\n text-align: center;\n width: 100%;\n }\n \n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n \n .puter-loading-container {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n min-height: 120px; \n background: #ffffff; \n border-radius: 10px;\n padding: 20px;\n min-width: 120px;\n }\n ",document.head.appendChild(e)}const t=document.createElement("div");t.classList.add("puter-loading-overlay"),Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(255, 255, 255, 0.8)",zIndex:"2147483647",display:"flex",justifyContent:"center",alignItems:"center",pointerEvents:"all"});const s=document.createElement("div");s.classList.add("puter-loading-container"),s.innerHTML=`\n <div class="puter-loading-spinner"></div>\n <div class="puter-loading-text">${e??"Working..."}</div>\n `,t.appendChild(s),document.body.appendChild(t),this.#I=!0,this.#L=Date.now(),this.#P=setTimeout(()=>{this.#P=null},1e3)}hideSpinner(){if(!this.#I)return;this.#P&&(clearTimeout(this.#P),this.#P=null);const e=Date.now()-this.#L,t=Math.max(0,1200-e);t>0?(this.#D&&clearTimeout(this.#D),this.#D=setTimeout(()=>{this.#M()},t)):this.#M()}#M(){const e=document.querySelector(".puter-loading-overlay");e&&e.parentNode?.removeChild(e),this.#I=!1,this.#L=null,this.#D=null}isWorkingActive(){return this.#I}getLanguage(){return"gui"===this.env?window.locale:new Promise(e=>{this.#O("getLanguage",e,{})})}},ss="9a9c83a4-7897-43a0-93b9-53217b84fde6";class ns{#N=1;constructor(){this.callbacks=new Map}register_callback(e){const t=this.#N++;return this.callbacks.set(t,e),t}attach_to_source(e){e.addEventListener("message",e=>{const{data:t}=e;if(t&&"object"==typeof t&&t.$SCOPE===ss){const{id:e,args:s}=t,n=this.callbacks.get(e);n&&n(...s)}})}}class rs{constructor({callbackManager:e}){this.callbackManager=e}dehydrate(e){return this.dehydrate_value_(e)}dehydrate_value_(e){if("function"==typeof e){const t=this.callbackManager.register_callback(e);return{$SCOPE:ss,id:t}}if(Array.isArray(e))return e.map(this.dehydrate_value_.bind(this));if("object"==typeof e&&null!==e){const t={};for(const s in e)t[s]=this.dehydrate_value_(e[s]);return t}return e}}class is{constructor({target:e}){this.target=e}hydrate(e){return this.hydrate_value_(e)}hydrate_value_(e){if(e&&"object"==typeof e&&e.$SCOPE===ss){const{id:t}=e;return(...e)=>{this.target.postMessage({$SCOPE:ss,id:t,args:e},"*")}}if(Array.isArray(e))return e.map(this.hydrate_value_.bind(this));if("object"==typeof e&&null!==e){const t={};for(const s in e)t[s]=this.hydrate_value_(e[s]);return t}return e}}class os{constructor(){this.rpc=new as}}class as{constructor(){this.callbackManager=new ns,this.callbackManager.attach_to_source(globalThis)}getDehydrator(){return new rs({callbackManager:this.callbackManager})}getHydrator({target:e}){return new is({target:e})}registerCallback(e){return this.callbackManager.register_callback(e)}send(e,t,...s){e.postMessage({$SCOPE:ss,id:t,args:s},"*")}}class cs{constructor(e){this.authToken=e}async create(e,t,s){if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){throw"Authentication failed."}let n;"string"==typeof s&&(n=(await puter.apps.list()).find(e=>e.name===s).uid),e=e.toLocaleLowerCase();let r=await puter.kv.get("user-workers");r||(r={}),t=pt(t);const i=await M(["authorization","filePath","workerName","appId"],"workers","worker-service","create")(puter.authToken,t,e,n);if(!i.success)throw new Error(i?.errors||"Driver failed to execute, do you have the necessary permissions?");return r[e]={filePath:t,url:i.url,deployTime:Date.now(),createTime:Date.now()},await puter.kv.set("user-workers",r),i}async exec(...e){if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){throw"Authentication failed."}const t=new Request(...e);return t.headers.get("puter-auth")||t.headers.set("puter-auth",puter.authToken),fetch(t)}async list(){if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){throw"Authentication failed."}return await M([],"workers","worker-service","getFilePaths")()}async get(e){if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){throw"Authentication failed."}return e=e.toLocaleLowerCase(),(await M(["workerName"],"workers","worker-service","getFilePaths")(e))[0]}async delete(e){if(!puter.authToken&&"web"===puter.env)try{await puter.ui.authenticateWithPuter()}catch(e){throw"Authentication failed."}e=e.toLocaleLowerCase();const t=await M(["authorization","workerName"],"workers","worker-service","destroy")(puter.authToken,e);if(t.result){let t=await puter.kv.get("user-workers");return t||(t={}),delete t[e],await puter.kv.set("user-workers",t),!0}throw t.result||new Error("Worker doesn't exist"),new Error(t?.errors||"Driver failed to execute, do you have the necessary permissions?")}}const{TTopics:hs}=e.traits;class ls extends e.concepts.Service{static TOPICS=["update"];static PROPERTIES={auth_token:{post_set(e){this.as(hs).pub("update")}},api_origin:{post_set(){this.as(hs).pub("update")}}};get_api_info(){const e=this,t={};return[["auth_token","auth_token"],["authToken","auth_token"],["APIOrigin","api_origin"],["api_origin","api_origin"]].forEach(([s,n])=>{Object.defineProperty(t,s,{get:()=>e[n],set:t=>e})}),t}}const us="TFilesystem";class ps extends e.AdvancedBase{static PROPERTIES={delegate:()=>{}};constructor({delegate:e}){super(),this.delegate=e}static IMPLEMENTS={[us]:{stat:async function(e){return this.delegate.stat(e)},readdir:async function(e){return this.delegate.readdir(e)}}}}class ds extends e.AdvancedBase{constructor({api_info:e}){super(),this.api_info=e}static IMPLEMENTS={[us]:{stat:async function(e){this.ensure_auth_();const t=new Ot.TeePromise,s=new O("/stat",this.api_info.APIOrigin,void 0,"post","text/plain;actually=json");C(s,void 0,void 0,t.resolve.bind(t),t.reject.bind(t));let n={};return void 0!==e.uid?n.uid=e.uid:void 0!==e.path&&(n.path=pt(e.path)),n.return_subdomains=e.returnSubdomains,n.return_permissions=e.returnPermissions,n.return_versions=e.returnVersions,n.return_size=e.returnSize,n.auth_token=this.api_info.authToken,s.send(JSON.stringify(n)),await t},readdir:async function(e){this.ensure_auth_();const t=new Ot.TeePromise,s=new O("/readdir",this.api_info.APIOrigin,void 0,"post","text/plain;actually=json");return C(s,void 0,void 0,t.resolve.bind(t),t.reject.bind(t)),s.send(JSON.stringify({path:pt(e.path),auth_token:this.api_info.authToken})),await t}}};ensure_auth_(){if(!this.api_info.authToken&&"web"===puter.env)try{this.ui.authenticateWithPuter()}catch(e){throw new Error("Authentication failed.")}}}class gs extends e.AdvancedBase{static PROPERTIES={assocs_path_:()=>({}),assocs_uuid_:()=>({}),entries:()=>({})};get_entry_ei(e){if(Array.isArray(e)){for(const t of e){const e=this.get_entry_ei(t);if(e)return e}return}console.log("GET ENTRY EI",e);const t=this.assocs_path_[e]||this.assocs_uuid_[e]||e;if(t)return this.entries[t]}add_entry({id:e}={}){const t=e??P(),s={id:t,stat_has:{},stat_exp:0,locks:{stat:new Ot.RWLock,members:new Ot.RWLock}};return this.entries[t]=s,s}assoc_path(e,t){console.log("ASSOC PATH",e,t),this.assocs_path_[e]=t}assoc_uuid(e,t){e!==t&&(this.assocs_uuid_[e]=t)}}class fs extends ps{constructor(e){super(e),this.cacheFS=new gs}static IMPLEMENTS={[us]:{stat:async function(e){let t=this.cacheFS.get_entry_ei(e.path??e.uid);const s=["subdomains","permissions","versions","size"];let n,r,i={};for(const t of s)e["return"+t.charAt(0).toUpperCase()+t.slice(1)]&&(i[t]=!0);if(t&&t.stat&&t.stat_exp>Date.now()){const e=await t.locks.stat.rlock();(e=>{for(const t of s)if(i[t]&&!e.stat_has[t])return!1;return!0})(t)&&(n=t.stat),e.unlock()}if(n)return console.log("CACHE HIT"),n;console.log("CACHE MISS"),t&&(r=await t.locks.stat.wlock()),console.log("DOING THE STAT",e);const o=await this.delegate.stat(e);let a=!!t;return t=this.cacheFS.get_entry_ei([o.uid,o.path]),t&&(a&&r.unlock(),r=await t.locks.stat.wlock()),t||(t=this.cacheFS.add_entry({id:o.uid}),this.cacheFS.assoc_path(o.path,t.id),this.cacheFS.assoc_uuid(o.uid,t.id),r=await t.locks.stat.wlock()),t.stat=o,t.stat_has={...i},t.stat_exp=Date.now()+5e3,r.unlock(),console.log("RETRUNING THE ENTRY",o),o},readdir:async function(e){let t=this.cacheFS.get_entry_ei([e.path,e.uid]);console.log("CENT",t,e);let s,n=null;if(t&&t.members&&t.members_exp>Date.now()){console.log("MEMBERS",t.members),n=[];const s=await t.locks.stat.rlock();for(const s of t.members){const t=this.cacheFS.get_entry_ei(s);if(!t||!t.stat||t.stat_exp<=Date.now()){console.log("NO MEMBER OR STAT",t),n=null;break}if(console.log("member",t),!e.no_assocs&&!t.stat_has.subdomains){n=null;break}if(!e.no_assocs&&!t.stat_has.apps){n=null;break}if(!e.no_thumbs&&!t.stat_has.thumbnail){n=null;break}console.log("PUSHING",t.stat),n.push(t.stat)}s.unlock()}if(console.log("STATS????",n),n)return n;t&&(s=await t.locks.members.wlock());const r=await this.delegate.readdir(e);t||(t=this.cacheFS.add_entry(e.uid?{id:e.uid}:{}),e.path&&this.cacheFS.assoc_path(e.path,t.id),s=await t.locks.members.wlock());let i=[];for(const t of r){let s=this.cacheFS.get_entry_ei([t.path,t.uid]);s||(s=this.cacheFS.add_entry({id:t.uid}),this.cacheFS.assoc_path(t.path,t.uid)),i.push(s.id),s.stat=t,s.stat_has={subdomains:!e.no_assocs,apps:!e.no_assocs,thumbnail:!e.no_thumbs},s.stat_exp=Date.now()+3e3}t.members=[];for(const e of i)t.members.push(e);return t.members_exp=Date.now()+5e3,s.unlock(),console.log("CACHE ENTRY?",t),r}}}}const ms={id:"f485f1ba-de07-422c-8c4b-c2da057d4a44",uid:"f485f1ba-de07-422c-8c4b-c2da057d4a44",is_dir:!0,immutable:!0,name:"Test"};class ys extends e.AdvancedBase{constructor({rpc:e,messageTarget:t}){super(),this.rpc=e,this.messageTarget=t}static IMPLEMENTS={[us]:{stat:async function(e){return ms},readdir:async function(t){const s=new e.libs.promise.TeePromise,n=this.rpc.registerCallback(e=>{s.resolve(e)});return this.messageTarget.postMessage({$:"puter-fs",$callback:n,op:"readdir",args:t},"*"),await s}}}}class bs extends e.concepts.Service{static PROPERTIES={};static DEPENDS=["api-access"];static HOOKS=[{service:"api-access",event:"update",description:"\n re-initialize the socket connection whenever the\n authentication token or API origin is changed.\n ",async do(){this.initializeSocket()}}];_init(){this._.context.env,this.init_top_fs_(),this.initializeSocket()}init_app_fs_(){this.fs_nocache_=new ys({messageTarget:globalThis.parent,rpc:this._.context.util.rpc}).as(us),this.filesystem=this.fs_nocache_}init_top_fs_(){const e=this._.context.services.get("api-access").get_api_info();this.fs_nocache_=new ds({api_info:e}).as(us),this.fs_cache_=new fs({delegate:this.fs_nocache_}).as(us),this.fs_proxy_=new ps({delegate:this.fs_nocache_}),this.filesystem=this.fs_proxy_.as(us)}cache_on(){this.fs_proxy_.delegate=this.fs_cache_}cache_off(){this.fs_proxy_.delegate=this.fs_nocache_}async initializeSocket(){this.socket&&this.socket.disconnect();const e=this._.context.services.get("api-access").get_api_info();void 0!==e.api_origin&&(this.socket=ut(e.api_origin,{auth:{auth_token:e.auth_token},autoUnref:"nodejs"===this._.context.env}),this.bindSocketEvents())}bindSocketEvents(){this.socket.on("connect",()=>{puter.debugMode&&console.log("FileSystem Socket: Connected",this.socket.id)}),this.socket.on("disconnect",()=>{puter.debugMode&&console.log("FileSystem Socket: Disconnected")}),this.socket.on("reconnect",e=>{puter.debugMode&&console.log("FileSystem Socket: Reconnected",this.socket.id)}),this.socket.on("reconnect_attempt",e=>{puter.debugMode&&console.log("FileSystem Socket: Reconnection Attemps",e)}),this.socket.on("reconnect_error",e=>{puter.debugMode&&console.log("FileSystem Socket: Reconnection Error",e)}),this.socket.on("reconnect_failed",()=>{puter.debugMode&&console.log("FileSystem Socket: Reconnection Failed")}),this.socket.on("error",e=>{puter.debugMode&&console.error("FileSystem Socket Error:",e)})}}const ws={id:"f485f1ba-de07-422c-8c4b-c2da057d4a44",uid:"f485f1ba-de07-422c-8c4b-c2da057d4a44",is_dir:!0,immutable:!0,name:"FromParentWindow"};class vs extends e.concepts.Service{async _init(){const e=this._.context.services,t=this._.context.util;e.get("xd-incoming").register_tagged_listener("puter-fs",e=>{t.rpc.send(e.source,e.data.$callback,[ws])})}}class _s extends e.concepts.Service{_init(){if(globalThis.when_puter_happens&&(!puter||"gui"===puter.env)){Array.isArray(globalThis.when_puter_happens)||(globalThis.when_puter_happens=[globalThis.when_puter_happens]);for(const e of globalThis.when_puter_happens)e({context:this._.context})}}}const ks=e.libs.promise.TeePromise;class As extends e.concepts.Service{_construct(){this.filter_listeners_=[],this.tagged_listeners_={}}_init(){globalThis.addEventListener("message",async e=>{for(const t of this.filter_listeners_){const s=new ks;if(t(e,s),await s)return}const t=e.data,s=t.$;if(s&&this.tagged_listeners_[s])for(const n of this.tagged_listeners_[s])n({data:t,source:e.source})})}register_filter_listener(e){this.filter_listeners_.push(e)}register_tagged_listener(e,t){this.tagged_listeners_[e]||(this.tagged_listeners_[e]=[]),this.tagged_listeners_[e].push(t)}}const Ts=function(){const s=new class{env;defaultAPIOrigin="https://api.puter.com";defaultGUIOrigin="https://puter.com";onAuth;puterAuthState={isPromptOpen:!1,authGranted:null,resolver:null};appInstanceID;parentInstanceID;static FSItem=Et;eventHandlers={};debugMode=!1;initSubmodules=function(){this.util=new os,this.registerModule("auth",F),this.registerModule("os",Vt),this.registerModule("fs",It),this.registerModule("ui",ts,{appInstanceID:this.appInstanceID,parentInstanceID:this.parentInstanceID}),this.registerModule("hosting",Pt),this.registerModule("apps",B),this.registerModule("ai",z),this.registerModule("kv",Lt),this.registerModule("threads",Yt),this.registerModule("perms",Kt),this.registerModule("drivers",V),this.registerModule("debug",W),this.path=c};constructor(){this._cache=new t,this.modules_=[];const s=(new e.libs.context.Context).follow(this,["env","util","authToken","APIOrigin","appID"]);s.puter=this,this.services=new e.system.ServiceManager({context:s}),this.context=s,s.services=this.services;let r=new URLSearchParams(globalThis.location?.search);r.has("puter.app_instance_id")?this.env="app":!0===globalThis.puter_gui_enabled?this.env="gui":globalThis.WorkerGlobalScope?(globalThis.ServiceWorkerGlobalScope?(this.env="service-worker",globalThis.XMLHttpRequest||(globalThis.XMLHttpRequest=S),globalThis.location||(globalThis.location=new URL("https://puter.site/"))):this.env="web-worker",globalThis.localStorage||(globalThis.localStorage=u)):globalThis.process?(this.env="nodejs",globalThis.localStorage||(globalThis.localStorage=u),globalThis.XMLHttpRequest||(globalThis.XMLHttpRequest=S),globalThis.location||(globalThis.location=new URL("https://nodejs.puter.site/")),globalThis.addEventListener||(globalThis.addEventListener=()=>{})):this.env="web","gui"!==this.env&&location.hostname.replace(/\.$/,"")===new URL("https://puter.com").hostname&&(this.env="gui"),r.has("puter.args")?this.args=JSON.parse(decodeURIComponent(r.get("puter.args"))):this.args={},r.has("puter.app_instance_id")&&(this.appInstanceID=decodeURIComponent(r.get("puter.app_instance_id"))),r.has("puter.parent_instance_id")&&(this.parentInstanceID=decodeURIComponent(r.get("puter.parent_instance_id"))),r.has("puter.app.id")&&(this.appID=decodeURIComponent(r.get("puter.app.id"))),r.has("puter.app.name")&&(this.appName=decodeURIComponent(r.get("puter.app.name"))),this.appID&&(this.appDataPath=`~/AppData/${this.appID}`),this.APIOrigin=this.defaultAPIOrigin,r.has("puter.api_origin")&&"app"===this.env?this.APIOrigin=decodeURIComponent(r.get("puter.api_origin")):r.has("puter.domain")&&"app"===this.env&&(this.APIOrigin="https://api."+r.get("puter.domain"));let i=new e.libs.log.ConsoleLogger;i=new e.libs.log.CategorizedToggleLogger({delegate:i});const o=i;if(this.logger=new e.libs.log.LoggerFacade({impl:i,cat:o}),this.apiCallLogger=new n({enabled:!1}),this.services.register("no-puter-yet",_s),this.services.register("filesystem",bs),this.services.register("api-access",ls),this.services.register("xd-incoming",As),"app"!==this.env&&this.services.register("fs-relay",vs),(async()=>{await this.services.wait_for_init(["api-access"]);const e=this.services.get("api-access");e.auth_token=this.authToken,e.api_origin=this.APIOrigin,[["authToken","auth_token"],["APIOrigin","api_origin"]].forEach(([t,s])=>{Object.defineProperty(this,t,{get:()=>e[s],set(t){e[s]=t}})})})(),"gui"===this.env)this.authToken=window.auth_token,this.initSubmodules();else if("app"===this.env){this.authToken=decodeURIComponent(r.get("puter.auth.token")),this.initSubmodules();try{localStorage.getItem("puter.auth.token")&&this.setAuthToken(localStorage.getItem("puter.auth.token")),localStorage.getItem("puter.app.id")&&this.setAppID(localStorage.getItem("puter.app.id"))}catch(e){console.error("Error accessing localStorage:",e)}}else if("web"===this.env){this.initSubmodules();try{localStorage.getItem("puter.auth.token")&&this.setAuthToken(localStorage.getItem("puter.auth.token")),localStorage.getItem("puter.app.id")&&this.setAppID(localStorage.getItem("puter.app.id"))}catch(e){console.error("Error accessing localStorage:",e)}}else"web-worker"!==this.env&&"service-worker"!==this.env&&"nodejs"!==this.env||this.initSubmodules();(async()=>{await this.services.wait_for_init(["api-access"]);const t=await this.auth.whoami();i=new e.libs.log.PrefixLogger({delegate:i,prefix:"["+(t?.app_name??this.appInstanceID??"HOST")+"] "}),this.logger.impl=i})(),this.lock_rao_=new e.libs.promise.Lock,this.p_can_request_rao_=new e.libs.promise.TeePromise,this.rao_requested_=!1,(async()=>{await this.services.wait_for_init(["api-access"]),this.p_can_request_rao_.resolve()})(),this.net={generateWispV1URL:async()=>{const{token:e,server:t}=await(await fetch(this.APIOrigin+"/wisp/relay-token/create",{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({})})).json();return`${t}/${e}/`},Socket:Wt,tls:{TLSSocket:Xt},fetch:Gt},this.workers=new cs(this.authToken),this.initNetworkMonitoring()}async request_rao_(){if(await this.p_can_request_rao_,"gui"===this.env)return;if(await this.lock_rao_.acquire(),this.rao_requested_)return void this.lock_rao_.release();let e=!1;try{const e=await fetch(this.APIOrigin+"/rao",{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,Origin:location.origin}});return await e.json()}catch(t){e=!0,console.error(t)}finally{this.lock_rao_.release()}e||(this.rao_requested_=!0)}registerModule(e,t,s={}){const n=new t(this.context,s);this.modules_.push(e),this[e]=n,n._init&&n._init({puter:this})}updateSubmodules(){for(const e of this.modules_)this[e]&&(this[e]?.setAuthToken?.(this.authToken),this[e]?.setAPIOrigin?.(this.APIOrigin))}setAppID=function(e){try{localStorage.setItem("puter.app.id",e)}catch(e){console.error("Error accessing localStorage:",e)}this.appID=e};setAuthToken=function(e){if(this.authToken=e,"web"===this.env||"app"===this.env)try{localStorage.setItem("puter.auth.token",e)}catch(e){console.error("Error accessing localStorage:",e)}this.updateSubmodules(),this.request_rao_()};setAPIOrigin=function(e){this.APIOrigin=e,this.updateSubmodules()};resetAuthToken=function(){if(this.authToken=null,"web"===this.env||"app"===this.env)try{localStorage.removeItem("puter.auth.token")}catch(e){console.error("Error accessing localStorage:",e)}this.updateSubmodules()};exit=function(e=0){e&&"number"!=typeof e&&(console.warn("puter.exit() requires status code to be a number. Treating it as 1"),e=1),globalThis.parent.postMessage({msg:"exit",appInstanceID:this.appInstanceID,statusCode:e},"*")};randName=function(e="-"){const t=["helpful","sensible","loyal","honest","clever","capable","calm","smart","genius","bright","charming","creative","diligent","elegant","fancy","colorful","avid","active","gentle","happy","intelligent","jolly","kind","lively","merry","nice","optimistic","polite","quiet","relaxed","silly","victorious","witty","young","zealous","strong","brave","agile","bold"],s=["street","roof","floor","tv","idea","morning","game","wheel","shoe","bag","clock","pencil","pen","magnet","chair","table","house","dog","room","book","car","cat","tree","flower","bird","fish","sun","moon","star","cloud","rain","snow","wind","mountain","river","lake","sea","ocean","island","bridge","road","train","plane","ship","bicycle","horse","elephant","lion","tiger","bear","zebra","giraffe","monkey","snake","rabbit","duck","goose","penguin","frog","crab","shrimp","whale","octopus","spider","ant","bee","butterfly","dragonfly","ladybug","snail","camel","kangaroo","koala","panda","piglet","sheep","wolf","fox","deer","mouse","seal","chicken","cow","dinosaur","puppy","kitten","circle","square","garden","otter","bunny","meerkat","harp"];return t[Math.floor(Math.random()*t.length)]+e+s[Math.floor(Math.random()*s.length)]+e+Math.floor(1e4*Math.random())};getUser=function(...e){let t;return t="object"==typeof e[0]&&null!==e[0]?e[0]:{success:e[0],error:e[1]},new Promise((e,s)=>{const n=O("/whoami",this.APIOrigin,this.authToken,"get");C(n,t.success,t.error,e,s),n.send()})};print=function(...e){let t={};e.length>0&&"object"==typeof e[e.length-1]&&null!==e[e.length-1]&&("escapeHTML"in e[e.length-1]||"code"in e[e.length-1])&&(t=e.pop());for(let s of e)!0!==t.escapeHTML&&!0!==t.code||"string"!=typeof s||(s=s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")),!0===t.code&&(s=`<code><pre>${s}</pre></code>`),document.body.innerHTML+=s};configureAPILogging=function(e={}){return this.apiCallLogger&&this.apiCallLogger.updateConfig(e),this};enableAPILogging=function(e={}){return this.apiCallLogger&&this.apiCallLogger.updateConfig({...e,enabled:!0}),this};disableAPILogging=function(){return this.apiCallLogger&&this.apiCallLogger.disable(),this};initNetworkMonitoring=function(){if(void 0===globalThis.navigator||"function"!=typeof globalThis.addEventListener)return;let e=navigator.onLine;const t=()=>{const t=navigator.onLine;e&&!t&&(console.log("Network connection lost - purging cache"),this.purgeCache()),e=t};globalThis.addEventListener("online",t),globalThis.addEventListener("offline",t),"undefined"!=typeof document&&document.addEventListener("visibilitychange",()=>{setTimeout(t,100)})};purgeCache=function(){try{this._cache&&"function"==typeof this._cache.flushall?(this._cache.flushall(),console.log("Cache purged successfully")):console.warn("Cache purge failed: cache instance not available")}catch(e){console.error("Error purging cache:",e)}}};return s}();globalThis.puter=Ts,globalThis.addEventListener&&globalThis.addEventListener("message",async e=>{e.origin===Ts.defaultGUIOrigin&&(e.data.msg&&"requestOrigin"===e.data.msg?e.source.postMessage({msg:"originResponse"},"*"):"puter.token"===e.data.msg&&(Ts.setAuthToken(e.data.token),Ts.setAppID(e.data.app_uid),Ts.puterAuthState.authGranted=!0,Ts.onAuth&&"function"==typeof Ts.onAuth&&Ts.getUser().then(e=>{Ts.onAuth(e)}),Ts.puterAuthState.isPromptOpen=!1,Ts.puterAuthState.resolver&&(Ts.puterAuthState.authGranted?Ts.puterAuthState.resolver.resolve():Ts.puterAuthState.resolver.reject(),Ts.puterAuthState.resolver=null)))})})()})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyputer/puter.js",
3
- "version": "2.0.10",
3
+ "version": "2.0.11",
4
4
  "description": "Puter.js - A JavaScript library for interacting with Puter services.",
5
5
  "main": "src/index.js",
6
6
  "types": "index.d.ts",
@@ -2,11 +2,11 @@ const { readFileSync } = require('node:fs');
2
2
  const vm = require('node:vm');
3
3
  const { resolve } = require('node:path');
4
4
  /**
5
- * Method for loading puter.js in Node.js environment
5
+ * Method for loading puter.js in Node.js environment with auth token
6
6
  * @param {string} authToken - Optional auth token to initialize puter with
7
- * @returns {import('../index.d.ts').puter} The `puter` object from puter.js
7
+ * @returns {import('../index').puter} The `puter` object from puter.js
8
8
  */
9
- const safeLoadPuterJs = (authToken) => {
9
+ const init = (authToken) => {
10
10
  const goodContext = {};
11
11
  Object.getOwnPropertyNames(globalThis).forEach(name => {
12
12
  try {
@@ -25,4 +25,4 @@ const safeLoadPuterJs = (authToken) => {
25
25
  return goodContext.puter;
26
26
  };
27
27
 
28
- module.exports = { safeLoadPuterJs };
28
+ module.exports = { init };