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.64 to 0.0.65

2

dist/mps3.js

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

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

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

@@ -72,7 +72,7 @@ # MPS3

There is no authorization. Do one thing and do it well. Every use-case needs different authorization. A malicious user could sabotage the manifest file if they have unrestricted write permissions to the manifest file, but not all use-cases have malicious users.
There is no authorization. Do one thing and do it well. Every use-case needs different authorization. A malicious user could sabotage the manifest file if they have unrestricted write permissions to the manifest file, but not all use-cases have malicious users. There are a few options:-
- Share access key only to trusted personal.
- If using S3 and IAM, issue STS tokens that grant access to a subpath of a bucket per user/team
- For public use, use a third-party auth solution and a authenticating proxy. Verify manifest changes are valid during passthrough
- For public use, use a third-party auth solution and a authenticating proxy. Verify manifest changes are valid during passthrough, there is an example of an proxy configuration [here](mps3-proxy.endpointservices.workers.dev/) that hides credentials from the browser using a CloudFlare worker.

@@ -79,0 +79,0 @@

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