@milaboratories/pl-client 2.16.14 → 2.16.15

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.
@@ -8,10 +8,9 @@ function isConnectionProblem(err, nested = false) {
8
8
  return true;
9
9
  if (err.name == 'RpcError' && err.code == 'UNAVAILABLE')
10
10
  return true;
11
- if (err.code == code.Code.UNAVAILABLE)
11
+ if (err.name == 'RESTError' && err.status.code == code.Code.UNAVAILABLE)
12
12
  return true;
13
13
  if (err.cause !== undefined && !nested)
14
- // nested limits the depth of search
15
14
  return isConnectionProblem(err.cause, true);
16
15
  return false;
17
16
  }
@@ -20,41 +19,73 @@ function isUnauthenticated(err, nested = false) {
20
19
  return true;
21
20
  if (err.name == 'RpcError' && err.code == 'UNAUTHENTICATED')
22
21
  return true;
23
- if (err.code == code.Code.UNAUTHENTICATED)
22
+ if (err.name == 'RESTError' && err.status.code == code.Code.UNAUTHENTICATED)
24
23
  return true;
25
24
  if (err.cause !== undefined && !nested)
26
- // nested limits the depth of search
27
25
  return isUnauthenticated(err.cause, true);
28
26
  return false;
29
27
  }
30
- function isTimeoutOrCancelError(err, nested = false) {
31
- if (err instanceof tsHelpers.Aborted || err.name == 'AbortError')
32
- return true;
28
+ function isTimeoutError(err, nested = false) {
33
29
  if (err.name == 'TimeoutError')
34
30
  return true;
31
+ if (err.name == 'RpcError' && err.code == 'DEADLINE_EXCEEDED')
32
+ return true;
33
+ if (err.name == 'RESTError' && err.status.code == code.Code.DEADLINE_EXCEEDED)
34
+ return true;
35
+ if (err.cause !== undefined && !nested)
36
+ return isTimeoutError(err.cause, true);
37
+ return false;
38
+ }
39
+ function isCancelError(err, nested = false) {
40
+ if (err.name == 'RpcError' && err.code == 'CANCELLED')
41
+ return true;
42
+ if (err.name == 'RESTError' && err.status.code == code.Code.CANCELLED)
43
+ return true;
44
+ if (err.cause !== undefined && !nested)
45
+ return isCancelError(err.cause, true);
46
+ return false;
47
+ }
48
+ function isAbortedError(err, nested = false) {
49
+ if (err instanceof tsHelpers.Aborted || err.name == 'AbortError')
50
+ return true;
35
51
  if (err.code == 'ABORT_ERR')
36
52
  return true;
37
- // Check for DOMException with ABORT_ERR code (thrown by AbortSignal.timeout)
38
53
  if (err instanceof DOMException && err.code === DOMException.ABORT_ERR)
54
+ return true; // WebSocket error
55
+ if (err.name == 'RpcError' && err.code == 'ABORTED')
39
56
  return true;
40
- if (err.code == code.Code.ABORTED)
57
+ if (err.name == 'RESTError' && err.status.code == code.Code.ABORTED)
58
+ return true;
59
+ if (err.cause !== undefined && !nested)
60
+ isAbortedError(err.cause, true);
61
+ return false;
62
+ }
63
+ function isTimeoutOrCancelError(err, nested = false) {
64
+ if (isAbortedError(err, true))
41
65
  return true;
42
- if (err.name == 'RpcError'
43
- && (err.code == 'CANCELLED' || err.code == 'DEADLINE_EXCEEDED'))
66
+ if (isTimeoutError(err, true))
44
67
  return true;
45
- if (err.code == code.Code.CANCELLED || err.code == code.Code.DEADLINE_EXCEEDED)
68
+ if (isCancelError(err, true))
46
69
  return true;
47
70
  if (err.cause !== undefined && !nested)
48
- // nested limits the depth of search
49
71
  return isTimeoutOrCancelError(err.cause, true);
50
72
  return false;
51
73
  }
52
- const PlErrorCodeNotFound = 5;
74
+ function isNotFoundError(err, nested = false) {
75
+ if (err.name == 'RpcError' && err.code == 'NOT_FOUND')
76
+ return true;
77
+ if (err.name == 'RESTError' && err.status.code == code.Code.NOT_FOUND)
78
+ return true;
79
+ if (err.cause !== undefined && !nested)
80
+ return isNotFoundError(err.cause, true);
81
+ return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;
82
+ }
83
+ const PlErrorCodeNotFound = code.Code.NOT_FOUND;
53
84
  class PlError extends Error {
54
85
  status;
55
86
  name = 'PlError';
56
- constructor(status) {
57
- super(`code=${status.code} ${status.message}`);
87
+ constructor(status, opts) {
88
+ super(`code=${status.code} ${status.message}`, opts);
58
89
  this.status = status;
59
90
  }
60
91
  }
@@ -73,13 +104,6 @@ class UnrecoverablePlError extends PlError {
73
104
  super(status);
74
105
  }
75
106
  }
76
- function isNotFoundError(err, nested = false) {
77
- if (err.name == 'RpcError' && err.code == 'NOT_FOUND')
78
- return true;
79
- if (err.cause !== undefined && !nested)
80
- return isNotFoundError(err.cause, true);
81
- return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;
82
- }
83
107
  class UnauthenticatedError extends Error {
84
108
  name = 'UnauthenticatedError';
85
109
  constructor(message) {
@@ -92,6 +116,12 @@ class DisconnectedError extends Error {
92
116
  super('Disconnected: ' + message);
93
117
  }
94
118
  }
119
+ class RESTError extends PlError {
120
+ name = 'RESTError';
121
+ constructor(status, opts) {
122
+ super(status, opts);
123
+ }
124
+ }
95
125
  function rethrowMeaningfulError(error, wrapIfUnknown = false) {
96
126
  if (isUnauthenticated(error)) {
97
127
  if (error instanceof UnauthenticatedError)
@@ -116,11 +146,15 @@ function rethrowMeaningfulError(error, wrapIfUnknown = false) {
116
146
  exports.DisconnectedError = DisconnectedError;
117
147
  exports.PlError = PlError;
118
148
  exports.PlErrorCodeNotFound = PlErrorCodeNotFound;
149
+ exports.RESTError = RESTError;
119
150
  exports.RecoverablePlError = RecoverablePlError;
120
151
  exports.UnauthenticatedError = UnauthenticatedError;
121
152
  exports.UnrecoverablePlError = UnrecoverablePlError;
153
+ exports.isAbortedError = isAbortedError;
154
+ exports.isCancelError = isCancelError;
122
155
  exports.isConnectionProblem = isConnectionProblem;
123
156
  exports.isNotFoundError = isNotFoundError;
157
+ exports.isTimeoutError = isTimeoutError;
124
158
  exports.isTimeoutOrCancelError = isTimeoutOrCancelError;
125
159
  exports.isUnauthenticated = isUnauthenticated;
126
160
  exports.rethrowMeaningfulError = rethrowMeaningfulError;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from '../proto-grpc/github.com/googleapis/googleapis/google/rpc/status';\nimport { Aborted } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAVAILABLE') return true;\n if ((err as any).code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested)\n // nested limits the depth of search\n return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAUTHENTICATED') return true;\n if ((err as any).code == Code.UNAUTHENTICATED) return true;\n if ((err as any).cause !== undefined && !nested)\n // nested limits the depth of search\n return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (err instanceof Aborted || (err as any).name == 'AbortError') return true;\n if ((err as any).name == 'TimeoutError') return true;\n if ((err as any).code == 'ABORT_ERR') return true;\n // Check for DOMException with ABORT_ERR code (thrown by AbortSignal.timeout)\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true;\n if ((err as any).code == Code.ABORTED) return true;\n if (\n (err as any).name == 'RpcError'\n && ((err as any).code == 'CANCELLED' || (err as any).code == 'DEADLINE_EXCEEDED')\n )\n return true;\n if ((err as any).code == Code.CANCELLED || (err as any).code == Code.DEADLINE_EXCEEDED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n // nested limits the depth of search\n return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport const PlErrorCodeNotFound = 5;\n\nexport class PlError extends Error {\n name = 'PlError';\n constructor(public readonly status: Status) {\n super(`code=${status.code} ${status.message}`);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = 'RecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = 'UnrecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'RpcError' && (err as any).code == 'NOT_FOUND') return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport class UnauthenticatedError extends Error {\n name = 'UnauthenticatedError';\n constructor(message: string) {\n super('LoginFailed: ' + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = 'DisconnectedError';\n constructor(message: string) {\n super('Disconnected: ' + message);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || 'Unknown error';\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"names":["Code","Aborted"],"mappings":";;;;;SAIgB,mBAAmB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACvE,IAAI,GAAG,YAAY,iBAAiB;AAAE,QAAA,OAAO,IAAI;IACjD,IAAK,GAAW,CAAC,IAAI,IAAI,UAAU,IAAK,GAAW,CAAC,IAAI,IAAI,aAAa;AAAE,QAAA,OAAO,IAAI;AACtF,IAAA,IAAK,GAAW,CAAC,IAAI,IAAIA,SAAI,CAAC,WAAW;AAAE,QAAA,OAAO,IAAI;AACtD,IAAA,IAAK,GAAW,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM;;QAE7C,OAAO,mBAAmB,CAAE,GAAW,CAAC,KAAK,EAAE,IAAI,CAAC;AACtD,IAAA,OAAO,KAAK;AACd;SAEgB,iBAAiB,CAAC,GAAY,E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mB;AACrF;AAEM,MAAO,oBAAqB,SAAQ,KAAK,CAAA;IAC7C,IAAI,GAAG,sBAAsB;AAC7B,IAAA,WAAA,CAAY,OAAe,EAAA;AACzB,QAAA,KAAK,CAAC,eAAe,GAAG,OAAO,CAAC;IAClC;AACD;AAEK,MAAO,iBAAkB,SAAQ,KAAK,CAAA;IAC1C,IAAI,GAAG,mBAAmB;AAC1B,IAAA,WAAA,CAAY,OAAe,EAAA;AACzB,QAAA,KAAK,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACnC;AACD;SAEe,sBAAsB,CAAC,KAAU,EAAE,gBAAyB,KAAK,EAAA;AAC/E,IAAA,IAAI,iBAAiB,CAAC,KAAK,CAAC,EAAE;QAC5B,IAAI,KAAK,YAAY,oBAAoB;AAAE,YAAA,MAAM,KAAK;AACtD,QAAA,MAAM,IAAI,oBAAoB,CAAC,KAAK,CAAC,OAAO,CAAC;IAC/C;AACA,IAAA,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;QAC9B,IAAI,KAAK,YAAY,iBAAiB;AAAE,YAAA,MAAM,KAAK;AACnD,QAAA,MAAM,IAAI,iBAAiB,CAAC,KAAK,CAAC,OAAO,CAAC;IAC5C;IACA,IAAI,sBAAsB,CAAC,KAAK,CAAC;AAAE,QAAA,MAAM,IAAIC,iBAAO,CAAC,KAAK,CAAC;IAC3D,IAAI,aAAa,EAAE;AACjB,QAAA,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,eAAe;QACjE,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC5C;;AAAO,QAAA,MAAM,KAAK;AACpB;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"errors.cjs","sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from '../proto-grpc/github.com/googleapis/googleapis/google/rpc/status';\nimport { Aborted } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAVAILABLE') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested) return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAUTHENTICATED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.UNAUTHENTICATED) return true;\n if ((err as any).cause !== undefined && !nested) return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'TimeoutError') return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'DEADLINE_EXCEEDED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.DEADLINE_EXCEEDED) return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);\n return false;\n}\n\nexport function isCancelError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'RpcError' && (err as any).code == 'CANCELLED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.CANCELLED) return true;\n if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isAbortedError(err: unknown, nested: boolean = false): boolean {\n if (err instanceof Aborted || (err as any).name == 'AbortError') return true;\n if ((err as any).code == 'ABORT_ERR') return true;\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error\n if ((err as any).name == 'RpcError' && (err as any).code == 'ABORTED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.ABORTED) return true;\n if ((err as any).cause !== undefined && !nested) isAbortedError((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (isAbortedError(err, true)) return true;\n if (isTimeoutError(err, true)) return true;\n if (isCancelError(err, true)) return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'RpcError' && (err as any).code == 'NOT_FOUND') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.NOT_FOUND) return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport const PlErrorCodeNotFound: number = Code.NOT_FOUND;\n\nexport class PlError extends Error {\n name = 'PlError';\n constructor(public readonly status: Status, opts?: ErrorOptions) {\n super(`code=${status.code} ${status.message}`, opts);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = 'RecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = 'UnrecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnauthenticatedError extends Error {\n name = 'UnauthenticatedError';\n constructor(message: string) {\n super('LoginFailed: ' + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = 'DisconnectedError';\n constructor(message: string) {\n super('Disconnected: ' + message);\n }\n}\n\nexport class RESTError extends PlError {\n name = 'RESTError';\n constructor(status: Status, opts?: ErrorOptions) {\n super(status, opts);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || 'Unknown error';\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"names":["Code","Aborted"],"mappings":";;;;;SAIgB,mBAAmB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACvE,IAAI,GAAG,YAAY,iBAAiB;AAAE,QAAA,OAAO,IAAI;IACjD,IAAK,GAAW,CAAC,IAAI,IAAI,UAAU,IAAK,GAAW,CAAC,IAAI,IAAI,aAAa;AAAE,QAAA,OAAO,IAAI;AACtF,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,WAAW,IAAK,GAAW,CAAC,MAAM,CAAC,IAAI,IAAIA,SAAI,CAAC,WAAW;AAAE,QAAA,OAAO,IAAI;AACjG,IAAA,IAAK,GAAW,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM;QAAE,OAAO,mBAAmB,CAAE,GAAW,CAAC,KAAK,EAAE,IAAI,CAAC;AACrG,IAAA,OAAO,KAAK;AACd;SAEgB,iBAAiB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACrE,IAAI,GAAG,YAAY,oBAAoB;AAAE,QAAA,OAAO,IAAI;IACpD,IAAK,GAAW,CAAC,IAAI,IAAI,UAAU,IAAK,GAAW,CAAC,IAAI,IAAI,iBAAiB;AAAE,QAAA,OAAO,IAAI;AAC1F,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,WAAW,IAAK,GAAW,CAAC,MAAM,CAAC,IAAI,IAAIA,SAAI,CAAC,eAAe;AAAE,QAAA,OAAO,IAAI;AACrG,IAAA,IAAK,GAAW,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM;QAAE,OAAO,iBAAiB,CAAE,GAAW,CAAC,KAAK,EAAE,IAAI,CAAC;AACnG,IAAA,OAAO,KAAK;AACd;SAEgB,cAAc,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;AAClE,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,cAAc;AAAE,QAAA,OA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AClB,WAAA,CAAY,MAAc,EAAE,IAAmB,EAAA;AAC7C,QAAA,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC;IACrB;AACD;SAEe,sBAAsB,CAAC,KAAU,EAAE,gBAAyB,KAAK,EAAA;AAC/E,IAAA,IAAI,iBAAiB,CAAC,KAAK,CAAC,EAAE;QAC5B,IAAI,KAAK,YAAY,oBAAoB;AAAE,YAAA,MAAM,KAAK;AACtD,QAAA,MAAM,IAAI,oBAAoB,CAAC,KAAK,CAAC,OAAO,CAAC;IAC/C;AACA,IAAA,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;QAC9B,IAAI,KAAK,YAAY,iBAAiB;AAAE,YAAA,MAAM,KAAK;AACnD,QAAA,MAAM,IAAI,iBAAiB,CAAC,KAAK,CAAC,OAAO,CAAC;IAC5C;IACA,IAAI,sBAAsB,CAAC,KAAK,CAAC;AAAE,QAAA,MAAM,IAAIC,iBAAO,CAAC,KAAK,CAAC;IAC3D,IAAI,aAAa,EAAE;AACjB,QAAA,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,eAAe;QACjE,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC5C;;AAAO,QAAA,MAAM,KAAK;AACpB;;;;;;;;;;;;;;;;;;;"}
@@ -1,12 +1,16 @@
1
1
  import type { Status } from '../proto-grpc/github.com/googleapis/googleapis/google/rpc/status';
2
2
  export declare function isConnectionProblem(err: unknown, nested?: boolean): boolean;
3
3
  export declare function isUnauthenticated(err: unknown, nested?: boolean): boolean;
4
+ export declare function isTimeoutError(err: unknown, nested?: boolean): boolean;
5
+ export declare function isCancelError(err: unknown, nested?: boolean): boolean;
6
+ export declare function isAbortedError(err: unknown, nested?: boolean): boolean;
4
7
  export declare function isTimeoutOrCancelError(err: unknown, nested?: boolean): boolean;
5
- export declare const PlErrorCodeNotFound = 5;
8
+ export declare function isNotFoundError(err: unknown, nested?: boolean): boolean;
9
+ export declare const PlErrorCodeNotFound: number;
6
10
  export declare class PlError extends Error {
7
11
  readonly status: Status;
8
12
  name: string;
9
- constructor(status: Status);
13
+ constructor(status: Status, opts?: ErrorOptions);
10
14
  }
11
15
  export declare function throwPlNotFoundError(message: string): never;
12
16
  export declare class RecoverablePlError extends PlError {
@@ -17,7 +21,6 @@ export declare class UnrecoverablePlError extends PlError {
17
21
  name: string;
18
22
  constructor(status: Status);
19
23
  }
20
- export declare function isNotFoundError(err: unknown, nested?: boolean): boolean;
21
24
  export declare class UnauthenticatedError extends Error {
22
25
  name: string;
23
26
  constructor(message: string);
@@ -26,5 +29,9 @@ export declare class DisconnectedError extends Error {
26
29
  name: string;
27
30
  constructor(message: string);
28
31
  }
32
+ export declare class RESTError extends PlError {
33
+ name: string;
34
+ constructor(status: Status, opts?: ErrorOptions);
35
+ }
29
36
  export declare function rethrowMeaningfulError(error: any, wrapIfUnknown?: boolean): never;
30
37
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kEAAkE,CAAC;AAI/F,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAQlF;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAQhF;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAkBrF;AAED,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC,qBAAa,OAAQ,SAAQ,KAAK;aAEJ,MAAM,EAAE,MAAM;IAD1C,IAAI,SAAa;gBACW,MAAM,EAAE,MAAM;CAG3C;AAED,wBAAgB,oBAAoB,CAAC,OAAO,E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AAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAK9E;AAED,eAAO,MAAM,mBAAmB,EAAE,MAAuB,CAAC;AAE1D,qBAAa,OAAQ,SAAQ,KAAK;aAEJ,MAAM,EAAE,MAAM;IAD1C,IAAI,SAAa;gBACW,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAGhE;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,CAE3D;AAED,qBAAa,kBAAmB,SAAQ,OAAO;IAC7C,IAAI,SAAwB;gBAChB,MAAM,EAAE,MAAM;CAG3B;AAED,qBAAa,oBAAqB,SAAQ,OAAO;IAC/C,IAAI,SAA0B;gBAClB,MAAM,EAAE,MAAM;CAG3B;AAED,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,IAAI,SAA0B;gBAClB,OAAO,EAAE,MAAM;CAG5B;AAED,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,IAAI,SAAuB;gBACf,OAAO,EAAE,MAAM;CAG5B;AAED,qBAAa,SAAU,SAAQ,OAAO;IACpC,IAAI,SAAe;gBACP,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAGhD;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,GAAG,EAAE,aAAa,GAAE,OAAe,GAAG,KAAK,CAcxF"}
@@ -6,10 +6,9 @@ function isConnectionProblem(err, nested = false) {
6
6
  return true;
7
7
  if (err.name == 'RpcError' && err.code == 'UNAVAILABLE')
8
8
  return true;
9
- if (err.code == Code.UNAVAILABLE)
9
+ if (err.name == 'RESTError' && err.status.code == Code.UNAVAILABLE)
10
10
  return true;
11
11
  if (err.cause !== undefined && !nested)
12
- // nested limits the depth of search
13
12
  return isConnectionProblem(err.cause, true);
14
13
  return false;
15
14
  }
@@ -18,41 +17,73 @@ function isUnauthenticated(err, nested = false) {
18
17
  return true;
19
18
  if (err.name == 'RpcError' && err.code == 'UNAUTHENTICATED')
20
19
  return true;
21
- if (err.code == Code.UNAUTHENTICATED)
20
+ if (err.name == 'RESTError' && err.status.code == Code.UNAUTHENTICATED)
22
21
  return true;
23
22
  if (err.cause !== undefined && !nested)
24
- // nested limits the depth of search
25
23
  return isUnauthenticated(err.cause, true);
26
24
  return false;
27
25
  }
28
- function isTimeoutOrCancelError(err, nested = false) {
29
- if (err instanceof Aborted || err.name == 'AbortError')
30
- return true;
26
+ function isTimeoutError(err, nested = false) {
31
27
  if (err.name == 'TimeoutError')
32
28
  return true;
29
+ if (err.name == 'RpcError' && err.code == 'DEADLINE_EXCEEDED')
30
+ return true;
31
+ if (err.name == 'RESTError' && err.status.code == Code.DEADLINE_EXCEEDED)
32
+ return true;
33
+ if (err.cause !== undefined && !nested)
34
+ return isTimeoutError(err.cause, true);
35
+ return false;
36
+ }
37
+ function isCancelError(err, nested = false) {
38
+ if (err.name == 'RpcError' && err.code == 'CANCELLED')
39
+ return true;
40
+ if (err.name == 'RESTError' && err.status.code == Code.CANCELLED)
41
+ return true;
42
+ if (err.cause !== undefined && !nested)
43
+ return isCancelError(err.cause, true);
44
+ return false;
45
+ }
46
+ function isAbortedError(err, nested = false) {
47
+ if (err instanceof Aborted || err.name == 'AbortError')
48
+ return true;
33
49
  if (err.code == 'ABORT_ERR')
34
50
  return true;
35
- // Check for DOMException with ABORT_ERR code (thrown by AbortSignal.timeout)
36
51
  if (err instanceof DOMException && err.code === DOMException.ABORT_ERR)
52
+ return true; // WebSocket error
53
+ if (err.name == 'RpcError' && err.code == 'ABORTED')
37
54
  return true;
38
- if (err.code == Code.ABORTED)
55
+ if (err.name == 'RESTError' && err.status.code == Code.ABORTED)
56
+ return true;
57
+ if (err.cause !== undefined && !nested)
58
+ isAbortedError(err.cause, true);
59
+ return false;
60
+ }
61
+ function isTimeoutOrCancelError(err, nested = false) {
62
+ if (isAbortedError(err, true))
39
63
  return true;
40
- if (err.name == 'RpcError'
41
- && (err.code == 'CANCELLED' || err.code == 'DEADLINE_EXCEEDED'))
64
+ if (isTimeoutError(err, true))
42
65
  return true;
43
- if (err.code == Code.CANCELLED || err.code == Code.DEADLINE_EXCEEDED)
66
+ if (isCancelError(err, true))
44
67
  return true;
45
68
  if (err.cause !== undefined && !nested)
46
- // nested limits the depth of search
47
69
  return isTimeoutOrCancelError(err.cause, true);
48
70
  return false;
49
71
  }
50
- const PlErrorCodeNotFound = 5;
72
+ function isNotFoundError(err, nested = false) {
73
+ if (err.name == 'RpcError' && err.code == 'NOT_FOUND')
74
+ return true;
75
+ if (err.name == 'RESTError' && err.status.code == Code.NOT_FOUND)
76
+ return true;
77
+ if (err.cause !== undefined && !nested)
78
+ return isNotFoundError(err.cause, true);
79
+ return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;
80
+ }
81
+ const PlErrorCodeNotFound = Code.NOT_FOUND;
51
82
  class PlError extends Error {
52
83
  status;
53
84
  name = 'PlError';
54
- constructor(status) {
55
- super(`code=${status.code} ${status.message}`);
85
+ constructor(status, opts) {
86
+ super(`code=${status.code} ${status.message}`, opts);
56
87
  this.status = status;
57
88
  }
58
89
  }
@@ -71,13 +102,6 @@ class UnrecoverablePlError extends PlError {
71
102
  super(status);
72
103
  }
73
104
  }
74
- function isNotFoundError(err, nested = false) {
75
- if (err.name == 'RpcError' && err.code == 'NOT_FOUND')
76
- return true;
77
- if (err.cause !== undefined && !nested)
78
- return isNotFoundError(err.cause, true);
79
- return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;
80
- }
81
105
  class UnauthenticatedError extends Error {
82
106
  name = 'UnauthenticatedError';
83
107
  constructor(message) {
@@ -90,6 +114,12 @@ class DisconnectedError extends Error {
90
114
  super('Disconnected: ' + message);
91
115
  }
92
116
  }
117
+ class RESTError extends PlError {
118
+ name = 'RESTError';
119
+ constructor(status, opts) {
120
+ super(status, opts);
121
+ }
122
+ }
93
123
  function rethrowMeaningfulError(error, wrapIfUnknown = false) {
94
124
  if (isUnauthenticated(error)) {
95
125
  if (error instanceof UnauthenticatedError)
@@ -111,5 +141,5 @@ function rethrowMeaningfulError(error, wrapIfUnknown = false) {
111
141
  throw error;
112
142
  }
113
143
 
114
- export { DisconnectedError, PlError, PlErrorCodeNotFound, RecoverablePlError, UnauthenticatedError, UnrecoverablePlError, isConnectionProblem, isNotFoundError, isTimeoutOrCancelError, isUnauthenticated, rethrowMeaningfulError, throwPlNotFoundError };
144
+ export { DisconnectedError, PlError, PlErrorCodeNotFound, RESTError, RecoverablePlError, UnauthenticatedError, UnrecoverablePlError, isAbortedError, isCancelError, isConnectionProblem, isNotFoundError, isTimeoutError, isTimeoutOrCancelError, isUnauthenticated, rethrowMeaningfulError, throwPlNotFoundError };
115
145
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from '../proto-grpc/github.com/googleapis/googleapis/google/rpc/status';\nimport { Aborted } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAVAILABLE') return true;\n if ((err as any).code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested)\n // nested limits the depth of search\n return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAUTHENTICATED') return true;\n if ((err as any).code == Code.UNAUTHENTICATED) return true;\n if ((err as any).cause !== undefined && !nested)\n // nested limits the depth of search\n return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (err instanceof Aborted || (err as any).name == 'AbortError') return true;\n if ((err as any).name == 'TimeoutError') return true;\n if ((err as any).code == 'ABORT_ERR') return true;\n // Check for DOMException with ABORT_ERR code (thrown by AbortSignal.timeout)\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true;\n if ((err as any).code == Code.ABORTED) return true;\n if (\n (err as any).name == 'RpcError'\n && ((err as any).code == 'CANCELLED' || (err as any).code == 'DEADLINE_EXCEEDED')\n )\n return true;\n if ((err as any).code == Code.CANCELLED || (err as any).code == Code.DEADLINE_EXCEEDED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n // nested limits the depth of search\n return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport const PlErrorCodeNotFound = 5;\n\nexport class PlError extends Error {\n name = 'PlError';\n constructor(public readonly status: Status) {\n super(`code=${status.code} ${status.message}`);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = 'RecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = 'UnrecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'RpcError' && (err as any).code == 'NOT_FOUND') return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport class UnauthenticatedError extends Error {\n name = 'UnauthenticatedError';\n constructor(message: string) {\n super('LoginFailed: ' + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = 'DisconnectedError';\n constructor(message: string) {\n super('Disconnected: ' + message);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || 'Unknown error';\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"names":[],"mappings":";;;SAIgB,mBAAmB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACvE,IAAI,GAAG,YAAY,iBAAiB;AAAE,QAAA,OAAO,IAAI;IACjD,IAAK,GAAW,CAAC,IAAI,IAAI,UAAU,IAAK,GAAW,CAAC,IAAI,IAAI,aAAa;AAAE,QAAA,OAAO,IAAI;AACtF,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,IAAI,CAAC,WAAW;AAAE,QAAA,OAAO,IAAI;AACtD,IAAA,IAAK,GAAW,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM;;QAE7C,OAAO,mBAAmB,CAAE,GAAW,CAAC,KAAK,EAAE,IAAI,CAAC;AACtD,IAAA,OAAO,KAAK;AACd;SAEgB,iBAAiB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACrE,IAAI,GAAG,YAAY,oBAAoB;AAAE,QAAA,OAAO,IAAI;IACpD,IAAK,GAAW,CAAC,IAAI,IAAI,UAAU,IAAK,GAAW,CAAC,IAAI,IAAI,iBAAiB;AAAE,QAAA,OAAO,IAAI;AAC1F,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,IAAI,CAAC,eAAe;AAAE,QAAA,OAAO,IAAI;AAC1D,IAAA,IAAK,GAAW,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM;;QAE7C,OAAO,iBAAiB,CAAE,GAAW,CAAC,KAAK,EAAE,IAAI,CAAC;AACpD,IAAA,OAAO,KAAK;AACd;SAEgB,sBAAsB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IAC1E,IAAI,GAAG,YAAY,OAAO,IAAK,GAAW,CAAC,IAAI,IAAI,YAAY;AAAE,QAAA,OAAO,IAAI;AAC5E,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,cAAc;AAAE,QAA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AAY,iBAAiB;AAAE,YAAA,MAAM,KAAK;AACnD,QAAA,MAAM,IAAI,iBAAiB,CAAC,KAAK,CAAC,OAAO,CAAC;IAC5C;IACA,IAAI,sBAAsB,CAAC,KAAK,CAAC;AAAE,QAAA,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC;IAC3D,IAAI,aAAa,EAAE;AACjB,QAAA,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,eAAe;QACjE,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC5C;;AAAO,QAAA,MAAM,KAAK;AACpB;;;;"}
1
+ {"version":3,"file":"errors.js","sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from '../proto-grpc/github.com/googleapis/googleapis/google/rpc/status';\nimport { Aborted } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAVAILABLE') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested) return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'UNAUTHENTICATED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.UNAUTHENTICATED) return true;\n if ((err as any).cause !== undefined && !nested) return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'TimeoutError') return true;\n if ((err as any).name == 'RpcError' && (err as any).code == 'DEADLINE_EXCEEDED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.DEADLINE_EXCEEDED) return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);\n return false;\n}\n\nexport function isCancelError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'RpcError' && (err as any).code == 'CANCELLED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.CANCELLED) return true;\n if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isAbortedError(err: unknown, nested: boolean = false): boolean {\n if (err instanceof Aborted || (err as any).name == 'AbortError') return true;\n if ((err as any).code == 'ABORT_ERR') return true;\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error\n if ((err as any).name == 'RpcError' && (err as any).code == 'ABORTED') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.ABORTED) return true;\n if ((err as any).cause !== undefined && !nested) isAbortedError((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (isAbortedError(err, true)) return true;\n if (isTimeoutError(err, true)) return true;\n if (isCancelError(err, true)) return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if ((err as any).name == 'RpcError' && (err as any).code == 'NOT_FOUND') return true;\n if ((err as any).name == 'RESTError' && (err as any).status.code == Code.NOT_FOUND) return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport const PlErrorCodeNotFound: number = Code.NOT_FOUND;\n\nexport class PlError extends Error {\n name = 'PlError';\n constructor(public readonly status: Status, opts?: ErrorOptions) {\n super(`code=${status.code} ${status.message}`, opts);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = 'RecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = 'UnrecoverablePlError';\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnauthenticatedError extends Error {\n name = 'UnauthenticatedError';\n constructor(message: string) {\n super('LoginFailed: ' + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = 'DisconnectedError';\n constructor(message: string) {\n super('Disconnected: ' + message);\n }\n}\n\nexport class RESTError extends PlError {\n name = 'RESTError';\n constructor(status: Status, opts?: ErrorOptions) {\n super(status, opts);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || 'Unknown error';\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"names":[],"mappings":";;;SAIgB,mBAAmB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACvE,IAAI,GAAG,YAAY,iBAAiB;AAAE,QAAA,OAAO,IAAI;IACjD,IAAK,GAAW,CAAC,IAAI,IAAI,UAAU,IAAK,GAAW,CAAC,IAAI,IAAI,aAAa;AAAE,QAAA,OAAO,IAAI;AACtF,IAAA,IAAK,GAAW,CAAC,IAAI,IAAI,WAAW,IAAK,GAAW,CAAC,MAAM,CAAC,IAAI,IAAI,IAAI,CAAC,WAAW;AAAE,QAAA,OAAO,IAAI;AACjG,IAAA,IAAK,GAAW,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM;QAAE,OAAO,mBAAmB,CAAE,GAAW,CAAC,KAAK,EAAE,IAAI,CAAC;AACrG,IAAA,OAAO,KAAK;AACd;SAEgB,iBAAiB,CAAC,GAAY,EAAE,SAAkB,KAAK,EAAA;IACrE,I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,CAAC,KAAK,CAAC,IAAI,eAAe;QACjE,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC5C;;AAAO,QAAA,MAAM,KAAK;AACpB;;;;"}
@@ -373,7 +373,7 @@ class LLPlClient {
373
373
  body: { expiration: `${ttlSeconds}s` },
374
374
  headers,
375
375
  });
376
- return tsHelpers.notEmpty((await resp).data).token;
376
+ return tsHelpers.notEmpty((await resp).data, 'REST: empty response for JWT token request').token;
377
377
  }
378
378
  }
379
379
  async ping() {
@@ -382,7 +382,7 @@ class LLPlClient {
382
382
  return (await cl.ping({})).response;
383
383
  }
384
384
  else {
385
- return tsHelpers.notEmpty((await cl.GET('/v1/ping')).data);
385
+ return tsHelpers.notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');
386
386
  }
387
387
  }
388
388
  /**
@@ -414,7 +414,7 @@ class LLPlClient {
414
414
  return (await cl.license({})).response;
415
415
  }
416
416
  else {
417
- const resp = tsHelpers.notEmpty((await cl.GET('/v1/license')).data);
417
+ const resp = tsHelpers.notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');
418
418
  return {
419
419
  status: resp.status,
420
420
  isOk: resp.isOk,
@@ -428,7 +428,7 @@ class LLPlClient {
428
428
  return (await cl.authMethods({})).response;
429
429
  }
430
430
  else {
431
- return tsHelpers.notEmpty((await cl.GET('/v1/auth/methods')).data);
431
+ return tsHelpers.notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');
432
432
  }
433
433
  }
434
434
  async txSync(txId) {
@@ -1 +1 @@
1
- {"version":3,"file":"ll_client.cjs","sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client';\nimport type { ClientOptions, Interceptor } from '@grpc/grpc-js';\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from '@grpc/grpc-js';\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from './config';\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from './config';\nimport type { GrpcOptions } from '@protobuf-ts/grpc-transport';\nimport { GrpcTransport } from '@protobuf-ts/grpc-transport';\nimport { LLPlTransaction } from './ll_transaction';\nimport { parsePlJwt } from '../util/pl';\nimport { type Dispatcher, interceptors } from 'undici';\nimport type { Middleware } from 'openapi-fetch';\nimport { inferAuthRefreshTime } from './auth';\nimport { defaultHttpDispatcher } from '@milaboratories/pl-http';\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from './wire';\nimport { parseHttpAuth } from '@milaboratories/pl-model-common';\nimport type * as grpcTypes from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { type PlApiPaths, type PlRestClientType, createClient, parseResponseError } from '../proto-rest';\nimport { notEmpty, retry, withTimeout, type RetryOptions } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\nimport { WebSocketBiDiStream } from './websocket_stream';\nimport { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(private readonly wireOpts: () => WireConnection, private readonly clientConstructor: (wireOpts: WireConnection) => Client) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined)\n this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n private _status: PlConnectionStatus = 'OK';\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = 'grpc';\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const conf = typeof configOrAddress === 'string' ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n await pl.detectOptimalWireProtocol();\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === 'grpc') {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case 'rest':\n this.initRestConnection();\n return;\n case 'grpc':\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(`Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({ type: 'rest', Config: this.conf, Dispatcher: dispatcher, Middlewares: this._restMiddlewares });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n 'grpc.keepalive_time_ms': 30_000, // 30 seconds\n 'grpc.service_config_disable_resolution': 1, // Disable DNS TXT lookups for service config\n 'interceptors': this._grpcInterceptors,\n };\n\n if (gzip) clientOptions['grpc.default_compression_algorithm'] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy = typeof this.conf.grpcProxy === 'string'\n ? { url: this.conf.grpcProxy }\n : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== 'Basic') {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: 'grpc', Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === 'grpc') oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(clientConstructor: (transport: WireConnection) => Client): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error('Client is not authenticated');\n if (this.authInformation?.jwtToken)\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined\n || Date.now() < this.refreshTimestamp\n || this.authRefreshInProgress\n || this._status === 'Unauthenticated'\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body: body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus('Disconnected');\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n this.updateStatus('Unauthenticated');\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n this.updateStatus('Unauthenticated');\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus('Disconnected');\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = { ...options.headers, authorization: 'Bearer ' + this.authInformation.jwtToken };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set('authorization', 'Bearer ' + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(ttlSeconds: bigint, options?: { authorization?: string }): Promise<string> {\n const cl = this.clientProvider.get();\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST('/v1/auth/jwt-token', {\n body: { expiration: `${ttlSeconds}s` },\n headers,\n });\n return notEmpty((await resp).data).token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.ping({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/ping')).data);\n }\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n const retryOptions: RetryOptions = {\n type: 'exponentialBackoff',\n maxAttempts: 80,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n await retry(() => withTimeout(this.ping(), 500), retryOptions, () => {\n const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';\n this.initWireConnection(protocol);\n return true;\n });\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty((await cl.GET('/v1/license')).data);\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.authMethods({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/auth/methods')).data);\n }\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n (await cl.POST('/v1/tx-sync', { body: { txId: txId.toString() } }));\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === 'rest') {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) => stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: 'streamClose', streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === 'grpc') {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"names":["plAddressToConfig","auth","inferAuthRefreshTime","interceptors","defaultHttpDispatcher","GrpcPlApiClient","createClient","SUPPORTED_WIRE_PROTOCOLS","compressionAlgorithms","ChannelCredentials","parseHttpAuth","GrpcTransport","parsePlJwt","parseResponseError","Code","InterceptingCall","GrpcStatus","notEmpty","retry","withTimeout","LLPlTransaction","WebSocketBiDiStream","TxAPI_ClientMessage","TxAPI_ServerMessage"],"mappings":";;;;;;;;;;;;;;;;;;AAsCA,MAAM,sBAAsB,CAAA;AAGG,IAAA,QAAA;AAAiD,IAAA,iBAAA;IAFtE,MAAM,GAAuB,SAAS;IAE9C,WAAA,CAA6B,QAA8B,EAAmB,iBAAuD,EAAA;QAAxG,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAAyC,IAAA,CAAA,iBAAiB,GAAjB,iBAAiB;IAAyC;IAEjI,KAAK,GAAA;AACV,QAAA,IAAI,CAAC,MAAM,GAAG,SAAS;IACzB;IAEO,GAAG,GAAA;AACR,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;AAC3B,YAAA,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACvD,OAAO,IAAI,CAAC,MAAM;IACpB;AACD;AAED;MACa,UAAU,CAAA;AA2CH,IAAA,IAAA;AACC,IAAA,GAAA;;AA1CX,IAAA,eAAe;;AAEN,IAAA,YAAY;;AAEZ,IAAA,WAAW;;AAEX,IAAA,oBAAoB;;AAE7B,IAAA,gBAAgB;IAEhB,OAAO,GAAuB,IAAI;AACzB,IAAA,cAAc;IAEvB,UAAU,GAAiB,MAAM;AACjC,IAAA,SAAS;AAEA,IAAA,iBAAiB;AACjB,IAAA,gBAAgB;AAChB,IAAA,iBAAiB;IACjB,SAAS,GAA2C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,YAAA,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,EAAE;QACvC;AAGA,QAAA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;IACrC;AACD;;;;"}
1
+ {"version":3,"file":"ll_client.cjs","sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client';\nimport type { ClientOptions, Interceptor } from '@grpc/grpc-js';\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from '@grpc/grpc-js';\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from './config';\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from './config';\nimport type { GrpcOptions } from '@protobuf-ts/grpc-transport';\nimport { GrpcTransport } from '@protobuf-ts/grpc-transport';\nimport { LLPlTransaction } from './ll_transaction';\nimport { parsePlJwt } from '../util/pl';\nimport { type Dispatcher, interceptors } from 'undici';\nimport type { Middleware } from 'openapi-fetch';\nimport { inferAuthRefreshTime } from './auth';\nimport { defaultHttpDispatcher } from '@milaboratories/pl-http';\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from './wire';\nimport { parseHttpAuth } from '@milaboratories/pl-model-common';\nimport type * as grpcTypes from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { type PlApiPaths, type PlRestClientType, createClient, parseResponseError } from '../proto-rest';\nimport { notEmpty, retry, withTimeout, type RetryOptions } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\nimport { WebSocketBiDiStream } from './websocket_stream';\nimport { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(private readonly wireOpts: () => WireConnection, private readonly clientConstructor: (wireOpts: WireConnection) => Client) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined)\n this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n private _status: PlConnectionStatus = 'OK';\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = 'grpc';\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const conf = typeof configOrAddress === 'string' ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n await pl.detectOptimalWireProtocol();\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === 'grpc') {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case 'rest':\n this.initRestConnection();\n return;\n case 'grpc':\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(`Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({ type: 'rest', Config: this.conf, Dispatcher: dispatcher, Middlewares: this._restMiddlewares });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n 'grpc.keepalive_time_ms': 30_000, // 30 seconds\n 'grpc.service_config_disable_resolution': 1, // Disable DNS TXT lookups for service config\n 'interceptors': this._grpcInterceptors,\n };\n\n if (gzip) clientOptions['grpc.default_compression_algorithm'] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy = typeof this.conf.grpcProxy === 'string'\n ? { url: this.conf.grpcProxy }\n : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== 'Basic') {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: 'grpc', Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === 'grpc') oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(clientConstructor: (transport: WireConnection) => Client): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error('Client is not authenticated');\n if (this.authInformation?.jwtToken)\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined\n || Date.now() < this.refreshTimestamp\n || this.authRefreshInProgress\n || this._status === 'Unauthenticated'\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body: body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus('Disconnected');\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n this.updateStatus('Unauthenticated');\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n this.updateStatus('Unauthenticated');\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus('Disconnected');\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = { ...options.headers, authorization: 'Bearer ' + this.authInformation.jwtToken };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set('authorization', 'Bearer ' + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(ttlSeconds: bigint, options?: { authorization?: string }): Promise<string> {\n const cl = this.clientProvider.get();\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST('/v1/auth/jwt-token', {\n body: { expiration: `${ttlSeconds}s` },\n headers,\n });\n return notEmpty((await resp).data, 'REST: empty response for JWT token request').token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.ping({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');\n }\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n const retryOptions: RetryOptions = {\n type: 'exponentialBackoff',\n maxAttempts: 80,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n await retry(\n () => withTimeout(this.ping(), 500),\n retryOptions,\n () => {\n const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';\n this.initWireConnection(protocol);\n return true;\n });\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.authMethods({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');\n }\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n (await cl.POST('/v1/tx-sync', { body: { txId: txId.toString() } }));\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === 'rest') {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) => stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: 'streamClose', streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === 'grpc') {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"names":["plAddressToConfig","auth","inferAuthRefreshTime","interceptors","defaultHttpDispatcher","GrpcPlApiClient","createClient","SUPPORTED_WIRE_PROTOCOLS","compressionAlgorithms","ChannelCredentials","parseHttpAuth","GrpcTransport","parsePlJwt","parseResponseError","Code","InterceptingCall","GrpcStatus","notEmpty","retry","withTimeout","LLPlTransaction","WebSocketBiDiStream","TxAPI_ClientMessage","TxAPI_ServerMessage"],"mappings":";;;;;;;;;;;;;;;;;;AAsCA,MAAM,sBAAsB,CAAA;AAGG,IAAA,QAAA;AAAiD,IAAA,iBAAA;IAFtE,MAAM,GAAuB,SAAS;IAE9C,WAAA,CAA6B,QAA8B,EAAmB,iBAAuD,EAAA;QAAxG,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAAyC,IAAA,CAAA,iBAAiB,GAAjB,iBAAiB;IAAyC;IAEjI,KAAK,GAAA;AACV,QAAA,IAAI,CAAC,MAAM,GAAG,SAAS;IACzB;IAEO,GAAG,GAAA;AACR,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;AAC3B,YAAA,IAAI,CAAC,M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IAoBlC,OAAO,CAAC,yBAAyB;IAcjC,mDAAmD;IACnD,OAAO,CAAC,yBAAyB;IAgBpB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAkBtF,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,4BAA4B,CAAC;IASpE;;;;OAIG;YACW,yBAAyB;IAwB1B,OAAO,IAAI,OAAO,CAAC,SAAS,CAAC,+BAA+B,CAAC;IAc7D,WAAW,IAAI,OAAO,CAAC,SAAS,CAAC,4BAA4B,CAAC;IAS9D,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAShD,QAAQ,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,GAAE,SAAc,GAAG,eAAe;IAkD3D,kCAAkC;IACrB,KAAK;CAQnB"}
@@ -371,7 +371,7 @@ class LLPlClient {
371
371
  body: { expiration: `${ttlSeconds}s` },
372
372
  headers,
373
373
  });
374
- return notEmpty((await resp).data).token;
374
+ return notEmpty((await resp).data, 'REST: empty response for JWT token request').token;
375
375
  }
376
376
  }
377
377
  async ping() {
@@ -380,7 +380,7 @@ class LLPlClient {
380
380
  return (await cl.ping({})).response;
381
381
  }
382
382
  else {
383
- return notEmpty((await cl.GET('/v1/ping')).data);
383
+ return notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');
384
384
  }
385
385
  }
386
386
  /**
@@ -412,7 +412,7 @@ class LLPlClient {
412
412
  return (await cl.license({})).response;
413
413
  }
414
414
  else {
415
- const resp = notEmpty((await cl.GET('/v1/license')).data);
415
+ const resp = notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');
416
416
  return {
417
417
  status: resp.status,
418
418
  isOk: resp.isOk,
@@ -426,7 +426,7 @@ class LLPlClient {
426
426
  return (await cl.authMethods({})).response;
427
427
  }
428
428
  else {
429
- return notEmpty((await cl.GET('/v1/auth/methods')).data);
429
+ return notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');
430
430
  }
431
431
  }
432
432
  async txSync(txId) {
@@ -1 +1 @@
1
- {"version":3,"file":"ll_client.js","sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client';\nimport type { ClientOptions, Interceptor } from '@grpc/grpc-js';\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from '@grpc/grpc-js';\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from './config';\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from './config';\nimport type { GrpcOptions } from '@protobuf-ts/grpc-transport';\nimport { GrpcTransport } from '@protobuf-ts/grpc-transport';\nimport { LLPlTransaction } from './ll_transaction';\nimport { parsePlJwt } from '../util/pl';\nimport { type Dispatcher, interceptors } from 'undici';\nimport type { Middleware } from 'openapi-fetch';\nimport { inferAuthRefreshTime } from './auth';\nimport { defaultHttpDispatcher } from '@milaboratories/pl-http';\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from './wire';\nimport { parseHttpAuth } from '@milaboratories/pl-model-common';\nimport type * as grpcTypes from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { type PlApiPaths, type PlRestClientType, createClient, parseResponseError } from '../proto-rest';\nimport { notEmpty, retry, withTimeout, type RetryOptions } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\nimport { WebSocketBiDiStream } from './websocket_stream';\nimport { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(private readonly wireOpts: () => WireConnection, private readonly clientConstructor: (wireOpts: WireConnection) => Client) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined)\n this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n private _status: PlConnectionStatus = 'OK';\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = 'grpc';\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const conf = typeof configOrAddress === 'string' ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n await pl.detectOptimalWireProtocol();\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === 'grpc') {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case 'rest':\n this.initRestConnection();\n return;\n case 'grpc':\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(`Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({ type: 'rest', Config: this.conf, Dispatcher: dispatcher, Middlewares: this._restMiddlewares });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n 'grpc.keepalive_time_ms': 30_000, // 30 seconds\n 'grpc.service_config_disable_resolution': 1, // Disable DNS TXT lookups for service config\n 'interceptors': this._grpcInterceptors,\n };\n\n if (gzip) clientOptions['grpc.default_compression_algorithm'] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy = typeof this.conf.grpcProxy === 'string'\n ? { url: this.conf.grpcProxy }\n : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== 'Basic') {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: 'grpc', Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === 'grpc') oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(clientConstructor: (transport: WireConnection) => Client): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error('Client is not authenticated');\n if (this.authInformation?.jwtToken)\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined\n || Date.now() < this.refreshTimestamp\n || this.authRefreshInProgress\n || this._status === 'Unauthenticated'\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body: body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus('Disconnected');\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n this.updateStatus('Unauthenticated');\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n this.updateStatus('Unauthenticated');\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus('Disconnected');\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = { ...options.headers, authorization: 'Bearer ' + this.authInformation.jwtToken };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set('authorization', 'Bearer ' + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(ttlSeconds: bigint, options?: { authorization?: string }): Promise<string> {\n const cl = this.clientProvider.get();\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST('/v1/auth/jwt-token', {\n body: { expiration: `${ttlSeconds}s` },\n headers,\n });\n return notEmpty((await resp).data).token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.ping({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/ping')).data);\n }\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n const retryOptions: RetryOptions = {\n type: 'exponentialBackoff',\n maxAttempts: 80,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n await retry(() => withTimeout(this.ping(), 500), retryOptions, () => {\n const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';\n this.initWireConnection(protocol);\n return true;\n });\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty((await cl.GET('/v1/license')).data);\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.authMethods({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/auth/methods')).data);\n }\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n (await cl.POST('/v1/tx-sync', { body: { txId: txId.toString() } }));\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === 'rest') {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) => stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: 'streamClose', streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === 'grpc') {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"names":["GrpcPlApiClient","status","GrpcStatus"],"mappings":";;;;;;;;;;;;;;;;AAsCA,MAAM,sBAAsB,CAAA;AAGG,IAAA,QAAA;AAAiD,IAAA,iBAAA;IAFtE,MAAM,GAAuB,SAAS;IAE9C,WAAA,CAA6B,QAA8B,EAAmB,iBAAuD,EAAA;QAAxG,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAAyC,IAAA,CAAA,iBAAiB,GAAjB,iBAAiB;IAAyC;IAEjI,KAAK,GAAA;AACV,QAAA,IAAI,CAAC,MAAM,GAAG,SAAS;IACzB;IAEO,GAAG,GAAA;AACR,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;AAC3B,YAAA,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACvD,OAAO,IAAI,CAAC,MAAM;IACpB;AACD;AAED;MACa,UAAU,CAAA;AA2CH,IAAA,IAAA;AACC,IAAA,GAAA;;AA1CX,IAAA,eAAe;;AAEN,IAAA,YAAY;;AAEZ,IAAA,WAAW;;AAEX,IAAA,oBAAoB;;AAE7B,IAAA,gBAAgB;IAEhB,OAAO,GAAuB,IAAI;AACzB,I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AAA;QAChB,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,KAAK,MAAM,EAAE;AACvC,YAAA,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,EAAE;QACvC;AAGA,QAAA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;IACrC;AACD;;;;"}
1
+ {"version":3,"file":"ll_client.js","sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client';\nimport type { ClientOptions, Interceptor } from '@grpc/grpc-js';\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from '@grpc/grpc-js';\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from './config';\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from './config';\nimport type { GrpcOptions } from '@protobuf-ts/grpc-transport';\nimport { GrpcTransport } from '@protobuf-ts/grpc-transport';\nimport { LLPlTransaction } from './ll_transaction';\nimport { parsePlJwt } from '../util/pl';\nimport { type Dispatcher, interceptors } from 'undici';\nimport type { Middleware } from 'openapi-fetch';\nimport { inferAuthRefreshTime } from './auth';\nimport { defaultHttpDispatcher } from '@milaboratories/pl-http';\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from './wire';\nimport { parseHttpAuth } from '@milaboratories/pl-model-common';\nimport type * as grpcTypes from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\nimport { type PlApiPaths, type PlRestClientType, createClient, parseResponseError } from '../proto-rest';\nimport { notEmpty, retry, withTimeout, type RetryOptions } from '@milaboratories/ts-helpers';\nimport { Code } from '../proto-grpc/google/rpc/code';\nimport { WebSocketBiDiStream } from './websocket_stream';\nimport { TxAPI_ClientMessage, TxAPI_ServerMessage } from '../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api';\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(private readonly wireOpts: () => WireConnection, private readonly clientConstructor: (wireOpts: WireConnection) => Client) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined)\n this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n private _status: PlConnectionStatus = 'OK';\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = 'grpc';\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const conf = typeof configOrAddress === 'string' ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n await pl.detectOptimalWireProtocol();\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === 'grpc') {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case 'rest':\n this.initRestConnection();\n return;\n case 'grpc':\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(`Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(', ')}`);\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({ type: 'rest', Config: this.conf, Dispatcher: dispatcher, Middlewares: this._restMiddlewares });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n 'grpc.keepalive_time_ms': 30_000, // 30 seconds\n 'grpc.service_config_disable_resolution': 1, // Disable DNS TXT lookups for service config\n 'interceptors': this._grpcInterceptors,\n };\n\n if (gzip) clientOptions['grpc.default_compression_algorithm'] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy = typeof this.conf.grpcProxy === 'string'\n ? { url: this.conf.grpcProxy }\n : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== 'Basic') {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: 'grpc', Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === 'grpc') oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(clientConstructor: (transport: WireConnection) => Client): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error('Client is not authenticated');\n if (this.authInformation?.jwtToken)\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined\n || Date.now() < this.refreshTimestamp\n || this.authRefreshInProgress\n || this._status === 'Unauthenticated'\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const token = await this.getJwtToken(BigInt(this.conf.authTTLSeconds));\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body: body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus('Disconnected');\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n this.updateStatus('Unauthenticated');\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n this.updateStatus('Unauthenticated');\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus('Disconnected');\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = { ...options.headers, authorization: 'Bearer ' + this.authInformation.jwtToken };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set('authorization', 'Bearer ' + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(ttlSeconds: bigint, options?: { authorization?: string }): Promise<string> {\n const cl = this.clientProvider.get();\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (await cl.getJWTToken({ expiration: { seconds: ttlSeconds, nanos: 0 } }, { meta }).response).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST('/v1/auth/jwt-token', {\n body: { expiration: `${ttlSeconds}s` },\n headers,\n });\n return notEmpty((await resp).data, 'REST: empty response for JWT token request').token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.ping({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');\n }\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n const retryOptions: RetryOptions = {\n type: 'exponentialBackoff',\n maxAttempts: 80,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n await retry(\n () => withTimeout(this.ping(), 500),\n retryOptions,\n () => {\n const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';\n this.initWireConnection(protocol);\n return true;\n });\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.authMethods({})).response;\n } else {\n return notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');\n }\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n (await cl.POST('/v1/tx-sync', { body: { txId: txId.toString() } }));\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout = ops.timeout ?? (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === 'rest') {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) => stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: 'streamClose', streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === 'grpc') {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"names":["GrpcPlApiClient","status","GrpcStatus"],"mappings":";;;;;;;;;;;;;;;;AAsCA,MAAM,sBAAsB,CAAA;AAGG,IAAA,QAAA;AAAiD,IAAA,iBAAA;IAFtE,MAAM,GAAuB,SAAS;IAE9C,WAAA,CAA6B,QAA8B,EAAmB,iBAAuD,EAAA;QAAxG,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAAyC,IAAA,CAAA,iBAAiB,GAAjB,iBAAiB;IAAyC;IAEjI,KAAK,GAAA;AACV,QAAA,IAAI,CAAC,MAAM,GAAG,SAAS;IACzB;IAEO,GAAG,GAAA;AACR,QAAA,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;AAC3B,YAAA,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACvD,OAAO,IAAI,CAAC,MAAM;IACpB;AACD;AAED;MACa,UAAU,CAAA;AA2CH,IAAA,IAAA;AACC,IAAA,G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,WAAW,EAAE,EAAE,EAAE;qBACvD,CAAC;AACH,iBAAA,CACF;YACH;YAEA,MAAM,IAAI,KAAK,CAAC,CAAA,iDAAA,EAAoD,IAAI,CAAC,UAAU,CAAA,CAAE,CAAC;AACxF,QAAA,CAAC,CAAC;IACJ;;AAGO,IAAA,MAAM,KAAK,GAAA;QAChB,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,KAAK,MAAM,EAAE;AACvC,YAAA,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,EAAE;QACvC;AAGA,QAAA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;IACrC;AACD;;;;"}
package/dist/index.cjs CHANGED
@@ -77,11 +77,15 @@ exports.toResourceId = transaction.toResourceId;
77
77
  exports.DisconnectedError = errors.DisconnectedError;
78
78
  exports.PlError = errors.PlError;
79
79
  exports.PlErrorCodeNotFound = errors.PlErrorCodeNotFound;
80
+ exports.RESTError = errors.RESTError;
80
81
  exports.RecoverablePlError = errors.RecoverablePlError;
81
82
  exports.UnauthenticatedError = errors.UnauthenticatedError;
82
83
  exports.UnrecoverablePlError = errors.UnrecoverablePlError;
84
+ exports.isAbortedError = errors.isAbortedError;
85
+ exports.isCancelError = errors.isCancelError;
83
86
  exports.isConnectionProblem = errors.isConnectionProblem;
84
87
  exports.isNotFoundError = errors.isNotFoundError;
88
+ exports.isTimeoutError = errors.isTimeoutError;
85
89
  exports.isTimeoutOrCancelError = errors.isTimeoutOrCancelError;
86
90
  exports.isUnauthenticated = errors.isUnauthenticated;
87
91
  exports.rethrowMeaningfulError = errors.rethrowMeaningfulError;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ export { AnonymousAuthInformation, DEFAULT_AUTH_MAX_REFRESH, DEFAULT_MAX_CACHE_B
5
5
  export { PlClient } from './core/client.js';
6
6
  export { addRTypeToMetadata, createRTypeRoutingHeader } from './core/driver.js';
7
7
  export { PlTransaction, TxCommitConflict, field, isField, isFieldRef, isResource, isResourceId, isResourceRef, toFieldId, toGlobalFieldId, toGlobalResourceId, toResourceId } from './core/transaction.js';
8
- export { DisconnectedError, PlError, PlErrorCodeNotFound, RecoverablePlError, UnauthenticatedError, UnrecoverablePlError, isConnectionProblem, isNotFoundError, isTimeoutOrCancelError, isUnauthenticated, rethrowMeaningfulError, throwPlNotFoundError } from './core/errors.js';
8
+ export { DisconnectedError, PlError, PlErrorCodeNotFound, RESTError, RecoverablePlError, UnauthenticatedError, UnrecoverablePlError, isAbortedError, isCancelError, isConnectionProblem, isNotFoundError, isTimeoutError, isTimeoutOrCancelError, isUnauthenticated, rethrowMeaningfulError, throwPlNotFoundError } from './core/errors.js';
9
9
  export { defaultPlClient, tryGetFileConfig } from './core/default_client.js';
10
10
  export { UnauthenticatedPlClient } from './core/unauth_client.js';
11
11
  export { expirationFromAuthInformation, inferAuthRefreshTime } from './core/auth.js';
@@ -68,7 +68,7 @@ function errorHandlerMiddleware() {
68
68
  if (typeof respErr.error === 'string') {
69
69
  throw new Error(respErr.error);
70
70
  }
71
- errors.rethrowMeaningfulError(respErr.error);
71
+ errors.rethrowMeaningfulError(new errors.RESTError(respErr.error));
72
72
  },
73
73
  };
74
74
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/proto-rest/index.ts"],"sourcesContent":["//\n// This file is NOT autogenerated!\n//\n// After generating new clients from openapi specifications, add client types here.\n//\n\nimport type { paths as PlApiPaths } from './plapi';\nimport { default as createOpenApiClient, type Middleware, type Client } from 'openapi-fetch';\nimport { Dispatcher, fetch as undiciFetch } from 'undici';\nimport { rethrowMeaningfulError } from '../core/errors';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport { PlApiPaths };\nexport type PlRestClientType = Client<PlApiPaths>;\n\nexport type RestClientConfig = {\n hostAndPort: string;\n ssl: boolean;\n dispatcher: Dispatcher;\n middlewares: Middleware[];\n}\n\nexport function createClient<Paths extends {}>(opts: RestClientConfig): Client<Paths> {\n const scheme = opts.ssl ? 'https://' : 'http://';\n const client = createOpenApiClient<Paths>({\n baseUrl: `${scheme}${opts.hostAndPort}`,\n fetch: (input: Request): Promise<Response> => {\n // If body has already been consumed, clone the request\n const request = input.bodyUsed ? input.clone() : input;\n\n return undiciFetch(request.url, {\n body: request.body,\n cache: request.cache,\n credentials: request.credentials,\n dispatcher: opts.dispatcher,\n duplex: request.duplex,\n headers: request.headers,\n integrity: request.integrity,\n keepalive: request.keepalive,\n method: request.method,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n });\n },\n });\n client.use(errorHandlerMiddleware(), ...opts.middlewares);\n return client;\n}\n\nexport type ErrorResponse = {\n code: Code,\n message: string,\n details: any[],\n}\nexport async function parseResponseError(response: Response): Promise<{\n error?: ErrorResponse | string,\n origBody?: string,\n}>{\n if (response.status < 400) {\n return {};\n }\n\n let error: any = await response.clone().text();\n const origBody = error;\n try {\n error = JSON.parse(error) as ErrorResponse;\n } catch {\n }\n return {\n error: error,\n origBody\n };\n}\n\n/**\n * Parses all API responses and thrown error in case of error response.\n * Allows all callers to not bother about .error response field checking.\n */\nfunction errorHandlerMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n const { body, ...resOptions } = response;\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n throw new Error(respErr.error);\n }\n\n rethrowMeaningfulError(respErr.error);\n },\n };\n}\n"],"names":["undiciFetch","rethrowMeaningfulError"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AAkBM,SAAU,YAAY,CAAmB,IAAsB,EAAA;AACnE,IAAA,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,GAAG,UAAU,GAAG,SAAS;IAChD,MAAM,MAAM,GAAG,mBAAmB,CAAQ;AACxC,QAAA,OAAO,EAAE,CAAA,EAAG,MAAM,GAAG,IAAI,CAAC,WAAW,CAAA,CAAE;AACvC,QAAA,KAAK,EAAE,CAAC,KAAc,KAAuB;;AAE3C,YAAA,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK;AAEtD,YAAA,OAAOA,YAAW,CAAC,OAAO,CAAC,GAAG,EAAE;gBAC9B,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,WAAW,EAAE,OAAO,CAAC,WAAW;gBAChC,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,cAAc,EAAE,OAAO,CAAC,cAAc;gBACtC,MAAM,EAAE,OAAO,CAAC,MAAM;AACvB,aAAA,CAAC;QACJ,CAAC;AACF,KAAA,CAAC;IACF,MAAM,CAAC,GAAG,CAAC,sBAAsB,EAAE,EAAE,GAAG,IAAI,CAAC,WAAW,CAAC;AACzD,IAAA,OAAO,MAAM;AACf;AAOO,eAAe,kBAAkB,CAAC,QAAkB,EAAA;AAIzD,IAAA,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,EAAE;AACzB,QAAA,OAAO,EAAE;IACX;IAEA,IAAI,KAAK,GAAQ,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE;IAC9C,MAAM,QAAQ,GAAG,KAAK;AACtB,IAAA,IAAI;AACF,QAAA,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAkB;IAC5C;AAAE,IAAA,MAAM;IACR;IACA,OAAO;AACL,QAAA,KAAK,EAAE,KAAK;QACZ;KACD;AACH;AAEA;;;AAGG;AACH,SAAS,sBAAsB,GAAA;IAC7B,OAAO;AACL,QAAA,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAI;AACvE,YAAA,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,QAAQ,CAAC;AAClD,YAAA,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE;gBAClB,MAAM,EAAE,IAAI,EAAE,GAAG,UAAU,EAAE,GAAG,QAAQ;AACxC,gBAAA,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,GAAG,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;YACvE;AAEA,YAAA,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;AACrC,gBAAA,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAChC;AAEA,YAAAC,6BAAsB,CAAC,OAAO,CAAC,KAAK,CAAC;QACvC,CAAC;KACF;AACH;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/proto-rest/index.ts"],"sourcesContent":["//\n// This file is NOT autogenerated!\n//\n// After generating new clients from openapi specifications, add client types here.\n//\n\nimport type { paths as PlApiPaths } from './plapi';\nimport { default as createOpenApiClient, type Middleware, type Client } from 'openapi-fetch';\nimport { Dispatcher, fetch as undiciFetch } from 'undici';\nimport { RESTError, rethrowMeaningfulError } from '../core/errors';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport { PlApiPaths };\nexport type PlRestClientType = Client<PlApiPaths>;\n\nexport type RestClientConfig = {\n hostAndPort: string;\n ssl: boolean;\n dispatcher: Dispatcher;\n middlewares: Middleware[];\n}\n\nexport function createClient<Paths extends {}>(opts: RestClientConfig): Client<Paths> {\n const scheme = opts.ssl ? 'https://' : 'http://';\n const client = createOpenApiClient<Paths>({\n baseUrl: `${scheme}${opts.hostAndPort}`,\n fetch: (input: Request): Promise<Response> => {\n // If body has already been consumed, clone the request\n const request = input.bodyUsed ? input.clone() : input;\n\n return undiciFetch(request.url, {\n body: request.body,\n cache: request.cache,\n credentials: request.credentials,\n dispatcher: opts.dispatcher,\n duplex: request.duplex,\n headers: request.headers,\n integrity: request.integrity,\n keepalive: request.keepalive,\n method: request.method,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n });\n },\n });\n client.use(errorHandlerMiddleware(), ...opts.middlewares);\n return client;\n}\n\nexport type ErrorResponse = {\n code: Code,\n message: string,\n details: any[],\n}\nexport async function parseResponseError(response: Response): Promise<{\n error?: ErrorResponse | string,\n origBody?: string,\n}>{\n if (response.status < 400) {\n return {};\n }\n\n let error: any = await response.clone().text();\n const origBody = error;\n try {\n error = JSON.parse(error) as ErrorResponse;\n } catch {\n }\n return {\n error: error,\n origBody\n };\n}\n\n/**\n * Parses all API responses and thrown error in case of error response.\n * Allows all callers to not bother about .error response field checking.\n */\nfunction errorHandlerMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n const { body, ...resOptions } = response;\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n throw new Error(respErr.error);\n }\n\n rethrowMeaningfulError(new RESTError(respErr.error));\n },\n };\n}\n"],"names":["undiciFetch","rethrowMeaningfulError","RESTError"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AAkBM,SAAU,YAAY,CAAmB,IAAsB,EAAA;AACnE,IAAA,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,GAAG,UAAU,GAAG,SAAS;IAChD,MAAM,MAAM,GAAG,mBAAmB,CAAQ;AACxC,QAAA,OAAO,EAAE,CAAA,EAAG,MAAM,GAAG,IAAI,CAAC,WAAW,CAAA,CAAE;AACvC,QAAA,KAAK,EAAE,CAAC,KAAc,KAAuB;;AAE3C,YAAA,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK;AAEtD,YAAA,OAAOA,YAAW,CAAC,OAAO,CAAC,GAAG,EAAE;gBAC9B,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,WAAW,EAAE,OAAO,CAAC,WAAW;gBAChC,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,cAAc,EAAE,OAAO,CAAC,cAAc;gBACtC,MAAM,EAAE,OAAO,CAAC,MAAM;AACvB,aAAA,CAAC;QACJ,CAAC;AACF,KAAA,CAAC;IACF,MAAM,CAAC,GAAG,CAAC,sBAAsB,EAAE,EAAE,GAAG,IAAI,CAAC,WAAW,CAAC;AACzD,IAAA,OAAO,MAAM;AACf;AAOO,eAAe,kBAAkB,CAAC,QAAkB,EAAA;AAIzD,IAAA,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,EAAE;AACzB,QAAA,OAAO,EAAE;IACX;IAEA,IAAI,KAAK,GAAQ,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE;IAC9C,MAAM,QAAQ,GAAG,KAAK;AACtB,IAAA,IAAI;AACF,QAAA,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAkB;IAC5C;AAAE,IAAA,MAAM;IACR;IACA,OAAO;AACL,QAAA,KAAK,EAAE,KAAK;QACZ;KACD;AACH;AAEA;;;AAGG;AACH,SAAS,sBAAsB,GAAA;IAC7B,OAAO;AACL,QAAA,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAI;AACvE,YAAA,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,QAAQ,CAAC;AAClD,YAAA,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE;gBAClB,MAAM,EAAE,IAAI,EAAE,GAAG,UAAU,EAAE,GAAG,QAAQ;AACxC,gBAAA,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,GAAG,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;YACvE;AAEA,YAAA,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;AACrC,gBAAA,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAChC;YAEAC,6BAAsB,CAAC,IAAIC,gBAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACtD,CAAC;KACF;AACH;;;;;"}
@@ -1,6 +1,6 @@
1
1
  import createOpenApiClient from 'openapi-fetch';
2
2
  import { fetch } from 'undici';
3
- import { rethrowMeaningfulError } from '../core/errors.js';
3
+ import { rethrowMeaningfulError, RESTError } from '../core/errors.js';
4
4
 
5
5
  //
6
6
  // This file is NOT autogenerated!
@@ -66,7 +66,7 @@ function errorHandlerMiddleware() {
66
66
  if (typeof respErr.error === 'string') {
67
67
  throw new Error(respErr.error);
68
68
  }
69
- rethrowMeaningfulError(respErr.error);
69
+ rethrowMeaningfulError(new RESTError(respErr.error));
70
70
  },
71
71
  };
72
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/proto-rest/index.ts"],"sourcesContent":["//\n// This file is NOT autogenerated!\n//\n// After generating new clients from openapi specifications, add client types here.\n//\n\nimport type { paths as PlApiPaths } from './plapi';\nimport { default as createOpenApiClient, type Middleware, type Client } from 'openapi-fetch';\nimport { Dispatcher, fetch as undiciFetch } from 'undici';\nimport { rethrowMeaningfulError } from '../core/errors';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport { PlApiPaths };\nexport type PlRestClientType = Client<PlApiPaths>;\n\nexport type RestClientConfig = {\n hostAndPort: string;\n ssl: boolean;\n dispatcher: Dispatcher;\n middlewares: Middleware[];\n}\n\nexport function createClient<Paths extends {}>(opts: RestClientConfig): Client<Paths> {\n const scheme = opts.ssl ? 'https://' : 'http://';\n const client = createOpenApiClient<Paths>({\n baseUrl: `${scheme}${opts.hostAndPort}`,\n fetch: (input: Request): Promise<Response> => {\n // If body has already been consumed, clone the request\n const request = input.bodyUsed ? input.clone() : input;\n\n return undiciFetch(request.url, {\n body: request.body,\n cache: request.cache,\n credentials: request.credentials,\n dispatcher: opts.dispatcher,\n duplex: request.duplex,\n headers: request.headers,\n integrity: request.integrity,\n keepalive: request.keepalive,\n method: request.method,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n });\n },\n });\n client.use(errorHandlerMiddleware(), ...opts.middlewares);\n return client;\n}\n\nexport type ErrorResponse = {\n code: Code,\n message: string,\n details: any[],\n}\nexport async function parseResponseError(response: Response): Promise<{\n error?: ErrorResponse | string,\n origBody?: string,\n}>{\n if (response.status < 400) {\n return {};\n }\n\n let error: any = await response.clone().text();\n const origBody = error;\n try {\n error = JSON.parse(error) as ErrorResponse;\n } catch {\n }\n return {\n error: error,\n origBody\n };\n}\n\n/**\n * Parses all API responses and thrown error in case of error response.\n * Allows all callers to not bother about .error response field checking.\n */\nfunction errorHandlerMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n const { body, ...resOptions } = response;\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n throw new Error(respErr.error);\n }\n\n rethrowMeaningfulError(respErr.error);\n },\n };\n}\n"],"names":["undiciFetch"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AAkBM,SAAU,YAAY,CAAmB,IAAsB,EAAA;AACnE,IAAA,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,GAAG,UAAU,GAAG,SAAS;IAChD,MAAM,MAAM,GAAG,mBAAmB,CAAQ;AACxC,QAAA,OAAO,EAAE,CAAA,EAAG,MAAM,GAAG,IAAI,CAAC,WAAW,CAAA,CAAE;AACvC,QAAA,KAAK,EAAE,CAAC,KAAc,KAAuB;;AAE3C,YAAA,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK;AAEtD,YAAA,OAAOA,KAAW,CAAC,OAAO,CAAC,GAAG,EAAE;gBAC9B,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,WAAW,EAAE,OAAO,CAAC,WAAW;gBAChC,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EA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A,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;AACrC,gBAAA,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAChC;AAEA,YAAA,sBAAsB,CAAC,OAAO,CAAC,KAAK,CAAC;QACvC,CAAC;KACF;AACH;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/proto-rest/index.ts"],"sourcesContent":["//\n// This file is NOT autogenerated!\n//\n// After generating new clients from openapi specifications, add client types here.\n//\n\nimport type { paths as PlApiPaths } from './plapi';\nimport { default as createOpenApiClient, type Middleware, type Client } from 'openapi-fetch';\nimport { Dispatcher, fetch as undiciFetch } from 'undici';\nimport { RESTError, rethrowMeaningfulError } from '../core/errors';\nimport { Code } from '../proto-grpc/google/rpc/code';\n\nexport { PlApiPaths };\nexport type PlRestClientType = Client<PlApiPaths>;\n\nexport type RestClientConfig = {\n hostAndPort: string;\n ssl: boolean;\n dispatcher: Dispatcher;\n middlewares: Middleware[];\n}\n\nexport function createClient<Paths extends {}>(opts: RestClientConfig): Client<Paths> {\n const scheme = opts.ssl ? 'https://' : 'http://';\n const client = createOpenApiClient<Paths>({\n baseUrl: `${scheme}${opts.hostAndPort}`,\n fetch: (input: Request): Promise<Response> => {\n // If body has already been consumed, clone the request\n const request = input.bodyUsed ? input.clone() : input;\n\n return undiciFetch(request.url, {\n body: request.body,\n cache: request.cache,\n credentials: request.credentials,\n dispatcher: opts.dispatcher,\n duplex: request.duplex,\n headers: request.headers,\n integrity: request.integrity,\n keepalive: request.keepalive,\n method: request.method,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n });\n },\n });\n client.use(errorHandlerMiddleware(), ...opts.middlewares);\n return client;\n}\n\nexport type ErrorResponse = {\n code: Code,\n message: string,\n details: any[],\n}\nexport async function parseResponseError(response: Response): Promise<{\n error?: ErrorResponse | string,\n origBody?: string,\n}>{\n if (response.status < 400) {\n return {};\n }\n\n let error: any = await response.clone().text();\n const origBody = error;\n try {\n error = JSON.parse(error) as ErrorResponse;\n } catch {\n }\n return {\n error: error,\n origBody\n };\n}\n\n/**\n * Parses all API responses and thrown error in case of error response.\n * Allows all callers to not bother about .error response field checking.\n */\nfunction errorHandlerMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n const { body, ...resOptions } = response;\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === 'string') {\n throw new Error(respErr.error);\n }\n\n rethrowMeaningfulError(new RESTError(respErr.error));\n },\n };\n}\n"],"names":["undiciFetch"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AAkBM,SAAU,YAAY,CAAmB,IAAsB,EAAA;AACnE,IAAA,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,GAAG,UAAU,GAAG,SAAS;IAChD,MAAM,MAAM,GAAG,mBAAmB,CAAQ;AACxC,QAAA,OAAO,EAAE,CAAA,EAAG,MAAM,GAAG,IAAI,CAAC,WAAW,CAAA,CAAE;AACvC,QAAA,KAAK,EAAE,CAAC,KAAc,KAAuB;;AAE3C,YAAA,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK;AAEtD,YAAA,OAAOA,KAAW,CAAC,OAAO,CAAC,GAAG,EAAE;gBAC9B,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,WAAW,EAAE,OAAO,CAAC,WAAW;gBAChC,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,IAAI,EA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,QAAQ,EAAE;AACrC,gBAAA,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAChC;YAEA,sBAAsB,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACtD,CAAC;KACF;AACH;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-client",
3
- "version": "2.16.14",
3
+ "version": "2.16.15",
4
4
  "engines": {
5
5
  "node": ">=22.19.0"
6
6
  },
@@ -35,20 +35,22 @@
35
35
  "undici": "~7.16.0",
36
36
  "utility-types": "^3.11.0",
37
37
  "yaml": "^2.8.0",
38
- "@milaboratories/pl-http": "1.2.0",
38
+ "@milaboratories/pl-model-common": "1.21.10",
39
39
  "@milaboratories/ts-helpers": "1.5.4",
40
- "@milaboratories/pl-model-common": "1.21.10"
40
+ "@milaboratories/pl-http": "1.2.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@protobuf-ts/plugin": "2.11.1",
44
44
  "openapi-typescript": "^7.10.0",
45
45
  "@types/http-proxy": "^1.17.16",
46
46
  "@types/node": "~24.5.2",
47
- "@vitest/coverage-v8": "^4.0.7",
48
- "vitest": "^4.0.7",
47
+ "@vitest/coverage-istanbul": "^4.0.16",
48
+ "vitest": "^4.0.16",
49
+ "eslint": "^9.25.1",
49
50
  "typescript": "~5.6.3",
50
- "@milaboratories/build-configs": "1.2.0",
51
- "@milaboratories/ts-builder": "1.2.0",
51
+ "@milaboratories/ts-builder": "1.2.1",
52
+ "@milaboratories/build-configs": "1.2.1",
53
+ "@milaboratories/eslint-config": "1.0.5",
52
54
  "@milaboratories/ts-configs": "1.2.0"
53
55
  },
54
56
  "scripts": {
@@ -5,49 +5,65 @@ import { Code } from '../proto-grpc/google/rpc/code';
5
5
  export function isConnectionProblem(err: unknown, nested: boolean = false): boolean {
6
6
  if (err instanceof DisconnectedError) return true;
7
7
  if ((err as any).name == 'RpcError' && (err as any).code == 'UNAVAILABLE') return true;
8
- if ((err as any).code == Code.UNAVAILABLE) return true;
9
- if ((err as any).cause !== undefined && !nested)
10
- // nested limits the depth of search
11
- return isConnectionProblem((err as any).cause, true);
8
+ if ((err as any).name == 'RESTError' && (err as any).status.code == Code.UNAVAILABLE) return true;
9
+ if ((err as any).cause !== undefined && !nested) return isConnectionProblem((err as any).cause, true);
12
10
  return false;
13
11
  }
14
12
 
15
13
  export function isUnauthenticated(err: unknown, nested: boolean = false): boolean {
16
14
  if (err instanceof UnauthenticatedError) return true;
17
15
  if ((err as any).name == 'RpcError' && (err as any).code == 'UNAUTHENTICATED') return true;
18
- if ((err as any).code == Code.UNAUTHENTICATED) return true;
19
- if ((err as any).cause !== undefined && !nested)
20
- // nested limits the depth of search
21
- return isUnauthenticated((err as any).cause, true);
16
+ if ((err as any).name == 'RESTError' && (err as any).status.code == Code.UNAUTHENTICATED) return true;
17
+ if ((err as any).cause !== undefined && !nested) return isUnauthenticated((err as any).cause, true);
22
18
  return false;
23
19
  }
24
20
 
25
- export function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {
26
- if (err instanceof Aborted || (err as any).name == 'AbortError') return true;
21
+ export function isTimeoutError(err: unknown, nested: boolean = false): boolean {
27
22
  if ((err as any).name == 'TimeoutError') return true;
23
+ if ((err as any).name == 'RpcError' && (err as any).code == 'DEADLINE_EXCEEDED') return true;
24
+ if ((err as any).name == 'RESTError' && (err as any).status.code == Code.DEADLINE_EXCEEDED) return true;
25
+ if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);
26
+ return false;
27
+ }
28
+
29
+ export function isCancelError(err: unknown, nested: boolean = false): boolean {
30
+ if ((err as any).name == 'RpcError' && (err as any).code == 'CANCELLED') return true;
31
+ if ((err as any).name == 'RESTError' && (err as any).status.code == Code.CANCELLED) return true;
32
+ if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);
33
+ return false;
34
+ }
35
+
36
+ export function isAbortedError(err: unknown, nested: boolean = false): boolean {
37
+ if (err instanceof Aborted || (err as any).name == 'AbortError') return true;
28
38
  if ((err as any).code == 'ABORT_ERR') return true;
29
- // Check for DOMException with ABORT_ERR code (thrown by AbortSignal.timeout)
30
- if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true;
31
- if ((err as any).code == Code.ABORTED) return true;
32
- if (
33
- (err as any).name == 'RpcError'
34
- && ((err as any).code == 'CANCELLED' || (err as any).code == 'DEADLINE_EXCEEDED')
35
- )
36
- return true;
37
- if ((err as any).code == Code.CANCELLED || (err as any).code == Code.DEADLINE_EXCEEDED)
38
- return true;
39
- if ((err as any).cause !== undefined && !nested)
40
- // nested limits the depth of search
41
- return isTimeoutOrCancelError((err as any).cause, true);
39
+ if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error
40
+ if ((err as any).name == 'RpcError' && (err as any).code == 'ABORTED') return true;
41
+ if ((err as any).name == 'RESTError' && (err as any).status.code == Code.ABORTED) return true;
42
+ if ((err as any).cause !== undefined && !nested) isAbortedError((err as any).cause, true);
42
43
  return false;
43
44
  }
44
45
 
45
- export const PlErrorCodeNotFound = 5;
46
+ export function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {
47
+ if (isAbortedError(err, true)) return true;
48
+ if (isTimeoutError(err, true)) return true;
49
+ if (isCancelError(err, true)) return true;
50
+ if ((err as any).cause !== undefined && !nested) return isTimeoutOrCancelError((err as any).cause, true);
51
+ return false;
52
+ }
53
+
54
+ export function isNotFoundError(err: unknown, nested: boolean = false): boolean {
55
+ if ((err as any).name == 'RpcError' && (err as any).code == 'NOT_FOUND') return true;
56
+ if ((err as any).name == 'RESTError' && (err as any).status.code == Code.NOT_FOUND) return true;
57
+ if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);
58
+ return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;
59
+ }
60
+
61
+ export const PlErrorCodeNotFound: number = Code.NOT_FOUND;
46
62
 
