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.62 to 0.0.63

2

dist/mps3.js

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

var z=(J,W)=>()=>(W||J((W={exports:{}}).exports,W),W.exports);var A=z((Z0,d)=>{Z0.serialize=function(J){return J&&typeof J.toJSON==="function"?J.toJSON():J}});var p=z((U0,l)=>{var g=A().serialize;l.exports=function J(W,X){if(X=g(X),X===null||typeof X!=="object"||Array.isArray(X))return X;if(W=g(W),W===null||typeof W!=="object"||Array.isArray(W))W={};var $=Object.keys(X);for(var D=0;D<$.length;D++){var Y=$[D];if(Y==="__proto__"||Y==="constructor"||Y==="prototype")return W;if(X[Y]===null){if(W.hasOwnProperty(Y))delete W[Y]}else W[Y]=J(W[Y],X[Y])}return W}});var o=z((L0,f)=>{f.exports=function J(W,X){if(W===X)return!0;if(W&&X&&typeof W=="object"&&typeof X=="object"){if(W.constructor!==X.constructor)return!1;var $,D,Y;if(Array.isArray(W)){if($=W.length,$!=X.length)return!1;for(D=$;D--!==0;)if(!J(W[D],X[D]))return!1;return!0}if(W.constructor===RegExp)return W.source===X.source&&W.flags===X.flags;if(W.valueOf!==Object.prototype.valueOf)return W.valueOf()===X.valueOf();if(W.toString!==Object.prototype.toString)return W.toString()===X.toString();if(Y=Object.keys(W),$=Y.length,$!==Object.keys(X).length)return!1;for(D=$;D--!==0;)if(!Object.prototype.hasOwnProperty.call(X,Y[D]))return!1;for(D=$;D--!==0;){var Z=Y[D];if(!J(W[Z],X[Z]))return!1}return!0}return W!==W&&X!==X}});var i=z((P0,c)=>{var G0=function(J,W){if(J.length!==W.length)return!1;for(var X=0;X<J.length;X++)if(!F0(W[X],J[X]))return!1;return!0},F0=o(),U=A().serialize;c.exports=function J(W,X){if(W=U(W),X=U(X),W===null||X===null||typeof W!=="object"||typeof X!=="object"||Array.isArray(W)!==Array.isArray(X))return X;if(Array.isArray(W)){if(!G0(W,X))return X;return}var $={},D=Object.keys(W),Y=Object.keys(X),Z,B,G={};for(B=0;B<Y.length;B++)if(Z=Y[B],D.indexOf(Z)===-1)G[Z]=!0,$[Z]=U(X[Z]);var Q={};for(B=0;B<D.length;B++)if(Z=D[B],Y.indexOf(Z)===-1)Q[Z]=!0,$[Z]=null;else if(W[Z]!==null&&typeof W[Z]==="object"){var j=J(W[Z],X[Z]);if(j!==void 0)$[Z]=j}else if(W[Z]!==X[Z])$[Z]=U(X[Z]);return Object.keys($).length>0?$:void 0}});var t=z((V0,n)=>{n.exports=function J(W,X){if(W===null||X===null||typeof W!=="object"||typeof X!=="object"||Array.isArray(W)!==Array.isArray(X))return X;var $=JSON.parse(JSON.stringify(W));return Object.keys(X).forEach(function(D){if(W[D]!==void 0)$[D]=J(W[D],X[D]);else $[D]=X[D]}),$}});async function N(J,W){const X=await crypto.subtle.importKey("raw",typeof J==="string"?V.encode(J):J,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",X,V.encode(W))}async function b(J){return crypto.subtle.digest("SHA-256",typeof J==="string"?V.encode(J):J)}var P=function(J){return Array.prototype.map.call(new Uint8Array(J),(W)=>("0"+W.toString(16)).slice(-2)).join("")},h=function(J){return J.replace(/[!'()*]/g,(W)=>"%"+W.charCodeAt(0).toString(16).toUpperCase())},D0=function(J,W){const{hostname:X,pathname:$}=J;if(X.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(X.endsWith(".backblazeb2.com")){const B=X.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);return B!=null?["s3",B[1]]:["",""]}const D=X.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[Y,Z]=(D||["",""]).slice(1,3);if(Z==="us-gov")Z="us-gov-west-1";else if(Z==="s3"||Z==="s3-accelerate")Z="us-east-1",Y="s3";else if(Y==="iot")if(X.startsWith("iot."))Y="execute-api";else if(X.startsWith("data.jobs.iot."))Y="iot-jobs-data";else Y=$==="/mqtt"?"iotdevicegateway":"iotdata";else if(Y==="autoscaling"){const B=(W.get("X-Amz-Target")||"").split(".")[0];if(B==="AnyScaleFrontendService")Y="application-autoscaling";else if(B==="AnyScaleScalingPlannerFrontendService")Y="autoscaling-plans"}else if(Z==null&&Y.startsWith("s3-"))Z=Y.slice(3).replace(/^fips-|^external-1/,""),Y="s3";else if(Y.endsWith("-fips"))Y=Y.slice(0,-5);else if(Z&&/-\d$/.test(Y)&&!/-\d$/.test(Z))[Y,Z]=[Z,Y];return[X0[Y]||Y,Z]},V=new TextEncoder,X0={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"},$0=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class E{constructor({accessKeyId:J,secretAccessKey:W,sessionToken:X,service:$,region:D,cache:Y,retries:Z,initRetryMs:B}){if(J==null)throw new TypeError("accessKeyId is a required option");if(W==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=J,this.secretAccessKey=W,this.sessionToken=X,this.service=$,this.region=D,this.cache=Y||new Map,this.retries=Z!=null?Z:10,this.initRetryMs=B||50}async sign(J,W){if(J instanceof Request){const{method:D,url:Y,headers:Z,body:B}=J;if(W=Object.assign({method:D,url:Y,headers:Z},W),W.body==null&&Z.has("Content-Type"))W.body=B!=null&&Z.has("X-Amz-Content-Sha256")?B:await J.clone().arrayBuffer();J=Y}const X=new k(Object.assign({url:J},W,this,W&&W.aws)),$=Object.assign({},W,await X.sign());delete $.aws;try{return new Request($.url.toString(),$)}catch(D){if(D instanceof TypeError)return new Request($.url.toString(),Object.assign({duplex:"half"},$));throw D}}async fetch(J,W){for(let X=0;X<=this.retries;X++){const $=fetch(await this.sign(J,W));if(X===this.retries)return $;const D=await $;if(D.status<500&&D.status!==429)return D;await new Promise((Y)=>setTimeout(Y,Math.random()*this.initRetryMs*Math.pow(2,X)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class k{constructor({method:J,url:W,headers:X,body:$,accessKeyId:D,secretAccessKey:Y,sessionToken:Z,service:B,region:G,cache:Q,datetime:j,signQuery:r,appendSessionToken:e,allHeaders:J0,singleEncode:W0}){if(W==null)throw new TypeError("url is a required option");if(D==null)throw new TypeError("accessKeyId is a required option");if(Y==null)throw new TypeError("secretAccessKey is a required option");this.method=J||($?"POST":"GET"),this.url=new URL(W),this.headers=new Headers(X||{}),this.body=$,this.accessKeyId=D,this.secretAccessKey=Y,this.sessionToken=Z;let S,I;if(!B||!G)[S,I]=D0(this.url,this.headers);if(this.service=B||S||"",this.region=G||I||"us-east-1",this.cache=Q||new Map,this.datetime=j||(new Date()).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=r,this.appendSessionToken=e||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 q=this.signQuery?this.url.searchParams:this.headers;if(q.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)q.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((F)=>J0||!$0.has(F)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((F)=>F+":"+(F==="host"?this.url.host:(this.headers.get(F)||"").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"&&!q.has("X-Amz-Expires"))q.set("X-Amz-Expires","86400");q.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),q.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),q.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(F){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!W0)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=h(this.encodedPath);const R=new Set;this.encodedSearch=[...this.url.searchParams].filter(([F])=>{if(!F)return!1;if(this.service==="s3"){if(R.has(F))return!1;R.add(F)}return!0}).map((F)=>F.map((H)=>h(encodeURIComponent(H)))).sort(([F,H],[v,u])=>F<v?-1:F>v?1:H<u?-1:H>u?1:0).map((F)=>F.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 J=this.datetime.slice(0,8),W=[this.secretAccessKey,J,this.region,this.service].join();let X=this.cache.get(W);if(!X){const $=await N("AWS4"+this.secretAccessKey,J),D=await N($,this.region),Y=await N(D,this.service);X=await N(Y,"aws4_request"),this.cache.set(W,X)}return P(await N(X,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,P(await b(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 J=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(J==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");J=P(await b(this.body||""))}return J}}var m=(J,W)=>{const X=W.parseFromString(J,"text/xml"),$=X.getElementsByTagName("ListBucketResult")[0],D=X.getElementsByTagName("Contents"),Y=X.getElementsByTagName("CommonPrefixes")[0];if($===null||D===null)throw new Error("Invalid XML");return{$metadata:{},IsTruncated:$.getElementsByTagName("IsTruncated")[0]?.textContent==="true",Contents:Array.from(D).map((Z)=>({ChecksumAlgorithm:[Z.getElementsByTagName("ChecksumAlgorithm")[0]?.textContent],ETag:Z.getElementsByTagName("ETag")[0]?.textContent,Key:Z.getElementsByTagName("Key")[0]?.textContent,LastModified:new Date(Z.getElementsByTagName("LastModified")[0]?.textContent),Owner:{DisplayName:Z.getElementsByTagName("DisplayName")[0]?.textContent,ID:Z.getElementsByTagName("ID")[0]?.textContent},Size:Number.parseInt(Z.getElementsByTagName("Size")[0]?.textContent),StorageClass:Z.getElementsByTagName("StorageClass")[0]?.textContent})),Name:X.getElementsByTagName("Name")[0]?.textContent,Prefix:X.getElementsByTagName("Prefix")[0]?.textContent,Delimiter:X.getElementsByTagName("Delimiter")[0]?.textContent,MaxKeys:Number.parseInt(X.getElementsByTagName("MaxKeys")[0]?.textContent),CommonPrefixes:Array.from(Y?Y.getElementsByTagName("Prefix"):[],(Z)=>({Prefix:Z?.textContent})),EncodingType:X.getElementsByTagName("EncodingType")[0]?.textContent,KeyCount:Number.parseInt(X.getElementsByTagName("KeyCount")[0]?.textContent),ContinuationToken:X.getElementsByTagName("ContinuationToken")[0]?.textContent,NextContinuationToken:X.getElementsByTagName("NextContinuationToken")[0]?.textContent,StartAfter:X.getElementsByTagName("StartAfter")[0]?.textContent}};class x{client;endpoint;parser;constructor(J,W,X){this.client=J,this.endpoint=W,this.parser=X}async listObjectV2(J){const W=`${this.endpoint}/${J.Bucket}/?list-type=2&prefix=${J.Prefix}`,$=await(await this.client(W,{})).text();return m($,this.parser)}async putObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}`,X=await this.client(W,{method:"PUT",body:J.Body,headers:{"Content-Type":"application/json",...J.ChecksumSHA256&&{"x-amz-content-sha256":J.ChecksumSHA256}}});if(X.status!=200)throw new Error(`Failed to PUT: ${await X.text()}`);return{$metadata:{httpStatusCode:X.status},ETag:X.headers.get("ETag"),...X.headers.get("x-amz-version-id")&&{VersionId:X.headers.get("x-amz-version-id")}}}async deleteObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}`;return{$metadata:{httpStatusCode:(await this.client(W,{method:"DELETE"})).status}}}async getObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}?${J.VersionId?`versionId=${J.VersionId}`:""}`,X=await this.client(W,{method:"GET",headers:{"If-None-Match":J.IfNoneMatch}});if(X.status==304){const D=new Error;throw D.name="304",D}const $=X.status==404?void 0:await X.json();return{$metadata:{httpStatusCode:X.status},Body:$,ETag:X.headers.get("ETag"),...X.headers.get("x-amz-version-id")&&{VersionId:X.headers.get("x-amz-version-id")}}}}class C{key;_vals;_keys;constructor(J,W){if(this.key=J,this._vals=new Map,this._keys=new Map,W)for(let[X,$]of W)this.set(X,$)}get size(){return this._vals.size}set(J,W){const X=this.key(J);return this._vals.set(X,W),this._keys.set(X,J),this}get(J){return this._vals.get(this.key(J))}delete(J){const W=this.key(J);return this._keys.delete(W),this._vals.delete(W)}has(J){return this._vals.has(this.key(J))}values(){return this._vals.values()}keys(){return this._keys.values()}forEach(J){return this._vals.forEach((W,X,$)=>J(W,this._keys.get(X)))}}var w=()=>`${Date.now()-200}`.padStart(14,"0"),y=()=>`${Date.now()+200}`.padStart(14,"0");var O=()=>crypto.randomUUID();var M=(J)=>`${J.bucket}/${J.key}`;var L=p(),Q0=i(),M0=t();var _={previous:".",files:{},update:{}};class s{ref;handler;lastVersion;queue=Promise.resolve();constructor(J,W){this.ref=J,this.handler=W}notify(J,W,X){this.queue=this.queue.then(()=>X).then(($)=>{if(W===this.lastVersion)return;else console.log(`${J} NOTIFY ${M(this.ref)} ${W}`),this.lastVersion=W,this.handler($)})}}class K{service;ref;subscribers=new Set;poller;cache;pollInProgress=!1;authoritative_key="";authoritative_state=JSON.parse(JSON.stringify(_));optimistic_state=JSON.parse(JSON.stringify(_));pendingWrites=new Map;writtenOperations=new Map;constructor(J,W,X){console.log("New manifest",W),this.service=J,this.ref=W}observeVersionId(J){if(this.writtenOperations.has(J)){const W=this.writtenOperations.get(J);this.pendingWrites.delete(W),this.writtenOperations.delete(J)}}async get(){return this.getLatest().then((J)=>J||this.cache?.data)}async getLatest(){try{const J=await this.service._getObject({operation:"POLL_TIME",ref:this.ref,ifNoneMatch:this.cache?.etag});if(J.$metadata.httpStatusCode===304)return;if(J.data===void 0)this.authoritative_key=".";else this.authoritative_key=J.data;const W=await this.service.s3ClientLite.listObjectV2({Bucket:this.ref.bucket,Prefix:this.ref.key,StartAfter:this.authoritative_key});if(W.Contents===void 0)return this.authoritative_state=JSON.parse(JSON.stringify(_)),this.optimistic_state=JSON.parse(JSON.stringify(_)),this.authoritative_state;for(let X=W.Contents.length-1;X>=0;X--){const $=W.Contents[X].Key;if($==this.ref.key)continue;const D=w(),Y=await this.service._getObject({operation:"LOOK_BACK",ref:{bucket:this.ref.bucket,key:$}});if(Y.data===void 0)throw new Error("empty data");if(Y.data.previous<D){this.authoritative_key=Y.data.previous,this.authoritative_state=Y.data;break}}for(let X=0;X<W.Contents.length;X++){const $=W.Contents[X].Key;if($==this.ref.key)continue;const D=await this.service._getObject({operation:"SWEEP",ref:{bucket:this.ref.bucket,key:$}}),Y=$.substring($.lastIndexOf("@")+1),Z=w();if($<this.authoritative_key);else if(Y>=Z)this.optimistic_state=L(this.optimistic_state,D.data?.update);else this.authoritative_state=L(this.authoritative_state,D.data?.update),this.authoritative_key=$;this.observeVersionId(Y)}return this.authoritative_state}catch(J){if(J.name==="NoSuchKey")return this.authoritative_state=_,this.authoritative_state;else throw J}}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 J=await this.getLatest();if(J===void 0){this.pollInProgress=!1;return}this.subscribers.forEach(async(W)=>{const X=J.files[M(W.ref)];if(X){const $=this.service._getObject({operation:"GET_CONTENT",ref:W.ref,version:X.version});W.notify(this.service.config.label,X.version,$.then((D)=>D.data))}else if(X===null)W.notify(this.service.config.label,void 0,Promise.resolve(void 0))}),this.pollInProgress=!1}async updateContent(J,W){this.pendingWrites.set(W,J);try{const X=await W,$=await this.get();$.previous=this.authoritative_key,$.update={files:{}};for(let[B,G]of X){const Q=M(B);if(G){const j={version:G};$.update.files[Q]=j}else $.update.files[Q]=null}const D=y()+"_"+O().substring(0,2),Y=this.ref.key+"@"+D;await this.service._putObject({operation:"PUT_MANIFEST",ref:{key:Y,bucket:this.ref.bucket},value:$});const Z=await this.service._putObject({operation:"PUT_POLL",ref:{key:this.ref.key,bucket:this.ref.bucket},value:this.authoritative_key});return this.writtenOperations.set(D,W),this.poll(),Z}catch(X){throw console.error(X),this.pendingWrites.delete(W),X}}async getOptimisticVersion(J){return await this.get(),this.optimistic_state.files[M(J)]?.version}subscribe(J,W){console.log(`SUBSCRIBE ${M(J)} ${this.subscriberCount+1}`);const X=new s(J,W);return this.subscribers.add(X),()=>this.subscribers.delete(X)}get subscriberCount(){return this.subscribers.size}}async function a(J){const W=(new TextEncoder()).encode(J),X=await crypto.subtle.digest("SHA-256",W);return[...new Uint8Array(X)].map(($)=>$.toString(16).padStart(2,"0")).join("")}class j0{config;s3ClientLite;manifests=new C(M);getCache=new C((J)=>`${J.Bucket}${J.Key}${J.VersionId}${J.IfNoneMatch}`);constructor(J){if(this.config={...J,label:J.label||O().substring(0,3),useChecksum:J.useChecksum===!1?!1:!0,useVersioning:J.useVersioning||!1,pollFrequency:J.pollFrequency||1000,defaultManifest:{bucket:J.defaultManifest?.bucket||J.defaultBucket,key:J.defaultManifest?.key||"manifest.json"}},this.config.s3Config?.credentials instanceof Function)throw Error("We can't do that yet");const W=J.s3Config.endpoint||`https://s3.${J.s3Config.region}.amazonaws.com`;let X;if(this.config.s3Config?.credentials){const $=new E({accessKeyId:this.config.s3Config.credentials.accessKeyId,secretAccessKey:this.config.s3Config.credentials.secretAccessKey,sessionToken:this.config.s3Config.credentials.sessionToken,service:"s3",retries:0});X=(...D)=>$.fetch(...D)}else X=fetch;this.s3ClientLite=new x(X,W,J.parser||new DOMParser)}getOrCreateManifest(J){if(!this.manifests.has(J))this.manifests.set(J,new K(this,J));return this.manifests.get(J)}async get(J,W={}){const X={...this.config.defaultManifest,...W.manifest},$=this.getOrCreateManifest(X),D={bucket:J.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof J==="string"?J:J.key};let Y=!1,Z=void 0;for(let[G,Q]of $.pendingWrites)if(Q.has(D))Y=!0,Z=Q.get(D);if(Y)return console.log(`${this.config.label} get (cached) ${M(D)}`),Z;const B=await $.getOptimisticVersion(D);if(B===void 0)return;return(await this._getObject({operation:"GET",ref:D,version:B})).data}async _getObject(J){let W;if(this.config.useVersioning)W={Bucket:J.ref.bucket,Key:J.ref.key,IfNoneMatch:J.ifNoneMatch,...J.version&&{VersionId:J.version}};else W={Bucket:J.ref.bucket,Key:`${J.ref.key}${J.version?`@${J.version}`:""}`,IfNoneMatch:J.ifNoneMatch};if(this.getCache.has(W))return await this.getCache.get(W);const X=this.s3ClientLite.getObject(W).then(async($)=>{const D={...$,data:$.Body};return console.log(`${this.config.label} ${J.operation} ${J.ref.bucket}/${J.ref.key}@${J.version} => ${D.VersionId} ${D.data}}`),this.getCache.set(W,X),D}).catch(($)=>{if($?.name==="304")return{$metadata:{httpStatusCode:304},data:void 0};else throw $});return X}async delete(J,W={}){return this.putAll(new Map([[J,void 0]]),W)}async put(J,W,X={}){return this.putAll(new Map([[J,W]]),X)}async putAll(J,W={}){const X=new C(M,[...J].map(([D,Y])=>[{bucket:D.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof D==="string"?D:D.key},Y])),$=(W?.manifests||[this.config.defaultManifest]).map((D)=>({...this.config.defaultManifest,...D}));return this._putAll(X,{manifests:$})}async _putAll(J,W){const X=new Promise(async($,D)=>{const Y=new Map,Z=[];J.forEach((B,G)=>{if(B!==void 0){let Q=this.config.useVersioning?void 0:O();Z.push(this._putObject({operation:"PUT_CONTENT",ref:G,value:B,version:Q}).then((j)=>{if(this.config.useVersioning)if(j.VersionId===void 0)throw console.error(j),Error(`Bucket ${G.bucket} is not version enabled!`);else Q=j.VersionId;Y.set(G,Q)}))}else Z.push(this._deleteObject({ref:G}).then((Q)=>{Y.set(G,void 0)}))}),await Promise.all(Z).catch(D),$(Y)});return Promise.all(W.manifests.map(($)=>{return this.getOrCreateManifest($).updateContent(J,X)}))}async _putObject(J){const W=JSON.stringify(J.value,null,2);let X;if(this.config.useVersioning)X={Bucket:J.ref.bucket,Key:J.ref.key,ContentType:"application/json",Body:W,...this.config.useChecksum&&{ChecksumSHA256:await a(W)}};else X={Bucket:J.ref.bucket,Key:`${J.ref.key}${J.version?`@${J.version}`:""}`,ContentType:"application/json",Body:W,...this.config.useChecksum&&{ChecksumSHA256:await a(W)}};const $=await this.s3ClientLite.putObject(X);return console.log(`${this.config.label} ${J.operation} ${X.Bucket}/${X.Key} => ${$.VersionId}`),$}async _deleteObject(J){const W={Bucket:J.ref.bucket,Key:J.ref.key},X=await this.s3ClientLite.deleteObject(W);return console.log(`${this.config.label} DELETE ${J.ref.bucket}/${J.ref.key} => ${X.VersionId}`),X}subscribe(J,W,X){const $={...this.config.defaultManifest,...X?.manifest},D={key:typeof J==="string"?J:J.key,bucket:J.bucket||this.config.defaultBucket||$.bucket},Y=this.getOrCreateManifest($),Z=Y.subscribe(D,W);return this.get(D,{manifest:$}).then((B)=>{console.log(`${this.config.label} NOTIFY (initial) ${M(D)}`),queueMicrotask(()=>{W(B),Y.poll()})}),Z}refresh(){return Promise.all([...this.manifests.values()].map((J)=>J.poll()))}get subscriberCount(){return[...this.manifests.values()].reduce((J,W)=>J+W.subscriberCount,0)}}export{j0 as MPS3};
var N=(J,W)=>()=>(W||J((W={exports:{}}).exports,W),W.exports);var A=N((G0,d)=>{G0.serialize=function(J){return J&&typeof J.toJSON==="function"?J.toJSON():J}});var p=N((U0,l)=>{var g=A().serialize;l.exports=function J(W,X){if(X=g(X),X===null||typeof X!=="object"||Array.isArray(X))return X;if(W=g(W),W===null||typeof W!=="object"||Array.isArray(W))W={};var $=Object.keys(X);for(var B=0;B<$.length;B++){var D=$[B];if(D==="__proto__"||D==="constructor"||D==="prototype")return W;if(X[D]===null){if(W.hasOwnProperty(D))delete W[D]}else W[D]=J(W[D],X[D])}return W}});var o=N((L0,f)=>{f.exports=function J(W,X){if(W===X)return!0;if(W&&X&&typeof W=="object"&&typeof X=="object"){if(W.constructor!==X.constructor)return!1;var $,B,D;if(Array.isArray(W)){if($=W.length,$!=X.length)return!1;for(B=$;B--!==0;)if(!J(W[B],X[B]))return!1;return!0}if(W.constructor===RegExp)return W.source===X.source&&W.flags===X.flags;if(W.valueOf!==Object.prototype.valueOf)return W.valueOf()===X.valueOf();if(W.toString!==Object.prototype.toString)return W.toString()===X.toString();if(D=Object.keys(W),$=D.length,$!==Object.keys(X).length)return!1;for(B=$;B--!==0;)if(!Object.prototype.hasOwnProperty.call(X,D[B]))return!1;for(B=$;B--!==0;){var G=D[B];if(!J(W[G],X[G]))return!1}return!0}return W!==W&&X!==X}});var i=N((E0,c)=>{var F0=function(J,W){if(J.length!==W.length)return!1;for(var X=0;X<J.length;X++)if(!Z0(W[X],J[X]))return!1;return!0},Z0=o(),U=A().serialize;c.exports=function J(W,X){if(W=U(W),X=U(X),W===null||X===null||typeof W!=="object"||typeof X!=="object"||Array.isArray(W)!==Array.isArray(X))return X;if(Array.isArray(W)){if(!F0(W,X))return X;return}var $={},B=Object.keys(W),D=Object.keys(X),G,Y,F={};for(Y=0;Y<D.length;Y++)if(G=D[Y],B.indexOf(G)===-1)F[G]=!0,$[G]=U(X[G]);var Q={};for(Y=0;Y<B.length;Y++)if(G=B[Y],D.indexOf(G)===-1)Q[G]=!0,$[G]=null;else if(W[G]!==null&&typeof W[G]==="object"){var z=J(W[G],X[G]);if(z!==void 0)$[G]=z}else if(W[G]!==X[G])$[G]=U(X[G]);return Object.keys($).length>0?$:void 0}});var s=N((P0,n)=>{n.exports=function J(W,X){if(W===null||X===null||typeof W!=="object"||typeof X!=="object"||Array.isArray(W)!==Array.isArray(X))return X;var $=JSON.parse(JSON.stringify(W));return Object.keys(X).forEach(function(B){if(W[B]!==void 0)$[B]=J(W[B],X[B]);else $[B]=X[B]}),$}});async function j(J,W){const X=await crypto.subtle.importKey("raw",typeof J==="string"?P.encode(J):J,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",X,P.encode(W))}async function b(J){return crypto.subtle.digest("SHA-256",typeof J==="string"?P.encode(J):J)}var E=function(J){return Array.prototype.map.call(new Uint8Array(J),(W)=>("0"+W.toString(16)).slice(-2)).join("")},h=function(J){return J.replace(/[!'()*]/g,(W)=>"%"+W.charCodeAt(0).toString(16).toUpperCase())},B0=function(J,W){const{hostname:X,pathname:$}=J;if(X.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(X.endsWith(".backblazeb2.com")){const Y=X.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);return Y!=null?["s3",Y[1]]:["",""]}const B=X.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[D,G]=(B||["",""]).slice(1,3);if(G==="us-gov")G="us-gov-west-1";else if(G==="s3"||G==="s3-accelerate")G="us-east-1",D="s3";else if(D==="iot")if(X.startsWith("iot."))D="execute-api";else if(X.startsWith("data.jobs.iot."))D="iot-jobs-data";else D=$==="/mqtt"?"iotdevicegateway":"iotdata";else if(D==="autoscaling"){const Y=(W.get("X-Amz-Target")||"").split(".")[0];if(Y==="AnyScaleFrontendService")D="application-autoscaling";else if(Y==="AnyScaleScalingPlannerFrontendService")D="autoscaling-plans"}else if(G==null&&D.startsWith("s3-"))G=D.slice(3).replace(/^fips-|^external-1/,""),D="s3";else if(D.endsWith("-fips"))D=D.slice(0,-5);else if(G&&/-\d$/.test(D)&&!/-\d$/.test(G))[D,G]=[G,D];return[X0[D]||D,G]},P=new TextEncoder,X0={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"},$0=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class V{constructor({accessKeyId:J,secretAccessKey:W,sessionToken:X,service:$,region:B,cache:D,retries:G,initRetryMs:Y}){if(J==null)throw new TypeError("accessKeyId is a required option");if(W==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=J,this.secretAccessKey=W,this.sessionToken=X,this.service=$,this.region=B,this.cache=D||new Map,this.retries=G!=null?G:10,this.initRetryMs=Y||50}async sign(J,W){if(J instanceof Request){const{method:B,url:D,headers:G,body:Y}=J;if(W=Object.assign({method:B,url:D,headers:G},W),W.body==null&&G.has("Content-Type"))W.body=Y!=null&&G.has("X-Amz-Content-Sha256")?Y:await J.clone().arrayBuffer();J=D}const X=new k(Object.assign({url:J},W,this,W&&W.aws)),$=Object.assign({},W,await X.sign());delete $.aws;try{return new Request($.url.toString(),$)}catch(B){if(B instanceof TypeError)return new Request($.url.toString(),Object.assign({duplex:"half"},$));throw B}}async fetch(J,W){for(let X=0;X<=this.retries;X++){const $=fetch(await this.sign(J,W));if(X===this.retries)return $;const B=await $;if(B.status<500&&B.status!==429)return B;await new Promise((D)=>setTimeout(D,Math.random()*this.initRetryMs*Math.pow(2,X)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class k{constructor({method:J,url:W,headers:X,body:$,accessKeyId:B,secretAccessKey:D,sessionToken:G,service:Y,region:F,cache:Q,datetime:z,signQuery:r,appendSessionToken:e,allHeaders:J0,singleEncode:W0}){if(W==null)throw new TypeError("url is a required option");if(B==null)throw new TypeError("accessKeyId is a required option");if(D==null)throw new TypeError("secretAccessKey is a required option");this.method=J||($?"POST":"GET"),this.url=new URL(W),this.headers=new Headers(X||{}),this.body=$,this.accessKeyId=B,this.secretAccessKey=D,this.sessionToken=G;let S,I;if(!Y||!F)[S,I]=B0(this.url,this.headers);if(this.service=Y||S||"",this.region=F||I||"us-east-1",this.cache=Q||new Map,this.datetime=z||(new Date()).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=r,this.appendSessionToken=e||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 M=this.signQuery?this.url.searchParams:this.headers;if(M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)M.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((Z)=>J0||!$0.has(Z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((Z)=>Z+":"+(Z==="host"?this.url.host:(this.headers.get(Z)||"").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"&&!M.has("X-Amz-Expires"))M.set("X-Amz-Expires","86400");M.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),M.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),M.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(Z){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!W0)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=h(this.encodedPath);const R=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if(R.has(Z))return!1;R.add(Z)}return!0}).map((Z)=>Z.map((C)=>h(encodeURIComponent(C)))).sort(([Z,C],[v,u])=>Z<v?-1:Z>v?1:C<u?-1:C>u?1:0).map((Z)=>Z.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 J=this.datetime.slice(0,8),W=[this.secretAccessKey,J,this.region,this.service].join();let X=this.cache.get(W);if(!X){const $=await j("AWS4"+this.secretAccessKey,J),B=await j($,this.region),D=await j(B,this.service);X=await j(D,"aws4_request"),this.cache.set(W,X)}return E(await j(X,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await b(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 J=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(J==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");J=E(await b(this.body||""))}return J}}var m=(J,W)=>{const X=W.parseFromString(J,"text/xml"),$=X.getElementsByTagName("ListBucketResult")[0],B=X.getElementsByTagName("Contents"),D=X.getElementsByTagName("CommonPrefixes")[0];if($===null||B===null)throw new Error("Invalid XML");return{$metadata:{},IsTruncated:$.getElementsByTagName("IsTruncated")[0]?.textContent==="true",Contents:Array.from(B).map((G)=>({ChecksumAlgorithm:[G.getElementsByTagName("ChecksumAlgorithm")[0]?.textContent],ETag:G.getElementsByTagName("ETag")[0]?.textContent,Key:G.getElementsByTagName("Key")[0]?.textContent,LastModified:new Date(G.getElementsByTagName("LastModified")[0]?.textContent),Owner:{DisplayName:G.getElementsByTagName("DisplayName")[0]?.textContent,ID:G.getElementsByTagName("ID")[0]?.textContent},Size:Number.parseInt(G.getElementsByTagName("Size")[0]?.textContent),StorageClass:G.getElementsByTagName("StorageClass")[0]?.textContent})),Name:X.getElementsByTagName("Name")[0]?.textContent,Prefix:X.getElementsByTagName("Prefix")[0]?.textContent,Delimiter:X.getElementsByTagName("Delimiter")[0]?.textContent,MaxKeys:Number.parseInt(X.getElementsByTagName("MaxKeys")[0]?.textContent),CommonPrefixes:Array.from(D?D.getElementsByTagName("Prefix"):[],(G)=>({Prefix:G?.textContent})),EncodingType:X.getElementsByTagName("EncodingType")[0]?.textContent,KeyCount:Number.parseInt(X.getElementsByTagName("KeyCount")[0]?.textContent),ContinuationToken:X.getElementsByTagName("ContinuationToken")[0]?.textContent,NextContinuationToken:X.getElementsByTagName("NextContinuationToken")[0]?.textContent,StartAfter:X.getElementsByTagName("StartAfter")[0]?.textContent}};class x{client;endpoint;parser;constructor(J,W,X){this.client=J,this.endpoint=W,this.parser=X}async listObjectV2(J){const W=`${this.endpoint}/${J.Bucket}/?list-type=2&prefix=${J.Prefix}`,$=await(await this.client(W,{})).text();return m($,this.parser)}async putObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}`,X=await this.client(W,{method:"PUT",body:J.Body,headers:{"Content-Type":"application/json",...J.ChecksumSHA256&&{"x-amz-content-sha256":J.ChecksumSHA256}}});if(X.status!=200)throw new Error(`Failed to PUT: ${await X.text()}`);return{$metadata:{httpStatusCode:X.status},ETag:X.headers.get("ETag"),...X.headers.get("x-amz-version-id")&&{VersionId:X.headers.get("x-amz-version-id")}}}async deleteObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}`;return{$metadata:{httpStatusCode:(await this.client(W,{method:"DELETE"})).status}}}async getObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}?${J.VersionId?`versionId=${J.VersionId}`:""}`,X=await this.client(W,{method:"GET",headers:{"If-None-Match":J.IfNoneMatch}});if(X.status==304){const B=new Error;throw B.name="304",B}const $=X.status==404?void 0:await X.json();return{$metadata:{httpStatusCode:X.status},Body:$,ETag:X.headers.get("ETag"),...X.headers.get("x-amz-version-id")&&{VersionId:X.headers.get("x-amz-version-id")}}}}class O{key;_vals;_keys;constructor(J,W){if(this.key=J,this._vals=new Map,this._keys=new Map,W)for(let[X,$]of W)this.set(X,$)}get size(){return this._vals.size}set(J,W){const X=this.key(J);return this._vals.set(X,W),this._keys.set(X,J),this}get(J){return this._vals.get(this.key(J))}delete(J){const W=this.key(J);return this._keys.delete(W),this._vals.delete(W)}has(J){return this._vals.has(this.key(J))}values(){return this._vals.values()}keys(){return this._keys.values()}forEach(J){return this._vals.forEach((W,X,$)=>J(W,this._keys.get(X)))}}var w=()=>`${Date.now()-200}`.padStart(14,"0"),y=()=>`${Date.now()+200}`.padStart(14,"0");var H=()=>crypto.randomUUID();var q=(J)=>`${J.bucket}/${J.key}`;var L=p(),Q0=i(),q0=s();var _={previous:".",files:{},update:{}};class t{ref;handler;lastVersion;queue=Promise.resolve();constructor(J,W){this.ref=J,this.handler=W}notify(J,W,X){this.queue=this.queue.then(()=>X).then(($)=>{if(W===this.lastVersion)return;else console.log(`${J} NOTIFY ${q(this.ref)} ${W}`),this.lastVersion=W,this.handler($)})}}class K{service;ref;subscribers=new Set;poller;cache;pollInProgress=!1;authoritative_key="";authoritative_state=JSON.parse(JSON.stringify(_));optimistic_state=JSON.parse(JSON.stringify(_));pendingWrites=new Map;writtenOperations=new Map;constructor(J,W,X){console.log("New manifest",W),this.service=J,this.ref=W}observeVersionId(J){if(this.writtenOperations.has(J)){const W=this.writtenOperations.get(J);this.pendingWrites.delete(W),this.writtenOperations.delete(J)}}async get(){return this.getLatest().then((J)=>J||this.cache?.data)}async getLatest(){try{const J=await this.service._getObject({operation:"POLL_TIME",ref:this.ref,ifNoneMatch:this.cache?.etag});if(J.$metadata.httpStatusCode===304)return;if(J.data===void 0)this.authoritative_key=".";else this.authoritative_key=J.data;const W=await this.service.s3ClientLite.listObjectV2({Bucket:this.ref.bucket,Prefix:this.ref.key,StartAfter:this.authoritative_key});if(W.Contents===void 0)return this.authoritative_state=JSON.parse(JSON.stringify(_)),this.optimistic_state=JSON.parse(JSON.stringify(_)),this.authoritative_state;for(let X=W.Contents.length-1;X>=0;X--){const $=W.Contents[X].Key;if($==this.ref.key)continue;const B=w(),D=await this.service._getObject({operation:"LOOK_BACK",ref:{bucket:this.ref.bucket,key:$}});if(D.data===void 0)throw new Error("empty data");if(D.data.previous<B){this.authoritative_key=D.data.previous,this.authoritative_state=D.data;break}}for(let X=0;X<W.Contents.length;X++){const $=W.Contents[X].Key;if($==this.ref.key)continue;const B=await this.service._getObject({operation:"SWEEP",ref:{bucket:this.ref.bucket,key:$}}),D=$.substring($.lastIndexOf("@")+1),G=w();if($<this.authoritative_key);else if(D>=G)this.optimistic_state=L(this.optimistic_state,B.data?.update);else this.authoritative_state=L(this.authoritative_state,B.data?.update),this.authoritative_key=$;this.observeVersionId(D)}return this.authoritative_state}catch(J){if(J.name==="NoSuchKey")return this.authoritative_state=_,this.authoritative_state;else throw J}}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 J=await this.getLatest();if(J===void 0){this.pollInProgress=!1;return}this.subscribers.forEach(async(W)=>{const X=J.files[q(W.ref)];if(X){const $=this.service._getObject({operation:"GET_CONTENT",ref:W.ref,version:X.version});W.notify(this.service.config.label,X.version,$.then((B)=>B.data))}else if(X===null)W.notify(this.service.config.label,void 0,Promise.resolve(void 0))}),this.pollInProgress=!1}async updateContent(J,W){this.pendingWrites.set(W,J);try{const X=await W,$=await this.get();$.previous=this.authoritative_key,$.update={files:{}};for(let[Y,F]of X){const Q=q(Y);if(F){const z={version:F};$.update.files[Q]=z}else $.update.files[Q]=null}const B=y()+"_"+H().substring(0,2),D=this.ref.key+"@"+B;await this.service._putObject({operation:"PUT_MANIFEST",ref:{key:D,bucket:this.ref.bucket},value:$});const G=await this.service._putObject({operation:"PUT_POLL",ref:{key:this.ref.key,bucket:this.ref.bucket},value:this.authoritative_key});return this.writtenOperations.set(B,W),this.poll(),G}catch(X){throw console.error(X),this.pendingWrites.delete(W),X}}async getOptimisticVersion(J){return await this.get(),this.optimistic_state.files[q(J)]?.version}subscribe(J,W){console.log(`SUBSCRIBE ${q(J)} ${this.subscriberCount+1}`);const X=new t(J,W);return this.subscribers.add(X),()=>this.subscribers.delete(X)}get subscriberCount(){return this.subscribers.size}}async function a(J){const W=(new TextEncoder()).encode(J),X=await crypto.subtle.digest("SHA-256",W);return[...new Uint8Array(X)].map(($)=>$.toString(16).padStart(2,"0")).join("")}class z0{config;s3ClientLite;manifests=new O(q);getCache=new O((J)=>`${J.Bucket}${J.Key}${J.VersionId}${J.IfNoneMatch}`);constructor(J){if(this.config={...J,label:J.label||H().substring(0,3),useChecksum:J.useChecksum===!1?!1:!0,useVersioning:J.useVersioning||!1,pollFrequency:J.pollFrequency||1000,defaultManifest:{bucket:J.defaultManifest?.bucket||J.defaultBucket,key:J.defaultManifest?.key||"manifest.json"}},this.config.s3Config?.credentials instanceof Function)throw Error("We can't do that yet");const W=J.s3Config.endpoint||`https://s3.${J.s3Config.region}.amazonaws.com`;let X;if(this.config.s3Config?.credentials){const $=new V({accessKeyId:this.config.s3Config.credentials.accessKeyId,secretAccessKey:this.config.s3Config.credentials.secretAccessKey,sessionToken:this.config.s3Config.credentials.sessionToken,service:"s3",retries:0});X=(...B)=>$.fetch(...B)}else X=(global||window).fetch.bind(global||window);this.s3ClientLite=new x(X,W,J.parser||new DOMParser)}getOrCreateManifest(J){if(!this.manifests.has(J))this.manifests.set(J,new K(this,J));return this.manifests.get(J)}async get(J,W={}){const X={...this.config.defaultManifest,...W.manifest},$=this.getOrCreateManifest(X),B={bucket:J.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof J==="string"?J:J.key};let D=!1,G=void 0;for(let[F,Q]of $.pendingWrites)if(Q.has(B))D=!0,G=Q.get(B);if(D)return console.log(`${this.config.label} get (cached) ${q(B)}`),G;const Y=await $.getOptimisticVersion(B);if(Y===void 0)return;return(await this._getObject({operation:"GET",ref:B,version:Y})).data}async _getObject(J){let W;if(this.config.useVersioning)W={Bucket:J.ref.bucket,Key:J.ref.key,IfNoneMatch:J.ifNoneMatch,...J.version&&{VersionId:J.version}};else W={Bucket:J.ref.bucket,Key:`${J.ref.key}${J.version?`@${J.version}`:""}`,IfNoneMatch:J.ifNoneMatch};if(this.getCache.has(W))return await this.getCache.get(W);const X=this.s3ClientLite.getObject(W).then(async($)=>{const B={...$,data:$.Body};return console.log(`${this.config.label} ${J.operation} ${J.ref.bucket}/${J.ref.key}@${J.version} => ${B.VersionId} ${B.data}}`),this.getCache.set(W,X),B}).catch(($)=>{if($?.name==="304")return{$metadata:{httpStatusCode:304},data:void 0};else throw $});return X}async delete(J,W={}){return this.putAll(new Map([[J,void 0]]),W)}async put(J,W,X={}){return this.putAll(new Map([[J,W]]),X)}async putAll(J,W={}){const X=new O(q,[...J].map(([B,D])=>[{bucket:B.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof B==="string"?B:B.key},D])),$=(W?.manifests||[this.config.defaultManifest]).map((B)=>({...this.config.defaultManifest,...B}));return this._putAll(X,{manifests:$})}async _putAll(J,W){const X=new Promise(async($,B)=>{const D=new Map,G=[];J.forEach((Y,F)=>{if(Y!==void 0){let Q=this.config.useVersioning?void 0:H();G.push(this._putObject({operation:"PUT_CONTENT",ref:F,value:Y,version:Q}).then((z)=>{if(this.config.useVersioning)if(z.VersionId===void 0)throw console.error(z),Error(`Bucket ${F.bucket} is not version enabled!`);else Q=z.VersionId;D.set(F,Q)}))}else G.push(this._deleteObject({ref:F}).then((Q)=>{D.set(F,void 0)}))}),await Promise.all(G).catch(B),$(D)});return Promise.all(W.manifests.map(($)=>{return this.getOrCreateManifest($).updateContent(J,X)}))}async _putObject(J){const W=JSON.stringify(J.value,null,2);let X;if(this.config.useVersioning)X={Bucket:J.ref.bucket,Key:J.ref.key,ContentType:"application/json",Body:W,...this.config.useChecksum&&{ChecksumSHA256:await a(W)}};else X={Bucket:J.ref.bucket,Key:`${J.ref.key}${J.version?`@${J.version}`:""}`,ContentType:"application/json",Body:W,...this.config.useChecksum&&{ChecksumSHA256:await a(W)}};const $=await this.s3ClientLite.putObject(X);return console.log(`${this.config.label} ${J.operation} ${X.Bucket}/${X.Key} => ${$.VersionId}`),$}async _deleteObject(J){const W={Bucket:J.ref.bucket,Key:J.ref.key},X=await this.s3ClientLite.deleteObject(W);return console.log(`${this.config.label} DELETE ${J.ref.bucket}/${J.ref.key} => ${X.VersionId}`),X}subscribe(J,W,X){const $={...this.config.defaultManifest,...X?.manifest},B={key:typeof J==="string"?J:J.key,bucket:J.bucket||this.config.defaultBucket||$.bucket},D=this.getOrCreateManifest($),G=D.subscribe(B,W);return this.get(B,{manifest:$}).then((Y)=>{console.log(`${this.config.label} NOTIFY (initial) ${q(B)}`),queueMicrotask(()=>{W(Y),D.poll()})}),G}refresh(){return Promise.all([...this.manifests.values()].map((J)=>J.poll()))}get subscriberCount(){return[...this.manifests.values()].reduce((J,W)=>J+W.subscriberCount,0)}}export{z0 as MPS3};
{
"name": "mps3",
"description": "Provide clientside multiplayer and optimistic updates over any s3-compatible storage API",
"version": "0.0.62",
"version": "0.0.63",
"license": "MIT",

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

SocketSocket SOC 2 Logo

Product

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

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc