hbsig 0.0.1

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 (44) hide show
  1. package/cjs/bin_to_str.js +44 -0
  2. package/cjs/collect-body-keys.js +470 -0
  3. package/cjs/encode-array-item.js +110 -0
  4. package/cjs/encode-utils.js +236 -0
  5. package/cjs/encode.js +1318 -0
  6. package/cjs/erl_json.js +317 -0
  7. package/cjs/erl_str.js +1037 -0
  8. package/cjs/flat.js +222 -0
  9. package/cjs/http-message-signatures/httpbis.js +489 -0
  10. package/cjs/http-message-signatures/index.js +25 -0
  11. package/cjs/http-message-signatures/structured-header.js +129 -0
  12. package/cjs/httpsig.js +716 -0
  13. package/cjs/httpsig2.js +1160 -0
  14. package/cjs/id.js +470 -0
  15. package/cjs/index.js +63 -0
  16. package/cjs/send.js +194 -0
  17. package/cjs/signer-utils.js +617 -0
  18. package/cjs/signer.js +606 -0
  19. package/cjs/structured.js +296 -0
  20. package/cjs/test.js +27 -0
  21. package/cjs/utils.js +42 -0
  22. package/esm/bin_to_str.js +46 -0
  23. package/esm/collect-body-keys.js +436 -0
  24. package/esm/encode-array-item.js +112 -0
  25. package/esm/encode-utils.js +185 -0
  26. package/esm/encode.js +1219 -0
  27. package/esm/erl_json.js +289 -0
  28. package/esm/erl_str.js +1139 -0
  29. package/esm/flat.js +196 -0
  30. package/esm/http-message-signatures/httpbis.js +438 -0
  31. package/esm/http-message-signatures/index.js +4 -0
  32. package/esm/http-message-signatures/structured-header.js +105 -0
  33. package/esm/httpsig.js +658 -0
  34. package/esm/httpsig2.js +1097 -0
  35. package/esm/id.js +459 -0
  36. package/esm/index.js +4 -0
  37. package/esm/package.json +3 -0
  38. package/esm/send.js +124 -0
  39. package/esm/signer-utils.js +494 -0
  40. package/esm/signer.js +452 -0
  41. package/esm/structured.js +269 -0
  42. package/esm/test.js +6 -0
  43. package/esm/utils.js +28 -0
  44. package/package.json +28 -0
package/cjs/encode.js ADDED
@@ -0,0 +1,1318 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.enc = enc;
7
+ var _base64url = _interopRequireDefault(require("base64url"));
8
+ var _encodeUtils = require("./encode-utils.js");
9
+ var _encodeArrayItem = _interopRequireDefault(require("./encode-array-item.js"));
10
+ var _collectBodyKeys = _interopRequireDefault(require("./collect-body-keys.js"));
11
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
12
+ function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
13
+ function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
14
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
15
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
16
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
17
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
18
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
19
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
20
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
21
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
22
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
23
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
24
+ var MAX_HEADER_LENGTH = 4096;
25
+
26
+ // Step 1: Process and normalize input values (handle symbols, nested objects/arrays)
27
+ function processInputValues(obj) {
28
+ // Currently this is a no-op, but will be used for input validation/normalization
29
+ return obj;
30
+ }
31
+
32
+ // Step 2: Handle empty object case
33
+ function handleEmptyObject(obj) {
34
+ if (Object.keys(obj).length === 0) {
35
+ return {
36
+ headers: {},
37
+ body: undefined
38
+ };
39
+ }
40
+ return null;
41
+ }
42
+
43
+ // Step 3: Handle single field with empty binary
44
+ function handleSingleEmptyBinaryField(obj) {
45
+ var objKeys = Object.keys(obj);
46
+ if (objKeys.length === 1) {
47
+ var fieldName = objKeys[0];
48
+ var fieldValue = obj[fieldName];
49
+ if ((0, _encodeUtils.isBytes)(fieldValue) && (fieldValue.length === 0 || fieldValue.byteLength === 0)) {
50
+ var headers = {};
51
+ headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"empty-binary\"");
52
+ return {
53
+ headers: headers,
54
+ body: undefined
55
+ };
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+
61
+ // Step 4: Handle single field with binary data
62
+ function handleSingleBinaryField(_x) {
63
+ return _handleSingleBinaryField.apply(this, arguments);
64
+ } // Step 5: Handle single field with primitive value (string/number/boolean/null/undefined/symbol)
65
+ function _handleSingleBinaryField() {
66
+ _handleSingleBinaryField = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(obj) {
67
+ var hasBodyBinary, otherFields, headers, bodyBuffer, bodyArrayBuffer, contentDigest, base64;
68
+ return _regenerator().w(function (_context) {
69
+ while (1) switch (_context.n) {
70
+ case 0:
71
+ hasBodyBinary = obj.body && (0, _encodeUtils.isBytes)(obj.body);
72
+ otherFields = Object.keys(obj).filter(function (k) {
73
+ return k !== "body";
74
+ });
75
+ if (!(hasBodyBinary && otherFields.length === 0)) {
76
+ _context.n = 2;
77
+ break;
78
+ }
79
+ headers = {};
80
+ bodyBuffer = (0, _encodeUtils.toBuffer)(obj.body);
81
+ bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
82
+ _context.n = 1;
83
+ return (0, _encodeUtils.sha256)(bodyArrayBuffer);
84
+ case 1:
85
+ contentDigest = _context.v;
86
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
87
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
88
+ return _context.a(2, {
89
+ headers: headers,
90
+ body: obj.body
91
+ });
92
+ case 2:
93
+ return _context.a(2, null);
94
+ }
95
+ }, _callee);
96
+ }));
97
+ return _handleSingleBinaryField.apply(this, arguments);
98
+ }
99
+ function handleSinglePrimitiveField(_x2) {
100
+ return _handleSinglePrimitiveField.apply(this, arguments);
101
+ } // Step 6a: Handle single field with non-empty binary (not body field)
102
+ function _handleSinglePrimitiveField() {
103
+ _handleSinglePrimitiveField = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(obj) {
104
+ var objKeys, fieldName, fieldValue, headers, bodyContent, encoder, encoded, contentDigest, base64, aoType;
105
+ return _regenerator().w(function (_context2) {
106
+ while (1) switch (_context2.n) {
107
+ case 0:
108
+ objKeys = Object.keys(obj);
109
+ if (!(objKeys.length === 1)) {
110
+ _context2.n = 2;
111
+ break;
112
+ }
113
+ fieldName = objKeys[0];
114
+ fieldValue = obj[fieldName];
115
+ if (!((fieldName === "data" || fieldName === "body") && (typeof fieldValue === "string" || typeof fieldValue === "boolean" || typeof fieldValue === "number" || fieldValue === null || fieldValue === undefined || _typeof(fieldValue) === "symbol"))) {
116
+ _context2.n = 2;
117
+ break;
118
+ }
119
+ headers = {};
120
+ bodyContent = (0, _encodeUtils.encodePrimitiveContent)(fieldValue);
121
+ encoder = new TextEncoder();
122
+ encoded = encoder.encode(bodyContent);
123
+ _context2.n = 1;
124
+ return (0, _encodeUtils.sha256)(encoded.buffer);
125
+ case 1:
126
+ contentDigest = _context2.v;
127
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
128
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
129
+ aoType = (0, _encodeUtils.getAoType)(fieldValue);
130
+ if (aoType === "atom" || aoType === "integer" || aoType === "float") {
131
+ headers["ao-types"] = "".concat(fieldName.toLowerCase(), "=\"").concat(aoType, "\"");
132
+ }
133
+ if (fieldName !== "body") {
134
+ headers["inline-body-key"] = fieldName;
135
+ }
136
+ return _context2.a(2, {
137
+ headers: headers,
138
+ body: bodyContent
139
+ });
140
+ case 2:
141
+ return _context2.a(2, null);
142
+ }
143
+ }, _callee2);
144
+ }));
145
+ return _handleSinglePrimitiveField.apply(this, arguments);
146
+ }
147
+ function handleSingleNonEmptyBinaryField(_x3) {
148
+ return _handleSingleNonEmptyBinaryField.apply(this, arguments);
149
+ } // Step 6: Handle single field with non-ASCII string
150
+ function _handleSingleNonEmptyBinaryField() {
151
+ _handleSingleNonEmptyBinaryField = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(obj) {
152
+ var objKeys, fieldName, fieldValue, headers, bodyBuffer, bodyArrayBuffer, contentDigest, base64;
153
+ return _regenerator().w(function (_context3) {
154
+ while (1) switch (_context3.n) {
155
+ case 0:
156
+ objKeys = Object.keys(obj);
157
+ if (!(objKeys.length === 1)) {
158
+ _context3.n = 2;
159
+ break;
160
+ }
161
+ fieldName = objKeys[0];
162
+ fieldValue = obj[fieldName];
163
+ if (!((0, _encodeUtils.isBytes)(fieldValue) && fieldValue.length > 0)) {
164
+ _context3.n = 2;
165
+ break;
166
+ }
167
+ headers = {};
168
+ bodyBuffer = (0, _encodeUtils.toBuffer)(fieldValue);
169
+ bodyArrayBuffer = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
170
+ _context3.n = 1;
171
+ return (0, _encodeUtils.sha256)(bodyArrayBuffer);
172
+ case 1:
173
+ contentDigest = _context3.v;
174
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
175
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
176
+ if (fieldName !== "body") {
177
+ headers["inline-body-key"] = fieldName;
178
+ }
179
+ return _context3.a(2, {
180
+ headers: headers,
181
+ body: fieldValue
182
+ });
183
+ case 2:
184
+ return _context3.a(2, null);
185
+ }
186
+ }, _callee3);
187
+ }));
188
+ return _handleSingleNonEmptyBinaryField.apply(this, arguments);
189
+ }
190
+ function handleSingleNonAsciiStringField(_x4) {
191
+ return _handleSingleNonAsciiStringField.apply(this, arguments);
192
+ } // Step 7: Collect all keys that need to go in body
193
+ function _handleSingleNonAsciiStringField() {
194
+ _handleSingleNonAsciiStringField = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(obj) {
195
+ var objKeys, fieldName, fieldValue, headers, encoder, encoded, contentDigest, base64;
196
+ return _regenerator().w(function (_context4) {
197
+ while (1) switch (_context4.n) {
198
+ case 0:
199
+ objKeys = Object.keys(obj);
200
+ if (!(objKeys.length === 1)) {
201
+ _context4.n = 2;
202
+ break;
203
+ }
204
+ fieldName = objKeys[0];
205
+ fieldValue = obj[fieldName];
206
+ if (!(typeof fieldValue === "string" && (0, _encodeUtils.hasNonAscii)(fieldValue))) {
207
+ _context4.n = 2;
208
+ break;
209
+ }
210
+ headers = {};
211
+ encoder = new TextEncoder();
212
+ encoded = encoder.encode(fieldValue);
213
+ _context4.n = 1;
214
+ return (0, _encodeUtils.sha256)(encoded.buffer);
215
+ case 1:
216
+ contentDigest = _context4.v;
217
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
218
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
219
+ if (fieldName !== "body") {
220
+ headers["inline-body-key"] = fieldName;
221
+ }
222
+ return _context4.a(2, {
223
+ headers: headers,
224
+ body: fieldValue
225
+ });
226
+ case 2:
227
+ return _context4.a(2, null);
228
+ }
229
+ }, _callee4);
230
+ }));
231
+ return _handleSingleNonAsciiStringField.apply(this, arguments);
232
+ }
233
+ function collectBodyKeysStep(obj) {
234
+ return (0, _collectBodyKeys["default"])(obj);
235
+ }
236
+
237
+ // Step 8: Process fields that can go in headers
238
+ function processHeaderFields(obj, bodyKeys, headers, headerTypes) {
239
+ var _loop = function _loop() {
240
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
241
+ key = _Object$entries$_i[0],
242
+ value = _Object$entries$_i[1];
243
+ var needsBody = bodyKeys.includes(key) || bodyKeys.some(function (k) {
244
+ return k.startsWith("".concat(key, "/"));
245
+ });
246
+ if (!needsBody) {
247
+ if (value === null) {
248
+ headers[key] = '"null"';
249
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
250
+ } else if (value === undefined) {
251
+ headers[key] = '"undefined"';
252
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
253
+ } else if (typeof value === "boolean") {
254
+ headers[key] = "\"".concat(value, "\"");
255
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
256
+ } else if (_typeof(value) === "symbol") {
257
+ headers[key] = "\"".concat(value.description || "Symbol.for()", "\"");
258
+ headerTypes.push("".concat(key.toLowerCase(), "=\"atom\""));
259
+ } else if (typeof value === "number") {
260
+ headers[key] = String(value);
261
+ headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(Number.isInteger(value) ? "integer" : "float", "\""));
262
+ } else if (typeof value === "string") {
263
+ if (value.length === 0) {
264
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
265
+ } else if ((0, _encodeUtils.hasNonAscii)(value)) {
266
+ return 1; // continue
267
+ } else {
268
+ headers[key] = value;
269
+ }
270
+ } else if (Array.isArray(value) && value.length === 0) {
271
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-list\""));
272
+ } else if (Array.isArray(value) && !value.some(function (item) {
273
+ return (0, _encodeUtils.isPojo)(item);
274
+ })) {
275
+ var hasNonAsciiItems = value.some(function (item) {
276
+ return typeof item === "string" && (0, _encodeUtils.hasNonAscii)(item);
277
+ });
278
+ if (!hasNonAsciiItems) {
279
+ var encodedItems = value.map(function (item) {
280
+ return (0, _encodeArrayItem["default"])(item);
281
+ }).join(", ");
282
+ headers[key] = encodedItems;
283
+ headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
284
+ }
285
+ } else if ((0, _encodeUtils.isBytes)(value) && (value.length === 0 || value.byteLength === 0)) {
286
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-binary\""));
287
+ } else if ((0, _encodeUtils.isPojo)(value) && Object.keys(value).length === 0) {
288
+ headerTypes.push("".concat(key.toLowerCase(), "=\"empty-message\""));
289
+ }
290
+ } else {
291
+ // Fields that need body still get type annotations
292
+ var aoType = (0, _encodeUtils.getAoType)(value);
293
+ if (aoType) {
294
+ headerTypes.push("".concat(key.toLowerCase(), "=\"").concat(aoType, "\""));
295
+ }
296
+ }
297
+ };
298
+ for (var _i = 0, _Object$entries = Object.entries(obj); _i < _Object$entries.length; _i++) {
299
+ if (_loop()) continue;
300
+ }
301
+
302
+ // Second pass for array type annotations
303
+ var _loop2 = function _loop2() {
304
+ var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
305
+ key = _Object$entries2$_i[0],
306
+ value = _Object$entries2$_i[1];
307
+ if (Array.isArray(value)) {
308
+ if (bodyKeys.includes(key) || bodyKeys.some(function (k) {
309
+ return k.startsWith("".concat(key, "/"));
310
+ })) {
311
+ if (!headerTypes.some(function (t) {
312
+ return t.startsWith("".concat(key.toLowerCase(), "="));
313
+ })) {
314
+ headerTypes.push("".concat(key.toLowerCase(), "=\"list\""));
315
+ }
316
+ }
317
+ }
318
+ };
319
+ for (var _i2 = 0, _Object$entries2 = Object.entries(obj); _i2 < _Object$entries2.length; _i2++) {
320
+ _loop2();
321
+ }
322
+ }
323
+
324
+ // Step 9: Handle case where all body keys are empty binaries
325
+ function handleAllEmptyBinaryBodyKeys(obj, bodyKeys, headers, headerTypes) {
326
+ if (bodyKeys.length === 0) {
327
+ if (headerTypes.length > 0) {
328
+ headers["ao-types"] = headerTypes.sort().join(", ");
329
+ }
330
+ return {
331
+ headers: headers,
332
+ body: undefined
333
+ };
334
+ }
335
+ var allBodyKeysAreEmptyBinaries = bodyKeys.every(function (key) {
336
+ var value = (0, _encodeUtils.getValueByPath)(obj, key);
337
+ return (0, _encodeUtils.isBytes)(value) && (value.length === 0 || value.byteLength === 0);
338
+ });
339
+ if (allBodyKeysAreEmptyBinaries) {
340
+ if (headerTypes.length > 0) {
341
+ headers["ao-types"] = headerTypes.sort().join(", ");
342
+ }
343
+ return {
344
+ headers: headers,
345
+ body: undefined
346
+ };
347
+ }
348
+ return null;
349
+ }
350
+
351
+ // Step 10: Handle single body key optimization
352
+ function handleSingleBodyKeyOptimization(_x5, _x6, _x7, _x8) {
353
+ return _handleSingleBodyKeyOptimization.apply(this, arguments);
354
+ } // Step 11: Sort body keys
355
+ function _handleSingleBodyKeyOptimization() {
356
+ _handleSingleBodyKeyOptimization = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(obj, bodyKeys, headers, headerTypes) {
357
+ var singleKey, value, contentToHash, bodyContent, bodyBuffer, encoder, encoded, contentDigest, base64;
358
+ return _regenerator().w(function (_context5) {
359
+ while (1) switch (_context5.n) {
360
+ case 0:
361
+ if (!(bodyKeys.length === 1)) {
362
+ _context5.n = 2;
363
+ break;
364
+ }
365
+ singleKey = bodyKeys[0];
366
+ value = (0, _encodeUtils.getValueByPath)(obj, singleKey); // Apply optimization for binary data OR strings with newlines
367
+ if (!((0, _encodeUtils.isBytes)(value) && value.length > 0 || typeof value === "string" && value.includes("\n"))) {
368
+ _context5.n = 2;
369
+ break;
370
+ }
371
+ bodyContent = value;
372
+ if ((0, _encodeUtils.isBytes)(value)) {
373
+ bodyBuffer = (0, _encodeUtils.toBuffer)(value);
374
+ contentToHash = bodyBuffer.buffer.slice(bodyBuffer.byteOffset, bodyBuffer.byteOffset + bodyBuffer.byteLength);
375
+ } else {
376
+ // For strings, encode to UTF-8 for hashing
377
+ encoder = new TextEncoder();
378
+ encoded = encoder.encode(value);
379
+ contentToHash = encoded.buffer;
380
+ bodyContent = value;
381
+ }
382
+ _context5.n = 1;
383
+ return (0, _encodeUtils.sha256)(contentToHash);
384
+ case 1:
385
+ contentDigest = _context5.v;
386
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
387
+ headers["content-digest"] = "sha-256=:".concat(base64, ":");
388
+ if (singleKey !== "body") {
389
+ headers["inline-body-key"] = singleKey;
390
+ }
391
+ if (headerTypes.length > 0) {
392
+ headers["ao-types"] = headerTypes.sort().join(", ");
393
+ }
394
+ return _context5.a(2, {
395
+ headers: headers,
396
+ body: bodyContent
397
+ });
398
+ case 2:
399
+ return _context5.a(2, null);
400
+ }
401
+ }, _callee5);
402
+ }));
403
+ return _handleSingleBodyKeyOptimization.apply(this, arguments);
404
+ }
405
+ function sortBodyKeys(bodyKeys) {
406
+ return bodyKeys.sort(function (a, b) {
407
+ var aIsArrayElement = /\/\d+$/.test(a);
408
+ var bIsArrayElement = /\/\d+$/.test(b);
409
+ var aBase = a.split("/")[0];
410
+ var bBase = b.split("/")[0];
411
+ if (aBase === bBase) {
412
+ if (!aIsArrayElement && bIsArrayElement) {
413
+ return -1;
414
+ }
415
+ if (aIsArrayElement && !bIsArrayElement) {
416
+ return 1;
417
+ }
418
+ if (aIsArrayElement && bIsArrayElement) {
419
+ var aIndex = parseInt(a.split("/")[1]);
420
+ var bIndex = parseInt(b.split("/")[1]);
421
+ return aIndex - bIndex;
422
+ }
423
+ return a.localeCompare(b);
424
+ }
425
+ return a.localeCompare(b);
426
+ });
427
+ }
428
+
429
+ // Step 12: Check for special data/body case
430
+ function checkSpecialDataBodyCase(obj, sortedBodyKeys) {
431
+ return sortedBodyKeys.includes("data") && sortedBodyKeys.includes("body") && obj.data && obj.data.body && (0, _encodeUtils.isBytes)(obj.data.body) && obj.body && obj.body.data && (0, _encodeUtils.isBytes)(obj.body.data);
432
+ }
433
+
434
+ // Step 13.2.2: Handle empty string in nested path
435
+ function handleEmptyStringInNestedPath(bodyKey, value, pathParts) {
436
+ if (typeof value === "string" && value === "" && pathParts.length > 1) {
437
+ var lines = [];
438
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
439
+ lines.push("");
440
+ lines.push("");
441
+ return new Blob([lines.join("\r\n")]);
442
+ }
443
+ return null;
444
+ }
445
+
446
+ // Step 13.2.3.2: Handle arrays with only empty elements
447
+ function handleArrayWithOnlyEmptyElements(bodyKey, value, headers, sortedBodyKeys) {
448
+ var fieldLines = [];
449
+ var partTypes = [];
450
+ value.forEach(function (item, idx) {
451
+ var index = idx + 1;
452
+ var itemType = (0, _encodeUtils.getAoType)(item);
453
+ if (itemType) {
454
+ partTypes.push("".concat(index, "=\"").concat(itemType, "\""));
455
+ }
456
+ });
457
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
458
+ if (isInline) {
459
+ var orderedLines = [];
460
+ if (partTypes.length > 0) {
461
+ orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
462
+ }
463
+ orderedLines.push("content-disposition: inline");
464
+ orderedLines.push("");
465
+ return new Blob([orderedLines.join("\r\n")]);
466
+ } else {
467
+ var _orderedLines = [];
468
+ if (partTypes.length > 0) {
469
+ _orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
470
+ }
471
+ _orderedLines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
472
+ var isLastBodyPart = sortedBodyKeys.indexOf(bodyKey) === sortedBodyKeys.length - 1;
473
+ var hasOnlyTypes = partTypes.length > 0 && fieldLines.length === 0;
474
+ if (isLastBodyPart && hasOnlyTypes) {
475
+ return new Blob([_orderedLines.join("\r\n")]);
476
+ } else {
477
+ _orderedLines.push("");
478
+ return new Blob([_orderedLines.join("\r\n")]);
479
+ }
480
+ }
481
+ }
482
+
483
+ // Step 13.2.3.3: Build indices with own parts
484
+ function buildIndicesWithOwnParts(bodyKey, sortedBodyKeys) {
485
+ var indicesWithOwnParts = new Set();
486
+ sortedBodyKeys.forEach(function (key) {
487
+ if (key.startsWith(bodyKey + "/")) {
488
+ var subPath = key.substring(bodyKey.length + 1);
489
+ var match = subPath.match(/^(\d+)/);
490
+ if (match) {
491
+ indicesWithOwnParts.add(parseInt(match[1]));
492
+ }
493
+ }
494
+ });
495
+ return indicesWithOwnParts;
496
+ }
497
+
498
+ // Step 13.2.3.4: Process array items
499
+ function processArrayItems(value, indicesWithOwnParts, hasNestedObjectParts, pathParts) {
500
+ var fieldLines = [];
501
+ var partTypes = [];
502
+ if (hasNestedObjectParts) {
503
+ value.forEach(function (item, idx) {
504
+ var index = idx + 1;
505
+ if (Array.isArray(item)) {
506
+ partTypes.push("".concat(index, "=\"list\""));
507
+ }
508
+ });
509
+ }
510
+ value.forEach(function (item, idx) {
511
+ var index = idx + 1;
512
+ if (indicesWithOwnParts.has(index)) {
513
+ // This item has its own part - skip it here
514
+ // Don't add type annotation for items that have their own parts
515
+ return;
516
+ }
517
+ if (hasNestedObjectParts && Array.isArray(item) && item.some(function (subItem) {
518
+ return (0, _encodeUtils.isPojo)(subItem);
519
+ })) {
520
+ return;
521
+ }
522
+ if (typeof item === "string" && item === "") {
523
+ partTypes.push("".concat(index, "=\"empty-binary\""));
524
+ } else if ((0, _encodeUtils.isPojo)(item) && Object.keys(item).length === 0) {
525
+ partTypes.push("".concat(index, "=\"empty-message\""));
526
+ } else if ((0, _encodeUtils.isPojo)(item)) {
527
+ // Non-empty objects are handled elsewhere
528
+ } else if (Array.isArray(item)) {
529
+ if (item.length === 0) {
530
+ partTypes.push("".concat(index, "=\"empty-list\""));
531
+ } else {
532
+ partTypes.push("".concat(index, "=\"list\""));
533
+ var encodedItems = item.map(function (subItem) {
534
+ if (typeof subItem === "number") {
535
+ if (Number.isInteger(subItem)) {
536
+ return "\"(ao-type-integer) ".concat(subItem, "\"");
537
+ } else {
538
+ return "\"(ao-type-float) ".concat((0, _encodeUtils.formatFloat)(subItem), "\"");
539
+ }
540
+ } else if (typeof subItem === "string") {
541
+ return "\"".concat(subItem, "\"");
542
+ } else if (subItem === null) {
543
+ return "\"(ao-type-atom) \\\"null\\\"\"";
544
+ } else if (subItem === undefined) {
545
+ return "\"(ao-type-atom) \\\"undefined\\\"\"";
546
+ } else if (_typeof(subItem) === "symbol") {
547
+ var desc = subItem.description || "Symbol.for()";
548
+ return "\"(ao-type-atom) \\\"".concat(desc, "\\\"\"");
549
+ } else if (typeof subItem === "boolean") {
550
+ return "\"(ao-type-atom) \\\"".concat(subItem, "\\\"\"");
551
+ } else if (Array.isArray(subItem)) {
552
+ return (0, _encodeArrayItem["default"])(subItem);
553
+ } else if ((0, _encodeUtils.isBytes)(subItem)) {
554
+ var buffer = (0, _encodeUtils.toBuffer)(subItem);
555
+ if (buffer.length === 0 || buffer.byteLength === 0) {
556
+ return "\"\"";
557
+ }
558
+ return "\"(ao-type-binary)\"";
559
+ } else if ((0, _encodeUtils.isPojo)(subItem)) {
560
+ var json = JSON.stringify(subItem);
561
+ var escaped = json.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
562
+ return "\"(ao-type-map) ".concat(escaped, "\"");
563
+ } else {
564
+ return "\"".concat(String(subItem), "\"");
565
+ }
566
+ }).join(", ");
567
+ fieldLines.push("".concat(index, ": ").concat(encodedItems));
568
+ }
569
+ } else if (typeof item === "number") {
570
+ if (Number.isInteger(item)) {
571
+ partTypes.push("".concat(index, "=\"integer\""));
572
+ fieldLines.push("".concat(index, ": ").concat(item));
573
+ } else {
574
+ partTypes.push("".concat(index, "=\"float\""));
575
+ fieldLines.push("".concat(index, ": ").concat((0, _encodeUtils.formatFloat)(item)));
576
+ }
577
+ } else if (typeof item === "string") {
578
+ fieldLines.push("".concat(index, ": ").concat(item));
579
+ } else if (item === null || item === undefined || _typeof(item) === "symbol" || typeof item === "boolean") {
580
+ partTypes.push("".concat(index, "=\"atom\""));
581
+ if (item === null) {
582
+ fieldLines.push("".concat(index, ": null"));
583
+ } else if (item === undefined) {
584
+ fieldLines.push("".concat(index, ": undefined"));
585
+ } else if (_typeof(item) === "symbol") {
586
+ var desc = item.description || "Symbol.for()";
587
+ fieldLines.push("".concat(index, ": ").concat(desc));
588
+ } else {
589
+ fieldLines.push("".concat(index, ": ").concat(item));
590
+ }
591
+ } else if ((0, _encodeUtils.isBytes)(item)) {
592
+ var buffer = (0, _encodeUtils.toBuffer)(item);
593
+ if (buffer.length === 0) {
594
+ partTypes.push("".concat(index, "=\"empty-binary\""));
595
+ } else {
596
+ partTypes.push("".concat(index, "=\"binary\""));
597
+ }
598
+ }
599
+ });
600
+ return {
601
+ fieldLines: fieldLines,
602
+ partTypes: partTypes
603
+ };
604
+ }
605
+
606
+ // Step 13.2.3.5: Create array body part
607
+ function createArrayBodyPart(bodyKey, fieldLines, partTypes, headers) {
608
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
609
+ if (isInline) {
610
+ var orderedLines = [];
611
+ if (partTypes.length > 0) {
612
+ orderedLines.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
613
+ }
614
+ orderedLines.push("content-disposition: inline");
615
+ if (fieldLines.length > 0) {
616
+ orderedLines.push("");
617
+ var _iterator = _createForOfIteratorHelper(fieldLines),
618
+ _step;
619
+ try {
620
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
621
+ var line = _step.value;
622
+ orderedLines.push(line);
623
+ }
624
+ } catch (err) {
625
+ _iterator.e(err);
626
+ } finally {
627
+ _iterator.f();
628
+ }
629
+ }
630
+ return new Blob([orderedLines.join("\r\n") + "\r\n"]);
631
+ } else {
632
+ var _orderedLines2 = [];
633
+ if (partTypes.length > 0) {
634
+ _orderedLines2.push("ao-types: ".concat((0, _encodeUtils.sortTypeAnnotations)(partTypes).join(", ")));
635
+ }
636
+ _orderedLines2.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
637
+ var _iterator2 = _createForOfIteratorHelper(fieldLines),
638
+ _step2;
639
+ try {
640
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
641
+ var _line = _step2.value;
642
+ _orderedLines2.push(_line);
643
+ }
644
+ } catch (err) {
645
+ _iterator2.e(err);
646
+ } finally {
647
+ _iterator2.f();
648
+ }
649
+ if (fieldLines.length > 0) {
650
+ return new Blob([_orderedLines2.join("\r\n") + "\r\n"]);
651
+ } else {
652
+ return new Blob([_orderedLines2.join("\r\n")]);
653
+ }
654
+ }
655
+ }
656
+
657
+ // Step 13.2.3: Handle array values
658
+ function handleArrayValue(bodyKey, value, headers, sortedBodyKeys, pathParts) {
659
+ var arrayInfo = (0, _encodeUtils.analyzeArray)(value);
660
+ if (arrayInfo.hasOnlyNonEmptyObjects) {
661
+ return null;
662
+ }
663
+ if (arrayInfo.hasOnlyEmptyElements) {
664
+ return handleArrayWithOnlyEmptyElements(bodyKey, value, headers, sortedBodyKeys);
665
+ }
666
+ var indicesWithOwnParts = buildIndicesWithOwnParts(bodyKey, sortedBodyKeys);
667
+ var hasNestedObjectParts = sortedBodyKeys.some(function (key) {
668
+ return key.startsWith(bodyKey + "/") && key.split("/").length > pathParts.length + 1;
669
+ });
670
+ var _processArrayItems = processArrayItems(value, indicesWithOwnParts, hasNestedObjectParts, pathParts),
671
+ fieldLines = _processArrayItems.fieldLines,
672
+ partTypes = _processArrayItems.partTypes;
673
+ return createArrayBodyPart(bodyKey, fieldLines, partTypes, headers);
674
+ }
675
+
676
+ // Step 13.2.4.3: Process object fields
677
+ function processObjectFields(value, bodyKey, sortedBodyKeys) {
678
+ var objectTypes = [];
679
+ var fieldLines = [];
680
+ var binaryFields = [];
681
+ var arrayTypes = [];
682
+
683
+ // First collect array types
684
+ for (var _i3 = 0, _Object$entries3 = Object.entries(value); _i3 < _Object$entries3.length; _i3++) {
685
+ var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
686
+ k = _Object$entries3$_i[0],
687
+ v = _Object$entries3$_i[1];
688
+ if (Array.isArray(v)) {
689
+ arrayTypes.push("".concat(k.toLowerCase(), "=\"").concat(v.length === 0 ? "empty-list" : "list", "\""));
690
+ }
691
+ }
692
+
693
+ // Then process other fields
694
+ for (var _i4 = 0, _Object$entries4 = Object.entries(value); _i4 < _Object$entries4.length; _i4++) {
695
+ var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i4], 2),
696
+ _k = _Object$entries4$_i[0],
697
+ _v = _Object$entries4$_i[1];
698
+ var childPath = "".concat(bodyKey, "/").concat(_k);
699
+ if (sortedBodyKeys.includes(childPath)) {
700
+ continue;
701
+ }
702
+ if (Array.isArray(_v) && _v.some(function (item) {
703
+ return (0, _encodeUtils.isPojo)(item);
704
+ })) {
705
+ var hasOnlyEmpty = _v.every(function (item) {
706
+ return (0, _encodeUtils.isEmpty)(item);
707
+ });
708
+ if (hasOnlyEmpty) {
709
+ continue;
710
+ }
711
+ }
712
+ if (Array.isArray(_v)) {
713
+ // Type already added in arrayTypes
714
+ } else if (_v === null || _v === undefined || _typeof(_v) === "symbol" || typeof _v === "boolean") {
715
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"atom\""));
716
+ } else if (typeof _v === "number") {
717
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"").concat(Number.isInteger(_v) ? "integer" : "float", "\""));
718
+ } else if (typeof _v === "string" && _v.length === 0) {
719
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-binary\""));
720
+ } else if ((0, _encodeUtils.isBytes)(_v) && (_v.length === 0 || _v.byteLength === 0)) {
721
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-binary\""));
722
+ } else if ((0, _encodeUtils.isPojo)(_v) && Object.keys(_v).length === 0) {
723
+ objectTypes.push("".concat(_k.toLowerCase(), "=\"empty-message\""));
724
+ }
725
+ if (typeof _v === "string") {
726
+ if (_v.length === 0) {
727
+ fieldLines.push("".concat(_k, ": "));
728
+ } else {
729
+ fieldLines.push("".concat(_k, ": ").concat(_v));
730
+ }
731
+ } else if (typeof _v === "number") {
732
+ fieldLines.push("".concat(_k, ": ").concat(_v));
733
+ } else if (typeof _v === "boolean") {
734
+ fieldLines.push("".concat(_k, ": \"").concat(_v, "\""));
735
+ } else if (_v === null) {
736
+ fieldLines.push("".concat(_k, ": \"null\""));
737
+ } else if (_v === undefined) {
738
+ fieldLines.push("".concat(_k, ": \"undefined\""));
739
+ } else if (_typeof(_v) === "symbol") {
740
+ var desc = _v.description || "Symbol.for()";
741
+ fieldLines.push("".concat(_k, ": \"").concat(desc, "\""));
742
+ } else if ((0, _encodeUtils.isBytes)(_v)) {
743
+ var buffer = (0, _encodeUtils.toBuffer)(_v);
744
+ binaryFields.push({
745
+ key: _k,
746
+ buffer: buffer
747
+ });
748
+ } else if (Array.isArray(_v) && _v.length > 0) {
749
+ var _childPath = "".concat(bodyKey, "/").concat(_k);
750
+ if (!sortedBodyKeys.includes(_childPath)) {
751
+ var hasObjects = _v.some(function (item) {
752
+ return (0, _encodeUtils.isPojo)(item);
753
+ });
754
+ if (!hasObjects) {
755
+ var encodedItems = _v.map(function (item) {
756
+ return (0, _encodeArrayItem["default"])(item);
757
+ }).join(", ");
758
+ fieldLines.push("".concat(_k, ": ").concat(encodedItems));
759
+ }
760
+ }
761
+ }
762
+ }
763
+ var allTypes = [].concat(arrayTypes, objectTypes);
764
+ return {
765
+ allTypes: allTypes,
766
+ fieldLines: fieldLines,
767
+ binaryFields: binaryFields
768
+ };
769
+ }
770
+
771
+ // Step 13.2.4.5: Create object body part
772
+ function createObjectBodyPart(bodyKey, value, allTypes, fieldLines, binaryFields, headers, sortedBodyKeys) {
773
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
774
+ var lines = [];
775
+ if (isInline) {
776
+ var orderedLines = [];
777
+
778
+ // For inline mode: fields first, then headers
779
+ var _iterator3 = _createForOfIteratorHelper(fieldLines),
780
+ _step3;
781
+ try {
782
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
783
+ var line = _step3.value;
784
+ orderedLines.push(line);
785
+ }
786
+ } catch (err) {
787
+ _iterator3.e(err);
788
+ } finally {
789
+ _iterator3.f();
790
+ }
791
+ if (allTypes.length > 0) {
792
+ orderedLines.push("ao-types: ".concat(allTypes.sort().join(", ")));
793
+ }
794
+ orderedLines.push("content-disposition: inline");
795
+ var binaryFieldsForInline = Object.entries(value).filter(function (_ref) {
796
+ var _ref2 = _slicedToArray(_ref, 2),
797
+ k = _ref2[0],
798
+ v = _ref2[1];
799
+ return (0, _encodeUtils.isBytes)(v) && !sortedBodyKeys.includes("".concat(bodyKey, "/").concat(k));
800
+ }).map(function (_ref3) {
801
+ var _ref4 = _slicedToArray(_ref3, 2),
802
+ k = _ref4[0],
803
+ v = _ref4[1];
804
+ return {
805
+ key: k,
806
+ buffer: (0, _encodeUtils.toBuffer)(v)
807
+ };
808
+ });
809
+ if (binaryFieldsForInline.length > 0) {
810
+ var parts = [];
811
+ // Join all text lines first
812
+ parts.push(Buffer.from(orderedLines.join("\r\n")));
813
+ // Then add binary fields
814
+ var _iterator4 = _createForOfIteratorHelper(binaryFieldsForInline),
815
+ _step4;
816
+ try {
817
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
818
+ var _step4$value = _step4.value,
819
+ key = _step4$value.key,
820
+ buffer = _step4$value.buffer;
821
+ parts.push(Buffer.from("\r\n".concat(key, ": ")));
822
+ parts.push(buffer);
823
+ }
824
+ } catch (err) {
825
+ _iterator4.e(err);
826
+ } finally {
827
+ _iterator4.f();
828
+ }
829
+ parts.push(Buffer.from("\r\n"));
830
+ var fullBody = Buffer.concat(parts);
831
+ return new Blob([fullBody]);
832
+ } else {
833
+ return new Blob([orderedLines.join("\r\n") + "\r\n"]);
834
+ }
835
+ } else {
836
+ // Non-inline mode remains the same
837
+ var _orderedLines3 = [];
838
+ if (allTypes.length > 0) {
839
+ _orderedLines3.push("ao-types: ".concat(allTypes.sort().join(", ")));
840
+ }
841
+ _orderedLines3.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
842
+ var hasBinaryFields = binaryFields && binaryFields.length > 0;
843
+ if (hasBinaryFields || fieldLines.length === 0) {
844
+ _orderedLines3.push("");
845
+ }
846
+ var _iterator5 = _createForOfIteratorHelper(fieldLines),
847
+ _step5;
848
+ try {
849
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
850
+ var _line2 = _step5.value;
851
+ _orderedLines3.push(_line2);
852
+ }
853
+ } catch (err) {
854
+ _iterator5.e(err);
855
+ } finally {
856
+ _iterator5.f();
857
+ }
858
+ if (binaryFields && binaryFields.length > 0) {
859
+ var _parts = [];
860
+ var headerText = _orderedLines3.join("\r\n");
861
+ _parts.push(Buffer.from(headerText));
862
+ for (var i = 0; i < binaryFields.length; i++) {
863
+ var _binaryFields$i = binaryFields[i],
864
+ _key = _binaryFields$i.key,
865
+ _buffer = _binaryFields$i.buffer;
866
+ if (i > 0) {
867
+ _parts.push(Buffer.from("\r\n"));
868
+ }
869
+ _parts.push(Buffer.from("".concat(_key, ": ")));
870
+ _parts.push(_buffer);
871
+ }
872
+ _parts.push(Buffer.from("\r\n"));
873
+ var _fullBody = Buffer.concat(_parts);
874
+ return new Blob([_fullBody]);
875
+ } else {
876
+ if (fieldLines.length > 0) {
877
+ return new Blob([_orderedLines3.join("\r\n") + "\r\n"]);
878
+ } else {
879
+ return new Blob([_orderedLines3.join("\r\n")]);
880
+ }
881
+ }
882
+ }
883
+ }
884
+
885
+ // Step 13.2.4: Handle object values
886
+ function handleObjectValue(obj, bodyKey, value, headers, sortedBodyKeys, pathParts, hasSpecialDataBody) {
887
+ if (Object.keys(value).length === 0) {
888
+ // Skip empty objects in certain contexts
889
+ var parentPath = pathParts.slice(0, -1).join("/");
890
+ var parentValue = parentPath ? (0, _encodeUtils.getValueByPath)(obj, parentPath) : obj;
891
+ if (Array.isArray(parentValue)) {
892
+ var parentArrayInfo = (0, _encodeUtils.analyzeArray)(parentValue);
893
+ if (parentArrayInfo.hasObjects && (parentArrayInfo.hasEmptyStrings || parentArrayInfo.hasEmptyObjects)) {
894
+ return null;
895
+ }
896
+ }
897
+ return null;
898
+ }
899
+
900
+ // Skip special data/body case
901
+ if (hasSpecialDataBody && bodyKey === "data" && Object.keys(value).length === 1 && value.body && (0, _encodeUtils.isBytes)(value.body)) {
902
+ return null;
903
+ }
904
+ var _processObjectFields = processObjectFields(value, bodyKey, sortedBodyKeys),
905
+ allTypes = _processObjectFields.allTypes,
906
+ fieldLines = _processObjectFields.fieldLines,
907
+ binaryFields = _processObjectFields.binaryFields;
908
+
909
+ // Check if object should be skipped
910
+ var hasOnlyEmptyCollections = Object.entries(value).every(function (_ref5) {
911
+ var _ref6 = _slicedToArray(_ref5, 2),
912
+ k = _ref6[0],
913
+ v = _ref6[1];
914
+ return (0, _encodeUtils.isEmpty)(v);
915
+ });
916
+ var hasArraysWithOnlyEmptyElements = Object.entries(value).some(function (_ref7) {
917
+ var _ref8 = _slicedToArray(_ref7, 2),
918
+ k = _ref8[0],
919
+ v = _ref8[1];
920
+ return Array.isArray(v) && v.length > 0 && v.every(function (item) {
921
+ return (0, _encodeUtils.isEmpty)(item);
922
+ });
923
+ });
924
+ var shouldSkipObject = Object.entries(value).every(function (_ref9) {
925
+ var _ref0 = _slicedToArray(_ref9, 2),
926
+ k = _ref0[0],
927
+ v = _ref0[1];
928
+ var childPath = "".concat(bodyKey, "/").concat(k);
929
+ if (sortedBodyKeys.includes(childPath)) return true;
930
+ if (Array.isArray(v) && v.some(function (item) {
931
+ return (0, _encodeUtils.isPojo)(item);
932
+ })) {
933
+ var hasOnlyEmpty = v.every(function (item) {
934
+ return (0, _encodeUtils.isEmpty)(item);
935
+ });
936
+ return hasOnlyEmpty || sortedBodyKeys.includes(childPath);
937
+ }
938
+ return false;
939
+ });
940
+ if (shouldSkipObject && !hasOnlyEmptyCollections && !hasArraysWithOnlyEmptyElements) {
941
+ return null;
942
+ }
943
+ return createObjectBodyPart(bodyKey, value, allTypes, fieldLines, binaryFields, headers, sortedBodyKeys);
944
+ }
945
+
946
+ // Step 13.2.5: Handle primitive values
947
+ function handlePrimitiveValue(bodyKey, value, headers) {
948
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
949
+ var lines = [];
950
+ if (isInline) {
951
+ lines.push("content-disposition: inline");
952
+ } else {
953
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
954
+ }
955
+ if (typeof value === "string") {
956
+ lines.push("");
957
+ lines.push(value);
958
+ return new Blob([lines.join("\r\n")]);
959
+ } else {
960
+ var content = (0, _encodeUtils.encodePrimitiveContent)(value);
961
+ lines.push("");
962
+ lines.push(content);
963
+ return new Blob([lines.join("\r\n")]);
964
+ }
965
+ }
966
+
967
+ // Step 13.2.6: Handle binary values
968
+ function handleBinaryValue(bodyKey, value, headers) {
969
+ var isInline = bodyKey === "body" && headers["inline-body-key"] === "body";
970
+ var lines = [];
971
+ if (isInline) {
972
+ lines.push("content-disposition: inline");
973
+ } else {
974
+ lines.push("content-disposition: form-data;name=\"".concat(bodyKey, "\""));
975
+ }
976
+ var buffer = (0, _encodeUtils.toBuffer)(value);
977
+ // Always keep binary data as raw binary, regardless of whether it's in an array
978
+ var headerText = lines.join("\r\n") + "\r\n\r\n";
979
+ return new Blob([headerText, buffer]);
980
+ }
981
+
982
+ // Step 13.3: Handle special data/body case
983
+ function handleSpecialDataBodyCase(obj, hasSpecialDataBody) {
984
+ if (hasSpecialDataBody && obj.data && obj.data.body && (0, _encodeUtils.isBytes)(obj.data.body)) {
985
+ var buffer = (0, _encodeUtils.toBuffer)(obj.data.body);
986
+ var specialPart = ["content-disposition: form-data;name=\"data/body\"", "", ""].join("\r\n");
987
+ return new Blob([specialPart, buffer]);
988
+ }
989
+ return null;
990
+ }
991
+
992
+ // Step 13: Build body parts for each body key
993
+ function buildBodyParts(obj, sortedBodyKeys, headers, hasSpecialDataBody) {
994
+ // Step 13.1: Initialize body parts collection
995
+ var bodyParts = [];
996
+
997
+ // Step 13.2: Process each body key
998
+ var _iterator6 = _createForOfIteratorHelper(sortedBodyKeys),
999
+ _step6;
1000
+ try {
1001
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1002
+ var bodyKey = _step6.value;
1003
+ // Step 13.2.1: Get value for current body key
1004
+ var value = (0, _encodeUtils.getValueByPath)(obj, bodyKey);
1005
+ var pathParts = bodyKey.split("/");
1006
+
1007
+ // Step 13.2.2: Handle empty string in nested path
1008
+ var emptyStringPart = handleEmptyStringInNestedPath(bodyKey, value, pathParts);
1009
+ if (emptyStringPart) {
1010
+ bodyParts.push(emptyStringPart);
1011
+ continue;
1012
+ }
1013
+
1014
+ // Step 13.2.3: Handle array values
1015
+ if (Array.isArray(value)) {
1016
+ var arrayPart = handleArrayValue(bodyKey, value, headers, sortedBodyKeys, pathParts);
1017
+ if (arrayPart) {
1018
+ bodyParts.push(arrayPart);
1019
+ }
1020
+ continue;
1021
+ }
1022
+
1023
+ // Step 13.2.4: Handle object values
1024
+ if ((0, _encodeUtils.isPojo)(value)) {
1025
+ var objectPart = handleObjectValue(obj, bodyKey, value, headers, sortedBodyKeys, pathParts, hasSpecialDataBody);
1026
+ if (objectPart) {
1027
+ bodyParts.push(objectPart);
1028
+ }
1029
+ continue;
1030
+ }
1031
+
1032
+ // Step 13.2.5: Handle primitive values
1033
+ if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" || value === null || value === undefined || _typeof(value) === "symbol") {
1034
+ var primitivePart = handlePrimitiveValue(bodyKey, value, headers);
1035
+ bodyParts.push(primitivePart);
1036
+ continue;
1037
+ }
1038
+
1039
+ // Step 13.2.6: Handle binary values
1040
+ if ((0, _encodeUtils.isBytes)(value)) {
1041
+ var binaryPart = handleBinaryValue(bodyKey, value, headers);
1042
+ bodyParts.push(binaryPart);
1043
+ continue;
1044
+ }
1045
+ }
1046
+
1047
+ // Step 13.3: Handle special data/body case
1048
+ } catch (err) {
1049
+ _iterator6.e(err);
1050
+ } finally {
1051
+ _iterator6.f();
1052
+ }
1053
+ var specialPart = handleSpecialDataBodyCase(obj, hasSpecialDataBody);
1054
+ if (specialPart) {
1055
+ bodyParts.push(specialPart);
1056
+ }
1057
+
1058
+ // Step 13.4: Return body parts
1059
+ return bodyParts;
1060
+ }
1061
+
1062
+ // Step 14: Generate multipart boundary
1063
+ function generateBoundary(_x9) {
1064
+ return _generateBoundary.apply(this, arguments);
1065
+ } // Step 15: Assemble final multipart body
1066
+ function _generateBoundary() {
1067
+ _generateBoundary = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(bodyParts) {
1068
+ var partsContent, allContent, boundaryHash, boundary;
1069
+ return _regenerator().w(function (_context6) {
1070
+ while (1) switch (_context6.n) {
1071
+ case 0:
1072
+ _context6.n = 1;
1073
+ return Promise.all(bodyParts.map(function (part) {
1074
+ return part.text();
1075
+ }));
1076
+ case 1:
1077
+ partsContent = _context6.v;
1078
+ allContent = partsContent.join("");
1079
+ _context6.n = 2;
1080
+ return (0, _encodeUtils.sha256)(new TextEncoder().encode(allContent));
1081
+ case 2:
1082
+ boundaryHash = _context6.v;
1083
+ boundary = _base64url["default"].encode(Buffer.from(boundaryHash));
1084
+ return _context6.a(2, boundary);
1085
+ }
1086
+ }, _callee6);
1087
+ }));
1088
+ return _generateBoundary.apply(this, arguments);
1089
+ }
1090
+ function assembleMultipartBody(bodyParts, boundary) {
1091
+ var finalParts = [];
1092
+ for (var i = 0; i < bodyParts.length; i++) {
1093
+ if (i === 0) {
1094
+ finalParts.push(new Blob(["--".concat(boundary, "\r\n")]));
1095
+ } else {
1096
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "\r\n")]));
1097
+ }
1098
+ finalParts.push(bodyParts[i]);
1099
+ }
1100
+ finalParts.push(new Blob(["\r\n--".concat(boundary, "--")]));
1101
+ return new Blob(finalParts);
1102
+ }
1103
+
1104
+ // Step 16: Calculate content digest
1105
+ function calculateContentDigest(_x0) {
1106
+ return _calculateContentDigest.apply(this, arguments);
1107
+ } // Step 17: Set final headers (content-type, content-length)
1108
+ function _calculateContentDigest() {
1109
+ _calculateContentDigest = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(body) {
1110
+ var finalContent, contentDigest, base64;
1111
+ return _regenerator().w(function (_context7) {
1112
+ while (1) switch (_context7.n) {
1113
+ case 0:
1114
+ _context7.n = 1;
1115
+ return body.arrayBuffer();
1116
+ case 1:
1117
+ finalContent = _context7.v;
1118
+ if (!(finalContent.byteLength > 0)) {
1119
+ _context7.n = 3;
1120
+ break;
1121
+ }
1122
+ _context7.n = 2;
1123
+ return (0, _encodeUtils.sha256)(finalContent);
1124
+ case 2:
1125
+ contentDigest = _context7.v;
1126
+ base64 = _base64url["default"].toBase64(_base64url["default"].encode(contentDigest));
1127
+ return _context7.a(2, {
1128
+ digest: base64,
1129
+ byteLength: finalContent.byteLength
1130
+ });
1131
+ case 3:
1132
+ return _context7.a(2, {
1133
+ digest: null,
1134
+ byteLength: finalContent.byteLength
1135
+ });
1136
+ }
1137
+ }, _callee7);
1138
+ }));
1139
+ return _calculateContentDigest.apply(this, arguments);
1140
+ }
1141
+ function setFinalHeaders(headers, boundary, contentDigest, byteLength) {
1142
+ headers["content-type"] = "multipart/form-data; boundary=\"".concat(boundary, "\"");
1143
+ if (contentDigest) {
1144
+ headers["content-digest"] = "sha-256=:".concat(contentDigest, ":");
1145
+ }
1146
+ headers["content-length"] = String(byteLength);
1147
+ }
1148
+ function enc() {
1149
+ return _enc.apply(this, arguments);
1150
+ }
1151
+ function _enc() {
1152
+ _enc = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8() {
1153
+ var obj,
1154
+ processedObj,
1155
+ emptyResult,
1156
+ emptyBinaryResult,
1157
+ singleBinaryResult,
1158
+ primitiveResult,
1159
+ nonEmptyBinaryResult,
1160
+ nonAsciiResult,
1161
+ bodyKeys,
1162
+ objKeys,
1163
+ headers,
1164
+ headerTypes,
1165
+ emptyBinaryBodyResult,
1166
+ singleBodyKeyResult,
1167
+ sortedBodyKeys,
1168
+ hasSpecialDataBody,
1169
+ bodyValue,
1170
+ bodyParts,
1171
+ boundary,
1172
+ body,
1173
+ _yield$calculateConte,
1174
+ contentDigest,
1175
+ byteLength,
1176
+ _args8 = arguments;
1177
+ return _regenerator().w(function (_context8) {
1178
+ while (1) switch (_context8.n) {
1179
+ case 0:
1180
+ obj = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {};
1181
+ // Step 1: Process and normalize input values
1182
+ processedObj = processInputValues(obj); // Step 2: Handle empty object case
1183
+ emptyResult = handleEmptyObject(processedObj);
1184
+ if (!emptyResult) {
1185
+ _context8.n = 1;
1186
+ break;
1187
+ }
1188
+ return _context8.a(2, emptyResult);
1189
+ case 1:
1190
+ // Step 3: Handle single field with empty binary
1191
+ emptyBinaryResult = handleSingleEmptyBinaryField(processedObj);
1192
+ if (!emptyBinaryResult) {
1193
+ _context8.n = 2;
1194
+ break;
1195
+ }
1196
+ return _context8.a(2, emptyBinaryResult);
1197
+ case 2:
1198
+ _context8.n = 3;
1199
+ return handleSingleBinaryField(processedObj);
1200
+ case 3:
1201
+ singleBinaryResult = _context8.v;
1202
+ if (!singleBinaryResult) {
1203
+ _context8.n = 4;
1204
+ break;
1205
+ }
1206
+ return _context8.a(2, singleBinaryResult);
1207
+ case 4:
1208
+ _context8.n = 5;
1209
+ return handleSinglePrimitiveField(processedObj);
1210
+ case 5:
1211
+ primitiveResult = _context8.v;
1212
+ if (!primitiveResult) {
1213
+ _context8.n = 6;
1214
+ break;
1215
+ }
1216
+ return _context8.a(2, primitiveResult);
1217
+ case 6:
1218
+ _context8.n = 7;
1219
+ return handleSingleNonEmptyBinaryField(processedObj);
1220
+ case 7:
1221
+ nonEmptyBinaryResult = _context8.v;
1222
+ if (!nonEmptyBinaryResult) {
1223
+ _context8.n = 8;
1224
+ break;
1225
+ }
1226
+ return _context8.a(2, nonEmptyBinaryResult);
1227
+ case 8:
1228
+ _context8.n = 9;
1229
+ return handleSingleNonAsciiStringField(processedObj);
1230
+ case 9:
1231
+ nonAsciiResult = _context8.v;
1232
+ if (!nonAsciiResult) {
1233
+ _context8.n = 10;
1234
+ break;
1235
+ }
1236
+ return _context8.a(2, nonAsciiResult);
1237
+ case 10:
1238
+ // Step 7: Collect all keys that need to go in body
1239
+ bodyKeys = collectBodyKeysStep(processedObj);
1240
+ objKeys = Object.keys(obj);
1241
+ headers = {};
1242
+ headerTypes = []; // Step 8: Process fields that can go in headers
1243
+ processHeaderFields(obj, bodyKeys, headers, headerTypes);
1244
+
1245
+ // Step 9: Handle case where all body keys are empty binaries
1246
+ emptyBinaryBodyResult = handleAllEmptyBinaryBodyKeys(obj, bodyKeys, headers, headerTypes);
1247
+ if (!emptyBinaryBodyResult) {
1248
+ _context8.n = 11;
1249
+ break;
1250
+ }
1251
+ return _context8.a(2, emptyBinaryBodyResult);
1252
+ case 11:
1253
+ _context8.n = 12;
1254
+ return handleSingleBodyKeyOptimization(obj, bodyKeys, headers, headerTypes);
1255
+ case 12:
1256
+ singleBodyKeyResult = _context8.v;
1257
+ if (!singleBodyKeyResult) {
1258
+ _context8.n = 13;
1259
+ break;
1260
+ }
1261
+ return _context8.a(2, singleBodyKeyResult);
1262
+ case 13:
1263
+ // Step 11: Sort body keys
1264
+ sortedBodyKeys = sortBodyKeys(bodyKeys); // Step 12: Check for special data/body case
1265
+ hasSpecialDataBody = checkSpecialDataBodyCase(obj, sortedBodyKeys); // Only add body-keys header if there are actual body keys
1266
+ if (sortedBodyKeys.length > 0) {
1267
+ headers["body-keys"] = sortedBodyKeys.map(function (k) {
1268
+ return "\"".concat(k, "\"");
1269
+ }).join(", ");
1270
+ }
1271
+
1272
+ // Special case: single body key named "body" containing an object
1273
+ if (!hasSpecialDataBody && sortedBodyKeys.length === 1 && sortedBodyKeys[0] === "body") {
1274
+ bodyValue = obj.body;
1275
+ if ((0, _encodeUtils.isPojo)(bodyValue)) {
1276
+ headers["inline-body-key"] = "body";
1277
+ }
1278
+ }
1279
+ if (headerTypes.length > 0) {
1280
+ headers["ao-types"] = headerTypes.sort().join(", ");
1281
+ }
1282
+
1283
+ // Step 13: Build body parts for each body key
1284
+ bodyParts = buildBodyParts(obj, sortedBodyKeys, headers, hasSpecialDataBody); // If no body parts were created, return headers only
1285
+ if (!(bodyParts.length === 0)) {
1286
+ _context8.n = 14;
1287
+ break;
1288
+ }
1289
+ return _context8.a(2, {
1290
+ headers: headers,
1291
+ body: undefined
1292
+ });
1293
+ case 14:
1294
+ _context8.n = 15;
1295
+ return generateBoundary(bodyParts);
1296
+ case 15:
1297
+ boundary = _context8.v;
1298
+ // Step 15: Assemble final multipart body
1299
+ body = assembleMultipartBody(bodyParts, boundary); // Step 16: Calculate content digest
1300
+ _context8.n = 16;
1301
+ return calculateContentDigest(body);
1302
+ case 16:
1303
+ _yield$calculateConte = _context8.v;
1304
+ contentDigest = _yield$calculateConte.digest;
1305
+ byteLength = _yield$calculateConte.byteLength;
1306
+ // Step 17: Set final headers (content-type, content-length)
1307
+ setFinalHeaders(headers, boundary, contentDigest, byteLength);
1308
+
1309
+ // Step 18: Return result
1310
+ return _context8.a(2, {
1311
+ headers: headers,
1312
+ body: body
1313
+ });
1314
+ }
1315
+ }, _callee8);
1316
+ }));
1317
+ return _enc.apply(this, arguments);
1318
+ }