47
63
  export class PlError extends Error {
48
64
  name = 'PlError';
49
- constructor(public readonly status: Status) {
50
- super(`code=${status.code} ${status.message}`);
65
+ constructor(public readonly status: Status, opts?: ErrorOptions) {
66
+ super(`code=${status.code} ${status.message}`, opts);
51
67
  }
52
68
  }
53
69
 
@@ -69,12 +85,6 @@ export class UnrecoverablePlError extends PlError {
69
85
  }
70
86
  }
71
87
 
72
- export function isNotFoundError(err: unknown, nested: boolean = false): boolean {
73
- if ((err as any).name == 'RpcError' && (err as any).code == 'NOT_FOUND') return true;
74
- if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);
75
- return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;
76
- }
77
-
78
88
  export class UnauthenticatedError extends Error {
79
89
  name = 'UnauthenticatedError';
80
90
  constructor(message: string) {
@@ -89,6 +99,13 @@ export class DisconnectedError extends Error {
89
99
  }
90
100
  }
91
101
 
102
+ export class RESTError extends PlError {
103
+ name = 'RESTError';
104
+ constructor(status: Status, opts?: ErrorOptions) {
105
+ super(status, opts);
106
+ }
107
+ }
108
+
92
109
  export function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {
93
110
  if (isUnauthenticated(error)) {
94
111
  if (error instanceof UnauthenticatedError) throw error;
@@ -7,6 +7,15 @@ import { test, expect } from 'vitest';
7
7
 
8
8
  import { UnauthenticatedError } from './errors';
9
9
 
10
+ test('wire protocol detection', async () => {
11
+ const { conf, auth } = await getTestClientConf();
12
+ const expectedWireProtocol = conf.wireProtocol ?? 'grpc';
13
+ conf.wireProtocol = undefined;
14
+
15
+ const client = await LLPlClient.build(conf, { auth });
16
+ expect(client.wireProtocol).toBe(expectedWireProtocol);
17
+ });
18
+
10
19
  test('authenticated instance test', async () => {
11
20
  const client = await getTestLLClient();
12
21
  const tx = client.createTx(true);
@@ -443,7 +443,7 @@ export class LLPlClient implements WireClientProviderFactory {
443
443
  body: { expiration: `${ttlSeconds}s` },
444
444
  headers,
445
445
  });
446
- return notEmpty((await resp).data).token;
446
+ return notEmpty((await resp).data, 'REST: empty response for JWT token request').token;
447
447
  }
448
448
  }
449
449
 
@@ -452,7 +452,7 @@ export class LLPlClient implements WireClientProviderFactory {
452
452
  if (cl instanceof GrpcPlApiClient) {
453
453
  return (await cl.ping({})).response;
454
454
  } else {
455
- return notEmpty((await cl.GET('/v1/ping')).data);
455
+ return notEmpty((await cl.GET('/v1/ping')).data, 'REST: empty response for ping request');
456
456
  }
457
457
  }
458
458
 
@@ -475,11 +475,14 @@ export class LLPlClient implements WireClientProviderFactory {
475
475
  maxDelay: 500,
476
476
  };
477
477
 
478
- await retry(() => withTimeout(this.ping(), 500), retryOptions, () => {
479
- const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';
480
- this.initWireConnection(protocol);
481
- return true;
482
- });
478
+ await retry(
479
+ () => withTimeout(this.ping(), 500),
480
+ retryOptions,
481
+ () => {
482
+ const protocol = this._wireProto === 'grpc' ? 'rest' : 'grpc';
483
+ this.initWireConnection(protocol);
484
+ return true;
485
+ });
483
486
  }
484
487
 
485
488
  public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {
@@ -487,7 +490,7 @@ export class LLPlClient implements WireClientProviderFactory {
487
490
  if (cl instanceof GrpcPlApiClient) {
488
491
  return (await cl.license({})).response;
489
492
  } else {
490
- const resp = notEmpty((await cl.GET('/v1/license')).data);
493
+ const resp = notEmpty((await cl.GET('/v1/license')).data, 'REST: empty response for license request');
491
494
  return {
492
495
  status: resp.status,
493
496
  isOk: resp.isOk,
@@ -501,7 +504,7 @@ export class LLPlClient implements WireClientProviderFactory {
501
504
  if (cl instanceof GrpcPlApiClient) {
502
505
  return (await cl.authMethods({})).response;
503
506
  } else {
504
- return notEmpty((await cl.GET('/v1/auth/methods')).data);
507
+ return notEmpty((await cl.GET('/v1/auth/methods')).data, 'REST: empty response for auth methods request');
505
508
  }
506
509
  }
507
510
 
@@ -7,7 +7,7 @@
7
7
  import type { paths as PlApiPaths } from './plapi';
8
8
  import { default as createOpenApiClient, type Middleware, type Client } from 'openapi-fetch';
9
9
  import { Dispatcher, fetch as undiciFetch } from 'undici';
10
- import { rethrowMeaningfulError } from '../core/errors';
10
+ import { RESTError, rethrowMeaningfulError } from '../core/errors';
11
11
  import { Code } from '../proto-grpc/google/rpc/code';
12
12
 
13
13
  export { PlApiPaths };
@@ -92,7 +92,7 @@ function errorHandlerMiddleware(): Middleware {
92
92
  throw new Error(respErr.error);
93
93
  }
94
94
 
95
- rethrowMeaningfulError(respErr.error);
95
+ rethrowMeaningfulError(new RESTError(respErr.error));
96
96
  },
97
97
  };
98
98
  }