@ethersphere/bee-js 12.2.1 → 12.3.0

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 (143) hide show
  1. package/dist/cjs/bee.js +56 -23
  2. package/dist/cjs/chunk/cac.js +4 -2
  3. package/dist/cjs/feed/index.js +3 -1
  4. package/dist/cjs/index.js +1 -3
  5. package/dist/cjs/modules/bytes.js +6 -4
  6. package/dist/cjs/modules/bzz.js +5 -4
  7. package/dist/cjs/modules/chunk.js +3 -2
  8. package/dist/cjs/modules/debug/balance.js +5 -29
  9. package/dist/cjs/modules/debug/chequebook.js +9 -58
  10. package/dist/cjs/modules/debug/connectivity.js +5 -82
  11. package/dist/cjs/modules/debug/settlements.js +3 -22
  12. package/dist/cjs/modules/debug/stake.js +8 -33
  13. package/dist/cjs/modules/debug/stamps.js +27 -53
  14. package/dist/cjs/modules/debug/states.js +6 -31
  15. package/dist/cjs/modules/debug/status.js +5 -37
  16. package/dist/cjs/modules/debug/transactions.js +5 -26
  17. package/dist/cjs/modules/envelope.js +6 -6
  18. package/dist/cjs/modules/feed.js +3 -4
  19. package/dist/cjs/modules/grantee.js +8 -10
  20. package/dist/cjs/modules/pinning.js +5 -11
  21. package/dist/cjs/modules/rchash.js +2 -3
  22. package/dist/cjs/modules/soc.js +3 -2
  23. package/dist/cjs/modules/status.js +3 -3
  24. package/dist/cjs/modules/stewardship.js +2 -3
  25. package/dist/cjs/modules/tag.js +4 -35
  26. package/dist/cjs/stamper/stamper.js +2 -1
  27. package/dist/cjs/types/schema/balance.js +14 -0
  28. package/dist/cjs/types/schema/chequebook.js +49 -0
  29. package/dist/cjs/types/schema/connectivity.js +46 -0
  30. package/dist/cjs/types/schema/envelope.js +11 -0
  31. package/dist/cjs/types/schema/grantee.js +10 -0
  32. package/dist/cjs/types/schema/pinning.js +7 -0
  33. package/dist/cjs/types/schema/rchash.js +7 -0
  34. package/dist/cjs/types/schema/settlements.js +17 -0
  35. package/dist/cjs/types/schema/stake.js +33 -0
  36. package/dist/cjs/types/schema/stamps.js +48 -0
  37. package/dist/cjs/types/schema/states.js +34 -0
  38. package/dist/cjs/types/schema/status.js +39 -0
  39. package/dist/cjs/types/schema/stewardship.js +7 -0
  40. package/dist/cjs/types/schema/tag.js +20 -0
  41. package/dist/cjs/types/schema/transactions.js +24 -0
  42. package/dist/cjs/types/schema/upload.js +8 -0
  43. package/dist/cjs/utils/bad-ports.js +92 -0
  44. package/dist/cjs/utils/bytes.js +5 -3
  45. package/dist/cjs/utils/error.js +1 -0
  46. package/dist/cjs/utils/headers.js +19 -13
  47. package/dist/cjs/utils/hex-schema.js +8 -0
  48. package/dist/cjs/utils/http.js +92 -52
  49. package/dist/cjs/utils/resource-locator.js +4 -3
  50. package/dist/cjs/utils/schema.js +88 -0
  51. package/dist/cjs/utils/stamps.js +2 -1
  52. package/dist/cjs/utils/type.js +12 -130
  53. package/dist/cjs/utils/url.js +24 -0
  54. package/dist/index.browser.min.js +1 -1
  55. package/dist/index.browser.min.js.map +1 -1
  56. package/dist/mjs/bee.js +59 -30
  57. package/dist/mjs/chunk/cac.js +5 -3
  58. package/dist/mjs/feed/index.js +4 -2
  59. package/dist/mjs/index.js +1 -2
  60. package/dist/mjs/modules/bytes.js +8 -8
  61. package/dist/mjs/modules/bzz.js +6 -9
  62. package/dist/mjs/modules/chunk.js +4 -7
  63. package/dist/mjs/modules/debug/balance.js +5 -61
  64. package/dist/mjs/modules/debug/chequebook.js +9 -114
  65. package/dist/mjs/modules/debug/connectivity.js +5 -145
  66. package/dist/mjs/modules/debug/settlements.js +3 -46
  67. package/dist/mjs/modules/debug/stake.js +8 -85
  68. package/dist/mjs/modules/debug/stamps.js +24 -126
  69. package/dist/mjs/modules/debug/states.js +6 -71
  70. package/dist/mjs/modules/debug/status.js +5 -91
  71. package/dist/mjs/modules/debug/transactions.js +5 -60
  72. package/dist/mjs/modules/envelope.js +6 -20
  73. package/dist/mjs/modules/feed.js +6 -7
  74. package/dist/mjs/modules/grantee.js +8 -26
  75. package/dist/mjs/modules/pinning.js +7 -21
  76. package/dist/mjs/modules/rchash.js +2 -7
  77. package/dist/mjs/modules/soc.js +4 -5
  78. package/dist/mjs/modules/status.js +4 -4
  79. package/dist/mjs/modules/stewardship.js +2 -7
  80. package/dist/mjs/modules/tag.js +4 -93
  81. package/dist/mjs/stamper/stamper.js +2 -1
  82. package/dist/mjs/types/schema/balance.js +13 -0
  83. package/dist/mjs/types/schema/chequebook.js +53 -0
  84. package/dist/mjs/types/schema/connectivity.js +41 -0
  85. package/dist/mjs/types/schema/envelope.js +8 -0
  86. package/dist/mjs/types/schema/grantee.js +7 -0
  87. package/dist/mjs/types/schema/pinning.js +4 -0
  88. package/dist/mjs/types/schema/rchash.js +4 -0
  89. package/dist/mjs/types/schema/settlements.js +22 -0
  90. package/dist/mjs/types/schema/stake.js +40 -0
  91. package/dist/mjs/types/schema/stamps.js +47 -0
  92. package/dist/mjs/types/schema/states.js +34 -0
  93. package/dist/mjs/types/schema/status.js +36 -0
  94. package/dist/mjs/types/schema/stewardship.js +4 -0
  95. package/dist/mjs/types/schema/tag.js +14 -0
  96. package/dist/mjs/types/schema/transactions.js +25 -0
  97. package/dist/mjs/types/schema/upload.js +5 -0
  98. package/dist/mjs/utils/bad-ports.js +6 -0
  99. package/dist/mjs/utils/bytes.js +6 -8
  100. package/dist/mjs/utils/error.js +5 -0
  101. package/dist/mjs/utils/headers.js +19 -13
  102. package/dist/mjs/utils/hex-schema.js +2 -0
  103. package/dist/mjs/utils/http.js +97 -59
  104. package/dist/mjs/utils/resource-locator.js +4 -3
  105. package/dist/mjs/utils/schema.js +81 -0
  106. package/dist/mjs/utils/stamps.js +2 -1
  107. package/dist/mjs/utils/type.js +13 -233
  108. package/dist/mjs/utils/url.js +23 -0
  109. package/dist/types/bee.d.ts +23 -0
  110. package/dist/types/index.d.ts +1 -3
  111. package/dist/types/modules/debug/connectivity.d.ts +2 -2
  112. package/dist/types/modules/debug/stamps.d.ts +2 -0
  113. package/dist/types/types/debug.d.ts +1 -0
  114. package/dist/types/types/schema/balance.d.ts +12 -0
  115. package/dist/types/types/schema/chequebook.d.ts +104 -0
  116. package/dist/types/types/schema/connectivity.d.ts +49 -0
  117. package/dist/types/types/schema/envelope.d.ts +7 -0
  118. package/dist/types/types/schema/grantee.d.ts +7 -0
  119. package/dist/types/types/schema/pinning.d.ts +4 -0
  120. package/dist/types/types/schema/rchash.d.ts +4 -0
  121. package/dist/types/types/schema/settlements.d.ts +16 -0
  122. package/dist/types/types/schema/stake.d.ts +29 -0
  123. package/dist/types/types/schema/stamps.d.ts +77 -0
  124. package/dist/types/types/schema/states.d.ts +26 -0
  125. package/dist/types/types/schema/status.d.ts +38 -0
  126. package/dist/types/types/schema/stewardship.d.ts +4 -0
  127. package/dist/types/types/schema/tag.d.ts +23 -0
  128. package/dist/types/types/schema/transactions.d.ts +29 -0
  129. package/dist/types/types/schema/upload.d.ts +5 -0
  130. package/dist/types/utils/bad-ports.d.ts +6 -0
  131. package/dist/types/utils/error.d.ts +5 -0
  132. package/dist/types/utils/hex-schema.d.ts +2 -0
  133. package/dist/types/utils/http.d.ts +18 -3
  134. package/dist/types/utils/schema.d.ts +90 -0
  135. package/dist/types/utils/stamps.d.ts +1 -0
  136. package/dist/types/utils/tar-uploader.browser.d.ts +1 -1
  137. package/dist/types/utils/tar-uploader.d.ts +1 -1
  138. package/dist/types/utils/type.d.ts +1 -16
  139. package/dist/types/utils/url.d.ts +9 -0
  140. package/package.json +10 -10
  141. package/dist/cjs/bee-dev.js +0 -78
  142. package/dist/mjs/bee-dev.js +0 -98
  143. package/dist/types/bee-dev.d.ts +0 -5
@@ -1,5 +1,7 @@
1
- import { Binary, Objects, Types } from 'cafe-utility';
1
+ import { Binary, Objects } from 'cafe-utility';
2
2
  import _debug from 'debug';
3
+ import { z } from 'zod';
4
+ import { HexStringSchema } from "./hex-schema.js";
3
5
  const debug = _debug('bee-js:bytes');
4
6
  const DECODER = new TextDecoder();
5
7
  const ENCODER = new TextEncoder();
@@ -11,9 +13,7 @@ export class Bytes {
11
13
  if (bytes instanceof Bytes) {
12
14
  this.bytes = bytes.bytes;
13
15
  } else if (typeof bytes === 'string') {
14
- this.bytes = Binary.hexToUint8Array(Types.asHexString(bytes, {
15
- name: 'Bytes#constructor(bytes)'
16
- }));
16
+ this.bytes = Binary.hexToUint8Array(HexStringSchema.parse(bytes));
17
17
  } else if (bytes instanceof ArrayBuffer) {
18
18
  this.bytes = new Uint8Array(bytes);
19
19
  } else if (bytes instanceof Uint8Array) {
@@ -21,11 +21,9 @@ export class Bytes {
21
21
  } else {
22
22
  const unknownInput = bytes;
23
23
  const toHex = Objects.getDeep(unknownInput, 'toHex');
24
- if (Types.isFunction(toHex)) {
24
+ if (z.function().safeParse(toHex).success) {
25
25
  const hex = toHex.call(unknownInput);
26
- this.bytes = Binary.hexToUint8Array(Types.asHexString(hex, {
27
- name: 'Bytes#constructor(bytes)'
28
- }));
26
+ this.bytes = Binary.hexToUint8Array(HexStringSchema.parse(hex));
29
27
  } else {
30
28
  debug('bytes', bytes);
31
29
  throw new Error(`Bytes#constructor: unsupported type: ${typeof bytes}`);
@@ -17,5 +17,10 @@ export class BeeResponseError extends BeeError {
17
17
  this.responseBody = responseBody;
18
18
  this.status = status;
19
19
  this.statusText = statusText;
20
+ this.response = {
21
+ status,
22
+ data: responseBody,
23
+ statusText
24
+ };
20
25
  }
21
26
  }
@@ -1,4 +1,4 @@
1
- import { Types } from 'cafe-utility';
1
+ import { z } from 'zod';
2
2
  import { BeeError } from "./error.js";
3
3
  import { convertEnvelopeToMarshaledStamp } from "./stamps.js";
4
4
  import { BatchId, PublicKey, Reference } from "./typed-bytes.js";
@@ -41,7 +41,7 @@ export function prepareRequestHeaders(stamp, nullableOptions) {
41
41
  if (!nullableOptions) {
42
42
  return headers;
43
43
  }
44
- const options = Types.asObject(nullableOptions);
44
+ const options = nullableOptions;
45
45
  if (options.size) {
46
46
  headers['content-length'] = String(options.size);
47
47
  }
@@ -51,26 +51,31 @@ export function prepareRequestHeaders(stamp, nullableOptions) {
51
51
  if (options.redundancyLevel) {
52
52
  headers['swarm-redundancy-level'] = String(options.redundancyLevel);
53
53
  }
54
- if (Types.isBoolean(options.act)) {
55
- headers['swarm-act'] = String(options.act);
54
+ const act = z.boolean().safeParse(options.act);
55
+ if (act.success) {
56
+ headers['swarm-act'] = String(act.data);
56
57
  }
57
- if (Types.isBoolean(options.pin)) {
58
- headers['swarm-pin'] = String(options.pin);
58
+ const pin = z.boolean().safeParse(options.pin);
59
+ if (pin.success) {
60
+ headers['swarm-pin'] = String(pin.data);
59
61
  }
60
- if (Types.isBoolean(options.encrypt)) {
61
- headers['swarm-encrypt'] = options.encrypt.toString();
62
+ const encrypt = z.boolean().safeParse(options.encrypt);
63
+ if (encrypt.success) {
64
+ headers['swarm-encrypt'] = String(encrypt.data);
62
65
  }
63
66
  if (options.tag) {
64
67
  headers['swarm-tag'] = String(options.tag);
65
68
  }
66
- if (Types.isBoolean(options.deferred)) {
67
- headers['swarm-deferred-upload'] = options.deferred.toString();
69
+ const deferred = z.boolean().safeParse(options.deferred);
70
+ if (deferred.success) {
71
+ headers['swarm-deferred-upload'] = String(deferred.data);
68
72
  }
69
73
  if (options.redundancyStrategy) {
70
74
  headers['swarm-redundancy-strategy'] = String(options.redundancyStrategy);
71
75
  }
72
- if (Types.isBoolean(options.fallback)) {
73
- headers['swarm-redundancy-fallback-mode'] = options.fallback.toString();
76
+ const fallback = z.boolean().safeParse(options.fallback);
77
+ if (fallback.success) {
78
+ headers['swarm-redundancy-fallback-mode'] = String(fallback.data);
74
79
  }
75
80
  if (options.timeoutMs) {
76
81
  headers['swarm-chunk-retrieval-timeout'] = String(options.timeoutMs);
@@ -102,7 +107,8 @@ export function prepareRequestHeaders(stamp, nullableOptions) {
102
107
  return headers;
103
108
  }
104
109
  function isEnvelopeWithBatchId(value) {
105
- if (!Types.isObject(value)) {
110
+ const result = z.object({}).safeParse(value);
111
+ if (!result.success) {
106
112
  return false;
107
113
  }
108
114
  const envelope = value;
@@ -0,0 +1,2 @@
1
+ import { z } from 'zod';
2
+ export const HexStringSchema = z.string().regex(/^(?:0x)?[0-9a-fA-F]*$/i, 'expected hex string').refine(s => s.replace(/^0x/i, '').length % 2 === 0, 'expected even-length hex string');
@@ -1,28 +1,16 @@
1
- import axios from 'axios';
2
- import { Dates, Objects, Strings, System } from 'cafe-utility';
1
+ import { Objects, Strings, System } from 'cafe-utility';
3
2
  import _debug from 'debug';
4
3
  import { BeeResponseError } from "../index.js";
5
4
  const debug = _debug('bee-js:http');
6
- const {
7
- AxiosError
8
- } = axios;
9
5
  const MAX_FAILED_ATTEMPTS = 100000;
10
6
  const DELAY_FAST = 200;
11
7
  const DELAY_SLOW = 1000;
12
- const DELAY_THRESHOLD = Dates.minutes(1) / DELAY_FAST;
13
- const ABORT_ERROR_MESSAGE = 'Request aborted';
8
+ const FAST_RETRY_COUNT = 300;
14
9
  export const DEFAULT_HTTP_CONFIG = {
15
10
  headers: {
16
11
  accept: 'application/json, text/plain, */*'
17
- },
18
- maxBodyLength: Infinity,
19
- maxContentLength: Infinity
20
- };
21
- function throwIfAborted(signal, config, responseData, responseStatus) {
22
- if (signal?.aborted) {
23
- throw new BeeResponseError(config.method || 'get', config.url || '<unknown>', ABORT_ERROR_MESSAGE, responseData, responseStatus, 'ERR_CANCELED');
24
12
  }
25
- }
13
+ };
26
14
  /**
27
15
  * Main function to make HTTP requests.
28
16
  * @param options User defined settings
@@ -32,68 +20,118 @@ export async function http(options, config) {
32
20
  const requestConfig = Objects.deepMerge3(DEFAULT_HTTP_CONFIG, config, options);
33
21
  if (options.signal) {
34
22
  requestConfig.signal = options.signal;
35
- throwIfAborted(options.signal, config);
36
23
  }
37
- maybeReplaceBodyBuffers(requestConfig);
24
+ attachBody(requestConfig);
38
25
  if (requestConfig.params) {
39
- const keys = Object.keys(requestConfig.params);
40
- for (const key of keys) {
41
- const value = requestConfig.params[key];
42
- if (value === undefined) {
43
- delete requestConfig.params[key];
44
- }
26
+ for (const k of Object.keys(requestConfig.params)) {
27
+ if (requestConfig.params[k] === undefined) delete requestConfig.params[k];
45
28
  }
46
29
  }
30
+ const url = buildUrl(requestConfig);
31
+ const method = (requestConfig.method || 'GET').toUpperCase();
32
+ requestConfig.method = method;
33
+ options.onRequest?.({
34
+ method,
35
+ url: Strings.joinUrl([requestConfig.baseURL ?? '', requestConfig.url ?? '']),
36
+ headers: {
37
+ ...requestConfig.headers
38
+ },
39
+ params: requestConfig.params
40
+ });
47
41
  let failedAttempts = 0;
48
42
  while (failedAttempts < MAX_FAILED_ATTEMPTS) {
49
- throwIfAborted(options.signal, config);
50
43
  try {
51
- debug(`${requestConfig.method || 'get'} ${Strings.joinUrl([requestConfig.baseURL, requestConfig.url])}`, {
52
- headers: {
53
- ...requestConfig.headers
54
- },
44
+ debug(`${method} ${url}`, {
45
+ headers: requestConfig.headers,
55
46
  params: requestConfig.params
56
47
  });
57
- maybeRunOnRequestHook(options, requestConfig);
58
- const response = await axios(requestConfig);
59
- return response;
48
+ const res = await fetch(url, requestConfig);
49
+ if (!res.ok) await throwHttpError(method, url, res, requestConfig.responseType);
50
+ return toBeeResponse(res, requestConfig.responseType);
60
51
  } catch (e) {
61
- if (e instanceof AxiosError) {
62
- if (e.code === 'ERR_CANCELED') {
63
- throwIfAborted({
64
- aborted: true
65
- }, config, e.response?.data, e.response?.status);
66
- }
67
- if (e.code === 'ECONNABORTED' && options.endlesslyRetry) {
68
- failedAttempts++;
69
- await System.sleepMillis(failedAttempts < DELAY_THRESHOLD ? DELAY_FAST : DELAY_SLOW);
70
- } else {
71
- throw new BeeResponseError(config.method || 'get', config.url || '<unknown>', e.message, e.response?.data, e.response?.status, e.response?.statusText);
72
- }
52
+ if (e instanceof BeeResponseError) throw e;
53
+ const err = e;
54
+ if (err.name === 'TimeoutError' && options.endlesslyRetry) {
55
+ failedAttempts++;
56
+ await System.sleepMillis(failedAttempts < FAST_RETRY_COUNT ? DELAY_FAST : DELAY_SLOW);
73
57
  } else {
74
- throw e;
58
+ throw toBeeError(err, method, url);
75
59
  }
76
60
  }
77
61
  }
78
62
  throw Error('Max number of failed attempts reached');
79
63
  }
80
- function maybeRunOnRequestHook(options, requestConfig) {
81
- if (options.onRequest) {
82
- options.onRequest({
83
- method: requestConfig.method || 'GET',
84
- url: Strings.joinUrl([requestConfig.baseURL, requestConfig.url]),
85
- headers: {
86
- ...requestConfig.headers
87
- },
88
- params: requestConfig.params
89
- });
64
+ function attachBody(config) {
65
+ if (config.data === undefined) return;
66
+ const data = config.data;
67
+ const isJsonShape = data !== null && typeof data === 'object' && data.constructor === Object || Array.isArray(data);
68
+ if (isJsonShape) {
69
+ config.body = JSON.stringify(data);
70
+ config.headers = {
71
+ 'content-type': 'application/json',
72
+ ...config.headers
73
+ };
74
+ } else {
75
+ config.body = data;
76
+ config.duplex = 'half';
77
+ const ct = data instanceof Blob && data.type ? data.type : 'application/octet-stream';
78
+ config.headers = {
79
+ 'content-type': ct,
80
+ ...config.headers
81
+ };
90
82
  }
91
83
  }
92
- function maybeReplaceBodyBuffers(config) {
93
- if (config.data && config.data instanceof Uint8Array) {
94
- config.data = config.data.buffer.slice(config.data.byteOffset, config.data.byteOffset + config.data.byteLength);
84
+ async function throwHttpError(method, url, res, responseType) {
85
+ const errBody = await toBeeResponse(res, responseType).catch(() => ({
86
+ data: undefined
87
+ }));
88
+ const bodyMsg = typeof errBody.data === 'string' ? errBody.data : JSON.stringify(errBody.data);
89
+ const message = bodyMsg && bodyMsg !== 'undefined' ? `${res.statusText}: ${bodyMsg}` : res.statusText;
90
+ throw new BeeResponseError(method, url, message, errBody.data, res.status, res.statusText);
91
+ }
92
+ function toBeeError(err, method, url) {
93
+ if (err.name === 'AbortError') {
94
+ return new BeeResponseError(method, url, 'Request aborted', undefined, undefined, 'ERR_CANCELED');
95
95
  }
96
- if (config.data && typeof Buffer !== 'undefined' && Buffer.isBuffer(config.data)) {
97
- config.data = config.data.buffer.slice(config.data.byteOffset, config.data.byteOffset + config.data.byteLength);
96
+ const cause = err.cause;
97
+ const message = cause?.message ? `${err.message}: ${cause.message}` : err.message;
98
+ return new BeeResponseError(method, url, message);
99
+ }
100
+ export async function toBeeResponse(res, responseType = 'json') {
101
+ let data;
102
+ switch (responseType) {
103
+ case 'arraybuffer':
104
+ data = await res.arrayBuffer();
105
+ break;
106
+ case 'text':
107
+ data = await res.text();
108
+ break;
109
+ case 'blob':
110
+ data = await res.blob();
111
+ break;
112
+ case 'stream':
113
+ data = res.body;
114
+ break;
115
+ case 'json':
116
+ default:
117
+ {
118
+ const text = await res.text();
119
+ data = text ? JSON.parse(text) : null;
120
+ }
121
+ }
122
+ return {
123
+ data: data,
124
+ status: res.status,
125
+ statusText: res.statusText,
126
+ headers: Object.fromEntries(res.headers.entries()),
127
+ raw: res
128
+ };
129
+ }
130
+ function buildUrl(config) {
131
+ let url = Strings.joinUrl([config.baseURL ?? '', config.url ?? '']);
132
+ if (config.params) {
133
+ const qs = new URLSearchParams(Object.entries(config.params).filter(([, v]) => v !== undefined).map(([k, v]) => [k, String(v)])).toString();
134
+ if (qs) url += `?${qs}`;
98
135
  }
136
+ return url;
99
137
  }
@@ -1,12 +1,13 @@
1
- import { Types } from 'cafe-utility';
1
+ import { z } from 'zod';
2
2
  import { Reference } from "./typed-bytes.js";
3
3
  export class ResourceLocator {
4
4
  constructor(raw) {
5
5
  this.raw = raw;
6
6
  }
7
7
  toString() {
8
- if (Types.isString(this.raw) && this.raw.includes('.eth')) {
9
- return this.raw;
8
+ const asString = z.string().safeParse(this.raw);
9
+ if (asString.success && asString.data.includes('.eth')) {
10
+ return asString.data;
10
11
  }
11
12
  return new Reference(this.raw).toHex();
12
13
  }
@@ -0,0 +1,81 @@
1
+ import { z } from 'zod';
2
+ import { TAGS_LIMIT_MAX, TAGS_LIMIT_MIN } from "../types/index.js";
3
+ import { PublicKey, Reference } from "./typed-bytes.js";
4
+ export { HexStringSchema } from "./hex-schema.js";
5
+ const fnField = z.any().refine(v => z.function().safeParse(v).success, 'expected a function');
6
+ const integerStringField = z.any().transform(v => {
7
+ if (z.bigint().safeParse(v).success) v = String(v);
8
+ return z.string().regex(/^-?\d+$/, 'expected integer string').parse(v);
9
+ });
10
+ const nonNegativeIntegerStringField = z.any().transform(v => {
11
+ if (z.bigint().safeParse(v).success) v = String(v);
12
+ return z.string().regex(/^\d+$/, 'expected non-negative integer string').parse(v);
13
+ });
14
+ export const BeeRequestOptionsSchema = z.object({
15
+ baseURL: z.string().optional(),
16
+ timeout: z.number().int().min(0).optional(),
17
+ headers: z.record(z.string(), z.string()).optional(),
18
+ onRequest: fnField.optional(),
19
+ httpAgent: z.unknown().optional(),
20
+ httpsAgent: z.unknown().optional(),
21
+ endlesslyRetry: z.boolean().optional(),
22
+ signal: z.any().optional()
23
+ });
24
+ export const DownloadOptionsSchema = z.object({
25
+ redundancyStrategy: z.number().int().optional(),
26
+ fallback: z.boolean().optional(),
27
+ timeoutMs: z.number().int().min(0).optional(),
28
+ actPublisher: z.optional(z.any().transform(v => new PublicKey(v))),
29
+ actHistoryAddress: z.optional(z.any().transform(v => new Reference(v))),
30
+ actTimestamp: z.coerce.number().optional()
31
+ });
32
+ export const UploadOptionsSchema = z.object({
33
+ act: z.boolean().optional(),
34
+ actHistoryAddress: z.optional(z.any().transform(v => new Reference(v))),
35
+ deferred: z.boolean().optional(),
36
+ encrypt: z.boolean().optional(),
37
+ pin: z.boolean().optional(),
38
+ tag: z.number().int().min(0).optional()
39
+ });
40
+ export const RedundantUploadOptionsSchema = UploadOptionsSchema.extend({
41
+ redundancyLevel: z.number().int().min(0).optional()
42
+ });
43
+ export const FileUploadOptionsSchema = UploadOptionsSchema.extend({
44
+ size: z.number().int().min(0).optional(),
45
+ contentType: z.string().optional(),
46
+ redundancyLevel: z.number().int().min(0).optional()
47
+ });
48
+ export const CollectionUploadOptionsSchema = UploadOptionsSchema.extend({
49
+ errorDocument: z.string().optional(),
50
+ indexDocument: z.string().optional(),
51
+ redundancyLevel: z.number().int().min(0).optional()
52
+ });
53
+ export const TagInputSchema = z.object({
54
+ uid: z.number().int()
55
+ });
56
+ export const TagUidSchema = z.coerce.number().min(0);
57
+ export const PssMessageHandlerSchema = z.object({
58
+ onMessage: fnField,
59
+ onError: fnField,
60
+ onClose: fnField
61
+ });
62
+ export const GsocMessageHandlerSchema = z.object({
63
+ onMessage: fnField,
64
+ onError: fnField,
65
+ onClose: fnField
66
+ });
67
+ export const PostageBatchOptionsSchema = z.object({
68
+ gasPrice: integerStringField.optional(),
69
+ immutableFlag: z.boolean().optional(),
70
+ label: z.string().optional(),
71
+ waitForUsable: z.boolean().optional(),
72
+ waitForUsableTimeout: z.number().int().min(0).optional()
73
+ });
74
+ export const TransactionOptionsSchema = z.object({
75
+ gasLimit: nonNegativeIntegerStringField.optional(),
76
+ gasPrice: nonNegativeIntegerStringField.optional()
77
+ });
78
+ export const AllTagsOptionsSchema = z.object({
79
+ limit: z.number().int().min(TAGS_LIMIT_MIN).max(TAGS_LIMIT_MAX).optional(),
80
+ offset: z.number().int().min(0).optional()
81
+ });
@@ -142,10 +142,10 @@ export function marshalStamp(signature, batchId, timestamp, index) {
142
142
  return new Bytes(Binary.concatBytes(batchId, index, timestamp, signature));
143
143
  }
144
144
  export function mapPostageBatch(raw, encryption, erasureCodeLevel) {
145
- const usage = getStampUsage(raw.utilization, raw.depth, raw.bucketDepth);
146
145
  const batchTTL = normalizeBatchTTL(raw.batchTTL);
147
146
  const duration = Duration.fromSeconds(batchTTL);
148
147
  const effectiveBytes = getStampEffectiveBytes(raw.depth, encryption, erasureCodeLevel);
148
+ const usage = raw.utilizationRatio ?? getStampUsage(raw.utilization, raw.depth, raw.bucketDepth);
149
149
  return {
150
150
  batchID: new BatchId(raw.batchID),
151
151
  utilization: raw.utilization,
@@ -176,6 +176,7 @@ export function unmapPostageBatch(batch) {
176
176
  return {
177
177
  batchID: batch.batchID.toHex(),
178
178
  utilization: batch.utilization,
179
+ utilizationRatio: batch.usage,
179
180
  usable: batch.usable,
180
181
  label: batch.label,
181
182
  depth: batch.depth,