@milaboratories/pl-drivers 1.5.64 → 1.5.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/drivers/download_blob/download_blob.d.ts +12 -3
  2. package/dist/drivers/download_blob/download_blob.d.ts.map +1 -1
  3. package/dist/drivers/download_blob/sparse_cache/cache.d.ts +79 -0
  4. package/dist/drivers/download_blob/sparse_cache/cache.d.ts.map +1 -0
  5. package/dist/drivers/download_blob/sparse_cache/file.d.ts +8 -0
  6. package/dist/drivers/download_blob/sparse_cache/file.d.ts.map +1 -0
  7. package/dist/drivers/download_blob/sparse_cache/ranges.d.ts +46 -0
  8. package/dist/drivers/download_blob/sparse_cache/ranges.d.ts.map +1 -0
  9. package/dist/drivers/helpers/download_remote_handle.d.ts +4 -1
  10. package/dist/drivers/helpers/download_remote_handle.d.ts.map +1 -1
  11. package/dist/index.js +2 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.mjs +1584 -1391
  14. package/dist/index.mjs.map +1 -1
  15. package/package.json +10 -9
  16. package/src/drivers/download_blob/download_blob.test.ts +48 -41
  17. package/src/drivers/download_blob/download_blob.ts +38 -39
  18. package/src/drivers/download_blob/sparse_cache/cache.test.ts +371 -0
  19. package/src/drivers/download_blob/sparse_cache/cache.ts +240 -0
  20. package/src/drivers/download_blob/sparse_cache/create_sparse_file_script.js +123 -0
  21. package/src/drivers/download_blob/sparse_cache/file.ts +49 -0
  22. package/src/drivers/download_blob/sparse_cache/ranges.test.ts +115 -0
  23. package/src/drivers/download_blob/sparse_cache/ranges.ts +93 -0
  24. package/src/drivers/download_url.ts +1 -1
  25. package/src/drivers/helpers/download_remote_handle.ts +16 -9
  26. package/src/drivers/logs.test.ts +18 -6
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var ht=Object.defineProperty;var ut=(s,e,t)=>e in s?ht(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var h=(s,e,t)=>ut(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@milaboratories/pl-client"),pt=require("node:fs/promises"),Re=require("undici"),y=require("@protobuf-ts/runtime-rpc"),i=require("@protobuf-ts/runtime"),p=require("@milaboratories/ts-helpers"),F=require("node:fs"),k=require("node:path"),L=require("node:stream"),ae=require("node:stream/consumers"),f=require("@milaboratories/computable"),ne=require("@milaboratories/pl-model-common"),m=require("@milaboratories/pl-tree"),gt=require("denque"),U=require("node:crypto"),Ie=require("node:os"),ft=require("node:readline/promises"),P=require("zod"),mt=require("node:zlib"),wt=require("tar-fs"),yt=require("decompress"),Se=require("node:timers/promises"),Tt=require("node:assert"),bt=require("node:util"),kt=require("node:child_process");function R(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const w=R(pt),le=R(F),T=R(k),Te=R(Ie),Pt=R(ft),De=R(mt),re=R(wt);class Lt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Lt;class Ut extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Ut;class Rt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const It=new Rt;class St extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Response",[{no:1,name:"parts_count",kind:"scalar",T:4,L:0},{no:2,name:"uploaded_parts",kind:"scalar",repeat:1,T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.partsCount=0n,t.uploadedParts=[],e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.partsCount=e.uint64().toBigInt();break;case 2:if(d===i.WireType.LengthDelimited)for(let A=e.int32()+e.pos;e.pos<A;)o.uploadedParts.push(e.uint64().toBigInt());else o.uploadedParts.push(e.uint64().toBigInt());break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){if(e.partsCount!==0n&&t.tag(1,i.WireType.Varint).uint64(e.partsCount),e.uploadedParts.length){t.tag(2,i.WireType.LengthDelimited).fork();for(let o=0;o<e.uploadedParts.length;o++)t.uint64(e.uploadedParts[o]);t.join()}const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Dt=new St;class vt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new vt;class Nt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"bytes_processed",kind:"scalar",T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.bytesProcessed=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.bytesProcessed=e.int64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.bytesProcessed!==0n&&t.tag(2,i.WireType.Varint).int64(e.bytesProcessed);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Ct=new Nt;class Bt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const $t=new Bt;class Wt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Wt;class Ft extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"part_number",kind:"scalar",T:4,L:0},{no:3,name:"uploaded_part_size",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.partNumber=0n,t.uploadedPartSize=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.partNumber=e.uint64().toBigInt();break;case 3:o.uploadedPartSize=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.partNumber!==0n&&t.tag(2,i.WireType.Varint).uint64(e.partNumber),e.uploadedPartSize!==0n&&t.tag(3,i.WireType.Varint).uint64(e.uploadedPartSize);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const _t=new Ft;class Et extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.name!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.value);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const j=new Et;class Mt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Response",[{no:1,name:"upload_url",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"headers",kind:"message",repeat:1,T:()=>j},{no:4,name:"chunk_start",kind:"scalar",T:4,L:0},{no:5,name:"chunk_end",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.uploadUrl="",t.method="",t.headers=[],t.chunkStart=0n,t.chunkEnd=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.uploadUrl=e.string();break;case 2:o.method=e.string();break;case 3:o.headers.push(j.internalBinaryRead(e,e.uint32(),n));break;case 4:o.chunkStart=e.uint64().toBigInt();break;case 5:o.chunkEnd=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.uploadUrl!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.uploadUrl),e.method!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.method);for(let o=0;o<e.headers.length;o++)j.internalBinaryWrite(e.headers[o],t.tag(3,i.WireType.LengthDelimited).fork(),n).join();e.chunkStart!==0n&&t.tag(4,i.WireType.Varint).uint64(e.chunkStart),e.chunkEnd!==0n&&t.tag(5,i.WireType.Varint).uint64(e.chunkEnd);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Ot=new Mt;class Ht extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Ht;class zt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const xt=new zt;class At extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const jt=new At,G=new y.ServiceType("MiLaboratories.Controller.Shared.Upload",[{name:"Init",options:{},I:It,O:Dt},{name:"GetPartURL",options:{},I:_t,O:Ot},{name:"UpdateProgress",options:{},I:Ct,O:$t},{name:"Finalize",options:{},I:xt,O:jt}]);class Gt{constructor(e){h(this,"typeName",G.typeName);h(this,"methods",G.methods);h(this,"options",G.options);this._transport=e}init(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}getPartURL(e,t){const n=this.methods[1],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}updateProgress(e,t){const n=this.methods[2],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}finalize(e,t){const n=this.methods[3],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}function ve(s,e,t){const n=Object.fromEntries(s.map(({name:r,value:o})=>[r,o]));return e!==void 0&&t!==void 0&&(n.Range=`bytes=${e}-${t-1}`),n}class ce extends Error{}class de extends Error{}class he extends Error{}class ue extends Error{}class Ne{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=r,this.grpcClient=new Gt(this.grpcTransport)}close(){}async initUpload({id:e,type:t},n){const r=await this.grpcInit(e,t,n);return{overall:r.partsCount,toUpload:this.partsToUpload(r.partsCount,r.uploadedParts)}}async partUpload({id:e,type:t},n,r,o,l){const a=await this.grpcGetPartUrl({id:e,type:t},o,0n,l),d=await Vt(n,a.chunkStart,a.chunkEnd);await Jt(n,r);try{const{body:c,statusCode:u,headers:A}=await Re.request(a.uploadUrl,{dispatcher:this.httpClient,body:d,headersTimeout:6e4,bodyTimeout:6e4,headers:ve(a.headers),method:a.method.toUpperCase()}),dt=await c.text();Zt(u,dt,A,a)}catch(c){throw c instanceof he?c:new Error(`partUpload: error ${JSON.stringify(c)} happened while trying to do part upload to the url ${a.uploadUrl}, headers: ${JSON.stringify(a.headers)}`)}await this.grpcUpdateProgress({id:e,type:t},BigInt(a.chunkEnd-a.chunkStart),l)}async finalize(e,t){return await this.grpcFinalize(e,t)}partsToUpload(e,t){const n=[],r=new Set(t);for(let o=1n;o<=e;o++)r.has(o)||n.push(o);return n}async grpcInit(e,t,n){return await this.grpcClient.init({resourceId:e},g.addRTypeToMetadata(t,n)).response}async grpcGetPartUrl({id:e,type:t},n,r,o){return await this.grpcClient.getPartURL({resourceId:e,partNumber:n,uploadedPartSize:r},g.addRTypeToMetadata(t,o)).response}async grpcUpdateProgress({id:e,type:t},n,r){await this.grpcClient.updateProgress({resourceId:e,bytesProcessed:n},g.addRTypeToMetadata(t,r)).response}async grpcFinalize({id:e,type:t},n){return await this.grpcClient.finalize({resourceId:e},g.addRTypeToMetadata(t,n)).response}}async function Vt(s,e,t){let n;try{n=await w.open(s);const r=Number(t-e),o=Number(e),l=Buffer.alloc(r),a=await qt(n,l,r,o);return l.subarray(0,a)}catch(r){throw r&&typeof r=="object"&&"code"in r&&r.code=="ENOENT"?new ue(`there is no file ${s} for uploading`):r}finally{await(n==null?void 0:n.close())}}async function qt(s,e,t,n){let r=0;for(;r<t;){const{bytesRead:o}=await s.read(e,r,t-r,n+r);if(o===0)throw new de("file ended earlier than expected.");r+=o}return r}async function Jt(s,e){const t=BigInt(Math.floor((await w.stat(s)).mtimeMs/1e3));if(t>e)throw new ce(`file was modified, expected mtime: ${e}, got: ${t}.`)}function Zt(s,e,t,n){if(s!=200)throw new he(`response is not ok, status code: ${s}, body: ${e}, headers: ${JSON.stringify(t)}, url: ${n.uploadUrl}`)}class Qt extends i.MessageType{constructor(){super("google.protobuf.Duration",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}internalJsonWrite(e,t){const n=i.PbLong.from(e.seconds).toNumber();if(n>315576e6||n<-315576e6)throw new Error("Duration value out of range.");let r=e.seconds.toString();if(n===0&&e.nanos<0&&(r="-"+r),e.nanos!==0){let o=Math.abs(e.nanos).toString();o="0".repeat(9-o.length)+o,o.substring(3)==="000000"?o=o.substring(0,3):o.substring(6)==="000"&&(o=o.substring(0,6)),r+="."+o}return r+"s"}internalJsonRead(e,t,n){if(typeof e!="string")throw new Error("Unable to parse Duration from JSON "+i.typeofJsonValue(e)+". Expected string.");const r=e.match(/^(-?)([0-9]+)(?:\.([0-9]+))?s/);if(r===null)throw new Error("Unable to parse Duration from JSON string. Invalid format.");n||(n=this.create());const[,o,l,a]=r,d=i.PbLong.from(o+l);if(d.toNumber()>315576e6||d.toNumber()<-315576e6)throw new Error("Unable to parse Duration from JSON string. Value out of range.");if(n.seconds=d.toBigInt(),typeof a=="string"){const c=o+a+"0".repeat(9-a.length);n.nanos=parseInt(c)}return n}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.seconds!==0n&&t.tag(1,i.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,i.WireType.Varint).int32(e.nanos);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const W=new Qt;class Kt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Kt;class Xt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.Report",[{no:1,name:"progress",kind:"scalar",T:2},{no:2,name:"bytes_processed",kind:"scalar",T:4,L:0},{no:3,name:"bytes_total",kind:"scalar",T:4,L:0},{no:4,name:"done",kind:"scalar",T:8},{no:5,name:"name",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.progress=0,t.bytesProcessed=0n,t.bytesTotal=0n,t.done=!1,t.name="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.progress=e.float();break;case 2:o.bytesProcessed=e.uint64().toBigInt();break;case 3:o.bytesTotal=e.uint64().toBigInt();break;case 4:o.done=e.bool();break;case 5:o.name=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.progress!==0&&t.tag(1,i.WireType.Bit32).float(e.progress),e.bytesProcessed!==0n&&t.tag(2,i.WireType.Varint).uint64(e.bytesProcessed),e.bytesTotal!==0n&&t.tag(3,i.WireType.Varint).uint64(e.bytesTotal),e.done!==!1&&t.tag(4,i.WireType.Varint).bool(e.done),e.name!==""&&t.tag(5,i.WireType.LengthDelimited).string(e.name);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const S=new Xt;class Yt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Yt;class en extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const tn=new en;class nn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Response",[{no:1,name:"report",kind:"message",T:()=>S}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.report=S.internalBinaryRead(e,e.uint32(),n,o.report);break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.report&&S.internalBinaryWrite(e.report,t.tag(1,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const rn=new nn;class on extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new on;class sn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"update_interval",kind:"message",T:()=>W}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.updateInterval=W.internalBinaryRead(e,e.uint32(),n,o.updateInterval);break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.updateInterval&&W.internalBinaryWrite(e.updateInterval,t.tag(2,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const an=new sn;class ln extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Response",[{no:1,name:"report",kind:"message",T:()=>S}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.report=S.internalBinaryRead(e,e.uint32(),n,o.report);break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.report&&S.internalBinaryWrite(e.report,t.tag(1,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const cn=new ln,V=new y.ServiceType("MiLaboratories.Controller.Shared.Progress",[{name:"GetStatus",options:{"google.api.http":{get:"/resources/{resource_id}/get-progress"}},I:tn,O:rn},{name:"RealtimeStatus",serverStreaming:!0,options:{},I:an,O:cn}]);class dn{constructor(e){h(this,"typeName",V.typeName);h(this,"methods",V.methods);h(this,"options",V.options);this._transport=e}getStatus(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}realtimeStatus(e,t){const n=this.methods[1],r=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,n,r,e)}}class Ce{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.client=n,this.logger=r,this.grpcClient=new dn(this.grpcTransport)}close(){}async getStatus({id:e,type:t},n){const r=await this.grpcClient.getStatus({resourceId:e},g.addRTypeToMetadata(t,n)),o=p.notEmpty(r.response.report);return{done:o.done,progress:o.progress,bytesProcessed:String(o.bytesProcessed),bytesTotal:String(o.bytesTotal)}}async*realtimeStatus({id:e,type:t},n=100,r){r=g.addRTypeToMetadata(t,r);const o=Math.floor(n/1e3),l=(n-o*1e3)*1e6,a=W.create({seconds:BigInt(o),nanos:l});try{const{responses:d}=this.grpcClient.realtimeStatus({resourceId:e,updateInterval:a},r);yield*d}catch(d){throw this.logger.warn("Failed to get realtime status"+String(d)),d}}}class O extends Error{}class Be{constructor(e){this.httpClient=e}async download(e,t,n){const{statusCode:r,body:o,headers:l}=await Re.request(e,{dispatcher:this.httpClient,headers:t,signal:n}),a=L.Readable.toWeb(o);return await hn(r,a,e),{content:a,size:Number(l["content-length"])}}}async function hn(s,e,t){if(s!=200&&s!=206){const n=(await ae.text(e)).substring(0,1e3);throw 400<=s&&s<500?new O(`Http error: statusCode: ${s} url: ${t.toString()}, beginning of body: ${n}`):new Error(`Http error: statusCode: ${s} url: ${t.toString()}`)}}function I(s){if(!k.isAbsolute(s))throw new Error(`Path ${s} is not absolute.`);return s}class un extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new un;class pn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new pn;class gn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const fn=new gn;class mn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.name!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.value);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const q=new mn;class wn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Response",[{no:1,name:"download_url",kind:"scalar",T:9},{no:2,name:"headers",kind:"message",repeat:1,T:()=>q}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.downloadUrl="",t.headers=[],e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.downloadUrl=e.string();break;case 2:o.headers.push(q.internalBinaryRead(e,e.uint32(),n));break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.downloadUrl!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.downloadUrl);for(let o=0;o<e.headers.length;o++)q.internalBinaryWrite(e.headers[o],t.tag(2,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const yn=new wn,J=new y.ServiceType("MiLaboratories.Controller.Shared.Download",[{name:"GetDownloadURL",options:{"google.api.http":{get:"/resources/{resource_id}/get-download-url"}},I:fn,O:yn}]);class Tn{constructor(e){h(this,"typeName",J.typeName);h(this,"methods",J.methods);h(this,"options",J.options);this._transport=e}getDownloadURL(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}class $e{constructor(e,t,n,r){h(this,"grpcClient");h(this,"remoteFileDownloader");h(this,"localStorageIdsToRoot");this.grpcTransport=e,this.httpClient=t,this.logger=n,this.grpcClient=new Tn(this.grpcTransport),this.remoteFileDownloader=new Be(t),this.localStorageIdsToRoot=_e(r)}close(){}async downloadBlob(e,t,n,r,o){const{downloadUrl:l,headers:a}=await this.grpcGetDownloadUrl(e,t,n),d=ve(a,r,o);return this.logger.info(`download blob from url ${l}, headers: ${JSON.stringify(d)}`),kn(l)?await this.readLocalFile(l,r,o):await this.remoteFileDownloader.download(l,d,n)}async readLocalFile(e,t,n){const{storageId:r,relativePath:o}=We(e),l=Fe(r,this.localStorageIdsToRoot,o);return{content:L.Readable.toWeb(le.createReadStream(l,{start:t,end:n!==void 0?n-1:void 0})),size:(await w.stat(l)).size}}async grpcGetDownloadUrl({id:e,type:t},n,r){const o=n??{};return o.abort=r,await this.grpcClient.getDownloadURL({resourceId:e},g.addRTypeToMetadata(t,o)).response}}function We(s){const e=new URL(s);if(e.pathname=="")throw new H(`url for local filepath ${s} does not match url scheme`);return{storageId:e.host,relativePath:decodeURIComponent(e.pathname.slice(1))}}function Fe(s,e,t){const n=e.get(s);if(n===void 0)throw new z(`Unknown storage location: ${s}`);return n===""?t:T.join(n,t)}const bn="storage://";function kn(s){return s.startsWith(bn)}class H extends Error{}class z extends Error{}function _e(s){const e=new Map;for(const t of s)t.localPath!==""&&I(t.localPath),e.set(t.storageId,t.localPath);return e}class Pn extends i.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=i.PbLong.from(Math.floor(t/1e3)).toBigInt(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(i.PbLong.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),n=e.getTime();return t.seconds=i.PbLong.from(Math.floor(n/1e3)).toBigInt(),t.nanos=n%1e3*1e6,t}internalJsonWrite(e,t){const n=i.PbLong.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let r="Z";if(e.nanos>0){const o=(e.nanos+1e9).toString().substring(1);o.substring(3)==="000000"?r="."+o.substring(0,3)+"Z":o.substring(6)==="000"?r="."+o.substring(0,6)+"Z":r="."+o+"Z"}return new Date(n).toISOString().replace(".000Z",r)}internalJsonRead(e,t,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+i.typeofJsonValue(e)+".");const r=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!r)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");const o=Date.parse(r[1]+"-"+r[2]+"-"+r[3]+"T"+r[4]+":"+r[5]+":"+r[6]+(r[8]?r[8]:"Z"));if(Number.isNaN(o))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(o<Date.parse("0001-01-01T00:00:00Z")||o>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return n||(n=this.create()),n.seconds=i.PbLong.from(o/1e3).toBigInt(),n.nanos=0,r[7]&&(n.nanos=parseInt("1"+r[7]+"0".repeat(9-r[7].length))-1e9),n}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.seconds!==0n&&t.tag(1,i.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,i.WireType.Varint).int32(e.nanos);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Z=new Pn;class Ln extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Ln;class Un extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.ListItem",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"is_dir",kind:"scalar",T:8},{no:10,name:"full_name",kind:"scalar",T:9},{no:11,name:"directory",kind:"scalar",T:9},{no:12,name:"last_modified",kind:"message",T:()=>Z},{no:13,name:"version",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.size=0n,t.isDir=!1,t.fullName="",t.directory="",t.version="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.name=e.string();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.isDir=e.bool();break;case 10:o.fullName=e.string();break;case 11:o.directory=e.string();break;case 12:o.lastModified=Z.internalBinaryRead(e,e.uint32(),n,o.lastModified);break;case 13:o.version=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.name!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.name),e.size!==0n&&t.tag(2,i.WireType.Varint).uint64(e.size),e.isDir!==!1&&t.tag(3,i.WireType.Varint).bool(e.isDir),e.fullName!==""&&t.tag(10,i.WireType.LengthDelimited).string(e.fullName),e.directory!==""&&t.tag(11,i.WireType.LengthDelimited).string(e.directory),e.lastModified&&Z.internalBinaryWrite(e.lastModified,t.tag(12,i.WireType.LengthDelimited).fork(),n).join(),e.version!==""&&t.tag(13,i.WireType.LengthDelimited).string(e.version);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Q=new Un;class Rn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Rn;class In extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"location",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.location="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.location=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.location!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.location);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Sn=new In;class Dn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Response",[{no:1,name:"items",kind:"message",repeat:1,T:()=>Q},{no:2,name:"delimiter",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.items=[],t.delimiter="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.items.push(Q.internalBinaryRead(e,e.uint32(),n));break;case 2:o.delimiter=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){for(let o=0;o<e.items.length;o++)Q.internalBinaryWrite(e.items[o],t.tag(1,i.WireType.LengthDelimited).fork(),n).join();e.delimiter!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.delimiter);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const vn=new Dn,K=new y.ServiceType("MiLaboratories.Controller.Shared.LS",[{name:"List",options:{},I:Sn,O:vn}]);class Nn{constructor(e){h(this,"typeName",K.typeName);h(this,"methods",K.methods);h(this,"options",K.options);this._transport=e}list(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}class Ee{constructor(e,t){h(this,"grpcClient");this.logger=t,this.grpcClient=new Nn(e)}close(){}async list(e,t,n){return await this.grpcClient.list({resourceId:e.id,location:t},g.addRTypeToMetadata(e.type,n)).response}}class Cn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Cn;class Bn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;case 20:o.readLimit=e.int64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,i.WireType.Varint).uint32(e.chunkSize),e.readLimit!==void 0&&t.tag(20,i.WireType.Varint).int64(e.readLimit);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const $n=new Bn;class Wn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,i.WireType.Varint).uint32(e.chunkSize);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Fn=new Wn;class _n extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,i.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,i.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,i.WireType.LengthDelimited).string(e.searchRe);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const En=new _n;class Mn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,i.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,i.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,i.WireType.LengthDelimited).string(e.searchRe);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const On=new Mn;class Hn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.LastLines",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",opt:!0,T:3,L:0},{no:3,name:"line_count",kind:"scalar",opt:!0,T:5},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 3:o.lineCount=e.int32();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==void 0&&t.tag(2,i.WireType.Varint).int64(e.offset),e.lineCount!==void 0&&t.tag(3,i.WireType.Varint).int32(e.lineCount),e.search!==void 0&&t.tag(21,i.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,i.WireType.LengthDelimited).string(e.searchRe);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const zn=new Hn;class xn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.Response",[{no:1,name:"data",kind:"scalar",T:12},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"new_offset",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.data=new Uint8Array(0),t.size=0n,t.newOffset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.data=e.bytes();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.newOffset=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.data.length&&t.tag(1,i.WireType.LengthDelimited).bytes(e.data),e.size!==0n&&t.tag(2,i.WireType.Varint).uint64(e.size),e.newOffset!==0n&&t.tag(3,i.WireType.Varint).uint64(e.newOffset);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const D=new xn,X=new y.ServiceType("MiLaboratories.Controller.Shared.Streaming",[{name:"StreamBinary",serverStreaming:!0,options:{},I:$n,O:D},{name:"ReadBinary",options:{},I:Fn,O:D},{name:"StreamText",serverStreaming:!0,options:{},I:En,O:D},{name:"ReadText",options:{},I:On,O:D},{name:"LastLines",options:{},I:zn,O:D}]);class An{constructor(e){h(this,"typeName",X.typeName);h(this,"methods",X.methods);h(this,"options",X.options);this._transport=e}streamBinary(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,n,r,e)}readBinary(e,t){const n=this.methods[1],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}streamText(e,t){const n=this.methods[2],r=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,n,r,e)}readText(e,t){const n=this.methods[3],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}lastLines(e,t){const n=this.methods[4],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}class Me{constructor(e,t,n){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=n,this.grpcClient=new An(this.grpcTransport)}close(){}async lastLines({id:e,type:t},n,r=0n,o,l){return(await this.grpcClient.lastLines({resourceId:e,lineCount:n,offset:r,search:o},g.addRTypeToMetadata(t,l))).response}async readText({id:e,type:t},n,r=0n,o,l){return(await this.grpcClient.readText({resourceId:p.notEmpty(e),readLimit:BigInt(n),offset:r,search:o},g.addRTypeToMetadata(t,l))).response}}function jn(s,e,t){return e.getDriver({name:"DownloadBlob",init:(n,r,o)=>new $e(r,o,s,t)})}function Gn(s,e){return s.getDriver({name:"StreamLogs",init:(t,n,r)=>new Me(n,r,e)})}function Vn(s,e){return s.getDriver({name:"UploadProgress",init:(t,n,r)=>new Ce(n,r,s,e)})}function qn(s,e){return s.getDriver({name:"UploadBlob",init:(t,n,r)=>new Ne(n,r,s,e)})}function Oe(s,e){return s.getDriver({name:"LsFiles",init:(t,n,r)=>new Ee(n,e)})}const He=/^blob\+local:\/\/download\/(?<path>.*)#(?<signature>.*)$/;function Jn(s,e){return`blob+local://download/${s}#${e.sign(s)}`}function Zn(s){return!!s.match(He)}function Y(s,e){const t=s.match(He);if(t===null)throw new Error(`Local handle is malformed: ${s}, matches: ${t}`);const{path:n,signature:r}=t.groups;return e.verify(n,r,`Signature verification failed for: ${s}`),{path:n,signature:r}}const ze=/^blob\+remote:\/\/download\/(?<content>(?<resourceType>.+)\/(?<resourceVersion>.+?)\/(?<resourceId>\d+?))#(?<signature>.*)$/;function Qn(s,e){let t=`${s.type.name}/${s.type.version}/${BigInt(s.id)}`;return`blob+remote://download/${t}#${e.sign(t)}`}function Kn(s){return!!s.match(ze)}function Xn(s,e){const t=s.match(ze);if(t===null)throw new Error(`Remote handle is malformed: ${s}, matches: ${t}`);const{content:n,resourceType:r,resourceVersion:o,resourceId:l,signature:a}=t.groups;return e.verify(n,a,`Signature verification failed for ${s}`),{id:g.bigintToResourceId(BigInt(l)),type:{name:r,version:o}}}class x extends Error{}class xe{constructor(e){h(this,"updating");this.onUpdate=e}schedule(){this.updating==null&&(this.updating=(async()=>{try{await this.onUpdate()}catch(e){console.log(`error while updating in Updater: ${e}`)}finally{this.updating=void 0}})())}}function Ae(s,e){return s?`log+live://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`:`log+ready://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`}const je=/^log\+live:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function _(s){return je.test(s)}const Ge=/^log\+ready:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function Yn(s){return Ge.test(s)}function E(s){let e;if(_(s))e=s.match(je);else if(Yn(s))e=s.match(Ge);else throw new Error(`Log handle is malformed: ${s}`);if(e==null)throw new Error(`Log handle wasn't parsed: ${s}`);const{resourceType:t,resourceVersion:n,resourceId:r}=e.groups;return{id:g.bigintToResourceId(BigInt(r)),type:{name:t,version:n}}}const Ve=m.rsSchema({kv:{"ctl/file/blobInfo":P.z.object({sizeBytes:P.z.coerce.number()})}});function qe(s,e){const t=s.kv["ctl/file/blobInfo"].sizeBytes;if(e){const n=e.to-e.from;if(n>t)throw new Error(`getSize: range (${JSON.stringify(e)}, newSize: ${n}) is greater than size (${t})`);return n}return t}const N=P.z.object({localPath:P.z.string(),pathSignature:P.z.string(),sizeBytes:P.z.string(),modificationTime:P.z.string()}),pe=P.z.object({storageId:P.z.string(),path:P.z.string()}),er=P.z.union([N,pe]),Je=m.rsSchema({data:N,fields:{blob:!1}}),Ze=m.rsSchema({fields:{incarnation:!1}});function b(s){return`${BigInt(s)}`}function be(s){return T.basename(s)}class tr{constructor(e,t,n,r,o){h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"counter",new p.CallersCounter);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"state",{});this.logger=e,this.clientDownload=t,this.rInfo=n,this.handle=r,this.path=o}info(){return{rInfo:this.rInfo,fPath:this.path,done:this.done,error:this.error,state:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.ensureDownloaded();this.setDone(e),this.change.markChanged()}catch(e){throw this.logger.error(`task failed: ${e}, ${JSON.stringify(this.state)}`),ge(e)&&(this.setError(e),this.change.markChanged(),await w.rm(this.path)),e}}async ensureDownloaded(){if(this.state={},this.state.filePath=this.path,await p.ensureDirExists(T.dirname(this.state.filePath)),this.state.dirExists=!0,await p.fileExists(this.state.filePath)){this.state.fileExists=!0,this.logger.info(`a blob was already downloaded: ${this.state.filePath}`);const n=await w.stat(this.state.filePath);return this.state.fileSize=n.size,this.state.fileSize}const{content:e,size:t}=await this.clientDownload.downloadBlob(this.rInfo,{},void 0);return this.state.fileSize=t,this.state.downloaded=!0,await p.createPathAtomically(this.logger,this.state.filePath,async n=>{const r=L.Writable.toWeb(F.createWriteStream(n,{flags:"wx"}));await e.pipeTo(r),this.state.tempWritten=!0}),this.state.done=!0,t}abort(e){this.signalCtl.abort(new Qe(e))}getBlob(){return this.done?{done:this.done,result:nr(this.handle,this.size,this.error)}:{done:!1}}setDone(e){this.done=!0,this.size=e}setError(e){this.done=!0,this.error=e}}function ge(s){return s instanceof Qe||s instanceof O||s instanceof z||s instanceof H||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")}class Qe extends Error{}function nr(s,e,t){return t?{ok:!1,error:t}:s?{ok:!0,value:{handle:s,size:e}}:{ok:!1,error:new Error("No file or handle provided")}}class fe{constructor(e){h(this,"cache",new Map);h(this,"totalSizeBytes",0);this.softSizeBytes=e}existsFile(e){return this.cache.get(e)!=null}getFile(e,t){const n=this.cache.get(e);return n!=null&&n.counter.inc(t),n}removeFile(e,t){return p.mapGet(this.cache,e).counter.dec(t),this.toDelete()}toDelete(){if(this.totalSizeBytes<=this.softSizeBytes)return[];const e=[];let t=0;return p.mapEntries(this.cache).filter(([n,r])=>r.counter.isZero()).forEach(([n,r])=>{if(this.totalSizeBytes-t<=this.softSizeBytes)return;const o=p.mapGet(this.cache,n);t+=o.size,e.push(o)}),e}addCache(e,t){const n=this.cache.get(e.path)==null;if(this.cache.set(e.path,e),e.counter.inc(t),e.size<0)throw new Error(`empty sizeBytes: ${e}`);n&&(this.totalSizeBytes+=e.size)}removeCache(e){this.cache.delete(e.path),this.totalSizeBytes-=e.size}}class me{constructor(e,t,n,r,o,l){h(this,"keyToDownload",new Map);h(this,"cache");h(this,"downloadQueue");h(this,"keyToOnDemand",new Map);h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"saveDir");this.logger=e,this.clientDownload=t,this.clientLogs=n,this.signer=o,this.cache=new fe(l.cacheSoftSizeBytes),this.downloadQueue=new p.TaskProcessor(this.logger,l.nConcurrentDownloads),this.saveDir=T.resolve(r)}static async init(e,t,n,r,o,l){const a=new me(e,t,n,r,o,l);return await a.initCache(),a}async initCache(){let e;try{e=await w.readdir(this.saveDir)}catch(t){if(typeof t=="object"&&t!==null&&t.code==="ENOENT")return;throw t}}getDownloadedBlob(e,t){if(t===void 0)return f.Computable.make(l=>this.getDownloadedBlob(e,l));const n=m.treeEntryToResourceInfo(e,t),r=U.randomUUID();t.addOnDestroy(()=>this.releaseBlob(n,r));const o=this.getDownloadedBlobNoCtx(t.watcher,n,r);return o==null&&t.markUnstable("download blob is still undefined"),o}getDownloadedBlobNoCtx(e,t,n){v("getDownloadedBlob",t.type);const r=this.getOrSetNewTask(t,n);r.attach(e,n);const o=r.getBlob();if(o.done){if(o.result.ok)return o.result.value;throw o.result.error}}getOrSetNewTask(e,t){const n=b(e.id),r=this.keyToDownload.get(n);if(r)return r;const o=T.resolve(this.saveDir,n),l=new tr(this.logger,this.clientDownload,e,Jn(o,this.signer),o);return this.keyToDownload.set(n,l),this.downloadQueue.push({fn:()=>this.downloadBlob(l,t),recoverableErrorPredicate:a=>!ge(a)}),l}async downloadBlob(e,t){await e.download();const n=e.getBlob();n.done&&n.result.ok&&this.cache.addCache(e,t)}getOnDemandBlob(e,t){if(t===void 0)return f.Computable.make(l=>this.getOnDemandBlob(e,l));const n=m.isPlTreeEntry(e)?m.makeResourceSnapshot(e,Ve,t):e,r=U.randomUUID();return t.addOnDestroy(()=>this.releaseOnDemandBlob(n.id,r)),this.getOnDemandBlobNoCtx(n,r)}getOnDemandBlobNoCtx(e,t){v("getOnDemandBlob",e.type);let n=this.keyToOnDemand.get(b(e.id));return n===void 0&&(n=new rr(qe(e),Qn(e,this.signer)),this.keyToOnDemand.set(b(e.id),n)),n.attach(t),n.getHandle()}getLocalPath(e){const{path:t}=Y(e,this.signer);return t}async getContent(e,t){if(t&&ne.validateRangeBytes(t,"getContent"),Zn(e))return await sr(this.getLocalPath(e),t);if(Kn(e)){const n=Xn(e,this.signer),{content:r}=await this.clientDownload.downloadBlob({id:n.id,type:n.type},void 0,void 0,t==null?void 0:t.from,t==null?void 0:t.to);return await ae.buffer(r)}throw new Error("Malformed remote handle")}getComputableContent(e,t){return t&&ne.validateRangeBytes(t,"getComputableContent"),f.Computable.make(n=>this.getDownloadedBlob(e,n),{postprocessValue:n=>n?this.getContent(n.handle,t):void 0}).withStableType()}getLastLogs(e,t,n){if(n==null)return f.Computable.make(a=>this.getLastLogs(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r,o));const l=this.getLastLogsNoCtx(n.watcher,r,t,o);return l==null&&n.markUnstable("either a file was not downloaded or logs was not read"),l}getLastLogsNoCtx(e,t,n,r){v("getLastLogs",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=Y(o.handle,this.signer);let a=this.idToLastLines.get(b(t.id));if(a==null){const c=new ke(l,n);this.idToLastLines.set(b(t.id),c),a=c}const d=a.getOrSchedule(e);if(d.error)throw d.error;return d.log}getProgressLog(e,t,n){if(n==null)return f.Computable.make(a=>this.getProgressLog(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r,o));const l=this.getProgressLogNoCtx(n.watcher,r,t,o);return l===void 0&&n.markUnstable("either a file was not downloaded or a progress log was not read"),l}getProgressLogNoCtx(e,t,n,r){v("getProgressLog",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=Y(o.handle,this.signer);let a=this.idToProgressLog.get(b(t.id));if(a==null){const c=new ke(l,1,n);this.idToProgressLog.set(b(t.id),c),a=c}const d=a.getOrSchedule(e);if(d.error)throw d.error;return d.log}getLogHandle(e,t){if(t==null)return f.Computable.make(r=>this.getLogHandle(e,r));const n=m.treeEntryToResourceInfo(e,t);return this.getLogHandleNoCtx(n)}getLogHandleNoCtx(e){return v("getLogHandle",e.type),Ae(!1,e)}async lastLines(e,t,n,r){const o=await this.clientLogs.lastLines(E(e),t,BigInt(n??0),r);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async readText(e,t,n,r){const o=await this.clientLogs.readText(E(e),t,BigInt(n??0),r);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async releaseBlob(e,t){const n=this.keyToDownload.get(b(e.id));if(n!=null)if(this.cache.existsFile(b(e.id))){const r=this.cache.removeFile(b(e.id),t);await Promise.all(r.map(async o=>{await w.rm(o.path),this.cache.removeCache(o),this.removeTask(p.mapGet(this.keyToDownload,be(o.path)),`the task ${g.stringifyWithResourceId(o)} was removedfrom cache along with ${g.stringifyWithResourceId(r.map(l=>l.path))}`)}))}else n.counter.dec(t)&&this.removeTask(n,`the task ${g.stringifyWithResourceId(n.info())} was removed from cache`)}removeTask(e,t){e.abort(t),e.change.markChanged(),this.keyToDownload.delete(be(e.path)),this.idToLastLines.delete(b(e.rInfo.id)),this.idToProgressLog.delete(b(e.rInfo.id))}async releaseOnDemandBlob(e,t){var r;(((r=this.keyToOnDemand.get(b(e)))==null?void 0:r.release(t))??!1)&&this.keyToOnDemand.delete(b(e))}async releaseAll(){this.downloadQueue.stop(),this.keyToDownload.forEach((e,t)=>{this.keyToDownload.delete(t),e.change.markChanged()})}}class rr{constructor(e,t){h(this,"counter",new p.CallersCounter);this.size=e,this.handle=t}getHandle(){return{handle:this.handle,size:this.size}}attach(e){this.counter.inc(e)}release(e){return this.counter.dec(e)}}class ke{constructor(e,t,n){h(this,"updater");h(this,"log");h(this,"change",new f.ChangeSource);h(this,"error");this.path=e,this.lines=t,this.patternToSearch=n,this.updater=new xe(async()=>this.update())}getOrSchedule(e){return this.change.attachWatcher(e),this.updater.schedule(),{log:this.log,error:this.error}}async update(){try{const e=await or(this.path,this.lines,this.patternToSearch);this.log!=e&&this.change.markChanged(),this.log=e}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.log="",this.error=e,this.change.markChanged();return}throw e}}}function or(s,e,t){const n=le.createReadStream(s),r=new L.Writable;return new Promise((o,l)=>{const a=Pt.createInterface(n,r),d=new gt;a.on("line",function(c){t!=null&&!c.includes(t)||(d.push(c),d.length>e&&d.shift())}),a.on("error",l),a.on("close",function(){o(d.toArray().join(Te.EOL)+Te.EOL)})})}async function sr(s,e){const t={};e&&(t.start=e.from,t.end=e.to-1);const n=le.createReadStream(s,t);return await ae.buffer(L.Readable.toWeb(n))}function v(s,e){if(!e.name.startsWith("Blob/")){let t=`${s}: wrong resource type: ${e.name}, expected: a resource of type that starts with 'Blob/'.`;throw e.name=="Blob"&&(t+=" If it's called from workflow, should a file be exported with 'file.exportFile' function?"),new x(t)}}const Ke=m.rsSchema({});function Xe(s,e){const t=m.isPlTreeEntry(s)?e.accessor(s).node():m.isPlTreeEntryAccessor(s)?s.node():s;return m.makeResourceSnapshot(t,Ke)}function ir(s,e,t){const n=k.relative(e,t);return`plblob+folder://${s.sign(n)}.${n}.blob`}function ar(s){return new URL(s).protocol=="plblob+folder:"}function lr(s,e,t){const n=new URL(e),[r,o,l]=n.host.split(".");s.verify(o,r,`signature verification failed for url: ${e}, subfolder: ${o}`);let a=cr(k.join(t,`${o}`),n.pathname.slice(1));return(n.pathname==""||n.pathname=="/")&&(a=k.join(a,"index.html")),k.resolve(a)}function cr(s,e){const t=k.resolve(s,e),n=k.resolve(s);if(!t.startsWith(n))throw new Error("Path validation failed.");return t}class dr{constructor(e,t,n,r,o,l,a){h(this,"counter",new p.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"url");h(this,"state");this.logger=e,this.signer=t,this.saveDir=n,this.path=r,this.rInfo=o,this.format=l,this.clientDownload=a}info(){return{rInfo:this.rInfo,format:this.format,path:this.path,done:this.done,size:this.size,error:this.error,taskHistory:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.downloadAndDecompress(this.signalCtl.signal);this.setDone(e),this.change.markChanged(),this.logger.info(`blob to URL task is done: ${g.stringifyWithResourceId(this.info())}`)}catch(e){if(this.logger.warn(`a error was produced: ${e} for blob to URL task: ${g.stringifyWithResourceId(this.info())}`),hr(e)){this.setError(e),this.change.markChanged(),await oe(this.path);return}throw e}}async downloadAndDecompress(e){if(this.state={},this.state.parentDir=k.dirname(this.path),await p.ensureDirExists(this.state.parentDir),this.state.fileExisted=await p.fileExists(this.path),this.state.fileExisted)return await Ye(this.path);const{content:t,size:n}=await this.clientDownload.downloadBlob(this.rInfo,{},e);return this.state.downloaded=!0,await p.createPathAtomically(this.logger,this.path,async r=>{switch(this.state.tempPath=r,this.state.archiveFormat=this.format,this.format){case"tar":await w.mkdir(r);const o=L.Writable.toWeb(re.extract(r));await t.pipeTo(o,{signal:e});return;case"tgz":await w.mkdir(r);const l=L.Transform.toWeb(De.createGunzip()),a=L.Writable.toWeb(re.extract(r));await t.pipeThrough(l,{signal:e}).pipeTo(a,{signal:e});return;case"zip":this.state.zipPath=this.path+".zip";const d=L.Writable.toWeb(F.createWriteStream(this.state.zipPath));await t.pipeTo(d,{signal:e}),this.state.zipPathCreated=!0,await yt(this.state.zipPath,r,{filter:c=>!c.path.endsWith("/")}),this.state.zipDecompressed=!0,await F.promises.rm(this.state.zipPath),this.state.zipPathDeleted=!0;return;default:i.assertNever(this.format)}}),this.state.pathCreated=!0,n}getURL(){if(this.done)return{url:p.notEmpty(this.url)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e,this.url=ir(this.signer,this.saveDir,this.path)}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new et(e))}}async function Ye(s){const e=await w.readdir(s,{withFileTypes:!0});return(await Promise.all(e.map(async n=>{const r=k.join(s,n.name);return n.isDirectory()?await Ye(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function oe(s){await w.rm(s,{recursive:!0,force:!0})}let et=class extends Error{};function hr(s){return s instanceof et||s instanceof O||s instanceof z||s instanceof H||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")||String(s).includes("incorrect header check")}function C(s,e){return`id:${String(BigInt(s))}-${e}`}class ur{constructor(e,t,n,r,o={cacheSoftSizeBytes:50*1024*1024,nConcurrentDownloads:50}){h(this,"idToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.signer=t,this.clientDownload=n,this.saveDir=r,this.opts=o,this.downloadQueue=new p.TaskProcessor(this.logger,this.opts.nConcurrentDownloads,{type:"exponentialWithMaxDelayBackoff",initialDelay:1e4,maxDelay:3e4,backoffMultiplier:1.5,jitter:.5}),this.cache=new fe(this.opts.cacheSoftSizeBytes)}info(){return{saveDir:this.saveDir,opts:this.opts,idToDownloadSize:this.idToDownload.size,idToDownloadKeys:this.idToDownload.keys(),idToDownload:Array.from(this.idToDownload.entries()).map(([e,t])=>[e,t.info()])}}getPathForCustomProtocol(e){if(ar(e))return lr(this.signer,e,this.saveDir);throw new Error(`getPathForCustomProtocol: ${e} is invalid`)}extractArchiveAndGetURL(e,t,n){if(n===void 0)return f.Computable.make(a=>this.extractArchiveAndGetURL(e,t,a));const r=m.isPlTreeEntry(e)?Xe(e,n):e,o=U.randomUUID();n.addOnDestroy(()=>this.releasePath(r.id,t,o));const l=this.extractArchiveAndGetURLNoCtx(r,t,n.watcher,o);if((l==null?void 0:l.url)===void 0&&n.markUnstable(`a path to the downloaded archive might be undefined. The current result: ${l}`),(l==null?void 0:l.error)!==void 0)throw l==null?void 0:l.error;return l==null?void 0:l.url}extractArchiveAndGetURLNoCtx(e,t,n,r){const o=this.idToDownload.get(C(e.id,t));if(o!=null)return o.attach(n,r),o.getURL();const l=this.setNewTask(n,e,t,r);return this.downloadQueue.push({fn:async()=>this.downloadUrl(l,r),recoverableErrorPredicate:a=>!ge(a)}),l.getURL()}async downloadUrl(e,t){var n;await e.download(),((n=e.getURL())==null?void 0:n.url)!=null&&this.cache.addCache(e,t)}async releasePath(e,t,n){const r=this.idToDownload.get(C(e,t));if(r!=null)if(this.cache.existsFile(r.path)){const o=this.cache.removeFile(r.path,n);await Promise.all(o.map(async l=>{await oe(l.path),this.cache.removeCache(l),this.removeTask(l,`the task ${g.stringifyWithResourceId(l.info())} was removedfrom cache along with ${g.stringifyWithResourceId(o.map(a=>a.info()))}`)}))}else r.counter.dec(n)&&this.removeTask(r,`the task ${g.stringifyWithResourceId(r.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.idToDownload.entries()).map(async([e,t])=>{await oe(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${g.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,n,r){const o=new dr(this.logger,this.signer,this.saveDir,this.getFilePath(t.id,n),t,n,this.clientDownload);return o.attach(e,r),this.idToDownload.set(C(t.id,n),o),o}removeTask(e,t){e.abort(t),e.change.markChanged(),this.idToDownload.delete(C(e.rInfo.id,e.format))}getFilePath(e,t){return T.join(this.saveDir,`${String(BigInt(e))}_${t}`)}}class tt{constructor(e,t,n,r,o,l){h(this,"change",new f.ChangeSource);h(this,"counter",new p.CallersCounter);h(this,"nMaxUploads");h(this,"nPartsWithThisUploadSpeed",0);h(this,"nPartsToIncreaseUpload",10);h(this,"uploadData");h(this,"progress");h(this,"failed");h(this,"alreadyExisted",!1);this.logger=e,this.clientBlob=t,this.clientProgress=n,this.maxNConcurrentPartsUpload=r,this.res=l,this.nMaxUploads=this.maxNConcurrentPartsUpload;const{uploadData:a,progress:d}=pr(l,o);this.uploadData=a,this.progress=d}getProgress(e,t){if(this.incCounter(e,t),this.failed)throw this.logger.error(`Uploading terminally failed: ${this.progress.lastError}`),new Error(this.progress.lastError);return gr(this.progress)}shouldScheduleUpload(){return rt(this.progress)}async uploadBlobTask(){try{await nt(this.logger,this.clientBlob,this.res,this.uploadData,this.isComputableDone.bind(this),{nPartsWithThisUploadSpeed:this.nPartsWithThisUploadSpeed,nPartsToIncreaseUpload:this.nPartsToIncreaseUpload,currentSpeed:this.nMaxUploads,maxSpeed:this.maxNConcurrentPartsUpload}),this.change.markChanged()}catch(e){if(this.setRetriableError(e),se(e)){this.logger.warn(`resource was deleted while uploading a blob: ${e}`),this.change.markChanged(),this.setDone(!0);return}if(this.logger.error(`error while uploading a blob: ${e}`),this.change.markChanged(),we(e)){this.setTerminalError(e);return}throw yr(e)&&(this.nMaxUploads=br(this.logger,this.nMaxUploads,1)),e}}async updateStatus(){var e;try{const t=await this.clientProgress.getStatus(this.res,{timeout:1e4}),n=this.progress.status,r=wr(this.alreadyExisted,mr(t));this.progress.status=r,this.setDone(t.done),(t.done||this.progress.status.progress!=(n==null?void 0:n.progress))&&this.change.markChanged()}catch(t){if(this.setRetriableError(t),t.name=="RpcError"&&t.code=="DEADLINE_EXCEEDED"||(e=t==null?void 0:t.message)!=null&&e.includes("DEADLINE_EXCEEDED")){this.logger.warn("deadline exceeded while getting a status of BlobImport");return}if(se(t)){this.logger.warn(`resource was not found while updating a status of BlobImport: ${t}, ${g.stringifyWithResourceId(this.res)}`),this.change.markChanged(),this.setDone(!0);return}this.logger.error(`retryable error while updating a status of BlobImport: ${t}`)}}setRetriableError(e){this.progress.lastError=String(e)}setTerminalError(e){this.progress.lastError=String(e),this.progress.done=!1,this.failed=!0}setDoneIfOutputSet(e){fr(e)&&(this.setDone(!0),this.alreadyExisted=!0)}setDone(e){this.progress.done=e,e&&(this.progress.lastError=void 0)}incCounter(e,t){this.change.attachWatcher(e),this.counter.inc(t)}decCounter(e){return this.counter.dec(e)}isComputableDone(){return this.counter.isZero()}}async function nt(s,e,t,n,r,o){Tt(M(t),"the upload operation can be done only for BlobUploads");const l=1e4;if(r())return;const a=await e.initUpload(t,{timeout:l});s.info(`started to upload blob ${t.id}, parts overall: ${a.overall}, parts remained: ${a.toUpload.length}, number of concurrent uploads: ${o.currentSpeed}`);const d=c=>async u=>{r()||(await e.partUpload(t,n.localPath,BigInt(n.modificationTime),c,{timeout:l}),s.info(`uploaded chunk ${c}/${a.overall} of resource: ${t.id}`),o.nPartsWithThisUploadSpeed++,o.nPartsWithThisUploadSpeed>=o.nPartsToIncreaseUpload&&(o.nPartsWithThisUploadSpeed=0,o.currentSpeed=Tr(s,o.currentSpeed,o.maxSpeed),u.setConcurrency(o.currentSpeed)))};await p.asyncPool(o.currentSpeed,a.toUpload.map(d)),!r()&&(await e.finalize(t,{timeout:l}),s.info(`uploading of resource ${t.id} finished.`))}function pr(s,e){let t,n;return M(s)&&(n=N.parse(s.data),t=ot(e,n.localPath,n.pathSignature)),{uploadData:n,progress:{done:!1,status:void 0,isUpload:M(s),isUploadSignMatch:t,lastError:void 0}}}function rt(s){return s.isUpload&&(s.isUploadSignMatch??!1)}function gr(s){return s.done,s.isUpload,s.isUploadSignMatch,s.lastError,s.status&&(s.status.progress,s.status.bytesProcessed,s.status.bytesTotal),s}function fr(s){return"blob"in s.fields?s.fields.blob!==void 0:s.fields.incarnation!==void 0}function M(s){return s.type.name.startsWith("BlobUpload")}function ot(s,e,t){try{return s.verify(e,t),!0}catch{return!1}}function mr(s){return{progress:s.progress??0,bytesProcessed:Number(s.bytesProcessed),bytesTotal:Number(s.bytesTotal)}}function wr(s,e){return s&&e.bytesTotal!=0&&e.bytesProcessed==0?{progress:1,bytesProcessed:Number(e.bytesTotal),bytesTotal:Number(e.bytesTotal)}:e}function se(s){return s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED"||s.code=="ALREADY_EXISTS")}function we(s){return s instanceof ce||s instanceof de||s instanceof ue}function yr(s){return s==null?void 0:s.message.includes("UND_ERR_HEADERS_TIMEOUT")}function Tr(s,e,t){const n=Math.min(e+2,t);return n!=e&&s.info(`uploadTask.increaseConcurrency: increased from ${e} to ${n}`),n}function br(s,e,t){const n=Math.max(Math.round(e/2),t);return n!=e&&s.info(`uploadTask.decreaseConcurrency: decreased from ${e} to ${n}`),n}function st(s,e){const t=m.isPlTreeEntry(s)?e.accessor(s).node():m.isPlTreeEntryAccessor(s)?s.node():s;return t.resourceType.name.startsWith("BlobUpload")?m.makeResourceSnapshot(t,Je):m.makeResourceSnapshot(t,Ze)}class kr{constructor(e,t,n,r,o={nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToProgress",new Map);h(this,"uploadQueue");h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.signer=t,this.clientBlob=n,this.clientProgress=r,this.opts=o,this.uploadQueue=new p.TaskProcessor(this.logger,1,{type:"exponentialWithMaxDelayBackoff",initialDelay:20,maxDelay:15e3,backoffMultiplier:1.5,jitter:.5}),this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:o.stopPollingDelay},(l,a)=>this.scheduleOnNextState(l,a))}getProgressId(e,t){if(t==null)return f.Computable.make(l=>this.getProgressId(e,l));const n=m.isPlTreeEntry(e)?st(e,t):e,r=U.randomUUID();return t.attacheHooks(this.hooks),t.addOnDestroy(()=>this.release(n.id,r)),this.getProgressIdNoCtx(t.watcher,n,r)}getProgressIdNoCtx(e,t,n){Lr("getProgressId",t.type);const r=this.idToProgress.get(t.id);if(r!=null)return r.setDoneIfOutputSet(t),r.getProgress(e,n);const o=new tt(this.logger,this.clientBlob,this.clientProgress,this.opts.nConcurrentPartUploads,this.signer,t);return this.idToProgress.set(t.id,o),o.shouldScheduleUpload()&&this.uploadQueue.push({fn:()=>o.uploadBlobTask(),recoverableErrorPredicate:l=>!we(l)}),o.setDoneIfOutputSet(t),o.getProgress(e,n)}async release(e,t){const n=this.idToProgress.get(e);if(n===void 0)return;n.decCounter(t)&&this.idToProgress.delete(e)}async releaseAll(){this.uploadQueue.stop()}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{await p.asyncPool(this.opts.nConcurrentGetProgresses,this.getAllNotDoneProgresses().map(t=>async()=>await t.updateStatus())),e.forEach(t=>t.resolve())}catch(t){console.error(t),e.forEach(n=>n.reject(t))}if(!this.keepRunning)break;await Se.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllNotDoneProgresses(){return Array.from(this.idToProgress.entries()).filter(([e,t])=>!Pr(t.progress)).map(([e,t])=>t)}}function Pr(s){var e;return s.done&&(((e=s.status)==null?void 0:e.progress)??0)>=1}function Lr(s,e){if(!e.name.startsWith("BlobUpload")&&!e.name.startsWith("BlobIndex"))throw new x(`${s}: wrong resource type: ${e.name}, expected: a resource of either type 'BlobUpload' or 'BlobIndex'.`)}class Ur{constructor(e,t,n={nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.clientLogs=t,this.opts=n,this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:n.stopPollingDelay},(r,o)=>this.scheduleOnNextState(r,o))}getLastLogs(e,t,n){if(n==null)return f.Computable.make(a=>this.getLastLogs(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.attacheHooks(this.hooks),n.addOnDestroy(()=>this.releaseLastLogs(r.id,o));const l=this.getLastLogsNoCtx(n.watcher,r,t,o);return n.markUnstable("The logs are from stream, so we consider them unstable. Final values will be got from blobs."),l}getLastLogsNoCtx(e,t,n,r){ee("getLastLogs",t.type);let o=this.idToLastLines.get(t.id);if(o==null){const a=new Pe(this.logger,this.clientLogs,t,n);this.idToLastLines.set(t.id,a),o=a}o.attach(e,r);const l=o.getLog();if(l.error!=null)throw l.error;return l.log}getProgressLog(e,t,n){if(n==null)return f.Computable.make(a=>this.getProgressLog(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.attacheHooks(this.hooks),n.addOnDestroy(()=>this.releaseProgressLog(r.id,o));const l=this.getProgressLogNoCtx(n.watcher,r,t,o);return n.markUnstable("The progress log is from the stream, so we consider it unstable. Final value will be got from blobs."),l}getProgressLogNoCtx(e,t,n,r){ee("getProgressLog",t.type);let o=this.idToProgressLog.get(t.id);if(o==null){const a=new Pe(this.logger,this.clientLogs,t,1,n);this.idToProgressLog.set(t.id,a),o=a}o.attach(e,r);const l=o.getLog();if(l.error)throw l.error;return l.log}getLogHandle(e,t){if(t==null)return f.Computable.make(o=>this.getLogHandle(e,o));const n=m.treeEntryToResourceInfo(e,t),r=this.getLogHandleNoCtx(n);return t.markUnstable(`live_log:${g.resourceIdToString(n.id)}`),r}getLogHandleNoCtx(e){return ee("getLogHandle",e.type),Ae(!0,e)}async lastLines(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.lastLines(E(e),t,BigInt(n??0),r))}async readText(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.readText(E(e),t,BigInt(n??0),r))}async tryWithNotFound(e,t){if(!_(e))throw new Error(`Not live log handle was passed to live log driver, handle: ${e}`);try{const n=await t();return{live:!0,shouldUpdateHandle:!1,data:n.data,size:Number(n.size),newOffset:Number(n.newOffset)}}catch(n){if(n.name=="RpcError"&&n.code=="NOT_FOUND")return{shouldUpdateHandle:!0};throw n}}async releaseLastLogs(e,t){var r;((r=this.idToLastLines.get(e))==null?void 0:r.release(t))&&this.idToLastLines.delete(e)}async releaseProgressLog(e,t){var r;((r=this.idToProgressLog.get(e))==null?void 0:r.release(t))&&this.idToProgressLog.delete(e)}async releaseAll(){}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{const t=this.getAllLogs();await p.asyncPool(this.opts.nConcurrentGetLogs,t.map(n=>async()=>await n.update())),e.forEach(n=>n.resolve())}catch(t){console.error(t),e.forEach(n=>n.reject(t))}if(!this.keepRunning)break;await Se.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllLogs(){return Array.from(this.idToLastLines.entries()).concat(Array.from(this.idToProgressLog.entries())).map(([e,t])=>t)}}class Pe{constructor(e,t,n,r,o){h(this,"logs");h(this,"error");h(this,"change",new f.ChangeSource);h(this,"counter",new p.CallersCounter);this.logger=e,this.clientLogs=t,this.rInfo=n,this.lines=r,this.patternToSearch=o}getLog(){return{log:this.logs,error:this.error}}attach(e,t){this.change.attachWatcher(e),this.counter.inc(t)}release(e){return this.counter.dec(e)}async update(){try{const t=(await this.clientLogs.lastLines(this.rInfo,this.lines,0n,this.patternToSearch)).data.toString();this.logs!=t&&this.change.markChanged(),this.logs=t,this.error=void 0;return}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.logs="",this.error=e,this.change.markChanged();return}throw this.logger.error(`Stream log lines for ${g.stringifyWithResourceId(this.rInfo.id)} failed, reason: ${e}`),e}}}function ee(s,e){if(!e.name.startsWith("StreamWorkdir"))throw new x(`${s}: wrong resource type: ${e.name}, expected: a resource of type 'StreamWorkdir'.`)}class Rr{constructor(e,t,n){this.logger=e,this.logsStreamDriver=t,this.downloadDriver=n}getLastLogs(e,t,n){if(n===void 0)return f.Computable.make(o=>this.getLastLogs(e,t,o));const r=$(n,e);if(r===void 0){n.markUnstable("no stream in stream manager");return}if(B(r))return this.downloadDriver.getLastLogs(r,t,n);try{return this.logsStreamDriver.getLastLogs(r,t,n)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){n.markUnstable(`NOT_FOUND in logs stream driver while getting last logs: ${o}`);return}throw o}}getProgressLog(e,t,n){if(n===void 0)return f.Computable.make(o=>this.getProgressLog(e,t,o));const r=$(n,e);if(r===void 0){n.markUnstable("no stream in stream manager");return}if(B(r))return this.downloadDriver.getProgressLog(r,t,n);try{return this.logsStreamDriver.getProgressLog(r,t,n)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){n.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log: ${o}`);return}throw o}}getProgressLogWithInfo(e,t,n){if(n===void 0)return f.Computable.make(o=>this.getProgressLogWithInfo(e,t,o));const r=$(n,e);if(r===void 0){n.markUnstable("no stream in stream manager");return}if(B(r))return{progressLine:this.downloadDriver.getProgressLog(r,t,n),live:!1};try{return{progressLine:this.logsStreamDriver.getProgressLog(r,t,n),live:!0}}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){n.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log with info: ${o}`);return}throw o}}getLogHandle(e,t){if(t===void 0)return f.Computable.make(r=>this.getLogHandle(e,r));const n=$(t,e);if(n===void 0){t.markUnstable("no stream in stream manager");return}return B(n)?this.downloadDriver.getLogHandle(n,t):this.logsStreamDriver.getLogHandle(n,t)}async lastLines(e,t,n,r){return _(e)?await this.logsStreamDriver.lastLines(e,t,n,r):await this.downloadDriver.lastLines(e,t,n,r)}async readText(e,t,n,r){return _(e)?await this.logsStreamDriver.readText(e,t,n,r):await this.downloadDriver.readText(e,t,n,r)}}function B(s){return!s.type.name.startsWith("StreamWorkdir")}function $(s,e){var t;return(t=s.accessor(e).node().traverse("stream"))==null?void 0:t.resourceInfo}class Ir{constructor(e,t,n,r={cacheSoftSizeBytes:50*1024*1024,withGunzip:!0,nConcurrentDownloads:50}){h(this,"downloadHelper");h(this,"urlToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.saveDir=n,this.opts=r,this.downloadQueue=new p.TaskProcessor(this.logger,this.opts.nConcurrentDownloads),this.cache=new fe(this.opts.cacheSoftSizeBytes),this.downloadHelper=new Be(t)}getPath(e,t){if(t===void 0)return f.Computable.make(o=>this.getPath(e,o));const n=U.randomUUID();t.addOnDestroy(()=>this.releasePath(e,n));const r=this.getPathNoCtx(e,t.watcher,n);return(r==null?void 0:r.path)===void 0&&t.markUnstable(`a path to the downloaded and untared archive might be undefined. The current result: ${r}`),r}getPathNoCtx(e,t,n){const r=e.toString(),o=this.urlToDownload.get(r);if(o!=null)return o.attach(t,n),o.getPath();const l=this.setNewTask(t,e,n);return this.downloadQueue.push({fn:async()=>this.downloadUrl(l,n),recoverableErrorPredicate:a=>!0}),l.getPath()}async downloadUrl(e,t){var n;await e.download(this.downloadHelper,this.opts.withGunzip),((n=e.getPath())==null?void 0:n.path)!=null&&this.cache.addCache(e,t)}async releasePath(e,t){const n=e.toString(),r=this.urlToDownload.get(n);if(r!=null)if(this.cache.existsFile(r.path)){const o=this.cache.removeFile(r.path,t);await Promise.all(o.map(async l=>{await ie(l.path),this.cache.removeCache(l),this.removeTask(l,`the task ${g.stringifyWithResourceId(l.info())} was removedfrom cache along with ${g.stringifyWithResourceId(o.map(a=>a.info()))}`)}))}else r.counter.dec(t)&&this.removeTask(r,`the task ${g.stringifyWithResourceId(r.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.urlToDownload.entries()).map(async([e,t])=>{await ie(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${g.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,n){const r=new Sr(this.logger,this.getFilePath(t),t);return r.attach(e,n),this.urlToDownload.set(t.toString(),r),r}removeTask(e,t){e.abort(t),e.change.markChanged(),this.urlToDownload.delete(e.url.toString())}getFilePath(e){const t=U.createHash("sha256").update(e.toString()).digest("hex");return T.join(this.saveDir,t)}}class Sr{constructor(e,t,n){h(this,"counter",new p.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);this.logger=e,this.path=t,this.url=n}info(){return{url:this.url.toString(),path:this.path,done:this.done,size:this.size,error:this.error}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(e,t){try{const n=await this.downloadAndUntar(e,t,this.signalCtl.signal);this.setDone(n),this.change.markChanged()}catch(n){if(n instanceof Le||n instanceof O){this.setError(n),this.change.markChanged(),await ie(this.path);return}throw n}}async downloadAndUntar(e,t,n){if(await p.ensureDirExists(T.dirname(this.path)),await p.fileExists(this.path))return await it(this.path);const r=await e.download(this.url.toString(),{},n);let o=r.content;if(t){const l=L.Transform.toWeb(De.createGunzip());o=o.pipeThrough(l,{signal:n})}return await p.createPathAtomically(this.logger,this.path,async l=>{await w.mkdir(l);const a=L.Writable.toWeb(re.extract(l));await o.pipeTo(a,{signal:n})}),r.size}getPath(){if(this.done)return{path:p.notEmpty(this.path)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new Le(e))}}class Le extends Error{}async function it(s){const e=await w.readdir(s,{withFileTypes:!0});return(await Promise.all(e.map(async n=>{const r=T.join(s,n.name);return n.isDirectory()?await it(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function ie(s){await w.rm(s,{recursive:!0,force:!0})}function te(s,e){return`index://index/${encodeURIComponent(JSON.stringify({storageId:s,path:e}))}`}function Dr(s,e,t,n){const r={localPath:s,pathSignature:e.sign(s),sizeBytes:String(t),modificationTime:String(n)};return`upload://upload/${encodeURIComponent(JSON.stringify(r))}`}function vr(s){const e=new URL(s);return N.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Nr(s){const e=new URL(s);return pe.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Ue(s){if(Wr(s))return _r(s);if(Cr(s))return $r(s);p.assertNever(s)}const at=/^local:\/\/(?<name>.*)\/(?<path>.*)$/;function Cr(s){return at.test(s)}function Br(s,e){return`local://${s}/${encodeURIComponent(e)}`}function $r(s){const e=s.match(at);if(e==null)throw new Error(`Local list handle wasn't parsed: ${s}`);const{name:t,path:n}=e.groups;return{rootPath:decodeURIComponent(n),name:t,isRemote:!1}}const lt=/^remote:\/\/(?<name>.*)\/(?<resourceId>.*)$/;function Wr(s){return lt.test(s)}function Fr(s,e){return`remote://${s}/${BigInt(e)}`}function _r(s){const e=s.match(lt);if(e==null)throw new Error(`Remote list handle wasn't parsed: ${s}`);const{name:t,resourceId:n}=e.groups;return{id:g.bigintToResourceId(BigInt(n)),type:Er(t),name:t,isRemote:!0}}function Er(s){return{name:`LS/${s}`,version:"1"}}async function ct(){const s=Ie.homedir();if(k.sep=="/")return[{name:"local",root:"/",initialPath:s}];{const t=k.parse(s).root.replaceAll(":\\","");try{return(await bt.promisify(kt.exec)("wmic logicaldisk get name")).stdout.split(`\r
2
- `).filter(o=>o.includes(":")).map(o=>o.trim().replaceAll(":","")).map(o=>{const l=o==t;return{name:`local_disk_${o}`,root:`${o}:\\`,initialPath:l?s:`${o}:\\`}})}catch{return[{name:`local_disk_${t}`,root:`${t}:\\`,initialPath:s}]}}}class ye{constructor(e,t,n,r,o,l,a){this.logger=e,this.lsClient=t,this.storageIdToResourceId=n,this.signer=r,this.virtualStoragesMap=o,this.localProjectionsMap=l,this.openFileDialogCallback=a}async getLocalFileContent(e,t){const n=await this.tryResolveLocalFileHandle(e);if(t)throw new Error("Range request not yet supported.");return await w.readFile(n)}async getLocalFileSize(e){const t=await this.tryResolveLocalFileHandle(e);return(await w.stat(t)).size}async showOpenMultipleFilesDialog(e){const t=await this.openFileDialogCallback(!0,e);return t===void 0?{}:{files:await Promise.all(t.map(n=>this.getLocalFileHandle(n)))}}async showOpenSingleFileDialog(e){const t=await this.openFileDialogCallback(!1,e);return t===void 0?{}:{file:await this.getLocalFileHandle(t[0])}}async tryResolveLocalFileHandle(e){if(ne.isImportFileHandleIndex(e)){const t=Nr(e),n=this.localProjectionsMap.get(t.storageId);if(!n)throw new Error(`Storage ${t.storageId} is not mounted locally.`);return T.join(n.localPath,t.path)}else{const t=vr(e);this.signer.verify(t.localPath,t.pathSignature,"Failed to validate local file handle signature.");const n=t.localPath,r=await w.stat(n,{bigint:!0});if(String(r.mtimeMs/1000n)!==t.modificationTime)throw new Error("File has changed since the handle was created.");return n}}async getLocalFileHandle(e){I(e);for(const n of this.localProjectionsMap.values())if(e.startsWith(n.localPath)){const r=n.localPath===""?e:T.relative(n.localPath,e);return te(n.storageId,r)}const t=await w.stat(e,{bigint:!0});return Dr(e,this.signer,t.size,t.mtimeMs/1000n)}async getStorageList(){const e=[...this.virtualStoragesMap.values()].map(r=>({name:r.name,handle:Br(r.name,r.root),initialFullPath:r.initialPath})),n=Object.entries(this.storageIdToResourceId).map(([r,o])=>({name:r,handle:Fr(r,o),initialFullPath:"",isInitialPathHome:!1})).filter(r=>r.name!=="root");return[...e,...n]}async listFiles(e,t){const n=Ue(e);if(n.isRemote)return{entries:(await this.lsClient.list(n,t)).items.map(a=>({type:a.isDir?"dir":"file",name:a.name,fullPath:a.fullName,handle:te(n.name,a.fullName)}))};T.sep==="/"&&t===""&&(t="/"),n.rootPath===""&&I(t);const r=T.isAbsolute(t)?t:T.join(n.rootPath,t),o=[];for await(const l of await w.opendir(r)){if(!l.isFile()&&!l.isDirectory())continue;const a=T.join(r,l.name);o.push({type:l.isFile()?"file":"dir",name:l.name,fullPath:a,handle:await this.getLocalFileHandle(a)})}return{entries:o}}async listRemoteFilesWithAdditionalInfo(e,t){const n=Ue(e);if(!n.isRemote)throw new Error(`Storage ${n.name} is not remote`);return{entries:(await this.lsClient.list(n,t)).items.map(o=>({type:o.isDir?"dir":"file",name:o.name,fullPath:o.fullName,handle:te(n.name,o.fullName),size:Number(o.size)}))}}async fileToImportHandle(e){throw new Error("Not implemented. This method must be implemented and intercepted in desktop preload script.")}static async init(e,t,n,r,o,l){const a=Oe(t,e);l||(l=await ct());for(const u of l)I(u.root);for(const u of r)u.localPath!==""&&I(u.localPath);const d=new Map(l.map(u=>[u.name,u])),c=new Map(r.map(u=>[u.storageId,u]));if(new Set([...d.keys(),...c.keys()]).size!==d.size+c.size)throw new Error("Intersection between local projection storage ids and virtual storages names detected.");return new ye(e,a,await Mr(t),n,d,c,o)}}async function Mr(s){return s.withReadTx("GetAvailableStorageIds",async e=>{const t=await e.getResourceByName("LSProvider"),n=await e.getResourceData(t,!0);return Or(n)})}function Or(s){return Object.fromEntries(s.fields.filter(e=>e.type=="Dynamic"&&g.isNotNullResourceId(e.value)).map(e=>[e.name.substring(8),e.value]))}exports.ClientDownload=$e;exports.ClientLogs=Me;exports.ClientLs=Ee;exports.ClientProgress=Ce;exports.ClientUpload=Ne;exports.DefaultVirtualLocalStorages=ct;exports.DownloadBlobToURLDriver=ur;exports.DownloadDriver=me;exports.DownloadUrlDriver=Ir;exports.DownloadableBlobSnapshot=Ke;exports.ImportFileHandleData=er;exports.ImportFileHandleIndexData=pe;exports.ImportFileHandleUploadData=N;exports.IndexResourceSnapshot=Ze;exports.LogsDriver=Rr;exports.LogsStreamDriver=Ur;exports.LsDriver=ye;exports.MTimeError=ce;exports.NetworkError=he;exports.NoFileForUploading=ue;exports.OnDemandBlobResourceSnapshot=Ve;exports.UnexpectedEOF=de;exports.UnknownStorageError=z;exports.Updater=xe;exports.UploadDriver=kr;exports.UploadResourceSnapshot=Je;exports.UploadTask=tt;exports.WrongLocalFileUrl=H;exports.WrongResourceTypeError=x;exports.createDownloadClient=jn;exports.createLogsClient=Gn;exports.createLsFilesClient=Oe;exports.createUploadBlobClient=qn;exports.createUploadProgressClient=Vn;exports.getFullPath=Fe;exports.getSize=qe;exports.isMyUpload=rt;exports.isResourceWasDeletedError=se;exports.isSignMatch=ot;exports.isUpload=M;exports.makeBlobImportSnapshot=st;exports.makeDownloadableBlobSnapshot=Xe;exports.newLocalStorageIdsToRoot=_e;exports.nonRecoverableError=we;exports.parseLocalUrl=We;exports.uploadBlob=nt;exports.validateAbsolute=I;
1
+ "use strict";var wt=Object.defineProperty;var mt=(s,e,t)=>e in s?wt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var h=(s,e,t)=>mt(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@milaboratories/pl-client"),yt=require("node:fs/promises"),ve=require("undici"),y=require("@protobuf-ts/runtime-rpc"),i=require("@protobuf-ts/runtime"),p=require("@milaboratories/ts-helpers"),R=require("node:fs"),P=require("node:path"),L=require("node:stream"),ce=require("node:stream/consumers"),f=require("@milaboratories/computable"),E=require("@milaboratories/pl-model-common"),m=require("@milaboratories/pl-tree"),Tt=require("denque"),U=require("node:crypto"),Ne=require("node:os"),bt=require("node:readline/promises"),k=require("zod"),kt=require("@milaboratories/helpers"),Pt=require("node:zlib"),Lt=require("tar-fs"),Ut=require("decompress"),Ce=require("node:timers/promises"),Rt=require("node:assert"),St=require("node:util"),Dt=require("node:child_process");function S(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const w=S(yt),de=S(R),b=S(P),Pe=S(Ne),It=S(bt),$e=S(Pt),se=S(Lt);class vt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new vt;class Nt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Nt;class Ct extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const $t=new Ct;class Bt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Response",[{no:1,name:"parts_count",kind:"scalar",T:4,L:0},{no:2,name:"uploaded_parts",kind:"scalar",repeat:1,T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.partsCount=0n,t.uploadedParts=[],e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.partsCount=e.uint64().toBigInt();break;case 2:if(d===i.WireType.LengthDelimited)for(let G=e.int32()+e.pos;e.pos<G;)o.uploadedParts.push(e.uint64().toBigInt());else o.uploadedParts.push(e.uint64().toBigInt());break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){if(e.partsCount!==0n&&t.tag(1,i.WireType.Varint).uint64(e.partsCount),e.uploadedParts.length){t.tag(2,i.WireType.LengthDelimited).fork();for(let o=0;o<e.uploadedParts.length;o++)t.uint64(e.uploadedParts[o]);t.join()}const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Ft=new Bt;class Wt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Wt;class _t extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"bytes_processed",kind:"scalar",T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.bytesProcessed=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.bytesProcessed=e.int64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.bytesProcessed!==0n&&t.tag(2,i.WireType.Varint).int64(e.bytesProcessed);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Et=new _t;class Mt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Ot=new Mt;class zt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new zt;class Ht extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"part_number",kind:"scalar",T:4,L:0},{no:3,name:"uploaded_part_size",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.partNumber=0n,t.uploadedPartSize=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.partNumber=e.uint64().toBigInt();break;case 3:o.uploadedPartSize=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.partNumber!==0n&&t.tag(2,i.WireType.Varint).uint64(e.partNumber),e.uploadedPartSize!==0n&&t.tag(3,i.WireType.Varint).uint64(e.uploadedPartSize);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const xt=new Ht;class At extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.name!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.value);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const V=new At;class jt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Response",[{no:1,name:"upload_url",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"headers",kind:"message",repeat:1,T:()=>V},{no:4,name:"chunk_start",kind:"scalar",T:4,L:0},{no:5,name:"chunk_end",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.uploadUrl="",t.method="",t.headers=[],t.chunkStart=0n,t.chunkEnd=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.uploadUrl=e.string();break;case 2:o.method=e.string();break;case 3:o.headers.push(V.internalBinaryRead(e,e.uint32(),n));break;case 4:o.chunkStart=e.uint64().toBigInt();break;case 5:o.chunkEnd=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.uploadUrl!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.uploadUrl),e.method!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.method);for(let o=0;o<e.headers.length;o++)V.internalBinaryWrite(e.headers[o],t.tag(3,i.WireType.LengthDelimited).fork(),n).join();e.chunkStart!==0n&&t.tag(4,i.WireType.Varint).uint64(e.chunkStart),e.chunkEnd!==0n&&t.tag(5,i.WireType.Varint).uint64(e.chunkEnd);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Gt=new jt;class Vt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Vt;class qt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Jt=new qt;class Zt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Qt=new Zt,q=new y.ServiceType("MiLaboratories.Controller.Shared.Upload",[{name:"Init",options:{},I:$t,O:Ft},{name:"GetPartURL",options:{},I:xt,O:Gt},{name:"UpdateProgress",options:{},I:Et,O:Ot},{name:"Finalize",options:{},I:Jt,O:Qt}]);class Kt{constructor(e){h(this,"typeName",q.typeName);h(this,"methods",q.methods);h(this,"options",q.options);this._transport=e}init(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}getPartURL(e,t){const n=this.methods[1],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}updateProgress(e,t){const n=this.methods[2],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}finalize(e,t){const n=this.methods[3],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}function Be(s,e,t){const n=Object.fromEntries(s.map(({name:r,value:o})=>[r,o]));return e!==void 0&&t!==void 0&&(n.Range=`bytes=${e}-${t-1}`),n}class he extends Error{}class ue extends Error{}class pe extends Error{}class ge extends Error{}class Fe{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=r,this.grpcClient=new Kt(this.grpcTransport)}close(){}async initUpload({id:e,type:t},n){const r=await this.grpcInit(e,t,n);return{overall:r.partsCount,toUpload:this.partsToUpload(r.partsCount,r.uploadedParts)}}async partUpload({id:e,type:t},n,r,o,l){const a=await this.grpcGetPartUrl({id:e,type:t},o,0n,l),d=await Xt(n,a.chunkStart,a.chunkEnd);await en(n,r);try{const{body:c,statusCode:u,headers:G}=await ve.request(a.uploadUrl,{dispatcher:this.httpClient,body:d,headersTimeout:6e4,bodyTimeout:6e4,headers:Be(a.headers),method:a.method.toUpperCase()}),ft=await c.text();tn(u,ft,G,a)}catch(c){throw c instanceof pe?c:new Error(`partUpload: error ${JSON.stringify(c)} happened while trying to do part upload to the url ${a.uploadUrl}, headers: ${JSON.stringify(a.headers)}`)}await this.grpcUpdateProgress({id:e,type:t},BigInt(a.chunkEnd-a.chunkStart),l)}async finalize(e,t){return await this.grpcFinalize(e,t)}partsToUpload(e,t){const n=[],r=new Set(t);for(let o=1n;o<=e;o++)r.has(o)||n.push(o);return n}async grpcInit(e,t,n){return await this.grpcClient.init({resourceId:e},g.addRTypeToMetadata(t,n)).response}async grpcGetPartUrl({id:e,type:t},n,r,o){return await this.grpcClient.getPartURL({resourceId:e,partNumber:n,uploadedPartSize:r},g.addRTypeToMetadata(t,o)).response}async grpcUpdateProgress({id:e,type:t},n,r){await this.grpcClient.updateProgress({resourceId:e,bytesProcessed:n},g.addRTypeToMetadata(t,r)).response}async grpcFinalize({id:e,type:t},n){return await this.grpcClient.finalize({resourceId:e},g.addRTypeToMetadata(t,n)).response}}async function Xt(s,e,t){let n;try{n=await w.open(s);const r=Number(t-e),o=Number(e),l=Buffer.alloc(r),a=await Yt(n,l,r,o);return l.subarray(0,a)}catch(r){throw r&&typeof r=="object"&&"code"in r&&r.code=="ENOENT"?new ge(`there is no file ${s} for uploading`):r}finally{await(n==null?void 0:n.close())}}async function Yt(s,e,t,n){let r=0;for(;r<t;){const{bytesRead:o}=await s.read(e,r,t-r,n+r);if(o===0)throw new ue("file ended earlier than expected.");r+=o}return r}async function en(s,e){const t=BigInt(Math.floor((await w.stat(s)).mtimeMs/1e3));if(t>e)throw new he(`file was modified, expected mtime: ${e}, got: ${t}.`)}function tn(s,e,t,n){if(s!=200)throw new pe(`response is not ok, status code: ${s}, body: ${e}, headers: ${JSON.stringify(t)}, url: ${n.uploadUrl}`)}class nn extends i.MessageType{constructor(){super("google.protobuf.Duration",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}internalJsonWrite(e,t){const n=i.PbLong.from(e.seconds).toNumber();if(n>315576e6||n<-315576e6)throw new Error("Duration value out of range.");let r=e.seconds.toString();if(n===0&&e.nanos<0&&(r="-"+r),e.nanos!==0){let o=Math.abs(e.nanos).toString();o="0".repeat(9-o.length)+o,o.substring(3)==="000000"?o=o.substring(0,3):o.substring(6)==="000"&&(o=o.substring(0,6)),r+="."+o}return r+"s"}internalJsonRead(e,t,n){if(typeof e!="string")throw new Error("Unable to parse Duration from JSON "+i.typeofJsonValue(e)+". Expected string.");const r=e.match(/^(-?)([0-9]+)(?:\.([0-9]+))?s/);if(r===null)throw new Error("Unable to parse Duration from JSON string. Invalid format.");n||(n=this.create());const[,o,l,a]=r,d=i.PbLong.from(o+l);if(d.toNumber()>315576e6||d.toNumber()<-315576e6)throw new Error("Unable to parse Duration from JSON string. Value out of range.");if(n.seconds=d.toBigInt(),typeof a=="string"){const c=o+a+"0".repeat(9-a.length);n.nanos=parseInt(c)}return n}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.seconds!==0n&&t.tag(1,i.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,i.WireType.Varint).int32(e.nanos);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const _=new nn;class rn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new rn;class on extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.Report",[{no:1,name:"progress",kind:"scalar",T:2},{no:2,name:"bytes_processed",kind:"scalar",T:4,L:0},{no:3,name:"bytes_total",kind:"scalar",T:4,L:0},{no:4,name:"done",kind:"scalar",T:8},{no:5,name:"name",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.progress=0,t.bytesProcessed=0n,t.bytesTotal=0n,t.done=!1,t.name="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.progress=e.float();break;case 2:o.bytesProcessed=e.uint64().toBigInt();break;case 3:o.bytesTotal=e.uint64().toBigInt();break;case 4:o.done=e.bool();break;case 5:o.name=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.progress!==0&&t.tag(1,i.WireType.Bit32).float(e.progress),e.bytesProcessed!==0n&&t.tag(2,i.WireType.Varint).uint64(e.bytesProcessed),e.bytesTotal!==0n&&t.tag(3,i.WireType.Varint).uint64(e.bytesTotal),e.done!==!1&&t.tag(4,i.WireType.Varint).bool(e.done),e.name!==""&&t.tag(5,i.WireType.LengthDelimited).string(e.name);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const I=new on;class sn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new sn;class an extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const ln=new an;class cn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Response",[{no:1,name:"report",kind:"message",T:()=>I}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.report=I.internalBinaryRead(e,e.uint32(),n,o.report);break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.report&&I.internalBinaryWrite(e.report,t.tag(1,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const dn=new cn;class hn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new hn;class un extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"update_interval",kind:"message",T:()=>_}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.updateInterval=_.internalBinaryRead(e,e.uint32(),n,o.updateInterval);break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.updateInterval&&_.internalBinaryWrite(e.updateInterval,t.tag(2,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const pn=new un;class gn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Response",[{no:1,name:"report",kind:"message",T:()=>I}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.report=I.internalBinaryRead(e,e.uint32(),n,o.report);break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.report&&I.internalBinaryWrite(e.report,t.tag(1,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const fn=new gn,J=new y.ServiceType("MiLaboratories.Controller.Shared.Progress",[{name:"GetStatus",options:{"google.api.http":{get:"/resources/{resource_id}/get-progress"}},I:ln,O:dn},{name:"RealtimeStatus",serverStreaming:!0,options:{},I:pn,O:fn}]);class wn{constructor(e){h(this,"typeName",J.typeName);h(this,"methods",J.methods);h(this,"options",J.options);this._transport=e}getStatus(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}realtimeStatus(e,t){const n=this.methods[1],r=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,n,r,e)}}class We{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.client=n,this.logger=r,this.grpcClient=new wn(this.grpcTransport)}close(){}async getStatus({id:e,type:t},n){const r=await this.grpcClient.getStatus({resourceId:e},g.addRTypeToMetadata(t,n)),o=p.notEmpty(r.response.report);return{done:o.done,progress:o.progress,bytesProcessed:String(o.bytesProcessed),bytesTotal:String(o.bytesTotal)}}async*realtimeStatus({id:e,type:t},n=100,r){r=g.addRTypeToMetadata(t,r);const o=Math.floor(n/1e3),l=(n-o*1e3)*1e6,a=_.create({seconds:BigInt(o),nanos:l});try{const{responses:d}=this.grpcClient.realtimeStatus({resourceId:e,updateInterval:a},r);yield*d}catch(d){throw this.logger.warn("Failed to get realtime status"+String(d)),d}}}class H extends Error{}class _e{constructor(e){this.httpClient=e}async download(e,t,n){const{statusCode:r,body:o,headers:l}=await ve.request(e,{dispatcher:this.httpClient,headers:t,signal:n}),a=L.Readable.toWeb(o);return await mn(r,a,e),{content:a,size:Number(l["content-length"])}}}async function mn(s,e,t){if(s!=200&&s!=206){const n=(await ce.text(e)).substring(0,1e3);throw 400<=s&&s<500?new H(`Http error: statusCode: ${s} url: ${t.toString()}, beginning of body: ${n}`):new Error(`Http error: statusCode: ${s} url: ${t.toString()}`)}}function D(s){if(!P.isAbsolute(s))throw new Error(`Path ${s} is not absolute.`);return s}class yn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new yn;class Tn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Tn;class bn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const kn=new bn;class Pn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.name!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.value);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Z=new Pn;class Ln extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Response",[{no:1,name:"download_url",kind:"scalar",T:9},{no:2,name:"headers",kind:"message",repeat:1,T:()=>Z}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.downloadUrl="",t.headers=[],e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.downloadUrl=e.string();break;case 2:o.headers.push(Z.internalBinaryRead(e,e.uint32(),n));break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.downloadUrl!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.downloadUrl);for(let o=0;o<e.headers.length;o++)Z.internalBinaryWrite(e.headers[o],t.tag(2,i.WireType.LengthDelimited).fork(),n).join();const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Un=new Ln,Q=new y.ServiceType("MiLaboratories.Controller.Shared.Download",[{name:"GetDownloadURL",options:{"google.api.http":{get:"/resources/{resource_id}/get-download-url"}},I:kn,O:Un}]);class Rn{constructor(e){h(this,"typeName",Q.typeName);h(this,"methods",Q.methods);h(this,"options",Q.options);this._transport=e}getDownloadURL(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}class Ee{constructor(e,t,n,r){h(this,"grpcClient");h(this,"remoteFileDownloader");h(this,"localStorageIdsToRoot");this.grpcTransport=e,this.httpClient=t,this.logger=n,this.grpcClient=new Rn(this.grpcTransport),this.remoteFileDownloader=new _e(t),this.localStorageIdsToRoot=ze(r)}close(){}async downloadBlob(e,t,n,r,o){const{downloadUrl:l,headers:a}=await this.grpcGetDownloadUrl(e,t,n),d=Be(a,r,o);return this.logger.info(`download blob from url ${l}, headers: ${JSON.stringify(d)}`),Dn(l)?await this.readLocalFile(l,r,o):await this.remoteFileDownloader.download(l,d,n)}async readLocalFile(e,t,n){const{storageId:r,relativePath:o}=Me(e),l=Oe(r,this.localStorageIdsToRoot,o);return{content:L.Readable.toWeb(de.createReadStream(l,{start:t,end:n!==void 0?n-1:void 0})),size:(await w.stat(l)).size}}async grpcGetDownloadUrl({id:e,type:t},n,r){const o=n??{};return o.abort=r,await this.grpcClient.getDownloadURL({resourceId:e},g.addRTypeToMetadata(t,o)).response}}function Me(s){const e=new URL(s);if(e.pathname=="")throw new x(`url for local filepath ${s} does not match url scheme`);return{storageId:e.host,relativePath:decodeURIComponent(e.pathname.slice(1))}}function Oe(s,e,t){const n=e.get(s);if(n===void 0)throw new A(`Unknown storage location: ${s}`);return n===""?t:b.join(n,t)}const Sn="storage://";function Dn(s){return s.startsWith(Sn)}class x extends Error{}class A extends Error{}function ze(s){const e=new Map;for(const t of s)t.localPath!==""&&D(t.localPath),e.set(t.storageId,t.localPath);return e}class In extends i.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=i.PbLong.from(Math.floor(t/1e3)).toBigInt(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(i.PbLong.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),n=e.getTime();return t.seconds=i.PbLong.from(Math.floor(n/1e3)).toBigInt(),t.nanos=n%1e3*1e6,t}internalJsonWrite(e,t){const n=i.PbLong.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let r="Z";if(e.nanos>0){const o=(e.nanos+1e9).toString().substring(1);o.substring(3)==="000000"?r="."+o.substring(0,3)+"Z":o.substring(6)==="000"?r="."+o.substring(0,6)+"Z":r="."+o+"Z"}return new Date(n).toISOString().replace(".000Z",r)}internalJsonRead(e,t,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+i.typeofJsonValue(e)+".");const r=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!r)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");const o=Date.parse(r[1]+"-"+r[2]+"-"+r[3]+"T"+r[4]+":"+r[5]+":"+r[6]+(r[8]?r[8]:"Z"));if(Number.isNaN(o))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(o<Date.parse("0001-01-01T00:00:00Z")||o>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return n||(n=this.create()),n.seconds=i.PbLong.from(o/1e3).toBigInt(),n.nanos=0,r[7]&&(n.nanos=parseInt("1"+r[7]+"0".repeat(9-r[7].length))-1e9),n}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.seconds!==0n&&t.tag(1,i.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,i.WireType.Varint).int32(e.nanos);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const K=new In;class vn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new vn;class Nn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.ListItem",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"is_dir",kind:"scalar",T:8},{no:10,name:"full_name",kind:"scalar",T:9},{no:11,name:"directory",kind:"scalar",T:9},{no:12,name:"last_modified",kind:"message",T:()=>K},{no:13,name:"version",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.size=0n,t.isDir=!1,t.fullName="",t.directory="",t.version="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.name=e.string();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.isDir=e.bool();break;case 10:o.fullName=e.string();break;case 11:o.directory=e.string();break;case 12:o.lastModified=K.internalBinaryRead(e,e.uint32(),n,o.lastModified);break;case 13:o.version=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.name!==""&&t.tag(1,i.WireType.LengthDelimited).string(e.name),e.size!==0n&&t.tag(2,i.WireType.Varint).uint64(e.size),e.isDir!==!1&&t.tag(3,i.WireType.Varint).bool(e.isDir),e.fullName!==""&&t.tag(10,i.WireType.LengthDelimited).string(e.fullName),e.directory!==""&&t.tag(11,i.WireType.LengthDelimited).string(e.directory),e.lastModified&&K.internalBinaryWrite(e.lastModified,t.tag(12,i.WireType.LengthDelimited).fork(),n).join(),e.version!==""&&t.tag(13,i.WireType.LengthDelimited).string(e.version);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const X=new Nn;class Cn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new Cn;class $n extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"location",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.location="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.location=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.location!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.location);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Bn=new $n;class Fn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Response",[{no:1,name:"items",kind:"message",repeat:1,T:()=>X},{no:2,name:"delimiter",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.items=[],t.delimiter="",e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.items.push(X.internalBinaryRead(e,e.uint32(),n));break;case 2:o.delimiter=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){for(let o=0;o<e.items.length;o++)X.internalBinaryWrite(e.items[o],t.tag(1,i.WireType.LengthDelimited).fork(),n).join();e.delimiter!==""&&t.tag(2,i.WireType.LengthDelimited).string(e.delimiter);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Wn=new Fn,Y=new y.ServiceType("MiLaboratories.Controller.Shared.LS",[{name:"List",options:{},I:Bn,O:Wn}]);class _n{constructor(e){h(this,"typeName",Y.typeName);h(this,"methods",Y.methods);h(this,"options",Y.options);this._transport=e}list(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}class He{constructor(e,t){h(this,"grpcClient");this.logger=t,this.grpcClient=new _n(e)}close(){}async list(e,t,n){return await this.grpcClient.list({resourceId:e.id,location:t},g.addRTypeToMetadata(e.type,n)).response}}class En extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){return r??this.create()}internalBinaryWrite(e,t,n){const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}new En;class Mn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;case 20:o.readLimit=e.int64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,i.WireType.Varint).uint32(e.chunkSize),e.readLimit!==void 0&&t.tag(20,i.WireType.Varint).int64(e.readLimit);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const On=new Mn;class zn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,i.WireType.Varint).uint32(e.chunkSize);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Hn=new zn;class xn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,i.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,i.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,i.WireType.LengthDelimited).string(e.searchRe);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const An=new xn;class jn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,i.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,i.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,i.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,i.WireType.LengthDelimited).string(e.searchRe);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const Gn=new jn;class Vn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.LastLines",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",opt:!0,T:3,L:0},{no:3,name:"line_count",kind:"scalar",opt:!0,T:5},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 3:o.lineCount=e.int32();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.resourceId!==0n&&t.tag(1,i.WireType.Varint).uint64(e.resourceId),e.offset!==void 0&&t.tag(2,i.WireType.Varint).int64(e.offset),e.lineCount!==void 0&&t.tag(3,i.WireType.Varint).int32(e.lineCount),e.search!==void 0&&t.tag(21,i.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,i.WireType.LengthDelimited).string(e.searchRe);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const qn=new Vn;class Jn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.Response",[{no:1,name:"data",kind:"scalar",T:12},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"new_offset",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.data=new Uint8Array(0),t.size=0n,t.newOffset=0n,e!==void 0&&i.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,n,r){const o=r??this.create(),l=e.pos+t;for(;e.pos<l;){const[a,d]=e.tag();switch(a){case 1:o.data=e.bytes();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.newOffset=e.uint64().toBigInt();break;default:const c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${d}) for ${this.typeName}`);const u=e.skip(d);c!==!1&&(c===!0?i.UnknownFieldHandler.onRead:c)(this.typeName,o,a,d,u)}}return o}internalBinaryWrite(e,t,n){e.data.length&&t.tag(1,i.WireType.LengthDelimited).bytes(e.data),e.size!==0n&&t.tag(2,i.WireType.Varint).uint64(e.size),e.newOffset!==0n&&t.tag(3,i.WireType.Varint).uint64(e.newOffset);const r=n.writeUnknownFields;return r!==!1&&(r==!0?i.UnknownFieldHandler.onWrite:r)(this.typeName,e,t),t}}const v=new Jn,ee=new y.ServiceType("MiLaboratories.Controller.Shared.Streaming",[{name:"StreamBinary",serverStreaming:!0,options:{},I:On,O:v},{name:"ReadBinary",options:{},I:Hn,O:v},{name:"StreamText",serverStreaming:!0,options:{},I:An,O:v},{name:"ReadText",options:{},I:Gn,O:v},{name:"LastLines",options:{},I:qn,O:v}]);class Zn{constructor(e){h(this,"typeName",ee.typeName);h(this,"methods",ee.methods);h(this,"options",ee.options);this._transport=e}streamBinary(e,t){const n=this.methods[0],r=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,n,r,e)}readBinary(e,t){const n=this.methods[1],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}streamText(e,t){const n=this.methods[2],r=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,n,r,e)}readText(e,t){const n=this.methods[3],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}lastLines(e,t){const n=this.methods[4],r=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,n,r,e)}}class xe{constructor(e,t,n){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=n,this.grpcClient=new Zn(this.grpcTransport)}close(){}async lastLines({id:e,type:t},n,r=0n,o,l){return(await this.grpcClient.lastLines({resourceId:e,lineCount:n,offset:r,search:o},g.addRTypeToMetadata(t,l))).response}async readText({id:e,type:t},n,r=0n,o,l){return(await this.grpcClient.readText({resourceId:p.notEmpty(e),readLimit:BigInt(n),offset:r,search:o},g.addRTypeToMetadata(t,l))).response}}function Qn(s,e,t){return e.getDriver({name:"DownloadBlob",init:(n,r,o)=>new Ee(r,o,s,t)})}function Kn(s,e){return s.getDriver({name:"StreamLogs",init:(t,n,r)=>new xe(n,r,e)})}function Xn(s,e){return s.getDriver({name:"UploadProgress",init:(t,n,r)=>new We(n,r,s,e)})}function Yn(s,e){return s.getDriver({name:"UploadBlob",init:(t,n,r)=>new Fe(n,r,s,e)})}function Ae(s,e){return s.getDriver({name:"LsFiles",init:(t,n,r)=>new He(n,e)})}const je=/^blob\+local:\/\/download\/(?<path>.*)#(?<signature>.*)$/;function er(s,e){return`blob+local://download/${s}#${e.sign(s)}`}function tr(s){return!!s.match(je)}function te(s,e){const t=s.match(je);if(t===null)throw new Error(`Local handle is malformed: ${s}, matches: ${t}`);const{path:n,signature:r}=t.groups;return e.verify(n,r,`Signature verification failed for: ${s}`),{path:n,signature:r}}const Ge=m.rsSchema({kv:{"ctl/file/blobInfo":k.z.object({sizeBytes:k.z.coerce.number()})}});function fe(s,e){const t=s.kv["ctl/file/blobInfo"].sizeBytes;if(e){const n=e.to-e.from;if(n>t)throw new Error(`getSize: range (${JSON.stringify(e)}, newSize: ${n}) is greater than size (${t})`);return n}return t}const C=k.z.object({localPath:k.z.string(),pathSignature:k.z.string(),sizeBytes:k.z.string(),modificationTime:k.z.string()}),we=k.z.object({storageId:k.z.string(),path:k.z.string()}),nr=k.z.union([C,we]),Ve=m.rsSchema({data:C,fields:{blob:!1}}),qe=m.rsSchema({fields:{incarnation:!1}}),Je=/^blob\+remote:\/\/download\/(?<content>(?<resourceType>.+)\/(?<resourceVersion>.+?)\/(?<resourceId>\d+?)\/(?<size>\d+?))#(?<signature>.*)$/;function rr(s,e){let t=`${s.type.name}/${s.type.version}/${BigInt(s.id)}/${fe(s)}`;return`blob+remote://download/${t}#${e.sign(t)}`}function or(s){return!!s.match(Je)}function sr(s,e){const t=s.match(Je);if(t===null)throw new Error(`Remote handle is malformed: ${s}, matches: ${t}`);const{content:n,resourceType:r,resourceVersion:o,resourceId:l,size:a,signature:d}=t.groups;return e.verify(n,d,`Signature verification failed for ${s}`),{info:{id:g.bigintToResourceId(BigInt(l)),type:{name:r,version:o}},size:Number(a)}}class j extends Error{}class Ze{constructor(e){h(this,"updating");this.onUpdate=e}schedule(){this.updating==null&&(this.updating=(async()=>{try{await this.onUpdate()}catch(e){console.log(`error while updating in Updater: ${e}`)}finally{this.updating=void 0}})())}}function Qe(s,e){return s?`log+live://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`:`log+ready://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`}const Ke=/^log\+live:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function M(s){return Ke.test(s)}const Xe=/^log\+ready:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function ir(s){return Xe.test(s)}function O(s){let e;if(M(s))e=s.match(Ke);else if(ir(s))e=s.match(Xe);else throw new Error(`Log handle is malformed: ${s}`);if(e==null)throw new Error(`Log handle wasn't parsed: ${s}`);const{resourceType:t,resourceVersion:n,resourceId:r}=e.groups;return{id:g.bigintToResourceId(BigInt(r)),type:{name:t,version:n}}}function T(s){return`${BigInt(s)}`}function Le(s){return b.basename(s)}class ar{constructor(e,t,n,r,o){h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"counter",new p.CallersCounter);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"state",{});this.logger=e,this.clientDownload=t,this.rInfo=n,this.handle=r,this.path=o}info(){return{rInfo:this.rInfo,fPath:this.path,done:this.done,error:this.error,state:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.ensureDownloaded();this.setDone(e),this.change.markChanged()}catch(e){throw this.logger.error(`task failed: ${e}, ${JSON.stringify(this.state)}`),me(e)&&(this.setError(e),this.change.markChanged(),await w.rm(this.path)),e}}async ensureDownloaded(){if(this.state={},this.state.filePath=this.path,await p.ensureDirExists(b.dirname(this.state.filePath)),this.state.dirExists=!0,await p.fileExists(this.state.filePath)){this.state.fileExists=!0,this.logger.info(`a blob was already downloaded: ${this.state.filePath}`);const n=await w.stat(this.state.filePath);return this.state.fileSize=n.size,this.state.fileSize}const{content:e,size:t}=await this.clientDownload.downloadBlob(this.rInfo,{},void 0);return this.state.fileSize=t,this.state.downloaded=!0,await p.createPathAtomically(this.logger,this.state.filePath,async n=>{const r=L.Writable.toWeb(R.createWriteStream(n,{flags:"wx"}));await e.pipeTo(r),this.state.tempWritten=!0}),this.state.done=!0,t}abort(e){this.signalCtl.abort(new Ye(e))}getBlob(){return this.done?{done:this.done,result:lr(this.handle,this.size,this.error)}:{done:!1}}setDone(e){this.done=!0,this.size=e}setError(e){this.done=!0,this.error=e}}function me(s){return s instanceof Ye||s instanceof H||s instanceof A||s instanceof x||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")}class Ye extends Error{}function lr(s,e,t){return t?{ok:!1,error:t}:s?{ok:!0,value:{handle:s,size:e}}:{ok:!1,error:new Error("No file or handle provided")}}class ye{constructor(e){h(this,"cache",new Map);h(this,"totalSizeBytes",0);this.softSizeBytes=e}existsFile(e){return this.cache.get(e)!=null}getFile(e,t){const n=this.cache.get(e);return n!=null&&n.counter.inc(t),n}removeFile(e,t){return p.mapGet(this.cache,e).counter.dec(t),this.toDelete()}toDelete(){if(this.totalSizeBytes<=this.softSizeBytes)return[];const e=[];let t=0;return p.mapEntries(this.cache).filter(([n,r])=>r.counter.isZero()).forEach(([n,r])=>{if(this.totalSizeBytes-t<=this.softSizeBytes)return;const o=p.mapGet(this.cache,n);t+=o.size,e.push(o)}),e}addCache(e,t){const n=this.cache.get(e.path)==null;if(this.cache.set(e.path,e),e.counter.inc(t),e.size<0)throw new Error(`empty sizeBytes: ${e}`);n&&(this.totalSizeBytes+=e.size)}removeCache(e){this.cache.delete(e.path),this.totalSizeBytes-=e.size}}const cr=k.z.object({ranges:k.z.array(E.RangeBytes)}),dr=".ranges.json";function hr(s){return s+dr}async function ur(s,e){let t={ranges:[]};try{const n=await w.readFile(e,"utf8");t=cr.parse(JSON.parse(n))}catch(n){if(n instanceof SyntaxError||n instanceof k.z.ZodError){const r=`readRangesFile: the file ${e} was corrupted: ${n}`;throw s.error(r),new tt(r)}if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw n}return et(t),t}async function pr(s,e,t){await p.createPathAtomically(s,e,async n=>{await w.writeFile(n,JSON.stringify(t,null,2),{flag:"wx"})})}function et(s){s.ranges.sort((e,t)=>e.from-t.from);for(let e=0;e<s.ranges.length-1;e++)s.ranges[e].to>=s.ranges[e+1].from&&(gr(s,e),e--)}function gr(s,e){const t=Math.min(s.ranges[e].from,s.ranges[e+1].from),n=Math.max(s.ranges[e].to,s.ranges[e+1].to);s.ranges.splice(e,2,{from:t,to:n})}function $(s){return s.ranges.reduce((e,t)=>e+t.to-t.from,0)}function fr(s,e){for(const t of s.ranges)if(t.from<=e.from&&e.to<=t.to)return!0;return!1}function wr(s,e){return s.ranges.push(e),et(s),s}async function mr(s,e,t){try{await(await w.open(e,"w")).close(),await yr(e,t)}catch(n){s.error(`Error creating file ${e} on platform ${t}: ${n}`)}}async function yr(s,e){e==="win32"&&await p.spawnAsync("fsutil",["sparse","setflag",`"${s}"`],{stdio:"pipe"})}async function Tr(s,e,t,n,r){await p.fileExists(t)||await mr(s,t,e);const o=await w.open(t,"r+");await o.write(n,0,n.length,r),await o.close()}class tt extends Error{}class br{constructor(e,t){this.logger=e,this.cacheDir=t}fPath(e){return P.join(this.cacheDir,hr(e))}async get(e){return await ur(this.logger,this.fPath(e))}async set(e,t){return await pr(this.logger,this.fPath(e),t)}async delete(e){await R.promises.rm(this.fPath(e))}}class kr{constructor(e,t){h(this,"suffix",".sparse.bin");this.logger=e,this.cacheDir=t}async all(){return await p.ensureDirExists(this.cacheDir),(await R.promises.readdir(this.cacheDir)).filter(t=>t.endsWith(this.suffix))}async exists(e){return await p.fileExists(this.path(e))}path(e){return P.join(this.cacheDir,e+this.suffix)}async write(e,t,n){await p.ensureDirExists(this.cacheDir),await Tr(this.logger,process.platform,this.path(e),t,n)}async delete(e){await R.promises.rm(this.path(e))}}class Pr{constructor(e,t,n,r){h(this,"lock",new kt.functions.AwaitLock);h(this,"keyToLastAccessTime",new Map);h(this,"size",0);this.logger=e,this.maxSize=t,this.ranges=n,this.storage=r}async reset(){await ne(this.lock,async()=>{await this.resetUnsafe()})}async get(e,t){return await ne(this.lock,async()=>await this.getUnsafe(e,t))}async set(e,t,n){await ne(this.lock,async()=>{await this.setUnsafe(e,t,n)})}async resetUnsafe(){this.size=0,this.keyToLastAccessTime=new Map;const e=new Date;for(const t of await this.storage.all()){const n=await this.ranges.get(t);this.size+=$(n),this.keyToLastAccessTime.set(t,e)}}async getUnsafe(e,t){if(await this.storage.exists(e)){this.keyToLastAccessTime.set(e,new Date);const n=await this.getRanges(e);return fr(n,t)?this.storage.path(e):void 0}}async setUnsafe(e,t,n){await this.setWithoutEviction(e,t,n),await this.ensureEvicted()}async setWithoutEviction(e,t,n){if(t.to-t.from!==n.length)throw new Error(`SparseCache.set: trying to set ${e} with wrong range length: range: ${JSON.stringify(t)}, data: ${n.length}`);this.keyToLastAccessTime.set(e,new Date);const r=await this.getRanges(e);this.size-=$(r),await this.storage.write(e,n,t.from);const o=wr(r,t);this.size+=$(o),await this.ranges.set(e,o)}async ensureEvicted(){const e=p.mapEntries(this.keyToLastAccessTime);for(e.sort(([t,n],[r,o])=>o.getTime()-n.getTime());this.size>this.maxSize;){const t=e.pop();if(!t)break;const[n,r]=t,o=await this.getRanges(n);this.size-=$(o),this.rmKey(n)}}async getRanges(e){try{return await this.ranges.get(e)}catch(t){if(t instanceof tt)return await this.rmKey(e),await this.resetUnsafe(),await this.ranges.get(e);throw t}}async rmKey(e){await this.storage.delete(e),await this.ranges.delete(e),this.keyToLastAccessTime.delete(e)}}async function ne(s,e){try{return await s.acquireAsync(),await e()}finally{s.release()}}class Te{constructor(e,t,n,r,o,l,a){h(this,"keyToDownload",new Map);h(this,"cache");h(this,"rangesCache");h(this,"downloadQueue");h(this,"keyToOnDemand",new Map);h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"saveDir");this.logger=e,this.clientDownload=t,this.clientLogs=n,this.rangesCacheDir=o,this.signer=l,this.ops=a,this.cache=new ye(this.ops.cacheSoftSizeBytes);const d=new br(this.logger,this.rangesCacheDir),c=new kr(this.logger,this.rangesCacheDir);this.rangesCache=new Pr(this.logger,this.ops.rangesCacheMaxSizeBytes,d,c),this.downloadQueue=new p.TaskProcessor(this.logger,a.nConcurrentDownloads),this.saveDir=b.resolve(r)}static async init(e,t,n,r,o,l,a){const d=new Te(e,t,n,r,o,l,a);return await d.rangesCache.reset(),d}getDownloadedBlob(e,t){if(t===void 0)return f.Computable.make(l=>this.getDownloadedBlob(e,l));const n=m.treeEntryToResourceInfo(e,t),r=U.randomUUID();t.addOnDestroy(()=>this.releaseBlob(n,r));const o=this.getDownloadedBlobNoCtx(t.watcher,n,r);return o==null&&t.markUnstable("download blob is still undefined"),o}getDownloadedBlobNoCtx(e,t,n){N("getDownloadedBlob",t.type);const r=this.getOrSetNewTask(t,n);r.attach(e,n);const o=r.getBlob();if(o.done){if(o.result.ok)return o.result.value;throw o.result.error}}getOrSetNewTask(e,t){const n=T(e.id),r=this.keyToDownload.get(n);if(r)return r;const o=b.resolve(this.saveDir,n),l=new ar(this.logger,this.clientDownload,e,er(o,this.signer),o);return this.keyToDownload.set(n,l),this.downloadQueue.push({fn:()=>this.downloadBlob(l,t),recoverableErrorPredicate:a=>!me(a)}),l}async downloadBlob(e,t){await e.download();const n=e.getBlob();n.done&&n.result.ok&&this.cache.addCache(e,t)}getOnDemandBlob(e,t){if(t===void 0)return f.Computable.make(l=>this.getOnDemandBlob(e,l));const n=m.isPlTreeEntry(e)?m.makeResourceSnapshot(e,Ge,t):e,r=U.randomUUID();return t.addOnDestroy(()=>this.releaseOnDemandBlob(n.id,r)),this.getOnDemandBlobNoCtx(n,r)}getOnDemandBlobNoCtx(e,t){N("getOnDemandBlob",e.type);let n=this.keyToOnDemand.get(T(e.id));return n===void 0&&(n=new Lr(fe(e),rr(e,this.signer)),this.keyToOnDemand.set(T(e.id),n)),n.attach(t),n.getHandle()}getLocalPath(e){const{path:t}=te(e,this.signer);return t}async getContent(e,t){if(t&&E.validateRangeBytes(t,"getContent"),tr(e))return await Re(this.getLocalPath(e),t);if(or(e)){const n=sr(e,this.signer),r=T(n.info.id),o=await this.rangesCache.get(r,t??{from:0,to:n.size});if(o)return await Re(o,t);const{content:l}=await this.clientDownload.downloadBlob({id:n.info.id,type:n.info.type},void 0,void 0,t==null?void 0:t.from,t==null?void 0:t.to),a=await ce.buffer(l);return await this.rangesCache.set(r,t??{from:0,to:n.size},a),a}throw new Error("Malformed remote handle")}getComputableContent(e,t){return t&&E.validateRangeBytes(t,"getComputableContent"),f.Computable.make(n=>this.getDownloadedBlob(e,n),{postprocessValue:n=>n?this.getContent(n.handle,t):void 0}).withStableType()}getLastLogs(e,t,n){if(n==null)return f.Computable.make(a=>this.getLastLogs(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r,o));const l=this.getLastLogsNoCtx(n.watcher,r,t,o);return l==null&&n.markUnstable("either a file was not downloaded or logs was not read"),l}getLastLogsNoCtx(e,t,n,r){N("getLastLogs",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=te(o.handle,this.signer);let a=this.idToLastLines.get(T(t.id));if(a==null){const c=new Ue(l,n);this.idToLastLines.set(T(t.id),c),a=c}const d=a.getOrSchedule(e);if(d.error)throw d.error;return d.log}getProgressLog(e,t,n){if(n==null)return f.Computable.make(a=>this.getProgressLog(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r,o));const l=this.getProgressLogNoCtx(n.watcher,r,t,o);return l===void 0&&n.markUnstable("either a file was not downloaded or a progress log was not read"),l}getProgressLogNoCtx(e,t,n,r){N("getProgressLog",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=te(o.handle,this.signer);let a=this.idToProgressLog.get(T(t.id));if(a==null){const c=new Ue(l,1,n);this.idToProgressLog.set(T(t.id),c),a=c}const d=a.getOrSchedule(e);if(d.error)throw d.error;return d.log}getLogHandle(e,t){if(t==null)return f.Computable.make(r=>this.getLogHandle(e,r));const n=m.treeEntryToResourceInfo(e,t);return this.getLogHandleNoCtx(n)}getLogHandleNoCtx(e){return N("getLogHandle",e.type),Qe(!1,e)}async lastLines(e,t,n,r){const o=await this.clientLogs.lastLines(O(e),t,BigInt(n??0),r);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async readText(e,t,n,r){const o=await this.clientLogs.readText(O(e),t,BigInt(n??0),r);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async releaseBlob(e,t){const n=this.keyToDownload.get(T(e.id));if(n!=null)if(this.cache.existsFile(T(e.id))){const r=this.cache.removeFile(T(e.id),t);await Promise.all(r.map(async o=>{await w.rm(o.path),this.cache.removeCache(o),this.removeTask(p.mapGet(this.keyToDownload,Le(o.path)),`the task ${g.stringifyWithResourceId(o)} was removedfrom cache along with ${g.stringifyWithResourceId(r.map(l=>l.path))}`)}))}else n.counter.dec(t)&&this.removeTask(n,`the task ${g.stringifyWithResourceId(n.info())} was removed from cache`)}removeTask(e,t){e.abort(t),e.change.markChanged(),this.keyToDownload.delete(Le(e.path)),this.idToLastLines.delete(T(e.rInfo.id)),this.idToProgressLog.delete(T(e.rInfo.id))}async releaseOnDemandBlob(e,t){var r;(((r=this.keyToOnDemand.get(T(e)))==null?void 0:r.release(t))??!1)&&this.keyToOnDemand.delete(T(e))}async releaseAll(){this.downloadQueue.stop(),this.keyToDownload.forEach((e,t)=>{this.keyToDownload.delete(t),e.change.markChanged()})}}class Lr{constructor(e,t){h(this,"counter",new p.CallersCounter);this.size=e,this.handle=t}getHandle(){return{handle:this.handle,size:this.size}}attach(e){this.counter.inc(e)}release(e){return this.counter.dec(e)}}class Ue{constructor(e,t,n){h(this,"updater");h(this,"log");h(this,"change",new f.ChangeSource);h(this,"error");this.path=e,this.lines=t,this.patternToSearch=n,this.updater=new Ze(async()=>this.update())}getOrSchedule(e){return this.change.attachWatcher(e),this.updater.schedule(),{log:this.log,error:this.error}}async update(){try{const e=await Ur(this.path,this.lines,this.patternToSearch);this.log!=e&&this.change.markChanged(),this.log=e}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.log="",this.error=e,this.change.markChanged();return}throw e}}}function Ur(s,e,t){const n=de.createReadStream(s),r=new L.Writable;return new Promise((o,l)=>{const a=It.createInterface(n,r),d=new Tt;a.on("line",function(c){t!=null&&!c.includes(t)||(d.push(c),d.length>e&&d.shift())}),a.on("error",l),a.on("close",function(){o(d.toArray().join(Pe.EOL)+Pe.EOL)})})}async function Re(s,e){const t={};e&&(t.start=e.from,t.end=e.to-1);const n=de.createReadStream(s,t);return await ce.buffer(L.Readable.toWeb(n))}function N(s,e){if(!e.name.startsWith("Blob/")){let t=`${s}: wrong resource type: ${e.name}, expected: a resource of type that starts with 'Blob/'.`;throw e.name=="Blob"&&(t+=" If it's called from workflow, should a file be exported with 'file.exportFile' function?"),new j(t)}}const nt=m.rsSchema({});function rt(s,e){const t=m.isPlTreeEntry(s)?e.accessor(s).node():m.isPlTreeEntryAccessor(s)?s.node():s;return m.makeResourceSnapshot(t,nt)}function Rr(s,e,t){const n=P.relative(e,t);return`plblob+folder://${s.sign(n)}.${n}.blob`}function Sr(s){return new URL(s).protocol=="plblob+folder:"}function Dr(s,e,t){const n=new URL(e),[r,o,l]=n.host.split(".");s.verify(o,r,`signature verification failed for url: ${e}, subfolder: ${o}`);let a=Ir(P.join(t,`${o}`),n.pathname.slice(1));return(n.pathname==""||n.pathname=="/")&&(a=P.join(a,"index.html")),P.resolve(a)}function Ir(s,e){const t=P.resolve(s,e),n=P.resolve(s);if(!t.startsWith(n))throw new Error("Path validation failed.");return t}class vr{constructor(e,t,n,r,o,l,a){h(this,"counter",new p.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"url");h(this,"state");this.logger=e,this.signer=t,this.saveDir=n,this.path=r,this.rInfo=o,this.format=l,this.clientDownload=a}info(){return{rInfo:this.rInfo,format:this.format,path:this.path,done:this.done,size:this.size,error:this.error,taskHistory:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.downloadAndDecompress(this.signalCtl.signal);this.setDone(e),this.change.markChanged(),this.logger.info(`blob to URL task is done: ${g.stringifyWithResourceId(this.info())}`)}catch(e){if(this.logger.warn(`a error was produced: ${e} for blob to URL task: ${g.stringifyWithResourceId(this.info())}`),Nr(e)){this.setError(e),this.change.markChanged(),await ie(this.path);return}throw e}}async downloadAndDecompress(e){if(this.state={},this.state.parentDir=P.dirname(this.path),await p.ensureDirExists(this.state.parentDir),this.state.fileExisted=await p.fileExists(this.path),this.state.fileExisted)return await ot(this.path);const{content:t,size:n}=await this.clientDownload.downloadBlob(this.rInfo,{},e);return this.state.downloaded=!0,await p.createPathAtomically(this.logger,this.path,async r=>{switch(this.state.tempPath=r,this.state.archiveFormat=this.format,this.format){case"tar":await w.mkdir(r);const o=L.Writable.toWeb(se.extract(r));await t.pipeTo(o,{signal:e});return;case"tgz":await w.mkdir(r);const l=L.Transform.toWeb($e.createGunzip()),a=L.Writable.toWeb(se.extract(r));await t.pipeThrough(l,{signal:e}).pipeTo(a,{signal:e});return;case"zip":this.state.zipPath=this.path+".zip";const d=L.Writable.toWeb(R.createWriteStream(this.state.zipPath));await t.pipeTo(d,{signal:e}),this.state.zipPathCreated=!0,await Ut(this.state.zipPath,r,{filter:c=>!c.path.endsWith("/")}),this.state.zipDecompressed=!0,await R.promises.rm(this.state.zipPath),this.state.zipPathDeleted=!0;return;default:i.assertNever(this.format)}}),this.state.pathCreated=!0,n}getURL(){if(this.done)return{url:p.notEmpty(this.url)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e,this.url=Rr(this.signer,this.saveDir,this.path)}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new st(e))}}async function ot(s){const e=await w.readdir(s,{withFileTypes:!0});return(await Promise.all(e.map(async n=>{const r=P.join(s,n.name);return n.isDirectory()?await ot(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function ie(s){await w.rm(s,{recursive:!0,force:!0})}let st=class extends Error{};function Nr(s){return s instanceof st||s instanceof H||s instanceof A||s instanceof x||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")||String(s).includes("incorrect header check")}function B(s,e){return`id:${String(BigInt(s))}-${e}`}class Cr{constructor(e,t,n,r,o={cacheSoftSizeBytes:50*1024*1024,nConcurrentDownloads:50}){h(this,"idToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.signer=t,this.clientDownload=n,this.saveDir=r,this.opts=o,this.downloadQueue=new p.TaskProcessor(this.logger,this.opts.nConcurrentDownloads,{type:"exponentialWithMaxDelayBackoff",initialDelay:1e4,maxDelay:3e4,backoffMultiplier:1.5,jitter:.5}),this.cache=new ye(this.opts.cacheSoftSizeBytes)}info(){return{saveDir:this.saveDir,opts:this.opts,idToDownloadSize:this.idToDownload.size,idToDownloadKeys:this.idToDownload.keys(),idToDownload:Array.from(this.idToDownload.entries()).map(([e,t])=>[e,t.info()])}}getPathForCustomProtocol(e){if(Sr(e))return Dr(this.signer,e,this.saveDir);throw new Error(`getPathForCustomProtocol: ${e} is invalid`)}extractArchiveAndGetURL(e,t,n){if(n===void 0)return f.Computable.make(a=>this.extractArchiveAndGetURL(e,t,a));const r=m.isPlTreeEntry(e)?rt(e,n):e,o=U.randomUUID();n.addOnDestroy(()=>this.releasePath(r.id,t,o));const l=this.extractArchiveAndGetURLNoCtx(r,t,n.watcher,o);if((l==null?void 0:l.url)===void 0&&n.markUnstable(`a path to the downloaded archive might be undefined. The current result: ${l}`),(l==null?void 0:l.error)!==void 0)throw l==null?void 0:l.error;return l==null?void 0:l.url}extractArchiveAndGetURLNoCtx(e,t,n,r){const o=this.idToDownload.get(B(e.id,t));if(o!=null)return o.attach(n,r),o.getURL();const l=this.setNewTask(n,e,t,r);return this.downloadQueue.push({fn:async()=>this.downloadUrl(l,r),recoverableErrorPredicate:a=>!me(a)}),l.getURL()}async downloadUrl(e,t){var n;await e.download(),((n=e.getURL())==null?void 0:n.url)!=null&&this.cache.addCache(e,t)}async releasePath(e,t,n){const r=this.idToDownload.get(B(e,t));if(r!=null)if(this.cache.existsFile(r.path)){const o=this.cache.removeFile(r.path,n);await Promise.all(o.map(async l=>{await ie(l.path),this.cache.removeCache(l),this.removeTask(l,`the task ${g.stringifyWithResourceId(l.info())} was removedfrom cache along with ${g.stringifyWithResourceId(o.map(a=>a.info()))}`)}))}else r.counter.dec(n)&&this.removeTask(r,`the task ${g.stringifyWithResourceId(r.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.idToDownload.entries()).map(async([e,t])=>{await ie(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${g.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,n,r){const o=new vr(this.logger,this.signer,this.saveDir,this.getFilePath(t.id,n),t,n,this.clientDownload);return o.attach(e,r),this.idToDownload.set(B(t.id,n),o),o}removeTask(e,t){e.abort(t),e.change.markChanged(),this.idToDownload.delete(B(e.rInfo.id,e.format))}getFilePath(e,t){return b.join(this.saveDir,`${String(BigInt(e))}_${t}`)}}class it{constructor(e,t,n,r,o,l){h(this,"change",new f.ChangeSource);h(this,"counter",new p.CallersCounter);h(this,"nMaxUploads");h(this,"nPartsWithThisUploadSpeed",0);h(this,"nPartsToIncreaseUpload",10);h(this,"uploadData");h(this,"progress");h(this,"failed");h(this,"alreadyExisted",!1);this.logger=e,this.clientBlob=t,this.clientProgress=n,this.maxNConcurrentPartsUpload=r,this.res=l,this.nMaxUploads=this.maxNConcurrentPartsUpload;const{uploadData:a,progress:d}=$r(l,o);this.uploadData=a,this.progress=d}getProgress(e,t){if(this.incCounter(e,t),this.failed)throw this.logger.error(`Uploading terminally failed: ${this.progress.lastError}`),new Error(this.progress.lastError);return Br(this.progress)}shouldScheduleUpload(){return lt(this.progress)}async uploadBlobTask(){try{await at(this.logger,this.clientBlob,this.res,this.uploadData,this.isComputableDone.bind(this),{nPartsWithThisUploadSpeed:this.nPartsWithThisUploadSpeed,nPartsToIncreaseUpload:this.nPartsToIncreaseUpload,currentSpeed:this.nMaxUploads,maxSpeed:this.maxNConcurrentPartsUpload}),this.change.markChanged()}catch(e){if(this.setRetriableError(e),ae(e)){this.logger.warn(`resource was deleted while uploading a blob: ${e}`),this.change.markChanged(),this.setDone(!0);return}if(this.logger.error(`error while uploading a blob: ${e}`),this.change.markChanged(),be(e)){this.setTerminalError(e);return}throw Er(e)&&(this.nMaxUploads=Or(this.logger,this.nMaxUploads,1)),e}}async updateStatus(){var e;try{const t=await this.clientProgress.getStatus(this.res,{timeout:1e4}),n=this.progress.status,r=_r(this.alreadyExisted,Wr(t));this.progress.status=r,this.setDone(t.done),(t.done||this.progress.status.progress!=(n==null?void 0:n.progress))&&this.change.markChanged()}catch(t){if(this.setRetriableError(t),t.name=="RpcError"&&t.code=="DEADLINE_EXCEEDED"||(e=t==null?void 0:t.message)!=null&&e.includes("DEADLINE_EXCEEDED")){this.logger.warn("deadline exceeded while getting a status of BlobImport");return}if(ae(t)){this.logger.warn(`resource was not found while updating a status of BlobImport: ${t}, ${g.stringifyWithResourceId(this.res)}`),this.change.markChanged(),this.setDone(!0);return}this.logger.error(`retryable error while updating a status of BlobImport: ${t}`)}}setRetriableError(e){this.progress.lastError=String(e)}setTerminalError(e){this.progress.lastError=String(e),this.progress.done=!1,this.failed=!0}setDoneIfOutputSet(e){Fr(e)&&(this.setDone(!0),this.alreadyExisted=!0)}setDone(e){this.progress.done=e,e&&(this.progress.lastError=void 0)}incCounter(e,t){this.change.attachWatcher(e),this.counter.inc(t)}decCounter(e){return this.counter.dec(e)}isComputableDone(){return this.counter.isZero()}}async function at(s,e,t,n,r,o){Rt(z(t),"the upload operation can be done only for BlobUploads");const l=1e4;if(r())return;const a=await e.initUpload(t,{timeout:l});s.info(`started to upload blob ${t.id}, parts overall: ${a.overall}, parts remained: ${a.toUpload.length}, number of concurrent uploads: ${o.currentSpeed}`);const d=c=>async u=>{r()||(await e.partUpload(t,n.localPath,BigInt(n.modificationTime),c,{timeout:l}),s.info(`uploaded chunk ${c}/${a.overall} of resource: ${t.id}`),o.nPartsWithThisUploadSpeed++,o.nPartsWithThisUploadSpeed>=o.nPartsToIncreaseUpload&&(o.nPartsWithThisUploadSpeed=0,o.currentSpeed=Mr(s,o.currentSpeed,o.maxSpeed),u.setConcurrency(o.currentSpeed)))};await p.asyncPool(o.currentSpeed,a.toUpload.map(d)),!r()&&(await e.finalize(t,{timeout:l}),s.info(`uploading of resource ${t.id} finished.`))}function $r(s,e){let t,n;return z(s)&&(n=C.parse(s.data),t=ct(e,n.localPath,n.pathSignature)),{uploadData:n,progress:{done:!1,status:void 0,isUpload:z(s),isUploadSignMatch:t,lastError:void 0}}}function lt(s){return s.isUpload&&(s.isUploadSignMatch??!1)}function Br(s){return s.done,s.isUpload,s.isUploadSignMatch,s.lastError,s.status&&(s.status.progress,s.status.bytesProcessed,s.status.bytesTotal),s}function Fr(s){return"blob"in s.fields?s.fields.blob!==void 0:s.fields.incarnation!==void 0}function z(s){return s.type.name.startsWith("BlobUpload")}function ct(s,e,t){try{return s.verify(e,t),!0}catch{return!1}}function Wr(s){return{progress:s.progress??0,bytesProcessed:Number(s.bytesProcessed),bytesTotal:Number(s.bytesTotal)}}function _r(s,e){return s&&e.bytesTotal!=0&&e.bytesProcessed==0?{progress:1,bytesProcessed:Number(e.bytesTotal),bytesTotal:Number(e.bytesTotal)}:e}function ae(s){return s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED"||s.code=="ALREADY_EXISTS")}function be(s){return s instanceof he||s instanceof ue||s instanceof ge}function Er(s){return s==null?void 0:s.message.includes("UND_ERR_HEADERS_TIMEOUT")}function Mr(s,e,t){const n=Math.min(e+2,t);return n!=e&&s.info(`uploadTask.increaseConcurrency: increased from ${e} to ${n}`),n}function Or(s,e,t){const n=Math.max(Math.round(e/2),t);return n!=e&&s.info(`uploadTask.decreaseConcurrency: decreased from ${e} to ${n}`),n}function dt(s,e){const t=m.isPlTreeEntry(s)?e.accessor(s).node():m.isPlTreeEntryAccessor(s)?s.node():s;return t.resourceType.name.startsWith("BlobUpload")?m.makeResourceSnapshot(t,Ve):m.makeResourceSnapshot(t,qe)}class zr{constructor(e,t,n,r,o={nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToProgress",new Map);h(this,"uploadQueue");h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.signer=t,this.clientBlob=n,this.clientProgress=r,this.opts=o,this.uploadQueue=new p.TaskProcessor(this.logger,1,{type:"exponentialWithMaxDelayBackoff",initialDelay:20,maxDelay:15e3,backoffMultiplier:1.5,jitter:.5}),this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:o.stopPollingDelay},(l,a)=>this.scheduleOnNextState(l,a))}getProgressId(e,t){if(t==null)return f.Computable.make(l=>this.getProgressId(e,l));const n=m.isPlTreeEntry(e)?dt(e,t):e,r=U.randomUUID();return t.attacheHooks(this.hooks),t.addOnDestroy(()=>this.release(n.id,r)),this.getProgressIdNoCtx(t.watcher,n,r)}getProgressIdNoCtx(e,t,n){xr("getProgressId",t.type);const r=this.idToProgress.get(t.id);if(r!=null)return r.setDoneIfOutputSet(t),r.getProgress(e,n);const o=new it(this.logger,this.clientBlob,this.clientProgress,this.opts.nConcurrentPartUploads,this.signer,t);return this.idToProgress.set(t.id,o),o.shouldScheduleUpload()&&this.uploadQueue.push({fn:()=>o.uploadBlobTask(),recoverableErrorPredicate:l=>!be(l)}),o.setDoneIfOutputSet(t),o.getProgress(e,n)}async release(e,t){const n=this.idToProgress.get(e);if(n===void 0)return;n.decCounter(t)&&this.idToProgress.delete(e)}async releaseAll(){this.uploadQueue.stop()}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{await p.asyncPool(this.opts.nConcurrentGetProgresses,this.getAllNotDoneProgresses().map(t=>async()=>await t.updateStatus())),e.forEach(t=>t.resolve())}catch(t){console.error(t),e.forEach(n=>n.reject(t))}if(!this.keepRunning)break;await Ce.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllNotDoneProgresses(){return Array.from(this.idToProgress.entries()).filter(([e,t])=>!Hr(t.progress)).map(([e,t])=>t)}}function Hr(s){var e;return s.done&&(((e=s.status)==null?void 0:e.progress)??0)>=1}function xr(s,e){if(!e.name.startsWith("BlobUpload")&&!e.name.startsWith("BlobIndex"))throw new j(`${s}: wrong resource type: ${e.name}, expected: a resource of either type 'BlobUpload' or 'BlobIndex'.`)}class Ar{constructor(e,t,n={nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.clientLogs=t,this.opts=n,this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:n.stopPollingDelay},(r,o)=>this.scheduleOnNextState(r,o))}getLastLogs(e,t,n){if(n==null)return f.Computable.make(a=>this.getLastLogs(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.attacheHooks(this.hooks),n.addOnDestroy(()=>this.releaseLastLogs(r.id,o));const l=this.getLastLogsNoCtx(n.watcher,r,t,o);return n.markUnstable("The logs are from stream, so we consider them unstable. Final values will be got from blobs."),l}getLastLogsNoCtx(e,t,n,r){re("getLastLogs",t.type);let o=this.idToLastLines.get(t.id);if(o==null){const a=new Se(this.logger,this.clientLogs,t,n);this.idToLastLines.set(t.id,a),o=a}o.attach(e,r);const l=o.getLog();if(l.error!=null)throw l.error;return l.log}getProgressLog(e,t,n){if(n==null)return f.Computable.make(a=>this.getProgressLog(e,t,a));const r=m.treeEntryToResourceInfo(e,n),o=U.randomUUID();n.attacheHooks(this.hooks),n.addOnDestroy(()=>this.releaseProgressLog(r.id,o));const l=this.getProgressLogNoCtx(n.watcher,r,t,o);return n.markUnstable("The progress log is from the stream, so we consider it unstable. Final value will be got from blobs."),l}getProgressLogNoCtx(e,t,n,r){re("getProgressLog",t.type);let o=this.idToProgressLog.get(t.id);if(o==null){const a=new Se(this.logger,this.clientLogs,t,1,n);this.idToProgressLog.set(t.id,a),o=a}o.attach(e,r);const l=o.getLog();if(l.error)throw l.error;return l.log}getLogHandle(e,t){if(t==null)return f.Computable.make(o=>this.getLogHandle(e,o));const n=m.treeEntryToResourceInfo(e,t),r=this.getLogHandleNoCtx(n);return t.markUnstable(`live_log:${g.resourceIdToString(n.id)}`),r}getLogHandleNoCtx(e){return re("getLogHandle",e.type),Qe(!0,e)}async lastLines(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.lastLines(O(e),t,BigInt(n??0),r))}async readText(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.readText(O(e),t,BigInt(n??0),r))}async tryWithNotFound(e,t){if(!M(e))throw new Error(`Not live log handle was passed to live log driver, handle: ${e}`);try{const n=await t();return{live:!0,shouldUpdateHandle:!1,data:n.data,size:Number(n.size),newOffset:Number(n.newOffset)}}catch(n){if(n.name=="RpcError"&&n.code=="NOT_FOUND")return{shouldUpdateHandle:!0};throw n}}async releaseLastLogs(e,t){var r;((r=this.idToLastLines.get(e))==null?void 0:r.release(t))&&this.idToLastLines.delete(e)}async releaseProgressLog(e,t){var r;((r=this.idToProgressLog.get(e))==null?void 0:r.release(t))&&this.idToProgressLog.delete(e)}async releaseAll(){}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{const t=this.getAllLogs();await p.asyncPool(this.opts.nConcurrentGetLogs,t.map(n=>async()=>await n.update())),e.forEach(n=>n.resolve())}catch(t){console.error(t),e.forEach(n=>n.reject(t))}if(!this.keepRunning)break;await Ce.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllLogs(){return Array.from(this.idToLastLines.entries()).concat(Array.from(this.idToProgressLog.entries())).map(([e,t])=>t)}}class Se{constructor(e,t,n,r,o){h(this,"logs");h(this,"error");h(this,"change",new f.ChangeSource);h(this,"counter",new p.CallersCounter);this.logger=e,this.clientLogs=t,this.rInfo=n,this.lines=r,this.patternToSearch=o}getLog(){return{log:this.logs,error:this.error}}attach(e,t){this.change.attachWatcher(e),this.counter.inc(t)}release(e){return this.counter.dec(e)}async update(){try{const t=(await this.clientLogs.lastLines(this.rInfo,this.lines,0n,this.patternToSearch)).data.toString();this.logs!=t&&this.change.markChanged(),this.logs=t,this.error=void 0;return}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.logs="",this.error=e,this.change.markChanged();return}throw this.logger.error(`Stream log lines for ${g.stringifyWithResourceId(this.rInfo.id)} failed, reason: ${e}`),e}}}function re(s,e){if(!e.name.startsWith("StreamWorkdir"))throw new j(`${s}: wrong resource type: ${e.name}, expected: a resource of type 'StreamWorkdir'.`)}class jr{constructor(e,t,n){this.logger=e,this.logsStreamDriver=t,this.downloadDriver=n}getLastLogs(e,t,n){if(n===void 0)return f.Computable.make(o=>this.getLastLogs(e,t,o));const r=W(n,e);if(r===void 0){n.markUnstable("no stream in stream manager");return}if(F(r))return this.downloadDriver.getLastLogs(r,t,n);try{return this.logsStreamDriver.getLastLogs(r,t,n)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){n.markUnstable(`NOT_FOUND in logs stream driver while getting last logs: ${o}`);return}throw o}}getProgressLog(e,t,n){if(n===void 0)return f.Computable.make(o=>this.getProgressLog(e,t,o));const r=W(n,e);if(r===void 0){n.markUnstable("no stream in stream manager");return}if(F(r))return this.downloadDriver.getProgressLog(r,t,n);try{return this.logsStreamDriver.getProgressLog(r,t,n)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){n.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log: ${o}`);return}throw o}}getProgressLogWithInfo(e,t,n){if(n===void 0)return f.Computable.make(o=>this.getProgressLogWithInfo(e,t,o));const r=W(n,e);if(r===void 0){n.markUnstable("no stream in stream manager");return}if(F(r))return{progressLine:this.downloadDriver.getProgressLog(r,t,n),live:!1};try{return{progressLine:this.logsStreamDriver.getProgressLog(r,t,n),live:!0}}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){n.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log with info: ${o}`);return}throw o}}getLogHandle(e,t){if(t===void 0)return f.Computable.make(r=>this.getLogHandle(e,r));const n=W(t,e);if(n===void 0){t.markUnstable("no stream in stream manager");return}return F(n)?this.downloadDriver.getLogHandle(n,t):this.logsStreamDriver.getLogHandle(n,t)}async lastLines(e,t,n,r){return M(e)?await this.logsStreamDriver.lastLines(e,t,n,r):await this.downloadDriver.lastLines(e,t,n,r)}async readText(e,t,n,r){return M(e)?await this.logsStreamDriver.readText(e,t,n,r):await this.downloadDriver.readText(e,t,n,r)}}function F(s){return!s.type.name.startsWith("StreamWorkdir")}function W(s,e){var t;return(t=s.accessor(e).node().traverse("stream"))==null?void 0:t.resourceInfo}class Gr{constructor(e,t,n,r={cacheSoftSizeBytes:1*1024*1024*1024,withGunzip:!0,nConcurrentDownloads:50}){h(this,"downloadHelper");h(this,"urlToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.saveDir=n,this.opts=r,this.downloadQueue=new p.TaskProcessor(this.logger,this.opts.nConcurrentDownloads),this.cache=new ye(this.opts.cacheSoftSizeBytes),this.downloadHelper=new _e(t)}getPath(e,t){if(t===void 0)return f.Computable.make(o=>this.getPath(e,o));const n=U.randomUUID();t.addOnDestroy(()=>this.releasePath(e,n));const r=this.getPathNoCtx(e,t.watcher,n);return(r==null?void 0:r.path)===void 0&&t.markUnstable(`a path to the downloaded and untared archive might be undefined. The current result: ${r}`),r}getPathNoCtx(e,t,n){const r=e.toString(),o=this.urlToDownload.get(r);if(o!=null)return o.attach(t,n),o.getPath();const l=this.setNewTask(t,e,n);return this.downloadQueue.push({fn:async()=>this.downloadUrl(l,n),recoverableErrorPredicate:a=>!0}),l.getPath()}async downloadUrl(e,t){var n;await e.download(this.downloadHelper,this.opts.withGunzip),((n=e.getPath())==null?void 0:n.path)!=null&&this.cache.addCache(e,t)}async releasePath(e,t){const n=e.toString(),r=this.urlToDownload.get(n);if(r!=null)if(this.cache.existsFile(r.path)){const o=this.cache.removeFile(r.path,t);await Promise.all(o.map(async l=>{await le(l.path),this.cache.removeCache(l),this.removeTask(l,`the task ${g.stringifyWithResourceId(l.info())} was removedfrom cache along with ${g.stringifyWithResourceId(o.map(a=>a.info()))}`)}))}else r.counter.dec(t)&&this.removeTask(r,`the task ${g.stringifyWithResourceId(r.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.urlToDownload.entries()).map(async([e,t])=>{await le(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${g.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,n){const r=new Vr(this.logger,this.getFilePath(t),t);return r.attach(e,n),this.urlToDownload.set(t.toString(),r),r}removeTask(e,t){e.abort(t),e.change.markChanged(),this.urlToDownload.delete(e.url.toString())}getFilePath(e){const t=U.createHash("sha256").update(e.toString()).digest("hex");return b.join(this.saveDir,t)}}class Vr{constructor(e,t,n){h(this,"counter",new p.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);this.logger=e,this.path=t,this.url=n}info(){return{url:this.url.toString(),path:this.path,done:this.done,size:this.size,error:this.error}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(e,t){try{const n=await this.downloadAndUntar(e,t,this.signalCtl.signal);this.setDone(n),this.change.markChanged()}catch(n){if(n instanceof De||n instanceof H){this.setError(n),this.change.markChanged(),await le(this.path);return}throw n}}async downloadAndUntar(e,t,n){if(await p.ensureDirExists(b.dirname(this.path)),await p.fileExists(this.path))return await ht(this.path);const r=await e.download(this.url.toString(),{},n);let o=r.content;if(t){const l=L.Transform.toWeb($e.createGunzip());o=o.pipeThrough(l,{signal:n})}return await p.createPathAtomically(this.logger,this.path,async l=>{await w.mkdir(l);const a=L.Writable.toWeb(se.extract(l));await o.pipeTo(a,{signal:n})}),r.size}getPath(){if(this.done)return{path:p.notEmpty(this.path)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new De(e))}}class De extends Error{}async function ht(s){const e=await w.readdir(s,{withFileTypes:!0});return(await Promise.all(e.map(async n=>{const r=b.join(s,n.name);return n.isDirectory()?await ht(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function le(s){await w.rm(s,{recursive:!0,force:!0})}function oe(s,e){return`index://index/${encodeURIComponent(JSON.stringify({storageId:s,path:e}))}`}function qr(s,e,t,n){const r={localPath:s,pathSignature:e.sign(s),sizeBytes:String(t),modificationTime:String(n)};return`upload://upload/${encodeURIComponent(JSON.stringify(r))}`}function Jr(s){const e=new URL(s);return C.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Zr(s){const e=new URL(s);return we.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Ie(s){if(Yr(s))return to(s);if(Qr(s))return Xr(s);p.assertNever(s)}const ut=/^local:\/\/(?<name>.*)\/(?<path>.*)$/;function Qr(s){return ut.test(s)}function Kr(s,e){return`local://${s}/${encodeURIComponent(e)}`}function Xr(s){const e=s.match(ut);if(e==null)throw new Error(`Local list handle wasn't parsed: ${s}`);const{name:t,path:n}=e.groups;return{rootPath:decodeURIComponent(n),name:t,isRemote:!1}}const pt=/^remote:\/\/(?<name>.*)\/(?<resourceId>.*)$/;function Yr(s){return pt.test(s)}function eo(s,e){return`remote://${s}/${BigInt(e)}`}function to(s){const e=s.match(pt);if(e==null)throw new Error(`Remote list handle wasn't parsed: ${s}`);const{name:t,resourceId:n}=e.groups;return{id:g.bigintToResourceId(BigInt(n)),type:no(t),name:t,isRemote:!0}}function no(s){return{name:`LS/${s}`,version:"1"}}async function gt(){const s=Ne.homedir();if(P.sep=="/")return[{name:"local",root:"/",initialPath:s}];{const t=P.parse(s).root.replaceAll(":\\","");try{return(await St.promisify(Dt.exec)("wmic logicaldisk get name")).stdout.split(`\r
2
+ `).filter(o=>o.includes(":")).map(o=>o.trim().replaceAll(":","")).map(o=>{const l=o==t;return{name:`local_disk_${o}`,root:`${o}:\\`,initialPath:l?s:`${o}:\\`}})}catch{return[{name:`local_disk_${t}`,root:`${t}:\\`,initialPath:s}]}}}class ke{constructor(e,t,n,r,o,l,a){this.logger=e,this.lsClient=t,this.storageIdToResourceId=n,this.signer=r,this.virtualStoragesMap=o,this.localProjectionsMap=l,this.openFileDialogCallback=a}async getLocalFileContent(e,t){const n=await this.tryResolveLocalFileHandle(e);if(t)throw new Error("Range request not yet supported.");return await w.readFile(n)}async getLocalFileSize(e){const t=await this.tryResolveLocalFileHandle(e);return(await w.stat(t)).size}async showOpenMultipleFilesDialog(e){const t=await this.openFileDialogCallback(!0,e);return t===void 0?{}:{files:await Promise.all(t.map(n=>this.getLocalFileHandle(n)))}}async showOpenSingleFileDialog(e){const t=await this.openFileDialogCallback(!1,e);return t===void 0?{}:{file:await this.getLocalFileHandle(t[0])}}async tryResolveLocalFileHandle(e){if(E.isImportFileHandleIndex(e)){const t=Zr(e),n=this.localProjectionsMap.get(t.storageId);if(!n)throw new Error(`Storage ${t.storageId} is not mounted locally.`);return b.join(n.localPath,t.path)}else{const t=Jr(e);this.signer.verify(t.localPath,t.pathSignature,"Failed to validate local file handle signature.");const n=t.localPath,r=await w.stat(n,{bigint:!0});if(String(r.mtimeMs/1000n)!==t.modificationTime)throw new Error("File has changed since the handle was created.");return n}}async getLocalFileHandle(e){D(e);for(const n of this.localProjectionsMap.values())if(e.startsWith(n.localPath)){const r=n.localPath===""?e:b.relative(n.localPath,e);return oe(n.storageId,r)}const t=await w.stat(e,{bigint:!0});return qr(e,this.signer,t.size,t.mtimeMs/1000n)}async getStorageList(){const e=[...this.virtualStoragesMap.values()].map(r=>({name:r.name,handle:Kr(r.name,r.root),initialFullPath:r.initialPath})),n=Object.entries(this.storageIdToResourceId).map(([r,o])=>({name:r,handle:eo(r,o),initialFullPath:"",isInitialPathHome:!1})).filter(r=>r.name!=="root");return[...e,...n]}async listFiles(e,t){const n=Ie(e);if(n.isRemote)return{entries:(await this.lsClient.list(n,t)).items.map(a=>({type:a.isDir?"dir":"file",name:a.name,fullPath:a.fullName,handle:oe(n.name,a.fullName)}))};b.sep==="/"&&t===""&&(t="/"),n.rootPath===""&&D(t);const r=b.isAbsolute(t)?t:b.join(n.rootPath,t),o=[];for await(const l of await w.opendir(r)){if(!l.isFile()&&!l.isDirectory())continue;const a=b.join(r,l.name);o.push({type:l.isFile()?"file":"dir",name:l.name,fullPath:a,handle:await this.getLocalFileHandle(a)})}return{entries:o}}async listRemoteFilesWithAdditionalInfo(e,t){const n=Ie(e);if(!n.isRemote)throw new Error(`Storage ${n.name} is not remote`);return{entries:(await this.lsClient.list(n,t)).items.map(o=>({type:o.isDir?"dir":"file",name:o.name,fullPath:o.fullName,handle:oe(n.name,o.fullName),size:Number(o.size)}))}}async fileToImportHandle(e){throw new Error("Not implemented. This method must be implemented and intercepted in desktop preload script.")}static async init(e,t,n,r,o,l){const a=Ae(t,e);l||(l=await gt());for(const u of l)D(u.root);for(const u of r)u.localPath!==""&&D(u.localPath);const d=new Map(l.map(u=>[u.name,u])),c=new Map(r.map(u=>[u.storageId,u]));if(new Set([...d.keys(),...c.keys()]).size!==d.size+c.size)throw new Error("Intersection between local projection storage ids and virtual storages names detected.");return new ke(e,a,await ro(t),n,d,c,o)}}async function ro(s){return s.withReadTx("GetAvailableStorageIds",async e=>{const t=await e.getResourceByName("LSProvider"),n=await e.getResourceData(t,!0);return oo(n)})}function oo(s){return Object.fromEntries(s.fields.filter(e=>e.type=="Dynamic"&&g.isNotNullResourceId(e.value)).map(e=>[e.name.substring(8),e.value]))}exports.ClientDownload=Ee;exports.ClientLogs=xe;exports.ClientLs=He;exports.ClientProgress=We;exports.ClientUpload=Fe;exports.DefaultVirtualLocalStorages=gt;exports.DownloadBlobToURLDriver=Cr;exports.DownloadDriver=Te;exports.DownloadUrlDriver=Gr;exports.DownloadableBlobSnapshot=nt;exports.ImportFileHandleData=nr;exports.ImportFileHandleIndexData=we;exports.ImportFileHandleUploadData=C;exports.IndexResourceSnapshot=qe;exports.LogsDriver=jr;exports.LogsStreamDriver=Ar;exports.LsDriver=ke;exports.MTimeError=he;exports.NetworkError=pe;exports.NoFileForUploading=ge;exports.OnDemandBlobResourceSnapshot=Ge;exports.UnexpectedEOF=ue;exports.UnknownStorageError=A;exports.Updater=Ze;exports.UploadDriver=zr;exports.UploadResourceSnapshot=Ve;exports.UploadTask=it;exports.WrongLocalFileUrl=x;exports.WrongResourceTypeError=j;exports.createDownloadClient=Qn;exports.createLogsClient=Kn;exports.createLsFilesClient=Ae;exports.createUploadBlobClient=Yn;exports.createUploadProgressClient=Xn;exports.getFullPath=Oe;exports.getSize=fe;exports.isMyUpload=lt;exports.isResourceWasDeletedError=ae;exports.isSignMatch=ct;exports.isUpload=z;exports.makeBlobImportSnapshot=dt;exports.makeDownloadableBlobSnapshot=rt;exports.newLocalStorageIdsToRoot=ze;exports.nonRecoverableError=be;exports.parseLocalUrl=Me;exports.uploadBlob=at;exports.validateAbsolute=D;
3
3
  //# sourceMappingURL=index.js.map