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
@@ -0,0 +1,303 @@
1
+ import { i as hmacHex } from "../crypto-usDg8L2K.js";
2
+ //#region src/observe/metrics.ts
3
+ const DEFAULT_DURATION_BUCKETS_MS = [
4
+ 50,
5
+ 100,
6
+ 250,
7
+ 500,
8
+ 1e3,
9
+ 2500,
10
+ 5e3,
11
+ 1e4,
12
+ 3e4,
13
+ 6e4
14
+ ];
15
+ const METRIC_HELP = {
16
+ kassza_requests_total: "Számla Agent próbálkozások száma kimenet szerint",
17
+ kassza_request_duration_ms: "Számla Agent próbálkozások időtartama ezredmásodpercben",
18
+ kassza_retries_total: "Automatikus újrapróbálások száma",
19
+ kassza_maintenance_total: "Karbantartás (1-es hiba) miatt elbukott kérések",
20
+ kassza_unexpected_response_total: "Ismeretlen formátumú Számlázz.hu válaszok",
21
+ kassza_store_errors_total: "Tároló (session, napló, zár, gyorsítótár) hibái",
22
+ kassza_warnings_total: "Figyelmeztetések fajta szerint",
23
+ kassza_documents_total: "Kiállított bizonylatok fajta és művelet szerint"
24
+ };
25
+ const NAME_PATTERN = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
26
+ const LABEL_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
27
+ function escapeLabel(value) {
28
+ return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, "\\\"");
29
+ }
30
+ function labelKey(labels) {
31
+ const entries = Object.entries(labels ?? {}).sort(([a], [b]) => a.localeCompare(b));
32
+ for (const [name] of entries) if (!LABEL_PATTERN.test(name)) throw new TypeError(`Érvénytelen metrika-címke: ${name}`);
33
+ return entries.map(([name, value]) => `${name}="${escapeLabel(value)}"`).join(",");
34
+ }
35
+ function assertName(name) {
36
+ if (!NAME_PATTERN.test(name)) throw new TypeError(`Érvénytelen metrikanév: ${name}`);
37
+ }
38
+ function series(name, key, extra) {
39
+ const labels = [key, extra].filter(Boolean).join(",");
40
+ return labels ? `${name}{${labels}}` : name;
41
+ }
42
+ function formatNumber(value) {
43
+ if (value === Number.POSITIVE_INFINITY) return "+Inf";
44
+ return String(value);
45
+ }
46
+ function createMetricsRegistry(buckets = DEFAULT_DURATION_BUCKETS_MS) {
47
+ const sorted = [...buckets].sort((a, b) => a - b);
48
+ if (sorted.some((bucket) => !Number.isFinite(bucket))) throw new TypeError("A hisztogram határai véges számok legyenek.");
49
+ const counters = /* @__PURE__ */ new Map();
50
+ const histograms = /* @__PURE__ */ new Map();
51
+ return {
52
+ counter(name, labels, value = 1) {
53
+ assertName(name);
54
+ if (!Number.isFinite(value) || value < 0) throw new TypeError(`A számláló csak nemnegatív értékkel nőhet, kapott: ${value}`);
55
+ const byLabels = counters.get(name) ?? /* @__PURE__ */ new Map();
56
+ const key = labelKey(labels);
57
+ byLabels.set(key, (byLabels.get(key) ?? 0) + value);
58
+ counters.set(name, byLabels);
59
+ },
60
+ histogram(name, value, labels) {
61
+ assertName(name);
62
+ if (!Number.isFinite(value)) throw new TypeError(`A hisztogram értéke véges szám legyen.`);
63
+ const byLabels = histograms.get(name) ?? /* @__PURE__ */ new Map();
64
+ const key = labelKey(labels);
65
+ const histogram = byLabels.get(key) ?? {
66
+ buckets: sorted.map(() => 0),
67
+ sum: 0,
68
+ count: 0
69
+ };
70
+ sorted.forEach((bound, index) => {
71
+ if (value <= bound) histogram.buckets[index] = (histogram.buckets[index] ?? 0) + 1;
72
+ });
73
+ histogram.sum += value;
74
+ histogram.count += 1;
75
+ byLabels.set(key, histogram);
76
+ histograms.set(name, byLabels);
77
+ },
78
+ renderPrometheus() {
79
+ const lines = [];
80
+ for (const name of [...counters.keys()].sort()) {
81
+ const help = METRIC_HELP[name];
82
+ if (help) lines.push(`# HELP ${name} ${help}`);
83
+ lines.push(`# TYPE ${name} counter`);
84
+ for (const [key, value] of [...counters.get(name) ?? []].sort()) lines.push(`${series(name, key)} ${formatNumber(value)}`);
85
+ }
86
+ for (const name of [...histograms.keys()].sort()) {
87
+ const help = METRIC_HELP[name];
88
+ if (help) lines.push(`# HELP ${name} ${help}`);
89
+ lines.push(`# TYPE ${name} histogram`);
90
+ for (const [key, histogram] of [...histograms.get(name) ?? []].sort()) {
91
+ sorted.forEach((bound, index) => {
92
+ lines.push(`${series(`${name}_bucket`, key, `le="${formatNumber(bound)}"`)} ${histogram.buckets[index] ?? 0}`);
93
+ });
94
+ lines.push(`${series(`${name}_bucket`, key, "le=\"+Inf\"")} ${histogram.count}`);
95
+ lines.push(`${series(`${name}_sum`, key)} ${formatNumber(histogram.sum)}`);
96
+ lines.push(`${series(`${name}_count`, key)} ${histogram.count}`);
97
+ }
98
+ }
99
+ return lines.length > 0 ? `${lines.join("\n")}\n` : "";
100
+ },
101
+ reset() {
102
+ counters.clear();
103
+ histograms.clear();
104
+ }
105
+ };
106
+ }
107
+ //#endregion
108
+ //#region src/observe/observe.ts
109
+ const SPAN_STATUS_OK = 1;
110
+ const SPAN_STATUS_ERROR = 2;
111
+ const MAX_OPEN_SPANS = 1e3;
112
+ const STORE_WARNINGS = /* @__PURE__ */ new Set([
113
+ "session",
114
+ "ledger",
115
+ "lock",
116
+ "dedupe",
117
+ "cache"
118
+ ]);
119
+ function randomSalt() {
120
+ return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
121
+ }
122
+ function safely(run) {
123
+ try {
124
+ run();
125
+ } catch {
126
+ return;
127
+ }
128
+ }
129
+ function orderNumberOf(event) {
130
+ if (event.kind === "receipt") return event.document.orderNumber;
131
+ if (event.action === "created") return event.input.orderNumber?.trim() || void 0;
132
+ }
133
+ function spanKey(event) {
134
+ return `${event.requestId}:${event.attempt}`;
135
+ }
136
+ function observe(options = {}) {
137
+ const { logger, tracer, metrics } = options;
138
+ const redact = options.redact !== false;
139
+ const salt = options.orderRefSalt ?? randomSalt();
140
+ const spans = /* @__PURE__ */ new Map();
141
+ async function orderRef(orderNumber) {
142
+ if (orderNumber === void 0) return void 0;
143
+ if (!redact) return orderNumber;
144
+ return `hmac:${(await hmacHex("SHA-256", salt, orderNumber)).slice(0, 16)}`;
145
+ }
146
+ const onRequest = (event) => {
147
+ if (tracer) safely(() => {
148
+ if (spans.size >= 1e3) {
149
+ const oldest = spans.keys().next().value;
150
+ if (oldest !== void 0) {
151
+ spans.get(oldest)?.end();
152
+ spans.delete(oldest);
153
+ }
154
+ }
155
+ spans.set(spanKey(event), tracer.startSpan(`kassza ${event.action}`, { attributes: {
156
+ "kassza.action": event.action,
157
+ "kassza.attempt": event.attempt,
158
+ "kassza.request_id": event.requestId
159
+ } }));
160
+ });
161
+ if (options.logRequests === true) safely(() => logger?.debug?.({
162
+ event: "kassza.request.start",
163
+ ...event
164
+ }, `kassza: ${event.action} kérés indul`));
165
+ };
166
+ const onResponse = (event) => {
167
+ const span = spans.get(spanKey(event));
168
+ if (!span) return;
169
+ safely(() => {
170
+ span.setAttribute("http.status_code", event.status);
171
+ span.setAttribute("kassza.response_bytes", event.responseBytes);
172
+ span.setAttribute("kassza.session_reused", event.sessionReused);
173
+ });
174
+ };
175
+ const onComplete = (event) => {
176
+ const key = spanKey(event);
177
+ const span = spans.get(key);
178
+ spans.delete(key);
179
+ const category = event.error?.category;
180
+ const code = event.error?.code;
181
+ if (span) safely(() => {
182
+ if (category) span.setAttribute("kassza.error.category", category);
183
+ if (code !== void 0) span.setAttribute("kassza.error.code", code);
184
+ if (event.error) {
185
+ span.recordException(event.error);
186
+ span.setStatus({
187
+ code: 2,
188
+ message: event.error.message
189
+ });
190
+ } else if (event.outcome === "error") span.setStatus({ code: 2 });
191
+ else span.setStatus({ code: 1 });
192
+ span.end();
193
+ });
194
+ if (metrics) safely(() => {
195
+ metrics.counter("kassza_requests_total", {
196
+ action: event.action,
197
+ outcome: event.outcome === "success" ? "success" : category ?? "error"
198
+ });
199
+ metrics.histogram("kassza_request_duration_ms", event.durationMs, { action: event.action });
200
+ if (event.willRetry) metrics.counter("kassza_retries_total", { action: event.action });
201
+ if (category === "maintenance") metrics.counter("kassza_maintenance_total");
202
+ if (category === "unexpected_response") metrics.counter("kassza_unexpected_response_total", { action: event.action });
203
+ });
204
+ const data = {
205
+ event: "kassza.request",
206
+ action: event.action,
207
+ attempt: event.attempt,
208
+ requestId: event.requestId,
209
+ outcome: event.outcome,
210
+ durationMs: event.durationMs,
211
+ willRetry: event.willRetry,
212
+ ...category ? { errorCategory: category } : {},
213
+ ...code === void 0 ? {} : { errorCode: code }
214
+ };
215
+ safely(() => {
216
+ if (event.outcome === "success") logger?.info?.(data, `kassza: ${event.action} sikeres (${event.durationMs} ms)`);
217
+ else logger?.warn?.(data, `kassza: ${event.action} sikertelen${category ? ` (${category})` : ""}${event.willRetry ? ", újrapróbálás" : ""}`);
218
+ });
219
+ };
220
+ const onWarning = (warning) => {
221
+ safely(() => {
222
+ metrics?.counter("kassza_warnings_total", { kind: warning.kind });
223
+ if (STORE_WARNINGS.has(warning.kind)) metrics?.counter("kassza_store_errors_total", { store: warning.kind });
224
+ });
225
+ safely(() => logger?.warn?.({
226
+ event: "kassza.warning",
227
+ kind: warning.kind,
228
+ ...warning.action ? { action: warning.action } : {},
229
+ ...warning.operation ? { operation: warning.operation } : {},
230
+ error: warning.error instanceof Error ? warning.error.message : String(warning.error)
231
+ }, warning.message));
232
+ };
233
+ const onDocument = async (event) => {
234
+ safely(() => metrics?.counter("kassza_documents_total", {
235
+ kind: event.kind,
236
+ action: event.action
237
+ }));
238
+ if (!logger?.info) return;
239
+ try {
240
+ const ref = await orderRef(orderNumberOf(event));
241
+ logger.info({
242
+ event: "kassza.document",
243
+ kind: event.kind,
244
+ action: event.action,
245
+ number: event.number,
246
+ ...ref === void 0 ? {} : { orderRef: ref }
247
+ }, `kassza: ${event.kind} ${event.action} ${event.number}`);
248
+ } catch {
249
+ return;
250
+ }
251
+ };
252
+ return {
253
+ onRequest,
254
+ onResponse,
255
+ onComplete,
256
+ onWarning,
257
+ onDocument
258
+ };
259
+ }
260
+ const SYNC_HOOKS = [
261
+ "onRequest",
262
+ "onResponse",
263
+ "onError",
264
+ "onComplete",
265
+ "onWarning"
266
+ ];
267
+ function combineSync(hooks, name) {
268
+ const handlers = hooks.map((hook) => hook[name]).filter((handler) => handler !== void 0);
269
+ if (handlers.length === 0) return void 0;
270
+ return (event) => {
271
+ let failure;
272
+ for (const handler of handlers) try {
273
+ const result = handler(event);
274
+ if (result instanceof Promise) result.catch(() => void 0);
275
+ } catch (error) {
276
+ failure ??= { error };
277
+ }
278
+ if (failure) throw failure.error;
279
+ };
280
+ }
281
+ function combineHooks(...hooks) {
282
+ const present = hooks.filter((hook) => hook !== void 0);
283
+ const combined = {};
284
+ for (const name of SYNC_HOOKS) {
285
+ const handler = combineSync(present, name);
286
+ if (handler) combined[name] = handler;
287
+ }
288
+ const documentHooks = present.map((hook) => hook.onDocument).filter((hook) => hook !== void 0);
289
+ if (documentHooks.length > 0) combined.onDocument = async (event) => {
290
+ let failure;
291
+ for (const hook of documentHooks) try {
292
+ await hook(event);
293
+ } catch (error) {
294
+ failure ??= { error };
295
+ }
296
+ if (failure) throw failure.error;
297
+ };
298
+ const mode = present.map((hook) => hook.onDocumentError).findLast((value) => value !== void 0);
299
+ if (mode !== void 0) combined.onDocumentError = mode;
300
+ return combined;
301
+ }
302
+ //#endregion
303
+ export { DEFAULT_DURATION_BUCKETS_MS, MAX_OPEN_SPANS, METRIC_HELP, SPAN_STATUS_ERROR, SPAN_STATUS_OK, combineHooks, createMetricsRegistry, observe };
@@ -0,0 +1,103 @@
1
+ const require_errors = require("./errors-EE96_6D_.cjs");
2
+ //#region src/core/once.ts
3
+ const DEFAULT_RECOVERY_DELAY_MS = 1e3;
4
+ const UNCERTAIN_CATEGORIES = /* @__PURE__ */ new Set([
5
+ "network",
6
+ "timeout",
7
+ "partial_success",
8
+ "duplicate",
9
+ "unexpected_response",
10
+ "unknown"
11
+ ]);
12
+ function isUncertainOutcome(error) {
13
+ return error instanceof require_errors.SzamlazzError && UNCERTAIN_CATEGORIES.has(error.category);
14
+ }
15
+ function resolveRecoveryDelay(value) {
16
+ if (value === void 0) return DEFAULT_RECOVERY_DELAY_MS;
17
+ if (!Number.isFinite(value) || value < 0) throw new require_errors.SzamlazzError(`A recoveryDelayMs értéke nemnegatív szám legyen, kapott: ${value}`, { category: "configuration" });
18
+ return value;
19
+ }
20
+ function wait(ms, signal) {
21
+ if (ms <= 0) return Promise.resolve();
22
+ return new Promise((resolve, reject) => {
23
+ if (signal?.aborted) {
24
+ reject(signal.reason);
25
+ return;
26
+ }
27
+ const timer = setTimeout(() => {
28
+ signal?.removeEventListener("abort", onAbort);
29
+ resolve();
30
+ }, ms);
31
+ const onAbort = () => {
32
+ clearTimeout(timer);
33
+ reject(signal?.reason);
34
+ };
35
+ signal?.addEventListener("abort", onAbort, { once: true });
36
+ });
37
+ }
38
+ async function recoverAfterFailure(lookup, delayMs, signal, state = {}) {
39
+ for (let attempt = 1; attempt <= 2; attempt++) {
40
+ await wait(delayMs * attempt, signal);
41
+ let found;
42
+ try {
43
+ found = await lookup();
44
+ } catch (error) {
45
+ if (!(error instanceof require_errors.SzamlazzError)) throw error;
46
+ state.lookupError = error;
47
+ if (!error.retryable) return null;
48
+ found = void 0;
49
+ }
50
+ if (found) return found;
51
+ }
52
+ return null;
53
+ }
54
+ function unknownOutcomeError(error, reference, options = {}) {
55
+ const lookupError = options.lookupError;
56
+ const lookupNote = lookupError ? ` A visszakeresés is hibát adott (${lookupError.category}: ${lookupError.message}), ezt előbb hárítsd el.` : "";
57
+ return new require_errors.SzamlazzError(error.message, {
58
+ category: error.category,
59
+ code: error.code,
60
+ action: error.action,
61
+ httpStatus: error.httpStatus,
62
+ rawResponse: error.rawResponse,
63
+ details: {
64
+ ...error.details,
65
+ outcome: "unknown",
66
+ reference,
67
+ ...lookupError ? { lookupError: `${lookupError.category}: ${lookupError.message}` } : {}
68
+ },
69
+ hint: `Nem tudni biztosan, hogy a(z) ${reference} ${options.subject ?? "bizonylata"} elkészült-e, és a visszakeresés sem találta meg.${lookupNote} Ne állítsd ki kézzel újra: később hívd meg ugyanígy a ${options.method ?? "createOnce"}-t, az előbb visszakeres.`,
70
+ cause: error
71
+ });
72
+ }
73
+ //#endregion
74
+ Object.defineProperty(exports, "DEFAULT_RECOVERY_DELAY_MS", {
75
+ enumerable: true,
76
+ get: function() {
77
+ return DEFAULT_RECOVERY_DELAY_MS;
78
+ }
79
+ });
80
+ Object.defineProperty(exports, "isUncertainOutcome", {
81
+ enumerable: true,
82
+ get: function() {
83
+ return isUncertainOutcome;
84
+ }
85
+ });
86
+ Object.defineProperty(exports, "recoverAfterFailure", {
87
+ enumerable: true,
88
+ get: function() {
89
+ return recoverAfterFailure;
90
+ }
91
+ });
92
+ Object.defineProperty(exports, "resolveRecoveryDelay", {
93
+ enumerable: true,
94
+ get: function() {
95
+ return resolveRecoveryDelay;
96
+ }
97
+ });
98
+ Object.defineProperty(exports, "unknownOutcomeError", {
99
+ enumerable: true,
100
+ get: function() {
101
+ return unknownOutcomeError;
102
+ }
103
+ });
@@ -0,0 +1,74 @@
1
+ import { r as SzamlazzError } from "./errors-DtN4g5Z9.js";
2
+ //#region src/core/once.ts
3
+ const DEFAULT_RECOVERY_DELAY_MS = 1e3;
4
+ const UNCERTAIN_CATEGORIES = /* @__PURE__ */ new Set([
5
+ "network",
6
+ "timeout",
7
+ "partial_success",
8
+ "duplicate",
9
+ "unexpected_response",
10
+ "unknown"
11
+ ]);
12
+ function isUncertainOutcome(error) {
13
+ return error instanceof SzamlazzError && UNCERTAIN_CATEGORIES.has(error.category);
14
+ }
15
+ function resolveRecoveryDelay(value) {
16
+ if (value === void 0) return DEFAULT_RECOVERY_DELAY_MS;
17
+ if (!Number.isFinite(value) || value < 0) throw new SzamlazzError(`A recoveryDelayMs értéke nemnegatív szám legyen, kapott: ${value}`, { category: "configuration" });
18
+ return value;
19
+ }
20
+ function wait(ms, signal) {
21
+ if (ms <= 0) return Promise.resolve();
22
+ return new Promise((resolve, reject) => {
23
+ if (signal?.aborted) {
24
+ reject(signal.reason);
25
+ return;
26
+ }
27
+ const timer = setTimeout(() => {
28
+ signal?.removeEventListener("abort", onAbort);
29
+ resolve();
30
+ }, ms);
31
+ const onAbort = () => {
32
+ clearTimeout(timer);
33
+ reject(signal?.reason);
34
+ };
35
+ signal?.addEventListener("abort", onAbort, { once: true });
36
+ });
37
+ }
38
+ async function recoverAfterFailure(lookup, delayMs, signal, state = {}) {
39
+ for (let attempt = 1; attempt <= 2; attempt++) {
40
+ await wait(delayMs * attempt, signal);
41
+ let found;
42
+ try {
43
+ found = await lookup();
44
+ } catch (error) {
45
+ if (!(error instanceof SzamlazzError)) throw error;
46
+ state.lookupError = error;
47
+ if (!error.retryable) return null;
48
+ found = void 0;
49
+ }
50
+ if (found) return found;
51
+ }
52
+ return null;
53
+ }
54
+ function unknownOutcomeError(error, reference, options = {}) {
55
+ const lookupError = options.lookupError;
56
+ const lookupNote = lookupError ? ` A visszakeresés is hibát adott (${lookupError.category}: ${lookupError.message}), ezt előbb hárítsd el.` : "";
57
+ return new SzamlazzError(error.message, {
58
+ category: error.category,
59
+ code: error.code,
60
+ action: error.action,
61
+ httpStatus: error.httpStatus,
62
+ rawResponse: error.rawResponse,
63
+ details: {
64
+ ...error.details,
65
+ outcome: "unknown",
66
+ reference,
67
+ ...lookupError ? { lookupError: `${lookupError.category}: ${lookupError.message}` } : {}
68
+ },
69
+ hint: `Nem tudni biztosan, hogy a(z) ${reference} ${options.subject ?? "bizonylata"} elkészült-e, és a visszakeresés sem találta meg.${lookupNote} Ne állítsd ki kézzel újra: később hívd meg ugyanígy a ${options.method ?? "createOnce"}-t, az előbb visszakeres.`,
70
+ cause: error
71
+ });
72
+ }
73
+ //#endregion
74
+ export { unknownOutcomeError as a, resolveRecoveryDelay as i, isUncertainOutcome as n, recoverAfterFailure as r, DEFAULT_RECOVERY_DELAY_MS as t };
@@ -1,6 +1,6 @@
1
- import { a as parseErrorCode, n as SzamlazzError, r as createAgentError } from "./errors-DLrb0g64.js";
1
+ import { i as createAgentError, r as SzamlazzError, s as parseErrorCode } from "./errors-DtN4g5Z9.js";
2
2
  import { a as isPdf, r as decodeUtf8, t as base64ToBytes } from "./binary-D0M9U2MD.js";
