Socket
Socket
Sign inDemoInstall

mps3

Package Overview
Dependencies
0
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.0.76 to 0.0.77

2

dist/mps3.js

@@ -1,1 +0,1 @@

async function M($,z){const D=await crypto.subtle.importKey("raw",typeof $==="string"?R.encode($):$,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",D,R.encode(z))}async function a($){return crypto.subtle.digest("SHA-256",typeof $==="string"?R.encode($):$)}var K=function($){return Array.prototype.map.call(new Uint8Array($),(z)=>("0"+z.toString(16)).slice(-2)).join("")},o=function($){return $.replace(/[!'()*]/g,(z)=>"%"+z.charCodeAt(0).toString(16).toUpperCase())},P$=function($,z){const{hostname:D,pathname:W}=$;if(D.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(D.endsWith(".backblazeb2.com")){const Q=D.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);return Q!=null?["s3",Q[1]]:["",""]}const X=D.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[J,Z]=(X||["",""]).slice(1,3);if(Z==="us-gov")Z="us-gov-west-1";else if(Z==="s3"||Z==="s3-accelerate")Z="us-east-1",J="s3";else if(J==="iot")if(D.startsWith("iot."))J="execute-api";else if(D.startsWith("data.jobs.iot."))J="iot-jobs-data";else J=W==="/mqtt"?"iotdevicegateway":"iotdata";else if(J==="autoscaling"){const Q=(z.get("X-Amz-Target")||"").split(".")[0];if(Q==="AnyScaleFrontendService")J="application-autoscaling";else if(Q==="AnyScaleScalingPlannerFrontendService")J="autoscaling-plans"}else if(Z==null&&J.startsWith("s3-"))Z=J.slice(3).replace(/^fips-|^external-1/,""),J="s3";else if(J.endsWith("-fips"))J=J.slice(0,-5);else if(Z&&/-\d$/.test(J)&&!/-\d$/.test(Z))[J,Z]=[Z,J];return[Y$[J]||J,Z]},R=new TextEncoder,Y$={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},O$=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class h{constructor({accessKeyId:$,secretAccessKey:z,sessionToken:D,service:W,region:X,cache:J,retries:Z,initRetryMs:Q}){if($==null)throw new TypeError("accessKeyId is a required option");if(z==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=$,this.secretAccessKey=z,this.sessionToken=D,this.service=W,this.region=X,this.cache=J||new Map,this.retries=Z!=null?Z:10,this.initRetryMs=Q||50}async sign($,z){if($ instanceof Request){const{method:X,url:J,headers:Z,body:Q}=$;if(z=Object.assign({method:X,url:J,headers:Z},z),z.body==null&&Z.has("Content-Type"))z.body=Q!=null&&Z.has("X-Amz-Content-Sha256")?Q:await $.clone().arrayBuffer();$=J}const D=new t(Object.assign({url:$},z,this,z&&z.aws)),W=Object.assign({},z,await D.sign());delete W.aws;try{return new Request(W.url.toString(),W)}catch(X){if(X instanceof TypeError)return new Request(W.url.toString(),Object.assign({duplex:"half"},W));throw X}}async fetch($,z){for(let D=0;D<=this.retries;D++){const W=fetch(await this.sign($,z));if(D===this.retries)return W;const X=await W;if(X.status<500&&X.status!==429)return X;await new Promise((J)=>setTimeout(J,Math.random()*this.initRetryMs*Math.pow(2,D)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class t{constructor({method:$,url:z,headers:D,body:W,accessKeyId:X,secretAccessKey:J,sessionToken:Z,service:Q,region:Y,cache:O,datetime:U,signQuery:F,appendSessionToken:H,allHeaders:A,singleEncode:Q$}){if(z==null)throw new TypeError("url is a required option");if(X==null)throw new TypeError("accessKeyId is a required option");if(J==null)throw new TypeError("secretAccessKey is a required option");this.method=$||(W?"POST":"GET"),this.url=new URL(z),this.headers=new Headers(D||{}),this.body=W,this.accessKeyId=X,this.secretAccessKey=J,this.sessionToken=Z;let u,l;if(!Q||!Y)[u,l]=P$(this.url,this.headers);if(this.service=Q||u||"",this.region=Y||l||"us-east-1",this.cache=O||new Map,this.datetime=U||(new Date()).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=F,this.appendSessionToken=H||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");const C=this.signQuery?this.url.searchParams:this.headers;if(C.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)C.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((P)=>A||!O$.has(P)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((P)=>P+":"+(P==="host"?this.url.host:(this.headers.get(P)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!C.has("X-Amz-Expires"))C.set("X-Amz-Expires","86400");C.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),C.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),C.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(P){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!Q$)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=o(this.encodedPath);const c=new Set;this.encodedSearch=[...this.url.searchParams].filter(([P])=>{if(!P)return!1;if(this.service==="s3"){if(c.has(P))return!1;c.add(P)}return!0}).map((P)=>P.map((q)=>o(encodeURIComponent(q)))).sort(([P,q],[n,i])=>P<n?-1:P>n?1:q<i?-1:q>i?1:0).map((P)=>P.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const $=this.datetime.slice(0,8),z=[this.secretAccessKey,$,this.region,this.service].join();let D=this.cache.get(z);if(!D){const W=await M("AWS4"+this.secretAccessKey,$),X=await M(W,this.region),J=await M(X,this.service);D=await M(J,"aws4_request"),this.cache.set(z,D)}return K(await M(D,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,K(await a(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let $=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if($==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");$=K(await a(this.body||""))}return $}}var r=($,z)=>{const D=z.parseFromString($,"text/xml");if(!D)throw new Error(`Invalid XML: ${$}`);const W=D.getElementsByTagName("Contents"),X=(J,Z)=>{const Q=J.getElementsByTagName(Z)[0]?.textContent;return Q?decodeURIComponent(Q.replace(/\+/g," ")):void 0};return{$metadata:{},Contents:Array.from(W).map((J)=>({ETag:X(J,"ETag"),Key:X(J,"Key")})),KeyCount:parseInt(X(D,"KeyCount")),ContinuationToken:X(D,"ContinuationToken"),NextContinuationToken:X(D,"NextContinuationToken"),StartAfter:X(D,"StartAfter")}};var I=async($,{retries:z=Number.MAX_VALUE,delay:D=100,max_delay:W=1e4}={})=>{try{return await $()}catch(X){if(z>0)return await new Promise((J)=>setTimeout(J,D)),I($,{retries:z-1,max_delay:W,delay:Math.min(D*1.5,W)});throw X}};class S{$;z;D;constructor($,z,D){this.fetch=$;this.endpoint=z;this.parser=D}getUrl($,z,D){return`${this.endpoint}/${$}${z?`/${encodeURIComponent(z)}`:""}${D||""}`}async listObjectV2($){for(let z=0;z<10;z++){const D=this.getUrl($.Bucket,void 0,`/?list-type=2&prefix=${$.Prefix}`),W=await I(()=>this.fetch(D,{}));if(W.status===200)return r(await W.text(),this.parser);else if(W.status===429)console.warn("listObjectV2: 429, retrying"),await new Promise((X)=>setTimeout(X,1000));else throw new Error(`Unexpected response: ${W.status} ${await W.text()}`)}throw new Error("Cannot contact server")}async putObject({Bucket:$,Key:z,Body:D,ChecksumSHA256:W}){const X=this.getUrl($,z),J=await I(()=>this.fetch(X,{method:"PUT",body:D,headers:{"Content-Type":"application/json",...W&&{"x-amz-content-sha256":W}}}));if(J.status!==200)throw new Error(`Failed to PUT: ${await J.text()}`);return{$metadata:{httpStatusCode:J.status},ETag:J.headers.get("ETag"),...J.headers.get("x-amz-version-id")&&{VersionId:J.headers.get("x-amz-version-id")}}}async deleteObject({Bucket:$,Key:z}){return{$metadata:{httpStatusCode:(await I(()=>this.fetch(this.getUrl($,z),{method:"DELETE"}))).status}}}async getObject({Bucket:$,Key:z,VersionId:D,IfNoneMatch:W}){const X=this.getUrl($,z,D?`?versionId=${D}`:""),J=await I(()=>this.fetch(X,{method:"GET",headers:{"If-None-Match":W}}));switch(J.status){case 304:throw new Error("304");case 404:return{$metadata:{httpStatusCode:404}};case 403:throw new Error("Access denied");default:{let Z;const Q=J.headers.get("content-type"),Y=await J.text();if(Q==="application/json"||Y&&Y!=="")try{Z=JSON.parse(Y)}catch(O){throw new Error(`Failed to parse response as JSON ${X}`)}return{$metadata:{httpStatusCode:J.status},Body:Z,ETag:J.headers.get("ETag"),...J.headers.get("x-amz-version-id")&&{VersionId:J.headers.get("x-amz-version-id")}}}}}}class L{key;_vals;_keys;constructor($,z){if(this.key=$,this._vals=new Map,this._keys=new Map,z)for(let[D,W]of z)this.set(D,W)}get size(){return this._vals.size}set($,z){const D=this.key($);return this._vals.set(D,z),this._keys.set(D,$),this}get($){return this._vals.get(this.key($))}delete($){const z=this.key($);return this._keys.delete(z),this._vals.delete(z)}has($){return this._vals.has(this.key($))}values(){return this._vals.values()}keys(){return this._keys.values()}forEach($){return this._vals.forEach((z,D,W)=>$(z,this._keys.get(D)))}}var s=()=>`${Date.now()-200}`.padStart(14,"0"),e=()=>`${Date.now()+200}`.padStart(14,"0");var E=async($)=>{const z=Date.now(),D=await $,W=Date.now();return[D,W-z]};var G=()=>crypto.randomUUID();var B=($)=>`${$.bucket}/${$.key}`;var V=function($){return new Promise((z,D)=>{$.oncomplete=$.onsuccess=()=>z($.result),$.onabort=$.onerror=()=>D($.error)})},_=function($,z){const D=indexedDB.open($);D.onupgradeneeded=()=>D.result.createObjectStore(z);const W=V(D);return(X,J)=>W.then((Z)=>J(Z.transaction(z,X).objectStore(z)))},N=function(){if(!v)v=_("keyval-store","keyval");return v},j=function($,z=N()){return z("readonly",(D)=>V(D.get($)))},T=function($,z,D=N()){return D("readwrite",(W)=>{return W.put(z,$),V(W.transaction)})};var $$=function($,z=N()){return z("readonly",(D)=>Promise.all($.map((W)=>V(D.get(W)))))};var z$=function($,z=N()){return z("readwrite",(D)=>{return D.delete($),V(D.transaction)})},w=function($,z=N()){return z("readwrite",(D)=>{return $.forEach((W)=>D.delete(W)),V(D.transaction)})};var U$=function($,z){return $.openCursor().onsuccess=function(){if(!this.result)return;z(this.result),this.result.continue()},V($.transaction)},x=function($=N()){return $("readonly",(z)=>{if(z.getAllKeys)return V(z.getAllKeys());const D=[];return U$(z,(W)=>D.push(W.key)).then(()=>D)})};var v;var B$=6,D$=($)=>`write-${$.toString().padStart(B$,"0")}`;class k{session=G();proposedOperations=new Map;operationLabels=new Map;db;lastIndex=0;load=void 0;constructor($){this.db=$}async propose($,z,D=!1){if(this.proposedOperations.set($,z),this.db){if(this.load&&!D)await this.load,this.proposedOperations.delete($),this.proposedOperations.set($,z);this.lastIndex++;const W=D$(this.lastIndex);$[this.session]=this.lastIndex,await T(W,[...z.entries()].map(([X,J])=>[JSON.stringify(X),J]),this.db),console.log(`STORE ${W} ${JSON.stringify([...z.entries()])}`)}}async label($,z,D=!1){if(this.operationLabels.set(z,$),this.db){if(this.load&&!D)await this.load;const W=$[this.session];if(W===void 0)throw new Error("Cannot label an unproposed operation");const X=`label-${W}`;await T(X,z,this.db),console.log(`STORE ${X} ${z}`)}}async confirm($,z=!1){if(this.operationLabels.has($)){const D=this.operationLabels.get($);if(this.proposedOperations.delete(D),this.operationLabels.delete($),this.db){if(this.load&&!z)await this.load;const W=D[this.session],X=[D$(W),`label-${W}`];await w(X,this.db),console.log(`DEL ${X}`)}}}async cancel($,z=!1){if(this.operationLabels.forEach((D,W)=>{if(D===$)this.operationLabels.delete(W)}),this.proposedOperations.delete($),this.db){if(this.load&&!z)await this.load;const D=$[this.session];await w([`write-${D}`,`label-${D}`],this.db)}}async flatten(){if(this.load)await this.load;const $=new L(B);return this.proposedOperations.forEach((z)=>{z.forEach((D,W)=>{$.set(W,D)})}),$}async restore($,z){return this.db=$,this.proposedOperations.clear(),this.operationLabels.clear(),this.lastIndex=0,this.load=new Promise(async(D)=>{const X=(await x(this.db)).filter((Z)=>Z.startsWith("write-")).sort();console.log("RESTORE",X);const J=await $$(X,this.db);for(let Z=0;Z<X.length;Z++){const Q=parseInt(X[Z].split("-")[1]);this.lastIndex=Math.max(this.lastIndex,Q)}for(let Z=0;Z<X.length;Z++){const Q=X[Z],Y=parseInt(Q.split("-")[1]),O=J[Z].map(([H,A])=>[JSON.parse(H),A]),U=await j(`label-${Y}`,this.db);if(!O)continue;const F=new Map(O);await z(F,U),await w([`write-${Y}`,`label-${Y}`],this.db)}D(void 0)}),this.load}}function p($,z){if(z===void 0)return $;if(z===null)return;if(typeof z!=="object"||typeof $!=="object")return z;const D=typeof $==="object"?{...$}:{};for(let W in z)if(z[W]===null)delete D[W];else D[W]=p($[W],z[W]);return D}var g=($)=>JSON.parse(JSON.stringify($));var f="manifest",m={previous:".",files:{},update:{}};class y{$;authoritative_key="";authoritative_state=g(m);loading;cache;db;constructor($){this.manifest=$}async restore($){this.db=$,this.loading=j(f,$).then((z)=>{if(z)this.authoritative_state=z,this.manifest.service.config.log(`RESTORE ${f}`)})}async getLatest(){if(this.loading)await this.loading;if(this.loading=void 0,!this.manifest.service.config.online)return this.authoritative_state;try{const $=await this.manifest.service._getObject({operation:"POLL_TIME",ref:this.manifest.ref,ifNoneMatch:this.cache?.etag,useCache:!1});if($.$metadata.httpStatusCode===304)return this.authoritative_state;if($.data===void 0)this.authoritative_key=".";else this.authoritative_key=$.data;const[z,D]=await E(this.manifest.service.s3ClientLite.listObjectV2({Bucket:this.manifest.ref.bucket,Prefix:this.manifest.ref.key,StartAfter:this.authoritative_key}));if(this.manifest.service.config.log(`${D}ms LIST ${this.manifest.ref.bucket}/${this.manifest.ref.key}`),z.Contents===void 0)return this.authoritative_state=g(m),this.authoritative_state;const W=`${this.manifest.ref.key}@${s()}`;for(let X=z.Contents.length-1;X>=0;X--){const J=z.Contents[X].Key;if(J==this.manifest.ref.key)continue;const Z={bucket:this.manifest.ref.bucket,key:J},Q=await this.manifest.service._getObject({operation:"LOOK_BACK",ref:Z});if(Q.data===void 0){this.manifest.service._deleteObject({operation:"CLEANUP",ref:Z});continue}if(Q.data.previous<W){this.authoritative_key=Q.data.previous,this.authoritative_state=Q.data;break}}for(let X=0;X<z.Contents.length;X++){const J=z.Contents[X].Key;if(J==this.manifest.ref.key)continue;if(J<this.authoritative_key){await this.manifest.service._deleteObject({operation:"CLEANUP",ref:{bucket:this.manifest.ref.bucket,key:J}});continue}const Z=await this.manifest.service._getObject({operation:"SWEEP",ref:{bucket:this.manifest.ref.bucket,key:J}}),Q=J.substring(J.lastIndexOf("@")+1);this.authoritative_state=p(this.authoritative_state,Z.data?.update),this.authoritative_key=J,this.manifest.observeVersionId(Q)}if(this.db)T(f,this.authoritative_state,this.db);return this.authoritative_state}catch($){if($.name==="NoSuchKey")return this.authoritative_state=m,this.authoritative_state;else throw $}}}class W${$;z;D;queue=Promise.resolve();constructor($,z,D){this.ref=$;this.handler=z;this.lastVersion=D}notify($,z,D){this.queue=this.queue.then(()=>D).then((W)=>{if(z!==this.lastVersion)$.config.log(`${$.config.label} NOTIFY ${B(this.ref)} ${z}`),this.lastVersion=z,this.handler(W)})}}class d{$;z;subscribers=new Set;poller;pollInProgress=!1;manifestState=new y(this);operationQueue=new k;constructor($,z){this.service=$;this.ref=z;console.log("Create manifest",B(z))}load($){this.manifestState.restore($),this.operationQueue.restore($,async(z,D)=>{if(!D)await this.service._putAll(z,{manifests:[this.ref],await:"local",isLoad:!0});else await this.updateContent(z,Promise.resolve(new Map([[this.ref,D]])),{await:"local",isLoad:!0})})}observeVersionId($){this.operationQueue.confirm($)}async poll(){if(this.pollInProgress)return;if(this.pollInProgress=!0,this.subscriberCount===0&&this.poller)clearInterval(this.poller),this.poller=void 0;if(this.subscriberCount>0&&!this.poller)this.poller=setInterval(()=>this.poll(),this.service.config.pollFrequency);const $=await this.manifestState.getLatest();if($===void 0){this.pollInProgress=!1;return}const z=await this.operationQueue.flatten();this.subscribers.forEach(async(D)=>{if(z.has(D.ref))D.notify(this.service,"local",Promise.resolve(z.get(D.ref)));else{const W=$.files[B(D.ref)];if(W){const X=this.service._getObject({operation:"GET_CONTENT",ref:D.ref,version:W.version});D.notify(this.service,W.version,X.then((J)=>J.data))}else if(W===null)D.notify(this.service,void 0,Promise.resolve(void 0))}}),this.pollInProgress=!1}updateContent($,z,D){const W=this.operationQueue.propose(z,$,D.isLoad),X=W.then(async()=>{try{const J=await z,Z=await this.manifestState.getLatest();Z.previous=this.manifestState.authoritative_key,Z.update={files:{}};for(let[U,F]of J){const H=B(U);if(F){const A={version:F};Z.update.files[H]=A}else Z.update.files[H]=null}const Q=e()+"_"+G().substring(0,2),Y=this.ref.key+"@"+Q;this.operationQueue.label(z,Q,D.isLoad),await this.service._putObject({operation:"PUT_MANIFEST",ref:{key:Y,bucket:this.ref.bucket},value:Z});const O=await this.service._putObject({operation:"PUT_POLL",ref:{key:this.ref.key,bucket:this.ref.bucket},value:this.manifestState.authoritative_key});return this.poll(),O}catch(J){throw console.error(J),this.operationQueue.cancel(z,D.isLoad),J}});if(D.await==="local")return W;else return X}async getVersion($){return(await this.manifestState.getLatest()).files[B($)]?.version}subscribe($,z){this.service.config.log(`SUBSCRIBE ${B($)} ${this.subscriberCount+1}`);const D=new W$($,z);return this.subscribers.add(D),()=>this.subscribers.delete(D)}get subscriberCount(){return this.subscribers.size}}var X$=async($,z)=>{const D=new URL($),W=new URLSearchParams(D.search),X=D.pathname.split("/"),J=X[1],Z=X.slice(2).join("/"),Q=_(J,"v0");let Y,O=200;if(W.get("list-type")){const U=W.get("prefix")||"";Y=`<ListBucketResult>${(await x(Q)).filter((H)=>`${H}`.startsWith(U)).map((H)=>`<Contents><Key>${H}</Key></Contents>`)}</ListBucketResult>`}else if(z?.method==="GET")Y=await j(Z,Q),O=Y===void 0?404:200;else if(z?.method==="PUT")Y=await z.body,await T(Z,Y,Q);else if(z?.method==="DELETE")await z$(Z,Q);else throw new Error;return new Response(Y,{status:O})};async function J$($){const z=(new TextEncoder()).encode($),D=await crypto.subtle.digest("SHA-256",z);return[...new Uint8Array(D)].map((W)=>W.toString(16).padStart(2,"0")).join("")}class Z${static LOCAL_ENDPOINT="indexdb://";config;s3ClientLite;manifests=new L(B);memCache=new L(($)=>`${$.Bucket}${$.Key}${$.VersionId}${$.IfNoneMatch}`);diskCache;endpoint;constructor($){if(this.config={...$,label:$.label||"default",useChecksum:$.useChecksum===!1?!1:!0,online:$.online===!1?!1:!0,offlineStorage:$.offlineStorage===!1?!1:!0,useVersioning:$.useVersioning||!1,pollFrequency:$.pollFrequency||1000,defaultManifest:{bucket:$.defaultManifest?.bucket||$.defaultBucket,key:typeof $.defaultManifest=="string"?$.defaultManifest:$.defaultManifest?.key||"manifest.json"},log:(...D)=>($.log||console.log)(this.config.label,...D)},this.config.s3Config?.credentials instanceof Function)throw Error("We can't do that yet");this.endpoint=$.s3Config.endpoint||`https://s3.${$.s3Config.region}.amazonaws.com`;let z;if(this.config.s3Config?.credentials){const D=new h({accessKeyId:this.config.s3Config.credentials.accessKeyId,secretAccessKey:this.config.s3Config.credentials.secretAccessKey,sessionToken:this.config.s3Config.credentials.sessionToken,region:this.config.s3Config.region||"us-east-1",service:"s3",retries:0});z=(...W)=>D.fetch(...W)}else if(this.endpoint==Z$.LOCAL_ENDPOINT)z=X$;else z=(global||window).fetch.bind(global||window);if(this.config.offlineStorage){const D=`mps3-${this.config.label}`;this.diskCache=_(D,"v0")}this.s3ClientLite=new S(this.config.online?z:()=>new Promise(()=>{}),this.endpoint,$.parser||new DOMParser)}getOrCreateManifest($){if(!this.manifests.has($)){const z=new d(this,$);if(this.manifests.set($,z),this.config.offlineStorage){const D=`mps3-${this.config.label}-${$.bucket}-${$.key}`,W=_(D,"v0");this.config.log(`Restoring manifest from ${D}`),z.load(W)}}return this.manifests.get($)}async get($,z={}){const D={...this.config.defaultManifest,...z.manifest},W=this.getOrCreateManifest(D),X={bucket:$.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof $==="string"?$:$.key},J=await W.operationQueue.flatten();if(J.has(X))return this.config.log(`GET (cached) ${X} ${J.get(X)}`),J.get(X);const Z=await W.getVersion(X);if(Z===void 0)return;return(await this._getObject({operation:"GET",ref:X,version:Z})).data}async _getObject($){let z;if(this.config.useVersioning)z={Bucket:$.ref.bucket,Key:$.ref.key,IfNoneMatch:$.ifNoneMatch,...$.version&&{VersionId:$.version}};else z={Bucket:$.ref.bucket,Key:`${$.ref.key}${$.version?`@${$.version}`:""}`,IfNoneMatch:$.ifNoneMatch};const D=`${z.Bucket}${z.Key}${z.VersionId}`;if($.useCache!==!1){if(this.memCache.has(z))return this.memCache.get(z);if(this.diskCache){const X=await j(D,this.diskCache);if(X)return this.config.log(`${$.operation} (disk cached) ${D}`),this.memCache.set(z,Promise.resolve(X)),X}}if(!this.config.online)throw new Error(`${this.config.label} Offline and value not cached for ${D}`);const W=E(this.s3ClientLite.getObject(z)).then(async([X,J])=>{const Z={$metadata:X.$metadata,ETag:X.ETag,data:X.Body};return this.config.log(`${J}ms ${$.operation} ${$.ref.bucket}/${$.ref.key}@${$.version} => ${Z.VersionId}`),Z}).catch((X)=>{if(X?.name==="304")return{$metadata:{httpStatusCode:304},data:void 0};else throw X});if($.useCache!==!1){if(this.memCache.set(z,W),this.diskCache)W.then((X)=>{T(`${z.Bucket}${z.Key}${z.VersionId}`,X,this.diskCache).then(()=>this.config.log(`STORE ${z.Bucket}${z.Key}`))})}return W}async delete($,z={}){return this.putAll(new Map([[$,void 0]]),z)}async put($,z,D={}){return this.putAll(new Map([[$,z]]),D)}async putAll($,z={}){const D=new Map([...$].map(([X,J])=>[{bucket:X.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof X==="string"?X:X.key},J])),W=(z?.manifests||[this.config.defaultManifest]).map((X)=>({...this.config.defaultManifest,...X}));return this._putAll(D,{manifests:W,await:z.await||this.config.online?"remote":"local"})}async _putAll($,z){const D=new Map,W=new Promise(async(X,J)=>{const Z=new Map,Q=[];$.forEach((Y,O)=>{if(Y!==void 0){let U=this.config.useVersioning?void 0:G();D.set(O,Y),Q.push(this._putObject({operation:"PUT_CONTENT",ref:O,value:Y,version:U}).then((F)=>{if(this.config.useVersioning)if(F.VersionId===void 0)throw console.error(F),Error(`Bucket ${O.bucket} is not version enabled!`);else U=F.VersionId;Z.set(O,U)}))}else Q.push(this._deleteObject({ref:O}).then((U)=>{Z.set(O,void 0)}))}),await Promise.all(Q).catch(J),X(Z)});return Promise.all(z.manifests.map((X)=>{return this.getOrCreateManifest(X).updateContent(D,W,{await:z.await,isLoad:z.isLoad===!0})}))}async _putObject($){const z=JSON.stringify($.value,null,2);let D;if(this.config.useVersioning)D={Bucket:$.ref.bucket,Key:$.ref.key,ContentType:"application/json",Body:z,...this.config.useChecksum&&{ChecksumSHA256:await J$(z)}};else D={Bucket:$.ref.bucket,Key:`${$.ref.key}${$.version?`@${$.version}`:""}`,ContentType:"application/json",Body:z,...this.config.useChecksum&&{ChecksumSHA256:await J$(z)}};const[W,X]=await E(this.s3ClientLite.putObject(D));if(this.config.log(`${X}ms ${$.operation} ${D.Bucket}/${D.Key} => ${W.VersionId}`),this.diskCache){const J=`${D.Bucket}${D.Key}${$.version||W.VersionId}`;await T(J,{$metadata:{httpStatusCode:200},etag:W.ETag,data:JSON.parse(z)},this.diskCache).then(()=>this.config.log(`STORE ${J}`))}return W}async _deleteObject($){const z={Bucket:$.ref.bucket,Key:$.ref.key},[D,W]=await E(this.s3ClientLite.deleteObject(z));return this.config.log(`${W}ms ${$.operation||"DELETE"} ${$.ref.bucket}/${$.ref.key} (${D.$metadata.httpStatusCode})}`),D}subscribe($,z,D){const W={...this.config.defaultManifest,...D?.manifest},X={key:typeof $==="string"?$:$.key,bucket:$.bucket||this.config.defaultBucket||W.bucket},J=this.getOrCreateManifest(W),Z=J.subscribe(X,z);return this.get(X,{manifest:W}).then((Q)=>{this.config.log(`NOTIFY (initial) ${B(X)}`),queueMicrotask(()=>{z(Q,void 0),J.poll()})}).catch((Q)=>{z(void 0,Q)}),Z}refresh(){return Promise.all([...this.manifests.values()].map(($)=>$.poll()))}get subscriberCount(){return[...this.manifests.values()].reduce(($,z)=>$+z.subscriberCount,0)}}export{Z$ as MPS3};
async function M($,z){const D=await crypto.subtle.importKey("raw",typeof $==="string"?R.encode($):$,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",D,R.encode(z))}async function a($){return crypto.subtle.digest("SHA-256",typeof $==="string"?R.encode($):$)}var K=function($){return Array.prototype.map.call(new Uint8Array($),(z)=>("0"+z.toString(16)).slice(-2)).join("")},o=function($){return $.replace(/[!'()*]/g,(z)=>"%"+z.charCodeAt(0).toString(16).toUpperCase())},U0=function($,z){const{hostname:D,pathname:W}=$;if(D.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(D.endsWith(".backblazeb2.com")){const O=D.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);return O!=null?["s3",O[1]]:["",""]}const X=D.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[J,Z]=(X||["",""]).slice(1,3);if(Z==="us-gov")Z="us-gov-west-1";else if(Z==="s3"||Z==="s3-accelerate")Z="us-east-1",J="s3";else if(J==="iot")if(D.startsWith("iot."))J="execute-api";else if(D.startsWith("data.jobs.iot."))J="iot-jobs-data";else J=W==="/mqtt"?"iotdevicegateway":"iotdata";else if(J==="autoscaling"){const O=(z.get("X-Amz-Target")||"").split(".")[0];if(O==="AnyScaleFrontendService")J="application-autoscaling";else if(O==="AnyScaleScalingPlannerFrontendService")J="autoscaling-plans"}else if(Z==null&&J.startsWith("s3-"))Z=J.slice(3).replace(/^fips-|^external-1/,""),J="s3";else if(J.endsWith("-fips"))J=J.slice(0,-5);else if(Z&&/-\d$/.test(J)&&!/-\d$/.test(Z))[J,Z]=[Z,J];return[Y0[J]||J,Z]},R=new TextEncoder,Y0={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},P0=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class h{constructor({accessKeyId:$,secretAccessKey:z,sessionToken:D,service:W,region:X,cache:J,retries:Z,initRetryMs:O}){if($==null)throw new TypeError("accessKeyId is a required option");if(z==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=$,this.secretAccessKey=z,this.sessionToken=D,this.service=W,this.region=X,this.cache=J||new Map,this.retries=Z!=null?Z:10,this.initRetryMs=O||50}async sign($,z){if($ instanceof Request){const{method:X,url:J,headers:Z,body:O}=$;if(z=Object.assign({method:X,url:J,headers:Z},z),z.body==null&&Z.has("Content-Type"))z.body=O!=null&&Z.has("X-Amz-Content-Sha256")?O:await $.clone().arrayBuffer();$=J}const D=new t(Object.assign({url:$},z,this,z&&z.aws)),W=Object.assign({},z,await D.sign());delete W.aws;try{return new Request(W.url.toString(),W)}catch(X){if(X instanceof TypeError)return new Request(W.url.toString(),Object.assign({duplex:"half"},W));throw X}}async fetch($,z){for(let D=0;D<=this.retries;D++){const W=fetch(await this.sign($,z));if(D===this.retries)return W;const X=await W;if(X.status<500&&X.status!==429)return X;await new Promise((J)=>setTimeout(J,Math.random()*this.initRetryMs*Math.pow(2,D)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class t{constructor({method:$,url:z,headers:D,body:W,accessKeyId:X,secretAccessKey:J,sessionToken:Z,service:O,region:Q,cache:Y,datetime:U,signQuery:B,appendSessionToken:V,allHeaders:N,singleEncode:Q0}){if(z==null)throw new TypeError("url is a required option");if(X==null)throw new TypeError("accessKeyId is a required option");if(J==null)throw new TypeError("secretAccessKey is a required option");this.method=$||(W?"POST":"GET"),this.url=new URL(z),this.headers=new Headers(D||{}),this.body=W,this.accessKeyId=X,this.secretAccessKey=J,this.sessionToken=Z;let u,l;if(!O||!Q)[u,l]=U0(this.url,this.headers);if(this.service=O||u||"",this.region=Q||l||"us-east-1",this.cache=Y||new Map,this.datetime=U||(new Date()).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=B,this.appendSessionToken=V||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");const _=this.signQuery?this.url.searchParams:this.headers;if(_.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)_.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((P)=>N||!P0.has(P)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((P)=>P+":"+(P==="host"?this.url.host:(this.headers.get(P)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!_.has("X-Amz-Expires"))_.set("X-Amz-Expires","86400");_.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),_.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),_.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(P){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!Q0)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=o(this.encodedPath);const c=new Set;this.encodedSearch=[...this.url.searchParams].filter(([P])=>{if(!P)return!1;if(this.service==="s3"){if(c.has(P))return!1;c.add(P)}return!0}).map((P)=>P.map((w)=>o(encodeURIComponent(w)))).sort(([P,w],[i,n])=>P<i?-1:P>i?1:w<n?-1:w>n?1:0).map((P)=>P.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const $=this.datetime.slice(0,8),z=[this.secretAccessKey,$,this.region,this.service].join();let D=this.cache.get(z);if(!D){const W=await M("AWS4"+this.secretAccessKey,$),X=await M(W,this.region),J=await M(X,this.service);D=await M(J,"aws4_request"),this.cache.set(z,D)}return K(await M(D,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,K(await a(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let $=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if($==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");$=K(await a(this.body||""))}return $}}var r=($,z)=>{const D=z.parseFromString($,"text/xml");if(!D)throw new Error(`Invalid XML: ${$}`);const W=D.getElementsByTagName("Contents"),X=(J,Z)=>{const O=J.getElementsByTagName(Z)[0]?.textContent;return O?decodeURIComponent(O.replace(/\+/g," ")):void 0};return{$metadata:{},Contents:Array.from(W).map((J)=>({ETag:X(J,"ETag"),Key:X(J,"Key")})),KeyCount:parseInt(X(D,"KeyCount")),ContinuationToken:X(D,"ContinuationToken"),NextContinuationToken:X(D,"NextContinuationToken"),StartAfter:X(D,"StartAfter")}};var q=async($,{retries:z=Number.MAX_VALUE,delay:D=100,max_delay:W=1e4}={})=>{try{return await $()}catch(X){if(z>0)return await new Promise((J)=>setTimeout(J,D)),q($,{retries:z-1,max_delay:W,delay:Math.min(D*1.5,W)});throw X}};class S{$;z;D;constructor($,z,D){this.fetch=$;this.endpoint=z;this.parser=D}getUrl($,z,D){return`${this.endpoint}/${$}${z?`/${encodeURIComponent(z)}`:""}${D||""}`}async listObjectV2($){for(let z=0;z<10;z++){const D=this.getUrl($.Bucket,void 0,`/?list-type=2&prefix=${$.Prefix}`),W=await q(()=>this.fetch(D,{}));if(W.status===200)return r(await W.text(),this.parser);else if(W.status===429)console.warn("listObjectV2: 429, retrying"),await new Promise((X)=>setTimeout(X,1000));else throw new Error(`Unexpected response: ${W.status} ${await W.text()}`)}throw new Error("Cannot contact server")}async putObject({Bucket:$,Key:z,Body:D,ChecksumSHA256:W}){const X=this.getUrl($,z),J=await q(()=>this.fetch(X,{method:"PUT",body:D,headers:{"Content-Type":"application/json",...W&&{"x-amz-content-sha256":W}}}));if(J.status!==200)throw new Error(`Failed to PUT: ${await J.text()}`);return{$metadata:{httpStatusCode:J.status},ETag:J.headers.get("ETag"),...J.headers.get("x-amz-version-id")&&{VersionId:J.headers.get("x-amz-version-id")}}}async deleteObject({Bucket:$,Key:z}){return{$metadata:{httpStatusCode:(await q(()=>this.fetch(this.getUrl($,z),{method:"DELETE"}))).status}}}async getObject({Bucket:$,Key:z,VersionId:D,IfNoneMatch:W}){const X=this.getUrl($,z,D?`?versionId=${D}`:""),J=await q(()=>this.fetch(X,{method:"GET",headers:{"If-None-Match":W}}));switch(J.status){case 304:throw new Error("304");case 404:return{$metadata:{httpStatusCode:404}};case 403:throw new Error("Access denied");default:{let Z;const O=J.headers.get("content-type"),Q=await J.text();if(O==="application/json"||Q&&Q!=="")try{Z=JSON.parse(Q)}catch(Y){throw new Error(`Failed to parse response as JSON ${X}`)}return{$metadata:{httpStatusCode:J.status},Body:Z,ETag:J.headers.get("ETag"),...J.headers.get("x-amz-version-id")&&{VersionId:J.headers.get("x-amz-version-id")}}}}}}class j{key;_vals;_keys;constructor($,z){if(this.key=$,this._vals=new Map,this._keys=new Map,z)for(let[D,W]of z)this.set(D,W)}get size(){return this._vals.size}set($,z){const D=this.key($);return this._vals.set(D,z),this._keys.set(D,$),this}get($){return this._vals.get(this.key($))}delete($){const z=this.key($);return this._keys.delete(z),this._vals.delete(z)}has($){return this._vals.has(this.key($))}values(){return this._vals.values()}keys(){return this._keys.values()}forEach($){return this._vals.forEach((z,D,W)=>$(z,this._keys.get(D)))}}var s=()=>`${Date.now()-200}`.padStart(14,"0"),e=()=>`${Date.now()+200}`.padStart(14,"0");var G=async($)=>{const z=Date.now(),D=await $,W=Date.now();return[D,W-z]};var L=()=>crypto.randomUUID(),$0=($)=>$.toString(36).padStart(4,"0");var F=($)=>`${$.bucket}/${$.key}`;var C=function($){return new Promise((z,D)=>{$.oncomplete=$.onsuccess=()=>z($.result),$.onabort=$.onerror=()=>D($.error)})},E=function($,z){const D=indexedDB.open($);D.onupgradeneeded=()=>D.result.createObjectStore(z);const W=C(D);return(X,J)=>W.then((Z)=>J(Z.transaction(z,X).objectStore(z)))},A=function(){if(!v)v=E("keyval-store","keyval");return v},T=function($,z=A()){return z("readonly",(D)=>C(D.get($)))},H=function($,z,D=A()){return D("readwrite",(W)=>{return W.put(z,$),C(W.transaction)})};var z0=function($,z=A()){return z("readonly",(D)=>Promise.all($.map((W)=>C(D.get(W)))))};var D0=function($,z=A()){return z("readwrite",(D)=>{return D.delete($),C(D.transaction)})},I=function($,z=A()){return z("readwrite",(D)=>{return $.forEach((W)=>D.delete(W)),C(D.transaction)})};var F0=function($,z){return $.openCursor().onsuccess=function(){if(!this.result)return;z(this.result),this.result.continue()},C($.transaction)},x=function($=A()){return $("readonly",(z)=>{if(z.getAllKeys)return C(z.getAllKeys());const D=[];return F0(z,(W)=>D.push(W.key)).then(()=>D)})};var v;var B0=6,W0=($)=>`write-${$.toString().padStart(B0,"0")}`;class g{session=L();proposedOperations=new Map;operationLabels=new Map;db;lastIndex=0;load=void 0;constructor($){this.db=$}async propose($,z,D=!1){if(this.proposedOperations.set($,z),this.db){if(this.load&&!D)await this.load,this.proposedOperations.delete($),this.proposedOperations.set($,z);this.lastIndex++;const W=W0(this.lastIndex);$[this.session]=this.lastIndex,await H(W,[...z.entries()].map(([X,J])=>[JSON.stringify(X),J]),this.db),console.log(`STORE ${W} ${JSON.stringify([...z.entries()])}`)}}async label($,z,D=!1){if(this.operationLabels.set(z,$),this.db){if(this.load&&!D)await this.load;const W=$[this.session];if(W===void 0)throw new Error("Cannot label an unproposed operation");const X=`label-${W}`;await H(X,z,this.db),console.log(`STORE ${X} ${z}`)}}async confirm($,z=!1){if(this.operationLabels.has($)){const D=this.operationLabels.get($);if(this.proposedOperations.delete(D),this.operationLabels.delete($),this.db){if(this.load&&!z)await this.load;const W=D[this.session],X=[W0(W),`label-${W}`];await I(X,this.db),console.log(`DEL ${X}`)}}}async cancel($,z=!1){if(this.operationLabels.forEach((D,W)=>{if(D===$)this.operationLabels.delete(W)}),this.proposedOperations.delete($),this.db){if(this.load&&!z)await this.load;const D=$[this.session];await I([`write-${D}`,`label-${D}`],this.db)}}async flatten(){if(this.load)await this.load;const $=new j(F);return this.proposedOperations.forEach((z)=>{z.forEach((D,W)=>{$.set(W,D)})}),$}async restore($,z){return this.db=$,this.proposedOperations.clear(),this.operationLabels.clear(),this.lastIndex=0,this.load=new Promise(async(D)=>{const X=(await x(this.db)).filter((Z)=>Z.startsWith("write-")).sort();console.log("RESTORE",X);const J=await z0(X,this.db);for(let Z=0;Z<X.length;Z++){const O=parseInt(X[Z].split("-")[1]);this.lastIndex=Math.max(this.lastIndex,O)}for(let Z=0;Z<X.length;Z++){const O=X[Z],Q=parseInt(O.split("-")[1]),Y=J[Z].map(([V,N])=>[JSON.parse(V),N]),U=await T(`label-${Q}`,this.db);if(!Y)continue;const B=new Map(Y);await z(B,U),await I([`write-${Q}`,`label-${Q}`],this.db)}D(void 0)}),this.load}}function p($,z){if(z===void 0)return $;if(z===null)return;if(typeof z!=="object"||typeof $!=="object")return z;const D=typeof $==="object"?{...$}:{};for(let W in z)if(z[W]===null)delete D[W];else D[W]=p($[W],z[W]);return D}var k=($)=>JSON.parse(JSON.stringify($));var f="manifest",m={previous:".",files:{},update:{}};class y{$;authoritative_key="";authoritative_state=k(m);loading;cache;db;constructor($){this.manifest=$}async restore($){this.db=$,this.loading=T(f,$).then((z)=>{if(z)this.authoritative_state=z,this.manifest.service.config.log(`RESTORE ${f}`)})}async getLatest(){if(this.loading)await this.loading;if(this.loading=void 0,!this.manifest.service.config.online)return this.authoritative_state;try{const $=await this.manifest.service._getObject({operation:"POLL_TIME",ref:this.manifest.ref,ifNoneMatch:this.cache?.etag,useCache:!1});if($.$metadata.httpStatusCode===304)return this.authoritative_state;if($.data===void 0)this.authoritative_key=".";else this.authoritative_key=$.data;const[z,D]=await G(this.manifest.service.s3ClientLite.listObjectV2({Bucket:this.manifest.ref.bucket,Prefix:this.manifest.ref.key,StartAfter:this.authoritative_key}));if(this.manifest.service.config.log(`${D}ms LIST ${this.manifest.ref.bucket}/${this.manifest.ref.key}`),z.Contents===void 0)return this.authoritative_state=k(m),this.authoritative_state;const W=`${this.manifest.ref.key}@${s()}`;for(let X=z.Contents.length-1;X>=0;X--){const J=z.Contents[X].Key;if(J==this.manifest.ref.key)continue;const Z={bucket:this.manifest.ref.bucket,key:J},O=await this.manifest.service._getObject({operation:"LOOK_BACK",ref:Z});if(O.data===void 0){if(this.manifest.service.autoclean)this.manifest.service._deleteObject({operation:"CLEANUP",ref:Z});continue}if(O.data.previous<W){this.authoritative_key=O.data.previous,this.authoritative_state=O.data;break}}for(let X=0;X<z.Contents.length;X++){const J=z.Contents[X].Key;if(J==this.manifest.ref.key)continue;if(J<this.authoritative_key){if(this.manifest.service.autoclean)this.manifest.service._deleteObject({operation:"CLEANUP",ref:{bucket:this.manifest.ref.bucket,key:J}});continue}const Z=await this.manifest.service._getObject({operation:"SWEEP",ref:{bucket:this.manifest.ref.bucket,key:J}}),O=J.substring(J.lastIndexOf("@")+1);this.authoritative_state=p(this.authoritative_state,Z.data?.update),this.authoritative_key=J,this.manifest.observeVersionId(O)}if(this.db)H(f,this.authoritative_state,this.db);return this.authoritative_state}catch($){if($.name==="NoSuchKey")return this.authoritative_state=m,this.authoritative_state;else throw $}}}class X0{$;z;D;queue=Promise.resolve();constructor($,z,D){this.ref=$;this.handler=z;this.lastVersion=D}notify($,z,D){this.queue=this.queue.then(()=>D).then((W)=>{if(z!==this.lastVersion)$.config.log(`${$.config.label} NOTIFY ${F(this.ref)} ${z}`),this.lastVersion=z,this.handler(W)})}}class d{$;z;session_id=L().substring(0,3);writes=0;subscribers=new Set;poller;pollInProgress=!1;manifestState=new y(this);operationQueue=new g;constructor($,z){this.service=$;this.ref=z;console.log("Create manifest",F(z))}load($){this.manifestState.restore($),this.operationQueue.restore($,async(z,D)=>{if(!D)await this.service._putAll(z,{manifests:[this.ref],await:"local",isLoad:!0});else await this.updateContent(z,Promise.resolve(new Map([[this.ref,D]])),{await:"local",isLoad:!0})})}observeVersionId($){this.operationQueue.confirm($)}async poll(){if(this.pollInProgress)return;if(this.pollInProgress=!0,this.subscriberCount===0&&this.poller)clearInterval(this.poller),this.poller=void 0;if(this.subscriberCount>0&&!this.poller)this.poller=setInterval(()=>this.poll(),this.service.config.pollFrequency);const $=await this.manifestState.getLatest();if($===void 0){this.pollInProgress=!1;return}const z=await this.operationQueue.flatten();this.subscribers.forEach(async(D)=>{if(z.has(D.ref))D.notify(this.service,"local",Promise.resolve(z.get(D.ref)));else{const W=$.files[F(D.ref)];if(W){const X=this.service._getObject({operation:"GET_CONTENT",ref:D.ref,version:W.version});D.notify(this.service,W.version,X.then((J)=>J.data))}else if(W===null)D.notify(this.service,void 0,Promise.resolve(void 0))}}),this.pollInProgress=!1}updateContent($,z,D){const W=e()+"_"+this.session_id+"_"+$0(this.writes++),X=this.operationQueue.propose(z,$,D.isLoad),J=X.then(async()=>{try{const Z=await z,O=await this.manifestState.getLatest();O.previous=this.manifestState.authoritative_key,O.update={files:{}};for(let[U,B]of Z){const V=F(U);if(B){const N={version:B};O.update.files[V]=N}else O.update.files[V]=null}const Q=this.ref.key+"@"+W;this.operationQueue.label(z,W,D.isLoad),await this.service._putObject({operation:"PUT_MANIFEST",ref:{key:Q,bucket:this.ref.bucket},value:O});const Y=await this.service._putObject({operation:"PUT_POLL",ref:{key:this.ref.key,bucket:this.ref.bucket},value:this.manifestState.authoritative_key});return this.poll(),Y}catch(Z){throw console.error(Z),this.operationQueue.cancel(z,D.isLoad),Z}});if(D.await==="local")return X;else return J}async getVersion($){return(await this.manifestState.getLatest()).files[F($)]?.version}subscribe($,z){this.service.config.log(`SUBSCRIBE ${F($)} ${this.subscriberCount+1}`);const D=new X0($,z);return this.subscribers.add(D),()=>this.subscribers.delete(D)}get subscriberCount(){return this.subscribers.size}}var J0=async($,z)=>{const D=new URL($),W=new URLSearchParams(D.search),X=D.pathname.split("/"),J=X[1],Z=X.slice(2).join("/"),O=E(J,"v0");let Q,Y=200;if(W.get("list-type")){const U=W.get("prefix")||"";Q=`<ListBucketResult>${(await x(O)).filter((V)=>`${V}`.startsWith(U)).map((V)=>`<Contents><Key>${V}</Key></Contents>`)}</ListBucketResult>`}else if(z?.method==="GET")Q=await T(Z,O),Y=Q===void 0?404:200;else if(z?.method==="PUT")Q=await z.body,await H(Z,Q,O);else if(z?.method==="DELETE")await D0(Z,O);else throw new Error;return new Response(Q,{status:Y})};async function Z0($){const z=(new TextEncoder()).encode($),D=await crypto.subtle.digest("SHA-256",z);return[...new Uint8Array(D)].map((W)=>W.toString(16).padStart(2,"0")).join("")}class O0{static LOCAL_ENDPOINT="indexdb://";config;s3ClientLite;manifests=new j(F);memCache=new j(($)=>`${$.Bucket}${$.Key}${$.VersionId}${$.IfNoneMatch}`);diskCache;endpoint;constructor($){if(this.config={...$,label:$.label||"default",useChecksum:$.useChecksum===!1?!1:!0,autoclean:$.autoclean===!1?!1:!0,online:$.online===!1?!1:!0,offlineStorage:$.offlineStorage===!1?!1:!0,useVersioning:$.useVersioning||!1,pollFrequency:$.pollFrequency||1000,defaultManifest:{bucket:$.defaultManifest?.bucket||$.defaultBucket,key:typeof $.defaultManifest=="string"?$.defaultManifest:$.defaultManifest?.key||"manifest.json"},log:(...D)=>($.log||console.log)(this.config.label,...D)},this.config.s3Config?.credentials instanceof Function)throw Error("We can't do that yet");this.endpoint=$.s3Config.endpoint||`https://s3.${$.s3Config.region}.amazonaws.com`;let z;if(this.config.s3Config?.credentials){const D=new h({accessKeyId:this.config.s3Config.credentials.accessKeyId,secretAccessKey:this.config.s3Config.credentials.secretAccessKey,sessionToken:this.config.s3Config.credentials.sessionToken,region:this.config.s3Config.region||"us-east-1",service:"s3",retries:0});z=(...W)=>D.fetch(...W)}else if(this.endpoint==O0.LOCAL_ENDPOINT)z=J0;else z=(global||window).fetch.bind(global||window);if(this.config.offlineStorage){const D=`mps3-${this.config.label}`;this.diskCache=E(D,"v0")}this.s3ClientLite=new S(this.config.online?z:()=>new Promise(()=>{}),this.endpoint,$.parser||new DOMParser)}getOrCreateManifest($){if(!this.manifests.has($)){const z=new d(this,$);if(this.manifests.set($,z),this.config.offlineStorage){const D=`mps3-${this.config.label}-${$.bucket}-${$.key}`,W=E(D,"v0");this.config.log(`Restoring manifest from ${D}`),z.load(W)}}return this.manifests.get($)}async get($,z={}){const D={...this.config.defaultManifest,...z.manifest},W=this.getOrCreateManifest(D),X={bucket:$.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof $==="string"?$:$.key},J=await W.operationQueue.flatten();if(J.has(X))return this.config.log(`GET (cached) ${X} ${J.get(X)}`),J.get(X);const Z=await W.getVersion(X);if(Z===void 0)return;return(await this._getObject({operation:"GET",ref:X,version:Z})).data}async _getObject($){let z;if(this.config.useVersioning)z={Bucket:$.ref.bucket,Key:$.ref.key,IfNoneMatch:$.ifNoneMatch,...$.version&&{VersionId:$.version}};else z={Bucket:$.ref.bucket,Key:`${$.ref.key}${$.version?`@${$.version}`:""}`,IfNoneMatch:$.ifNoneMatch};const D=`${z.Bucket}${z.Key}${z.VersionId}`;if($.useCache!==!1){if(this.memCache.has(z))return this.memCache.get(z);if(this.diskCache){const X=await T(D,this.diskCache);if(X)return this.config.log(`${$.operation} (disk cached) ${D}`),this.memCache.set(z,Promise.resolve(X)),X}}if(!this.config.online)throw new Error(`${this.config.label} Offline and value not cached for ${D}`);const W=G(this.s3ClientLite.getObject(z)).then(async([X,J])=>{const Z={$metadata:X.$metadata,ETag:X.ETag,data:X.Body};return this.config.log(`${J}ms ${$.operation} ${$.ref.bucket}/${$.ref.key}@${$.version} => ${Z.VersionId}`),Z}).catch((X)=>{if(X?.name==="304")return{$metadata:{httpStatusCode:304},data:void 0};else throw X});if($.useCache!==!1){if(this.memCache.set(z,W),this.diskCache)W.then((X)=>{H(`${z.Bucket}${z.Key}${z.VersionId}`,X,this.diskCache).then(()=>this.config.log(`STORE ${z.Bucket}${z.Key}`))})}return W}async delete($,z={}){return this.putAll(new Map([[$,void 0]]),z)}async put($,z,D={}){return this.putAll(new Map([[$,z]]),D)}async putAll($,z={}){const D=new Map([...$].map(([X,J])=>[{bucket:X.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof X==="string"?X:X.key},J])),W=(z?.manifests||[this.config.defaultManifest]).map((X)=>({...this.config.defaultManifest,...X}));return this._putAll(D,{manifests:W,await:z.await||this.config.online?"remote":"local"})}async _putAll($,z){const D=new Map,W=new Promise(async(X,J)=>{const Z=new Map,O=[];$.forEach((Q,Y)=>{if(Q!==void 0){let U=this.config.useVersioning?void 0:L();D.set(Y,Q),O.push(this._putObject({operation:"PUT_CONTENT",ref:Y,value:Q,version:U}).then((B)=>{if(this.config.useVersioning)if(B.VersionId===void 0)throw console.error(B),Error(`Bucket ${Y.bucket} is not version enabled!`);else U=B.VersionId;Z.set(Y,U)}))}else O.push(this._deleteObject({ref:Y}).then((U)=>{Z.set(Y,void 0)}))}),await Promise.all(O).catch(J),X(Z)});return Promise.all(z.manifests.map((X)=>{return this.getOrCreateManifest(X).updateContent(D,W,{await:z.await,isLoad:z.isLoad===!0})}))}async _putObject($){const z=JSON.stringify($.value,null,2);let D;if(this.config.useVersioning)D={Bucket:$.ref.bucket,Key:$.ref.key,ContentType:"application/json",Body:z,...this.config.useChecksum&&{ChecksumSHA256:await Z0(z)}};else D={Bucket:$.ref.bucket,Key:`${$.ref.key}${$.version?`@${$.version}`:""}`,ContentType:"application/json",Body:z,...this.config.useChecksum&&{ChecksumSHA256:await Z0(z)}};const[W,X]=await G(this.s3ClientLite.putObject(D));if(this.config.log(`${X}ms ${$.operation} ${D.Bucket}/${D.Key} => ${W.VersionId}`),this.diskCache){const J=`${D.Bucket}${D.Key}${$.version||W.VersionId}`;await H(J,{$metadata:{httpStatusCode:200},etag:W.ETag,data:JSON.parse(z)},this.diskCache).then(()=>this.config.log(`STORE ${J}`))}return W}async _deleteObject($){const z={Bucket:$.ref.bucket,Key:$.ref.key},[D,W]=await G(this.s3ClientLite.deleteObject(z));return this.config.log(`${W}ms ${$.operation||"DELETE"} ${$.ref.bucket}/${$.ref.key} (${D.$metadata.httpStatusCode})}`),D}subscribe($,z,D){const W={...this.config.defaultManifest,...D?.manifest},X={key:typeof $==="string"?$:$.key,bucket:$.bucket||this.config.defaultBucket||W.bucket},J=this.getOrCreateManifest(W),Z=J.subscribe(X,z);return this.get(X,{manifest:W}).then((O)=>{this.config.log(`NOTIFY (initial) ${F(X)}`),queueMicrotask(()=>{z(O,void 0),J.poll()})}).catch((O)=>{z(void 0,O)}),Z}refresh(){return Promise.all([...this.manifests.values()].map(($)=>$.poll()))}get subscriberCount(){return[...this.manifests.values()].reduce(($,z)=>$+z.subscriberCount,0)}}export{O0 as MPS3};
{
"name": "mps3",
"description": "Provide clientside multiplayer and optimistic updates over any s3-compatible storage API",
"version": "0.0.76",
"version": "0.0.77",
"license": "MIT",

@@ -6,0 +6,0 @@ "author": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc