@milaboratories/pl-client 2.16.26 → 2.16.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +2 -1
  2. package/dist/core/PromiseTracker.cjs +1 -3
  3. package/dist/core/PromiseTracker.cjs.map +1 -1
  4. package/dist/core/PromiseTracker.d.ts.map +1 -1
  5. package/dist/core/PromiseTracker.js +1 -3
  6. package/dist/core/PromiseTracker.js.map +1 -1
  7. package/dist/core/StatefulPromise.cjs +4 -4
  8. package/dist/core/StatefulPromise.cjs.map +1 -1
  9. package/dist/core/StatefulPromise.d.ts +1 -1
  10. package/dist/core/StatefulPromise.d.ts.map +1 -1
  11. package/dist/core/StatefulPromise.js +4 -4
  12. package/dist/core/StatefulPromise.js.map +1 -1
  13. package/dist/core/advisory_locks.cjs +1 -1
  14. package/dist/core/advisory_locks.cjs.map +1 -1
  15. package/dist/core/advisory_locks.js +1 -1
  16. package/dist/core/advisory_locks.js.map +1 -1
  17. package/dist/core/auth.cjs.map +1 -1
  18. package/dist/core/auth.d.ts +1 -1
  19. package/dist/core/auth.js.map +1 -1
  20. package/dist/core/cache.d.ts +1 -1
  21. package/dist/core/client.cjs +14 -14
  22. package/dist/core/client.cjs.map +1 -1
  23. package/dist/core/client.d.ts +11 -11
  24. package/dist/core/client.d.ts.map +1 -1
  25. package/dist/core/client.js +14 -14
  26. package/dist/core/client.js.map +1 -1
  27. package/dist/core/config.cjs +39 -39
  28. package/dist/core/config.cjs.map +1 -1
  29. package/dist/core/config.d.ts +5 -5
  30. package/dist/core/config.js +39 -39
  31. package/dist/core/config.js.map +1 -1
  32. package/dist/core/default_client.cjs +23 -23
  33. package/dist/core/default_client.cjs.map +1 -1
  34. package/dist/core/default_client.d.ts +3 -3
  35. package/dist/core/default_client.js +23 -23
  36. package/dist/core/default_client.js.map +1 -1
  37. package/dist/core/driver.cjs +1 -1
  38. package/dist/core/driver.cjs.map +1 -1
  39. package/dist/core/driver.d.ts +5 -5
  40. package/dist/core/driver.js +1 -1
  41. package/dist/core/driver.js.map +1 -1
  42. package/dist/core/error_resource.cjs +2 -2
  43. package/dist/core/error_resource.cjs.map +1 -1
  44. package/dist/core/error_resource.d.ts +1 -1
  45. package/dist/core/error_resource.js +2 -2
  46. package/dist/core/error_resource.js.map +1 -1
  47. package/dist/core/errors.cjs +24 -24
  48. package/dist/core/errors.cjs.map +1 -1
  49. package/dist/core/errors.d.ts +1 -1
  50. package/dist/core/errors.d.ts.map +1 -1
  51. package/dist/core/errors.js +24 -24
  52. package/dist/core/errors.js.map +1 -1
  53. package/dist/core/final.cjs +43 -43
  54. package/dist/core/final.cjs.map +1 -1
  55. package/dist/core/final.d.ts +3 -3
  56. package/dist/core/final.d.ts.map +1 -1
  57. package/dist/core/final.js +43 -43
  58. package/dist/core/final.js.map +1 -1
  59. package/dist/core/ll_client.cjs +50 -43
  60. package/dist/core/ll_client.cjs.map +1 -1
  61. package/dist/core/ll_client.d.ts +9 -9
  62. package/dist/core/ll_client.d.ts.map +1 -1
  63. package/dist/core/ll_client.js +50 -43
  64. package/dist/core/ll_client.js.map +1 -1
  65. package/dist/core/ll_transaction.cjs +9 -9
  66. package/dist/core/ll_transaction.cjs.map +1 -1
  67. package/dist/core/ll_transaction.d.ts +7 -7
  68. package/dist/core/ll_transaction.d.ts.map +1 -1
  69. package/dist/core/ll_transaction.js +9 -9
  70. package/dist/core/ll_transaction.js.map +1 -1
  71. package/dist/core/stat.cjs.map +1 -1
  72. package/dist/core/stat.d.ts +1 -1
  73. package/dist/core/stat.js.map +1 -1
  74. package/dist/core/transaction.cjs +46 -46
  75. package/dist/core/transaction.cjs.map +1 -1
  76. package/dist/core/transaction.d.ts +7 -7
  77. package/dist/core/transaction.d.ts.map +1 -1
  78. package/dist/core/transaction.js +46 -46
  79. package/dist/core/transaction.js.map +1 -1
  80. package/dist/core/type_conversion.cjs +22 -22
  81. package/dist/core/type_conversion.cjs.map +1 -1
  82. package/dist/core/type_conversion.d.ts +3 -3
  83. package/dist/core/type_conversion.d.ts.map +1 -1
  84. package/dist/core/type_conversion.js +22 -22
  85. package/dist/core/type_conversion.js.map +1 -1
  86. package/dist/core/types.cjs +25 -25
  87. package/dist/core/types.cjs.map +1 -1
  88. package/dist/core/types.d.ts +7 -7
  89. package/dist/core/types.js +25 -25
  90. package/dist/core/types.js.map +1 -1
  91. package/dist/core/unauth_client.cjs +6 -4
  92. package/dist/core/unauth_client.cjs.map +1 -1
  93. package/dist/core/unauth_client.d.ts +4 -4
  94. package/dist/core/unauth_client.d.ts.map +1 -1
  95. package/dist/core/unauth_client.js +6 -4
  96. package/dist/core/unauth_client.js.map +1 -1
  97. package/dist/core/websocket_stream.cjs +22 -20
  98. package/dist/core/websocket_stream.cjs.map +1 -1
  99. package/dist/core/websocket_stream.d.ts +3 -3
  100. package/dist/core/websocket_stream.d.ts.map +1 -1
  101. package/dist/core/websocket_stream.js +22 -20
  102. package/dist/core/websocket_stream.js.map +1 -1
  103. package/dist/core/wire.d.ts +6 -6
  104. package/dist/core/wire.d.ts.map +1 -1
  105. package/dist/helpers/pl.cjs +19 -19
  106. package/dist/helpers/pl.cjs.map +1 -1
  107. package/dist/helpers/pl.d.ts +2 -2
  108. package/dist/helpers/pl.js +19 -19
  109. package/dist/helpers/pl.js.map +1 -1
  110. package/dist/helpers/poll.cjs +6 -6
  111. package/dist/helpers/poll.cjs.map +1 -1
  112. package/dist/helpers/poll.d.ts +4 -4
  113. package/dist/helpers/poll.d.ts.map +1 -1
  114. package/dist/helpers/poll.js +6 -6
  115. package/dist/helpers/poll.js.map +1 -1
  116. package/dist/helpers/retry_strategy.cjs +1 -1
  117. package/dist/helpers/retry_strategy.cjs.map +1 -1
  118. package/dist/helpers/retry_strategy.d.ts.map +1 -1
  119. package/dist/helpers/retry_strategy.js +1 -1
  120. package/dist/helpers/retry_strategy.js.map +1 -1
  121. package/dist/helpers/state_helpers.d.ts +2 -2
  122. package/dist/helpers/tx_helpers.cjs +2 -2
  123. package/dist/helpers/tx_helpers.cjs.map +1 -1
  124. package/dist/helpers/tx_helpers.d.ts +2 -2
  125. package/dist/helpers/tx_helpers.d.ts.map +1 -1
  126. package/dist/helpers/tx_helpers.js +2 -2
  127. package/dist/helpers/tx_helpers.js.map +1 -1
  128. package/dist/index.d.ts +16 -16
  129. package/dist/proto-grpc/google/protobuf/struct.d.ts +1 -1
  130. package/dist/proto-grpc/google/protobuf/struct.d.ts.map +1 -1
  131. package/dist/proto-rest/index.cjs +4 -5
  132. package/dist/proto-rest/index.cjs.map +1 -1
  133. package/dist/proto-rest/index.d.ts +4 -4
  134. package/dist/proto-rest/index.d.ts.map +1 -1
  135. package/dist/proto-rest/index.js +4 -5
  136. package/dist/proto-rest/index.js.map +1 -1
  137. package/dist/proto-rest/plapi.d.ts.map +1 -1
  138. package/dist/test/tcp-proxy.cjs +11 -10
  139. package/dist/test/tcp-proxy.cjs.map +1 -1
  140. package/dist/test/tcp-proxy.d.ts +1 -1
  141. package/dist/test/tcp-proxy.d.ts.map +1 -1
  142. package/dist/test/tcp-proxy.js +11 -10
  143. package/dist/test/tcp-proxy.js.map +1 -1
  144. package/dist/test/test_config.cjs +21 -17
  145. package/dist/test/test_config.cjs.map +1 -1
  146. package/dist/test/test_config.d.ts +6 -6
  147. package/dist/test/test_config.d.ts.map +1 -1
  148. package/dist/test/test_config.js +21 -17
  149. package/dist/test/test_config.js.map +1 -1
  150. package/dist/util/pl.cjs +1 -1
  151. package/dist/util/pl.cjs.map +1 -1
  152. package/dist/util/pl.js +1 -1
  153. package/dist/util/pl.js.map +1 -1
  154. package/dist/util/util.cjs +1 -1
  155. package/dist/util/util.cjs.map +1 -1
  156. package/dist/util/util.js +1 -1
  157. package/dist/util/util.js.map +1 -1
  158. package/package.json +23 -23
  159. package/src/core/PromiseTracker.ts +3 -4
  160. package/src/core/StatefulPromise.ts +17 -8
  161. package/src/core/abstract_stream.ts +3 -4
  162. package/src/core/advisory_locks.ts +1 -1
  163. package/src/core/auth.ts +2 -2
  164. package/src/core/cache.ts +1 -1
  165. package/src/core/client.test.ts +25 -21
  166. package/src/core/client.ts +54 -45
  167. package/src/core/config.test.ts +44 -44
  168. package/src/core/config.ts +49 -49
  169. package/src/core/connectivity.test.ts +69 -63
  170. package/src/core/default_client.ts +46 -46
  171. package/src/core/driver.ts +6 -6
  172. package/src/core/error.test.ts +5 -5
  173. package/src/core/error_resource.ts +3 -3
  174. package/src/core/errors.ts +39 -31
  175. package/src/core/final.ts +48 -55
  176. package/src/core/ll_client.test.ts +53 -36
  177. package/src/core/ll_client.ts +125 -81
  178. package/src/core/ll_transaction.test.ts +75 -49
  179. package/src/core/ll_transaction.ts +37 -35
  180. package/src/core/stat.ts +1 -1
  181. package/src/core/transaction.test.ts +65 -65
  182. package/src/core/transaction.ts +91 -84
  183. package/src/core/type_conversion.ts +30 -31
  184. package/src/core/types.test.ts +6 -6
  185. package/src/core/types.ts +35 -35
  186. package/src/core/unauth_client.test.ts +18 -14
  187. package/src/core/unauth_client.ts +14 -12
  188. package/src/core/websocket_stream.test.ts +52 -52
  189. package/src/core/websocket_stream.ts +41 -37
  190. package/src/core/wire.ts +10 -8
  191. package/src/helpers/pl.ts +22 -22
  192. package/src/helpers/poll.ts +13 -27
  193. package/src/helpers/retry_strategy.ts +2 -4
  194. package/src/helpers/rich_resource_types.test.ts +2 -2
  195. package/src/helpers/state_helpers.ts +3 -3
  196. package/src/helpers/tx_helpers.ts +9 -7
  197. package/src/index.ts +16 -16
  198. package/src/proto-grpc/google/protobuf/struct.ts +1 -1
  199. package/src/proto-rest/index.ts +17 -18
  200. package/src/proto-rest/plapi.ts +1472 -1472
  201. package/src/test/tcp-proxy.ts +55 -54
  202. package/src/test/test_config.test.ts +3 -3
  203. package/src/test/test_config.ts +51 -46
  204. package/src/util/pl.ts +1 -1
  205. package/src/util/util.test.ts +5 -5
  206. package/src/util/util.ts +1 -1
  207. package/dist/helpers/rich_resource_types.d.ts +0 -2
  208. package/dist/helpers/rich_resource_types.d.ts.map +0 -1
  209. package/dist/helpers/smart_accessors.d.ts +0 -2
  210. package/dist/helpers/smart_accessors.d.ts.map +0 -1
  211. package/src/helpers/rich_resource_types.ts +0 -84
  212. package/src/helpers/smart_accessors.ts +0 -146
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sources":["../../src/core/config.ts"],"sourcesContent":["import type { ProxySettings } from '@milaboratories/pl-http';\nimport type { ExponentialBackoffRetryOptions } from '@milaboratories/ts-helpers';\n\nexport const SUPPORTED_WIRE_PROTOCOLS = ['grpc', 'rest'] as const;\nexport type wireProtocol = (typeof SUPPORTED_WIRE_PROTOCOLS)[number];\n\n/** Base configuration structure for PL client */\nexport interface PlClientConfig {\n /** Port and host of remote pl server */\n hostAndPort: string;\n\n /** Type of wire connection (protocol server uses for communication) */\n wireProtocol?: wireProtocol;\n\n /** If set, client will expose a nested object under a field with name `alternative_root_${alternativeRoot}` as a\n * client root. */\n alternativeRoot?: string;\n\n /** If true, client will establish tls connection to the server, using default\n * CA of node instance. */\n // Not implementing custom ssl validation logic for now.\n // Implementing it in a correct way is really nontrivial thing,\n // real use-cases should be considered.\n ssl: boolean;\n\n /** Default timeout in milliseconds for unary calls, like ping and login. */\n defaultRequestTimeout: number;\n\n /** Default timeout in milliseconds for read-write transaction, should be\n * adjusted for long round-trip or low bandwidth connections. */\n defaultRWTransactionTimeout: number;\n /** Default timeout in milliseconds for read-only transaction, should be\n * adjusted for long round-trip or low bandwidth connections. */\n defaultROTransactionTimeout: number;\n\n /** Controls what TTL will be requested from the server, when new JWT token\n * is requested. */\n authTTLSeconds: number;\n /** If token is older than this time, it will be refreshed regardless of its\n * expiration time. */\n authMaxRefreshSeconds: number;\n\n /** Proxy server config to use for pl connection. */\n grpcProxy?: string | ProxySettings;\n /** Proxy server config to use for http connections of pl drivers, like file\n * downloading. */\n httpProxy?: string | ProxySettings;\n\n /** Username extracted from pl URL. Ignored by {@link PlClient}, picked up by {@link defaultPlClient}. */\n user?: string;\n /** Password extracted from pl URL. Ignored by {@link PlClient}, picked up by {@link defaultPlClient}. */\n password?: string;\n\n /** Artificial delay introduced after write transactions completion, to\n * somewhat throttle the load on pl. Delay introduced after sync, if requested. */\n txDelay: number;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n forceSync: boolean;\n\n /** Maximal number of bytes of resource state to cache */\n maxCacheBytes: number;\n\n //\n // Retry\n //\n\n /**\n * What type of backoff strategy to use in transaction retries\n * (pl uses optimistic transaction model with regular retries in write transactions)\n */\n retryBackoffAlgorithm: 'exponential' | 'linear';\n\n /** Maximal number of attempts in */\n retryMaxAttempts: number;\n\n /** Delay after first failed attempt, in ms. */\n retryInitialDelay: number;\n\n /** Each time delay will be multiplied by this number (1.5 means plus on 50% each attempt) */\n retryExponentialBackoffMultiplier: number;\n\n /** [used only for ] This value will be added to the delay from the previous step, in ms */\n retryLinearBackoffStep: number;\n\n /** Value from 0 to 1, determine level of randomness to introduce to the backoff delays sequence. (0 meaning no randomness) */\n retryJitter: number;\n}\n\nexport const DEFAULT_REQUEST_TIMEOUT = 5_000;\nexport const DEFAULT_RO_TX_TIMEOUT = 300_000;\nexport const DEFAULT_RW_TX_TIMEOUT = 60_000;\nexport const DEFAULT_TOKEN_TTL_SECONDS = 31 * 24 * 60 * 60;\nexport const DEFAULT_AUTH_MAX_REFRESH = 12 * 24 * 60 * 60;\n\nexport const DEFAULT_MAX_CACHE_BYTES = 128_000_000; // 128 Mb\n\nexport const DEFAULT_RETRY_BACKOFF_ALGORITHM = 'exponential';\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 21; // 1st attempt + 20 retries\nexport const DEFAULT_RETRY_INITIAL_DELAY = 20; // 20 ms * <jitter> of sleep after first failure\nexport const DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER = 1.5; // + 50% on each round\nexport const DEFAULT_RETRY_LINEAR_BACKOFF_STEP = 50; // + 50 ms\nexport const DEFAULT_RETRY_JITTER = 0.3; // 30%\n\nexport const DefaultRetryOptions: ExponentialBackoffRetryOptions = {\n type: 'exponentialBackoff',\n maxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,\n initialDelay: DEFAULT_RETRY_INITIAL_DELAY,\n backoffMultiplier: DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER,\n jitter: DEFAULT_RETRY_JITTER,\n};\n\ntype PlConfigOverrides = Partial<\n Pick<\n PlClientConfig,\n | 'ssl'\n | 'defaultRequestTimeout'\n | 'defaultROTransactionTimeout'\n | 'defaultRWTransactionTimeout'\n | 'httpProxy'\n | 'grpcProxy'\n >\n>;\n\nfunction parseInt(s: string | null | undefined): number | undefined {\n if (!s) return undefined;\n const num = Number(s);\n if (Number.isNaN(num)) throw new Error(`Can't parse number: ${s}`);\n return num;\n}\n\n/** Parses pl url and creates a config object that can be passed to\n * {@link PlClient} of {@link UnauthenticatedPlClient}. */\nexport function plAddressToConfig(\n address: string,\n overrides: PlConfigOverrides = {},\n): PlClientConfig {\n if (address.indexOf('://') === -1)\n // non-url address\n return {\n hostAndPort: address,\n ssl: false,\n defaultRequestTimeout: DEFAULT_REQUEST_TIMEOUT,\n defaultROTransactionTimeout: DEFAULT_RO_TX_TIMEOUT,\n defaultRWTransactionTimeout: DEFAULT_RW_TX_TIMEOUT,\n authTTLSeconds: DEFAULT_TOKEN_TTL_SECONDS,\n authMaxRefreshSeconds: DEFAULT_AUTH_MAX_REFRESH,\n txDelay: 0,\n forceSync: false,\n\n maxCacheBytes: DEFAULT_MAX_CACHE_BYTES,\n\n retryBackoffAlgorithm: DEFAULT_RETRY_BACKOFF_ALGORITHM,\n retryMaxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,\n retryInitialDelay: DEFAULT_RETRY_INITIAL_DELAY,\n retryExponentialBackoffMultiplier: DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER,\n retryLinearBackoffStep: DEFAULT_RETRY_LINEAR_BACKOFF_STEP,\n retryJitter: DEFAULT_RETRY_JITTER,\n\n ...overrides,\n };\n\n const url = new URL(address);\n\n if (\n url.protocol !== 'https:'\n && url.protocol !== 'http:'\n && url.protocol !== 'grpc:'\n && url.protocol !== 'tls:'\n )\n throw new Error(`Unexpected URL schema: ${url.protocol}`);\n\n if (url.pathname !== '/' && url.pathname !== '')\n throw new Error(`Unexpected URL path: ${url.pathname}`);\n\n let port = url.port;\n if (!port) {\n switch (url.protocol) {\n case 'http:':\n port = '80';\n break;\n case 'https:':\n port = '443';\n break;\n default:\n throw new Error(`Port must be specified explicitly for ${url.protocol} protocol.`);\n }\n }\n\n return {\n hostAndPort: `${url.hostname}:${port}`,\n alternativeRoot: url.searchParams.get('alternative-root') ?? undefined,\n ssl: url.protocol === 'https:' || url.protocol === 'tls:',\n\n wireProtocol: url.searchParams.get('wire-protocol') as wireProtocol ?? undefined,\n\n defaultRequestTimeout:\n parseInt(url.searchParams.get('request-timeout')) ?? DEFAULT_REQUEST_TIMEOUT,\n defaultROTransactionTimeout:\n parseInt(url.searchParams.get('ro-tx-timeout'))\n ?? parseInt(url.searchParams.get('tx-timeout'))\n ?? DEFAULT_RO_TX_TIMEOUT,\n defaultRWTransactionTimeout:\n parseInt(url.searchParams.get('rw-tx-timeout'))\n ?? parseInt(url.searchParams.get('tx-timeout'))\n ?? DEFAULT_RW_TX_TIMEOUT,\n authTTLSeconds: DEFAULT_TOKEN_TTL_SECONDS,\n authMaxRefreshSeconds: DEFAULT_AUTH_MAX_REFRESH,\n grpcProxy: url.searchParams.get('grpc-proxy') ?? undefined,\n httpProxy: url.searchParams.get('http-proxy') ?? undefined,\n user: url.username === '' ? undefined : url.username,\n password: url.password === '' ? undefined : url.password,\n txDelay: parseInt(url.searchParams.get('tx-delay')) ?? 0,\n forceSync: Boolean(url.searchParams.get('force-sync')),\n\n maxCacheBytes: parseInt(url.searchParams.get('max-cache-bytes')) ?? DEFAULT_MAX_CACHE_BYTES,\n\n retryBackoffAlgorithm: (url.searchParams.get('retry-backoff-algorithm')\n ?? DEFAULT_RETRY_BACKOFF_ALGORITHM) as any,\n retryMaxAttempts:\n parseInt(url.searchParams.get('retry-max-attempts')) ?? DEFAULT_RETRY_MAX_ATTEMPTS,\n retryInitialDelay:\n parseInt(url.searchParams.get('retry-initial-delay')) ?? DEFAULT_RETRY_INITIAL_DELAY,\n retryExponentialBackoffMultiplier:\n parseInt(url.searchParams.get('retry-exp-backoff-multiplier'))\n ?? DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER,\n retryLinearBackoffStep:\n parseInt(url.searchParams.get('retry-linear-backoff-step'))\n ?? DEFAULT_RETRY_LINEAR_BACKOFF_STEP,\n retryJitter: parseInt(url.searchParams.get('retry-backoff-jitter')) ?? DEFAULT_RETRY_JITTER,\n\n ...overrides,\n };\n}\n\n/**\n * Authorization data / JWT Token.\n * Absent JWT Token tells the client to connect as anonymous user.\n */\nexport interface AuthInformation {\n /** Absent token means anonymous access */\n jwtToken?: string;\n}\n\nexport const AnonymousAuthInformation: AuthInformation = {};\n\n/** Authorization related settings to pass to {@link PlClient}. */\nexport interface AuthOps {\n /** Initial authorization information */\n authInformation: AuthInformation;\n /** Will be executed after successful authorization information refresh */\n readonly onUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n readonly onAuthError?: () => void;\n /** Will be executed if error encountered during token update */\n readonly onUpdateError?: (error: unknown) => void;\n}\n\n/** Connection status. */\nexport type PlConnectionStatus = 'OK' | 'Disconnected' | 'Unauthenticated';\n\n/** Listener that will be called each time connection status changes. */\nexport type PlConnectionStatusListener = (status: PlConnectionStatus) => void;\n"],"names":[],"mappings":"MAGa,wBAAwB,GAAG,CAAC,MAAM,EAAE,MAAM;AAsFhD,MAAM,uBAAuB,GAAG;AAChC,MAAM,qBAAqB,GAAG;AAC9B,MAAM,qBAAqB,GAAG;AAC9B,MAAM,yBAAyB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;AACjD,MAAM,wBAAwB,GAAG,EAAE,GAAG,EAAE,GAAG,EAA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Y,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,IAAI,uBAAuB;QAE3F,qBAAqB,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,yBAAyB;AACjE,eAAA,+BAA+B,CAAQ;AAC5C,QAAA,gBAAgB,EACd,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC,IAAI,0BAA0B;AACpF,QAAA,iBAAiB,EACf,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,IAAI,2BAA2B;QACtF,iCAAiC,EAC/B,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,8BAA8B,CAAC;eAC1D,4CAA4C;QACjD,sBAAsB,EACpB,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,2BAA2B,CAAC;eACvD,iCAAiC;AACtC,QAAA,WAAW,EAAE,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,IAAI,oBAAoB;AAE3F,QAAA,GAAG,SAAS;KACb;AACH;AAWO,MAAM,wBAAwB,GAAoB;;;;"}
1
+ {"version":3,"file":"config.js","sources":["../../src/core/config.ts"],"sourcesContent":["import type { ProxySettings } from \"@milaboratories/pl-http\";\nimport type { ExponentialBackoffRetryOptions } from \"@milaboratories/ts-helpers\";\n\nexport const SUPPORTED_WIRE_PROTOCOLS = [\"grpc\", \"rest\"] as const;\nexport type wireProtocol = (typeof SUPPORTED_WIRE_PROTOCOLS)[number];\n\n/** Base configuration structure for PL client */\nexport interface PlClientConfig {\n /** Port and host of remote pl server */\n hostAndPort: string;\n\n /** Type of wire connection (protocol server uses for communication) */\n wireProtocol?: wireProtocol;\n\n /** If set, client will expose a nested object under a field with name `alternative_root_${alternativeRoot}` as a\n * client root. */\n alternativeRoot?: string;\n\n /** If true, client will establish tls connection to the server, using default\n * CA of node instance. */\n // Not implementing custom ssl validation logic for now.\n // Implementing it in a correct way is really nontrivial thing,\n // real use-cases should be considered.\n ssl: boolean;\n\n /** Default timeout in milliseconds for unary calls, like ping and login. */\n defaultRequestTimeout: number;\n\n /** Default timeout in milliseconds for read-write transaction, should be\n * adjusted for long round-trip or low bandwidth connections. */\n defaultRWTransactionTimeout: number;\n /** Default timeout in milliseconds for read-only transaction, should be\n * adjusted for long round-trip or low bandwidth connections. */\n defaultROTransactionTimeout: number;\n\n /** Controls what TTL will be requested from the server, when new JWT token\n * is requested. */\n authTTLSeconds: number;\n /** If token is older than this time, it will be refreshed regardless of its\n * expiration time. */\n authMaxRefreshSeconds: number;\n\n /** Proxy server config to use for pl connection. */\n grpcProxy?: string | ProxySettings;\n /** Proxy server config to use for http connections of pl drivers, like file\n * downloading. */\n httpProxy?: string | ProxySettings;\n\n /** Username extracted from pl URL. Ignored by {@link PlClient}, picked up by {@link defaultPlClient}. */\n user?: string;\n /** Password extracted from pl URL. Ignored by {@link PlClient}, picked up by {@link defaultPlClient}. */\n password?: string;\n\n /** Artificial delay introduced after write transactions completion, to\n * somewhat throttle the load on pl. Delay introduced after sync, if requested. */\n txDelay: number;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n forceSync: boolean;\n\n /** Maximal number of bytes of resource state to cache */\n maxCacheBytes: number;\n\n //\n // Retry\n //\n\n /**\n * What type of backoff strategy to use in transaction retries\n * (pl uses optimistic transaction model with regular retries in write transactions)\n */\n retryBackoffAlgorithm: \"exponential\" | \"linear\";\n\n /** Maximal number of attempts in */\n retryMaxAttempts: number;\n\n /** Delay after first failed attempt, in ms. */\n retryInitialDelay: number;\n\n /** Each time delay will be multiplied by this number (1.5 means plus on 50% each attempt) */\n retryExponentialBackoffMultiplier: number;\n\n /** [used only for ] This value will be added to the delay from the previous step, in ms */\n retryLinearBackoffStep: number;\n\n /** Value from 0 to 1, determine level of randomness to introduce to the backoff delays sequence. (0 meaning no randomness) */\n retryJitter: number;\n}\n\nexport const DEFAULT_REQUEST_TIMEOUT = 5_000;\nexport const DEFAULT_RO_TX_TIMEOUT = 300_000;\nexport const DEFAULT_RW_TX_TIMEOUT = 60_000;\nexport const DEFAULT_TOKEN_TTL_SECONDS = 31 * 24 * 60 * 60;\nexport const DEFAULT_AUTH_MAX_REFRESH = 12 * 24 * 60 * 60;\n\nexport const DEFAULT_MAX_CACHE_BYTES = 128_000_000; // 128 Mb\n\nexport const DEFAULT_RETRY_BACKOFF_ALGORITHM = \"exponential\";\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 21; // 1st attempt + 20 retries\nexport const DEFAULT_RETRY_INITIAL_DELAY = 20; // 20 ms * <jitter> of sleep after first failure\nexport const DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER = 1.5; // + 50% on each round\nexport const DEFAULT_RETRY_LINEAR_BACKOFF_STEP = 50; // + 50 ms\nexport const DEFAULT_RETRY_JITTER = 0.3; // 30%\n\nexport const DefaultRetryOptions: ExponentialBackoffRetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,\n initialDelay: DEFAULT_RETRY_INITIAL_DELAY,\n backoffMultiplier: DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER,\n jitter: DEFAULT_RETRY_JITTER,\n};\n\ntype PlConfigOverrides = Partial<\n Pick<\n PlClientConfig,\n | \"ssl\"\n | \"defaultRequestTimeout\"\n | \"defaultROTransactionTimeout\"\n | \"defaultRWTransactionTimeout\"\n | \"httpProxy\"\n | \"grpcProxy\"\n >\n>;\n\nfunction parseInt(s: string | null | undefined): number | undefined {\n if (!s) return undefined;\n const num = Number(s);\n if (Number.isNaN(num)) throw new Error(`Can't parse number: ${s}`);\n return num;\n}\n\n/** Parses pl url and creates a config object that can be passed to\n * {@link PlClient} of {@link UnauthenticatedPlClient}. */\nexport function plAddressToConfig(\n address: string,\n overrides: PlConfigOverrides = {},\n): PlClientConfig {\n if (address.indexOf(\"://\") === -1)\n // non-url address\n return {\n hostAndPort: address,\n ssl: false,\n defaultRequestTimeout: DEFAULT_REQUEST_TIMEOUT,\n defaultROTransactionTimeout: DEFAULT_RO_TX_TIMEOUT,\n defaultRWTransactionTimeout: DEFAULT_RW_TX_TIMEOUT,\n authTTLSeconds: DEFAULT_TOKEN_TTL_SECONDS,\n authMaxRefreshSeconds: DEFAULT_AUTH_MAX_REFRESH,\n txDelay: 0,\n forceSync: false,\n\n maxCacheBytes: DEFAULT_MAX_CACHE_BYTES,\n\n retryBackoffAlgorithm: DEFAULT_RETRY_BACKOFF_ALGORITHM,\n retryMaxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,\n retryInitialDelay: DEFAULT_RETRY_INITIAL_DELAY,\n retryExponentialBackoffMultiplier: DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER,\n retryLinearBackoffStep: DEFAULT_RETRY_LINEAR_BACKOFF_STEP,\n retryJitter: DEFAULT_RETRY_JITTER,\n\n ...overrides,\n };\n\n const url = new URL(address);\n\n if (\n url.protocol !== \"https:\" &&\n url.protocol !== \"http:\" &&\n url.protocol !== \"grpc:\" &&\n url.protocol !== \"tls:\"\n )\n throw new Error(`Unexpected URL schema: ${url.protocol}`);\n\n if (url.pathname !== \"/\" && url.pathname !== \"\")\n throw new Error(`Unexpected URL path: ${url.pathname}`);\n\n let port = url.port;\n if (!port) {\n switch (url.protocol) {\n case \"http:\":\n port = \"80\";\n break;\n case \"https:\":\n port = \"443\";\n break;\n default:\n throw new Error(`Port must be specified explicitly for ${url.protocol} protocol.`);\n }\n }\n\n return {\n hostAndPort: `${url.hostname}:${port}`,\n alternativeRoot: url.searchParams.get(\"alternative-root\") ?? undefined,\n ssl: url.protocol === \"https:\" || url.protocol === \"tls:\",\n\n wireProtocol: (url.searchParams.get(\"wire-protocol\") as wireProtocol) ?? undefined,\n\n defaultRequestTimeout:\n parseInt(url.searchParams.get(\"request-timeout\")) ?? DEFAULT_REQUEST_TIMEOUT,\n defaultROTransactionTimeout:\n parseInt(url.searchParams.get(\"ro-tx-timeout\")) ??\n parseInt(url.searchParams.get(\"tx-timeout\")) ??\n DEFAULT_RO_TX_TIMEOUT,\n defaultRWTransactionTimeout:\n parseInt(url.searchParams.get(\"rw-tx-timeout\")) ??\n parseInt(url.searchParams.get(\"tx-timeout\")) ??\n DEFAULT_RW_TX_TIMEOUT,\n authTTLSeconds: DEFAULT_TOKEN_TTL_SECONDS,\n authMaxRefreshSeconds: DEFAULT_AUTH_MAX_REFRESH,\n grpcProxy: url.searchParams.get(\"grpc-proxy\") ?? undefined,\n httpProxy: url.searchParams.get(\"http-proxy\") ?? undefined,\n user: url.username === \"\" ? undefined : url.username,\n password: url.password === \"\" ? undefined : url.password,\n txDelay: parseInt(url.searchParams.get(\"tx-delay\")) ?? 0,\n forceSync: Boolean(url.searchParams.get(\"force-sync\")),\n\n maxCacheBytes: parseInt(url.searchParams.get(\"max-cache-bytes\")) ?? DEFAULT_MAX_CACHE_BYTES,\n\n retryBackoffAlgorithm: (url.searchParams.get(\"retry-backoff-algorithm\") ??\n DEFAULT_RETRY_BACKOFF_ALGORITHM) as any,\n retryMaxAttempts:\n parseInt(url.searchParams.get(\"retry-max-attempts\")) ?? DEFAULT_RETRY_MAX_ATTEMPTS,\n retryInitialDelay:\n parseInt(url.searchParams.get(\"retry-initial-delay\")) ?? DEFAULT_RETRY_INITIAL_DELAY,\n retryExponentialBackoffMultiplier:\n parseInt(url.searchParams.get(\"retry-exp-backoff-multiplier\")) ??\n DEFAULT_RETRY_EXPONENTIAL_BACKOFF_MULTIPLIER,\n retryLinearBackoffStep:\n parseInt(url.searchParams.get(\"retry-linear-backoff-step\")) ??\n DEFAULT_RETRY_LINEAR_BACKOFF_STEP,\n retryJitter: parseInt(url.searchParams.get(\"retry-backoff-jitter\")) ?? DEFAULT_RETRY_JITTER,\n\n ...overrides,\n };\n}\n\n/**\n * Authorization data / JWT Token.\n * Absent JWT Token tells the client to connect as anonymous user.\n */\nexport interface AuthInformation {\n /** Absent token means anonymous access */\n jwtToken?: string;\n}\n\nexport const AnonymousAuthInformation: AuthInformation = {};\n\n/** Authorization related settings to pass to {@link PlClient}. */\nexport interface AuthOps {\n /** Initial authorization information */\n authInformation: AuthInformation;\n /** Will be executed after successful authorization information refresh */\n readonly onUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n readonly onAuthError?: () => void;\n /** Will be executed if error encountered during token update */\n readonly onUpdateError?: (error: unknown) => void;\n}\n\n/** Connection status. */\nexport type PlConnectionStatus = \"OK\" | \"Disconnected\" | \"Unauthenticated\";\n\n/** Listener that will be called each time connection status changes. */\nexport type PlConnectionStatusListener = (status: PlConnectionStatus) => void;\n"],"names":[],"mappings":"MAGa,wBAAwB,GAAG,CAAC,MAAM,EAAE,MAAM;AAsFhD,MAAM,uBAAuB,GAAG;AAChC,MAAM,qBAAqB,GAAG;AAC9B,MAAM,qBAAqB,GAAG;AAC9B,MAAM,yBAAyB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;AACjD,MAAM,wBAAwB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;AAEhD,MAAM,uBAAuB,GAAG,YAAY;AAE5C,MAAM,+BAA+B,GAAG;AACxC,MAAM,0BAA0B,GAAG,GAAG;AACtC,MAAM,2BAA2B,GAAG,GAAG;AACvC,MAAM,4CAA4C,GAAG,IAAI;AACzD,MAAM,iCAAiC,GAAG,GAAG;AAC7C,MAAM,oBAAoB,GAAG,IAAI;AAEjC,MAAM,mBAAmB,GAAmC;AACjE,IAAA,IAAI,EAAE,oBAAoB;AAC1B,IAAA,WAAW,EAAE,0BAA0B;AACvC,IAAA,YAAY,EAAE,2BAA2B;AACzC,IAAA,iBAAiB,EAAE,4CAA4C;AAC/D,IAAA,MAAM,EAAE,oBAAoB;;AAe9B,SAAS,QAAQ,CAAC,CAA4B,EAAA;AAC5C,IAAA,IAAI,CAAC,CAAC;AAAE,QAAA,OAAO,SAAS;AACxB,IAAA,MAAM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,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;YAC3D,iCAAiC;AACnC,QAAA,WAAW,EAAE,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,IAAI,oBAAoB;AAE3F,QAAA,GAAG,SAAS;KACb;AACH;AAWO,MAAM,wBAAwB,GAAoB;;;;"}
@@ -32,34 +32,34 @@ function _interopNamespaceDefault(e) {
32
32
  var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os);
33
33
  var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
34
34
 
35
- const CONFIG_FILE_LOCAL_JSON = 'pl.json';
36
- const CONFIG_FILE_USER_JSON = path__namespace.join(os__namespace.homedir(), '.pl.json');
37
- const CONFIG_FILE_LOCAL_YAML = 'pl.yaml';
38
- const CONFIG_FILE_USER_YAML = path__namespace.join(os__namespace.homedir(), '.pl.yaml');
35
+ const CONFIG_FILE_LOCAL_JSON = "pl.json";
36
+ const CONFIG_FILE_USER_JSON = path__namespace.join(os__namespace.homedir(), ".pl.json");
37
+ const CONFIG_FILE_LOCAL_YAML = "pl.yaml";
38
+ const CONFIG_FILE_USER_YAML = path__namespace.join(os__namespace.homedir(), ".pl.yaml");
39
39
  const CONF_FILE_SEQUENCE = [
40
40
  CONFIG_FILE_LOCAL_JSON,
41
41
  CONFIG_FILE_LOCAL_YAML,
42
42
  CONFIG_FILE_USER_JSON,
43
43
  CONFIG_FILE_USER_YAML,
44
44
  ];
45
- const AUTH_DATA_FILE = '.pl_auth.json';
45
+ const AUTH_DATA_FILE = ".pl_auth.json";
46
46
  const FILE_CONFIG_OVERRIDE_FIELDS = [
47
- 'grpcProxy',
48
- 'httpProxy',
49
- 'user',
50
- 'password',
51
- 'alternativeRoot',
52
- 'defaultROTransactionTimeout',
53
- 'defaultRWTransactionTimeout',
54
- 'defaultRequestTimeout',
55
- 'authTTLSeconds',
56
- 'authMaxRefreshSeconds',
47
+ "grpcProxy",
48
+ "httpProxy",
49
+ "user",
50
+ "password",
51
+ "alternativeRoot",
52
+ "defaultROTransactionTimeout",
53
+ "defaultRWTransactionTimeout",
54
+ "defaultRequestTimeout",
55
+ "authTTLSeconds",
56
+ "authMaxRefreshSeconds",
57
57
  ];
58
58
  function tryGetFileConfig() {
59
59
  for (const confPath of CONF_FILE_SEQUENCE)
60
60
  if (fs.existsSync(confPath)) {
61
- const fileContent = fs.readFileSync(confPath, { encoding: 'utf-8' });
62
- if (confPath.endsWith('json'))
61
+ const fileContent = fs.readFileSync(confPath, { encoding: "utf-8" });
62
+ if (confPath.endsWith("json"))
63
63
  return [JSON.parse(fileContent), confPath];
64
64
  else
65
65
  return [YAML.parse(fileContent), confPath];
@@ -72,7 +72,7 @@ function saveAuthInfoCallback(confHash, authMaxRefreshSeconds) {
72
72
  confHash,
73
73
  authInformation: newAuthInfo,
74
74
  expiration: auth.inferAuthRefreshTime(newAuthInfo, authMaxRefreshSeconds),
75
- })), 'utf8');
75
+ })), "utf8");
76
76
  };
77
77
  }
78
78
  const cleanAuthInfoCallback = () => {
@@ -97,18 +97,18 @@ async function defaultPlClient() {
97
97
  }
98
98
  }
99
99
  if (config$1 === undefined)
100
- throw new Error('Can\'t find configuration to create default platform client.');
100
+ throw new Error("Can't find configuration to create default platform client.");
101
101
  if (process.env.PL_USER !== undefined)
102
102
  config$1.user = process.env.PL_USER;
103
103
  if (process.env.PL_PASSWORD !== undefined)
104
104
  config$1.user = process.env.PL_PASSWORD;
105
- const confHash = node_crypto.createHash('sha256')
105
+ const confHash = node_crypto.createHash("sha256")
106
106
  .update(Buffer.from(canonicalize(config$1)))
107
- .digest('base64');
107
+ .digest("base64");
108
108
  let authInformation = undefined;
109
109
  // try recover auth information from cache
110
110
  if (fs.existsSync(AUTH_DATA_FILE)) {
111
- const cache = JSON.parse(fs.readFileSync(AUTH_DATA_FILE, { encoding: 'utf-8' }));
111
+ const cache = JSON.parse(fs.readFileSync(AUTH_DATA_FILE, { encoding: "utf-8" }));
112
112
  if (cache.confHash === confHash && cache.expiration > Date.now())
113
113
  authInformation = cache.authInformation;
114
114
  }
@@ -128,7 +128,7 @@ async function defaultPlClient() {
128
128
  confHash,
129
129
  authInformation,
130
130
  expiration: auth.inferAuthRefreshTime(authInformation, config$1.authMaxRefreshSeconds),
131
- })), 'utf8');
131
+ })), "utf8");
132
132
  }
133
133
  return await client.PlClient.init(config$1, {
134
134
  authInformation,
@@ -1 +1 @@
1
- {"version":3,"file":"default_client.cjs","sources":["../../src/core/default_client.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { AuthInformation, PlClientConfig } from './config';\nimport { plAddressToConfig } from './config';\nimport canonicalize from 'canonicalize';\nimport YAML from 'yaml';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { UnauthenticatedPlClient } from './unauth_client';\nimport { PlClient } from './client';\nimport { createHash } from 'node:crypto';\nimport { inferAuthRefreshTime } from './auth';\n\nconst CONFIG_FILE_LOCAL_JSON = 'pl.json';\nconst CONFIG_FILE_USER_JSON = path.join(os.homedir(), '.pl.json');\nconst CONFIG_FILE_LOCAL_YAML = 'pl.yaml';\nconst CONFIG_FILE_USER_YAML = path.join(os.homedir(), '.pl.yaml');\nconst CONF_FILE_SEQUENCE = [\n CONFIG_FILE_LOCAL_JSON,\n CONFIG_FILE_LOCAL_YAML,\n CONFIG_FILE_USER_JSON,\n CONFIG_FILE_USER_YAML,\n];\n\nconst AUTH_DATA_FILE = '.pl_auth.json';\n\ntype FileConfigOverrideFields =\n | 'grpcProxy'\n | 'httpProxy'\n | 'user'\n | 'password'\n | 'alternativeRoot'\n | 'defaultROTransactionTimeout'\n | 'defaultRWTransactionTimeout'\n | 'defaultRequestTimeout'\n | 'authTTLSeconds'\n | 'authMaxRefreshSeconds';\nconst FILE_CONFIG_OVERRIDE_FIELDS: FileConfigOverrideFields[] = [\n 'grpcProxy',\n 'httpProxy',\n 'user',\n 'password',\n 'alternativeRoot',\n 'defaultROTransactionTimeout',\n 'defaultRWTransactionTimeout',\n 'defaultRequestTimeout',\n 'authTTLSeconds',\n 'authMaxRefreshSeconds',\n];\n\ntype PlConfigFile = {\n address: string;\n} & Partial<Pick<PlClientConfig, FileConfigOverrideFields>>;\n\ninterface AuthCache {\n /** To check if config changed */\n confHash: string;\n expiration: number;\n authInformation: AuthInformation;\n}\n\nexport function tryGetFileConfig(): [PlConfigFile, string] | undefined {\n for (const confPath of CONF_FILE_SEQUENCE)\n if (fs.existsSync(confPath)) {\n const fileContent = fs.readFileSync(confPath, { encoding: 'utf-8' });\n if (confPath.endsWith('json')) return [JSON.parse(fileContent) as PlConfigFile, confPath];\n else return [YAML.parse(fileContent) as PlConfigFile, confPath];\n }\n return undefined;\n}\n\nfunction saveAuthInfoCallback(\n confHash: string,\n authMaxRefreshSeconds: number,\n): (newAuthInfo: AuthInformation) => void {\n return (newAuthInfo) => {\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation: newAuthInfo,\n expiration: inferAuthRefreshTime(newAuthInfo, authMaxRefreshSeconds),\n } as AuthCache),\n ),\n 'utf8',\n );\n };\n}\n\nconst cleanAuthInfoCallback = () => {\n fs.rmSync(AUTH_DATA_FILE);\n};\n\n/** Uses default algorithm to construct a pl client from the environment */\nexport async function defaultPlClient(): Promise<PlClient> {\n let config: PlClientConfig | undefined = undefined;\n if (process.env.PL_ADDRESS !== undefined) {\n config = plAddressToConfig(process.env.PL_ADDRESS);\n } else {\n const fromFile = tryGetFileConfig();\n if (fromFile !== undefined) {\n const [fileConfig, configPath] = fromFile;\n const address = notEmpty(fileConfig.address, `no pl address in file: ${configPath}`);\n config = plAddressToConfig(address);\n // applying overrides\n for (const field of FILE_CONFIG_OVERRIDE_FIELDS)\n if (fileConfig[field] !== undefined) (config as any)[field] = fileConfig[field];\n }\n }\n\n if (config === undefined)\n throw new Error('Can\\'t find configuration to create default platform client.');\n\n if (process.env.PL_USER !== undefined) config.user = process.env.PL_USER;\n\n if (process.env.PL_PASSWORD !== undefined) config.user = process.env.PL_PASSWORD;\n\n const confHash = createHash('sha256')\n .update(Buffer.from(canonicalize(config)!))\n .digest('base64');\n\n let authInformation: AuthInformation | undefined = undefined;\n\n // try recover auth information from cache\n if (fs.existsSync(AUTH_DATA_FILE)) {\n const cache: AuthCache = JSON.parse(fs.readFileSync(AUTH_DATA_FILE, { encoding: 'utf-8' }));\n if (cache.confHash === confHash && cache.expiration > Date.now())\n authInformation = cache.authInformation;\n }\n\n if (authInformation === undefined) {\n const client = await UnauthenticatedPlClient.build(config);\n\n if (await client.requireAuth()) {\n if (config.user === undefined || config.password === undefined)\n throw new Error(`No auth information for found to authenticate with PL server.`);\n authInformation = await client.login(config.user, config.password);\n } else {\n // No authorization is required\n authInformation = {};\n }\n\n // saving cache\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation,\n expiration: inferAuthRefreshTime(authInformation, config.authMaxRefreshSeconds),\n } as AuthCache),\n ),\n 'utf8',\n );\n }\n\n return await PlClient.init(config, {\n authInformation,\n onUpdate: (_newAuthInfo) => saveAuthInfoCallback(confHash, config.authMaxRefreshSeconds),\n onUpdateError: cleanAuthInfoCallback,\n onAuthError: cleanAuthInfoCallback,\n });\n}\n"],"names":["path","os","inferAuthRefreshTime","config","plAddressToConfig","notEmpty","createHash","UnauthenticatedPlClient","PlClient"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAGA,eAAI,CAAC,IAAI,CAACC,aAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAGD,eAAI,CAAC,IAAI,CAACC,aAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,kBAAk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ACJ;;;;;"}
1
+ {"version":3,"file":"default_client.cjs","sources":["../../src/core/default_client.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { AuthInformation, PlClientConfig } from \"./config\";\nimport { plAddressToConfig } from \"./config\";\nimport canonicalize from \"canonicalize\";\nimport YAML from \"yaml\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { UnauthenticatedPlClient } from \"./unauth_client\";\nimport { PlClient } from \"./client\";\nimport { createHash } from \"node:crypto\";\nimport { inferAuthRefreshTime } from \"./auth\";\n\nconst CONFIG_FILE_LOCAL_JSON = \"pl.json\";\nconst CONFIG_FILE_USER_JSON = path.join(os.homedir(), \".pl.json\");\nconst CONFIG_FILE_LOCAL_YAML = \"pl.yaml\";\nconst CONFIG_FILE_USER_YAML = path.join(os.homedir(), \".pl.yaml\");\nconst CONF_FILE_SEQUENCE = [\n CONFIG_FILE_LOCAL_JSON,\n CONFIG_FILE_LOCAL_YAML,\n CONFIG_FILE_USER_JSON,\n CONFIG_FILE_USER_YAML,\n];\n\nconst AUTH_DATA_FILE = \".pl_auth.json\";\n\ntype FileConfigOverrideFields =\n | \"grpcProxy\"\n | \"httpProxy\"\n | \"user\"\n | \"password\"\n | \"alternativeRoot\"\n | \"defaultROTransactionTimeout\"\n | \"defaultRWTransactionTimeout\"\n | \"defaultRequestTimeout\"\n | \"authTTLSeconds\"\n | \"authMaxRefreshSeconds\";\nconst FILE_CONFIG_OVERRIDE_FIELDS: FileConfigOverrideFields[] = [\n \"grpcProxy\",\n \"httpProxy\",\n \"user\",\n \"password\",\n \"alternativeRoot\",\n \"defaultROTransactionTimeout\",\n \"defaultRWTransactionTimeout\",\n \"defaultRequestTimeout\",\n \"authTTLSeconds\",\n \"authMaxRefreshSeconds\",\n];\n\ntype PlConfigFile = {\n address: string;\n} & Partial<Pick<PlClientConfig, FileConfigOverrideFields>>;\n\ninterface AuthCache {\n /** To check if config changed */\n confHash: string;\n expiration: number;\n authInformation: AuthInformation;\n}\n\nexport function tryGetFileConfig(): [PlConfigFile, string] | undefined {\n for (const confPath of CONF_FILE_SEQUENCE)\n if (fs.existsSync(confPath)) {\n const fileContent = fs.readFileSync(confPath, { encoding: \"utf-8\" });\n if (confPath.endsWith(\"json\")) return [JSON.parse(fileContent) as PlConfigFile, confPath];\n else return [YAML.parse(fileContent) as PlConfigFile, confPath];\n }\n return undefined;\n}\n\nfunction saveAuthInfoCallback(\n confHash: string,\n authMaxRefreshSeconds: number,\n): (newAuthInfo: AuthInformation) => void {\n return (newAuthInfo) => {\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation: newAuthInfo,\n expiration: inferAuthRefreshTime(newAuthInfo, authMaxRefreshSeconds),\n } as AuthCache),\n ),\n \"utf8\",\n );\n };\n}\n\nconst cleanAuthInfoCallback = () => {\n fs.rmSync(AUTH_DATA_FILE);\n};\n\n/** Uses default algorithm to construct a pl client from the environment */\nexport async function defaultPlClient(): Promise<PlClient> {\n let config: PlClientConfig | undefined = undefined;\n if (process.env.PL_ADDRESS !== undefined) {\n config = plAddressToConfig(process.env.PL_ADDRESS);\n } else {\n const fromFile = tryGetFileConfig();\n if (fromFile !== undefined) {\n const [fileConfig, configPath] = fromFile;\n const address = notEmpty(fileConfig.address, `no pl address in file: ${configPath}`);\n config = plAddressToConfig(address);\n // applying overrides\n for (const field of FILE_CONFIG_OVERRIDE_FIELDS)\n if (fileConfig[field] !== undefined) (config as any)[field] = fileConfig[field];\n }\n }\n\n if (config === undefined)\n throw new Error(\"Can't find configuration to create default platform client.\");\n\n if (process.env.PL_USER !== undefined) config.user = process.env.PL_USER;\n\n if (process.env.PL_PASSWORD !== undefined) config.user = process.env.PL_PASSWORD;\n\n const confHash = createHash(\"sha256\")\n .update(Buffer.from(canonicalize(config)!))\n .digest(\"base64\");\n\n let authInformation: AuthInformation | undefined = undefined;\n\n // try recover auth information from cache\n if (fs.existsSync(AUTH_DATA_FILE)) {\n const cache: AuthCache = JSON.parse(fs.readFileSync(AUTH_DATA_FILE, { encoding: \"utf-8\" }));\n if (cache.confHash === confHash && cache.expiration > Date.now())\n authInformation = cache.authInformation;\n }\n\n if (authInformation === undefined) {\n const client = await UnauthenticatedPlClient.build(config);\n\n if (await client.requireAuth()) {\n if (config.user === undefined || config.password === undefined)\n throw new Error(`No auth information for found to authenticate with PL server.`);\n authInformation = await client.login(config.user, config.password);\n } else {\n // No authorization is required\n authInformation = {};\n }\n\n // saving cache\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation,\n expiration: inferAuthRefreshTime(authInformation, config.authMaxRefreshSeconds),\n } as AuthCache),\n ),\n \"utf8\",\n );\n }\n\n return await PlClient.init(config, {\n authInformation,\n onUpdate: (_newAuthInfo) => saveAuthInfoCallback(confHash, config.authMaxRefreshSeconds),\n onUpdateError: cleanAuthInfoCallback,\n onAuthError: cleanAuthInfoCallback,\n });\n}\n"],"names":["path","os","inferAuthRefreshTime","config","plAddressToConfig","notEmpty","createHash","UnauthenticatedPlClient","PlClient"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAGA,eAAI,CAAC,IAAI,CAACC,aAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAGD,eAAI,CAAC,IAAI,CAACC,aAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,kBAAkB,GAAG;IACzB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;CACtB;AAED,MAAM,cAAc,GAAG,eAAe;AAatC,MAAM,2BAA2B,GAA+B;IAC9D,WAAW;IACX,WAAW;IACX,MAAM;IACN,UAAU;IACV,iBAAiB;IACjB,6BAA6B;IAC7B,6BA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AC,GAAG,EAAE;AAC9D,YAAA,eAAe,GAAG,KAAK,CAAC,eAAe;IAC3C;AAEA,IAAA,IAAI,eAAe,KAAK,SAAS,EAAE;QACjC,MAAM,MAAM,GAAG,MAAMI,qCAAuB,CAAC,KAAK,CAACJ,QAAM,CAAC;AAE1D,QAAA,IAAI,MAAM,MAAM,CAAC,WAAW,EAAE,EAAE;YAC9B,IAAIA,QAAM,CAAC,IAAI,KAAK,SAAS,IAAIA,QAAM,CAAC,QAAQ,KAAK,SAAS;AAC5D,gBAAA,MAAM,IAAI,KAAK,CAAC,CAAA,6DAAA,CAA+D,CAAC;AAClF,YAAA,eAAe,GAAG,MAAM,MAAM,CAAC,KAAK,CAACA,QAAM,CAAC,IAAI,EAAEA,QAAM,CAAC,QAAQ,CAAC;QACpE;aAAO;;YAEL,eAAe,GAAG,EAAE;QACtB;;AAGA,QAAA,EAAE,CAAC,aAAa,CACd,cAAc,EACd,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;YACb,QAAQ;YACR,eAAe;YACf,UAAU,EAAED,yBAAoB,CAAC,eAAe,EAAEC,QAAM,CAAC,qBAAqB,CAAC;AACnE,SAAA,CAAC,CAChB,EACD,MAAM,CACP;IACH;AAEA,IAAA,OAAO,MAAMK,eAAQ,CAAC,IAAI,CAACL,QAAM,EAAE;QACjC,eAAe;AACf,QAAA,QAAQ,EAAE,CAAC,YAAY,KAAK,oBAAoB,CAAC,QAAQ,EAAEA,QAAM,CAAC,qBAAqB,CAAC;AACxF,QAAA,aAAa,EAAE,qBAAqB;AACpC,QAAA,WAAW,EAAE,qBAAqB;AACnC,KAAA,CAAC;AACJ;;;;;"}
@@ -1,6 +1,6 @@
1
- import type { PlClientConfig } from './config';
2
- import { PlClient } from './client';
3
- type FileConfigOverrideFields = 'grpcProxy' | 'httpProxy' | 'user' | 'password' | 'alternativeRoot' | 'defaultROTransactionTimeout' | 'defaultRWTransactionTimeout' | 'defaultRequestTimeout' | 'authTTLSeconds' | 'authMaxRefreshSeconds';
1
+ import type { PlClientConfig } from "./config";
2
+ import { PlClient } from "./client";
3
+ type FileConfigOverrideFields = "grpcProxy" | "httpProxy" | "user" | "password" | "alternativeRoot" | "defaultROTransactionTimeout" | "defaultRWTransactionTimeout" | "defaultRequestTimeout" | "authTTLSeconds" | "authMaxRefreshSeconds";
4
4
  type PlConfigFile = {
5
5
  address: string;
6
6
  } & Partial<Pick<PlClientConfig, FileConfigOverrideFields>>;
@@ -10,34 +10,34 @@ import { PlClient } from './client.js';
10
10
  import { createHash } from 'node:crypto';
11
11
  import { inferAuthRefreshTime } from './auth.js';
12
12
 
13
- const CONFIG_FILE_LOCAL_JSON = 'pl.json';
14
- const CONFIG_FILE_USER_JSON = path.join(os.homedir(), '.pl.json');
15
- const CONFIG_FILE_LOCAL_YAML = 'pl.yaml';
16
- const CONFIG_FILE_USER_YAML = path.join(os.homedir(), '.pl.yaml');
13
+ const CONFIG_FILE_LOCAL_JSON = "pl.json";
14
+ const CONFIG_FILE_USER_JSON = path.join(os.homedir(), ".pl.json");
15
+ const CONFIG_FILE_LOCAL_YAML = "pl.yaml";
16
+ const CONFIG_FILE_USER_YAML = path.join(os.homedir(), ".pl.yaml");
17
17
  const CONF_FILE_SEQUENCE = [
18
18
  CONFIG_FILE_LOCAL_JSON,
19
19
  CONFIG_FILE_LOCAL_YAML,
20
20
  CONFIG_FILE_USER_JSON,
21
21
  CONFIG_FILE_USER_YAML,
22
22
  ];
23
- const AUTH_DATA_FILE = '.pl_auth.json';
23
+ const AUTH_DATA_FILE = ".pl_auth.json";
24
24
  const FILE_CONFIG_OVERRIDE_FIELDS = [
25
- 'grpcProxy',
26
- 'httpProxy',
27
- 'user',
28
- 'password',
29
- 'alternativeRoot',
30
- 'defaultROTransactionTimeout',
31
- 'defaultRWTransactionTimeout',
32
- 'defaultRequestTimeout',
33
- 'authTTLSeconds',
34
- 'authMaxRefreshSeconds',
25
+ "grpcProxy",
26
+ "httpProxy",
27
+ "user",
28
+ "password",
29
+ "alternativeRoot",
30
+ "defaultROTransactionTimeout",
31
+ "defaultRWTransactionTimeout",
32
+ "defaultRequestTimeout",
33
+ "authTTLSeconds",
34
+ "authMaxRefreshSeconds",
35
35
  ];
36
36
  function tryGetFileConfig() {
37
37
  for (const confPath of CONF_FILE_SEQUENCE)
38
38
  if (fs__default.existsSync(confPath)) {
39
- const fileContent = fs__default.readFileSync(confPath, { encoding: 'utf-8' });
40
- if (confPath.endsWith('json'))
39
+ const fileContent = fs__default.readFileSync(confPath, { encoding: "utf-8" });
40
+ if (confPath.endsWith("json"))
41
41
  return [JSON.parse(fileContent), confPath];
42
42
  else
43
43
  return [YAML.parse(fileContent), confPath];
@@ -50,7 +50,7 @@ function saveAuthInfoCallback(confHash, authMaxRefreshSeconds) {
50
50
  confHash,
51
51
  authInformation: newAuthInfo,
52
52
  expiration: inferAuthRefreshTime(newAuthInfo, authMaxRefreshSeconds),
53
- })), 'utf8');
53
+ })), "utf8");
54
54
  };
55
55
  }
56
56
  const cleanAuthInfoCallback = () => {
@@ -75,18 +75,18 @@ async function defaultPlClient() {
75
75
  }
76
76
  }
77
77
  if (config === undefined)
78
- throw new Error('Can\'t find configuration to create default platform client.');
78
+ throw new Error("Can't find configuration to create default platform client.");
79
79
  if (process.env.PL_USER !== undefined)
80
80
  config.user = process.env.PL_USER;
81
81
  if (process.env.PL_PASSWORD !== undefined)
82
82
  config.user = process.env.PL_PASSWORD;
83
- const confHash = createHash('sha256')
83
+ const confHash = createHash("sha256")
84
84
  .update(Buffer.from(canonicalize(config)))
85
- .digest('base64');
85
+ .digest("base64");
86
86
  let authInformation = undefined;
87
87
  // try recover auth information from cache
88
88
  if (fs__default.existsSync(AUTH_DATA_FILE)) {
89
- const cache = JSON.parse(fs__default.readFileSync(AUTH_DATA_FILE, { encoding: 'utf-8' }));
89
+ const cache = JSON.parse(fs__default.readFileSync(AUTH_DATA_FILE, { encoding: "utf-8" }));
90
90
  if (cache.confHash === confHash && cache.expiration > Date.now())
91
91
  authInformation = cache.authInformation;
92
92
  }
@@ -106,7 +106,7 @@ async function defaultPlClient() {
106
106
  confHash,
107
107
  authInformation,
108
108
  expiration: inferAuthRefreshTime(authInformation, config.authMaxRefreshSeconds),
109
- })), 'utf8');
109
+ })), "utf8");
110
110
  }
111
111
  return await PlClient.init(config, {
112
112
  authInformation,
@@ -1 +1 @@
1
- {"version":3,"file":"default_client.js","sources":["../../src/core/default_client.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { AuthInformation, PlClientConfig } from './config';\nimport { plAddressToConfig } from './config';\nimport canonicalize from 'canonicalize';\nimport YAML from 'yaml';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { notEmpty } from '@milaboratories/ts-helpers';\nimport { UnauthenticatedPlClient } from './unauth_client';\nimport { PlClient } from './client';\nimport { createHash } from 'node:crypto';\nimport { inferAuthRefreshTime } from './auth';\n\nconst CONFIG_FILE_LOCAL_JSON = 'pl.json';\nconst CONFIG_FILE_USER_JSON = path.join(os.homedir(), '.pl.json');\nconst CONFIG_FILE_LOCAL_YAML = 'pl.yaml';\nconst CONFIG_FILE_USER_YAML = path.join(os.homedir(), '.pl.yaml');\nconst CONF_FILE_SEQUENCE = [\n CONFIG_FILE_LOCAL_JSON,\n CONFIG_FILE_LOCAL_YAML,\n CONFIG_FILE_USER_JSON,\n CONFIG_FILE_USER_YAML,\n];\n\nconst AUTH_DATA_FILE = '.pl_auth.json';\n\ntype FileConfigOverrideFields =\n | 'grpcProxy'\n | 'httpProxy'\n | 'user'\n | 'password'\n | 'alternativeRoot'\n | 'defaultROTransactionTimeout'\n | 'defaultRWTransactionTimeout'\n | 'defaultRequestTimeout'\n | 'authTTLSeconds'\n | 'authMaxRefreshSeconds';\nconst FILE_CONFIG_OVERRIDE_FIELDS: FileConfigOverrideFields[] = [\n 'grpcProxy',\n 'httpProxy',\n 'user',\n 'password',\n 'alternativeRoot',\n 'defaultROTransactionTimeout',\n 'defaultRWTransactionTimeout',\n 'defaultRequestTimeout',\n 'authTTLSeconds',\n 'authMaxRefreshSeconds',\n];\n\ntype PlConfigFile = {\n address: string;\n} & Partial<Pick<PlClientConfig, FileConfigOverrideFields>>;\n\ninterface AuthCache {\n /** To check if config changed */\n confHash: string;\n expiration: number;\n authInformation: AuthInformation;\n}\n\nexport function tryGetFileConfig(): [PlConfigFile, string] | undefined {\n for (const confPath of CONF_FILE_SEQUENCE)\n if (fs.existsSync(confPath)) {\n const fileContent = fs.readFileSync(confPath, { encoding: 'utf-8' });\n if (confPath.endsWith('json')) return [JSON.parse(fileContent) as PlConfigFile, confPath];\n else return [YAML.parse(fileContent) as PlConfigFile, confPath];\n }\n return undefined;\n}\n\nfunction saveAuthInfoCallback(\n confHash: string,\n authMaxRefreshSeconds: number,\n): (newAuthInfo: AuthInformation) => void {\n return (newAuthInfo) => {\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation: newAuthInfo,\n expiration: inferAuthRefreshTime(newAuthInfo, authMaxRefreshSeconds),\n } as AuthCache),\n ),\n 'utf8',\n );\n };\n}\n\nconst cleanAuthInfoCallback = () => {\n fs.rmSync(AUTH_DATA_FILE);\n};\n\n/** Uses default algorithm to construct a pl client from the environment */\nexport async function defaultPlClient(): Promise<PlClient> {\n let config: PlClientConfig | undefined = undefined;\n if (process.env.PL_ADDRESS !== undefined) {\n config = plAddressToConfig(process.env.PL_ADDRESS);\n } else {\n const fromFile = tryGetFileConfig();\n if (fromFile !== undefined) {\n const [fileConfig, configPath] = fromFile;\n const address = notEmpty(fileConfig.address, `no pl address in file: ${configPath}`);\n config = plAddressToConfig(address);\n // applying overrides\n for (const field of FILE_CONFIG_OVERRIDE_FIELDS)\n if (fileConfig[field] !== undefined) (config as any)[field] = fileConfig[field];\n }\n }\n\n if (config === undefined)\n throw new Error('Can\\'t find configuration to create default platform client.');\n\n if (process.env.PL_USER !== undefined) config.user = process.env.PL_USER;\n\n if (process.env.PL_PASSWORD !== undefined) config.user = process.env.PL_PASSWORD;\n\n const confHash = createHash('sha256')\n .update(Buffer.from(canonicalize(config)!))\n .digest('base64');\n\n let authInformation: AuthInformation | undefined = undefined;\n\n // try recover auth information from cache\n if (fs.existsSync(AUTH_DATA_FILE)) {\n const cache: AuthCache = JSON.parse(fs.readFileSync(AUTH_DATA_FILE, { encoding: 'utf-8' }));\n if (cache.confHash === confHash && cache.expiration > Date.now())\n authInformation = cache.authInformation;\n }\n\n if (authInformation === undefined) {\n const client = await UnauthenticatedPlClient.build(config);\n\n if (await client.requireAuth()) {\n if (config.user === undefined || config.password === undefined)\n throw new Error(`No auth information for found to authenticate with PL server.`);\n authInformation = await client.login(config.user, config.password);\n } else {\n // No authorization is required\n authInformation = {};\n }\n\n // saving cache\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation,\n expiration: inferAuthRefreshTime(authInformation, config.authMaxRefreshSeconds),\n } as AuthCache),\n ),\n 'utf8',\n );\n }\n\n return await PlClient.init(config, {\n authInformation,\n onUpdate: (_newAuthInfo) => saveAuthInfoCallback(confHash, config.authMaxRefreshSeconds),\n onUpdateError: cleanAuthInfoCallback,\n onAuthError: cleanAuthInfoCallback,\n });\n}\n"],"names":["fs"],"mappings":";;;;;;;;;;;;AAaA,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,kBAAkB,GAAG;IACzB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;CACtB;AAED,MAAM,cAAc,GAAG,eAAe;AAatC,MAAM,2BAA2B,GAA+B;IAC9D,WAAW;IACX,WAAW;IACX,MAAM;IACN,U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KAAK,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE;AAC9D,YAAA,eAAe,GAAG,KAAK,CAAC,eAAe;IAC3C;AAEA,IAAA,IAAI,eAAe,KAAK,SAAS,EAAE;QACjC,MAAM,MAAM,GAAG,MAAM,uBAAuB,CAAC,KAAK,CAAC,MAAM,CAAC;AAE1D,QAAA,IAAI,MAAM,MAAM,CAAC,WAAW,EAAE,EAAE;YAC9B,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,KAAK,SAAS;AAC5D,gBAAA,MAAM,IAAI,KAAK,CAAC,CAAA,6DAAA,CAA+D,CAAC;AAClF,YAAA,eAAe,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC;QACpE;aAAO;;YAEL,eAAe,GAAG,EAAE;QACtB;;AAGA,QAAAA,WAAE,CAAC,aAAa,CACd,cAAc,EACd,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;YACb,QAAQ;YACR,eAAe;YACf,UAAU,EAAE,oBAAoB,CAAC,eAAe,EAAE,MAAM,CAAC,qBAAqB,CAAC;AACnE,SAAA,CAAC,CAChB,EACD,MAAM,CACP;IACH;AAEA,IAAA,OAAO,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE;QACjC,eAAe;AACf,QAAA,QAAQ,EAAE,CAAC,YAAY,KAAK,oBAAoB,CAAC,QAAQ,EAAE,MAAM,CAAC,qBAAqB,CAAC;AACxF,QAAA,aAAa,EAAE,qBAAqB;AACpC,QAAA,WAAW,EAAE,qBAAqB;AACnC,KAAA,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"default_client.js","sources":["../../src/core/default_client.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { AuthInformation, PlClientConfig } from \"./config\";\nimport { plAddressToConfig } from \"./config\";\nimport canonicalize from \"canonicalize\";\nimport YAML from \"yaml\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { UnauthenticatedPlClient } from \"./unauth_client\";\nimport { PlClient } from \"./client\";\nimport { createHash } from \"node:crypto\";\nimport { inferAuthRefreshTime } from \"./auth\";\n\nconst CONFIG_FILE_LOCAL_JSON = \"pl.json\";\nconst CONFIG_FILE_USER_JSON = path.join(os.homedir(), \".pl.json\");\nconst CONFIG_FILE_LOCAL_YAML = \"pl.yaml\";\nconst CONFIG_FILE_USER_YAML = path.join(os.homedir(), \".pl.yaml\");\nconst CONF_FILE_SEQUENCE = [\n CONFIG_FILE_LOCAL_JSON,\n CONFIG_FILE_LOCAL_YAML,\n CONFIG_FILE_USER_JSON,\n CONFIG_FILE_USER_YAML,\n];\n\nconst AUTH_DATA_FILE = \".pl_auth.json\";\n\ntype FileConfigOverrideFields =\n | \"grpcProxy\"\n | \"httpProxy\"\n | \"user\"\n | \"password\"\n | \"alternativeRoot\"\n | \"defaultROTransactionTimeout\"\n | \"defaultRWTransactionTimeout\"\n | \"defaultRequestTimeout\"\n | \"authTTLSeconds\"\n | \"authMaxRefreshSeconds\";\nconst FILE_CONFIG_OVERRIDE_FIELDS: FileConfigOverrideFields[] = [\n \"grpcProxy\",\n \"httpProxy\",\n \"user\",\n \"password\",\n \"alternativeRoot\",\n \"defaultROTransactionTimeout\",\n \"defaultRWTransactionTimeout\",\n \"defaultRequestTimeout\",\n \"authTTLSeconds\",\n \"authMaxRefreshSeconds\",\n];\n\ntype PlConfigFile = {\n address: string;\n} & Partial<Pick<PlClientConfig, FileConfigOverrideFields>>;\n\ninterface AuthCache {\n /** To check if config changed */\n confHash: string;\n expiration: number;\n authInformation: AuthInformation;\n}\n\nexport function tryGetFileConfig(): [PlConfigFile, string] | undefined {\n for (const confPath of CONF_FILE_SEQUENCE)\n if (fs.existsSync(confPath)) {\n const fileContent = fs.readFileSync(confPath, { encoding: \"utf-8\" });\n if (confPath.endsWith(\"json\")) return [JSON.parse(fileContent) as PlConfigFile, confPath];\n else return [YAML.parse(fileContent) as PlConfigFile, confPath];\n }\n return undefined;\n}\n\nfunction saveAuthInfoCallback(\n confHash: string,\n authMaxRefreshSeconds: number,\n): (newAuthInfo: AuthInformation) => void {\n return (newAuthInfo) => {\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation: newAuthInfo,\n expiration: inferAuthRefreshTime(newAuthInfo, authMaxRefreshSeconds),\n } as AuthCache),\n ),\n \"utf8\",\n );\n };\n}\n\nconst cleanAuthInfoCallback = () => {\n fs.rmSync(AUTH_DATA_FILE);\n};\n\n/** Uses default algorithm to construct a pl client from the environment */\nexport async function defaultPlClient(): Promise<PlClient> {\n let config: PlClientConfig | undefined = undefined;\n if (process.env.PL_ADDRESS !== undefined) {\n config = plAddressToConfig(process.env.PL_ADDRESS);\n } else {\n const fromFile = tryGetFileConfig();\n if (fromFile !== undefined) {\n const [fileConfig, configPath] = fromFile;\n const address = notEmpty(fileConfig.address, `no pl address in file: ${configPath}`);\n config = plAddressToConfig(address);\n // applying overrides\n for (const field of FILE_CONFIG_OVERRIDE_FIELDS)\n if (fileConfig[field] !== undefined) (config as any)[field] = fileConfig[field];\n }\n }\n\n if (config === undefined)\n throw new Error(\"Can't find configuration to create default platform client.\");\n\n if (process.env.PL_USER !== undefined) config.user = process.env.PL_USER;\n\n if (process.env.PL_PASSWORD !== undefined) config.user = process.env.PL_PASSWORD;\n\n const confHash = createHash(\"sha256\")\n .update(Buffer.from(canonicalize(config)!))\n .digest(\"base64\");\n\n let authInformation: AuthInformation | undefined = undefined;\n\n // try recover auth information from cache\n if (fs.existsSync(AUTH_DATA_FILE)) {\n const cache: AuthCache = JSON.parse(fs.readFileSync(AUTH_DATA_FILE, { encoding: \"utf-8\" }));\n if (cache.confHash === confHash && cache.expiration > Date.now())\n authInformation = cache.authInformation;\n }\n\n if (authInformation === undefined) {\n const client = await UnauthenticatedPlClient.build(config);\n\n if (await client.requireAuth()) {\n if (config.user === undefined || config.password === undefined)\n throw new Error(`No auth information for found to authenticate with PL server.`);\n authInformation = await client.login(config.user, config.password);\n } else {\n // No authorization is required\n authInformation = {};\n }\n\n // saving cache\n fs.writeFileSync(\n AUTH_DATA_FILE,\n Buffer.from(\n JSON.stringify({\n confHash,\n authInformation,\n expiration: inferAuthRefreshTime(authInformation, config.authMaxRefreshSeconds),\n } as AuthCache),\n ),\n \"utf8\",\n );\n }\n\n return await PlClient.init(config, {\n authInformation,\n onUpdate: (_newAuthInfo) => saveAuthInfoCallback(confHash, config.authMaxRefreshSeconds),\n onUpdateError: cleanAuthInfoCallback,\n onAuthError: cleanAuthInfoCallback,\n });\n}\n"],"names":["fs"],"mappings":";;;;;;;;;;;;AAaA,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,sBAAsB,GAAG,SAAS;AACxC,MAAM,qBAAqB,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC;AACjE,MAAM,kBAAkB,GAAG;IACzB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;CACtB;AAED,MAAM,cAAc,GAAG,eAAe;AAatC,MAAM,2BAA2B,GAA+B;IAC9D,WAAW;IACX,WAAW;IACX,MAAM;IACN,UAAU;IACV,iBAAiB;IACjB,6BAA6B;IAC7B,6BAA6B;IAC7B,uBAAuB;IACvB,gBAAgB;IAChB,uBAAuB;CACxB;SAae,gBAAgB,GAAA;IAC9B,KAAK,MAAM,QAAQ,IAAI,kBAAkB;AACvC,QAAA,IAAIA,WAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;AAC3B,YAAA,MAAM,WAAW,GAAGA,WAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC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AAQ,KAAK,SAAS;AAC5D,gBAAA,MAAM,IAAI,KAAK,CAAC,CAAA,6DAAA,CAA+D,CAAC;AAClF,YAAA,eAAe,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC;QACpE;aAAO;;YAEL,eAAe,GAAG,EAAE;QACtB;;AAGA,QAAAA,WAAE,CAAC,aAAa,CACd,cAAc,EACd,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;YACb,QAAQ;YACR,eAAe;YACf,UAAU,EAAE,oBAAoB,CAAC,eAAe,EAAE,MAAM,CAAC,qBAAqB,CAAC;AACnE,SAAA,CAAC,CAChB,EACD,MAAM,CACP;IACH;AAEA,IAAA,OAAO,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE;QACjC,eAAe;AACf,QAAA,QAAQ,EAAE,CAAC,YAAY,KAAK,oBAAoB,CAAC,QAAQ,EAAE,MAAM,CAAC,qBAAqB,CAAC;AACxF,QAAA,aAAa,EAAE,qBAAqB;AACpC,QAAA,WAAW,EAAE,qBAAqB;AACnC,KAAA,CAAC;AACJ;;;;"}
@@ -6,7 +6,7 @@
6
6
  function addRTypeToMetadata(rType, options) {
7
7
  options = options ?? {};
8
8
  options.meta = options.meta ?? {};
9
- options.meta['resourceType'] = `${rType.name}:${rType.version}`;
9
+ options.meta["resourceType"] = `${rType.name}:${rType.version}`;
10
10
  return options;
11
11
  }
12
12
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"driver.cjs","sources":["../../src/core/driver.ts"],"sourcesContent":["import type { PlClient } from './client';\nimport type { RpcOptions } from '@protobuf-ts/runtime-rpc';\nimport type { Dispatcher } from 'undici';\nimport type { ResourceType } from './types';\nimport type { WireClientProviderFactory } from './wire';\n\n/** Drivers must implement this interface */\nexport interface PlDriver {\n close(): void;\n}\n\n/** Definition to use driver via {@link PlClient} */\nexport interface PlDriverDefinition<Drv extends PlDriver> {\n /** Used as key to only once instantiate specific drivers */\n readonly name: string;\n\n /** Initialization routine, will be executed only once for each driver in a specific client */\n init(pl: PlClient, wireClientFactory: WireClientProviderFactory, httpDispatcher: Dispatcher): Drv;\n}\n\n// addRTypeToMetadata adds a metadata with resource type\n// for every RPC call. It is necessary for the platform core\n// to proxy the call to the proper controller.\nexport function addRTypeToMetadata(rType: ResourceType, options?: RpcOptions) {\n options = options ?? {};\n options.meta = options.meta ?? {};\n options.meta['resourceType'] = `${rType.name}:${rType.version}`;\n\n return options;\n}\n\n/**\n * addRTypeToHeaders adds a header that helps to route request to the right resource and controller.\n * Without this header, API router on server side cannot route request to proper controller in internal\n * RPC proxy.\n */\nexport function createRTypeRoutingHeader(rType: ResourceType): Record<string, string> {\n return {\n resourceType: `${rType.name}:${rType.version}`,\n };\n}\n"],"names":[],"mappings":";;AAoBA;AACA;AACA;AACM,SAAU,kBAAkB,CAAC,KAAmB,EAAE,OAAoB,EAAA;AAC1E,IAAA,OAAO,GAAG,OAAO,IAAI,EAAE;IACvB,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;AACjC,IAAA,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAA,EAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,EAAE;AAE/D,IAAA,OAAO,OAAO;AAChB;AAEA;;;;AAIG;AACG,SAAU,wBAAwB,CAAC,KAAmB,EAAA;IAC1D,OAAO;QACL,YAAY,EAAE,GAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,CAAA,CAAE;KAC/C;AACH;;;;;"}
1
+ {"version":3,"file":"driver.cjs","sources":["../../src/core/driver.ts"],"sourcesContent":["import type { PlClient } from \"./client\";\nimport type { RpcOptions } from \"@protobuf-ts/runtime-rpc\";\nimport type { Dispatcher } from \"undici\";\nimport type { ResourceType } from \"./types\";\nimport type { WireClientProviderFactory } from \"./wire\";\n\n/** Drivers must implement this interface */\nexport interface PlDriver {\n close(): void;\n}\n\n/** Definition to use driver via {@link PlClient} */\nexport interface PlDriverDefinition<Drv extends PlDriver> {\n /** Used as key to only once instantiate specific drivers */\n readonly name: string;\n\n /** Initialization routine, will be executed only once for each driver in a specific client */\n init(pl: PlClient, wireClientFactory: WireClientProviderFactory, httpDispatcher: Dispatcher): Drv;\n}\n\n// addRTypeToMetadata adds a metadata with resource type\n// for every RPC call. It is necessary for the platform core\n// to proxy the call to the proper controller.\nexport function addRTypeToMetadata(rType: ResourceType, options?: RpcOptions) {\n options = options ?? {};\n options.meta = options.meta ?? {};\n options.meta[\"resourceType\"] = `${rType.name}:${rType.version}`;\n\n return options;\n}\n\n/**\n * addRTypeToHeaders adds a header that helps to route request to the right resource and controller.\n * Without this header, API router on server side cannot route request to proper controller in internal\n * RPC proxy.\n */\nexport function createRTypeRoutingHeader(rType: ResourceType): Record<string, string> {\n return {\n resourceType: `${rType.name}:${rType.version}`,\n };\n}\n"],"names":[],"mappings":";;AAoBA;AACA;AACA;AACM,SAAU,kBAAkB,CAAC,KAAmB,EAAE,OAAoB,EAAA;AAC1E,IAAA,OAAO,GAAG,OAAO,IAAI,EAAE;IACvB,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;AACjC,IAAA,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAA,EAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,EAAE;AAE/D,IAAA,OAAO,OAAO;AAChB;AAEA;;;;AAIG;AACG,SAAU,wBAAwB,CAAC,KAAmB,EAAA;IAC1D,OAAO;QACL,YAAY,EAAE,GAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,CAAA,CAAE;KAC/C;AACH;;;;;"}
@@ -1,8 +1,8 @@
1
- import type { PlClient } from './client';
2
- import type { RpcOptions } from '@protobuf-ts/runtime-rpc';
3
- import type { Dispatcher } from 'undici';
4
- import type { ResourceType } from './types';
5
- import type { WireClientProviderFactory } from './wire';
1
+ import type { PlClient } from "./client";
2
+ import type { RpcOptions } from "@protobuf-ts/runtime-rpc";
3
+ import type { Dispatcher } from "undici";
4
+ import type { ResourceType } from "./types";
5
+ import type { WireClientProviderFactory } from "./wire";
6
6
  /** Drivers must implement this interface */
7
7
  export interface PlDriver {
8
8
  close(): void;
@@ -4,7 +4,7 @@
4
4
  function addRTypeToMetadata(rType, options) {
5
5
  options = options ?? {};
6
6
  options.meta = options.meta ?? {};
7
- options.meta['resourceType'] = `${rType.name}:${rType.version}`;
7
+ options.meta["resourceType"] = `${rType.name}:${rType.version}`;
8
8
  return options;
9
9
  }
10
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"driver.js","sources":["../../src/core/driver.ts"],"sourcesContent":["import type { PlClient } from './client';\nimport type { RpcOptions } from '@protobuf-ts/runtime-rpc';\nimport type { Dispatcher } from 'undici';\nimport type { ResourceType } from './types';\nimport type { WireClientProviderFactory } from './wire';\n\n/** Drivers must implement this interface */\nexport interface PlDriver {\n close(): void;\n}\n\n/** Definition to use driver via {@link PlClient} */\nexport interface PlDriverDefinition<Drv extends PlDriver> {\n /** Used as key to only once instantiate specific drivers */\n readonly name: string;\n\n /** Initialization routine, will be executed only once for each driver in a specific client */\n init(pl: PlClient, wireClientFactory: WireClientProviderFactory, httpDispatcher: Dispatcher): Drv;\n}\n\n// addRTypeToMetadata adds a metadata with resource type\n// for every RPC call. It is necessary for the platform core\n// to proxy the call to the proper controller.\nexport function addRTypeToMetadata(rType: ResourceType, options?: RpcOptions) {\n options = options ?? {};\n options.meta = options.meta ?? {};\n options.meta['resourceType'] = `${rType.name}:${rType.version}`;\n\n return options;\n}\n\n/**\n * addRTypeToHeaders adds a header that helps to route request to the right resource and controller.\n * Without this header, API router on server side cannot route request to proper controller in internal\n * RPC proxy.\n */\nexport function createRTypeRoutingHeader(rType: ResourceType): Record<string, string> {\n return {\n resourceType: `${rType.name}:${rType.version}`,\n };\n}\n"],"names":[],"mappings":"AAoBA;AACA;AACA;AACM,SAAU,kBAAkB,CAAC,KAAmB,EAAE,OAAoB,EAAA;AAC1E,IAAA,OAAO,GAAG,OAAO,IAAI,EAAE;IACvB,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;AACjC,IAAA,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAA,EAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,EAAE;AAE/D,IAAA,OAAO,OAAO;AAChB;AAEA;;;;AAIG;AACG,SAAU,wBAAwB,CAAC,KAAmB,EAAA;IAC1D,OAAO;QACL,YAAY,EAAE,GAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,CAAA,CAAE;KAC/C;AACH;;;;"}
1
+ {"version":3,"file":"driver.js","sources":["../../src/core/driver.ts"],"sourcesContent":["import type { PlClient } from \"./client\";\nimport type { RpcOptions } from \"@protobuf-ts/runtime-rpc\";\nimport type { Dispatcher } from \"undici\";\nimport type { ResourceType } from \"./types\";\nimport type { WireClientProviderFactory } from \"./wire\";\n\n/** Drivers must implement this interface */\nexport interface PlDriver {\n close(): void;\n}\n\n/** Definition to use driver via {@link PlClient} */\nexport interface PlDriverDefinition<Drv extends PlDriver> {\n /** Used as key to only once instantiate specific drivers */\n readonly name: string;\n\n /** Initialization routine, will be executed only once for each driver in a specific client */\n init(pl: PlClient, wireClientFactory: WireClientProviderFactory, httpDispatcher: Dispatcher): Drv;\n}\n\n// addRTypeToMetadata adds a metadata with resource type\n// for every RPC call. It is necessary for the platform core\n// to proxy the call to the proper controller.\nexport function addRTypeToMetadata(rType: ResourceType, options?: RpcOptions) {\n options = options ?? {};\n options.meta = options.meta ?? {};\n options.meta[\"resourceType\"] = `${rType.name}:${rType.version}`;\n\n return options;\n}\n\n/**\n * addRTypeToHeaders adds a header that helps to route request to the right resource and controller.\n * Without this header, API router on server side cannot route request to proper controller in internal\n * RPC proxy.\n */\nexport function createRTypeRoutingHeader(rType: ResourceType): Record<string, string> {\n return {\n resourceType: `${rType.name}:${rType.version}`,\n };\n}\n"],"names":[],"mappings":"AAoBA;AACA;AACA;AACM,SAAU,kBAAkB,CAAC,KAAmB,EAAE,OAAoB,EAAA;AAC1E,IAAA,OAAO,GAAG,OAAO,IAAI,EAAE;IACvB,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE;AACjC,IAAA,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAA,EAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,EAAE;AAE/D,IAAA,OAAO,OAAO;AAChB;AAEA;;;;AAIG;AACG,SAAU,wBAAwB,CAAC,KAAmB,EAAA;IAC1D,OAAO;QACL,YAAY,EAAE,GAAG,KAAK,CAAC,IAAI,CAAA,CAAA,EAAI,KAAK,CAAC,OAAO,CAAA,CAAE;KAC/C;AACH;;;;"}
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const ErrorResourceType = {
4
- name: 'json/resourceError',
5
- version: '1',
4
+ name: "json/resourceError",
5
+ version: "1",
6
6
  };
7
7
 
8
8
  exports.ErrorResourceType = ErrorResourceType;
@@ -1 +1 @@
1
- {"version":3,"file":"error_resource.cjs","sources":["../../src/core/error_resource.ts"],"sourcesContent":["import type { ResourceType } from './types';\n\nexport type ErrorResourceData = {\n message: string;\n};\n\nexport const ErrorResourceType: ResourceType = {\n name: 'json/resourceError',\n version: '1',\n};\n"],"names":[],"mappings":";;AAMO,MAAM,iBAAiB,GAAiB;AAC7C,IAAA,IAAI,EAAE,oBAAoB;AAC1B,IAAA,OAAO,EAAE,GAAG;;;;;"}
1
+ {"version":3,"file":"error_resource.cjs","sources":["../../src/core/error_resource.ts"],"sourcesContent":["import type { ResourceType } from \"./types\";\n\nexport type ErrorResourceData = {\n message: string;\n};\n\nexport const ErrorResourceType: ResourceType = {\n name: \"json/resourceError\",\n version: \"1\",\n};\n"],"names":[],"mappings":";;AAMO,MAAM,iBAAiB,GAAiB;AAC7C,IAAA,IAAI,EAAE,oBAAoB;AAC1B,IAAA,OAAO,EAAE,GAAG;;;;;"}
@@ -1,4 +1,4 @@
1
- import type { ResourceType } from './types';
1
+ import type { ResourceType } from "./types";
2
2
  export type ErrorResourceData = {
3
3
  message: string;
4
4
  };
@@ -1,6 +1,6 @@
1
1
  const ErrorResourceType = {
2
- name: 'json/resourceError',
3
- version: '1',
2
+ name: "json/resourceError",
3
+ version: "1",
4
4
  };
5
5
 
6
6
  export { ErrorResourceType };
@@ -1 +1 @@
1
- {"version":3,"file":"error_resource.js","sources":["../../src/core/error_resource.ts"],"sourcesContent":["import type { ResourceType } from './types';\n\nexport type ErrorResourceData = {\n message: string;\n};\n\nexport const ErrorResourceType: ResourceType = {\n name: 'json/resourceError',\n version: '1',\n};\n"],"names":[],"mappings":"AAMO,MAAM,iBAAiB,GAAiB;AAC7C,IAAA,IAAI,EAAE,oBAAoB;AAC1B,IAAA,OAAO,EAAE,GAAG;;;;;"}
1
+ {"version":3,"file":"error_resource.js","sources":["../../src/core/error_resource.ts"],"sourcesContent":["import type { ResourceType } from \"./types\";\n\nexport type ErrorResourceData = {\n message: string;\n};\n\nexport const ErrorResourceType: ResourceType = {\n name: \"json/resourceError\",\n version: \"1\",\n};\n"],"names":[],"mappings":"AAMO,MAAM,iBAAiB,GAAiB;AAC7C,IAAA,IAAI,EAAE,oBAAoB;AAC1B,IAAA,OAAO,EAAE,GAAG;;;;;"}
@@ -8,9 +8,9 @@ function isConnectionProblem(err, nested = false) {
8
8
  return false;
9
9
  if (err instanceof DisconnectedError)
10
10
  return true;
11
- if (err.name == 'RpcError' && err.code == 'UNAVAILABLE')
11
+ if (err.name == "RpcError" && err.code == "UNAVAILABLE")
12
12
  return true;
13
- if (err.name == 'RESTError' && err.status.code == code.Code.UNAVAILABLE)
13
+ if (err.name == "RESTError" && err.status.code == code.Code.UNAVAILABLE)
14
14
  return true;
15
15
  if (err.cause !== undefined && !nested)
16
16
  return isConnectionProblem(err.cause, true);
@@ -21,9 +21,9 @@ function isUnauthenticated(err, nested = false) {
21
21
  return false;
22
22
  if (err instanceof UnauthenticatedError)
23
23
  return true;
24
- if (err.name == 'RpcError' && err.code == 'UNAUTHENTICATED')
24
+ if (err.name == "RpcError" && err.code == "UNAUTHENTICATED")
25
25
  return true;
26
- if (err.name == 'RESTError' && err.status.code == code.Code.UNAUTHENTICATED)
26
+ if (err.name == "RESTError" && err.status.code == code.Code.UNAUTHENTICATED)
27
27
  return true;
28
28
  if (err.cause !== undefined && !nested)
29
29
  return isUnauthenticated(err.cause, true);
@@ -32,11 +32,11 @@ function isUnauthenticated(err, nested = false) {
32
32
  function isTimeoutError(err, nested = false) {
33
33
  if (err === undefined || err === null)
34
34
  return false;
35
- if (err.name == 'TimeoutError')
35
+ if (err.name == "TimeoutError")
36
36
  return true;
37
- if (err.name == 'RpcError' && err.code == 'DEADLINE_EXCEEDED')
37
+ if (err.name == "RpcError" && err.code == "DEADLINE_EXCEEDED")
38
38
  return true;
39
- if (err.name == 'RESTError' && err.status.code == code.Code.DEADLINE_EXCEEDED)
39
+ if (err.name == "RESTError" && err.status.code == code.Code.DEADLINE_EXCEEDED)
40
40
  return true;
41
41
  if (err.cause !== undefined && !nested)
42
42
  return isTimeoutError(err.cause, true);
@@ -45,9 +45,9 @@ function isTimeoutError(err, nested = false) {
45
45
  function isCancelError(err, nested = false) {
46
46
  if (err === undefined || err === null)
47
47
  return false;
48
- if (err.name == 'RpcError' && err.code == 'CANCELLED')
48
+ if (err.name == "RpcError" && err.code == "CANCELLED")
49
49
  return true;
50
- if (err.name == 'RESTError' && err.status.code == code.Code.CANCELLED)
50
+ if (err.name == "RESTError" && err.status.code == code.Code.CANCELLED)
51
51
  return true;
52
52
  if (err.cause !== undefined && !nested)
53
53
  return isCancelError(err.cause, true);
@@ -56,15 +56,15 @@ function isCancelError(err, nested = false) {
56
56
  function isAbortedError(err, nested = false) {
57
57
  if (err === undefined || err === null)
58
58
  return false;
59
- if (err instanceof tsHelpers.Aborted || err.name == 'AbortError')
59
+ if (err instanceof tsHelpers.Aborted || err.name == "AbortError")
60
60
  return true;
61
- if (err.code == 'ABORT_ERR')
61
+ if (err.code == "ABORT_ERR")
62
62
  return true;
63
63
  if (err instanceof DOMException && err.code === DOMException.ABORT_ERR)
64
64
  return true; // WebSocket error
65
- if (err.name == 'RpcError' && err.code == 'ABORTED')
65
+ if (err.name == "RpcError" && err.code == "ABORTED")
66
66
  return true;
67
- if (err.name == 'RESTError' && err.status.code == code.Code.ABORTED)
67
+ if (err.name == "RESTError" && err.status.code == code.Code.ABORTED)
68
68
  return true;
69
69
  if (err.cause !== undefined && !nested)
70
70
  isAbortedError(err.cause, true);
@@ -86,9 +86,9 @@ function isTimeoutOrCancelError(err, nested = false) {
86
86
  function isNotFoundError(err, nested = false) {
87
87
  if (err === undefined || err === null)
88
88
  return false;
89
- if (err.name == 'RpcError' && err.code == 'NOT_FOUND')
89
+ if (err.name == "RpcError" && err.code == "NOT_FOUND")
90
90
  return true;
91
- if (err.name == 'RESTError' && err.status.code == code.Code.NOT_FOUND)
91
+ if (err.name == "RESTError" && err.status.code == code.Code.NOT_FOUND)
92
92
  return true;
93
93
  if (err.cause !== undefined && !nested)
94
94
  return isNotFoundError(err.cause, true);
@@ -97,7 +97,7 @@ function isNotFoundError(err, nested = false) {
97
97
  const PlErrorCodeNotFound = code.Code.NOT_FOUND;
98
98
  class PlError extends Error {
99
99
  status;
100
- name = 'PlError';
100
+ name = "PlError";
101
101
  constructor(status, opts) {
102
102
  super(`code=${status.code} ${status.message}`, opts);
103
103
  this.status = status;
@@ -107,31 +107,31 @@ function throwPlNotFoundError(message) {
107
107
  throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });
108
108
  }
109
109
  class RecoverablePlError extends PlError {
110
- name = 'RecoverablePlError';
110
+ name = "RecoverablePlError";
111
111
  constructor(status) {
112
112
  super(status);
113
113
  }
114
114
  }
115
115
  class UnrecoverablePlError extends PlError {
116
- name = 'UnrecoverablePlError';
116
+ name = "UnrecoverablePlError";
117
117
  constructor(status) {
118
118
  super(status);
119
119
  }
120
120
  }
121
121
  class UnauthenticatedError extends Error {
122
- name = 'UnauthenticatedError';
122
+ name = "UnauthenticatedError";
123
123
  constructor(message) {
124
- super('LoginFailed: ' + message);
124
+ super("LoginFailed: " + message);
125
125
  }
126
126
  }
127
127
  class DisconnectedError extends Error {
128
- name = 'DisconnectedError';
128
+ name = "DisconnectedError";
129
129
  constructor(message) {
130
- super('Disconnected: ' + message);
130
+ super("Disconnected: " + message);
131
131
  }
132
132
  }
133
133
  class RESTError extends PlError {
134
- name = 'RESTError';
134
+ name = "RESTError";
135
135
  constructor(status, opts) {
136
136
  super(status, opts);
137
137
  }
@@ -150,7 +150,7 @@ function rethrowMeaningfulError(error, wrapIfUnknown = false) {
150
150
  if (isTimeoutOrCancelError(error))
151
151
  throw new tsHelpers.Aborted(error);
152
152
  if (wrapIfUnknown) {
153
- const message = error.message || String(error) || 'Unknown error';
153
+ const message = error.message || String(error) || "Unknown error";
154
154
  throw new Error(message, { cause: error });
155
155
  }
156
156
  else