3
- import { c as childNumber, d as findChildren, f as parseXml, l as childText, s as childBoolean, u as findChild } from "./serialize-DSE_o9RK.js";
3
+ import { c as childNumber, d as findChildren, f as parseXml, l as childText, s as childBoolean, u as findChild } from "./serialize-B2eFh3D-.js";
4
4
  //#region src/core/response.ts
5
5
  function createAgentResponse(action, status, headers, body) {
6
6
  let cachedText;
@@ -1,6 +1,6 @@
1
- const require_errors = require("./errors-DxeuTslP.cjs");
1
+ const require_errors = require("./errors-EE96_6D_.cjs");
2
2
  const require_binary = require("./binary-B89HM03_.cjs");
3
- const require_serialize = require("./serialize-BXOww1Uq.cjs");
3
+ const require_serialize = require("./serialize-CquIsxA-.cjs");
4
4
  //#region src/core/response.ts
5
5
  function createAgentResponse(action, status, headers, body) {
6
6
  let cachedText;
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rounding = require("../rounding-TxoWy2ww.cjs");
3
- const require_webhook = require("../webhook-81giRMdQ.cjs");
3
+ const require_webhook = require("../webhook-Ckj-_hPD.cjs");
4
4
  const require_json = require("../json-4y4E2xxS.cjs");
5
5
  //#region src/payments/barion.ts
6
6
  const BARION_LIVE_API_URL = "https://api.barion.com";
@@ -144,6 +144,29 @@ function kindOf(status, paidTotal, refunds) {
144
144
  if (status && FAILED_STATUSES.has(status)) return "failed";
145
145
  return "other";
146
146
  }
147
+ function refundsOf(refunds, currency) {
148
+ if (!currency || refunds.length === 0) return void 0;
149
+ const ordered = refunds.map((refund) => ({
150
+ id: require_json.text(refund.TransactionId) ?? require_json.text(refund.POSTransactionId),
151
+ value: Math.abs(require_json.numeric(refund.Total) ?? 0),
152
+ createdAt: require_json.text(refund.TransactionTime)
153
+ })).filter((refund) => Boolean(refund.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id.localeCompare(b.id));
154
+ if (ordered.length !== refunds.length) return void 0;
155
+ let before = 0;
156
+ return ordered.map((refund) => {
157
+ const entry = {
158
+ id: refund.id,
159
+ amount: {
160
+ value: refund.value,
161
+ currency: require_webhook.normalizeCurrency(currency)
162
+ },
163
+ refundedBefore: before,
164
+ createdAt: refund.createdAt
165
+ };
166
+ before = sum([before, refund.value]);
167
+ return entry;
168
+ });
169
+ }
147
170
  function barionPaymentEvent(state, options = {}) {
148
171
  const paymentId = require_json.text(state.PaymentId);
149
172
  if (!paymentId) throw new require_webhook.PaymentProviderError("barion", "A Barion PaymentState válaszából hiányzik a PaymentId.");
@@ -170,6 +193,7 @@ function barionPaymentEvent(state, options = {}) {
170
193
  value: refunded,
171
194
  currency: require_webhook.normalizeCurrency(currency)
172
195
  } : void 0,
196
+ refunds: refundsOf(refunds, currency),
173
197
  paidAt: require_json.text(state.CompletedAt),
174
198
  method: methodOf(state, options.method),
175
199
  customer: customerOf(sales.length > 0 ? sales : transactions),
@@ -192,7 +216,7 @@ function barionWebhook(options) {
192
216
  });
193
217
  const returnedId = require_json.text(state.PaymentId);
194
218
  if (!returnedId || normalizeId(returnedId) !== normalizeId(paymentId)) throw new require_webhook.PaymentProviderError("barion", `A Barion más fizetést adott vissza (${returnedId ?? "?"}) a kért ${paymentId} helyett.`);
195
- await options.onPayment(barionPaymentEvent(state, { method: options.method }));
219
+ await require_webhook.deliverPayment(options, barionPaymentEvent(state, { method: options.method }));
196
220
  return require_webhook.plainResponse(200, "OK");
197
221
  });
198
222
  }
@@ -1,6 +1,6 @@
1
- import { i as PaymentEvent, l as PaymentWebhookBaseOptions } from "../types-BVeR7KyU.cjs";
1
+ import { i as PaymentEvent, u as PaymentWebhookBaseOptions } from "../types-B1A8mUIE.cjs";
2
2
  import { t as JsonRecord } from "../json-B70TwoX1.cjs";
3
- import { t as WebhookHandler } from "../webhook-CpMJuP6c.cjs";
3
+ import { r as WebhookHandler } from "../webhook-CmdhGiH5.cjs";
4
4
  //#region src/payments/barion.d.ts
5
5
  export declare const BARION_LIVE_API_URL = "https://api.barion.com";
6
6
  export declare const BARION_SANDBOX_API_URL = "https://api.test.barion.com";
@@ -1,6 +1,6 @@
1
- import { i as PaymentEvent, l as PaymentWebhookBaseOptions } from "../types-BVeR7KyU.js";
1
+ import { i as PaymentEvent, u as PaymentWebhookBaseOptions } from "../types-ByAEvGsZ.js";
2
2
  import { t as JsonRecord } from "../json-B70TwoX1.js";
3
- import { t as WebhookHandler } from "../webhook-CpCMHhn2.js";
3
+ import { r as WebhookHandler } from "../webhook-D6lEejob.js";
4
4
  //#region src/payments/barion.d.ts
5
5
  export declare const BARION_LIVE_API_URL = "https://api.barion.com";
6
6
  export declare const BARION_SANDBOX_API_URL = "https://api.test.barion.com";
@@ -1,5 +1,5 @@
1
1
  import { r as roundMoney } from "../rounding-BLyHjjI5.js";
2
- import { a as readRawBody, d as normalizeCurrency, i as plainResponse, o as PaymentProviderError, s as WebhookVerificationError, t as respondToWebhook } from "../webhook-CrEGohbg.js";
2
+ import { c as plainResponse, d as WebhookVerificationError, h as normalizeCurrency, i as respondToWebhook, l as readRawBody, r as deliverPayment, u as PaymentProviderError } from "../webhook-CQVShAfI.js";
3
3
  import { a as text, i as records, r as record, t as numeric } from "../json-DjnqnaJK.js";
4
4
  //#region src/payments/barion.ts
5
5
  const BARION_LIVE_API_URL = "https://api.barion.com";
@@ -143,6 +143,29 @@ function kindOf(status, paidTotal, refunds) {
143
143
  if (status && FAILED_STATUSES.has(status)) return "failed";
144
144
  return "other";
145
145
  }
146
+ function refundsOf(refunds, currency) {
147
+ if (!currency || refunds.length === 0) return void 0;
148
+ const ordered = refunds.map((refund) => ({
149
+ id: text(refund.TransactionId) ?? text(refund.POSTransactionId),
150
+ value: Math.abs(numeric(refund.Total) ?? 0),
151
+ createdAt: text(refund.TransactionTime)
152
+ })).filter((refund) => Boolean(refund.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id.localeCompare(b.id));
153
+ if (ordered.length !== refunds.length) return void 0;
154
+ let before = 0;
155
+ return ordered.map((refund) => {
156
+ const entry = {
157
+ id: refund.id,
158
+ amount: {
159
+ value: refund.value,
160
+ currency: normalizeCurrency(currency)
161
+ },
162
+ refundedBefore: before,
163
+ createdAt: refund.createdAt
164
+ };
165
+ before = sum([before, refund.value]);
166
+ return entry;
167
+ });
168
+ }
146
169
  function barionPaymentEvent(state, options = {}) {
147
170
  const paymentId = text(state.PaymentId);
148
171
  if (!paymentId) throw new PaymentProviderError("barion", "A Barion PaymentState válaszából hiányzik a PaymentId.");
@@ -169,6 +192,7 @@ function barionPaymentEvent(state, options = {}) {
169
192
  value: refunded,
170
193
  currency: normalizeCurrency(currency)
171
194
  } : void 0,
195
+ refunds: refundsOf(refunds, currency),
172
196
  paidAt: text(state.CompletedAt),
173
197
  method: methodOf(state, options.method),
174
198
  customer: customerOf(sales.length > 0 ? sales : transactions),
@@ -191,7 +215,7 @@ function barionWebhook(options) {
191
215
  });
192
216
  const returnedId = text(state.PaymentId);
193
217
  if (!returnedId || normalizeId(returnedId) !== normalizeId(paymentId)) throw new PaymentProviderError("barion", `A Barion más fizetést adott vissza (${returnedId ?? "?"}) a kért ${paymentId} helyett.`);
194
- await options.onPayment(barionPaymentEvent(state, { method: options.method }));
218
+ await deliverPayment(options, barionPaymentEvent(state, { method: options.method }));
195
219
  return plainResponse(200, "OK");
196
220
  });
197
221
  }
@@ -1,11 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_issue = require("../issue-AGRohSm7.cjs");
3
- const require_webhook = require("../webhook-81giRMdQ.cjs");
2
+ const require_issue = require("../issue-Bin4tKD_.cjs");
3
+ const require_webhook = require("../webhook-Ckj-_hPD.cjs");
4
+ exports.DEFAULT_DEDUPE_TTL_SECONDS = require_webhook.DEFAULT_DEDUPE_TTL_SECONDS;
4
5
  exports.DEFAULT_MAX_WEBHOOK_BYTES = require_webhook.DEFAULT_MAX_WEBHOOK_BYTES;
5
6
  exports.PaymentProviderError = require_webhook.PaymentProviderError;
7
+ exports.WEBHOOK_DEDUPE_KEY_PREFIX = require_webhook.WEBHOOK_DEDUPE_KEY_PREFIX;
6
8
  exports.WebhookVerificationError = require_webhook.WebhookVerificationError;
7
9
  exports.buyerFromCustomer = require_issue.buyerFromCustomer;
10
+ exports.correctionExternalId = require_issue.correctionExternalId;
8
11
  exports.currencyExponent = require_webhook.currencyExponent;
12
+ exports.deliverPayment = require_webhook.deliverPayment;
9
13
  exports.fromMinorUnits = require_webhook.fromMinorUnits;
10
14
  exports.isWebhookVerificationError = require_webhook.isWebhookVerificationError;
11
15
  exports.issueForPayment = require_issue.issueForPayment;
@@ -14,3 +18,4 @@ exports.parseDecimalAmount = require_webhook.parseDecimalAmount;
14
18
  exports.paymentOrderNumber = require_issue.paymentOrderNumber;
15
19
  exports.readRawBody = require_webhook.readRawBody;
16
20
  exports.respondToWebhook = require_webhook.respondToWebhook;
21
+ exports.webhookDedupeKey = require_webhook.webhookDedupeKey;
@@ -1,6 +1,6 @@
1
- import { C as buyerFromCustomer, S as SkippedPayment, T as paymentOrderNumber, _ as IssuedInvoice, b as PaymentDocumentItem, g as IssuedDocument, h as IssueForPaymentOptions, v as IssuedReceipt, w as issueForPayment, x as PaymentDocumentsApi, y as IssuedReversal } from "../client-B5FryKxJ.cjs";
2
- import { a as PaymentEventKind, c as PaymentProvider, i as PaymentEvent, l as PaymentWebhookBaseOptions, n as PaymentAmount, o as PaymentHandler, r as PaymentCustomer, s as PaymentLineItem, t as PaymentAddress } from "../types-BVeR7KyU.cjs";
3
- import { n as respondToWebhook, t as WebhookHandler } from "../webhook-CpMJuP6c.cjs";
1
+ import { A as IssuedRefundCorrection, C as PaymentDocumentItem, D as issueForPayment, E as buyerFromCustomer, F as RefundProposalLine, I as correctionExternalId, M as PartialRefundMode, N as RefundItemsContext, O as paymentOrderNumber, P as RefundItemsResolver, S as IssuedReversal, T as SkippedPayment, b as IssuedInvoice, j as IssuedRefundProposal, k as IssuedCorrection, v as IssueForPaymentOptions, w as PaymentDocumentsApi, x as IssuedReceipt, y as IssuedDocument } from "../client-SVZu25MB.cjs";
2
+ import { a as PaymentEventKind, c as PaymentProvider, i as PaymentEvent, l as PaymentRefund, n as PaymentAmount, o as PaymentHandler, r as PaymentCustomer, s as PaymentLineItem, t as PaymentAddress, u as PaymentWebhookBaseOptions } from "../types-B1A8mUIE.cjs";
3
+ import { a as respondToWebhook, i as deliverPayment, n as WEBHOOK_DEDUPE_KEY_PREFIX, o as webhookDedupeKey, r as WebhookHandler, t as DEFAULT_DEDUPE_TTL_SECONDS } from "../webhook-CmdhGiH5.cjs";
4
4
  //#region src/payments/amounts.d.ts
