Socket
Socket
Sign inDemoInstall

mps3

Package Overview
Dependencies
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mps3 - npm Package Compare versions

Comparing version 0.0.61 to 0.0.62

2

dist/mps3.js

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

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

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

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc