@milaboratories/pl-drivers 1.5.50 → 1.5.51

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.
@@ -1 +1 @@
1
- {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/drivers/upload.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EACL,UAAU,EAEX,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAEnE,OAAO,KAAK,KAAK,GAAG,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,yBAAyB,CAAC;AAOjC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAKtD,wBAAgB,sBAAsB,CACpC,eAAe,EAAE,WAAW,GAAG,kBAAkB,GAAG,mBAAmB,EACvE,GAAG,EAAE,aAAa,GACjB,sBAAsB,CAUxB;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,GAAG;IACzC,wEAAwE;IACxE,sBAAsB,EAAE,MAAM,CAAC;IAC/B;yCACqC;IACrC,wBAAwB,EAAE,MAAM,CAAC;CAClC,CAAC;AAIF;;;kEAGkE;AAClE,qBAAa,YAAY;IAQrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAXvB,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA0C;IAEvE,uCAAuC;IACvC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAgB;IAC5C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyB;gBAG5B,MAAM,EAAE,QAAQ,EAChB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,YAAY,EACxB,cAAc,EAAE,cAAc,EAC9B,IAAI,GAAE,eAKtB;IAkBH,4EAA4E;IAC5E,aAAa,CACX,cAAc,EAAE,sBAAsB,GAAG,WAAW,GACnD,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC;IACjC,aAAa,CACX,cAAc,EAAE,sBAAsB,GAAG,WAAW,EACpD,GAAG,EAAE,aAAa,GACjB,GAAG,CAAC,cAAc;IAoBrB,OAAO,CAAC,kBAAkB;IAmC1B,+EAA+E;YACjE,OAAO;IAQrB,iDAAiD;IACpC,UAAU;IAIvB,OAAO,CAAC,oBAAoB,CAA0B;IAEtD,OAAO,CAAC,mBAAmB;IAI3B,2BAA2B;IAC3B,OAAO,CAAC,aAAa;IAKrB,2BAA2B;IAC3B,OAAO,CAAC,YAAY;IAIpB,yDAAyD;IACzD,OAAO,CAAC,WAAW,CAAS;IAC5B,iCAAiC;IACjC,OAAO,CAAC,WAAW,CAAwC;YAE7C,QAAQ;IAwBtB,OAAO,CAAC,uBAAuB;CAKhC"}
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/drivers/upload.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EACL,UAAU,EAEX,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAEnE,OAAO,KAAK,KAAK,GAAG,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,yBAAyB,CAAC;AAOjC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAKtD,wBAAgB,sBAAsB,CACpC,eAAe,EAAE,WAAW,GAAG,kBAAkB,GAAG,mBAAmB,EACvE,GAAG,EAAE,aAAa,GACjB,sBAAsB,CAUxB;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,GAAG;IACzC,wEAAwE;IACxE,sBAAsB,EAAE,MAAM,CAAC;IAC/B;yCACqC;IACrC,wBAAwB,EAAE,MAAM,CAAC;CAClC,CAAC;AAIF;;;kEAGkE;AAClE,qBAAa,YAAY;IAQrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAXvB,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA0C;IAEvE,uCAAuC;IACvC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAgB;IAC5C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyB;gBAG5B,MAAM,EAAE,QAAQ,EAChB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,YAAY,EACxB,cAAc,EAAE,cAAc,EAC9B,IAAI,GAAE,eAKtB;IAkBH,4EAA4E;IAC5E,aAAa,CACX,cAAc,EAAE,sBAAsB,GAAG,WAAW,GACnD,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC;IACjC,aAAa,CACX,cAAc,EAAE,sBAAsB,GAAG,WAAW,EACpD,GAAG,EAAE,aAAa,GACjB,GAAG,CAAC,cAAc;IAoBrB,OAAO,CAAC,kBAAkB;IAoC1B,+EAA+E;YACjE,OAAO;IAQrB,iDAAiD;IACpC,UAAU;IAIvB,OAAO,CAAC,oBAAoB,CAA0B;IAEtD,OAAO,CAAC,mBAAmB;IAI3B,2BAA2B;IAC3B,OAAO,CAAC,aAAa;IAKrB,2BAA2B;IAC3B,OAAO,CAAC,YAAY;IAIpB,yDAAyD;IACzD,OAAO,CAAC,WAAW,CAAS;IAC5B,iCAAiC;IACjC,OAAO,CAAC,WAAW,CAAwC;YAE7C,QAAQ;IAwBtB,OAAO,CAAC,uBAAuB;CAKhC"}
@@ -2,7 +2,8 @@ import { Watcher } from '@milaboratories/computable';
2
2
  import { MiLogger, Signer } from '@milaboratories/ts-helpers';
3
3
  import { ClientProgress } from '../clients/progress';
4
4
  import { ClientUpload, MTimeError, NoFileForUploading, UnexpectedEOF } from '../clients/upload';
5
- import { ImportResourceSnapshot } from './types';
5
+ import { ImportResourceSnapshot, ImportFileHandleUploadData } from './types';
6
+ import { ResourceInfo } from '@milaboratories/pl-tree';
6
7
  import type * as sdk from '@milaboratories/pl-model-common';
7
8
  /** Holds all info needed to upload a file and a status of uploading
8
9
  * and indexing. Also, has a method to update a status of the progress.
@@ -42,6 +43,15 @@ export declare class UploadTask {
42
43
  decCounter(callerId: string): boolean;
43
44
  private isComputableDone;
44
45
  }
46
+ /** Uploads a blob if it's not BlobIndex. */
47
+ export declare function uploadBlob(logger: MiLogger, clientBlob: ClientUpload, res: ResourceInfo, uploadData: ImportFileHandleUploadData, isDoneFn: () => boolean, speed: {
48
+ nPartsWithThisUploadSpeed: number;
49
+ nPartsToIncreaseUpload: number;
50
+ currentSpeed: number;
51
+ maxSpeed: number;
52
+ }): Promise<void>;
53
+ /** Returns true if we need to upload the blob that got from this progress. */
54
+ export declare function isMyUpload(p: sdk.ImportProgress): boolean;
45
55
  export declare function isResourceWasDeletedError(e: any): boolean;
46
56
  export declare function nonRecoverableError(e: any): e is MTimeError | UnexpectedEOF | NoFileForUploading;
47
57
  //# sourceMappingURL=upload_task.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload_task.d.ts","sourceRoot":"","sources":["../../src/drivers/upload_task.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAG1D,OAAO,KAAK,KAAK,GAAG,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAuB,QAAQ,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAExF,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,qBAAqB,CAAC;AAC1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAItD;;gCAEgC;AAChC,qBAAa,UAAU;IAmBnB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,yBAAyB;aAE1B,GAAG,EAAE,sBAAsB;IAvB7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoC;IAC3D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwC;IAChE,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,yBAAyB,CAAK;IACtC,OAAO,CAAC,sBAAsB,CAAM;IAEpC,4DAA4D;IAC5D,OAAO,CAAC,UAAU,CAAC,CAA6B;IACzC,QAAQ,EAAE,GAAG,CAAC,cAAc,CAAC;IAEpC,+DAA+D;IACxD,MAAM,CAAC,EAAE,OAAO,CAAC;IAExB;2DACuD;IACvD,OAAO,CAAC,cAAc,CAAS;gBAGZ,MAAM,EAAE,QAAQ,EAChB,UAAU,EAAE,YAAY,EACxB,cAAc,EAAE,cAAc,EAC9B,yBAAyB,EAAE,MAAM,EAClD,MAAM,EAAE,MAAM,EACE,GAAG,EAAE,sBAAsB;IAQtC,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM;IAWxC,oBAAoB,IAAI,OAAO;IAItC,4CAA4C;IAC/B,cAAc;IAoEd,YAAY;IAuCzB,wDAAwD;IACxD,OAAO,CAAC,iBAAiB;IAIzB,+EAA+E;IAC/E,OAAO,CAAC,gBAAgB;IAMjB,kBAAkB,CAAC,GAAG,EAAE,sBAAsB;IAOrD,OAAO,CAAC,OAAO;IAKR,UAAU,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM;IAKvC,UAAU,CAAC,QAAQ,EAAE,MAAM;IAIlC,OAAO,CAAC,gBAAgB;CAGzB;AAyFD,wBAAgB,yBAAyB,CAAC,CAAC,EAAE,GAAG,WAK/C;AAED,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,GAAG,wDAEzC"}
1
+ {"version":3,"file":"upload_task.d.ts","sourceRoot":"","sources":["../../src/drivers/upload_task.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAG1D,OAAO,KAAK,KAAK,GAAG,MAAM,iCAAiC,CAAC;AAC5D,OAAO,KAAK,EAAuB,QAAQ,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAExF,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,qBAAqB,CAAC;AAC1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAEvD;;gCAEgC;AAChC,qBAAa,UAAU;IAmBnB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,yBAAyB;aAE1B,GAAG,EAAE,sBAAsB;IAvB7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoC;IAC3D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwC;IAChE,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,yBAAyB,CAAK;IACtC,OAAO,CAAC,sBAAsB,CAAM;IAEpC,4DAA4D;IAC5D,OAAO,CAAC,UAAU,CAAC,CAA6B;IACzC,QAAQ,EAAE,GAAG,CAAC,cAAc,CAAC;IAEpC,+DAA+D;IACxD,MAAM,CAAC,EAAE,OAAO,CAAC;IAExB;2DACuD;IACvD,OAAO,CAAC,cAAc,CAAS;gBAGZ,MAAM,EAAE,QAAQ,EAChB,UAAU,EAAE,YAAY,EACxB,cAAc,EAAE,cAAc,EAC9B,yBAAyB,EAAE,MAAM,EAClD,MAAM,EAAE,MAAM,EACE,GAAG,EAAE,sBAAsB;IAQtC,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM;IAWxC,oBAAoB,IAAI,OAAO;IAItC,4CAA4C;IAC/B,cAAc;IA4Cd,YAAY;IAuCzB,wDAAwD;IACxD,OAAO,CAAC,iBAAiB;IAIzB,+EAA+E;IAC/E,OAAO,CAAC,gBAAgB;IAMjB,kBAAkB,CAAC,GAAG,EAAE,sBAAsB;IAOrD,OAAO,CAAC,OAAO;IAKR,UAAU,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM;IAKvC,UAAU,CAAC,QAAQ,EAAE,MAAM;IAIlC,OAAO,CAAC,gBAAgB;CAGzB;AAED,4CAA4C;AAC5C,wBAAsB,UAAU,CAC9B,MAAM,EAAE,QAAQ,EAChB,UAAU,EAAE,YAAY,EACxB,GAAG,EAAE,YAAY,EACjB,UAAU,EAAE,0BAA0B,EACtC,QAAQ,EAAE,MAAM,OAAO,EACvB,KAAK,EAAE;IACL,yBAAyB,EAAE,MAAM,CAAC;IAClC,sBAAsB,EAAE,MAAM,CAAC;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;CAClB,iBAuCF;AAsBD,8EAA8E;AAC9E,wBAAgB,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,cAAc,GAAG,OAAO,CAEzD;AAqED,wBAAgB,yBAAyB,CAAC,CAAC,EAAE,GAAG,WAK/C;AAED,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,GAAG,wDAEzC"}
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export * from './drivers/download_blob';
8
8
  export * from './drivers/download_blob_url/driver';
9
9
  export * from './drivers/download_blob_url/snapshot';
10
10
  export * from './drivers/upload';
11
+ export * from './drivers/upload_task';
11
12
  export * from './drivers/logs_stream';
12
13
  export * from './drivers/logs';
13
14
  export * from './drivers/download_url';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,wBAAwB,CAAC;AAEvC,cAAc,yBAAyB,CAAC;AACxC,cAAc,oCAAoC,CAAC;AACnD,cAAc,sCAAsC,CAAC;AACrD,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,wBAAwB,CAAC;AACvC,cAAc,cAAc,CAAC;AAC7B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,+BAA+B,CAAC;AAE9C,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,wBAAwB,CAAC;AAEvC,cAAc,yBAAyB,CAAC;AACxC,cAAc,oCAAoC,CAAC;AACnD,cAAc,sCAAsC,CAAC;AACrD,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,wBAAwB,CAAC;AACvC,cAAc,cAAc,CAAC;AAC7B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,+BAA+B,CAAC;AAE9C,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var nt=Object.defineProperty;var rt=(s,e,t)=>e in s?nt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var h=(s,e,t)=>rt(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@milaboratories/pl-client"),ot=require("node:fs/promises"),Te=require("undici"),y=require("@protobuf-ts/runtime-rpc"),i=require("@protobuf-ts/runtime"),p=require("@milaboratories/ts-helpers"),F=require("node:fs"),b=require("node:path"),L=require("node:stream"),re=require("node:stream/consumers"),f=require("@milaboratories/computable"),m=require("@milaboratories/pl-tree"),st=require("denque"),P=require("node:crypto"),be=require("node:os"),it=require("node:readline/promises"),k=require("zod"),at=require("node:zlib"),lt=require("tar-fs"),ct=require("decompress"),ke=require("node:timers/promises"),dt=require("node:assert"),ht=require("@milaboratories/pl-model-common"),ut=require("node:util"),pt=require("node:child_process");function U(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=U(ot),oe=U(F),T=U(b),pe=U(be),gt=U(it),Le=U(at),Y=U(lt);class ft 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 ft;class mt 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 mt;class wt 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 yt=new wt;class Tt 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 z=e.int32()+e.pos;e.pos<z;)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 bt=new Tt;class kt 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 kt;class Lt 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 Pt=new Lt;class Ut 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 It=new Ut;class Rt 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 Rt;class Dt 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 St=new Dt;class vt 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 x=new vt;class Nt 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:()=>x},{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(x.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++)x.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 Bt=new Nt;class Ct 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 Ct;class $t 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 Ft=new $t;class Wt 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 _t=new Wt,A=new y.ServiceType("MiLaboratories.Controller.Shared.Upload",[{name:"Init",options:{},I:yt,O:bt},{name:"GetPartURL",options:{},I:St,O:Bt},{name:"UpdateProgress",options:{},I:Pt,O:It},{name:"Finalize",options:{},I:Ft,O:_t}]);class Mt{constructor(e){h(this,"typeName",A.typeName);h(this,"methods",A.methods);h(this,"options",A.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 Pe(s){return Object.fromEntries(s.map(({name:e,value:t})=>[e,t]))}class se extends Error{}class ie extends Error{}class ae extends Error{}class le extends Error{}class Ue{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=r,this.grpcClient=new Mt(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 Et(n,a.chunkStart,a.chunkEnd);await Ht(n,r);try{const{body:c,statusCode:u,headers:z}=await Te.request(a.uploadUrl,{dispatcher:this.httpClient,body:d,headersTimeout:6e4,bodyTimeout:6e4,headers:Pe(a.headers),method:a.method.toUpperCase()}),tt=await c.text();zt(u,tt,z,a)}catch(c){throw c instanceof ae?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 Et(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 Ot(n,l,r,o);return l.subarray(0,a)}catch(r){throw r&&typeof r=="object"&&"code"in r&&r.code=="ENOENT"?new le(`there is no file ${s} for uploading`):r}finally{await(n==null?void 0:n.close())}}async function Ot(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 ie("file ended earlier than expected.");r+=o}return r}async function Ht(s,e){const t=BigInt(Math.floor((await w.stat(s)).mtimeMs/1e3));if(t>e)throw new se(`file was modified, expected mtime: ${e}, got: ${t}.`)}function zt(s,e,t,n){if(s!=200)throw new ae(`response is not ok, status code: ${s}, body: ${e}, headers: ${JSON.stringify(t)}, url: ${n.uploadUrl}`)}class xt 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 xt;class At 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 At;class jt 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 R=new jt;class Gt 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 Gt;class Vt 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 qt=new Vt;class Jt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Response",[{no:1,name:"report",kind:"message",T:()=>R}])}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=R.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&&R.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 Zt=new Jt;class Qt 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 Qt;class Xt 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 Kt=new Xt;class Yt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Response",[{no:1,name:"report",kind:"message",T:()=>R}])}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=R.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&&R.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 en=new Yt,j=new y.ServiceType("MiLaboratories.Controller.Shared.Progress",[{name:"GetStatus",options:{"google.api.http":{get:"/resources/{resource_id}/get-progress"}},I:qt,O:Zt},{name:"RealtimeStatus",serverStreaming:!0,options:{},I:Kt,O:en}]);class tn{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 Ie{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.client=n,this.logger=r,this.grpcClient=new tn(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 M extends Error{}class Re{constructor(e){this.httpClient=e}async download(e,t,n){const{statusCode:r,body:o,headers:l}=await Te.request(e,{dispatcher:this.httpClient,headers:t,signal:n}),a=L.Readable.toWeb(o);return await nn(r,a,e),{content:a,size:Number(l["content-length"])}}}async function nn(s,e,t){if(s!=200){const n=(await re.text(e)).substring(0,1e3);throw 400<=s&&s<500?new M(`Http error: statusCode: ${s} url: ${t.toString()}, beginning of body: ${n}`):new Error(`Http error: statusCode: ${s} url: ${t.toString()}`)}}function I(s){if(!b.isAbsolute(s))throw new Error(`Path ${s} is not absolute.`);return s}class rn 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 rn;class on 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 on;class sn 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 an=new sn;class ln 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 G=new ln;class cn 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:()=>G}])}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(G.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++)G.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 dn=new cn,V=new y.ServiceType("MiLaboratories.Controller.Shared.Download",[{name:"GetDownloadURL",options:{"google.api.http":{get:"/resources/{resource_id}/get-download-url"}},I:an,O:dn}]);class hn{constructor(e){h(this,"typeName",V.typeName);h(this,"methods",V.methods);h(this,"options",V.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 De{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 hn(this.grpcTransport),this.remoteFileDownloader=new Re(t),this.localStorageIdsToRoot=Ne(r)}close(){}async downloadBlob(e,t,n){const{downloadUrl:r,headers:o}=await this.grpcGetDownloadUrl(e,t,n);return this.logger.info(`download blob from url ${r}`),pn(r)?await this.readLocalFile(r):await this.remoteFileDownloader.download(r,Pe(o),n)}async readLocalFile(e){const{storageId:t,relativePath:n}=Se(e),r=ve(t,this.localStorageIdsToRoot,n);return{content:L.Readable.toWeb(oe.createReadStream(r)),size:(await w.stat(r)).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 Se(s){const e=new URL(s);if(e.pathname=="")throw new E(`url for local filepath ${s} does not match url scheme`);return{storageId:e.host,relativePath:decodeURIComponent(e.pathname.slice(1))}}function ve(s,e,t){const n=e.get(s);if(n===void 0)throw new O(`Unknown storage location: ${s}`);return n===""?t:T.join(n,t)}const un="storage://";function pn(s){return s.startsWith(un)}class E extends Error{}class O extends Error{}function Ne(s){const e=new Map;for(const t of s)t.localPath!==""&&I(t.localPath),e.set(t.storageId,t.localPath);return e}class gn 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 q=new gn;class fn 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 fn;class mn 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:()=>q},{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=q.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&&q.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 J=new mn;class wn 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 wn;class yn 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 Tn=new yn;class bn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Response",[{no:1,name:"items",kind:"message",repeat:1,T:()=>J},{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(J.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++)J.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 kn=new bn,Z=new y.ServiceType("MiLaboratories.Controller.Shared.LS",[{name:"List",options:{},I:Tn,O:kn}]);class Ln{constructor(e){h(this,"typeName",Z.typeName);h(this,"methods",Z.methods);h(this,"options",Z.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 Be{constructor(e,t){h(this,"grpcClient");this.logger=t,this.grpcClient=new Ln(e)}close(){}async list(e,t,n){return await this.grpcClient.list({resourceId:e.id,location:t},g.addRTypeToMetadata(e.type,n)).response}}class Pn 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 Pn;class Un 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 In=new Un;class Rn 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 Dn=new Rn;class Sn 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 vn=new Sn;class Nn 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 Bn=new Nn;class Cn 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 $n=new Cn;class Fn 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 Fn,Q=new y.ServiceType("MiLaboratories.Controller.Shared.Streaming",[{name:"StreamBinary",serverStreaming:!0,options:{},I:In,O:D},{name:"ReadBinary",options:{},I:Dn,O:D},{name:"StreamText",serverStreaming:!0,options:{},I:vn,O:D},{name:"ReadText",options:{},I:Bn,O:D},{name:"LastLines",options:{},I:$n,O:D}]);class Wn{constructor(e){h(this,"typeName",Q.typeName);h(this,"methods",Q.methods);h(this,"options",Q.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 Ce{constructor(e,t,n){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=n,this.grpcClient=new Wn(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 _n(s,e,t){return e.getDriver({name:"DownloadBlob",init:(n,r,o)=>new De(r,o,s,t)})}function Mn(s,e){return s.getDriver({name:"StreamLogs",init:(t,n,r)=>new Ce(n,r,e)})}function En(s,e){return s.getDriver({name:"UploadProgress",init:(t,n,r)=>new Ie(n,r,s,e)})}function On(s,e){return s.getDriver({name:"UploadBlob",init:(t,n,r)=>new Ue(n,r,s,e)})}function $e(s,e){return s.getDriver({name:"LsFiles",init:(t,n,r)=>new Be(n,e)})}class Hn{constructor(e,t,n,r,o){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.clientDownload=t,this.rInfo=n,this.path=r,this.handle=o}info(){return{rInfo:this.rInfo,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(){try{const e=await this.ensureDownloaded();this.setDone(e),this.change.markChanged()}catch(e){throw ce(e)&&(this.setError(e),this.change.markChanged(),await w.rm(this.path)),e}}async ensureDownloaded(){if(await p.ensureDirExists(T.dirname(this.path)),await p.fileExists(this.path))return this.logger.info(`a blob was already downloaded: ${this.path}`),(await w.stat(this.path)).size;const{content:e,size:t}=await this.clientDownload.downloadBlob(this.rInfo);return await p.createPathAtomically(this.logger,this.path,async n=>{const r=L.Writable.toWeb(F.createWriteStream(n,{flags:"wx"}));await e.pipeTo(r)}),t}abort(e){this.signalCtl.abort(new Fe(e))}getBlob(){return this.done?this.error?{done:!0,result:{ok:!1,error:this.error}}:{done:!0,result:{ok:!0,value:{handle:this.handle,size:this.size}}}:{done:!1}}setDone(e){this.done=!0,this.size=e}setError(e){this.done=!0,this.error=e}}function ce(s){return s instanceof Fe||s instanceof M||s instanceof O||s instanceof E||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")}class Fe extends Error{}class de{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 We=/^blob\+local:\/\/download\/(?<path>.*)#(?<signature>.*)$/;function zn(s,e){return`blob+local://download/${s}#${e.sign(s)}`}function xn(s){return!!s.match(We)}function X(s,e){const t=s.match(We);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 _e=m.rsSchema({kv:{"ctl/file/blobInfo":k.z.object({sizeBytes:k.z.coerce.number()})}});function Me(s){return s.kv["ctl/file/blobInfo"].sizeBytes}const v=k.z.object({localPath:k.z.string(),pathSignature:k.z.string(),sizeBytes:k.z.string(),modificationTime:k.z.string()}),he=k.z.object({storageId:k.z.string(),path:k.z.string()}),An=k.z.union([v,he]),Ee=m.rsSchema({data:v,fields:{blob:!1}}),Oe=m.rsSchema({fields:{incarnation:!1}}),He=/^blob\+remote:\/\/download\/(?<content>(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*))#(?<signature>.*)$/;function jn(s,e){const t=`${s.type.name}/${s.type.version}/${BigInt(s.id)}`;return`blob+remote://download/${t}#${e.sign(t)}`}function Gn(s){return!!s.match(He)}function Vn(s,e){const t=s.match(He);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}}}function ze(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 xe=/^log\+live:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function W(s){return xe.test(s)}const Ae=/^log\+ready:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function qn(s){return Ae.test(s)}function _(s){let e;if(W(s))e=s.match(xe);else if(qn(s))e=s.match(Ae);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}}}class H extends Error{}class je{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}})())}}class Jn{constructor(e,t,n,r,o,l){h(this,"idToDownload",new Map);h(this,"cache");h(this,"downloadQueue");h(this,"idToOnDemand",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 de(l.cacheSoftSizeBytes),this.downloadQueue=new p.TaskProcessor(this.logger,l.nConcurrentDownloads),this.saveDir=T.resolve(r)}getDownloadedBlob(e,t){if(t===void 0)return f.Computable.make(l=>this.getDownloadedBlob(e,l));const n=m.treeEntryToResourceInfo(e,t),r=P.randomUUID();t.addOnDestroy(()=>this.releaseBlob(n.id,r));const o=this.getDownloadedBlobNoCtx(t.watcher,n,r);return o==null&&t.markUnstable("download blob is still undefined"),o}getDownloadedBlobNoCtx(e,t,n){S("getDownloadedBlob",t.type);let r=this.idToDownload.get(t.id);if(r===void 0){const l=this.setNewDownloadTask(t);this.downloadQueue.push({fn:()=>this.downloadBlob(l,n),recoverableErrorPredicate:a=>!ce(a)}),r=l}r.attach(e,n);const o=r.getBlob();if(o.done){if(o.result.ok)return o.result.value;throw o.result.error}}setNewDownloadTask(e){const t=this.getFilePath(e.id),n=new Hn(this.logger,this.clientDownload,e,t,zn(t,this.signer));return this.idToDownload.set(e.id,n),n}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,_e,t):e,r=P.randomUUID();return t.addOnDestroy(()=>this.releaseOnDemandBlob(n.id,r)),this.getOnDemandBlobNoCtx(n,r)}getOnDemandBlobNoCtx(e,t){S("getOnDemandBlob",e.type);let n=this.idToOnDemand.get(e.id);return n===void 0&&(n=new Zn(Me(e),jn(e,this.signer)),this.idToOnDemand.set(e.id,n)),n.attach(t),n.getHandle()}getLocalPath(e){const{path:t}=X(e,this.signer);return t}async getContent(e){if(xn(e))return await Xn(this.getLocalPath(e));if(Gn(e)){const t=Vn(e,this.signer),{content:n}=await this.clientDownload.downloadBlob(t);return await re.buffer(n)}throw new Error("Malformed remote handle")}getComputableContent(e){return f.Computable.make(t=>this.getDownloadedBlob(e,t),{postprocessValue:t=>t?this.getContent(t.handle):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=P.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r.id,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){S("getLastLogs",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=X(o.handle,this.signer);let a=this.idToLastLines.get(t.id);if(a==null){const c=new ge(l,n);this.idToLastLines.set(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=P.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r.id,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){S("getProgressLog",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=X(o.handle,this.signer);let a=this.idToProgressLog.get(t.id);if(a==null){const c=new ge(l,1,n);this.idToProgressLog.set(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 S("getLogHandle",e.type),ze(!1,e)}async lastLines(e,t,n,r){const o=await this.clientLogs.lastLines(_(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),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.idToDownload.get(e);if(n!=null)if(this.cache.existsFile(n.path)){const r=this.cache.removeFile(n.path,t);await Promise.all(r.map(async o=>{await w.rm(o.path),this.cache.removeCache(o),this.removeTask(o,`the task ${g.stringifyWithResourceId(o.info())} was removedfrom cache along with ${g.stringifyWithResourceId(r.map(l=>l.info()))}`)}))}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.idToDownload.delete(e.rInfo.id),this.idToLastLines.delete(e.rInfo.id),this.idToProgressLog.delete(e.rInfo.id)}async releaseOnDemandBlob(e,t){var r;(((r=this.idToOnDemand.get(e))==null?void 0:r.release(t))??!1)&&this.idToOnDemand.delete(e)}async releaseAll(){this.downloadQueue.stop(),this.idToDownload.forEach((e,t)=>{this.idToDownload.delete(t),e.change.markChanged()})}getFilePath(e){return T.resolve(this.saveDir,String(BigInt(e)))}}class Zn{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 ge{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 je(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 Qn(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 Qn(s,e,t){const n=oe.createReadStream(s),r=new L.Writable;return new Promise((o,l)=>{const a=gt.createInterface(n,r),d=new st;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 Xn(s){return await re.buffer(L.Readable.toWeb(oe.createReadStream(s)))}function S(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 H(t)}}const Ge=m.rsSchema({});function Ve(s,e){const t=m.isPlTreeEntry(s)?e.accessor(s).node():m.isPlTreeEntryAccessor(s)?s.node():s;return m.makeResourceSnapshot(t,Ge)}function Kn(s,e,t){const n=b.relative(e,t);return`plblob+folder://${s.sign(n)}.${n}.blob`}function Yn(s){return new URL(s).protocol=="plblob+folder:"}function er(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=tr(b.join(t,`${o}`),n.pathname.slice(1));return(n.pathname==""||n.pathname=="/")&&(a=b.join(a,"index.html")),b.resolve(a)}function tr(s,e){const t=b.resolve(s,e),n=b.resolve(s);if(!t.startsWith(n))throw new Error("Path validation failed.");return t}class nr{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())}`),rr(e)){this.setError(e),this.change.markChanged(),await ee(this.path);return}throw e}}async downloadAndDecompress(e){if(this.state={},this.state.parentDir=b.dirname(this.path),await p.ensureDirExists(this.state.parentDir),this.state.fileExisted=await p.fileExists(this.path),this.state.fileExisted)return await qe(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(Y.extract(r));await t.pipeTo(o,{signal:e});return;case"tgz":await w.mkdir(r);const l=L.Transform.toWeb(Le.createGunzip()),a=L.Writable.toWeb(Y.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 ct(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=Kn(this.signer,this.saveDir,this.path)}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new Je(e))}}async function qe(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 qe(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function ee(s){await w.rm(s,{recursive:!0,force:!0})}let Je=class extends Error{};function rr(s){return s instanceof Je||s instanceof M||s instanceof O||s instanceof E||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")||String(s).includes("incorrect header check")}function N(s,e){return`id:${String(BigInt(s))}-${e}`}class or{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 de(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(Yn(e))return er(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)?Ve(e,n):e,o=P.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(N(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=>!ce(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(N(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 ee(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 ee(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 nr(this.logger,this.signer,this.saveDir,this.getFilePath(t.id,n),t,n,this.clientDownload);return o.attach(e,r),this.idToDownload.set(N(t.id,n),o),o}removeTask(e,t){e.abort(t),e.change.markChanged(),this.idToDownload.delete(N(e.rInfo.id,e.format))}getFilePath(e,t){return T.join(this.saveDir,`${String(BigInt(e))}_${t}`)}}class sr{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}=ir(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 ar(this.progress)}shouldScheduleUpload(){return this.progress.isUpload&&this.progress.isUploadSignMatch}async uploadBlobTask(){dt(te(this.res),"the upload operation can be done only for BlobUploads");const e=1e4;try{if(this.isComputableDone())return;const t=await this.clientBlob.initUpload(this.res,{timeout:e});this.logger.info(`started to upload blob ${this.res.id}, parts overall: ${t.overall}, parts remained: ${t.toUpload.length}, number of concurrent uploads: ${this.nMaxUploads}`);const n=r=>async o=>{this.isComputableDone()||(await this.clientBlob.partUpload(this.res,this.uploadData.localPath,BigInt(this.uploadData.modificationTime),r,{timeout:e}),this.logger.info(`uploaded chunk ${r}/${t.overall} of resource: ${this.res.id}`),this.nPartsWithThisUploadSpeed++,this.nPartsWithThisUploadSpeed>=this.nPartsToIncreaseUpload&&(this.nPartsWithThisUploadSpeed=0,this.nMaxUploads=pr(this.logger,this.nMaxUploads,this.maxNConcurrentPartsUpload),o.setConcurrency(this.nMaxUploads)))};if(await p.asyncPool(this.nMaxUploads,t.toUpload.map(n)),this.isComputableDone())return;await this.clientBlob.finalize(this.res,{timeout:e}),this.logger.info(`uploading of resource ${this.res.id} finished.`),this.change.markChanged()}catch(t){if(this.setRetriableError(t),fe(t)){this.logger.warn(`resource was deleted while uploading a blob: ${t}`),this.change.markChanged(),this.setDone(!0);return}if(this.logger.error(`error while uploading a blob: ${t}`),this.change.markChanged(),Ze(t)){this.setTerminalError(t);return}throw ur(t)&&(this.nMaxUploads=gr(this.logger,this.nMaxUploads,1)),t}}async updateStatus(){var e;try{const t=await this.clientProgress.getStatus(this.res,{timeout:1e4}),n=this.progress.status,r=hr(this.alreadyExisted,dr(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(fe(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){lr(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()}}function ir(s,e){let t,n;return te(s)&&(n=v.parse(s.data),t=cr(e,n.localPath,n.pathSignature)),{uploadData:n,progress:{done:!1,status:void 0,isUpload:te(s),isUploadSignMatch:t,lastError:void 0}}}function ar(s){return s.done,s.isUpload,s.isUploadSignMatch,s.lastError,s.status&&(s.status.progress,s.status.bytesProcessed,s.status.bytesTotal),s}function lr(s){return"blob"in s.fields?s.fields.blob!==void 0:s.fields.incarnation!==void 0}function te(s){return s.type.name.startsWith("BlobUpload")}function cr(s,e,t){try{return s.verify(e,t),!0}catch{return!1}}function dr(s){return{progress:s.progress??0,bytesProcessed:Number(s.bytesProcessed),bytesTotal:Number(s.bytesTotal)}}function hr(s,e){return s&&e.bytesTotal!=0&&e.bytesProcessed==0?{progress:1,bytesProcessed:Number(e.bytesTotal),bytesTotal:Number(e.bytesTotal)}:e}function fe(s){return s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED"||s.code=="ALREADY_EXISTS")}function Ze(s){return s instanceof se||s instanceof ie||s instanceof le}function ur(s){return s==null?void 0:s.message.includes("UND_ERR_HEADERS_TIMEOUT")}function pr(s,e,t){const n=Math.min(e+2,t);return n!=e&&s.info(`uploadTask.increaseConcurrency: increased from ${e} to ${n}`),n}function gr(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 Qe(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,Ee):m.makeResourceSnapshot(t,Oe)}class fr{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)?Qe(e,t):e,r=P.randomUUID();return t.attacheHooks(this.hooks),t.addOnDestroy(()=>this.release(n.id,r)),this.getProgressIdNoCtx(t.watcher,n,r)}getProgressIdNoCtx(e,t,n){wr("getProgressId",t.type);const r=this.idToProgress.get(t.id);if(r!=null)return r.setDoneIfOutputSet(t),r.getProgress(e,n);const o=new sr(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=>!Ze(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 ke.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllNotDoneProgresses(){return Array.from(this.idToProgress.entries()).filter(([e,t])=>!mr(t.progress)).map(([e,t])=>t)}}function mr(s){var e;return s.done&&(((e=s.status)==null?void 0:e.progress)??0)>=1}function wr(s,e){if(!e.name.startsWith("BlobUpload")&&!e.name.startsWith("BlobIndex"))throw new H(`${s}: wrong resource type: ${e.name}, expected: a resource of either type 'BlobUpload' or 'BlobIndex'.`)}class yr{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=P.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){K("getLastLogs",t.type);let o=this.idToLastLines.get(t.id);if(o==null){const a=new me(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=P.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){K("getProgressLog",t.type);let o=this.idToProgressLog.get(t.id);if(o==null){const a=new me(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 K("getLogHandle",e.type),ze(!0,e)}async lastLines(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.lastLines(_(e),t,BigInt(n??0),r))}async readText(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.readText(_(e),t,BigInt(n??0),r))}async tryWithNotFound(e,t){if(!W(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 ke.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 me{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 K(s,e){if(!e.name.startsWith("StreamWorkdir"))throw new H(`${s}: wrong resource type: ${e.name}, expected: a resource of type 'StreamWorkdir'.`)}class Tr{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=C(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=C(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=C(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=C(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 W(e)?await this.logsStreamDriver.lastLines(e,t,n,r):await this.downloadDriver.lastLines(e,t,n,r)}async readText(e,t,n,r){return W(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 C(s,e){var t;return(t=s.accessor(e).node().traverse("stream"))==null?void 0:t.resourceInfo}class br{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 de(this.opts.cacheSoftSizeBytes),this.downloadHelper=new Re(t)}getPath(e,t){if(t===void 0)return f.Computable.make(o=>this.getPath(e,o));const n=P.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 ne(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 ne(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 kr(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=P.createHash("sha256").update(e.toString()).digest("hex");return T.join(this.saveDir,t)}}class kr{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 we||n instanceof M){this.setError(n),this.change.markChanged(),await ne(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 Xe(this.path);const r=await e.download(this.url.toString(),{},n);let o=r.content;if(t){const l=L.Transform.toWeb(Le.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(Y.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 we(e))}}class we extends Error{}async function Xe(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 Xe(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function ne(s){await w.rm(s,{recursive:!0,force:!0})}function ye(s,e){return`index://index/${encodeURIComponent(JSON.stringify({storageId:s,path:e}))}`}function Lr(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 Pr(s){const e=new URL(s);return v.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Ur(s){const e=new URL(s);return he.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Ir(s){if(vr(s))return Br(s);if(Rr(s))return Sr(s);p.assertNever(s)}const Ke=/^local:\/\/(?<name>.*)\/(?<path>.*)$/;function Rr(s){return Ke.test(s)}function Dr(s,e){return`local://${s}/${encodeURIComponent(e)}`}function Sr(s){const e=s.match(Ke);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 Ye=/^remote:\/\/(?<name>.*)\/(?<resourceId>.*)$/;function vr(s){return Ye.test(s)}function Nr(s,e){return`remote://${s}/${BigInt(e)}`}function Br(s){const e=s.match(Ye);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:Cr(t),name:t,isRemote:!0}}function Cr(s){return{name:`LS/${s}`,version:"1"}}async function et(){const s=be.homedir();if(b.sep=="/")return[{name:"local",root:"/",initialPath:s}];{const t=b.parse(s).root.replaceAll(":\\","");try{return(await ut.promisify(pt.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 ue{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(ht.isImportFileHandleIndex(e)){const t=Ur(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=Pr(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 ye(n.storageId,r)}const t=await w.stat(e,{bigint:!0});return Lr(e,this.signer,t.size,t.mtimeMs/1000n)}async getStorageList(){const e=[...this.virtualStoragesMap.values()].map(r=>({name:r.name,handle:Dr(r.name,r.root),initialFullPath:r.initialPath})),n=Object.entries(this.storageIdToResourceId).map(([r,o])=>({name:r,handle:Nr(r,o),initialFullPath:"",isInitialPathHome:!1})).filter(r=>r.name!=="root");return[...e,...n]}async listFiles(e,t){const n=Ir(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:ye(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 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=$e(t,e);l||(l=await et());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 ue(e,a,await $r(t),n,d,c,o)}}async function $r(s){return s.withReadTx("GetAvailableStorageIds",async e=>{const t=await e.getResourceByName("LSProvider"),n=await e.getResourceData(t,!0);return Fr(n)})}function Fr(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=De;exports.ClientLogs=Ce;exports.ClientLs=Be;exports.ClientProgress=Ie;exports.ClientUpload=Ue;exports.DefaultVirtualLocalStorages=et;exports.DownloadBlobToURLDriver=or;exports.DownloadDriver=Jn;exports.DownloadUrlDriver=br;exports.DownloadableBlobSnapshot=Ge;exports.ImportFileHandleData=An;exports.ImportFileHandleIndexData=he;exports.ImportFileHandleUploadData=v;exports.IndexResourceSnapshot=Oe;exports.LogsDriver=Tr;exports.LogsStreamDriver=yr;exports.LsDriver=ue;exports.MTimeError=se;exports.NetworkError=ae;exports.NoFileForUploading=le;exports.OnDemandBlobResourceSnapshot=_e;exports.UnexpectedEOF=ie;exports.UnknownStorageError=O;exports.Updater=je;exports.UploadDriver=fr;exports.UploadResourceSnapshot=Ee;exports.WrongLocalFileUrl=E;exports.WrongResourceTypeError=H;exports.createDownloadClient=_n;exports.createLogsClient=Mn;exports.createLsFilesClient=$e;exports.createUploadBlobClient=On;exports.createUploadProgressClient=En;exports.getFullPath=ve;exports.getSize=Me;exports.makeBlobImportSnapshot=Qe;exports.makeDownloadableBlobSnapshot=Ve;exports.newLocalStorageIdsToRoot=Ne;exports.parseLocalUrl=Se;exports.validateAbsolute=I;
1
+ "use strict";var st=Object.defineProperty;var it=(s,e,t)=>e in s?st(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var h=(s,e,t)=>it(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@milaboratories/pl-client"),at=require("node:fs/promises"),be=require("undici"),y=require("@protobuf-ts/runtime-rpc"),i=require("@protobuf-ts/runtime"),p=require("@milaboratories/ts-helpers"),F=require("node:fs"),b=require("node:path"),L=require("node:stream"),oe=require("node:stream/consumers"),f=require("@milaboratories/computable"),m=require("@milaboratories/pl-tree"),lt=require("denque"),P=require("node:crypto"),ke=require("node:os"),ct=require("node:readline/promises"),k=require("zod"),dt=require("node:zlib"),ht=require("tar-fs"),ut=require("decompress"),Le=require("node:timers/promises"),pt=require("node:assert"),gt=require("@milaboratories/pl-model-common"),ft=require("node:util"),mt=require("node:child_process");function U(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=U(at),se=U(F),T=U(b),fe=U(ke),wt=U(ct),Pe=U(dt),Y=U(ht);class yt 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 yt;class Tt 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 Tt;class bt 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 kt=new bt;class Lt 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 z=e.int32()+e.pos;e.pos<z;)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 Pt=new Lt;class Ut 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 Ut;class It 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 Rt=new It;class Dt 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 St=new Dt;class vt 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 vt;class Nt 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 Bt=new Nt;class Ct 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 x=new Ct;class $t 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:()=>x},{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(x.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++)x.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 Ft=new $t;class Wt 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 Wt;class _t 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 Mt=new _t;class Et 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 Ot=new Et,A=new y.ServiceType("MiLaboratories.Controller.Shared.Upload",[{name:"Init",options:{},I:kt,O:Pt},{name:"GetPartURL",options:{},I:Bt,O:Ft},{name:"UpdateProgress",options:{},I:Rt,O:St},{name:"Finalize",options:{},I:Mt,O:Ot}]);class Ht{constructor(e){h(this,"typeName",A.typeName);h(this,"methods",A.methods);h(this,"options",A.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 Ue(s){return Object.fromEntries(s.map(({name:e,value:t})=>[e,t]))}class ie extends Error{}class ae extends Error{}class le extends Error{}class ce extends Error{}class Ie{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=r,this.grpcClient=new Ht(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 zt(n,a.chunkStart,a.chunkEnd);await At(n,r);try{const{body:c,statusCode:u,headers:z}=await be.request(a.uploadUrl,{dispatcher:this.httpClient,body:d,headersTimeout:6e4,bodyTimeout:6e4,headers:Ue(a.headers),method:a.method.toUpperCase()}),ot=await c.text();jt(u,ot,z,a)}catch(c){throw c instanceof le?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 zt(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 xt(n,l,r,o);return l.subarray(0,a)}catch(r){throw r&&typeof r=="object"&&"code"in r&&r.code=="ENOENT"?new ce(`there is no file ${s} for uploading`):r}finally{await(n==null?void 0:n.close())}}async function xt(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 ae("file ended earlier than expected.");r+=o}return r}async function At(s,e){const t=BigInt(Math.floor((await w.stat(s)).mtimeMs/1e3));if(t>e)throw new ie(`file was modified, expected mtime: ${e}, got: ${t}.`)}function jt(s,e,t,n){if(s!=200)throw new le(`response is not ok, status code: ${s}, body: ${e}, headers: ${JSON.stringify(t)}, url: ${n.uploadUrl}`)}class Gt 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 Gt;class Vt 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 Vt;class qt 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 R=new qt;class Jt 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 Jt;class Zt 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 Qt=new Zt;class Xt extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Response",[{no:1,name:"report",kind:"message",T:()=>R}])}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=R.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&&R.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 Kt=new Xt;class Yt 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 Yt;class en 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 tn=new en;class nn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Response",[{no:1,name:"report",kind:"message",T:()=>R}])}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=R.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&&R.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,j=new y.ServiceType("MiLaboratories.Controller.Shared.Progress",[{name:"GetStatus",options:{"google.api.http":{get:"/resources/{resource_id}/get-progress"}},I:Qt,O:Kt},{name:"RealtimeStatus",serverStreaming:!0,options:{},I:tn,O:rn}]);class on{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 Re{constructor(e,t,n,r){h(this,"grpcClient");this.grpcTransport=e,this.client=n,this.logger=r,this.grpcClient=new on(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 M extends Error{}class De{constructor(e){this.httpClient=e}async download(e,t,n){const{statusCode:r,body:o,headers:l}=await be.request(e,{dispatcher:this.httpClient,headers:t,signal:n}),a=L.Readable.toWeb(o);return await sn(r,a,e),{content:a,size:Number(l["content-length"])}}}async function sn(s,e,t){if(s!=200){const n=(await oe.text(e)).substring(0,1e3);throw 400<=s&&s<500?new M(`Http error: statusCode: ${s} url: ${t.toString()}, beginning of body: ${n}`):new Error(`Http error: statusCode: ${s} url: ${t.toString()}`)}}function I(s){if(!b.isAbsolute(s))throw new Error(`Path ${s} is not absolute.`);return s}class an 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 an;class ln 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 ln;class cn 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 dn=new cn;class hn 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 G=new hn;class un 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:()=>G}])}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(G.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++)G.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 pn=new un,V=new y.ServiceType("MiLaboratories.Controller.Shared.Download",[{name:"GetDownloadURL",options:{"google.api.http":{get:"/resources/{resource_id}/get-download-url"}},I:dn,O:pn}]);class gn{constructor(e){h(this,"typeName",V.typeName);h(this,"methods",V.methods);h(this,"options",V.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 Se{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 gn(this.grpcTransport),this.remoteFileDownloader=new De(t),this.localStorageIdsToRoot=Be(r)}close(){}async downloadBlob(e,t,n){const{downloadUrl:r,headers:o}=await this.grpcGetDownloadUrl(e,t,n);return this.logger.info(`download blob from url ${r}`),mn(r)?await this.readLocalFile(r):await this.remoteFileDownloader.download(r,Ue(o),n)}async readLocalFile(e){const{storageId:t,relativePath:n}=ve(e),r=Ne(t,this.localStorageIdsToRoot,n);return{content:L.Readable.toWeb(se.createReadStream(r)),size:(await w.stat(r)).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 ve(s){const e=new URL(s);if(e.pathname=="")throw new E(`url for local filepath ${s} does not match url scheme`);return{storageId:e.host,relativePath:decodeURIComponent(e.pathname.slice(1))}}function Ne(s,e,t){const n=e.get(s);if(n===void 0)throw new O(`Unknown storage location: ${s}`);return n===""?t:T.join(n,t)}const fn="storage://";function mn(s){return s.startsWith(fn)}class E extends Error{}class O extends Error{}function Be(s){const e=new Map;for(const t of s)t.localPath!==""&&I(t.localPath),e.set(t.storageId,t.localPath);return e}class wn 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 q=new wn;class yn 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 yn;class Tn 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:()=>q},{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=q.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&&q.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 J=new Tn;class bn 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 bn;class kn 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 Ln=new kn;class Pn extends i.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Response",[{no:1,name:"items",kind:"message",repeat:1,T:()=>J},{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(J.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++)J.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 Un=new Pn,Z=new y.ServiceType("MiLaboratories.Controller.Shared.LS",[{name:"List",options:{},I:Ln,O:Un}]);class In{constructor(e){h(this,"typeName",Z.typeName);h(this,"methods",Z.methods);h(this,"options",Z.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 Ce{constructor(e,t){h(this,"grpcClient");this.logger=t,this.grpcClient=new In(e)}close(){}async list(e,t,n){return await this.grpcClient.list({resourceId:e.id,location:t},g.addRTypeToMetadata(e.type,n)).response}}class Rn 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 Rn;class Dn 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 Sn=new Dn;class vn 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 Nn=new vn;class Bn 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 Cn=new Bn;class $n 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 Fn=new $n;class Wn 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 _n=new Wn;class Mn 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 Mn,Q=new y.ServiceType("MiLaboratories.Controller.Shared.Streaming",[{name:"StreamBinary",serverStreaming:!0,options:{},I:Sn,O:D},{name:"ReadBinary",options:{},I:Nn,O:D},{name:"StreamText",serverStreaming:!0,options:{},I:Cn,O:D},{name:"ReadText",options:{},I:Fn,O:D},{name:"LastLines",options:{},I:_n,O:D}]);class En{constructor(e){h(this,"typeName",Q.typeName);h(this,"methods",Q.methods);h(this,"options",Q.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 $e{constructor(e,t,n){h(this,"grpcClient");this.grpcTransport=e,this.httpClient=t,this.logger=n,this.grpcClient=new En(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 On(s,e,t){return e.getDriver({name:"DownloadBlob",init:(n,r,o)=>new Se(r,o,s,t)})}function Hn(s,e){return s.getDriver({name:"StreamLogs",init:(t,n,r)=>new $e(n,r,e)})}function zn(s,e){return s.getDriver({name:"UploadProgress",init:(t,n,r)=>new Re(n,r,s,e)})}function xn(s,e){return s.getDriver({name:"UploadBlob",init:(t,n,r)=>new Ie(n,r,s,e)})}function Fe(s,e){return s.getDriver({name:"LsFiles",init:(t,n,r)=>new Ce(n,e)})}class An{constructor(e,t,n,r,o){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.clientDownload=t,this.rInfo=n,this.path=r,this.handle=o}info(){return{rInfo:this.rInfo,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(){try{const e=await this.ensureDownloaded();this.setDone(e),this.change.markChanged()}catch(e){throw de(e)&&(this.setError(e),this.change.markChanged(),await w.rm(this.path)),e}}async ensureDownloaded(){if(await p.ensureDirExists(T.dirname(this.path)),await p.fileExists(this.path))return this.logger.info(`a blob was already downloaded: ${this.path}`),(await w.stat(this.path)).size;const{content:e,size:t}=await this.clientDownload.downloadBlob(this.rInfo);return await p.createPathAtomically(this.logger,this.path,async n=>{const r=L.Writable.toWeb(F.createWriteStream(n,{flags:"wx"}));await e.pipeTo(r)}),t}abort(e){this.signalCtl.abort(new We(e))}getBlob(){return this.done?this.error?{done:!0,result:{ok:!1,error:this.error}}:{done:!0,result:{ok:!0,value:{handle:this.handle,size:this.size}}}:{done:!1}}setDone(e){this.done=!0,this.size=e}setError(e){this.done=!0,this.error=e}}function de(s){return s instanceof We||s instanceof M||s instanceof O||s instanceof E||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")}class We extends Error{}class he{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 _e=/^blob\+local:\/\/download\/(?<path>.*)#(?<signature>.*)$/;function jn(s,e){return`blob+local://download/${s}#${e.sign(s)}`}function Gn(s){return!!s.match(_e)}function X(s,e){const t=s.match(_e);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 Me=m.rsSchema({kv:{"ctl/file/blobInfo":k.z.object({sizeBytes:k.z.coerce.number()})}});function Ee(s){return s.kv["ctl/file/blobInfo"].sizeBytes}const v=k.z.object({localPath:k.z.string(),pathSignature:k.z.string(),sizeBytes:k.z.string(),modificationTime:k.z.string()}),ue=k.z.object({storageId:k.z.string(),path:k.z.string()}),Vn=k.z.union([v,ue]),Oe=m.rsSchema({data:v,fields:{blob:!1}}),He=m.rsSchema({fields:{incarnation:!1}}),ze=/^blob\+remote:\/\/download\/(?<content>(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*))#(?<signature>.*)$/;function qn(s,e){const t=`${s.type.name}/${s.type.version}/${BigInt(s.id)}`;return`blob+remote://download/${t}#${e.sign(t)}`}function Jn(s){return!!s.match(ze)}function Zn(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}}}function xe(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 Ae=/^log\+live:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function W(s){return Ae.test(s)}const je=/^log\+ready:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function Qn(s){return je.test(s)}function _(s){let e;if(W(s))e=s.match(Ae);else if(Qn(s))e=s.match(je);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}}}class H extends Error{}class Ge{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}})())}}class Xn{constructor(e,t,n,r,o,l){h(this,"idToDownload",new Map);h(this,"cache");h(this,"downloadQueue");h(this,"idToOnDemand",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 he(l.cacheSoftSizeBytes),this.downloadQueue=new p.TaskProcessor(this.logger,l.nConcurrentDownloads),this.saveDir=T.resolve(r)}getDownloadedBlob(e,t){if(t===void 0)return f.Computable.make(l=>this.getDownloadedBlob(e,l));const n=m.treeEntryToResourceInfo(e,t),r=P.randomUUID();t.addOnDestroy(()=>this.releaseBlob(n.id,r));const o=this.getDownloadedBlobNoCtx(t.watcher,n,r);return o==null&&t.markUnstable("download blob is still undefined"),o}getDownloadedBlobNoCtx(e,t,n){S("getDownloadedBlob",t.type);let r=this.idToDownload.get(t.id);if(r===void 0){const l=this.setNewDownloadTask(t);this.downloadQueue.push({fn:()=>this.downloadBlob(l,n),recoverableErrorPredicate:a=>!de(a)}),r=l}r.attach(e,n);const o=r.getBlob();if(o.done){if(o.result.ok)return o.result.value;throw o.result.error}}setNewDownloadTask(e){const t=this.getFilePath(e.id),n=new An(this.logger,this.clientDownload,e,t,jn(t,this.signer));return this.idToDownload.set(e.id,n),n}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,Me,t):e,r=P.randomUUID();return t.addOnDestroy(()=>this.releaseOnDemandBlob(n.id,r)),this.getOnDemandBlobNoCtx(n,r)}getOnDemandBlobNoCtx(e,t){S("getOnDemandBlob",e.type);let n=this.idToOnDemand.get(e.id);return n===void 0&&(n=new Kn(Ee(e),qn(e,this.signer)),this.idToOnDemand.set(e.id,n)),n.attach(t),n.getHandle()}getLocalPath(e){const{path:t}=X(e,this.signer);return t}async getContent(e){if(Gn(e))return await er(this.getLocalPath(e));if(Jn(e)){const t=Zn(e,this.signer),{content:n}=await this.clientDownload.downloadBlob(t);return await oe.buffer(n)}throw new Error("Malformed remote handle")}getComputableContent(e){return f.Computable.make(t=>this.getDownloadedBlob(e,t),{postprocessValue:t=>t?this.getContent(t.handle):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=P.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r.id,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){S("getLastLogs",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=X(o.handle,this.signer);let a=this.idToLastLines.get(t.id);if(a==null){const c=new me(l,n);this.idToLastLines.set(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=P.randomUUID();n.addOnDestroy(()=>this.releaseBlob(r.id,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){S("getProgressLog",t.type);const o=this.getDownloadedBlobNoCtx(e,t,r);if(o==null)return;const{path:l}=X(o.handle,this.signer);let a=this.idToProgressLog.get(t.id);if(a==null){const c=new me(l,1,n);this.idToProgressLog.set(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 S("getLogHandle",e.type),xe(!1,e)}async lastLines(e,t,n,r){const o=await this.clientLogs.lastLines(_(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),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.idToDownload.get(e);if(n!=null)if(this.cache.existsFile(n.path)){const r=this.cache.removeFile(n.path,t);await Promise.all(r.map(async o=>{await w.rm(o.path),this.cache.removeCache(o),this.removeTask(o,`the task ${g.stringifyWithResourceId(o.info())} was removedfrom cache along with ${g.stringifyWithResourceId(r.map(l=>l.info()))}`)}))}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.idToDownload.delete(e.rInfo.id),this.idToLastLines.delete(e.rInfo.id),this.idToProgressLog.delete(e.rInfo.id)}async releaseOnDemandBlob(e,t){var r;(((r=this.idToOnDemand.get(e))==null?void 0:r.release(t))??!1)&&this.idToOnDemand.delete(e)}async releaseAll(){this.downloadQueue.stop(),this.idToDownload.forEach((e,t)=>{this.idToDownload.delete(t),e.change.markChanged()})}getFilePath(e){return T.resolve(this.saveDir,String(BigInt(e)))}}class Kn{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 me{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 Ge(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 Yn(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 Yn(s,e,t){const n=se.createReadStream(s),r=new L.Writable;return new Promise((o,l)=>{const a=wt.createInterface(n,r),d=new lt;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(fe.EOL)+fe.EOL)})})}async function er(s){return await oe.buffer(L.Readable.toWeb(se.createReadStream(s)))}function S(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 H(t)}}const Ve=m.rsSchema({});function qe(s,e){const t=m.isPlTreeEntry(s)?e.accessor(s).node():m.isPlTreeEntryAccessor(s)?s.node():s;return m.makeResourceSnapshot(t,Ve)}function tr(s,e,t){const n=b.relative(e,t);return`plblob+folder://${s.sign(n)}.${n}.blob`}function nr(s){return new URL(s).protocol=="plblob+folder:"}function rr(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=or(b.join(t,`${o}`),n.pathname.slice(1));return(n.pathname==""||n.pathname=="/")&&(a=b.join(a,"index.html")),b.resolve(a)}function or(s,e){const t=b.resolve(s,e),n=b.resolve(s);if(!t.startsWith(n))throw new Error("Path validation failed.");return t}class sr{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())}`),ir(e)){this.setError(e),this.change.markChanged(),await ee(this.path);return}throw e}}async downloadAndDecompress(e){if(this.state={},this.state.parentDir=b.dirname(this.path),await p.ensureDirExists(this.state.parentDir),this.state.fileExisted=await p.fileExists(this.path),this.state.fileExisted)return await Je(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(Y.extract(r));await t.pipeTo(o,{signal:e});return;case"tgz":await w.mkdir(r);const l=L.Transform.toWeb(Pe.createGunzip()),a=L.Writable.toWeb(Y.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 ut(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=tr(this.signer,this.saveDir,this.path)}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new Ze(e))}}async function Je(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 Je(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function ee(s){await w.rm(s,{recursive:!0,force:!0})}let Ze=class extends Error{};function ir(s){return s instanceof Ze||s instanceof M||s instanceof O||s instanceof E||(s==null?void 0:s.code)=="ENOENT"||s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED")||String(s).includes("incorrect header check")}function N(s,e){return`id:${String(BigInt(s))}-${e}`}class ar{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 he(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(nr(e))return rr(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)?qe(e,n):e,o=P.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(N(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=>!de(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(N(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 ee(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 ee(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 sr(this.logger,this.signer,this.saveDir,this.getFilePath(t.id,n),t,n,this.clientDownload);return o.attach(e,r),this.idToDownload.set(N(t.id,n),o),o}removeTask(e,t){e.abort(t),e.change.markChanged(),this.idToDownload.delete(N(e.rInfo.id,e.format))}getFilePath(e,t){return T.join(this.saveDir,`${String(BigInt(e))}_${t}`)}}class Qe{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}=lr(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 cr(this.progress)}shouldScheduleUpload(){return Ke(this.progress)}async uploadBlobTask(){try{await Xe(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),ne(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(),pe(e)){this.setTerminalError(e);return}throw gr(e)&&(this.nMaxUploads=mr(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=pr(this.alreadyExisted,ur(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(ne(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){dr(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 Xe(s,e,t,n,r,o){pt(te(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=fr(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 lr(s,e){let t,n;return te(s)&&(n=v.parse(s.data),t=hr(e,n.localPath,n.pathSignature)),{uploadData:n,progress:{done:!1,status:void 0,isUpload:te(s),isUploadSignMatch:t,lastError:void 0}}}function Ke(s){return s.isUpload&&(s.isUploadSignMatch??!1)}function cr(s){return s.done,s.isUpload,s.isUploadSignMatch,s.lastError,s.status&&(s.status.progress,s.status.bytesProcessed,s.status.bytesTotal),s}function dr(s){return"blob"in s.fields?s.fields.blob!==void 0:s.fields.incarnation!==void 0}function te(s){return s.type.name.startsWith("BlobUpload")}function hr(s,e,t){try{return s.verify(e,t),!0}catch{return!1}}function ur(s){return{progress:s.progress??0,bytesProcessed:Number(s.bytesProcessed),bytesTotal:Number(s.bytesTotal)}}function pr(s,e){return s&&e.bytesTotal!=0&&e.bytesProcessed==0?{progress:1,bytesProcessed:Number(e.bytesTotal),bytesTotal:Number(e.bytesTotal)}:e}function ne(s){return s.name=="RpcError"&&(s.code=="NOT_FOUND"||s.code=="ABORTED"||s.code=="ALREADY_EXISTS")}function pe(s){return s instanceof ie||s instanceof ae||s instanceof ce}function gr(s){return s==null?void 0:s.message.includes("UND_ERR_HEADERS_TIMEOUT")}function fr(s,e,t){const n=Math.min(e+2,t);return n!=e&&s.info(`uploadTask.increaseConcurrency: increased from ${e} to ${n}`),n}function mr(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 Ye(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,Oe):m.makeResourceSnapshot(t,He)}class wr{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)?Ye(e,t):e,r=P.randomUUID();return t.attacheHooks(this.hooks),t.addOnDestroy(()=>this.release(n.id,r)),this.getProgressIdNoCtx(t.watcher,n,r)}getProgressIdNoCtx(e,t,n){Tr("getProgressId",t.type);const r=this.idToProgress.get(t.id);if(r!=null)return r.setDoneIfOutputSet(t),r.getProgress(e,n);const o=new Qe(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=>!pe(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 Le.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllNotDoneProgresses(){return Array.from(this.idToProgress.entries()).filter(([e,t])=>!yr(t.progress)).map(([e,t])=>t)}}function yr(s){var e;return s.done&&(((e=s.status)==null?void 0:e.progress)??0)>=1}function Tr(s,e){if(!e.name.startsWith("BlobUpload")&&!e.name.startsWith("BlobIndex"))throw new H(`${s}: wrong resource type: ${e.name}, expected: a resource of either type 'BlobUpload' or 'BlobIndex'.`)}class br{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=P.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){K("getLastLogs",t.type);let o=this.idToLastLines.get(t.id);if(o==null){const a=new we(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=P.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){K("getProgressLog",t.type);let o=this.idToProgressLog.get(t.id);if(o==null){const a=new we(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 K("getLogHandle",e.type),xe(!0,e)}async lastLines(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.lastLines(_(e),t,BigInt(n??0),r))}async readText(e,t,n,r){return await this.tryWithNotFound(e,()=>this.clientLogs.readText(_(e),t,BigInt(n??0),r))}async tryWithNotFound(e,t){if(!W(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 Le.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 we{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 K(s,e){if(!e.name.startsWith("StreamWorkdir"))throw new H(`${s}: wrong resource type: ${e.name}, expected: a resource of type 'StreamWorkdir'.`)}class kr{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=C(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=C(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=C(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=C(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 W(e)?await this.logsStreamDriver.lastLines(e,t,n,r):await this.downloadDriver.lastLines(e,t,n,r)}async readText(e,t,n,r){return W(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 C(s,e){var t;return(t=s.accessor(e).node().traverse("stream"))==null?void 0:t.resourceInfo}class Lr{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 he(this.opts.cacheSoftSizeBytes),this.downloadHelper=new De(t)}getPath(e,t){if(t===void 0)return f.Computable.make(o=>this.getPath(e,o));const n=P.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 re(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 re(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 Pr(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=P.createHash("sha256").update(e.toString()).digest("hex");return T.join(this.saveDir,t)}}class Pr{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 ye||n instanceof M){this.setError(n),this.change.markChanged(),await re(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 et(this.path);const r=await e.download(this.url.toString(),{},n);let o=r.content;if(t){const l=L.Transform.toWeb(Pe.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(Y.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 ye(e))}}class ye extends Error{}async function et(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 et(r):(await w.stat(r)).size}))).reduce((n,r)=>n+r,0)}async function re(s){await w.rm(s,{recursive:!0,force:!0})}function Te(s,e){return`index://index/${encodeURIComponent(JSON.stringify({storageId:s,path:e}))}`}function Ur(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 Ir(s){const e=new URL(s);return v.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Rr(s){const e=new URL(s);return ue.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Dr(s){if(Br(s))return $r(s);if(Sr(s))return Nr(s);p.assertNever(s)}const tt=/^local:\/\/(?<name>.*)\/(?<path>.*)$/;function Sr(s){return tt.test(s)}function vr(s,e){return`local://${s}/${encodeURIComponent(e)}`}function Nr(s){const e=s.match(tt);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 nt=/^remote:\/\/(?<name>.*)\/(?<resourceId>.*)$/;function Br(s){return nt.test(s)}function Cr(s,e){return`remote://${s}/${BigInt(e)}`}function $r(s){const e=s.match(nt);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:Fr(t),name:t,isRemote:!0}}function Fr(s){return{name:`LS/${s}`,version:"1"}}async function rt(){const s=ke.homedir();if(b.sep=="/")return[{name:"local",root:"/",initialPath:s}];{const t=b.parse(s).root.replaceAll(":\\","");try{return(await ft.promisify(mt.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 ge{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(gt.isImportFileHandleIndex(e)){const t=Rr(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=Ir(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 Ur(e,this.signer,t.size,t.mtimeMs/1000n)}async getStorageList(){const e=[...this.virtualStoragesMap.values()].map(r=>({name:r.name,handle:vr(r.name,r.root),initialFullPath:r.initialPath})),n=Object.entries(this.storageIdToResourceId).map(([r,o])=>({name:r,handle:Cr(r,o),initialFullPath:"",isInitialPathHome:!1})).filter(r=>r.name!=="root");return[...e,...n]}async listFiles(e,t){const n=Dr(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 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=Fe(t,e);l||(l=await rt());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 ge(e,a,await Wr(t),n,d,c,o)}}async function Wr(s){return s.withReadTx("GetAvailableStorageIds",async e=>{const t=await e.getResourceByName("LSProvider"),n=await e.getResourceData(t,!0);return _r(n)})}function _r(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=Se;exports.ClientLogs=$e;exports.ClientLs=Ce;exports.ClientProgress=Re;exports.ClientUpload=Ie;exports.DefaultVirtualLocalStorages=rt;exports.DownloadBlobToURLDriver=ar;exports.DownloadDriver=Xn;exports.DownloadUrlDriver=Lr;exports.DownloadableBlobSnapshot=Ve;exports.ImportFileHandleData=Vn;exports.ImportFileHandleIndexData=ue;exports.ImportFileHandleUploadData=v;exports.IndexResourceSnapshot=He;exports.LogsDriver=kr;exports.LogsStreamDriver=br;exports.LsDriver=ge;exports.MTimeError=ie;exports.NetworkError=le;exports.NoFileForUploading=ce;exports.OnDemandBlobResourceSnapshot=Me;exports.UnexpectedEOF=ae;exports.UnknownStorageError=O;exports.Updater=Ge;exports.UploadDriver=wr;exports.UploadResourceSnapshot=Oe;exports.UploadTask=Qe;exports.WrongLocalFileUrl=E;exports.WrongResourceTypeError=H;exports.createDownloadClient=On;exports.createLogsClient=Hn;exports.createLsFilesClient=Fe;exports.createUploadBlobClient=xn;exports.createUploadProgressClient=zn;exports.getFullPath=Ne;exports.getSize=Ee;exports.isMyUpload=Ke;exports.isResourceWasDeletedError=ne;exports.makeBlobImportSnapshot=Ye;exports.makeDownloadableBlobSnapshot=qe;exports.newLocalStorageIdsToRoot=Be;exports.nonRecoverableError=pe;exports.parseLocalUrl=ve;exports.uploadBlob=Xe;exports.validateAbsolute=I;
3
3
  //# sourceMappingURL=index.js.map