5
5
  type MinorUnitConvention = "iso4217" | "stripe";
6
6
  export declare function currencyExponent(currency: string, convention: MinorUnitConvention): number;
@@ -28,4 +28,4 @@ export declare class PaymentProviderError extends Error {
28
28
  }
29
29
  export declare function isWebhookVerificationError(error: unknown): error is WebhookVerificationError;
30
30
  //#endregion
31
- export { type IssueForPaymentOptions, type IssuedDocument, type IssuedInvoice, type IssuedReceipt, type IssuedReversal, type MinorUnitConvention, type PaymentAddress, type PaymentAmount, type PaymentCustomer, type PaymentDocumentItem, type PaymentDocumentsApi, type PaymentEvent, type PaymentEventKind, type PaymentHandler, type PaymentLineItem, type PaymentProvider, type PaymentWebhookBaseOptions, type SkippedPayment, type WebhookHandler, type WebhookVerificationReason, buyerFromCustomer, issueForPayment, paymentOrderNumber, respondToWebhook };
31
+ export { DEFAULT_DEDUPE_TTL_SECONDS, type IssueForPaymentOptions, type IssuedCorrection, type IssuedDocument, type IssuedInvoice, type IssuedReceipt, type IssuedRefundCorrection, type IssuedRefundProposal, type IssuedReversal, type MinorUnitConvention, type PartialRefundMode, type PaymentAddress, type PaymentAmount, type PaymentCustomer, type PaymentDocumentItem, type PaymentDocumentsApi, type PaymentEvent, type PaymentEventKind, type PaymentHandler, type PaymentLineItem, type PaymentProvider, type PaymentRefund, type PaymentWebhookBaseOptions, type RefundItemsContext, type RefundItemsResolver, type RefundProposalLine, type SkippedPayment, WEBHOOK_DEDUPE_KEY_PREFIX, type WebhookHandler, type WebhookVerificationReason, buyerFromCustomer, correctionExternalId, deliverPayment, issueForPayment, paymentOrderNumber, respondToWebhook, webhookDedupeKey };