kassza 0.13.0 → 0.14.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 (164) hide show
  1. package/README.en.md +48 -0
  2. package/README.md +152 -22
  3. package/agents/README.md +6 -1
  4. package/agents/api.md +64 -12
  5. package/agents/pitfalls.md +12 -1
  6. package/agents/recipes.md +67 -8
  7. package/agents/skills/kassza/SKILL.md +3 -0
  8. package/agents/skills/migrate-from-szamlazz-js/SKILL.md +39 -0
  9. package/dist/batch/index.cjs +346 -0
  10. package/dist/batch/index.d.cts +91 -0
  11. package/dist/batch/index.d.ts +91 -0
  12. package/dist/batch/index.js +339 -0
  13. package/dist/cli.cjs +105 -14
  14. package/dist/cli.js +104 -13
  15. package/dist/{client-C-PdfL_P.cjs → client-CLFvJCVW.cjs} +358 -181
  16. package/dist/{client-CfaS1-Jx.js → client-Cvf-hTz_.js} +311 -152
  17. package/dist/{client-6MkeuFqD.d.ts → client-DeWWQ-RZ.d.ts} +99 -26
  18. package/dist/{client-B5FryKxJ.d.cts → client-SVZu25MB.d.cts} +99 -26
  19. package/dist/{context-DXNbTPwz.d.cts → context-CFNKzStE.d.cts} +82 -58
  20. package/dist/{context-BxQlIlug.d.ts → context-kb33TgzE.d.ts} +82 -58
  21. package/dist/cookie-stores/index.cjs +21 -150
  22. package/dist/cookie-stores/index.d.cts +4 -63
  23. package/dist/cookie-stores/index.d.ts +4 -63
  24. package/dist/cookie-stores/index.js +3 -144
  25. package/dist/create-CflXrPip.js +204 -0
  26. package/dist/create-CvUvLUaT.cjs +257 -0
  27. package/dist/{create-once-DgMtKKcG.cjs → create-once-9yxR_Er_.cjs} +285 -33
  28. package/dist/create-once-Bh6fOWkW.d.cts +20 -0
  29. package/dist/{create-once-Cz621l8r.js → create-once-Ca2gMk1h.js} +250 -34
  30. package/dist/create-once-VKp0tVow.d.ts +20 -0
  31. package/dist/data-link/index.cjs +4 -4
  32. package/dist/data-link/index.d.cts +2 -52
  33. package/dist/data-link/index.d.ts +2 -52
  34. package/dist/data-link/index.js +4 -4
  35. package/dist/delegation/index.cjs +4 -4
  36. package/dist/delegation/index.d.cts +2 -2
  37. package/dist/delegation/index.d.ts +2 -2
  38. package/dist/delegation/index.js +4 -4
  39. package/dist/{errors-DLrb0g64.js → errors-DtN4g5Z9.js} +9 -1
  40. package/dist/{errors-DxeuTslP.cjs → errors-EE96_6D_.cjs} +20 -0
  41. package/dist/{get-Csm2n0rZ.cjs → get-BdMTseh4.cjs} +9 -183
  42. package/dist/{get-DT3JEgQ6.js → get-CZEShCcj.js} +4 -124
  43. package/dist/index-BhUPY_EH.d.cts +109 -0
  44. package/dist/index-BqGgQ4t3.d.ts +109 -0
  45. package/dist/{index-CYAGCdKJ.d.cts → index-C-7yWV7L.d.cts} +24 -1
  46. package/dist/{index-CYAGCdKJ.d.ts → index-C-7yWV7L.d.ts} +24 -1
  47. package/dist/index.cjs +19 -5
  48. package/dist/index.d.cts +10 -20
  49. package/dist/index.d.ts +10 -20
  50. package/dist/index.js +6 -6
  51. package/dist/ipn/index.cjs +26 -5
  52. package/dist/ipn/index.d.cts +12 -1
  53. package/dist/ipn/index.d.ts +12 -1
  54. package/dist/ipn/index.js +26 -6
  55. package/dist/{issue-AGRohSm7.cjs → issue-Bin4tKD_.cjs} +416 -342
  56. package/dist/{issue-DtSLpVdJ.js → issue-DMA1Nbr1.js} +394 -266
  57. package/dist/journal/index.cjs +454 -0
  58. package/dist/journal/index.d.cts +18 -0
  59. package/dist/journal/index.d.ts +18 -0
  60. package/dist/journal/index.js +445 -0
  61. package/dist/journal-DvI81Kt7.d.cts +114 -0
  62. package/dist/journal-Y9qrIB8G.d.ts +114 -0
  63. package/dist/mcp/index.cjs +1 -1
  64. package/dist/mcp/index.d.cts +1 -1
  65. package/dist/mcp/index.d.ts +1 -1
  66. package/dist/mcp/index.js +1 -1
  67. package/dist/money/index.cjs +2 -1
  68. package/dist/money/index.d.cts +2 -2
  69. package/dist/money/index.d.ts +2 -2
  70. package/dist/money/index.js +2 -2
  71. package/dist/{money-t7uy1n91.js → money-Cw457SD6.js} +95 -3
  72. package/dist/{money-BxytJW6f.cjs → money-K9j0wPit.cjs} +99 -1
  73. package/dist/nav/index.cjs +2 -2
  74. package/dist/nav/index.d.cts +1 -1
  75. package/dist/nav/index.d.ts +1 -1
  76. package/dist/nav/index.js +2 -2
  77. package/dist/{nav-BEwcX7-N.cjs → nav-BNbc8U0R.cjs} +1 -1
  78. package/dist/{nav-CK1WgYo7.js → nav-BcCerwWS.js} +1 -1
  79. package/dist/node/index.cjs +124 -0
  80. package/dist/node/index.d.cts +35 -0
  81. package/dist/node/index.d.ts +35 -0
  82. package/dist/node/index.js +120 -0
  83. package/dist/observe/index.cjs +311 -0
  84. package/dist/observe/index.d.cts +53 -0
  85. package/dist/observe/index.d.ts +53 -0
  86. package/dist/observe/index.js +303 -0
  87. package/dist/once-BN_3B5OF.cjs +103 -0
  88. package/dist/once-CqqZxsXG.js +74 -0
  89. package/dist/{parse-C608ehqM.js → parse-Cr7yQ3_z.js} +2 -2
  90. package/dist/{parse-BJj-aqKy.cjs → parse-DOA2XQ3e.cjs} +2 -2
  91. package/dist/payments/barion.cjs +26 -2
  92. package/dist/payments/barion.d.cts +2 -2
  93. package/dist/payments/barion.d.ts +2 -2
  94. package/dist/payments/barion.js +26 -2
  95. package/dist/payments/index.cjs +7 -2
  96. package/dist/payments/index.d.cts +4 -4
  97. package/dist/payments/index.d.ts +4 -4
  98. package/dist/payments/index.js +3 -3
  99. package/dist/payments/paypal.cjs +16 -2
  100. package/dist/payments/paypal.d.cts +2 -2
  101. package/dist/payments/paypal.d.ts +2 -2
  102. package/dist/payments/paypal.js +16 -2
  103. package/dist/payments/revolut.cjs +16 -2
  104. package/dist/payments/revolut.d.cts +2 -2
  105. package/dist/payments/revolut.d.ts +2 -2
  106. package/dist/payments/revolut.js +16 -2
  107. package/dist/payments/simplepay.cjs +36 -4
  108. package/dist/payments/simplepay.d.cts +2 -2
  109. package/dist/payments/simplepay.d.ts +2 -2
  110. package/dist/payments/simplepay.js +36 -4
  111. package/dist/payments/stripe.cjs +19 -2
  112. package/dist/payments/stripe.d.cts +2 -2
  113. package/dist/payments/stripe.d.ts +2 -2
  114. package/dist/payments/stripe.js +19 -2
  115. package/dist/push-BXj0Sf0Z.d.ts +52 -0
  116. package/dist/push-D4nNbCNV.d.cts +52 -0
  117. package/dist/reference-B5TATqb5.js +124 -0
  118. package/dist/reference-BIdYMK0t.cjs +183 -0
  119. package/dist/reports/index.cjs +1 -1
  120. package/dist/reports/index.d.cts +1 -1
  121. package/dist/reports/index.d.ts +1 -1
  122. package/dist/reports/index.js +1 -1
  123. package/dist/{serialize-DSE_o9RK.js → serialize-B2eFh3D-.js} +5 -1
  124. package/dist/{serialize-BXOww1Uq.cjs → serialize-CquIsxA-.cjs} +5 -1
  125. package/dist/{server-Cd8HB661.js → server-BrJUbXs7.js} +8 -7
  126. package/dist/{server-C6PoNkdD.cjs → server-Dw9j8Mnd.cjs} +17 -16
  127. package/dist/session-Ckl5eJhV.d.ts +7 -0
  128. package/dist/{session-CKOuE6Jc.cjs → session-DeM5vjvC.cjs} +69 -13
  129. package/dist/{session-rMKaJcmq.js → session-SaEEXu2N.js} +58 -14
  130. package/dist/session-YbChChx7.d.cts +7 -0
  131. package/dist/storage/fs.cjs +1 -1
  132. package/dist/storage/fs.js +1 -1
  133. package/dist/storage/index.cjs +1 -1
  134. package/dist/storage/index.js +1 -1
  135. package/dist/store-C1rHd9DB.d.cts +19 -0
  136. package/dist/store-C1rHd9DB.d.ts +19 -0
  137. package/dist/stores/index.cjs +24 -0
  138. package/dist/stores/index.d.cts +4 -0
  139. package/dist/stores/index.d.ts +4 -0
  140. package/dist/stores/index.js +3 -0
  141. package/dist/stores-BNrS0dWl.cjs +506 -0
  142. package/dist/stores-DhjGBrl_.js +441 -0
  143. package/dist/testing/index.cjs +28 -16
  144. package/dist/testing/index.d.cts +6 -3
  145. package/dist/testing/index.d.ts +6 -3
  146. package/dist/testing/index.js +26 -14
  147. package/dist/{types-BVeR7KyU.d.ts → types-B1A8mUIE.d.cts} +13 -1
  148. package/dist/{types-BVeR7KyU.d.cts → types-ByAEvGsZ.d.ts} +13 -1
  149. package/dist/{types-k--zHf4l.d.ts → types-D1zDOH_F.d.ts} +1 -1
  150. package/dist/{types-DH8QoNZK.d.cts → types-lnKkQdot.d.cts} +1 -1
  151. package/dist/warnings-B3DXnveC.d.cts +31 -0
  152. package/dist/warnings-B3DXnveC.d.ts +31 -0
  153. package/dist/warnings-DeIw5RFj.cjs +20 -0
  154. package/dist/warnings-DwTl5J-2.js +15 -0
  155. package/dist/{webhook-CrEGohbg.js → webhook-CQVShAfI.js} +44 -1
  156. package/dist/{webhook-81giRMdQ.cjs → webhook-Ckj-_hPD.cjs} +67 -0
  157. package/dist/webhook-CmdhGiH5.d.cts +11 -0
  158. package/dist/webhook-D6lEejob.d.ts +11 -0
  159. package/llms.txt +4 -3
  160. package/package.json +92 -4
  161. package/dist/session-Dm_45x8K.d.cts +0 -11
  162. package/dist/session-Dm_45x8K.d.ts +0 -11
  163. package/dist/webhook-CpCMHhn2.d.ts +0 -6
  164. package/dist/webhook-CpMJuP6c.d.cts +0 -6
@@ -1,4 +1,4 @@
1
- import { i as KasszaOptions } from "../client-6MkeuFqD.js";
1
+ import { i as KasszaOptions } from "../client-DeWWQ-RZ.js";
2
2
  //#region src/mcp/protocol.d.ts
3
3
  export declare const MCP_MODERN_VERSIONS: readonly string[];
4
4
  export declare const MCP_LEGACY_VERSIONS: readonly string[];
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createConfirmations, c as MCP_MODERN_VERSIONS, i as canonicalJson, l as MCP_SUPPORTED_VERSIONS, o as ToolInputError, r as DEFAULT_CONFIRMATION_TTL_MS, s as MCP_LEGACY_VERSIONS, t as createKasszaMcpServer } from "../server-Cd8HB661.js";
1
+ import { a as createConfirmations, c as MCP_MODERN_VERSIONS, i as canonicalJson, l as MCP_SUPPORTED_VERSIONS, o as ToolInputError, r as DEFAULT_CONFIRMATION_TTL_MS, s as MCP_LEGACY_VERSIONS, t as createKasszaMcpServer } from "../server-BrJUbXs7.js";
2
2
  export { DEFAULT_CONFIRMATION_TTL_MS, MCP_LEGACY_VERSIONS, MCP_MODERN_VERSIONS, MCP_SUPPORTED_VERSIONS, ToolInputError, canonicalJson, createConfirmations, createKasszaMcpServer };
@@ -1,10 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rounding = require("../rounding-TxoWy2ww.cjs");
3
3
  const require_vat = require("../vat-g35srbNG.cjs");
4
- const require_money = require("../money-BxytJW6f.cjs");
4
+ const require_money = require("../money-K9j0wPit.cjs");
5
5
  exports.NUMERIC_VAT_RATES = require_vat.NUMERIC_VAT_RATES;
6
6
  exports.SPECIAL_VAT_CODES = require_vat.SPECIAL_VAT_CODES;
7
7
  exports.addMoney = require_rounding.addMoney;
8
+ exports.allocateRefund = require_money.allocateRefund;
8
9
  exports.calculateInvoiceItem = require_money.calculateInvoiceItem;
9
10
  exports.calculateItemAmounts = require_money.calculateItemAmounts;
10
11
  exports.calculateReceiptItem = require_money.calculateReceiptItem;
@@ -1,2 +1,2 @@
1
- import { _ as VatRate, a as DocumentTotals, b as isVatRate, c as VatBreakdown, d as calculateReceiptItem, f as summarizeItems, g as SpecialVatCode, h as SPECIAL_VAT_CODES, i as DocumentKind, l as calculateInvoiceItem, m as NumericVatRate, n as decimalPlaces, o as ItemAmounts, p as NUMERIC_VAT_RATES, r as roundMoney, s as ItemPriceInput, t as addMoney, u as calculateItemAmounts, v as formatVatRate, x as vatPercentage, y as isHuf } from "../index-CYAGCdKJ.cjs";
2
- export { type DocumentKind, type DocumentTotals, type ItemAmounts, type ItemPriceInput, NUMERIC_VAT_RATES, type NumericVatRate, SPECIAL_VAT_CODES, type SpecialVatCode, type VatBreakdown, type VatRate, addMoney, calculateInvoiceItem, calculateItemAmounts, calculateReceiptItem, decimalPlaces, formatVatRate, isHuf, isVatRate, roundMoney, summarizeItems, vatPercentage };
1
+ import { C as formatVatRate, E as vatPercentage, S as VatRate, T as isVatRate, _ as summarizeItems, a as RefundAllocation, b as SPECIAL_VAT_CODES, c as allocateRefund, d as ItemAmounts, f as ItemPriceInput, g as calculateReceiptItem, h as calculateItemAmounts, i as AllocateRefundOptions, l as DocumentKind, m as calculateInvoiceItem, n as decimalPlaces, o as RefundVat, p as VatBreakdown, r as roundMoney, s as RefundableItem, t as addMoney, u as DocumentTotals, v as NUMERIC_VAT_RATES, w as isHuf, x as SpecialVatCode, y as NumericVatRate } from "../index-C-7yWV7L.cjs";
2
+ export { type AllocateRefundOptions, type DocumentKind, type DocumentTotals, type ItemAmounts, type ItemPriceInput, NUMERIC_VAT_RATES, type NumericVatRate, type RefundAllocation, type RefundVat, type RefundableItem, SPECIAL_VAT_CODES, type SpecialVatCode, type VatBreakdown, type VatRate, addMoney, allocateRefund, calculateInvoiceItem, calculateItemAmounts, calculateReceiptItem, decimalPlaces, formatVatRate, isHuf, isVatRate, roundMoney, summarizeItems, vatPercentage };
@@ -1,2 +1,2 @@
1
- import { _ as VatRate, a as DocumentTotals, b as isVatRate, c as VatBreakdown, d as calculateReceiptItem, f as summarizeItems, g as SpecialVatCode, h as SPECIAL_VAT_CODES, i as DocumentKind, l as calculateInvoiceItem, m as NumericVatRate, n as decimalPlaces, o as ItemAmounts, p as NUMERIC_VAT_RATES, r as roundMoney, s as ItemPriceInput, t as addMoney, u as calculateItemAmounts, v as formatVatRate, x as vatPercentage, y as isHuf } from "../index-CYAGCdKJ.js";
2
- export { type DocumentKind, type DocumentTotals, type ItemAmounts, type ItemPriceInput, NUMERIC_VAT_RATES, type NumericVatRate, SPECIAL_VAT_CODES, type SpecialVatCode, type VatBreakdown, type VatRate, addMoney, calculateInvoiceItem, calculateItemAmounts, calculateReceiptItem, decimalPlaces, formatVatRate, isHuf, isVatRate, roundMoney, summarizeItems, vatPercentage };
1
+ import { C as formatVatRate, E as vatPercentage, S as VatRate, T as isVatRate, _ as summarizeItems, a as RefundAllocation, b as SPECIAL_VAT_CODES, c as allocateRefund, d as ItemAmounts, f as ItemPriceInput, g as calculateReceiptItem, h as calculateItemAmounts, i as AllocateRefundOptions, l as DocumentKind, m as calculateInvoiceItem, n as decimalPlaces, o as RefundVat, p as VatBreakdown, r as roundMoney, s as RefundableItem, t as addMoney, u as DocumentTotals, v as NUMERIC_VAT_RATES, w as isHuf, x as SpecialVatCode, y as NumericVatRate } from "../index-C-7yWV7L.js";
2
+ export { type AllocateRefundOptions, type DocumentKind, type DocumentTotals, type ItemAmounts, type ItemPriceInput, NUMERIC_VAT_RATES, type NumericVatRate, type RefundAllocation, type RefundVat, type RefundableItem, SPECIAL_VAT_CODES, type SpecialVatCode, type VatBreakdown, type VatRate, addMoney, allocateRefund, calculateInvoiceItem, calculateItemAmounts, calculateReceiptItem, decimalPlaces, formatVatRate, isHuf, isVatRate, roundMoney, summarizeItems, vatPercentage };
@@ -1,4 +1,4 @@
1
1
  import { n as decimalPlaces, r as roundMoney, t as addMoney } from "../rounding-BLyHjjI5.js";
2
2
  import { a as isVatRate, i as isHuf, n as SPECIAL_VAT_CODES, o as vatPercentage, r as formatVatRate, t as NUMERIC_VAT_RATES } from "../vat-v_dcWCto.js";
3
- import { i as summarizeItems, n as calculateItemAmounts, r as calculateReceiptItem, t as calculateInvoiceItem } from "../money-t7uy1n91.js";
4
- export { NUMERIC_VAT_RATES, SPECIAL_VAT_CODES, addMoney, calculateInvoiceItem, calculateItemAmounts, calculateReceiptItem, decimalPlaces, formatVatRate, isHuf, isVatRate, roundMoney, summarizeItems, vatPercentage };
3
+ import { a as summarizeItems, i as calculateReceiptItem, n as calculateInvoiceItem, r as calculateItemAmounts, t as allocateRefund } from "../money-Cw457SD6.js";
4
+ export { NUMERIC_VAT_RATES, SPECIAL_VAT_CODES, addMoney, allocateRefund, calculateInvoiceItem, calculateItemAmounts, calculateReceiptItem, decimalPlaces, formatVatRate, isHuf, isVatRate, roundMoney, summarizeItems, vatPercentage };
@@ -1,5 +1,5 @@
1
- import { n as SzamlazzError } from "./errors-DLrb0g64.js";
2
- import { r as roundMoney } from "./rounding-BLyHjjI5.js";
1
+ import { r as SzamlazzError } from "./errors-DtN4g5Z9.js";
2
+ import { n as decimalPlaces, r as roundMoney } from "./rounding-BLyHjjI5.js";
3
3
  import { a as isVatRate, i as isHuf, o as vatPercentage } from "./vat-v_dcWCto.js";
4
4
  //#region src/money/items.ts
5
5
  const FOREIGN_CURRENCY_DECIMALS = 2;
@@ -174,4 +174,96 @@ function summarizeItems(items) {
174
174
  };
175
175
  }
176
176
  //#endregion
177
- export { summarizeItems as i, calculateItemAmounts as n, calculateReceiptItem as r, calculateInvoiceItem as t };
177
+ //#region src/money/refund.ts
178
+ function invalid(message) {
179
+ return new SzamlazzError(message, { category: "validation" });
180
+ }
181
+ function toMinor(value, decimals, field) {
182
+ if (!Number.isFinite(value)) throw invalid(`A(z) ${field} nem véges szám: ${value}`);
183
+ if (decimalPlaces(value) > decimals) throw invalid(`A(z) ${field} (${value}) több tizedesjegyet tartalmaz, mint amennyit a bizonylat pénzneme enged (${decimals}).`);
184
+ return BigInt(Math.round(Number((value * 10 ** decimals).toPrecision(15))));
185
+ }
186
+ function fromMinor(value, decimals) {
187
+ return Number(value) / 10 ** decimals;
188
+ }
189
+ function resolveDecimals(value) {
190
+ if (value === void 0) return 0;
191
+ if (!Number.isInteger(value) || value < 0 || value > 6) throw invalid(`A decimals értéke 0 és 6 közötti egész legyen, kapott: ${value}`);
192
+ return value;
193
+ }
194
+ function outranks(weights, first, firstUnit, second, secondUnit) {
195
+ const left = (weights[first] ?? 0n) * (2n * secondUnit + 1n);
196
+ const right = (weights[second] ?? 0n) * (2n * firstUnit + 1n);
197
+ if (left !== right) return left > right;
198
+ return first < second;
199
+ }
200
+ function bestOpen(weights, shares) {
201
+ let best = -1;
202
+ for (let index = 0; index < weights.length; index++) {
203
+ const share = shares[index] ?? 0n;
204
+ if (share >= (weights[index] ?? 0n)) continue;
205
+ if (best === -1 || outranks(weights, index, share, best, shares[best] ?? 0n)) best = index;
206
+ }
207
+ return best;
208
+ }
209
+ function worstTaken(weights, shares) {
210
+ let worst = -1;
211
+ for (let index = 0; index < weights.length; index++) {
212
+ const share = shares[index] ?? 0n;
213
+ if (share === 0n) continue;
214
+ if (worst === -1 || outranks(weights, worst, (shares[worst] ?? 0n) - 1n, index, share - 1n)) worst = index;
215
+ }
216
+ return worst;
217
+ }
218
+ function apportion(weights, amount) {
219
+ const total = weights.reduce((sum, weight) => sum + weight, 0n);
220
+ if (amount === 0n || total === 0n) return weights.map(() => 0n);
221
+ if (amount === total) return [...weights];
222
+ const shares = weights.map((weight) => amount * weight / total);
223
+ let left = amount - shares.reduce((sum, share) => sum + share, 0n);
224
+ while (left > 0n) {
225
+ const best = bestOpen(weights, shares);
226
+ shares[best] = (shares[best] ?? 0n) + 1n;
227
+ left -= 1n;
228
+ }
229
+ for (;;) {
230
+ const best = bestOpen(weights, shares);
231
+ const worst = worstTaken(weights, shares);
232
+ if (best === -1 || worst === -1 || best === worst) break;
233
+ if (!outranks(weights, best, shares[best] ?? 0n, worst, (shares[worst] ?? 0n) - 1n)) break;
234
+ shares[best] = (shares[best] ?? 0n) + 1n;
235
+ shares[worst] = (shares[worst] ?? 0n) - 1n;
236
+ }
237
+ return shares;
238
+ }
239
+ function allocateRefund(items, refundGross, options = {}) {
240
+ const decimals = resolveDecimals(options.decimals);
241
+ if (items.length === 0) throw invalid("A visszatérítés szétosztásához legalább egy tétel kell.");
242
+ const gross = items.map((item, index) => {
243
+ const minor = toMinor(item.grossAmount, decimals, `${index + 1}. tétel bruttó összege`);
244
+ if (minor < 0n) throw invalid(`A(z) ${index + 1}. tétel bruttó összege negatív.`);
245
+ return minor;
246
+ });
247
+ const total = gross.reduce((sum, value) => sum + value, 0n);
248
+ const refund = toMinor(refundGross, decimals, "visszatérített összeg");
249
+ const before = toMinor(options.refundedBefore ?? 0, decimals, "korábban visszatérített összeg");
250
+ if (refund <= 0n) throw invalid("A visszatérített összeg legyen pozitív.");
251
+ if (before < 0n) throw invalid("A korábban visszatérített összeg nem lehet negatív.");
252
+ if (before + refund > total) throw invalid(`A visszatérítések összege (${fromMinor(before + refund, decimals)}) nagyobb, mint az eredeti bizonylat bruttó összege (${fromMinor(total, decimals)}).`);
253
+ const earlier = apportion(gross, before);
254
+ const shares = apportion(gross, before + refund).map((value, index) => value - (earlier[index] ?? 0n));
255
+ return items.flatMap((item, index) => {
256
+ const share = shares[index] ?? 0n;
257
+ if (share === 0n) return [];
258
+ return [{
259
+ index,
260
+ name: item.name,
261
+ vat: item.vat,
262
+ grossAmount: fromMinor(share, decimals),
263
+ ...item.unit === void 0 ? {} : { unit: item.unit },
264
+ ...item.identifier === void 0 ? {} : { identifier: item.identifier }
265
+ }];
266
+ });
267
+ }
268
+ //#endregion
269
+ export { summarizeItems as a, calculateReceiptItem as i, calculateInvoiceItem as n, calculateItemAmounts as r, allocateRefund as t };
@@ -1,4 +1,4 @@
1
- const require_errors = require("./errors-DxeuTslP.cjs");
1
+ const require_errors = require("./errors-EE96_6D_.cjs");
2
2
  const require_rounding = require("./rounding-TxoWy2ww.cjs");
3
3
  const require_vat = require("./vat-g35srbNG.cjs");
4
4
  //#region src/money/items.ts
@@ -174,6 +174,104 @@ function summarizeItems(items) {
174
174
  };
175
175
  }
176
176
  //#endregion
177
+ //#region src/money/refund.ts
178
+ function invalid(message) {
179
+ return new require_errors.SzamlazzError(message, { category: "validation" });
180
+ }
181
+ function toMinor(value, decimals, field) {
182
+ if (!Number.isFinite(value)) throw invalid(`A(z) ${field} nem véges szám: ${value}`);
183
+ if (require_rounding.decimalPlaces(value) > decimals) throw invalid(`A(z) ${field} (${value}) több tizedesjegyet tartalmaz, mint amennyit a bizonylat pénzneme enged (${decimals}).`);
184
+ return BigInt(Math.round(Number((value * 10 ** decimals).toPrecision(15))));
185
+ }
186
+ function fromMinor(value, decimals) {
187
+ return Number(value) / 10 ** decimals;
188
+ }
189
+ function resolveDecimals(value) {
190
+ if (value === void 0) return 0;
191
+ if (!Number.isInteger(value) || value < 0 || value > 6) throw invalid(`A decimals értéke 0 és 6 közötti egész legyen, kapott: ${value}`);
192
+ return value;
193
+ }
194
+ function outranks(weights, first, firstUnit, second, secondUnit) {
195
+ const left = (weights[first] ?? 0n) * (2n * secondUnit + 1n);
196
+ const right = (weights[second] ?? 0n) * (2n * firstUnit + 1n);
197
+ if (left !== right) return left > right;
198
+ return first < second;
199
+ }
200
+ function bestOpen(weights, shares) {
201
+ let best = -1;
202
+ for (let index = 0; index < weights.length; index++) {
203
+ const share = shares[index] ?? 0n;
204
+ if (share >= (weights[index] ?? 0n)) continue;
205
+ if (best === -1 || outranks(weights, index, share, best, shares[best] ?? 0n)) best = index;
206
+ }
207
+ return best;
208
+ }
209
+ function worstTaken(weights, shares) {
210
+ let worst = -1;
211
+ for (let index = 0; index < weights.length; index++) {
212
+ const share = shares[index] ?? 0n;
213
+ if (share === 0n) continue;
214
+ if (worst === -1 || outranks(weights, worst, (shares[worst] ?? 0n) - 1n, index, share - 1n)) worst = index;
215
+ }
216
+ return worst;
217
+ }
218
+ function apportion(weights, amount) {
219
+ const total = weights.reduce((sum, weight) => sum + weight, 0n);
220
+ if (amount === 0n || total === 0n) return weights.map(() => 0n);
221
+ if (amount === total) return [...weights];
222
+ const shares = weights.map((weight) => amount * weight / total);
223
+ let left = amount - shares.reduce((sum, share) => sum + share, 0n);
224
+ while (left > 0n) {
225
+ const best = bestOpen(weights, shares);
226
+ shares[best] = (shares[best] ?? 0n) + 1n;
227
+ left -= 1n;
228
+ }
229
+ for (;;) {
230
+ const best = bestOpen(weights, shares);
231
+ const worst = worstTaken(weights, shares);
232
+ if (best === -1 || worst === -1 || best === worst) break;
233
+ if (!outranks(weights, best, shares[best] ?? 0n, worst, (shares[worst] ?? 0n) - 1n)) break;
234
+ shares[best] = (shares[best] ?? 0n) + 1n;
235
+ shares[worst] = (shares[worst] ?? 0n) - 1n;
236
+ }
237
+ return shares;
238
+ }
239
+ function allocateRefund(items, refundGross, options = {}) {
240
+ const decimals = resolveDecimals(options.decimals);
241
+ if (items.length === 0) throw invalid("A visszatérítés szétosztásához legalább egy tétel kell.");
242
+ const gross = items.map((item, index) => {
243
+ const minor = toMinor(item.grossAmount, decimals, `${index + 1}. tétel bruttó összege`);
244
+ if (minor < 0n) throw invalid(`A(z) ${index + 1}. tétel bruttó összege negatív.`);
245
+ return minor;
246
+ });
247
+ const total = gross.reduce((sum, value) => sum + value, 0n);
248
+ const refund = toMinor(refundGross, decimals, "visszatérített összeg");
249
+ const before = toMinor(options.refundedBefore ?? 0, decimals, "korábban visszatérített összeg");
250
+ if (refund <= 0n) throw invalid("A visszatérített összeg legyen pozitív.");
251
+ if (before < 0n) throw invalid("A korábban visszatérített összeg nem lehet negatív.");
252
+ if (before + refund > total) throw invalid(`A visszatérítések összege (${fromMinor(before + refund, decimals)}) nagyobb, mint az eredeti bizonylat bruttó összege (${fromMinor(total, decimals)}).`);
253
+ const earlier = apportion(gross, before);
254
+ const shares = apportion(gross, before + refund).map((value, index) => value - (earlier[index] ?? 0n));
255
+ return items.flatMap((item, index) => {
256
+ const share = shares[index] ?? 0n;
257
+ if (share === 0n) return [];
258
+ return [{
259
+ index,
260
+ name: item.name,
261
+ vat: item.vat,
262
+ grossAmount: fromMinor(share, decimals),
263
+ ...item.unit === void 0 ? {} : { unit: item.unit },
264
+ ...item.identifier === void 0 ? {} : { identifier: item.identifier }
265
+ }];
266
+ });
267
+ }
268
+ //#endregion
269
+ Object.defineProperty(exports, "allocateRefund", {
270
+ enumerable: true,
271
+ get: function() {
272
+ return allocateRefund;
273
+ }
274
+ });
177
275
  Object.defineProperty(exports, "calculateInvoiceItem", {
178
276
  enumerable: true,
179
277
  get: function() {
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_serialize = require("../serialize-BXOww1Uq.cjs");
2
+ const require_serialize = require("../serialize-CquIsxA-.cjs");
3
3
  const require_dates = require("../dates-CPgBodkP.cjs");
4
4
  const require_rounding = require("../rounding-TxoWy2ww.cjs");
5
5
  const require_crypto = require("../crypto-Dpn4FHQ6.cjs");
6
- const require_nav = require("../nav-BEwcX7-N.cjs");
6
+ const require_nav = require("../nav-BNbc8U0R.cjs");
7
7
  //#region src/nav/errors.ts
8
8
  const NAV_RECEIPT_ERROR_CODES = {
9
9
  EPGP0002: {
@@ -1,5 +1,5 @@
1
- import { o as RequestOptions } from "../context-DXNbTPwz.cjs";
2
1
  import { t as DateInput } from "../dates-9zvESP0i.cjs";
2
+ import { s as RequestOptions } from "../context-CFNKzStE.cjs";
3
3
  //#region src/core/xml/parse.d.ts
4
4
  interface XmlElement {
5
5
  readonly name: string;
@@ -1,5 +1,5 @@
1
- import { o as RequestOptions } from "../context-BxQlIlug.js";
2
1
  import { t as DateInput } from "../dates-9zvESP0i.js";
2
+ import { s as RequestOptions } from "../context-kb33TgzE.js";
3
3
  //#region src/core/xml/parse.d.ts
4
4
  interface XmlElement {
5
5
  readonly name: string;
package/dist/nav/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { a as optionalEl, d as findChildren, f as parseXml, l as childText, n as buildXmlDocument, o as XmlParseError, r as el, t as XSI_NAMESPACE, u as findChild } from "../serialize-DSE_o9RK.js";
1
+ import { a as optionalEl, d as findChildren, f as parseXml, l as childText, n as buildXmlDocument, o as XmlParseError, r as el, t as XSI_NAMESPACE, u as findChild } from "../serialize-B2eFh3D-.js";
2
2
  import { a as todayInBudapest, n as toAgentDate } from "../dates-CXyj7Azy.js";
3
3
  import { n as decimalPlaces, r as roundMoney } from "../rounding-BLyHjjI5.js";
4
4
  import { n as digestHex, t as bytesToHex } from "../crypto-usDg8L2K.js";
5
- import { o as NAV_VAT_CATEGORIES, t as compareReceiptNumbers } from "../nav-CK1WgYo7.js";
5
+ import { o as NAV_VAT_CATEGORIES, t as compareReceiptNumbers } from "../nav-BcCerwWS.js";
6
6
  //#region src/nav/errors.ts
7
7
  const NAV_RECEIPT_ERROR_CODES = {
8
8
  EPGP0002: {
@@ -1,4 +1,4 @@
1
- const require_errors = require("./errors-DxeuTslP.cjs");
1
+ const require_errors = require("./errors-EE96_6D_.cjs");
2
2
  const require_rounding = require("./rounding-TxoWy2ww.cjs");
3
3
  const require_vat = require("./vat-g35srbNG.cjs");
4
4
  //#region src/reports/vat-category.ts
@@ -1,4 +1,4 @@
1
- import { n as SzamlazzError } from "./errors-DLrb0g64.js";
1
+ import { r as SzamlazzError } from "./errors-DtN4g5Z9.js";
2
2
  import { r as roundMoney } from "./rounding-BLyHjjI5.js";
3
3
  import { i as isHuf } from "./vat-v_dcWCto.js";
4
4
  //#region src/reports/vat-category.ts
@@ -0,0 +1,124 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/node/index.ts
3
+ const encoder = new TextEncoder();
4
+ var NodeBodyError = class extends Error {
5
+ name = "NodeBodyError";
6
+ };
7
+ function firstHeader(value) {
8
+ if (value === void 0) return void 0;
9
+ return typeof value === "string" ? value : value[0];
10
+ }
11
+ function requestUrl(request, trustProxy) {
12
+ const forwardedProto = trustProxy ? firstHeader(request.headers["x-forwarded-proto"])?.split(",")[0]?.trim() : void 0;
13
+ const forwardedHost = trustProxy ? firstHeader(request.headers["x-forwarded-host"])?.split(",")[0]?.trim() : void 0;
14
+ const protocol = forwardedProto || (request.socket?.encrypted ? "https" : "http");
15
+ const host = forwardedHost || firstHeader(request.headers.host) || firstHeader(request.headers[":authority"]) || "localhost";
16
+ const path = request.originalUrl ?? request.url ?? "/";
17
+ return `${protocol}://${host}${path.startsWith("/") ? path : `/${path}`}`;
18
+ }
19
+ function requestHeaders(request) {
20
+ const headers = new Headers();
21
+ for (const [name, value] of Object.entries(request.headers)) {
22
+ if (value === void 0 || name.startsWith(":")) continue;
23
+ if (typeof value === "string") headers.append(name, value);
24
+ else for (const item of value) headers.append(name, item);
25
+ }
26
+ return headers;
27
+ }
28
+ function streamOf(source) {
29
+ const iterator = source[Symbol.asyncIterator]();
30
+ return new ReadableStream({
31
+ async pull(controller) {
32
+ const { value, done } = await iterator.next();
33
+ if (done) {
34
+ controller.close();
35
+ return;
36
+ }
37
+ controller.enqueue(typeof value === "string" ? encoder.encode(value) : value);
38
+ },
39
+ async cancel(reason) {
40
+ await iterator.return?.(reason);
41
+ }
42
+ });
43
+ }
44
+ function bytesOf(value) {
45
+ if (typeof value === "string") return value;
46
+ if (value instanceof Uint8Array) return value;
47
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
48
+ }
49
+ function isUnparsedPlaceholder(request) {
50
+ const { body } = request;
51
+ if (request.readableEnded || typeof body !== "object" || body === null) return false;
52
+ const prototype = Object.getPrototypeOf(body);
53
+ return (prototype === Object.prototype || prototype === null) && Object.keys(body).length === 0;
54
+ }
55
+ function requestBody(request) {
56
+ const method = (request.method ?? "GET").toUpperCase();
57
+ if (method === "GET" || method === "HEAD") return void 0;
58
+ const raw = bytesOf(request.rawBody);
59
+ if (raw !== void 0) return raw;
60
+ if (request.body !== void 0 && request.body !== null && !isUnparsedPlaceholder(request)) {
61
+ const body = bytesOf(request.body);
62
+ if (body !== void 0) return body;
63
+ throw new NodeBodyError("A kérés törzsét egy middleware (például az express.json()) már feldolgozta, így az aláírás nem ellenőrizhető. A webhook útvonalat az express.json() elé tedd, vagy használd rajta az express.raw({ type: \"*/*\" }) middleware-t. NestJS-ben kapcsold be a rawBody: true beállítást.");
64
+ }
65
+ if (request.readableEnded) throw new NodeBodyError("A kérés törzsét egy middleware már elolvasta, és nem adta tovább. A webhook útvonalra ne tegyél törzsolvasó middleware-t, vagy használd az express.raw({ type: \"*/*\" }) middleware-t.");
66
+ if (typeof request[Symbol.asyncIterator] !== "function") return void 0;
67
+ return streamOf(request);
68
+ }
69
+ function toWebRequest(request, options = {}) {
70
+ const node = request;
71
+ const body = requestBody(node);
72
+ const init = {
73
+ method: node.method ?? "GET",
74
+ headers: requestHeaders(node)
75
+ };
76
+ if (body !== void 0) {
77
+ init.body = body;
78
+ if (body instanceof ReadableStream) init.duplex = "half";
79
+ }
80
+ return new Request(requestUrl(node, options.trustProxy === true), init);
81
+ }
82
+ async function writeWebResponse(source, target) {
83
+ const response = target;
84
+ response.statusCode = source.status;
85
+ const setCookies = source.headers.getSetCookie();
86
+ source.headers.forEach((value, name) => {
87
+ if (name.toLowerCase() === "set-cookie") return;
88
+ response.setHeader(name, value);
89
+ });
90
+ if (setCookies.length > 0) response.setHeader("set-cookie", setCookies);
91
+ const body = new Uint8Array(await source.arrayBuffer());
92
+ response.end(body.byteLength > 0 ? body : void 0);
93
+ }
94
+ function reportError(options, error) {
95
+ try {
96
+ if (options.onError) options.onError(error);
97
+ else console.error("[kassza] A Node kérés kezelése nem sikerült.", error);
98
+ } catch {
99
+ return;
100
+ }
101
+ }
102
+ function toNodeHandler(handler, options = {}) {
103
+ return async (request, response, next) => {
104
+ try {
105
+ await writeWebResponse(await handler(toWebRequest(request, options)), response);
106
+ } catch (error) {
107
+ if (next) {
108
+ next(error);
109
+ return;
110
+ }
111
+ reportError(options, error);
112
+ const target = response;
113
+ if (target.headersSent) return;
114
+ target.statusCode = 500;
115
+ target.setHeader("content-type", "text/plain; charset=utf-8");
116
+ target.end(encoder.encode("A kérés feldolgozása nem sikerült."));
117
+ }
118
+ };
119
+ }
120
+ //#endregion
121
+ exports.NodeBodyError = NodeBodyError;
122
+ exports.toNodeHandler = toNodeHandler;
123
+ exports.toWebRequest = toWebRequest;
124
+ exports.writeWebResponse = writeWebResponse;
@@ -0,0 +1,35 @@
1
+ import { IncomingMessage, ServerResponse } from "node:http";
2
+ //#region src/node/index.d.ts
3
+ export type WebRequestHandler = (request: Request) => Response | Promise<Response>;
4
+ export interface NodeRequestLike {
5
+ [Symbol.asyncIterator]?(): AsyncIterator<Uint8Array | string>;
6
+ readonly method?: string | undefined;
7
+ readonly url?: string | undefined;
8
+ readonly headers: IncomingMessage["headers"];
9
+ readonly readableEnded?: boolean | undefined;
10
+ readonly socket?: {
11
+ readonly encrypted?: boolean | undefined;
12
+ } | undefined;
13
+ readonly originalUrl?: string | undefined;
14
+ readonly body?: unknown;
15
+ readonly rawBody?: unknown;
16
+ }
17
+ export interface NodeResponseLike {
18
+ statusCode: number;
19
+ setHeader(name: string, value: string | readonly string[]): unknown;
20
+ end(chunk?: Uint8Array): unknown;
21
+ readonly headersSent?: boolean | undefined;
22
+ }
23
+ export type NodeNext = (error?: unknown) => void;
24
+ export interface ToNodeHandlerOptions {
25
+ readonly trustProxy?: boolean | undefined;
26
+ readonly onError?: ((error: unknown) => void) | undefined;
27
+ }
28
+ export type NodeHandler = (request: IncomingMessage | NodeRequestLike, response: ServerResponse | NodeResponseLike, next?: NodeNext) => Promise<void>;
29
+ export declare class NodeBodyError extends Error {
30
+ override readonly name: string;
31
+ }
32
+ export declare function toWebRequest(request: IncomingMessage | NodeRequestLike, options?: ToNodeHandlerOptions): Request;
33
+ export declare function writeWebResponse(source: Response, target: ServerResponse | NodeResponseLike): Promise<void>;
34
+ export declare function toNodeHandler(handler: WebRequestHandler, options?: ToNodeHandlerOptions): NodeHandler;
35
+ //#endregion
@@ -0,0 +1,35 @@
1
+ import { IncomingMessage, ServerResponse } from "node:http";
2
+ //#region src/node/index.d.ts
3
+ export type WebRequestHandler = (request: Request) => Response | Promise<Response>;
4
+ export interface NodeRequestLike {
5
+ [Symbol.asyncIterator]?(): AsyncIterator<Uint8Array | string>;
6
+ readonly method?: string | undefined;
7
+ readonly url?: string | undefined;
8
+ readonly headers: IncomingMessage["headers"];
9
+ readonly readableEnded?: boolean | undefined;
10
+ readonly socket?: {
11
+ readonly encrypted?: boolean | undefined;
12
+ } | undefined;
13
+ readonly originalUrl?: string | undefined;
14
+ readonly body?: unknown;
15
+ readonly rawBody?: unknown;
16
+ }
17
+ export interface NodeResponseLike {
18
+ statusCode: number;
19
+ setHeader(name: string, value: string | readonly string[]): unknown;
20
+ end(chunk?: Uint8Array): unknown;
21
+ readonly headersSent?: boolean | undefined;
22
+ }
23
+ export type NodeNext = (error?: unknown) => void;
24
+ export interface ToNodeHandlerOptions {
25
+ readonly trustProxy?: boolean | undefined;
26
+ readonly onError?: ((error: unknown) => void) | undefined;
27
+ }
28
+ export type NodeHandler = (request: IncomingMessage | NodeRequestLike, response: ServerResponse | NodeResponseLike, next?: NodeNext) => Promise<void>;
29
+ export declare class NodeBodyError extends Error {
30
+ override readonly name: string;
31
+ }
32
+ export declare function toWebRequest(request: IncomingMessage | NodeRequestLike, options?: ToNodeHandlerOptions): Request;
33
+ export declare function writeWebResponse(source: Response, target: ServerResponse | NodeResponseLike): Promise<void>;
34
+ export declare function toNodeHandler(handler: WebRequestHandler, options?: ToNodeHandlerOptions): NodeHandler;
35
+ //#endregion
@@ -0,0 +1,120 @@
1
+ //#region src/node/index.ts
2
+ const encoder = new TextEncoder();
3
+ var NodeBodyError = class extends Error {
4
+ name = "NodeBodyError";
5
+ };
6
+ function firstHeader(value) {
7
+ if (value === void 0) return void 0;
8
+ return typeof value === "string" ? value : value[0];
9
+ }
10
+ function requestUrl(request, trustProxy) {
11
+ const forwardedProto = trustProxy ? firstHeader(request.headers["x-forwarded-proto"])?.split(",")[0]?.trim() : void 0;
12
+ const forwardedHost = trustProxy ? firstHeader(request.headers["x-forwarded-host"])?.split(",")[0]?.trim() : void 0;
13
+ const protocol = forwardedProto || (request.socket?.encrypted ? "https" : "http");
14
+ const host = forwardedHost || firstHeader(request.headers.host) || firstHeader(request.headers[":authority"]) || "localhost";
15
+ const path = request.originalUrl ?? request.url ?? "/";
16
+ return `${protocol}://${host}${path.startsWith("/") ? path : `/${path}`}`;
17
+ }
18
+ function requestHeaders(request) {
19
+ const headers = new Headers();
20
+ for (const [name, value] of Object.entries(request.headers)) {
21
+ if (value === void 0 || name.startsWith(":")) continue;
22
+ if (typeof value === "string") headers.append(name, value);
23
+ else for (const item of value) headers.append(name, item);
24
+ }
25
+ return headers;
26
+ }
27
+ function streamOf(source) {
28
+ const iterator = source[Symbol.asyncIterator]();
29
+ return new ReadableStream({
30
+ async pull(controller) {
31
+ const { value, done } = await iterator.next();
32
+ if (done) {
33
+ controller.close();
34
+ return;
35
+ }
36
+ controller.enqueue(typeof value === "string" ? encoder.encode(value) : value);
37
+ },
38
+ async cancel(reason) {
39
+ await iterator.return?.(reason);
40
+ }
41
+ });
42
+ }
43
+ function bytesOf(value) {
44
+ if (typeof value === "string") return value;
45
+ if (value instanceof Uint8Array) return value;
46
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
47
+ }
48
+ function isUnparsedPlaceholder(request) {
49
+ const { body } = request;
50
+ if (request.readableEnded || typeof body !== "object" || body === null) return false;
51
+ const prototype = Object.getPrototypeOf(body);
52
+ return (prototype === Object.prototype || prototype === null) && Object.keys(body).length === 0;
53
+ }
54
+ function requestBody(request) {
55
+ const method = (request.method ?? "GET").toUpperCase();
56
+ if (method === "GET" || method === "HEAD") return void 0;
57
+ const raw = bytesOf(request.rawBody);
58
+ if (raw !== void 0) return raw;
59
+ if (request.body !== void 0 && request.body !== null && !isUnparsedPlaceholder(request)) {
60
+ const body = bytesOf(request.body);
61
+ if (body !== void 0) return body;
62
+ throw new NodeBodyError("A kérés törzsét egy middleware (például az express.json()) már feldolgozta, így az aláírás nem ellenőrizhető. A webhook útvonalat az express.json() elé tedd, vagy használd rajta az express.raw({ type: \"*/*\" }) middleware-t. NestJS-ben kapcsold be a rawBody: true beállítást.");
63
+ }
64
+ if (request.readableEnded) throw new NodeBodyError("A kérés törzsét egy middleware már elolvasta, és nem adta tovább. A webhook útvonalra ne tegyél törzsolvasó middleware-t, vagy használd az express.raw({ type: \"*/*\" }) middleware-t.");
65
+ if (typeof request[Symbol.asyncIterator] !== "function") return void 0;
66
+ return streamOf(request);
67
+ }
68
+ function toWebRequest(request, options = {}) {
69
+ const node = request;
70
+ const body = requestBody(node);
71
+ const init = {
72
+ method: node.method ?? "GET",
73
+ headers: requestHeaders(node)
74
+ };
75
+ if (body !== void 0) {
76
+ init.body = body;
77
+ if (body instanceof ReadableStream) init.duplex = "half";
78
+ }
79
+ return new Request(requestUrl(node, options.trustProxy === true), init);
80
+ }
81
+ async function writeWebResponse(source, target) {
82
+ const response = target;
83
+ response.statusCode = source.status;
84
+ const setCookies = source.headers.getSetCookie();
85
+ source.headers.forEach((value, name) => {
86
+ if (name.toLowerCase() === "set-cookie") return;
87
+ response.setHeader(name, value);
88
+ });
89
+ if (setCookies.length > 0) response.setHeader("set-cookie", setCookies);
90
+ const body = new Uint8Array(await source.arrayBuffer());
91
+ response.end(body.byteLength > 0 ? body : void 0);
92
+ }
93
+ function reportError(options, error) {
94
+ try {
95
+ if (options.onError) options.onError(error);
96
+ else console.error("[kassza] A Node kérés kezelése nem sikerült.", error);
97
+ } catch {
98
+ return;
99
+ }
100
+ }
101
+ function toNodeHandler(handler, options = {}) {
102
+ return async (request, response, next) => {
103
+ try {
104
+ await writeWebResponse(await handler(toWebRequest(request, options)), response);
105
+ } catch (error) {
106
+ if (next) {
107
+ next(error);
108
+ return;
109
+ }
110
+ reportError(options, error);
111
+ const target = response;
112
+ if (target.headersSent) return;
113
+ target.statusCode = 500;
114
+ target.setHeader("content-type", "text/plain; charset=utf-8");
115
+ target.end(encoder.encode("A kérés feldolgozása nem sikerült."));
116
+ }
117
+ };
118
+ }
119
+ //#endregion
120
+ export { NodeBodyError, toNodeHandler, toWebRequest, writeWebResponse };