ksef-client-ts 0.5.1 → 0.6.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.
package/dist/cli.js CHANGED
@@ -134,6 +134,34 @@ var init_ksef_forbidden_error = __esm({
134
134
  }
135
135
  });
136
136
 
137
+ // src/errors/ksef-validation-error.ts
138
+ var ksef_validation_error_exports = {};
139
+ __export(ksef_validation_error_exports, {
140
+ KSeFValidationError: () => KSeFValidationError
141
+ });
142
+ var KSeFValidationError;
143
+ var init_ksef_validation_error = __esm({
144
+ "src/errors/ksef-validation-error.ts"() {
145
+ "use strict";
146
+ init_ksef_error();
147
+ KSeFValidationError = class _KSeFValidationError extends KSeFError {
148
+ details;
149
+ constructor(message, details = []) {
150
+ super(message);
151
+ this.name = "KSeFValidationError";
152
+ this.details = details;
153
+ }
154
+ static fromField(field, message) {
155
+ return new _KSeFValidationError(message, [{ field, message }]);
156
+ }
157
+ static fromMessages(messages2) {
158
+ const details = messages2.map((m) => ({ message: m }));
159
+ return new _KSeFValidationError(messages2.join("; "), details);
160
+ }
161
+ };
162
+ }
163
+ });
164
+
137
165
  // src/config/environments.ts
138
166
  var Environment;
139
167
  var init_environments = __esm({
@@ -253,8 +281,8 @@ function isRetryableError(error, policy) {
253
281
  if (code && RETRYABLE_ERROR_CODES.has(code)) return true;
254
282
  return false;
255
283
  }
256
- function isRetryableStatus(status6, policy) {
257
- return policy.retryableStatusCodes.includes(status6);
284
+ function isRetryableStatus(status7, policy) {
285
+ return policy.retryableStatusCodes.includes(status7);
258
286
  }
259
287
  function sleep(ms) {
260
288
  return new Promise((resolve2) => setTimeout(resolve2, ms));
@@ -272,30 +300,6 @@ var init_retry_policy = __esm({
272
300
  }
273
301
  });
274
302
 
275
- // src/errors/ksef-validation-error.ts
276
- var KSeFValidationError;
277
- var init_ksef_validation_error = __esm({
278
- "src/errors/ksef-validation-error.ts"() {
279
- "use strict";
280
- init_ksef_error();
281
- KSeFValidationError = class _KSeFValidationError extends KSeFError {
282
- details;
283
- constructor(message, details = []) {
284
- super(message);
285
- this.name = "KSeFValidationError";
286
- this.details = details;
287
- }
288
- static fromField(field, message) {
289
- return new _KSeFValidationError(message, [{ field, message }]);
290
- }
291
- static fromMessages(messages2) {
292
- const details = messages2.map((m) => ({ message: m }));
293
- return new _KSeFValidationError(messages2.join("; "), details);
294
- }
295
- };
296
- }
297
- });
298
-
299
303
  // src/http/presigned-url-policy.ts
300
304
  function defaultPresignedUrlPolicy() {
301
305
  return {
@@ -504,9 +508,9 @@ var init_rest_client = __esm({
504
508
  return response;
505
509
  }
506
510
  buildUrl(request) {
507
- const path9 = this.routeBuilder.build(request.path);
511
+ const path10 = this.routeBuilder.build(request.path);
508
512
  const base = this.options.baseUrl;
509
- const url2 = new URL(`${base}${path9}`);
513
+ const url2 = new URL(`${base}${path10}`);
510
514
  const query2 = request.getQuery();
511
515
  for (const [key, value] of query2) {
512
516
  url2.searchParams.append(key, value);
@@ -677,21 +681,21 @@ var init_rest_request = __esm({
677
681
  _query = [];
678
682
  _presigned = false;
679
683
  _skipAuthRetry = false;
680
- constructor(method, path9) {
684
+ constructor(method, path10) {
681
685
  this.method = method;
682
- this.path = path9;
686
+ this.path = path10;
683
687
  }
684
- static get(path9) {
685
- return new _RestRequest("GET", path9);
688
+ static get(path10) {
689
+ return new _RestRequest("GET", path10);
686
690
  }
687
- static post(path9) {
688
- return new _RestRequest("POST", path9);
691
+ static post(path10) {
692
+ return new _RestRequest("POST", path10);
689
693
  }
690
- static put(path9) {
691
- return new _RestRequest("PUT", path9);
694
+ static put(path10) {
695
+ return new _RestRequest("PUT", path10);
692
696
  }
693
- static delete(path9) {
694
- return new _RestRequest("DELETE", path9);
697
+ static delete(path10) {
698
+ return new _RestRequest("DELETE", path10);
695
699
  }
696
700
  body(data) {
697
701
  this._body = data;
@@ -1090,8 +1094,8 @@ var init_session_status = __esm({
1090
1094
  if (filter.dateModifiedFrom) req.query("dateModifiedFrom", filter.dateModifiedFrom);
1091
1095
  if (filter.dateModifiedTo) req.query("dateModifiedTo", filter.dateModifiedTo);
1092
1096
  if (filter.statuses) {
1093
- for (const status6 of filter.statuses) {
1094
- req.query("statuses", status6);
1097
+ for (const status7 of filter.statuses) {
1098
+ req.query("statuses", status7);
1095
1099
  }
1096
1100
  }
1097
1101
  }
@@ -1465,20 +1469,20 @@ var init_lighthouse = __esm({
1465
1469
  this.lighthouseUrl = options.lighthouseUrl;
1466
1470
  this.timeout = options.timeout;
1467
1471
  }
1468
- async fetchJson(path9) {
1472
+ async fetchJson(path10) {
1469
1473
  if (!this.lighthouseUrl) {
1470
1474
  throw new KSeFError(
1471
1475
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
1472
1476
  );
1473
1477
  }
1474
- const response = await fetch(`${this.lighthouseUrl}${path9}`, {
1478
+ const response = await fetch(`${this.lighthouseUrl}${path10}`, {
1475
1479
  headers: { Accept: "application/json" },
1476
1480
  signal: AbortSignal.timeout(this.timeout)
1477
1481
  });
1478
1482
  if (!response.ok) {
1479
1483
  const body = await response.text();
1480
1484
  throw new KSeFError(
1481
- `Lighthouse ${path9} failed: HTTP ${response.status} \u2014 ${body}`
1485
+ `Lighthouse ${path10} failed: HTTP ${response.status} \u2014 ${body}`
1482
1486
  );
1483
1487
  }
1484
1488
  return await response.json();
@@ -2083,12 +2087,450 @@ var init_auth_xml_builder = __esm({
2083
2087
  }
2084
2088
  });
2085
2089
 
2090
+ // src/offline/deadline.ts
2091
+ function getDefaultReason(mode) {
2092
+ switch (mode) {
2093
+ case "offline24":
2094
+ return "PLANNED";
2095
+ case "offline":
2096
+ return "SYSTEM_UNAVAILABLE";
2097
+ case "awaryjny":
2098
+ return "EMERGENCY";
2099
+ case "awaria_calkowita":
2100
+ return "TOTAL_FAILURE";
2101
+ }
2102
+ }
2103
+ function nextBusinessDay(from) {
2104
+ const d = new Date(from);
2105
+ d.setUTCDate(d.getUTCDate() + 1);
2106
+ while (d.getUTCDay() === 0 || d.getUTCDay() === 6) {
2107
+ d.setUTCDate(d.getUTCDate() + 1);
2108
+ }
2109
+ return d;
2110
+ }
2111
+ function addBusinessDays(from, days) {
2112
+ if (!Number.isInteger(days) || days < 0) {
2113
+ throw new Error(`days must be a non-negative integer, got ${days}`);
2114
+ }
2115
+ const d = new Date(from);
2116
+ let remaining = days;
2117
+ while (remaining > 0) {
2118
+ d.setUTCDate(d.getUTCDate() + 1);
2119
+ if (d.getUTCDay() !== 0 && d.getUTCDay() !== 6) {
2120
+ remaining--;
2121
+ }
2122
+ }
2123
+ return d;
2124
+ }
2125
+ function endOfDay(d) {
2126
+ const result = new Date(d);
2127
+ result.setUTCHours(23, 59, 59, 999);
2128
+ return result;
2129
+ }
2130
+ function getMaintenanceEndFallback(mw) {
2131
+ if (mw.endTime) {
2132
+ return new Date(mw.endTime);
2133
+ }
2134
+ const start = new Date(mw.startTime);
2135
+ start.setUTCDate(start.getUTCDate() + 7);
2136
+ return start;
2137
+ }
2138
+ function calculateOfflineDeadline(mode, invoiceDate, maintenanceWindow) {
2139
+ const date = typeof invoiceDate === "string" ? new Date(invoiceDate) : invoiceDate;
2140
+ switch (mode) {
2141
+ case "offline24": {
2142
+ return endOfDay(nextBusinessDay(date));
2143
+ }
2144
+ case "offline": {
2145
+ const base = maintenanceWindow ? getMaintenanceEndFallback(maintenanceWindow) : date;
2146
+ return endOfDay(nextBusinessDay(base));
2147
+ }
2148
+ case "awaryjny": {
2149
+ const base = maintenanceWindow ? getMaintenanceEndFallback(maintenanceWindow) : date;
2150
+ return endOfDay(addBusinessDays(base, 7));
2151
+ }
2152
+ case "awaria_calkowita": {
2153
+ return new Date(FAR_FUTURE);
2154
+ }
2155
+ }
2156
+ }
2157
+ function isExpired(submitBy) {
2158
+ const deadline = typeof submitBy === "string" ? new Date(submitBy) : submitBy;
2159
+ return Date.now() > deadline.getTime();
2160
+ }
2161
+ var FAR_FUTURE;
2162
+ var init_deadline = __esm({
2163
+ "src/offline/deadline.ts"() {
2164
+ "use strict";
2165
+ FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T23:59:59Z");
2166
+ }
2167
+ });
2168
+
2169
+ // src/models/document-structures/types.ts
2170
+ var SystemCode, FORM_CODES, DEFAULT_FORM_CODE, INVOICE_TYPES_BY_SYSTEM_CODE, FORM_CODE_KEYS;
2171
+ var init_types = __esm({
2172
+ "src/models/document-structures/types.ts"() {
2173
+ "use strict";
2174
+ SystemCode = {
2175
+ FA_2: "FA (2)",
2176
+ FA_3: "FA (3)",
2177
+ PEF_3: "PEF (3)",
2178
+ PEF_KOR_3: "PEF_KOR (3)",
2179
+ FA_RR_1: "FA_RR (1)"
2180
+ };
2181
+ FORM_CODES = {
2182
+ FA_2: { systemCode: "FA (2)", schemaVersion: "1-0E", value: "FA" },
2183
+ FA_3: { systemCode: "FA (3)", schemaVersion: "1-0E", value: "FA" },
2184
+ PEF_3: { systemCode: "PEF (3)", schemaVersion: "2-1", value: "PEF" },
2185
+ PEF_KOR_3: { systemCode: "PEF_KOR (3)", schemaVersion: "2-1", value: "PEF" },
2186
+ FA_RR_1_LEGACY: { systemCode: "FA_RR (1)", schemaVersion: "1-0E", value: "RR" },
2187
+ FA_RR_1_TRANSITION: { systemCode: "FA_RR (1)", schemaVersion: "1-1E", value: "RR" },
2188
+ FA_RR_1: { systemCode: "FA_RR (1)", schemaVersion: "1-1E", value: "FA_RR" }
2189
+ };
2190
+ DEFAULT_FORM_CODE = FORM_CODES.FA_3;
2191
+ INVOICE_TYPES_BY_SYSTEM_CODE = {
2192
+ [SystemCode.FA_2]: ["Vat", "Zal", "Kor", "Roz", "Upr", "KorZal", "KorRoz"],
2193
+ [SystemCode.FA_3]: ["Vat", "Zal", "Kor", "Roz", "Upr", "KorZal", "KorRoz"],
2194
+ [SystemCode.PEF_3]: ["VatPef", "VatPefSp", "KorPef"],
2195
+ [SystemCode.PEF_KOR_3]: ["KorPef"],
2196
+ [SystemCode.FA_RR_1]: ["VatRr", "KorVatRr"]
2197
+ };
2198
+ FORM_CODE_KEYS = {
2199
+ FA2: FORM_CODES.FA_2,
2200
+ FA3: FORM_CODES.FA_3,
2201
+ PEF3: FORM_CODES.PEF_3,
2202
+ PEFKOR3: FORM_CODES.PEF_KOR_3,
2203
+ FARR1: FORM_CODES.FA_RR_1
2204
+ };
2205
+ }
2206
+ });
2207
+
2208
+ // src/models/document-structures/helpers.ts
2209
+ function validateFormCodeForSession(formCode, sessionType) {
2210
+ if (sessionType === "online") return true;
2211
+ return !BATCH_DISALLOWED_SYSTEM_CODES.has(formCode.systemCode);
2212
+ }
2213
+ var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
2214
+ var init_helpers = __esm({
2215
+ "src/models/document-structures/helpers.ts"() {
2216
+ "use strict";
2217
+ init_types();
2218
+ SYSTEM_CODE_TO_FORM_CODE = {
2219
+ [SystemCode.FA_2]: FORM_CODES.FA_2,
2220
+ [SystemCode.FA_3]: FORM_CODES.FA_3,
2221
+ [SystemCode.PEF_3]: FORM_CODES.PEF_3,
2222
+ [SystemCode.PEF_KOR_3]: FORM_CODES.PEF_KOR_3,
2223
+ [SystemCode.FA_RR_1]: FORM_CODES.FA_RR_1
2224
+ };
2225
+ ALL_FORM_CODES = Object.values(FORM_CODES);
2226
+ BATCH_DISALLOWED_SYSTEM_CODES = /* @__PURE__ */ new Set([
2227
+ SystemCode.PEF_3,
2228
+ SystemCode.PEF_KOR_3
2229
+ ]);
2230
+ }
2231
+ });
2232
+
2233
+ // src/models/document-structures/index.ts
2234
+ var init_document_structures = __esm({
2235
+ "src/models/document-structures/index.ts"() {
2236
+ "use strict";
2237
+ init_types();
2238
+ init_helpers();
2239
+ }
2240
+ });
2241
+
2242
+ // src/workflows/offline-invoice-workflow.ts
2243
+ import crypto3 from "crypto";
2244
+ var OfflineInvoiceWorkflow;
2245
+ var init_offline_invoice_workflow = __esm({
2246
+ "src/workflows/offline-invoice-workflow.ts"() {
2247
+ "use strict";
2248
+ init_ksef_api_error();
2249
+ init_deadline();
2250
+ init_document_structures();
2251
+ OfflineInvoiceWorkflow = class {
2252
+ constructor(qrService) {
2253
+ this.qrService = qrService;
2254
+ }
2255
+ async generate(input, options) {
2256
+ if (!input.invoiceXml || input.invoiceXml.trim().length === 0) {
2257
+ throw new Error("invoiceXml must not be empty");
2258
+ }
2259
+ if (!input.invoiceNumber) {
2260
+ throw new Error("invoiceNumber is required");
2261
+ }
2262
+ if (!input.sellerNip) {
2263
+ throw new Error("sellerNip is required");
2264
+ }
2265
+ const mode = options?.mode ?? "offline24";
2266
+ const reason = getDefaultReason(mode);
2267
+ const invoiceHashBase64 = crypto3.createHash("sha256").update(input.invoiceXml).digest("base64");
2268
+ const kod1Url = this.qrService.buildInvoiceVerificationUrl(
2269
+ input.sellerNip,
2270
+ input.invoiceDate,
2271
+ invoiceHashBase64
2272
+ );
2273
+ let kod2Url;
2274
+ if (options?.certificate) {
2275
+ kod2Url = this.qrService.buildCertificateVerificationUrl(
2276
+ input.sellerIdentifier.type,
2277
+ input.sellerIdentifier.value,
2278
+ input.sellerNip,
2279
+ options.certificate.certificateSerial,
2280
+ invoiceHashBase64,
2281
+ options.certificate.privateKeyPem
2282
+ );
2283
+ }
2284
+ const submitBy = options?.customDeadline ? typeof options.customDeadline === "string" ? options.customDeadline : options.customDeadline.toISOString() : calculateOfflineDeadline(mode, input.invoiceDate, options?.maintenanceWindow).toISOString();
2285
+ const metadata = {
2286
+ id: crypto3.randomUUID(),
2287
+ mode,
2288
+ reason,
2289
+ status: "GENERATED",
2290
+ invoiceNumber: input.invoiceNumber,
2291
+ invoiceDate: input.invoiceDate,
2292
+ invoiceXml: input.invoiceXml,
2293
+ sellerNip: input.sellerNip,
2294
+ sellerIdentifier: input.sellerIdentifier,
2295
+ buyerIdentifier: input.buyerIdentifier,
2296
+ totalAmount: input.totalAmount,
2297
+ currency: input.currency,
2298
+ kod1Url,
2299
+ kod2Url,
2300
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2301
+ submitBy,
2302
+ maintenanceWindowId: options?.maintenanceWindow?.id
2303
+ };
2304
+ if (options?.storage) {
2305
+ await options.storage.save(metadata);
2306
+ }
2307
+ return metadata;
2308
+ }
2309
+ async submit(client, options) {
2310
+ const { storage, checkExpiry = true } = options;
2311
+ let invoices2;
2312
+ if (options.invoiceIds) {
2313
+ invoices2 = [];
2314
+ const notFound = [];
2315
+ for (const id of options.invoiceIds) {
2316
+ const inv = await storage.get(id);
2317
+ if (inv) {
2318
+ invoices2.push(inv);
2319
+ } else {
2320
+ notFound.push(id);
2321
+ }
2322
+ }
2323
+ if (notFound.length > 0) {
2324
+ throw new Error(`Offline invoice(s) not found: ${notFound.join(", ")}`);
2325
+ }
2326
+ } else {
2327
+ invoices2 = await storage.list({ status: ["GENERATED", "QUEUED", "SUBMITTED"] });
2328
+ }
2329
+ const result = {
2330
+ total: invoices2.length,
2331
+ submitted: 0,
2332
+ accepted: 0,
2333
+ rejected: 0,
2334
+ failed: 0,
2335
+ expired: 0,
2336
+ results: []
2337
+ };
2338
+ if (invoices2.length === 0) return result;
2339
+ const pending = [];
2340
+ for (const inv of invoices2) {
2341
+ if (checkExpiry && isExpired(inv.submitBy)) {
2342
+ await storage.update(inv.id, { status: "EXPIRED" });
2343
+ result.expired++;
2344
+ result.results.push({
2345
+ invoiceId: inv.id,
2346
+ invoiceNumber: inv.invoiceNumber,
2347
+ status: "EXPIRED"
2348
+ });
2349
+ } else {
2350
+ pending.push(inv);
2351
+ }
2352
+ }
2353
+ if (pending.length === 0) return result;
2354
+ await client.crypto.init();
2355
+ const encData = client.crypto.getEncryptionData();
2356
+ const formCode = options.formCode ?? DEFAULT_FORM_CODE;
2357
+ const openResp = await client.onlineSession.openSession(
2358
+ { formCode, encryption: encData.encryptionInfo }
2359
+ );
2360
+ const sessionRef = openResp.referenceNumber;
2361
+ try {
2362
+ for (const inv of pending) {
2363
+ await storage.update(inv.id, { status: "QUEUED" });
2364
+ try {
2365
+ const data = new TextEncoder().encode(inv.invoiceXml);
2366
+ const plainMeta = client.crypto.getFileMetadata(data);
2367
+ const encrypted = client.crypto.encryptAES256(data, encData.cipherKey, encData.cipherIv);
2368
+ const encMeta = client.crypto.getFileMetadata(encrypted);
2369
+ await storage.update(inv.id, { status: "SUBMITTED", submittedAt: (/* @__PURE__ */ new Date()).toISOString() });
2370
+ const resp = await client.onlineSession.sendInvoice(sessionRef, {
2371
+ invoiceHash: plainMeta.hashSHA,
2372
+ invoiceSize: plainMeta.fileSize,
2373
+ encryptedInvoiceHash: encMeta.hashSHA,
2374
+ encryptedInvoiceSize: encMeta.fileSize,
2375
+ encryptedInvoiceContent: Buffer.from(encrypted).toString("base64"),
2376
+ offlineMode: true
2377
+ });
2378
+ await storage.update(inv.id, {
2379
+ status: "ACCEPTED",
2380
+ acceptedAt: (/* @__PURE__ */ new Date()).toISOString(),
2381
+ ksefReferenceNumber: resp.referenceNumber
2382
+ });
2383
+ result.submitted++;
2384
+ result.accepted++;
2385
+ result.results.push({
2386
+ invoiceId: inv.id,
2387
+ invoiceNumber: inv.invoiceNumber,
2388
+ status: "ACCEPTED",
2389
+ ksefReferenceNumber: resp.referenceNumber
2390
+ });
2391
+ } catch (err) {
2392
+ const message = err instanceof Error ? err.message : String(err);
2393
+ if (err instanceof KSeFApiError) {
2394
+ await storage.update(inv.id, {
2395
+ status: "REJECTED",
2396
+ error: { code: err.statusCode, message }
2397
+ });
2398
+ result.submitted++;
2399
+ result.rejected++;
2400
+ result.results.push({
2401
+ invoiceId: inv.id,
2402
+ invoiceNumber: inv.invoiceNumber,
2403
+ status: "REJECTED",
2404
+ error: { code: err.statusCode, message }
2405
+ });
2406
+ } else {
2407
+ await storage.update(inv.id, {
2408
+ status: "QUEUED",
2409
+ error: { code: 0, message }
2410
+ });
2411
+ result.failed++;
2412
+ result.results.push({
2413
+ invoiceId: inv.id,
2414
+ invoiceNumber: inv.invoiceNumber,
2415
+ status: "QUEUED",
2416
+ error: { code: 0, message }
2417
+ });
2418
+ }
2419
+ }
2420
+ }
2421
+ } finally {
2422
+ try {
2423
+ await client.onlineSession.closeSession(sessionRef);
2424
+ } catch {
2425
+ }
2426
+ }
2427
+ return result;
2428
+ }
2429
+ // TODO(perf): Each correction opens a separate KSeF session.
2430
+ // For batch corrections, consider a correctBatch() sharing one session (like submit()).
2431
+ async correct(client, options) {
2432
+ const { storage, rejectedInvoiceId, correctedInvoiceXml } = options;
2433
+ const original = await storage.get(rejectedInvoiceId);
2434
+ if (!original) {
2435
+ throw new Error(`Offline invoice not found: ${rejectedInvoiceId}`);
2436
+ }
2437
+ if (original.status !== "REJECTED") {
2438
+ throw new Error(
2439
+ original.status === "CORRECTED" ? `Invoice ${rejectedInvoiceId} has already been corrected (by ${original.correctedBy})` : `Only rejected invoices can be corrected (current status: ${original.status})`
2440
+ );
2441
+ }
2442
+ const originalHash = crypto3.createHash("sha256").update(original.invoiceXml).digest("base64");
2443
+ await client.crypto.init();
2444
+ const encData = client.crypto.getEncryptionData();
2445
+ const formCode = options.formCode ?? DEFAULT_FORM_CODE;
2446
+ const openResp = await client.onlineSession.openSession(
2447
+ { formCode, encryption: encData.encryptionInfo }
2448
+ );
2449
+ const sessionRef = openResp.referenceNumber;
2450
+ try {
2451
+ const data = new TextEncoder().encode(correctedInvoiceXml);
2452
+ const plainMeta = client.crypto.getFileMetadata(data);
2453
+ const encrypted = client.crypto.encryptAES256(data, encData.cipherKey, encData.cipherIv);
2454
+ const encMeta = client.crypto.getFileMetadata(encrypted);
2455
+ const correctionId = crypto3.randomUUID();
2456
+ const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
2457
+ const correctedHashBase64 = crypto3.createHash("sha256").update(correctedInvoiceXml).digest("base64");
2458
+ const kod1Url = this.qrService.buildInvoiceVerificationUrl(
2459
+ original.sellerNip,
2460
+ original.invoiceDate,
2461
+ correctedHashBase64
2462
+ );
2463
+ let kod2Url;
2464
+ if (options.certificate) {
2465
+ kod2Url = this.qrService.buildCertificateVerificationUrl(
2466
+ original.sellerIdentifier.type,
2467
+ original.sellerIdentifier.value,
2468
+ original.sellerNip,
2469
+ options.certificate.certificateSerial,
2470
+ correctedHashBase64,
2471
+ options.certificate.privateKeyPem
2472
+ );
2473
+ }
2474
+ const correctionMetadata = {
2475
+ id: correctionId,
2476
+ mode: original.mode,
2477
+ reason: original.reason,
2478
+ status: "SUBMITTED",
2479
+ invoiceNumber: original.invoiceNumber,
2480
+ invoiceDate: original.invoiceDate,
2481
+ invoiceXml: correctedInvoiceXml,
2482
+ sellerNip: original.sellerNip,
2483
+ sellerIdentifier: original.sellerIdentifier,
2484
+ buyerIdentifier: original.buyerIdentifier,
2485
+ kod1Url,
2486
+ kod2Url,
2487
+ generatedAt: submittedAt,
2488
+ submitBy: original.submitBy,
2489
+ submittedAt,
2490
+ correctedInvoiceId: rejectedInvoiceId
2491
+ };
2492
+ await storage.save(correctionMetadata);
2493
+ const resp = await client.onlineSession.sendInvoice(sessionRef, {
2494
+ invoiceHash: plainMeta.hashSHA,
2495
+ invoiceSize: plainMeta.fileSize,
2496
+ encryptedInvoiceHash: encMeta.hashSHA,
2497
+ encryptedInvoiceSize: encMeta.fileSize,
2498
+ encryptedInvoiceContent: Buffer.from(encrypted).toString("base64"),
2499
+ offlineMode: true,
2500
+ hashOfCorrectedInvoice: originalHash
2501
+ });
2502
+ await storage.update(correctionId, {
2503
+ status: "ACCEPTED",
2504
+ acceptedAt: (/* @__PURE__ */ new Date()).toISOString(),
2505
+ ksefReferenceNumber: resp.referenceNumber
2506
+ });
2507
+ await storage.update(rejectedInvoiceId, {
2508
+ status: "CORRECTED",
2509
+ correctedBy: correctionId
2510
+ });
2511
+ return {
2512
+ invoiceId: correctionId,
2513
+ invoiceNumber: correctionMetadata.invoiceNumber,
2514
+ status: "ACCEPTED",
2515
+ ksefReferenceNumber: resp.referenceNumber
2516
+ };
2517
+ } finally {
2518
+ try {
2519
+ await client.onlineSession.closeSession(sessionRef);
2520
+ } catch {
2521
+ }
2522
+ }
2523
+ }
2524
+ };
2525
+ }
2526
+ });
2527
+
2086
2528
  // src/crypto/signature-service.ts
2087
2529
  var signature_service_exports = {};
2088
2530
  __export(signature_service_exports, {
2089
2531
  SignatureService: () => SignatureService
2090
2532
  });
2091
- import * as crypto3 from "crypto";
2533
+ import * as crypto4 from "crypto";
2092
2534
  import { ExclusiveCanonicalization } from "xml-crypto";
2093
2535
  import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
2094
2536
  function extractDerFromPem(pem) {
@@ -2108,7 +2550,7 @@ function canonicalize(elem) {
2108
2550
  function computeRootDigest(doc) {
2109
2551
  const root = doc.documentElement;
2110
2552
  const canonical = canonicalize(root);
2111
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
2553
+ return crypto4.createHash("sha256").update(canonical, "utf-8").digest("base64");
2112
2554
  }
2113
2555
  function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
2114
2556
  const parser = new DOMParser();
@@ -2118,7 +2560,7 @@ function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
2118
2560
  throw new Error("SignedProperties element not found in QualifyingProperties");
2119
2561
  }
2120
2562
  const canonical = canonicalize(signedProps);
2121
- return crypto3.createHash("sha256").update(canonical, "utf-8").digest("base64");
2563
+ return crypto4.createHash("sha256").update(canonical, "utf-8").digest("base64");
2122
2564
  }
2123
2565
  function buildSignedInfo(signatureAlgorithm, rootDigest, signedPropertiesDigest) {
2124
2566
  return [
@@ -2149,12 +2591,12 @@ function computeSignatureValue(canonicalSignedInfo, privateKey, isEc) {
2149
2591
  const data = Buffer.from(canonicalSignedInfo, "utf-8");
2150
2592
  let signature;
2151
2593
  if (isEc) {
2152
- signature = crypto3.sign("sha256", data, {
2594
+ signature = crypto4.sign("sha256", data, {
2153
2595
  key: privateKey,
2154
2596
  dsaEncoding: "ieee-p1363"
2155
2597
  });
2156
2598
  } else {
2157
- signature = crypto3.sign("sha256", data, privateKey);
2599
+ signature = crypto4.sign("sha256", data, privateKey);
2158
2600
  }
2159
2601
  return signature.toString("base64");
2160
2602
  }
@@ -2254,11 +2696,11 @@ var init_signature_service = __esm({
2254
2696
  }
2255
2697
  const certDer = extractDerFromPem(certPem);
2256
2698
  const certBase64 = certDer.toString("base64");
2257
- const certDigest = crypto3.createHash("sha256").update(certDer).digest("base64");
2258
- const x5093 = new crypto3.X509Certificate(certPem);
2699
+ const certDigest = crypto4.createHash("sha256").update(certDer).digest("base64");
2700
+ const x5093 = new crypto4.X509Certificate(certPem);
2259
2701
  const issuerName = normalizeIssuerDn(x5093.issuer);
2260
2702
  const serialNumber = hexSerialToDecimal(x5093.serialNumber);
2261
- const privateKey = crypto3.createPrivateKey(
2703
+ const privateKey = crypto4.createPrivateKey(
2262
2704
  passphrase ? { key: privateKeyPem, format: "pem", passphrase } : privateKeyPem
2263
2705
  );
2264
2706
  const isEc = privateKey.asymmetricKeyType === "ec";
@@ -2423,6 +2865,7 @@ var init_client = __esm({
2423
2865
  init_cryptography_service();
2424
2866
  init_verification_link_service();
2425
2867
  init_auth_xml_builder();
2868
+ init_offline_invoice_workflow();
2426
2869
  KSeFClient = class {
2427
2870
  auth;
2428
2871
  activeSessions;
@@ -2441,6 +2884,7 @@ var init_client = __esm({
2441
2884
  qr;
2442
2885
  options;
2443
2886
  authManager;
2887
+ _offline;
2444
2888
  constructor(options) {
2445
2889
  this.options = resolveOptions(options);
2446
2890
  const authManager = options?.authManager ?? new DefaultAuthManager(async () => {
@@ -2469,6 +2913,12 @@ var init_client = __esm({
2469
2913
  this.testData = new TestDataService(restClient, this.options.environmentName);
2470
2914
  this.qr = new VerificationLinkService(this.options.baseQrUrl);
2471
2915
  }
2916
+ get offline() {
2917
+ if (!this._offline) {
2918
+ this._offline = new OfflineInvoiceWorkflow(this.qr);
2919
+ }
2920
+ return this._offline;
2921
+ }
2472
2922
  async loginWithToken(token, nip) {
2473
2923
  const challenge2 = await this.auth.getChallenge();
2474
2924
  await this.crypto.init();
@@ -2503,10 +2953,10 @@ var init_client = __esm({
2503
2953
  }
2504
2954
  async awaitAuthReady(referenceNumber, authToken) {
2505
2955
  for (let i = 0; i < 30; i++) {
2506
- const status6 = await this.auth.getAuthStatus(referenceNumber, authToken);
2507
- if (status6.status.code === 200) return;
2508
- if (status6.status.code !== 100) {
2509
- throw new Error(`Authentication failed with status ${status6.status.code}: ${status6.status.description}`);
2956
+ const status7 = await this.auth.getAuthStatus(referenceNumber, authToken);
2957
+ if (status7.status.code === 200) return;
2958
+ if (status7.status.code !== 100) {
2959
+ throw new Error(`Authentication failed with status ${status7.status.code}: ${status7.status.description}`);
2510
2960
  }
2511
2961
  await new Promise((r) => setTimeout(r, 1e3));
2512
2962
  }
@@ -2541,89 +2991,16 @@ var init_polling = __esm({
2541
2991
  }
2542
2992
  });
2543
2993
 
2544
- // src/models/document-structures/types.ts
2545
- var SystemCode, FORM_CODES, DEFAULT_FORM_CODE, INVOICE_TYPES_BY_SYSTEM_CODE, FORM_CODE_KEYS;
2546
- var init_types = __esm({
2547
- "src/models/document-structures/types.ts"() {
2548
- "use strict";
2549
- SystemCode = {
2550
- FA_2: "FA (2)",
2551
- FA_3: "FA (3)",
2552
- PEF_3: "PEF (3)",
2553
- PEF_KOR_3: "PEF_KOR (3)",
2554
- FA_RR_1: "FA_RR (1)"
2555
- };
2556
- FORM_CODES = {
2557
- FA_2: { systemCode: "FA (2)", schemaVersion: "1-0E", value: "FA" },
2558
- FA_3: { systemCode: "FA (3)", schemaVersion: "1-0E", value: "FA" },
2559
- PEF_3: { systemCode: "PEF (3)", schemaVersion: "2-1", value: "PEF" },
2560
- PEF_KOR_3: { systemCode: "PEF_KOR (3)", schemaVersion: "2-1", value: "PEF" },
2561
- FA_RR_1_LEGACY: { systemCode: "FA_RR (1)", schemaVersion: "1-0E", value: "RR" },
2562
- FA_RR_1_TRANSITION: { systemCode: "FA_RR (1)", schemaVersion: "1-1E", value: "RR" },
2563
- FA_RR_1: { systemCode: "FA_RR (1)", schemaVersion: "1-1E", value: "FA_RR" }
2564
- };
2565
- DEFAULT_FORM_CODE = FORM_CODES.FA_3;
2566
- INVOICE_TYPES_BY_SYSTEM_CODE = {
2567
- [SystemCode.FA_2]: ["Vat", "Zal", "Kor", "Roz", "Upr", "KorZal", "KorRoz"],
2568
- [SystemCode.FA_3]: ["Vat", "Zal", "Kor", "Roz", "Upr", "KorZal", "KorRoz"],
2569
- [SystemCode.PEF_3]: ["VatPef", "VatPefSp", "KorPef"],
2570
- [SystemCode.PEF_KOR_3]: ["KorPef"],
2571
- [SystemCode.FA_RR_1]: ["VatRr", "KorVatRr"]
2572
- };
2573
- FORM_CODE_KEYS = {
2574
- FA2: FORM_CODES.FA_2,
2575
- FA3: FORM_CODES.FA_3,
2576
- PEF3: FORM_CODES.PEF_3,
2577
- PEFKOR3: FORM_CODES.PEF_KOR_3,
2578
- FARR1: FORM_CODES.FA_RR_1
2579
- };
2994
+ // src/xml/upo-parser.ts
2995
+ import { XMLParser } from "fast-xml-parser";
2996
+ function isRecord(value) {
2997
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2998
+ }
2999
+ function requireRecord(value, at) {
3000
+ if (!isRecord(value)) {
3001
+ throw KSeFValidationError.fromField(at, `Expected object at ${at}`);
2580
3002
  }
2581
- });
2582
-
2583
- // src/models/document-structures/helpers.ts
2584
- function validateFormCodeForSession(formCode, sessionType) {
2585
- if (sessionType === "online") return true;
2586
- return !BATCH_DISALLOWED_SYSTEM_CODES.has(formCode.systemCode);
2587
- }
2588
- var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
2589
- var init_helpers = __esm({
2590
- "src/models/document-structures/helpers.ts"() {
2591
- "use strict";
2592
- init_types();
2593
- SYSTEM_CODE_TO_FORM_CODE = {
2594
- [SystemCode.FA_2]: FORM_CODES.FA_2,
2595
- [SystemCode.FA_3]: FORM_CODES.FA_3,
2596
- [SystemCode.PEF_3]: FORM_CODES.PEF_3,
2597
- [SystemCode.PEF_KOR_3]: FORM_CODES.PEF_KOR_3,
2598
- [SystemCode.FA_RR_1]: FORM_CODES.FA_RR_1
2599
- };
2600
- ALL_FORM_CODES = Object.values(FORM_CODES);
2601
- BATCH_DISALLOWED_SYSTEM_CODES = /* @__PURE__ */ new Set([
2602
- SystemCode.PEF_3,
2603
- SystemCode.PEF_KOR_3
2604
- ]);
2605
- }
2606
- });
2607
-
2608
- // src/models/document-structures/index.ts
2609
- var init_document_structures = __esm({
2610
- "src/models/document-structures/index.ts"() {
2611
- "use strict";
2612
- init_types();
2613
- init_helpers();
2614
- }
2615
- });
2616
-
2617
- // src/xml/upo-parser.ts
2618
- import { XMLParser } from "fast-xml-parser";
2619
- function isRecord(value) {
2620
- return typeof value === "object" && value !== null && !Array.isArray(value);
2621
- }
2622
- function requireRecord(value, at) {
2623
- if (!isRecord(value)) {
2624
- throw KSeFValidationError.fromField(at, `Expected object at ${at}`);
2625
- }
2626
- return value;
3003
+ return value;
2627
3004
  }
2628
3005
  function requireString(value, at) {
2629
3006
  if (typeof value !== "string" || value.length === 0) {
@@ -2738,11 +3115,251 @@ var init_upo_parser = __esm({
2738
3115
  }
2739
3116
  });
2740
3117
 
3118
+ // src/xml/invoice-field-extractor.ts
3119
+ import { XMLParser as XMLParser2 } from "fast-xml-parser";
3120
+ function extractInvoiceFields(xml) {
3121
+ const parsed = invoiceParser.parse(xml);
3122
+ const root = parsed?.Faktura;
3123
+ if (!root || typeof root !== "object") {
3124
+ throw new Error(
3125
+ "Cannot extract invoice fields: missing <Faktura> root element. Ensure the XML is a valid KSeF invoice (FA_2, FA_3, or FA_RR)."
3126
+ );
3127
+ }
3128
+ if (root.Fa && typeof root.Fa === "object") {
3129
+ const invoiceDate = nonEmptyString(root.Fa.P_1);
3130
+ const invoiceNumber = nonEmptyString(root.Fa.P_2);
3131
+ if (invoiceDate && invoiceNumber) {
3132
+ return { invoiceNumber, invoiceDate };
3133
+ }
3134
+ }
3135
+ if (root.FakturaRR && typeof root.FakturaRR === "object") {
3136
+ const invoiceDate = nonEmptyString(root.FakturaRR.P_4B);
3137
+ const invoiceNumber = nonEmptyString(root.FakturaRR.P_4C);
3138
+ if (invoiceDate && invoiceNumber) {
3139
+ return { invoiceNumber, invoiceDate };
3140
+ }
3141
+ }
3142
+ throw new Error(
3143
+ "Cannot extract invoice number and date from XML. Expected <Fa><P_1>/<P_2> (FA format) or <FakturaRR><P_4B>/<P_4C> (RR format)."
3144
+ );
3145
+ }
3146
+ function nonEmptyString(value) {
3147
+ return typeof value === "string" && value.length > 0 ? value : void 0;
3148
+ }
3149
+ var invoiceParser;
3150
+ var init_invoice_field_extractor = __esm({
3151
+ "src/xml/invoice-field-extractor.ts"() {
3152
+ "use strict";
3153
+ invoiceParser = new XMLParser2({
3154
+ ignoreAttributes: false,
3155
+ attributeNamePrefix: "@_",
3156
+ parseTagValue: false,
3157
+ parseAttributeValue: false,
3158
+ removeNSPrefix: true,
3159
+ trimValues: false
3160
+ });
3161
+ }
3162
+ });
3163
+
2741
3164
  // src/xml/index.ts
2742
3165
  var init_xml = __esm({
2743
3166
  "src/xml/index.ts"() {
2744
3167
  "use strict";
2745
3168
  init_upo_parser();
3169
+ init_invoice_field_extractor();
3170
+ }
3171
+ });
3172
+
3173
+ // src/utils/zip.ts
3174
+ var zip_exports = {};
3175
+ __export(zip_exports, {
3176
+ createZip: () => createZip,
3177
+ unzip: () => unzip
3178
+ });
3179
+ import { ZipFile } from "yazl";
3180
+ import { fromBuffer } from "yauzl";
3181
+ async function createZip(entries) {
3182
+ return new Promise((resolve2, reject) => {
3183
+ const zipfile = new ZipFile();
3184
+ for (const entry of entries) {
3185
+ zipfile.addBuffer(Buffer.from(entry.content), entry.fileName);
3186
+ }
3187
+ const chunks = [];
3188
+ zipfile.outputStream.on("data", (chunk) => chunks.push(chunk));
3189
+ zipfile.outputStream.on("error", (err) => reject(err));
3190
+ zipfile.outputStream.on("end", () => resolve2(Buffer.concat(chunks)));
3191
+ zipfile.end();
3192
+ });
3193
+ }
3194
+ async function unzip(buffer, options = {}) {
3195
+ const limits2 = { ...DEFAULT_UNZIP_OPTIONS, ...options };
3196
+ return new Promise((resolve2, reject) => {
3197
+ fromBuffer(buffer, { lazyEntries: true }, (err, zipfile) => {
3198
+ if (err || !zipfile) {
3199
+ reject(err ?? new Error("Failed to open zip buffer"));
3200
+ return;
3201
+ }
3202
+ const files = /* @__PURE__ */ new Map();
3203
+ let totalUncompressed = 0;
3204
+ zipfile.readEntry();
3205
+ zipfile.on("entry", (entry) => {
3206
+ if (entry.fileName.endsWith("/")) {
3207
+ zipfile.readEntry();
3208
+ return;
3209
+ }
3210
+ if (limits2.maxFiles > 0 && files.size >= limits2.maxFiles) {
3211
+ reject(new Error("zip contains too many files"));
3212
+ return;
3213
+ }
3214
+ const uncompressedSize = entry.uncompressedSize ?? 0;
3215
+ const compressedSize = entry.compressedSize ?? 0;
3216
+ if (limits2.maxFileUncompressedSize > 0 && uncompressedSize > limits2.maxFileUncompressedSize) {
3217
+ reject(new Error("zip entry exceeds max_file_uncompressed_size"));
3218
+ return;
3219
+ }
3220
+ if (limits2.maxTotalUncompressedSize > 0) {
3221
+ totalUncompressed += uncompressedSize;
3222
+ if (totalUncompressed > limits2.maxTotalUncompressedSize) {
3223
+ reject(new Error("zip exceeds max_total_uncompressed_size"));
3224
+ return;
3225
+ }
3226
+ }
3227
+ if (limits2.maxCompressionRatio !== null) {
3228
+ if (compressedSize === 0 && uncompressedSize > 0) {
3229
+ reject(new Error("zip entry has suspicious compression metadata"));
3230
+ return;
3231
+ }
3232
+ if (compressedSize > 0 && uncompressedSize > 0) {
3233
+ const ratio = uncompressedSize / compressedSize;
3234
+ if (ratio > limits2.maxCompressionRatio) {
3235
+ reject(new Error("zip entry exceeds max_compression_ratio"));
3236
+ return;
3237
+ }
3238
+ }
3239
+ }
3240
+ zipfile.openReadStream(entry, (streamErr, stream) => {
3241
+ if (streamErr || !stream) {
3242
+ reject(streamErr ?? new Error("Failed to read zip entry"));
3243
+ return;
3244
+ }
3245
+ const chunks = [];
3246
+ stream.on("data", (chunk) => chunks.push(chunk));
3247
+ stream.on("error", (streamError) => reject(streamError));
3248
+ stream.on("end", () => {
3249
+ files.set(entry.fileName, Buffer.concat(chunks));
3250
+ zipfile.readEntry();
3251
+ });
3252
+ });
3253
+ });
3254
+ zipfile.on("end", () => resolve2(files));
3255
+ zipfile.on("error", (zipErr) => reject(zipErr));
3256
+ });
3257
+ });
3258
+ }
3259
+ var DEFAULT_UNZIP_OPTIONS;
3260
+ var init_zip = __esm({
3261
+ "src/utils/zip.ts"() {
3262
+ "use strict";
3263
+ DEFAULT_UNZIP_OPTIONS = {
3264
+ maxFiles: 1e4,
3265
+ maxTotalUncompressedSize: 2e9,
3266
+ maxFileUncompressedSize: 5e8,
3267
+ maxCompressionRatio: 200
3268
+ };
3269
+ }
3270
+ });
3271
+
3272
+ // src/validation/xml-to-object.ts
3273
+ import { DOMParser as DOMParser2 } from "@xmldom/xmldom";
3274
+ function xmlToObject(xml) {
3275
+ const errors = [];
3276
+ const doc = new DOMParser2({
3277
+ errorHandler: {
3278
+ warning: (_msg) => {
3279
+ },
3280
+ error: (msg) => errors.push(msg),
3281
+ fatalError: (msg) => errors.push(msg)
3282
+ }
3283
+ }).parseFromString(xml, "text/xml");
3284
+ if (errors.length > 0 || !doc || !doc.documentElement) {
3285
+ return { object: null, rootElement: null, namespace: null, errors };
3286
+ }
3287
+ const root = doc.documentElement;
3288
+ const rootName = getLocalName(root);
3289
+ const namespace = root.namespaceURI || null;
3290
+ const obj = elementToObject(root);
3291
+ return {
3292
+ object: typeof obj === "object" && obj !== null ? obj : { "#text": obj },
3293
+ rootElement: rootName,
3294
+ namespace,
3295
+ errors: []
3296
+ };
3297
+ }
3298
+ function getLocalName(node) {
3299
+ if (node.localName) return node.localName;
3300
+ const name = node.nodeName;
3301
+ const idx = name.indexOf(":");
3302
+ return idx === -1 ? name : name.substring(idx + 1);
3303
+ }
3304
+ function elementToObject(el) {
3305
+ const result = {};
3306
+ let hasChildElements = false;
3307
+ for (let i = 0; i < el.attributes.length; i++) {
3308
+ const a = el.attributes.item(i);
3309
+ if (!a) continue;
3310
+ const name = a.nodeName;
3311
+ if (name === "xmlns" || name.startsWith("xmlns:")) continue;
3312
+ const attrLocal = getLocalName(a);
3313
+ result[`@${attrLocal}`] = a.value;
3314
+ }
3315
+ const childCounts = /* @__PURE__ */ new Map();
3316
+ for (let i = 0; i < el.childNodes.length; i++) {
3317
+ const child = el.childNodes.item(i);
3318
+ if (!child || child.nodeType !== 1) continue;
3319
+ const name = getLocalName(child);
3320
+ childCounts.set(name, (childCounts.get(name) || 0) + 1);
3321
+ hasChildElements = true;
3322
+ }
3323
+ if (!hasChildElements) {
3324
+ const text = getTextContent(el);
3325
+ const hasAttrs = Object.keys(result).length > 0;
3326
+ if (hasAttrs) {
3327
+ result["#text"] = text;
3328
+ return result;
3329
+ }
3330
+ return text;
3331
+ }
3332
+ for (let i = 0; i < el.childNodes.length; i++) {
3333
+ const child = el.childNodes.item(i);
3334
+ if (!child || child.nodeType !== 1) continue;
3335
+ const name = getLocalName(child);
3336
+ const value = elementToObject(child);
3337
+ const count = childCounts.get(name) || 1;
3338
+ if (count > 1) {
3339
+ if (!Array.isArray(result[name])) {
3340
+ result[name] = [];
3341
+ }
3342
+ result[name].push(value);
3343
+ } else {
3344
+ result[name] = value;
3345
+ }
3346
+ }
3347
+ return result;
3348
+ }
3349
+ function getTextContent(el) {
3350
+ let text = "";
3351
+ for (let i = 0; i < el.childNodes.length; i++) {
3352
+ const child = el.childNodes.item(i);
3353
+ if (!child) continue;
3354
+ if (child.nodeType === 3 || child.nodeType === 4) {
3355
+ text += child.nodeValue || "";
3356
+ }
3357
+ }
3358
+ return text.trim();
3359
+ }
3360
+ var init_xml_to_object = __esm({
3361
+ "src/validation/xml-to-object.ts"() {
3362
+ "use strict";
2746
3363
  }
2747
3364
  });
2748
3365
 
@@ -2760,18 +3377,18 @@ var init_fa3 = __esm({
2760
3377
  TDataCzas = z.string();
2761
3378
  TZnakowy = z.string().min(1).max(256);
2762
3379
  TNaglowek = z.object({
2763
- "KodFormularza": z.object({ "#text": TKodFormularza, "@kodSystemowy": z.literal("FA (3)"), "@wersjaSchemy": z.literal("1-0E") }),
3380
+ "KodFormularza": z.object({ "#text": TKodFormularza, "@kodSystemowy": z.literal("FA (3)"), "@wersjaSchemy": z.literal("1-0E") }).strict(),
2764
3381
  "WariantFormularza": z.literal("3"),
2765
3382
  "DataWytworzeniaFa": z.string(),
2766
3383
  "SystemInfo": TZnakowy.optional()
2767
- });
3384
+ }).strict();
2768
3385
  TKodyKrajowUE = z.enum(["AT", "BE", "BG", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "EL", "HR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "XI"]);
2769
3386
  TNrNIP = z.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
2770
3387
  TZnakowy512 = z.string().min(1).max(512);
2771
3388
  TPodmiot1 = z.object({
2772
3389
  "NIP": TNrNIP,
2773
3390
  "Nazwa": TZnakowy512
2774
- });
3391
+ }).strict();
2775
3392
  TKodKraju = z.enum(["AF", "AX", "AL", "DZ", "AD", "AO", "AI", "AQ", "AG", "AN", "SA", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BY", "BO", "BQ", "BA", "BW", "BR", "BN", "IO", "BG", "BF", "BI", "XC", "CL", "CN", "HR", "CW", "CY", "TD", "ME", "DK", "DM", "DO", "DJ", "EG", "EC", "ER", "EE", "ET", "FK", "FJ", "PH", "FI", "FR", "TF", "GA", "GM", "GH", "GI", "GR", "GD", "GL", "GE", "GU", "GG", "GY", "GF", "GP", "GT", "GN", "GQ", "GW", "HT", "ES", "HN", "HK", "IN", "ID", "IQ", "IR", "IE", "IS", "IL", "JM", "JP", "YE", "JE", "JO", "KY", "KH", "CM", "CA", "QA", "KZ", "KE", "KG", "KI", "CO", "KM", "CG", "CD", "KP", "XK", "CR", "CU", "KW", "LA", "LS", "LB", "LR", "LY", "LI", "LT", "LV", "LU", "MK", "MG", "YT", "MO", "MW", "MV", "MY", "ML", "MT", "MP", "MA", "MQ", "MR", "MU", "MX", "XL", "FM", "UM", "MD", "MC", "MN", "MS", "MZ", "MM", "NA", "NR", "NP", "NL", "DE", "NE", "NG", "NI", "NU", "NF", "NO", "NC", "NZ", "PS", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PN", "PF", "PL", "GS", "PT", "PR", "CF", "CZ", "KR", "ZA", "RE", "RU", "RO", "RW", "EH", "BL", "KN", "LC", "MF", "VC", "SV", "WS", "AS", "SM", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SO", "LK", "PM", "US", "SZ", "SD", "SS", "SR", "SJ", "SH", "SY", "CH", "SE", "TJ", "TH", "TW", "TZ", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TV", "UG", "UA", "UY", "UZ", "VU", "WF", "VA", "HU", "VE", "GB", "VN", "IT", "TL", "CI", "BV", "CX", "IM", "SX", "CK", "VI", "VG", "HM", "CC", "MH", "FO", "SB", "ST", "TC", "ZM", "CV", "ZW", "AE", "XI"]);
2776
3393
  TGLN = z.string().min(1).max(13);
2777
3394
  TAdres = z.object({
@@ -2779,7 +3396,7 @@ var init_fa3 = __esm({
2779
3396
  "AdresL1": TZnakowy512,
2780
3397
  "AdresL2": TZnakowy512.optional(),
2781
3398
  "GLN": TGLN.optional()
2782
- });
3399
+ }).strict();
2783
3400
  TAdresEmail = z.string().min(3).max(255).regex(/^(.)+@(.)+$/);
2784
3401
  TNumerTelefonu = z.string().min(1).max(16);
2785
3402
  TStatusInfoPodatnika = z.enum(["1", "2", "3", "4"]);
@@ -2794,7 +3411,7 @@ var init_fa3 = __esm({
2794
3411
  "NrID": z.string().min(1).max(50).optional(),
2795
3412
  "BrakID": TWybor1.optional(),
2796
3413
  "Nazwa": TZnakowy512.optional()
2797
- });
3414
+ }).strict();
2798
3415
  TZnakowy50 = z.string().min(1).max(50);
2799
3416
  TZnakowy20 = z.string().min(1).max(20);
2800
3417
  TNIPIdWew = z.string().min(1).max(20).regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}-\d{5}$/);
@@ -2807,7 +3424,7 @@ var init_fa3 = __esm({
2807
3424
  "NrID": z.string().min(1).max(50).optional(),
2808
3425
  "BrakID": TWybor1.optional(),
2809
3426
  "Nazwa": TZnakowy512.optional()
2810
- });
3427
+ }).strict();
2811
3428
  TRolaPodmiotu3 = z.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]);
2812
3429
  TProcentowy = z.coerce.number().min(0).max(100);
2813
3430
  TRolaPodmiotuUpowaznionego = z.enum(["1", "2", "3"]);
@@ -2825,7 +3442,7 @@ var init_fa3 = __esm({
2825
3442
  "NrWiersza": TNaturalny.optional(),
2826
3443
  "Klucz": TZnakowy,
2827
3444
  "Wartosc": TZnakowy
2828
- });
3445
+ }).strict();
2829
3446
  TKwotowy2 = z.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
2830
3447
  TStawkaPodatku = z.enum(["23", "22", "8", "7", "5", "4", "3", "0 KR", "0 WDT", "0 EX", "zw", "oo", "np I", "np II"]);
2831
3448
  TGTU = z.enum(["GTU_01", "GTU_02", "GTU_03", "GTU_04", "GTU_05", "GTU_06", "GTU_07", "GTU_08", "GTU_09", "GTU_10", "GTU_11", "GTU_12", "GTU_13"]);
@@ -2840,7 +3457,7 @@ var init_fa3 = __esm({
2840
3457
  "RachunekWlasnyBanku": TRachunekWlasnyBanku.optional(),
2841
3458
  "NazwaBanku": TZnakowy.optional(),
2842
3459
  "OpisRachunku": TZnakowy.optional()
2843
- });
3460
+ }).strict();
2844
3461
  TDataU = z.string();
2845
3462
  TRodzajTransportu = z.enum(["1", "2", "3", "4", "5", "7", "8"]);
2846
3463
  TLadunek = z.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]);
@@ -2861,13 +3478,13 @@ var init_fa3 = __esm({
2861
3478
  "AdresL1": TZnakowy512,
2862
3479
  "AdresL2": TZnakowy512.optional(),
2863
3480
  "GLN": TGLN.optional()
2864
- }).optional(),
3481
+ }).strict().optional(),
2865
3482
  "DaneKontaktowe": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2866
3483
  "Email": TAdresEmail.optional(),
2867
3484
  "Telefon": TNumerTelefonu.optional()
2868
- })).min(0).max(3)).optional(),
3485
+ }).strict()).min(0).max(3)).optional(),
2869
3486
  "StatusInfoPodatnika": TStatusInfoPodatnika.optional()
2870
- }),
3487
+ }).strict(),
2871
3488
  "Podmiot2": z.object({
2872
3489
  "NrEORI": TZnakowy.optional(),
2873
3490
  "DaneIdentyfikacyjne": TPodmiot2,
@@ -2876,12 +3493,12 @@ var init_fa3 = __esm({
2876
3493
  "DaneKontaktowe": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2877
3494
  "Email": TAdresEmail.optional(),
2878
3495
  "Telefon": TNumerTelefonu.optional()
2879
- })).min(0).max(3)).optional(),
3496
+ }).strict()).min(0).max(3)).optional(),
2880
3497
  "NrKlienta": TZnakowy.optional(),
2881
3498
  "IDNabywcy": z.string().min(1).max(32).optional(),
2882
3499
  "JST": z.enum(["1", "2"]),
2883
3500
  "GV": z.enum(["1", "2"])
2884
- }),
3501
+ }).strict(),
2885
3502
  "Podmiot3": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2886
3503
  "IDNabywcy": z.string().min(1).max(32).optional(),
2887
3504
  "NrEORI": TZnakowy.optional(),
@@ -2891,13 +3508,13 @@ var init_fa3 = __esm({
2891
3508
  "DaneKontaktowe": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2892
3509
  "Email": TAdresEmail.optional(),
2893
3510
  "Telefon": TNumerTelefonu.optional()
2894
- })).min(0).max(3)).optional(),
3511
+ }).strict()).min(0).max(3)).optional(),
2895
3512
  "Rola": TRolaPodmiotu3.optional(),
2896
3513
  "RolaInna": TWybor1.optional(),
2897
3514
  "OpisRoli": TZnakowy.optional(),
2898
3515
  "Udzial": TProcentowy.optional(),
2899
3516
  "NrKlienta": TZnakowy.optional()
2900
- })).min(0).max(100)).optional(),
3517
+ }).strict()).min(0).max(100)).optional(),
2901
3518
  "PodmiotUpowazniony": z.object({
2902
3519
  "NrEORI": TZnakowy.optional(),
2903
3520
  "DaneIdentyfikacyjne": TPodmiot1,
@@ -2906,9 +3523,9 @@ var init_fa3 = __esm({
2906
3523
  "DaneKontaktowe": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2907
3524
  "EmailPU": TAdresEmail.optional(),
2908
3525
  "TelefonPU": TNumerTelefonu.optional()
2909
- })).min(0).max(3)).optional(),
3526
+ }).strict()).min(0).max(3)).optional(),
2910
3527
  "RolaPU": TRolaPodmiotuUpowaznionego
2911
- }).optional(),
3528
+ }).strict().optional(),
2912
3529
  "Fa": z.object({
2913
3530
  "KodWaluty": TKodWaluty,
2914
3531
  "P_1": TDataT,
@@ -2919,7 +3536,7 @@ var init_fa3 = __esm({
2919
3536
  "OkresFa": z.object({
2920
3537
  "P_6_Od": TDataT,
2921
3538
  "P_6_Do": TDataT
2922
- }).optional(),
3539
+ }).strict().optional(),
2923
3540
  "P_13_1": TKwotowy.optional(),
2924
3541
  "P_14_1": TKwotowy.optional(),
2925
3542
  "P_14_1W": TKwotowy.optional(),
@@ -2949,7 +3566,7 @@ var init_fa3 = __esm({
2949
3566
  "P_17": TWybor1_2,
2950
3567
  "P_18": TWybor1_2,
2951
3568
  "P_18A": TWybor1_2,
2952
- "Zwolnienie": z.union([z.object({ "P_19": TWybor1, "P_19A": TZnakowy.optional(), "P_19B": TZnakowy.optional(), "P_19C": TZnakowy.optional() }), z.object({ "P_19N": TWybor1 })]),
3569
+ "Zwolnienie": z.union([z.object({ "P_19": TWybor1, "P_19A": TZnakowy.optional(), "P_19B": TZnakowy.optional(), "P_19C": TZnakowy.optional() }).strict(), z.object({ "P_19N": TWybor1 }).strict()]),
2953
3570
  "NoweSrodkiTransportu": z.union([z.object({ "P_22": TWybor1, "P_42_5": TWybor1_2, "NowySrodekTransportu": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2954
3571
  "P_22A": TDataT,
2955
3572
  "P_NrWierszaNST": TNaturalny,
@@ -2968,10 +3585,10 @@ var init_fa3 = __esm({
2968
3585
  "P_22C1": TZnakowy.optional(),
2969
3586
  "P_22D": TZnakowy.optional(),
2970
3587
  "P_22D1": TZnakowy.optional()
2971
- })).min(1).max(1e4)) }), z.object({ "P_22N": TWybor1 })]),
3588
+ }).strict()).min(1).max(1e4)) }).strict(), z.object({ "P_22N": TWybor1 }).strict()]),
2972
3589
  "P_23": TWybor1_2,
2973
- "PMarzy": z.union([z.object({ "P_PMarzy": TWybor1, "P_PMarzy_2": TWybor1.optional(), "P_PMarzy_3_1": TWybor1.optional(), "P_PMarzy_3_2": TWybor1.optional(), "P_PMarzy_3_3": TWybor1.optional() }), z.object({ "P_PMarzyN": TWybor1 })])
2974
- }),
3590
+ "PMarzy": z.union([z.object({ "P_PMarzy": TWybor1, "P_PMarzy_2": TWybor1.optional(), "P_PMarzy_3_1": TWybor1.optional(), "P_PMarzy_3_2": TWybor1.optional(), "P_PMarzy_3_3": TWybor1.optional() }).strict(), z.object({ "P_PMarzyN": TWybor1 }).strict()])
3591
+ }).strict(),
2975
3592
  "RodzajFaktury": TRodzajFaktury,
2976
3593
  "PrzyczynaKorekty": TZnakowy.optional(),
2977
3594
  "TypKorekty": TTypKorekty.optional(),
@@ -2981,30 +3598,30 @@ var init_fa3 = __esm({
2981
3598
  "NrKSeF": TWybor1.optional(),
2982
3599
  "NrKSeFFaKorygowanej": TNumerKSeF.optional(),
2983
3600
  "NrKSeFN": TWybor1.optional()
2984
- })).min(1).max(5e4)).optional(),
3601
+ }).strict()).min(1).max(5e4)).optional(),
2985
3602
  "OkresFaKorygowanej": TZnakowy.optional(),
2986
3603
  "NrFaKorygowany": TZnakowy.optional(),
2987
3604
  "Podmiot1K": z.object({
2988
3605
  "PrefiksPodatnika": TKodyKrajowUE.optional(),
2989
3606
  "DaneIdentyfikacyjne": TPodmiot1,
2990
3607
  "Adres": TAdres
2991
- }).optional(),
3608
+ }).strict().optional(),
2992
3609
  "Podmiot2K": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
2993
3610
  "DaneIdentyfikacyjne": TPodmiot2,
2994
3611
  "Adres": TAdres.optional(),
2995
3612
  "IDNabywcy": z.string().min(1).max(32).optional()
2996
- })).min(0).max(101)).optional(),
3613
+ }).strict()).min(0).max(101)).optional(),
2997
3614
  "P_15ZK": TKwotowy.optional(),
2998
3615
  "KursWalutyZK": TIlosci.optional(),
2999
3616
  "ZaliczkaCzesciowa": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3000
3617
  "P_6Z": TDataT,
3001
3618
  "P_15Z": TKwotowy,
3002
3619
  "KursWalutyZW": TIlosci.optional()
3003
- })).min(0).max(31)).optional(),
3620
+ }).strict()).min(0).max(31)).optional(),
3004
3621
  "FP": TWybor1.optional(),
3005
3622
  "TP": TWybor1.optional(),
3006
3623
  "DodatkowyOpis": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(TKluczWartosc).min(0).max(1e4)).optional(),
3007
- "FakturaZaliczkowa": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.union([z.object({ "NrKSeFZN": TWybor1, "NrFaZaliczkowej": TZnakowy }), z.object({ "NrKSeFFaZaliczkowej": TNumerKSeF })])).min(0).max(100)).optional(),
3624
+ "FakturaZaliczkowa": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.union([z.object({ "NrKSeFZN": TWybor1, "NrFaZaliczkowej": TZnakowy }).strict(), z.object({ "NrKSeFFaZaliczkowej": TNumerKSeF }).strict()])).min(0).max(100)).optional(),
3008
3625
  "ZwrotAkcyzy": TWybor1.optional(),
3009
3626
  "FaWiersz": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3010
3627
  "NrWierszaFa": TNaturalny,
@@ -3032,21 +3649,21 @@ var init_fa3 = __esm({
3032
3649
  "Procedura": TOznaczenieProcedury.optional(),
3033
3650
  "KursWaluty": TIlosci.optional(),
3034
3651
  "StanPrzed": TWybor1.optional()
3035
- })).min(0).max(1e4)).optional(),
3652
+ }).strict()).min(0).max(1e4)).optional(),
3036
3653
  "Rozliczenie": z.object({
3037
3654
  "Obciazenia": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3038
3655
  "Kwota": TKwotowy,
3039
3656
  "Powod": TZnakowy
3040
- })).min(0).max(100)).optional(),
3657
+ }).strict()).min(0).max(100)).optional(),
3041
3658
  "SumaObciazen": TKwotowy.optional(),
3042
3659
  "Odliczenia": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3043
3660
  "Kwota": TKwotowy,
3044
3661
  "Powod": TZnakowy
3045
- })).min(0).max(100)).optional(),
3662
+ }).strict()).min(0).max(100)).optional(),
3046
3663
  "SumaOdliczen": TKwotowy.optional(),
3047
3664
  "DoZaplaty": TKwotowy.optional(),
3048
3665
  "DoRozliczenia": TKwotowy.optional()
3049
- }).optional(),
3666
+ }).strict().optional(),
3050
3667
  "Platnosc": z.object({
3051
3668
  "Zaplacono": TWybor1.optional(),
3052
3669
  "DataZaplaty": TData.optional(),
@@ -3057,15 +3674,15 @@ var init_fa3 = __esm({
3057
3674
  "FormaPlatnosci": TFormaPlatnosci.optional(),
3058
3675
  "PlatnoscInna": TWybor1.optional(),
3059
3676
  "OpisPlatnosci": TZnakowy.optional()
3060
- })).min(1).max(100)).optional(),
3677
+ }).strict()).min(1).max(100)).optional(),
3061
3678
  "TerminPlatnosci": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3062
3679
  "Termin": TData.optional(),
3063
3680
  "TerminOpis": z.object({
3064
3681
  "Ilosc": z.coerce.number().int(),
3065
3682
  "Jednostka": TZnakowy50,
3066
3683
  "ZdarzeniePoczatkowe": TZnakowy
3067
- }).optional()
3068
- })).min(0).max(100)).optional(),
3684
+ }).strict().optional()
3685
+ }).strict()).min(0).max(100)).optional(),
3069
3686
  "FormaPlatnosci": TFormaPlatnosci.optional(),
3070
3687
  "PlatnoscInna": TWybor1.optional(),
3071
3688
  "OpisPlatnosci": TZnakowy.optional(),
@@ -3074,19 +3691,19 @@ var init_fa3 = __esm({
3074
3691
  "Skonto": z.object({
3075
3692
  "WarunkiSkonta": TZnakowy,
3076
3693
  "WysokoscSkonta": TZnakowy
3077
- }).optional(),
3694
+ }).strict().optional(),
3078
3695
  "LinkDoPlatnosci": z.string().min(1).max(512).regex(/^(https?):\/\/([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?(\/[^\s?#]*)?\?([^#\s]*&)?IPKSeF=[0-9]{3}[a-zA-Z0-9]{10}(&[^#\s]*)?(#.*)?$/).optional(),
3079
3696
  "IPKSeF": z.string().min(1).max(13).regex(/^[0-9]{3}[a-zA-Z0-9]{10}$/).optional()
3080
- }).optional(),
3697
+ }).strict().optional(),
3081
3698
  "WarunkiTransakcji": z.object({
3082
3699
  "Umowy": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3083
3700
  "DataUmowy": TDataU.optional(),
3084
3701
  "NrUmowy": TZnakowy.optional()
3085
- })).min(0).max(100)).optional(),
3702
+ }).strict()).min(0).max(100)).optional(),
3086
3703
  "Zamowienia": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3087
3704
  "DataZamowienia": TDataU.optional(),
3088
3705
  "NrZamowienia": TZnakowy.optional()
3089
- })).min(0).max(100)).optional(),
3706
+ }).strict()).min(0).max(100)).optional(),
3090
3707
  "NrPartiiTowaru": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(TZnakowy).min(0).max(1e3)).optional(),
3091
3708
  "WarunkiDostawy": TZnakowy.optional(),
3092
3709
  "KursUmowny": TIlosci.optional(),
@@ -3098,7 +3715,7 @@ var init_fa3 = __esm({
3098
3715
  "Przewoznik": z.object({
3099
3716
  "DaneIdentyfikacyjne": TPodmiot2,
3100
3717
  "AdresPrzewoznika": TAdres
3101
- }).optional(),
3718
+ }).strict().optional(),
3102
3719
  "NrZleceniaTransportu": TZnakowy.optional(),
3103
3720
  "OpisLadunku": TLadunek.optional(),
3104
3721
  "LadunekInny": TWybor1.optional(),
@@ -3109,9 +3726,9 @@ var init_fa3 = __esm({
3109
3726
  "WysylkaZ": TAdres.optional(),
3110
3727
  "WysylkaPrzez": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(TAdres).min(0).max(20)).optional(),
3111
3728
  "WysylkaDo": TAdres.optional()
3112
- })).min(0).max(20)).optional(),
3729
+ }).strict()).min(0).max(20)).optional(),
3113
3730
  "PodmiotPosredniczacy": TWybor1.optional()
3114
- }).optional(),
3731
+ }).strict().optional(),
3115
3732
  "Zamowienie": z.object({
3116
3733
  "WartoscZamowienia": TKwotowy,
3117
3734
  "ZamowienieWiersz": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
@@ -3135,24 +3752,24 @@ var init_fa3 = __esm({
3135
3752
  "ProceduraZ": TOznaczenieProceduryZ.optional(),
3136
3753
  "KwotaAkcyzyZ": TKwotowy.optional(),
3137
3754
  "StanPrzedZ": TWybor1.optional()
3138
- })).min(1).max(1e4))
3139
- }).optional()
3140
- }),
3755
+ }).strict()).min(1).max(1e4))
3756
+ }).strict().optional()
3757
+ }).strict(),
3141
3758
  "Stopka": z.object({
3142
3759
  "Informacje": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3143
3760
  "StopkaFaktury": TTekstowy.optional()
3144
- })).min(0).max(3)).optional(),
3761
+ }).strict()).min(0).max(3)).optional(),
3145
3762
  "Rejestry": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.object({
3146
3763
  "PelnaNazwa": TZnakowy.optional(),
3147
3764
  "KRS": TNrKRS.optional(),
3148
3765
  "REGON": TNrREGON.optional(),
3149
3766
  "BDO": z.string().min(1).max(9).optional()
3150
- })).min(0).max(100)).optional()
3151
- }).optional(),
3767
+ }).strict()).min(0).max(100)).optional()
3768
+ }).strict().optional(),
3152
3769
  "Zalacznik": z.object({
3153
3770
  "BlokDanych": z.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z.array(z.any()).min(1).max(1e3))
3154
- }).optional()
3155
- });
3771
+ }).strict().optional()
3772
+ }).strict();
3156
3773
  }
3157
3774
  });
3158
3775
 
@@ -3170,18 +3787,18 @@ var init_fa2 = __esm({
3170
3787
  TDataCzas2 = z2.string();
3171
3788
  TZnakowy3 = z2.string().min(1).max(256);
3172
3789
  TNaglowek2 = z2.object({
3173
- "KodFormularza": z2.object({ "#text": TKodFormularza2, "@kodSystemowy": z2.literal("FA (2)"), "@wersjaSchemy": z2.literal("1-0E") }),
3790
+ "KodFormularza": z2.object({ "#text": TKodFormularza2, "@kodSystemowy": z2.literal("FA (2)"), "@wersjaSchemy": z2.literal("1-0E") }).strict(),
3174
3791
  "WariantFormularza": z2.literal("2"),
3175
3792
  "DataWytworzeniaFa": z2.string(),
3176
3793
  "SystemInfo": TZnakowy3.optional()
3177
- });
3794
+ }).strict();
3178
3795
  TKodyKrajowUE2 = z2.enum(["AT", "BE", "BG", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "EL", "HR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "XI"]);
3179
3796
  TNrNIP2 = z2.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
3180
3797
  TZnakowy5122 = z2.string().min(1).max(512);
3181
3798
  TPodmiot12 = z2.object({
3182
3799
  "NIP": TNrNIP2,
3183
3800
  "Nazwa": TZnakowy5122
3184
- });
3801
+ }).strict();
3185
3802
  TKodKraju2 = z2.enum(["AF", "AX", "AL", "DZ", "AD", "AO", "AI", "AQ", "AG", "AN", "SA", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BY", "BO", "BQ", "BA", "BW", "BR", "BN", "IO", "BG", "BF", "BI", "XC", "CL", "CN", "HR", "CW", "CY", "TD", "ME", "DK", "DM", "DO", "DJ", "EG", "EC", "ER", "EE", "ET", "FK", "FJ", "PH", "FI", "FR", "TF", "GA", "GM", "GH", "GI", "GR", "GD", "GL", "GE", "GU", "GG", "GY", "GF", "GP", "GT", "GN", "GQ", "GW", "HT", "ES", "HN", "HK", "IN", "ID", "IQ", "IR", "IE", "IS", "IL", "JM", "JP", "YE", "JE", "JO", "KY", "KH", "CM", "CA", "QA", "KZ", "KE", "KG", "KI", "CO", "KM", "CG", "CD", "KP", "XK", "CR", "CU", "KW", "LA", "LS", "LB", "LR", "LY", "LI", "LT", "LV", "LU", "MK", "MG", "YT", "MO", "MW", "MV", "MY", "ML", "MT", "MP", "MA", "MQ", "MR", "MU", "MX", "XL", "FM", "UM", "MD", "MC", "MN", "MS", "MZ", "MM", "NA", "NR", "NP", "NL", "DE", "NE", "NG", "NI", "NU", "NF", "NO", "NC", "NZ", "PS", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PN", "PF", "PL", "GS", "PT", "PR", "CF", "CZ", "KR", "ZA", "RE", "RU", "RO", "RW", "EH", "BL", "KN", "LC", "MF", "VC", "SV", "WS", "AS", "SM", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SO", "LK", "PM", "US", "SZ", "SD", "SS", "SR", "SJ", "SH", "SY", "CH", "SE", "TJ", "TH", "TW", "TZ", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TV", "UG", "UA", "UY", "UZ", "VU", "WF", "VA", "HU", "VE", "GB", "VN", "IT", "TL", "CI", "BV", "CX", "IM", "SX", "CK", "VI", "VG", "HM", "CC", "MH", "FO", "SB", "ST", "TC", "ZM", "CV", "ZW", "AE", "XI"]);
3186
3803
  TGLN2 = z2.string().min(1).max(13);
3187
3804
  TAdres2 = z2.object({
@@ -3189,7 +3806,7 @@ var init_fa2 = __esm({
3189
3806
  "AdresL1": TZnakowy5122,
3190
3807
  "AdresL2": TZnakowy5122.optional(),
3191
3808
  "GLN": TGLN2.optional()
3192
- });
3809
+ }).strict();
3193
3810
  TAdresEmail2 = z2.string().min(3).max(255).regex(/^(.)+@(.)+$/);
3194
3811
  TNumerTelefonu2 = z2.string().min(1).max(16);
3195
3812
  TStatusInfoPodatnika2 = z2.enum(["1", "2", "3", "4"]);
@@ -3204,7 +3821,7 @@ var init_fa2 = __esm({
3204
3821
  "NrID": z2.string().min(1).max(50).regex(/^[a-zA-Z0-9]{1,50}$/).optional(),
3205
3822
  "BrakID": TWybor12.optional(),
3206
3823
  "Nazwa": TZnakowy5122.optional()
3207
- });
3824
+ }).strict();
3208
3825
  TZnakowy502 = z2.string().min(1).max(50);
3209
3826
  TZnakowy202 = z2.string().min(1).max(20);
3210
3827
  TNIPIdWew2 = z2.string().min(1).max(20).regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}-\d{5}$/);
@@ -3217,7 +3834,7 @@ var init_fa2 = __esm({
3217
3834
  "NrID": z2.string().min(1).max(50).regex(/^[a-zA-Z0-9]{1,50}$/).optional(),
3218
3835
  "BrakID": TWybor12.optional(),
3219
3836
  "Nazwa": TZnakowy5122.optional()
3220
- });
3837
+ }).strict();
3221
3838
  TRolaPodmiotu32 = z2.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]);
3222
3839
  TProcentowy2 = z2.coerce.number().min(0).max(100);
3223
3840
  TRolaPodmiotuUpowaznionego2 = z2.enum(["1", "2", "3"]);
@@ -3235,7 +3852,7 @@ var init_fa2 = __esm({
3235
3852
  "NrWiersza": TNaturalny2.optional(),
3236
3853
  "Klucz": TZnakowy3,
3237
3854
  "Wartosc": TZnakowy3
3238
- });
3855
+ }).strict();
3239
3856
  TKwotowy22 = z2.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
3240
3857
  TStawkaPodatku2 = z2.enum(["23", "22", "8", "7", "5", "4", "3", "0", "zw", "oo", "np"]);
3241
3858
  TGTU2 = z2.enum(["GTU_01", "GTU_02", "GTU_03", "GTU_04", "GTU_05", "GTU_06", "GTU_07", "GTU_08", "GTU_09", "GTU_10", "GTU_11", "GTU_12", "GTU_13"]);
@@ -3250,7 +3867,7 @@ var init_fa2 = __esm({
3250
3867
  "RachunekWlasnyBanku": TRachunekWlasnyBanku2.optional(),
3251
3868
  "NazwaBanku": TZnakowy3.optional(),
3252
3869
  "OpisRachunku": TZnakowy3.optional()
3253
- });
3870
+ }).strict();
3254
3871
  TRodzajTransportu2 = z2.enum(["1", "2", "3", "4", "5", "7", "8"]);
3255
3872
  TLadunek2 = z2.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]);
3256
3873
  TOznaczenieProceduryZ2 = z2.enum(["WSTO_EE", "IED", "TT_D", "B_SPV", "B_SPV_DOSTAWA", "B_MPV_PROWIZJA"]);
@@ -3269,13 +3886,13 @@ var init_fa2 = __esm({
3269
3886
  "AdresL1": TZnakowy5122,
3270
3887
  "AdresL2": TZnakowy5122.optional(),
3271
3888
  "GLN": TGLN2.optional()
3272
- }).optional(),
3889
+ }).strict().optional(),
3273
3890
  "DaneKontaktowe": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3274
3891
  "Email": TAdresEmail2.optional(),
3275
3892
  "Telefon": TNumerTelefonu2.optional()
3276
- })).min(0).max(3)).optional(),
3893
+ }).strict()).min(0).max(3)).optional(),
3277
3894
  "StatusInfoPodatnika": TStatusInfoPodatnika2.optional()
3278
- }),
3895
+ }).strict(),
3279
3896
  "Podmiot2": z2.object({
3280
3897
  "NrEORI": TZnakowy3.optional(),
3281
3898
  "DaneIdentyfikacyjne": TPodmiot22,
@@ -3284,10 +3901,10 @@ var init_fa2 = __esm({
3284
3901
  "DaneKontaktowe": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3285
3902
  "Email": TAdresEmail2.optional(),
3286
3903
  "Telefon": TNumerTelefonu2.optional()
3287
- })).min(0).max(3)).optional(),
3904
+ }).strict()).min(0).max(3)).optional(),
3288
3905
  "NrKlienta": TZnakowy3.optional(),
3289
3906
  "IDNabywcy": z2.string().min(1).max(32).optional()
3290
- }),
3907
+ }).strict(),
3291
3908
  "Podmiot3": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3292
3909
  "IDNabywcy": z2.string().min(1).max(32).optional(),
3293
3910
  "NrEORI": TZnakowy3.optional(),
@@ -3297,13 +3914,13 @@ var init_fa2 = __esm({
3297
3914
  "DaneKontaktowe": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3298
3915
  "Email": TAdresEmail2.optional(),
3299
3916
  "Telefon": TNumerTelefonu2.optional()
3300
- })).min(0).max(3)).optional(),
3917
+ }).strict()).min(0).max(3)).optional(),
3301
3918
  "Rola": TRolaPodmiotu32.optional(),
3302
3919
  "RolaInna": TWybor12.optional(),
3303
3920
  "OpisRoli": TZnakowy3.optional(),
3304
3921
  "Udzial": TProcentowy2.optional(),
3305
3922
  "NrKlienta": TZnakowy3.optional()
3306
- })).min(0).max(100)).optional(),
3923
+ }).strict()).min(0).max(100)).optional(),
3307
3924
  "PodmiotUpowazniony": z2.object({
3308
3925
  "NrEORI": TZnakowy3.optional(),
3309
3926
  "DaneIdentyfikacyjne": TPodmiot12,
@@ -3312,9 +3929,9 @@ var init_fa2 = __esm({
3312
3929
  "DaneKontaktowe": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3313
3930
  "EmailPU": TAdresEmail2.optional(),
3314
3931
  "TelefonPU": TNumerTelefonu2.optional()
3315
- })).min(0).max(3)).optional(),
3932
+ }).strict()).min(0).max(3)).optional(),
3316
3933
  "RolaPU": TRolaPodmiotuUpowaznionego2
3317
- }).optional(),
3934
+ }).strict().optional(),
3318
3935
  "Fa": z2.object({
3319
3936
  "KodWaluty": TKodWaluty2,
3320
3937
  "P_1": TDataT2,
@@ -3325,7 +3942,7 @@ var init_fa2 = __esm({
3325
3942
  "OkresFa": z2.object({
3326
3943
  "P_6_Od": TDataT2,
3327
3944
  "P_6_Do": TDataT2
3328
- }).optional(),
3945
+ }).strict().optional(),
3329
3946
  "P_13_1": TKwotowy3.optional(),
3330
3947
  "P_14_1": TKwotowy3.optional(),
3331
3948
  "P_14_1W": TKwotowy3.optional(),
@@ -3355,7 +3972,7 @@ var init_fa2 = __esm({
3355
3972
  "P_17": TWybor1_22,
3356
3973
  "P_18": TWybor1_22,
3357
3974
  "P_18A": TWybor1_22,
3358
- "Zwolnienie": z2.union([z2.object({ "P_19": TWybor12, "P_19A": TZnakowy3.optional(), "P_19B": TZnakowy3.optional(), "P_19C": TZnakowy3.optional() }), z2.object({ "P_19N": TWybor12 })]),
3975
+ "Zwolnienie": z2.union([z2.object({ "P_19": TWybor12, "P_19A": TZnakowy3.optional(), "P_19B": TZnakowy3.optional(), "P_19C": TZnakowy3.optional() }).strict(), z2.object({ "P_19N": TWybor12 }).strict()]),
3359
3976
  "NoweSrodkiTransportu": z2.union([z2.object({ "P_22": TWybor12, "P_42_5": TWybor1_22, "NowySrodekTransportu": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3360
3977
  "P_22A": TDataT2,
3361
3978
  "P_NrWierszaNST": TNaturalny2,
@@ -3374,10 +3991,10 @@ var init_fa2 = __esm({
3374
3991
  "P_22C1": TZnakowy3.optional(),
3375
3992
  "P_22D": TZnakowy3.optional(),
3376
3993
  "P_22D1": TZnakowy3.optional()
3377
- })).min(1).max(1e4)) }), z2.object({ "P_22N": TWybor12 })]),
3994
+ }).strict()).min(1).max(1e4)) }).strict(), z2.object({ "P_22N": TWybor12 }).strict()]),
3378
3995
  "P_23": TWybor1_22,
3379
- "PMarzy": z2.union([z2.object({ "P_PMarzy": TWybor12, "P_PMarzy_2": TWybor12.optional(), "P_PMarzy_3_1": TWybor12.optional(), "P_PMarzy_3_2": TWybor12.optional(), "P_PMarzy_3_3": TWybor12.optional() }), z2.object({ "P_PMarzyN": TWybor12 })])
3380
- }),
3996
+ "PMarzy": z2.union([z2.object({ "P_PMarzy": TWybor12, "P_PMarzy_2": TWybor12.optional(), "P_PMarzy_3_1": TWybor12.optional(), "P_PMarzy_3_2": TWybor12.optional(), "P_PMarzy_3_3": TWybor12.optional() }).strict(), z2.object({ "P_PMarzyN": TWybor12 }).strict()])
3997
+ }).strict(),
3381
3998
  "RodzajFaktury": TRodzajFaktury2,
3382
3999
  "PrzyczynaKorekty": TZnakowy3.optional(),
3383
4000
  "TypKorekty": TTypKorekty2.optional(),
@@ -3387,30 +4004,30 @@ var init_fa2 = __esm({
3387
4004
  "NrKSeF": TWybor12.optional(),
3388
4005
  "NrKSeFFaKorygowanej": TNumerKSeF2.optional(),
3389
4006
  "NrKSeFN": TWybor12.optional()
3390
- })).min(1)).optional(),
4007
+ }).strict()).min(1)).optional(),
3391
4008
  "OkresFaKorygowanej": TZnakowy3.optional(),
3392
4009
  "NrFaKorygowany": TZnakowy3.optional(),
3393
4010
  "Podmiot1K": z2.object({
3394
4011
  "PrefiksPodatnika": TKodyKrajowUE2.optional(),
3395
4012
  "DaneIdentyfikacyjne": TPodmiot12,
3396
4013
  "Adres": TAdres2
3397
- }).optional(),
4014
+ }).strict().optional(),
3398
4015
  "Podmiot2K": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3399
4016
  "DaneIdentyfikacyjne": TPodmiot22,
3400
4017
  "Adres": TAdres2.optional(),
3401
4018
  "IDNabywcy": z2.string().min(1).max(32).optional()
3402
- })).min(0).max(101)).optional(),
4019
+ }).strict()).min(0).max(101)).optional(),
3403
4020
  "P_15ZK": TKwotowy3.optional(),
3404
4021
  "KursWalutyZK": TIlosci2.optional(),
3405
4022
  "ZaliczkaCzesciowa": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3406
4023
  "P_6Z": TDataT2,
3407
4024
  "P_15Z": TKwotowy3,
3408
4025
  "KursWalutyZW": TIlosci2.optional()
3409
- })).min(0).max(31)).optional(),
4026
+ }).strict()).min(0).max(31)).optional(),
3410
4027
  "FP": TWybor12.optional(),
3411
4028
  "TP": TWybor12.optional(),
3412
4029
  "DodatkowyOpis": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(TKluczWartosc2).min(0).max(1e4)).optional(),
3413
- "FakturaZaliczkowa": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.union([z2.object({ "NrKSeFZN": TWybor12, "NrFaZaliczkowej": TZnakowy3 }), z2.object({ "NrKSeFFaZaliczkowej": TNumerKSeF2 })])).min(0).max(100)).optional(),
4030
+ "FakturaZaliczkowa": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.union([z2.object({ "NrKSeFZN": TWybor12, "NrFaZaliczkowej": TZnakowy3 }).strict(), z2.object({ "NrKSeFFaZaliczkowej": TNumerKSeF2 }).strict()])).min(0).max(100)).optional(),
3414
4031
  "ZwrotAkcyzy": TWybor12.optional(),
3415
4032
  "FaWiersz": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3416
4033
  "NrWierszaFa": TNaturalny2,
@@ -3438,21 +4055,21 @@ var init_fa2 = __esm({
3438
4055
  "Procedura": TOznaczenieProcedury2.optional(),
3439
4056
  "KursWaluty": TIlosci2.optional(),
3440
4057
  "StanPrzed": TWybor12.optional()
3441
- })).min(0).max(1e4)).optional(),
4058
+ }).strict()).min(0).max(1e4)).optional(),
3442
4059
  "Rozliczenie": z2.object({
3443
4060
  "Obciazenia": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3444
4061
  "Kwota": TKwotowy3,
3445
4062
  "Powod": TZnakowy3
3446
- })).min(0).max(100)).optional(),
4063
+ }).strict()).min(0).max(100)).optional(),
3447
4064
  "SumaObciazen": TKwotowy3.optional(),
3448
4065
  "Odliczenia": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3449
4066
  "Kwota": TKwotowy3,
3450
4067
  "Powod": TZnakowy3
3451
- })).min(0).max(100)).optional(),
4068
+ }).strict()).min(0).max(100)).optional(),
3452
4069
  "SumaOdliczen": TKwotowy3.optional(),
3453
4070
  "DoZaplaty": TKwotowy3.optional(),
3454
4071
  "DoRozliczenia": TKwotowy3.optional()
3455
- }).optional(),
4072
+ }).strict().optional(),
3456
4073
  "Platnosc": z2.object({
3457
4074
  "Zaplacono": TWybor12.optional(),
3458
4075
  "DataZaplaty": TData2.optional(),
@@ -3460,11 +4077,11 @@ var init_fa2 = __esm({
3460
4077
  "ZaplataCzesciowa": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3461
4078
  "KwotaZaplatyCzesciowej": TKwotowy3,
3462
4079
  "DataZaplatyCzesciowej": TData2
3463
- })).min(1).max(100)).optional(),
4080
+ }).strict()).min(1).max(100)).optional(),
3464
4081
  "TerminPlatnosci": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3465
4082
  "Termin": TData2,
3466
4083
  "TerminOpis": TZnakowy3.optional()
3467
- })).min(0).max(100)).optional(),
4084
+ }).strict()).min(0).max(100)).optional(),
3468
4085
  "FormaPlatnosci": TFormaPlatnosci2.optional(),
3469
4086
  "PlatnoscInna": TWybor12.optional(),
3470
4087
  "OpisPlatnosci": TZnakowy3.optional(),
@@ -3473,17 +4090,17 @@ var init_fa2 = __esm({
3473
4090
  "Skonto": z2.object({
3474
4091
  "WarunkiSkonta": TZnakowy3,
3475
4092
  "WysokoscSkonta": TZnakowy3
3476
- }).optional()
3477
- }).optional(),
4093
+ }).strict().optional()
4094
+ }).strict().optional(),
3478
4095
  "WarunkiTransakcji": z2.object({
3479
4096
  "Umowy": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3480
4097
  "DataUmowy": TData2.optional(),
3481
4098
  "NrUmowy": TZnakowy3.optional()
3482
- })).min(0).max(100)).optional(),
4099
+ }).strict()).min(0).max(100)).optional(),
3483
4100
  "Zamowienia": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3484
4101
  "DataZamowienia": TData2.optional(),
3485
4102
  "NrZamowienia": TZnakowy3.optional()
3486
- })).min(0).max(100)).optional(),
4103
+ }).strict()).min(0).max(100)).optional(),
3487
4104
  "NrPartiiTowaru": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(TZnakowy3).min(0).max(1e3)).optional(),
3488
4105
  "WarunkiDostawy": TZnakowy3.optional(),
3489
4106
  "KursUmowny": TIlosci2.optional(),
@@ -3495,7 +4112,7 @@ var init_fa2 = __esm({
3495
4112
  "Przewoznik": z2.object({
3496
4113
  "DaneIdentyfikacyjne": TPodmiot22,
3497
4114
  "AdresPrzewoznika": TAdres2
3498
- }).optional(),
4115
+ }).strict().optional(),
3499
4116
  "NrZleceniaTransportu": TZnakowy3.optional(),
3500
4117
  "OpisLadunku": TLadunek2.optional(),
3501
4118
  "LadunekInny": TWybor12.optional(),
@@ -3506,9 +4123,9 @@ var init_fa2 = __esm({
3506
4123
  "WysylkaZ": TAdres2.optional(),
3507
4124
  "WysylkaPrzez": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(TAdres2).min(0).max(20)).optional(),
3508
4125
  "WysylkaDo": TAdres2.optional()
3509
- })).min(0).max(20)).optional(),
4126
+ }).strict()).min(0).max(20)).optional(),
3510
4127
  "PodmiotPosredniczacy": TWybor12.optional()
3511
- }).optional(),
4128
+ }).strict().optional(),
3512
4129
  "Zamowienie": z2.object({
3513
4130
  "WartoscZamowienia": TKwotowy3,
3514
4131
  "ZamowienieWiersz": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
@@ -3532,21 +4149,21 @@ var init_fa2 = __esm({
3532
4149
  "ProceduraZ": TOznaczenieProceduryZ2.optional(),
3533
4150
  "KwotaAkcyzyZ": TKwotowy3.optional(),
3534
4151
  "StanPrzedZ": TWybor12.optional()
3535
- })).min(1).max(1e4))
3536
- }).optional()
3537
- }),
4152
+ }).strict()).min(1).max(1e4))
4153
+ }).strict().optional()
4154
+ }).strict(),
3538
4155
  "Stopka": z2.object({
3539
4156
  "Informacje": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3540
4157
  "StopkaFaktury": TTekstowy2.optional()
3541
- })).min(0).max(3)).optional(),
4158
+ }).strict()).min(0).max(3)).optional(),
3542
4159
  "Rejestry": z2.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z2.array(z2.object({
3543
4160
  "PelnaNazwa": TZnakowy3.optional(),
3544
4161
  "KRS": TNrKRS2.optional(),
3545
4162
  "REGON": TNrREGON2.optional(),
3546
4163
  "BDO": z2.string().min(1).max(9).optional()
3547
- })).min(0).max(100)).optional()
3548
- }).optional()
3549
- });
4164
+ }).strict()).min(0).max(100)).optional()
4165
+ }).strict().optional()
4166
+ }).strict();
3550
4167
  }
3551
4168
  });
3552
4169
 
@@ -3564,17 +4181,17 @@ var init_rr1_v11e = __esm({
3564
4181
  TDataCzas3 = z3.string();
3565
4182
  TZnakowy4 = z3.string().min(1).max(256);
3566
4183
  TNaglowek3 = z3.object({
3567
- "KodFormularza": z3.object({ "#text": TKodFormularza3, "@kodSystemowy": z3.literal("FA_RR (1)"), "@wersjaSchemy": z3.literal("1-1E") }),
4184
+ "KodFormularza": z3.object({ "#text": TKodFormularza3, "@kodSystemowy": z3.literal("FA_RR (1)"), "@wersjaSchemy": z3.literal("1-1E") }).strict(),
3568
4185
  "WariantFormularza": z3.literal("1"),
3569
4186
  "DataWytworzeniaFa": z3.string(),
3570
4187
  "SystemInfo": TZnakowy4.optional()
3571
- });
4188
+ }).strict();
3572
4189
  TNrNIP3 = z3.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
3573
4190
  TZnakowy5123 = z3.string().min(1).max(512);
3574
4191
  TPodmiot13 = z3.object({
3575
4192
  "NIP": TNrNIP3,
3576
4193
  "Nazwa": TZnakowy5123
3577
- });
4194
+ }).strict();
3578
4195
  TKodKraju3 = z3.enum(["AF", "AX", "AL", "DZ", "AD", "AO", "AI", "AQ", "AG", "AN", "SA", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BY", "BO", "BQ", "BA", "BW", "BR", "BN", "IO", "BG", "BF", "BI", "XC", "CL", "CN", "HR", "CW", "CY", "TD", "ME", "DK", "DM", "DO", "DJ", "EG", "EC", "ER", "EE", "ET", "FK", "FJ", "PH", "FI", "FR", "TF", "GA", "GM", "GH", "GI", "GR", "GD", "GL", "GE", "GU", "GG", "GY", "GF", "GP", "GT", "GN", "GQ", "GW", "HT", "ES", "HN", "HK", "IN", "ID", "IQ", "IR", "IE", "IS", "IL", "JM", "JP", "YE", "JE", "JO", "KY", "KH", "CM", "CA", "QA", "KZ", "KE", "KG", "KI", "CO", "KM", "CG", "CD", "KP", "XK", "CR", "CU", "KW", "LA", "LS", "LB", "LR", "LY", "LI", "LT", "LV", "LU", "MK", "MG", "YT", "MO", "MW", "MV", "MY", "ML", "MT", "MP", "MA", "MQ", "MR", "MU", "MX", "XL", "FM", "UM", "MD", "MC", "MN", "MS", "MZ", "MM", "NA", "NR", "NP", "NL", "DE", "NE", "NG", "NI", "NU", "NF", "NO", "NC", "NZ", "PS", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PN", "PF", "PL", "GS", "PT", "PR", "CF", "CZ", "KR", "ZA", "RE", "RU", "RO", "RW", "EH", "BL", "KN", "LC", "MF", "VC", "SV", "WS", "AS", "SM", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SO", "LK", "PM", "US", "SZ", "SD", "SS", "SR", "SJ", "SH", "SY", "CH", "SE", "TJ", "TH", "TW", "TZ", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TV", "UG", "UA", "UY", "UZ", "VU", "WF", "VA", "HU", "VE", "GB", "VN", "IT", "TL", "CI", "BV", "CX", "IM", "SX", "CK", "VI", "VG", "HM", "CC", "MH", "FO", "SB", "ST", "TC", "ZM", "CV", "ZW", "AE", "XI"]);
3579
4196
  TGLN3 = z3.string().min(1).max(13);
3580
4197
  TAdres3 = z3.object({
@@ -3582,7 +4199,7 @@ var init_rr1_v11e = __esm({
3582
4199
  "AdresL1": TZnakowy5123,
3583
4200
  "AdresL2": TZnakowy5123.optional(),
3584
4201
  "GLN": TGLN3.optional()
3585
- });
4202
+ }).strict();
3586
4203
  TAdresEmail3 = z3.string().min(3).max(255).regex(/^(.)+@(.)+$/);
3587
4204
  TNumerTelefonu3 = z3.string().min(1).max(16);
3588
4205
  TStatusInfoPodatnika3 = z3.enum(["1", "2", "3", "4"]);
@@ -3594,7 +4211,7 @@ var init_rr1_v11e = __esm({
3594
4211
  "IDWew": TNIPIdWew3.optional(),
3595
4212
  "BrakID": TWybor13.optional(),
3596
4213
  "Nazwa": TZnakowy5123
3597
- });
4214
+ }).strict();
3598
4215
  TRolaPodmiotu33 = z3.enum(["1", "2", "3", "5", "6", "7", "8", "9", "10", "11"]);
3599
4216
  TKodWaluty3 = z3.enum(["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GGP", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "IMP", "INR", "IQD", "IRR", "ISK", "JEP", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XCG", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XUA", "XXX", "YER", "ZAR", "ZMW", "ZWL"]);
3600
4217
  TData3 = z3.string();
@@ -3608,7 +4225,7 @@ var init_rr1_v11e = __esm({
3608
4225
  "NrWiersza": TNaturalny3.optional(),
3609
4226
  "Klucz": TZnakowy4,
3610
4227
  "Wartosc": TZnakowy4
3611
- });
4228
+ }).strict();
3612
4229
  TZnakowy503 = z3.string().min(1).max(50);
3613
4230
  TIlosci3 = z3.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,6})?$/);
3614
4231
  TKwotowy23 = z3.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
@@ -3622,7 +4239,7 @@ var init_rr1_v11e = __esm({
3622
4239
  "SWIFT": SWIFT_Type3.optional(),
3623
4240
  "NazwaBanku": TZnakowy4.optional(),
3624
4241
  "OpisRachunku": TZnakowy4.optional()
3625
- });
4242
+ }).strict();
3626
4243
  TTekstowy3 = z3.string().min(1).max(3500);
3627
4244
  TNrKRS3 = z3.string().regex(/^\d{10}$/);
3628
4245
  TNrREGON3 = z3.union([z3.string().regex(/^\d{9}$/), z3.string().regex(/^\d{14}$/)]);
@@ -3635,9 +4252,9 @@ var init_rr1_v11e = __esm({
3635
4252
  "DaneKontaktowe": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3636
4253
  "Email": TAdresEmail3.optional(),
3637
4254
  "Telefon": TNumerTelefonu3.optional()
3638
- })).min(0).max(3)).optional(),
4255
+ }).strict()).min(0).max(3)).optional(),
3639
4256
  "NrKontrahenta": TZnakowy4.optional()
3640
- }),
4257
+ }).strict(),
3641
4258
  "Podmiot2": z3.object({
3642
4259
  "DaneIdentyfikacyjne": TPodmiot13,
3643
4260
  "Adres": TAdres3,
@@ -3645,9 +4262,9 @@ var init_rr1_v11e = __esm({
3645
4262
  "DaneKontaktowe": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3646
4263
  "Email": TAdresEmail3.optional(),
3647
4264
  "Telefon": TNumerTelefonu3.optional()
3648
- })).min(0).max(3)).optional(),
4265
+ }).strict()).min(0).max(3)).optional(),
3649
4266
  "StatusInfoPodatnika": TStatusInfoPodatnika3.optional()
3650
- }),
4267
+ }).strict(),
3651
4268
  "Podmiot3": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3652
4269
  "DaneIdentyfikacyjne": TPodmiot33,
3653
4270
  "Adres": TAdres3.optional(),
@@ -3655,11 +4272,11 @@ var init_rr1_v11e = __esm({
3655
4272
  "DaneKontaktowe": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3656
4273
  "Email": TAdresEmail3.optional(),
3657
4274
  "Telefon": TNumerTelefonu3.optional()
3658
- })).min(0).max(3)).optional(),
4275
+ }).strict()).min(0).max(3)).optional(),
3659
4276
  "Rola": TRolaPodmiotu33.optional(),
3660
4277
  "RolaInna": TWybor13.optional(),
3661
4278
  "OpisRoli": TZnakowy4.optional()
3662
- })).min(0).max(100)).optional(),
4279
+ }).strict()).min(0).max(100)).optional(),
3663
4280
  "FakturaRR": z3.object({
3664
4281
  "KodWaluty": TKodWaluty3,
3665
4282
  "P_1M": TZnakowy4.optional(),
@@ -3682,20 +4299,20 @@ var init_rr1_v11e = __esm({
3682
4299
  "NrKSeF": TWybor13.optional(),
3683
4300
  "NrKSeFFaKorygowanej": TNumerKSeF3.optional(),
3684
4301
  "NrKSeFN": TWybor13.optional()
3685
- })).min(1).max(5e4)).optional(),
4302
+ }).strict()).min(1).max(5e4)).optional(),
3686
4303
  "NrFaKorygowany": TZnakowy4.optional(),
3687
4304
  "Podmiot1K": z3.object({
3688
4305
  "DaneIdentyfikacyjne": TPodmiot13,
3689
4306
  "Adres": TAdres3
3690
- }).optional(),
4307
+ }).strict().optional(),
3691
4308
  "Podmiot2K": z3.object({
3692
4309
  "DaneIdentyfikacyjne": TPodmiot13,
3693
4310
  "Adres": TAdres3
3694
- }).optional(),
4311
+ }).strict().optional(),
3695
4312
  "DokumentZaplaty": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3696
4313
  "NrDokumentu": TZnakowy4,
3697
4314
  "DataDokumentu": TData3.optional()
3698
- })).min(0).max(50)).optional(),
4315
+ }).strict()).min(0).max(50)).optional(),
3699
4316
  "DodatkowyOpis": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(TKluczWartosc3).min(0).max(1e4)).optional(),
3700
4317
  "FakturaRRWiersz": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3701
4318
  "NrWierszaFa": TNaturalny3,
@@ -3715,21 +4332,21 @@ var init_rr1_v11e = __esm({
3715
4332
  "P_11": TKwotowy4,
3716
4333
  "StanPrzed": TWybor13.optional(),
3717
4334
  "KursWaluty": TIlosci3.optional()
3718
- })).min(0).max(1e4)).optional(),
4335
+ }).strict()).min(0).max(1e4)).optional(),
3719
4336
  "Rozliczenie": z3.object({
3720
4337
  "Obciazenia": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3721
4338
  "Kwota": TKwotowy4,
3722
4339
  "Powod": TZnakowy4
3723
- })).min(0).max(100)).optional(),
4340
+ }).strict()).min(0).max(100)).optional(),
3724
4341
  "SumaObciazen": TKwotowy4.optional(),
3725
4342
  "Odliczenia": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3726
4343
  "Kwota": TKwotowy4,
3727
4344
  "Powod": TZnakowy4
3728
- })).min(0).max(100)).optional(),
4345
+ }).strict()).min(0).max(100)).optional(),
3729
4346
  "SumaOdliczen": TKwotowy4.optional(),
3730
4347
  "DoZaplaty": TKwotowy4.optional(),
3731
4348
  "DoRozliczenia": TKwotowy4.optional()
3732
- }).optional(),
4349
+ }).strict().optional(),
3733
4350
  "Platnosc": z3.object({
3734
4351
  "FormaPlatnosci": TFormaPlatnosci3.optional(),
3735
4352
  "PlatnoscInna": TWybor13.optional(),
@@ -3738,20 +4355,20 @@ var init_rr1_v11e = __esm({
3738
4355
  "RachunekBankowy2": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(TRachunekBankowy3).min(0).max(3)).optional(),
3739
4356
  "IPKSeF": z3.string().min(1).max(13).regex(/^[0-9]{3}[a-zA-Z0-9]{10}$/).optional(),
3740
4357
  "LinkDoPlatnosci": z3.string().min(1).max(512).regex(/^(https?):\/\/([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?(\/[^\s?#]*)?\?([^#\s]*&)?IPKSeF=[0-9]{3}[a-zA-Z0-9]{10}(&[^#\s]*)?(#.*)?$/).optional()
3741
- }).optional()
3742
- }),
4358
+ }).strict().optional()
4359
+ }).strict(),
3743
4360
  "Stopka": z3.object({
3744
4361
  "Informacje": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3745
4362
  "StopkaFaktury": TTekstowy3.optional()
3746
- })).min(0).max(3)).optional(),
4363
+ }).strict()).min(0).max(3)).optional(),
3747
4364
  "Rejestry": z3.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z3.array(z3.object({
3748
4365
  "PelnaNazwa": TZnakowy4.optional(),
3749
4366
  "KRS": TNrKRS3.optional(),
3750
4367
  "REGON": TNrREGON3.optional(),
3751
4368
  "BDO": z3.string().min(1).max(9).optional()
3752
- })).min(0).max(100)).optional()
3753
- }).optional()
3754
- });
4369
+ }).strict()).min(0).max(100)).optional()
4370
+ }).strict().optional()
4371
+ }).strict();
3755
4372
  }
3756
4373
  });
3757
4374
 
@@ -3769,17 +4386,17 @@ var init_rr1_v10e = __esm({
3769
4386
  TDataCzas4 = z4.string();
3770
4387
  TZnakowy5 = z4.string().min(1).max(256);
3771
4388
  TNaglowek4 = z4.object({
3772
- "KodFormularza": z4.object({ "#text": TKodFormularza4, "@kodSystemowy": z4.literal("FA_RR(1)"), "@wersjaSchemy": z4.literal("1-0E") }),
4389
+ "KodFormularza": z4.object({ "#text": TKodFormularza4, "@kodSystemowy": z4.literal("FA_RR(1)"), "@wersjaSchemy": z4.literal("1-0E") }).strict(),
3773
4390
  "WariantFormularza": z4.literal("1"),
3774
4391
  "DataWytworzeniaFa": z4.string(),
3775
4392
  "SystemInfo": TZnakowy5.optional()
3776
- });
4393
+ }).strict();
3777
4394
  TNrNIP4 = z4.string().regex(/^[1-9]((\d[1-9])|([1-9]\d))\d{7}$/);
3778
4395
  TZnakowy5124 = z4.string().min(1).max(512);
3779
4396
  TPodmiot14 = z4.object({
3780
4397
  "NIP": TNrNIP4,
3781
4398
  "Nazwa": TZnakowy5124
3782
- });
4399
+ }).strict();
3783
4400
  TKodKraju4 = z4.enum(["AF", "AX", "AL", "DZ", "AD", "AO", "AI", "AQ", "AG", "AN", "SA", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BY", "BO", "BQ", "BA", "BW", "BR", "BN", "IO", "BG", "BF", "BI", "XC", "CL", "CN", "HR", "CW", "CY", "TD", "ME", "DK", "DM", "DO", "DJ", "EG", "EC", "ER", "EE", "ET", "FK", "FJ", "PH", "FI", "FR", "TF", "GA", "GM", "GH", "GI", "GR", "GD", "GL", "GE", "GU", "GG", "GY", "GF", "GP", "GT", "GN", "GQ", "GW", "HT", "ES", "HN", "HK", "IN", "ID", "IQ", "IR", "IE", "IS", "IL", "JM", "JP", "YE", "JE", "JO", "KY", "KH", "CM", "CA", "QA", "KZ", "KE", "KG", "KI", "CO", "KM", "CG", "CD", "KP", "XK", "CR", "CU", "KW", "LA", "LS", "LB", "LR", "LY", "LI", "LT", "LV", "LU", "MK", "MG", "YT", "MO", "MW", "MV", "MY", "ML", "MT", "MP", "MA", "MQ", "MR", "MU", "MX", "XL", "FM", "UM", "MD", "MC", "MN", "MS", "MZ", "MM", "NA", "NR", "NP", "NL", "DE", "NE", "NG", "NI", "NU", "NF", "NO", "NC", "NZ", "PS", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PN", "PF", "PL", "GS", "PT", "PR", "CF", "CZ", "KR", "ZA", "RE", "RU", "RO", "RW", "EH", "BL", "KN", "LC", "MF", "VC", "SV", "WS", "AS", "SM", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SO", "LK", "PM", "US", "SZ", "SD", "SS", "SR", "SJ", "SH", "SY", "CH", "SE", "TJ", "TH", "TW", "TZ", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TV", "UG", "UA", "UY", "UZ", "VU", "WF", "VA", "HU", "VE", "GB", "VN", "IT", "TL", "CI", "BV", "CX", "IM", "SX", "CK", "VI", "VG", "HM", "CC", "MH", "FO", "SB", "ST", "TC", "ZM", "CV", "ZW", "AE", "XI"]);
3784
4401
  TGLN4 = z4.string().min(1).max(13);
3785
4402
  TAdres4 = z4.object({
@@ -3787,7 +4404,7 @@ var init_rr1_v10e = __esm({
3787
4404
  "AdresL1": TZnakowy5124,
3788
4405
  "AdresL2": TZnakowy5124.optional(),
3789
4406
  "GLN": TGLN4.optional()
3790
- });
4407
+ }).strict();
3791
4408
  TAdresEmail4 = z4.string().min(3).max(255).regex(/^(.)+@(.)+$/);
3792
4409
  TNumerTelefonu4 = z4.string().min(1).max(16);
3793
4410
  TStatusInfoPodatnika4 = z4.enum(["1", "2", "3", "4"]);
@@ -3799,7 +4416,7 @@ var init_rr1_v10e = __esm({
3799
4416
  "IDWew": TNIPIdWew4.optional(),
3800
4417
  "BrakID": TWybor14.optional(),
3801
4418
  "Nazwa": TZnakowy5124
3802
- });
4419
+ }).strict();
3803
4420
  TRolaPodmiotu34 = z4.enum(["1", "2", "3", "5", "6", "7", "8", "9", "10", "11"]);
3804
4421
  TKodWaluty4 = z4.enum(["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GGP", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "IMP", "INR", "IQD", "IRR", "ISK", "JEP", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XCG", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XUA", "XXX", "YER", "ZAR", "ZMW", "ZWL"]);
3805
4422
  TData4 = z4.string();
@@ -3813,7 +4430,7 @@ var init_rr1_v10e = __esm({
3813
4430
  "NrWiersza": TNaturalny4.optional(),
3814
4431
  "Klucz": TZnakowy5,
3815
4432
  "Wartosc": TZnakowy5
3816
- });
4433
+ }).strict();
3817
4434
  TZnakowy504 = z4.string().min(1).max(50);
3818
4435
  TIlosci4 = z4.string().regex(/^-?([1-9]\d{0,15}|0)(\.\d{1,6})?$/);
3819
4436
  TKwotowy24 = z4.string().regex(/^-?([1-9]\d{0,13}|0)(\.\d{1,8})?$/);
@@ -3827,7 +4444,7 @@ var init_rr1_v10e = __esm({
3827
4444
  "SWIFT": SWIFT_Type4.optional(),
3828
4445
  "NazwaBanku": TZnakowy5.optional(),
3829
4446
  "OpisRachunku": TZnakowy5.optional()
3830
- });
4447
+ }).strict();
3831
4448
  TTekstowy4 = z4.string().min(1).max(3500);
3832
4449
  TNrKRS4 = z4.string().regex(/^\d{10}$/);
3833
4450
  TNrREGON4 = z4.union([z4.string().regex(/^\d{9}$/), z4.string().regex(/^\d{14}$/)]);
@@ -3840,9 +4457,9 @@ var init_rr1_v10e = __esm({
3840
4457
  "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3841
4458
  "Email": TAdresEmail4.optional(),
3842
4459
  "Telefon": TNumerTelefonu4.optional()
3843
- })).min(0).max(3)).optional(),
4460
+ }).strict()).min(0).max(3)).optional(),
3844
4461
  "NrKontrahenta": TZnakowy5.optional()
3845
- }),
4462
+ }).strict(),
3846
4463
  "Podmiot2": z4.object({
3847
4464
  "DaneIdentyfikacyjne": TPodmiot14,
3848
4465
  "Adres": TAdres4,
@@ -3850,9 +4467,9 @@ var init_rr1_v10e = __esm({
3850
4467
  "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3851
4468
  "Email": TAdresEmail4.optional(),
3852
4469
  "Telefon": TNumerTelefonu4.optional()
3853
- })).min(0).max(3)).optional(),
4470
+ }).strict()).min(0).max(3)).optional(),
3854
4471
  "StatusInfoPodatnika": TStatusInfoPodatnika4.optional()
3855
- }),
4472
+ }).strict(),
3856
4473
  "Podmiot3": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3857
4474
  "DaneIdentyfikacyjne": TPodmiot34,
3858
4475
  "Adres": TAdres4.optional(),
@@ -3860,11 +4477,11 @@ var init_rr1_v10e = __esm({
3860
4477
  "DaneKontaktowe": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3861
4478
  "Email": TAdresEmail4.optional(),
3862
4479
  "Telefon": TNumerTelefonu4.optional()
3863
- })).min(0).max(3)).optional(),
4480
+ }).strict()).min(0).max(3)).optional(),
3864
4481
  "Rola": TRolaPodmiotu34.optional(),
3865
4482
  "RolaInna": TWybor14.optional(),
3866
4483
  "OpisRoli": TZnakowy5.optional()
3867
- })).min(0).max(100)).optional(),
4484
+ }).strict()).min(0).max(100)).optional(),
3868
4485
  "FakturaRR": z4.object({
3869
4486
  "KodWaluty": TKodWaluty4,
3870
4487
  "P_1M": TZnakowy5.optional(),
@@ -3887,20 +4504,20 @@ var init_rr1_v10e = __esm({
3887
4504
  "NrKSeF": TWybor14.optional(),
3888
4505
  "NrKSeFFaKorygowanej": TNumerKSeF4.optional(),
3889
4506
  "NrKSeFN": TWybor14.optional()
3890
- })).min(1).max(5e4)).optional(),
4507
+ }).strict()).min(1).max(5e4)).optional(),
3891
4508
  "NrFaKorygowany": TZnakowy5.optional(),
3892
4509
  "Podmiot1K": z4.object({
3893
4510
  "DaneIdentyfikacyjne": TPodmiot14,
3894
4511
  "Adres": TAdres4
3895
- }).optional(),
4512
+ }).strict().optional(),
3896
4513
  "Podmiot2K": z4.object({
3897
4514
  "DaneIdentyfikacyjne": TPodmiot14,
3898
4515
  "Adres": TAdres4
3899
- }).optional(),
4516
+ }).strict().optional(),
3900
4517
  "DokumentZaplaty": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3901
4518
  "NrDokumentu": TZnakowy5,
3902
4519
  "DataDokumentu": TData4.optional()
3903
- })).min(0).max(50)).optional(),
4520
+ }).strict()).min(0).max(50)).optional(),
3904
4521
  "DodatkowyOpis": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TKluczWartosc4).min(0).max(1e4)).optional(),
3905
4522
  "FakturaRRWiersz": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3906
4523
  "NrWierszaFa": TNaturalny4,
@@ -3920,21 +4537,21 @@ var init_rr1_v10e = __esm({
3920
4537
  "P_11": TKwotowy5,
3921
4538
  "StanPrzed": TWybor14.optional(),
3922
4539
  "KursWaluty": TIlosci4.optional()
3923
- })).min(0).max(1e4)).optional(),
4540
+ }).strict()).min(0).max(1e4)).optional(),
3924
4541
  "Rozliczenie": z4.object({
3925
4542
  "Obciazenia": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3926
4543
  "Kwota": TKwotowy5,
3927
4544
  "Powod": TZnakowy5
3928
- })).min(0).max(100)).optional(),
4545
+ }).strict()).min(0).max(100)).optional(),
3929
4546
  "SumaObciazen": TKwotowy5.optional(),
3930
4547
  "Odliczenia": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3931
4548
  "Kwota": TKwotowy5,
3932
4549
  "Powod": TZnakowy5
3933
- })).min(0).max(100)).optional(),
4550
+ }).strict()).min(0).max(100)).optional(),
3934
4551
  "SumaOdliczen": TKwotowy5.optional(),
3935
4552
  "DoZaplaty": TKwotowy5.optional(),
3936
4553
  "DoRozliczenia": TKwotowy5.optional()
3937
- }).optional(),
4554
+ }).strict().optional(),
3938
4555
  "Platnosc": z4.object({
3939
4556
  "FormaPlatnosci": TFormaPlatnosci4.optional(),
3940
4557
  "PlatnoscInna": TWybor14.optional(),
@@ -3943,20 +4560,20 @@ var init_rr1_v10e = __esm({
3943
4560
  "RachunekBankowy2": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(TRachunekBankowy4).min(0).max(3)).optional(),
3944
4561
  "IPKSeF": z4.string().min(1).max(13).regex(/^[0-9]{3}[a-zA-Z0-9]{10}$/).optional(),
3945
4562
  "LinkDoPlatnosci": z4.string().min(1).max(512).regex(/^(https?):\/\/([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?(\/[^\s?#]*)?\?([^#\s]*&)?IPKSeF=[0-9]{3}[a-zA-Z0-9]{10}(&[^#\s]*)?(#.*)?$/).optional()
3946
- }).optional()
3947
- }),
4563
+ }).strict().optional()
4564
+ }).strict(),
3948
4565
  "Stopka": z4.object({
3949
4566
  "Informacje": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3950
4567
  "StopkaFaktury": TTekstowy4.optional()
3951
- })).min(0).max(3)).optional(),
4568
+ }).strict()).min(0).max(3)).optional(),
3952
4569
  "Rejestry": z4.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z4.array(z4.object({
3953
4570
  "PelnaNazwa": TZnakowy5.optional(),
3954
4571
  "KRS": TNrKRS4.optional(),
3955
4572
  "REGON": TNrREGON4.optional(),
3956
4573
  "BDO": z4.string().min(1).max(9).optional()
3957
- })).min(0).max(100)).optional()
3958
- }).optional()
3959
- });
4574
+ }).strict()).min(0).max(100)).optional()
4575
+ }).strict().optional()
4576
+ }).strict();
3960
4577
  }
3961
4578
  });
3962
4579
 
@@ -4025,7 +4642,7 @@ var init_pef3 = __esm({
4025
4642
  "WithholdingTaxTotal": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(0)).optional(),
4026
4643
  "LegalMonetaryTotal": z5.any(),
4027
4644
  "InvoiceLine": z5.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z5.array(z5.any()).min(1))
4028
- });
4645
+ }).strict();
4029
4646
  PEF3Schema = InvoiceType;
4030
4647
  }
4031
4648
  });
@@ -4092,47 +4709,366 @@ var init_pef_kor3 = __esm({
4092
4709
  "TaxTotal": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(0)).optional(),
4093
4710
  "LegalMonetaryTotal": z6.any(),
4094
4711
  "CreditNoteLine": z6.preprocess((v) => Array.isArray(v) ? v : v == null ? [] : [v], z6.array(z6.any()).min(1))
4095
- });
4712
+ }).strict();
4096
4713
  PEF_KOR3Schema = CreditNoteType;
4097
4714
  }
4098
4715
  });
4099
4716
 
4100
- // src/builders/batch-file.ts
4101
- import * as crypto4 from "crypto";
4102
- function splitBuffer(data, maxPartSize) {
4103
- if (data.length <= maxPartSize) {
4104
- return [data];
4105
- }
4106
- const parts = [];
4107
- for (let offset = 0; offset < data.length; offset += maxPartSize) {
4108
- parts.push(data.subarray(offset, Math.min(offset + maxPartSize, data.length)));
4109
- }
4110
- return parts;
4111
- }
4112
- function sha256Base64(data) {
4113
- return crypto4.createHash("sha256").update(data).digest("base64");
4114
- }
4115
- var BATCH_MAX_PART_SIZE, BATCH_MAX_TOTAL_SIZE, BATCH_MAX_PARTS, BatchFileBuilder;
4116
- var init_batch_file = __esm({
4117
- "src/builders/batch-file.ts"() {
4717
+ // src/validation/schemas/index.ts
4718
+ var SCHEMA_TYPES, NAMESPACE_MAP;
4719
+ var init_schemas = __esm({
4720
+ "src/validation/schemas/index.ts"() {
4118
4721
  "use strict";
4119
- init_ksef_validation_error();
4120
- BATCH_MAX_PART_SIZE = 1e8;
4121
- BATCH_MAX_TOTAL_SIZE = 5e9;
4122
- BATCH_MAX_PARTS = 50;
4123
- BatchFileBuilder = class {
4124
- /**
4125
- * Build batch file metadata and encrypted parts from a raw ZIP.
4126
- *
4127
- * @param zipBytes - Unencrypted ZIP data
4128
- * @param encryptFn - AES-256-CBC encryption function (called per part)
4129
- * @param options - Optional configuration
4130
- */
4131
- static build(zipBytes, encryptFn, options) {
4132
- const maxPartSize = options?.maxPartSize ?? BATCH_MAX_PART_SIZE;
4133
- if (maxPartSize <= 0) {
4134
- throw new KSeFValidationError("maxPartSize must be a positive number");
4135
- }
4722
+ init_fa3();
4723
+ init_fa2();
4724
+ init_rr1_v11e();
4725
+ init_rr1_v10e();
4726
+ init_pef3();
4727
+ init_pef_kor3();
4728
+ SCHEMA_TYPES = ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
4729
+ NAMESPACE_MAP = {
4730
+ "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
4731
+ "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
4732
+ "http://crd.gov.pl/wzor/2026/03/06/14189/": "RR1_V11E",
4733
+ "http://crd.gov.pl/wzor/2026/02/17/14164/": "RR1_V10E",
4734
+ "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2": "PEF3",
4735
+ "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2": "PEF_KOR3"
4736
+ };
4737
+ }
4738
+ });
4739
+
4740
+ // src/validation/schema-registry.ts
4741
+ async function loadSchema(type) {
4742
+ const cached = schemaCache.get(type);
4743
+ if (cached) return cached;
4744
+ let mod;
4745
+ switch (type) {
4746
+ case "FA3":
4747
+ mod = await Promise.resolve().then(() => (init_fa3(), fa3_exports));
4748
+ break;
4749
+ case "FA2":
4750
+ mod = await Promise.resolve().then(() => (init_fa2(), fa2_exports));
4751
+ break;
4752
+ case "RR1_V11E":
4753
+ mod = await Promise.resolve().then(() => (init_rr1_v11e(), rr1_v11e_exports));
4754
+ break;
4755
+ case "RR1_V10E":
4756
+ mod = await Promise.resolve().then(() => (init_rr1_v10e(), rr1_v10e_exports));
4757
+ break;
4758
+ case "PEF3":
4759
+ mod = await Promise.resolve().then(() => (init_pef3(), pef3_exports));
4760
+ break;
4761
+ case "PEF_KOR3":
4762
+ mod = await Promise.resolve().then(() => (init_pef_kor3(), pef_kor3_exports));
4763
+ break;
4764
+ default:
4765
+ throw new Error(`Unknown schema type: ${type}`);
4766
+ }
4767
+ const exportName = `${type}Schema`;
4768
+ const schema = mod[exportName];
4769
+ if (!schema) {
4770
+ throw new Error(`Schema export "${exportName}" not found in module for type "${type}"`);
4771
+ }
4772
+ schemaCache.set(type, schema);
4773
+ return schema;
4774
+ }
4775
+ var ROOT_ELEMENT_MAP, schemaCache, SchemaRegistry;
4776
+ var init_schema_registry = __esm({
4777
+ "src/validation/schema-registry.ts"() {
4778
+ "use strict";
4779
+ init_schemas();
4780
+ ROOT_ELEMENT_MAP = {
4781
+ Invoice: "PEF3",
4782
+ CreditNote: "PEF_KOR3"
4783
+ };
4784
+ schemaCache = /* @__PURE__ */ new Map();
4785
+ SchemaRegistry = {
4786
+ /**
4787
+ * Get a Zod schema by type. Lazy-loads the module on first access.
4788
+ */
4789
+ async get(type) {
4790
+ return loadSchema(type);
4791
+ },
4792
+ /**
4793
+ * List all available schema types.
4794
+ */
4795
+ availableSchemas() {
4796
+ return ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
4797
+ },
4798
+ /**
4799
+ * Detect schema type from XML namespace URI and/or root element name.
4800
+ *
4801
+ * Detection priority:
4802
+ * 1. Namespace URI match (unique per FA/RR schemas)
4803
+ * 2. Root element name match (for PEF/PEF_KOR which use UBL namespaces)
4804
+ */
4805
+ detect(namespace, rootElement) {
4806
+ if (namespace) {
4807
+ const byNs = NAMESPACE_MAP[namespace];
4808
+ if (byNs) return byNs;
4809
+ }
4810
+ if (rootElement) {
4811
+ const byRoot = ROOT_ELEMENT_MAP[rootElement];
4812
+ if (byRoot) return byRoot;
4813
+ }
4814
+ return null;
4815
+ }
4816
+ };
4817
+ }
4818
+ });
4819
+
4820
+ // src/validation/patterns.ts
4821
+ function isValidNip(value) {
4822
+ if (!Nip.test(value)) return false;
4823
+ let sum = 0;
4824
+ for (let i = 0; i < 9; i++) {
4825
+ sum += Number(value[i]) * NIP_WEIGHTS[i];
4826
+ }
4827
+ const checksum = sum % 11;
4828
+ return checksum !== 10 && checksum === Number(value[9]);
4829
+ }
4830
+ function isValidPesel(value) {
4831
+ if (!Pesel.test(value)) return false;
4832
+ let sum = 0;
4833
+ for (let i = 0; i < 10; i++) {
4834
+ sum += Number(value[i]) * PESEL_WEIGHTS[i];
4835
+ }
4836
+ const checksum = (10 - sum % 10) % 10;
4837
+ return checksum === Number(value[10]);
4838
+ }
4839
+ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, Pesel, NIP_WEIGHTS, PESEL_WEIGHTS;
4840
+ var init_patterns = __esm({
4841
+ "src/validation/patterns.ts"() {
4842
+ "use strict";
4843
+ NIP_PATTERN_CORE = "[1-9]((\\d[1-9])|([1-9]\\d))\\d{7}";
4844
+ VAT_UE_PATTERN_CORE = "(ATU\\d{8}|BE[01]{1}\\d{9}|BG\\d{9,10}|CY\\d{8}[A-Z]|CZ\\d{8,10}|DE\\d{9}|DK\\d{8}|EE\\d{9}|EL\\d{9}|ES([A-Z]\\d{8}|\\d{8}[A-Z]|[A-Z]\\d{7}[A-Z])|FI\\d{8}|FR[A-Z0-9]{2}\\d{9}|HR\\d{11}|HU\\d{8}|IE(\\d{7}[A-Z]{2}|\\d[A-Z0-9+*]\\d{5}[A-Z])|IT\\d{11}|LT(\\d{9}|\\d{12})|LU\\d{8}|LV\\d{11}|MT\\d{8}|NL[A-Z0-9+*]{12}|PT\\d{9}|RO\\d{2,10}|SE\\d{12}|SI\\d{8}|SK\\d{10}|XI((\\d{9}|\\d{12})|(GD|HA)\\d{3}))";
4845
+ Nip = new RegExp(`^${NIP_PATTERN_CORE}$`);
4846
+ VatUe = new RegExp(`^${VAT_UE_PATTERN_CORE}$`);
4847
+ NipVatUe = new RegExp(`^${NIP_PATTERN_CORE}-${VAT_UE_PATTERN_CORE}$`);
4848
+ Pesel = /^\d{2}(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|4[1-9]|5[0-2]|6[1-9]|7[0-2]|8[1-9]|9[0-2])\d{7}$/;
4849
+ NIP_WEIGHTS = [6, 5, 7, 2, 3, 4, 5, 6, 7];
4850
+ PESEL_WEIGHTS = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3];
4851
+ }
4852
+ });
4853
+
4854
+ // src/validation/invoice-validator.ts
4855
+ var invoice_validator_exports = {};
4856
+ __export(invoice_validator_exports, {
4857
+ batchValidationDetails: () => batchValidationDetails,
4858
+ validate: () => validate,
4859
+ validateBatch: () => validateBatch,
4860
+ validateBusinessRules: () => validateBusinessRules,
4861
+ validateSchema: () => validateSchema,
4862
+ validateWellFormedness: () => validateWellFormedness
4863
+ });
4864
+ function validateWellFormedness(xml, _parsed) {
4865
+ if (!xml || !xml.trim()) {
4866
+ return {
4867
+ valid: false,
4868
+ schemaType: null,
4869
+ errors: [{ code: "MALFORMED_XML", message: "Empty XML input" }]
4870
+ };
4871
+ }
4872
+ const { object, rootElement, namespace, errors } = _parsed ?? xmlToObject(xml);
4873
+ if (errors.length > 0 || !object) {
4874
+ return {
4875
+ valid: false,
4876
+ schemaType: null,
4877
+ errors: errors.map((msg) => ({ code: "MALFORMED_XML", message: msg }))
4878
+ };
4879
+ }
4880
+ const schemaType = SchemaRegistry.detect(namespace, rootElement);
4881
+ return { valid: true, schemaType, errors: [] };
4882
+ }
4883
+ async function validateSchema(xml, options, _parsed) {
4884
+ const { object, rootElement, namespace, errors: parseErrors } = _parsed ?? xmlToObject(xml);
4885
+ if (parseErrors.length > 0 || !object) {
4886
+ return {
4887
+ valid: false,
4888
+ schemaType: null,
4889
+ errors: parseErrors.map((msg) => ({ code: "MALFORMED_XML", message: msg }))
4890
+ };
4891
+ }
4892
+ const schemaType = options?.schema ?? SchemaRegistry.detect(namespace, rootElement);
4893
+ if (!schemaType) {
4894
+ return {
4895
+ valid: false,
4896
+ schemaType: null,
4897
+ errors: [{
4898
+ code: "UNKNOWN_SCHEMA",
4899
+ message: `Cannot detect schema type from namespace "${namespace}" and root element "${rootElement}"`
4900
+ }]
4901
+ };
4902
+ }
4903
+ const schema = await SchemaRegistry.get(schemaType);
4904
+ const result = schema.safeParse(object);
4905
+ if (result.success) {
4906
+ return { valid: true, schemaType, errors: [] };
4907
+ }
4908
+ const prefix = rootElement ? `/${rootElement}/` : "/";
4909
+ const validationErrors = result.error.issues.map((issue) => {
4910
+ const zodPath = issue.path.join("/");
4911
+ const path10 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
4912
+ return {
4913
+ code: mapZodErrorCode(issue),
4914
+ message: issue.message,
4915
+ path: path10
4916
+ };
4917
+ });
4918
+ return { valid: false, schemaType, errors: validationErrors };
4919
+ }
4920
+ function mapZodErrorCode(issue) {
4921
+ switch (issue.code) {
4922
+ case "invalid_type":
4923
+ return issue.input === void 0 ? "MISSING_REQUIRED_ELEMENT" : "INVALID_VALUE";
4924
+ case "invalid_enum_value":
4925
+ // Zod v3
4926
+ case "invalid_value":
4927
+ return "INVALID_ENUM_VALUE";
4928
+ case "invalid_string":
4929
+ // Zod v3
4930
+ case "invalid_format":
4931
+ return "PATTERN_MISMATCH";
4932
+ case "too_big":
4933
+ return "MAX_OCCURS_EXCEEDED";
4934
+ case "unrecognized_keys":
4935
+ return "UNRECOGNIZED_KEY";
4936
+ default:
4937
+ return "SCHEMA_VALIDATION_ERROR";
4938
+ }
4939
+ }
4940
+ function validateBusinessRules(xml, _parsed) {
4941
+ const { object, rootElement, namespace, errors: parseErrors } = _parsed ?? xmlToObject(xml);
4942
+ if (parseErrors.length > 0 || !object) {
4943
+ return {
4944
+ valid: false,
4945
+ schemaType: null,
4946
+ errors: parseErrors.map((msg) => ({ code: "MALFORMED_XML", message: msg }))
4947
+ };
4948
+ }
4949
+ const schemaType = SchemaRegistry.detect(namespace, rootElement);
4950
+ const errors = [];
4951
+ collectNipPeselErrors(object, rootElement ? `/${rootElement}` : "", errors);
4952
+ collectDateErrors(object, rootElement, errors);
4953
+ return { valid: errors.length === 0, schemaType, errors };
4954
+ }
4955
+ function collectNipPeselErrors(obj, path10, errors) {
4956
+ for (const [key, value] of Object.entries(obj)) {
4957
+ const currentPath = path10 ? `${path10}/${key}` : key;
4958
+ if (key === "NIP" && typeof value === "string") {
4959
+ if (!isValidNip(value)) {
4960
+ errors.push({
4961
+ code: "INVALID_NIP_CHECKSUM",
4962
+ message: `Invalid NIP checksum: ${value}`,
4963
+ path: currentPath
4964
+ });
4965
+ }
4966
+ } else if (key === "PESEL" && typeof value === "string") {
4967
+ if (!isValidPesel(value)) {
4968
+ errors.push({
4969
+ code: "INVALID_PESEL_CHECKSUM",
4970
+ message: `Invalid PESEL checksum: ${value}`,
4971
+ path: currentPath
4972
+ });
4973
+ }
4974
+ } else if (typeof value === "object" && value !== null) {
4975
+ if (Array.isArray(value)) {
4976
+ for (let i = 0; i < value.length; i++) {
4977
+ if (typeof value[i] === "object" && value[i] !== null) {
4978
+ collectNipPeselErrors(value[i], `${currentPath}/${i}`, errors);
4979
+ }
4980
+ }
4981
+ } else {
4982
+ collectNipPeselErrors(value, currentPath, errors);
4983
+ }
4984
+ }
4985
+ }
4986
+ }
4987
+ function getPolandLocalDate() {
4988
+ return new Intl.DateTimeFormat("sv-SE", { timeZone: "Europe/Warsaw" }).format(Date.now());
4989
+ }
4990
+ function collectDateErrors(obj, rootElement, errors) {
4991
+ const fa = obj["Fa"];
4992
+ if (!fa || typeof fa !== "object") return;
4993
+ const p1 = fa["P_1"];
4994
+ if (typeof p1 !== "string") return;
4995
+ const today = getPolandLocalDate();
4996
+ if (p1 > today) {
4997
+ const prefix = rootElement ? `/${rootElement}` : "";
4998
+ errors.push({
4999
+ code: "FUTURE_INVOICE_DATE",
5000
+ message: `Invoice date P_1 (${p1}) is in the future \u2014 KSeF rejects invoices with P_1 > today (${today})`,
5001
+ path: `${prefix}/Fa/P_1`
5002
+ });
5003
+ }
5004
+ }
5005
+ async function validate(xml, options) {
5006
+ const parsed = xml && xml.trim() ? xmlToObject(xml) : void 0;
5007
+ const l1 = validateWellFormedness(xml, parsed);
5008
+ if (!l1.valid) return l1;
5009
+ const l2 = await validateSchema(xml, options, parsed);
5010
+ if (!l2.valid) return l2;
5011
+ const l3 = validateBusinessRules(xml, parsed);
5012
+ return { ...l3, schemaType: l2.schemaType };
5013
+ }
5014
+ async function validateBatch(invoices2, options) {
5015
+ const results = [];
5016
+ for (const { fileName, xml } of invoices2) {
5017
+ results.push({ fileName, result: await validate(xml, options) });
5018
+ }
5019
+ return { valid: results.every((r) => r.result.valid), results };
5020
+ }
5021
+ function batchValidationDetails(batch) {
5022
+ return batch.results.filter((r) => !r.result.valid).flatMap((r) => r.result.errors.map((e) => ({
5023
+ field: e.path ? `${r.fileName}:${e.path}` : r.fileName,
5024
+ message: e.message
5025
+ })));
5026
+ }
5027
+ var init_invoice_validator = __esm({
5028
+ "src/validation/invoice-validator.ts"() {
5029
+ "use strict";
5030
+ init_xml_to_object();
5031
+ init_schema_registry();
5032
+ init_patterns();
5033
+ }
5034
+ });
5035
+
5036
+ // src/builders/batch-file.ts
5037
+ import * as crypto5 from "crypto";
5038
+ function splitBuffer(data, maxPartSize) {
5039
+ if (data.length <= maxPartSize) {
5040
+ return [data];
5041
+ }
5042
+ const parts = [];
5043
+ for (let offset = 0; offset < data.length; offset += maxPartSize) {
5044
+ parts.push(data.subarray(offset, Math.min(offset + maxPartSize, data.length)));
5045
+ }
5046
+ return parts;
5047
+ }
5048
+ function sha256Base64(data) {
5049
+ return crypto5.createHash("sha256").update(data).digest("base64");
5050
+ }
5051
+ var BATCH_MAX_PART_SIZE, BATCH_MAX_TOTAL_SIZE, BATCH_MAX_PARTS, BatchFileBuilder;
5052
+ var init_batch_file = __esm({
5053
+ "src/builders/batch-file.ts"() {
5054
+ "use strict";
5055
+ init_ksef_validation_error();
5056
+ BATCH_MAX_PART_SIZE = 1e8;
5057
+ BATCH_MAX_TOTAL_SIZE = 5e9;
5058
+ BATCH_MAX_PARTS = 50;
5059
+ BatchFileBuilder = class {
5060
+ /**
5061
+ * Build batch file metadata and encrypted parts from a raw ZIP.
5062
+ *
5063
+ * @param zipBytes - Unencrypted ZIP data
5064
+ * @param encryptFn - AES-256-CBC encryption function (called per part)
5065
+ * @param options - Optional configuration
5066
+ */
5067
+ static build(zipBytes, encryptFn, options) {
5068
+ const maxPartSize = options?.maxPartSize ?? BATCH_MAX_PART_SIZE;
5069
+ if (maxPartSize <= 0) {
5070
+ throw new KSeFValidationError("maxPartSize must be a positive number");
5071
+ }
4136
5072
  if (zipBytes.length === 0) {
4137
5073
  throw new KSeFValidationError("ZIP data must not be empty");
4138
5074
  }
@@ -4283,6 +5219,24 @@ __export(batch_session_workflow_exports, {
4283
5219
  });
4284
5220
  async function uploadBatch(client, zipData, options) {
4285
5221
  await client.crypto.init();
5222
+ if (options?.validate) {
5223
+ const { unzip: unzip2 } = await Promise.resolve().then(() => (init_zip(), zip_exports));
5224
+ const { validateBatch: validateBatch2, batchValidationDetails: batchValidationDetails2 } = await Promise.resolve().then(() => (init_invoice_validator(), invoice_validator_exports));
5225
+ const { KSeFValidationError: KSeFValidationError2 } = await Promise.resolve().then(() => (init_ksef_validation_error(), ksef_validation_error_exports));
5226
+ const zipBuf = Buffer.isBuffer(zipData) ? zipData : Buffer.from(zipData.buffer, zipData.byteOffset, zipData.byteLength);
5227
+ const files = await unzip2(zipBuf);
5228
+ const invoices2 = [...files.entries()].filter(([name]) => name.endsWith(".xml")).map(([name, data]) => ({ fileName: name, xml: data.toString("utf-8") }));
5229
+ if (invoices2.length > 0) {
5230
+ const result2 = await validateBatch2(invoices2);
5231
+ if (!result2.valid) {
5232
+ const invalidCount = result2.results.filter((r) => !r.result.valid).length;
5233
+ throw new KSeFValidationError2(
5234
+ `Batch validation failed: ${invalidCount} of ${invoices2.length} invoices invalid`,
5235
+ batchValidationDetails2(result2)
5236
+ );
5237
+ }
5238
+ }
5239
+ }
4286
5240
  const encData = client.crypto.getEncryptionData();
4287
5241
  const formCode = options?.formCode ?? DEFAULT_FORM_CODE;
4288
5242
  const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
@@ -4403,10 +5357,10 @@ var init_batch_session_workflow = __esm({
4403
5357
  });
4404
5358
 
4405
5359
  // src/cli/index.ts
4406
- import { readFileSync as readFileSync8 } from "fs";
5360
+ import { readFileSync as readFileSync9 } from "fs";
4407
5361
  import { fileURLToPath } from "url";
4408
5362
  import { dirname as dirname2, resolve } from "path";
4409
- import { defineCommand as defineCommand17, runMain } from "citty";
5363
+ import { defineCommand as defineCommand18, runMain } from "citty";
4410
5364
 
4411
5365
  // src/cli/commands/config.ts
4412
5366
  import { defineCommand } from "citty";
@@ -4558,6 +5512,7 @@ init_ksef_rate_limit_error();
4558
5512
  init_ksef_unauthorized_error();
4559
5513
  init_ksef_forbidden_error();
4560
5514
  init_ksef_api_error();
5515
+ init_ksef_validation_error();
4561
5516
  import { consola as consola2 } from "consola";
4562
5517
  async function withErrorHandler(fn) {
4563
5518
  try {
@@ -4581,6 +5536,13 @@ async function withErrorHandler(fn) {
4581
5536
  consola2.info("Hint: Check your permissions for this operation.");
4582
5537
  process.exit(1);
4583
5538
  }
5539
+ if (error instanceof KSeFValidationError) {
5540
+ consola2.error(error.message);
5541
+ for (const detail of error.details) {
5542
+ consola2.error(` ${detail.field ? `[${detail.field}] ` : ""}${detail.message}`);
5543
+ }
5544
+ process.exit(1);
5545
+ }
4584
5546
  if (error instanceof KSeFApiError) {
4585
5547
  consola2.error(`KSeF API error (HTTP ${error.statusCode}): ${error.message}`);
4586
5548
  if (error.errorResponse?.exception?.exceptionDetailList) {
@@ -4964,13 +5926,13 @@ var login = defineCommand2({
4964
5926
  if (token) {
4965
5927
  await client.loginWithToken(token, nip);
4966
5928
  } else if (args.p12) {
4967
- const fs13 = await import("fs");
4968
- const p12Buffer = fs13.readFileSync(args.p12);
5929
+ const fs15 = await import("fs");
5930
+ const p12Buffer = fs15.readFileSync(args.p12);
4969
5931
  await client.loginWithPkcs12(p12Buffer, args["p12-password"] ?? "", nip);
4970
5932
  } else if (args.cert && args.key) {
4971
- const fs13 = await import("fs");
4972
- const certPem = fs13.readFileSync(args.cert, "utf-8");
4973
- const keyPem = fs13.readFileSync(args.key, "utf-8");
5933
+ const fs15 = await import("fs");
5934
+ const certPem = fs15.readFileSync(args.cert, "utf-8");
5935
+ const keyPem = fs15.readFileSync(args.key, "utf-8");
4974
5936
  await client.loginWithCertificate(certPem, keyPem, nip, args["key-password"]);
4975
5937
  } else {
4976
5938
  throw new Error("Provide --token, --p12, or both --cert and --key for authentication.");
@@ -5306,227 +6268,23 @@ var status2 = defineCommand3({
5306
6268
  if (args.json) {
5307
6269
  outputResult(result, { json: true });
5308
6270
  } else {
5309
- outputKeyValue({
5310
- "Status": `${result.status.code} \u2014 ${result.status.description}`,
5311
- "Created": result.dateCreated,
5312
- "Updated": result.dateUpdated,
5313
- "Valid Until": result.validUntil ?? "N/A",
5314
- "Invoices": result.invoiceCount ?? 0,
5315
- "Successful": result.successfulInvoiceCount ?? 0,
5316
- "Failed": result.failedInvoiceCount ?? 0
5317
- }, { json: false });
5318
- }
5319
- });
5320
- }
5321
- });
5322
- var list = defineCommand3({
5323
- meta: { name: "list", description: "List sessions" },
5324
- args: {
5325
- type: { type: "string", description: "Session type: online or batch (default: online)" },
5326
- pageSize: { type: "string", description: "Number of results per page" },
5327
- env: { type: "string", description: "Environment (test/demo/prod)" },
5328
- json: { type: "boolean", description: "Output as JSON" },
5329
- verbose: { type: "boolean", description: "Show HTTP request/response details" },
5330
- timeout: { type: "string", description: "Request timeout (ms)" }
5331
- },
5332
- run({ args }) {
5333
- return withErrorHandler(async () => {
5334
- const globalOpts = getGlobalOpts2(args);
5335
- const { client } = await requireSession(globalOpts);
5336
- const sessionType = args.type === "batch" ? "Batch" : "Online";
5337
- const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
5338
- const result = await client.sessionStatus.getSessions(sessionType, pageSize);
5339
- if (args.json) {
5340
- outputResult(result, { json: true });
5341
- return;
5342
- }
5343
- if (result.sessions.length === 0) {
5344
- outputWarning("No sessions found.");
5345
- return;
5346
- }
5347
- outputTable(
5348
- result.sessions.map((s) => ({
5349
- reference: s.referenceNumber,
5350
- status: `${s.status.code} \u2014 ${s.status.description}`,
5351
- created: s.dateCreated,
5352
- total: s.totalInvoiceCount,
5353
- success: s.successfulInvoiceCount,
5354
- failed: s.failedInvoiceCount
5355
- })),
5356
- [
5357
- { key: "reference", label: "Reference" },
5358
- { key: "status", label: "Status" },
5359
- { key: "created", label: "Created" },
5360
- { key: "total", label: "Total" },
5361
- { key: "success", label: "Success" },
5362
- { key: "failed", label: "Failed" }
5363
- ],
5364
- { json: false }
5365
- );
5366
- if (result.continuationToken) {
5367
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
5368
- }
5369
- });
5370
- }
5371
- });
5372
- var invoices = defineCommand3({
5373
- meta: { name: "invoices", description: "List invoices in a session" },
5374
- args: {
5375
- ref: { type: "positional", description: "Session reference (uses stored ref if omitted)", required: false },
5376
- pageSize: { type: "string", description: "Number of results per page" },
5377
- env: { type: "string", description: "Environment (test/demo/prod)" },
5378
- json: { type: "boolean", description: "Output as JSON" },
5379
- verbose: { type: "boolean", description: "Show HTTP request/response details" },
5380
- timeout: { type: "string", description: "Request timeout (ms)" }
5381
- },
5382
- run({ args }) {
5383
- return withErrorHandler(async () => {
5384
- const globalOpts = getGlobalOpts2(args);
5385
- const { client, session } = await requireSession(globalOpts);
5386
- const ref = args.ref ?? session.onlineSessionRef;
5387
- if (!ref) {
5388
- throw new Error("No session reference. Provide a ref or run `ksef session open` first.");
5389
- }
5390
- const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
5391
- const result = await client.sessionStatus.getSessionInvoices(ref, pageSize);
5392
- if (args.json) {
5393
- outputResult(result, { json: true });
5394
- return;
5395
- }
5396
- if (result.invoices.length === 0) {
5397
- outputWarning("No invoices found.");
5398
- return;
5399
- }
5400
- outputTable(
5401
- result.invoices.map((inv) => ({
5402
- ordinal: inv.ordinalNumber,
5403
- invoiceNumber: inv.invoiceNumber ?? "N/A",
5404
- ksefNumber: inv.ksefNumber ?? "N/A",
5405
- status: `${inv.status.code} \u2014 ${inv.status.description}`,
5406
- date: inv.invoicingDate
5407
- })),
5408
- [
5409
- { key: "ordinal", label: "#" },
5410
- { key: "invoiceNumber", label: "Invoice Number" },
5411
- { key: "ksefNumber", label: "KSeF Number" },
5412
- { key: "status", label: "Status" },
5413
- { key: "date", label: "Date" }
5414
- ],
5415
- { json: false }
5416
- );
5417
- if (result.continuationToken) {
5418
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
5419
- }
5420
- });
5421
- }
5422
- });
5423
- var failed = defineCommand3({
5424
- meta: { name: "failed", description: "List failed invoices in a session" },
5425
- args: {
5426
- ref: { type: "positional", description: "Session reference (uses stored ref if omitted)", required: false },
5427
- pageSize: { type: "string", description: "Number of results per page" },
5428
- env: { type: "string", description: "Environment (test/demo/prod)" },
5429
- json: { type: "boolean", description: "Output as JSON" },
5430
- verbose: { type: "boolean", description: "Show HTTP request/response details" },
5431
- timeout: { type: "string", description: "Request timeout (ms)" }
5432
- },
5433
- run({ args }) {
5434
- return withErrorHandler(async () => {
5435
- const globalOpts = getGlobalOpts2(args);
5436
- const { client, session } = await requireSession(globalOpts);
5437
- const ref = args.ref ?? session.onlineSessionRef;
5438
- if (!ref) {
5439
- throw new Error("No session reference. Provide a ref or run `ksef session open` first.");
5440
- }
5441
- const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
5442
- const result = await client.sessionStatus.getSessionFailedInvoices(ref, pageSize);
5443
- if (args.json) {
5444
- outputResult(result, { json: true });
5445
- return;
5446
- }
5447
- if (result.invoices.length === 0) {
5448
- outputSuccess("No failed invoices.");
5449
- return;
5450
- }
5451
- outputTable(
5452
- result.invoices.map((inv) => ({
5453
- ordinal: inv.ordinalNumber,
5454
- invoiceNumber: inv.invoiceNumber ?? "N/A",
5455
- status: `${inv.status.code} \u2014 ${inv.status.description}`,
5456
- details: inv.status.details?.join("; ") ?? "",
5457
- date: inv.invoicingDate
5458
- })),
5459
- [
5460
- { key: "ordinal", label: "#" },
5461
- { key: "invoiceNumber", label: "Invoice Number" },
5462
- { key: "status", label: "Status" },
5463
- { key: "details", label: "Details" },
5464
- { key: "date", label: "Date" }
5465
- ],
5466
- { json: false }
5467
- );
5468
- if (result.continuationToken) {
5469
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
5470
- }
5471
- });
5472
- }
5473
- });
5474
- var upo = defineCommand3({
5475
- meta: { name: "upo", description: "Download UPO (official receipt)" },
5476
- args: {
5477
- sessionRef: { type: "positional", description: "Session reference", required: true },
5478
- upoRef: { type: "string", description: "UPO reference" },
5479
- ksefNumber: { type: "string", description: "KSeF invoice number" },
5480
- invoiceRef: { type: "string", description: "Invoice reference" },
5481
- parsed: { type: "boolean", description: "Parse UPO XML and output as JSON" },
5482
- o: { type: "string", description: "Output file path" },
5483
- env: { type: "string", description: "Environment (test/demo/prod)" },
5484
- json: { type: "boolean", description: "Output as JSON" },
5485
- verbose: { type: "boolean", description: "Show HTTP request/response details" },
5486
- timeout: { type: "string", description: "Request timeout (ms)" }
5487
- },
5488
- run({ args }) {
5489
- return withErrorHandler(async () => {
5490
- const globalOpts = getGlobalOpts2(args);
5491
- const { client } = await requireSession(globalOpts);
5492
- const sessionRef = args.sessionRef;
5493
- let result;
5494
- if (args.upoRef) {
5495
- result = await client.sessionStatus.getSessionUpo(sessionRef, args.upoRef);
5496
- } else if (args.ksefNumber) {
5497
- result = await client.sessionStatus.getInvoiceUpoByKsefNumber(sessionRef, args.ksefNumber);
5498
- } else if (args.invoiceRef) {
5499
- result = await client.sessionStatus.getInvoiceUpoByReference(sessionRef, args.invoiceRef);
5500
- } else {
5501
- throw new Error("Provide one of: --upo-ref, --ksef-number, or --invoice-ref");
5502
- }
5503
- if (args.parsed) {
5504
- const parsed = parseUpoXml(result.upo);
5505
- const json = JSON.stringify(parsed, null, 2);
5506
- if (args.o) {
5507
- fs6.writeFileSync(args.o, json, "utf-8");
5508
- outputSuccess(`Parsed UPO saved to ${args.o}`);
5509
- } else {
5510
- console.log(json);
5511
- }
5512
- return;
5513
- }
5514
- if (args.json) {
5515
- outputResult(result, { json: true });
5516
- return;
5517
- }
5518
- if (args.o) {
5519
- fs6.writeFileSync(args.o, result.upo, "utf-8");
5520
- outputSuccess(`UPO saved to ${args.o}`);
5521
- } else {
5522
- console.log(result.upo);
6271
+ outputKeyValue({
6272
+ "Status": `${result.status.code} \u2014 ${result.status.description}`,
6273
+ "Created": result.dateCreated,
6274
+ "Updated": result.dateUpdated,
6275
+ "Valid Until": result.validUntil ?? "N/A",
6276
+ "Invoices": result.invoiceCount ?? 0,
6277
+ "Successful": result.successfulInvoiceCount ?? 0,
6278
+ "Failed": result.failedInvoiceCount ?? 0
6279
+ }, { json: false });
5523
6280
  }
5524
6281
  });
5525
6282
  }
5526
6283
  });
5527
- var active = defineCommand3({
5528
- meta: { name: "active", description: "List active authentication sessions" },
6284
+ var list = defineCommand3({
6285
+ meta: { name: "list", description: "List sessions" },
5529
6286
  args: {
6287
+ type: { type: "string", description: "Session type: online or batch (default: online)" },
5530
6288
  pageSize: { type: "string", description: "Number of results per page" },
5531
6289
  env: { type: "string", description: "Environment (test/demo/prod)" },
5532
6290
  json: { type: "boolean", description: "Output as JSON" },
@@ -5537,30 +6295,33 @@ var active = defineCommand3({
5537
6295
  return withErrorHandler(async () => {
5538
6296
  const globalOpts = getGlobalOpts2(args);
5539
6297
  const { client } = await requireSession(globalOpts);
6298
+ const sessionType = args.type === "batch" ? "Batch" : "Online";
5540
6299
  const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
5541
- const result = await client.activeSessions.getActiveSessions(pageSize);
6300
+ const result = await client.sessionStatus.getSessions(sessionType, pageSize);
5542
6301
  if (args.json) {
5543
6302
  outputResult(result, { json: true });
5544
6303
  return;
5545
6304
  }
5546
- if (result.items.length === 0) {
5547
- outputWarning("No active sessions found.");
6305
+ if (result.sessions.length === 0) {
6306
+ outputWarning("No sessions found.");
5548
6307
  return;
5549
6308
  }
5550
6309
  outputTable(
5551
- result.items.map((s) => ({
6310
+ result.sessions.map((s) => ({
5552
6311
  reference: s.referenceNumber,
5553
- startDate: s.startDate,
5554
- authMethod: s.authenticationMethodInfo?.category ?? "N/A",
5555
6312
  status: `${s.status.code} \u2014 ${s.status.description}`,
5556
- isCurrent: s.isCurrent ? "Yes" : "No"
6313
+ created: s.dateCreated,
6314
+ total: s.totalInvoiceCount,
6315
+ success: s.successfulInvoiceCount,
6316
+ failed: s.failedInvoiceCount
5557
6317
  })),
5558
6318
  [
5559
6319
  { key: "reference", label: "Reference" },
5560
- { key: "startDate", label: "Start Date" },
5561
- { key: "authMethod", label: "Auth Method" },
5562
6320
  { key: "status", label: "Status" },
5563
- { key: "isCurrent", label: "Current" }
6321
+ { key: "created", label: "Created" },
6322
+ { key: "total", label: "Total" },
6323
+ { key: "success", label: "Success" },
6324
+ { key: "failed", label: "Failed" }
5564
6325
  ],
5565
6326
  { json: false }
5566
6327
  );
@@ -5570,45 +6331,11 @@ var active = defineCommand3({
5570
6331
  });
5571
6332
  }
5572
6333
  });
5573
- var revoke = defineCommand3({
5574
- meta: { name: "revoke", description: "Revoke an active authentication session" },
5575
- args: {
5576
- ref: { type: "positional", description: "Session reference to revoke", required: false },
5577
- current: { type: "boolean", description: "Revoke the current session" },
5578
- env: { type: "string", description: "Environment (test/demo/prod)" },
5579
- json: { type: "boolean", description: "Output as JSON" },
5580
- verbose: { type: "boolean", description: "Show HTTP request/response details" },
5581
- timeout: { type: "string", description: "Request timeout (ms)" }
5582
- },
5583
- run({ args }) {
5584
- return withErrorHandler(async () => {
5585
- const globalOpts = getGlobalOpts2(args);
5586
- const { client } = await requireSession(globalOpts);
5587
- if (args.current) {
5588
- await client.activeSessions.revokeCurrentSession();
5589
- if (args.json) {
5590
- outputResult({ status: "revoked", reference: "current" }, { json: true });
5591
- } else {
5592
- outputSuccess("Current session revoked.");
5593
- }
5594
- } else if (args.ref) {
5595
- await client.activeSessions.revokeSession(args.ref);
5596
- if (args.json) {
5597
- outputResult({ status: "revoked", reference: args.ref }, { json: true });
5598
- } else {
5599
- outputSuccess(`Session ${args.ref} revoked.`);
5600
- }
5601
- } else {
5602
- throw new Error("Provide a session reference or use --current to revoke the current session.");
5603
- }
5604
- });
5605
- }
5606
- });
5607
- var invoice = defineCommand3({
5608
- meta: { name: "invoice", description: "Get single invoice status in a session" },
6334
+ var invoices = defineCommand3({
6335
+ meta: { name: "invoices", description: "List invoices in a session" },
5609
6336
  args: {
5610
- invoiceRef: { type: "positional", description: "Invoice reference number", required: true },
5611
- ref: { type: "string", description: "Session reference (uses stored ref if omitted)" },
6337
+ ref: { type: "positional", description: "Session reference (uses stored ref if omitted)", required: false },
6338
+ pageSize: { type: "string", description: "Number of results per page" },
5612
6339
  env: { type: "string", description: "Environment (test/demo/prod)" },
5613
6340
  json: { type: "boolean", description: "Output as JSON" },
5614
6341
  verbose: { type: "boolean", description: "Show HTTP request/response details" },
@@ -5618,664 +6345,543 @@ var invoice = defineCommand3({
5618
6345
  return withErrorHandler(async () => {
5619
6346
  const globalOpts = getGlobalOpts2(args);
5620
6347
  const { client, session } = await requireSession(globalOpts);
5621
- const sessionRef = args.ref ?? session.onlineSessionRef;
5622
- if (!sessionRef) {
5623
- throw new Error("No session reference. Provide --ref or run `ksef session open` first.");
6348
+ const ref = args.ref ?? session.onlineSessionRef;
6349
+ if (!ref) {
6350
+ throw new Error("No session reference. Provide a ref or run `ksef session open` first.");
5624
6351
  }
5625
- const result = await client.sessionStatus.getSessionInvoice(sessionRef, args.invoiceRef);
6352
+ const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
6353
+ const result = await client.sessionStatus.getSessionInvoices(ref, pageSize);
5626
6354
  if (args.json) {
5627
6355
  outputResult(result, { json: true });
5628
- } else {
5629
- outputKeyValue({
5630
- "Ordinal": result.ordinalNumber,
5631
- "Invoice Number": result.invoiceNumber ?? "N/A",
5632
- "KSeF Number": result.ksefNumber ?? "N/A",
5633
- "Reference": result.referenceNumber,
5634
- "Hash": result.invoiceHash,
5635
- "Status": `${result.status.code} \u2014 ${result.status.description}`,
5636
- "Invoicing Date": result.invoicingDate,
5637
- "Invoicing Mode": result.invoicingMode ?? "N/A"
5638
- }, { json: false });
5639
- }
5640
- });
5641
- }
5642
- });
5643
- var sessionCommand = defineCommand3({
5644
- meta: { name: "session", description: "Session management commands" },
5645
- subCommands: { open, close, status: status2, list, invoices, failed, upo, active, revoke, invoice }
5646
- });
5647
-
5648
- // src/cli/commands/invoice.ts
5649
- import * as fs9 from "fs";
5650
- import * as path6 from "path";
5651
- import { Readable } from "stream";
5652
- import { defineCommand as defineCommand5 } from "citty";
5653
- import { consola as consola9 } from "consola";
5654
- init_document_structures();
5655
-
5656
- // src/cli/commands/export-incremental.ts
5657
- import * as fs8 from "fs";
5658
- import * as path5 from "path";
5659
- import { defineCommand as defineCommand4 } from "citty";
5660
- import { consola as consola8 } from "consola";
5661
-
5662
- // src/workflows/hwm-storage.ts
5663
- import * as fs7 from "fs/promises";
5664
- var FileHwmStore = class {
5665
- constructor(filePath) {
5666
- this.filePath = filePath;
5667
- }
5668
- async load() {
5669
- try {
5670
- const data = await fs7.readFile(this.filePath, "utf-8");
5671
- return JSON.parse(data);
5672
- } catch (err) {
5673
- if (err.code === "ENOENT") {
5674
- return {};
6356
+ return;
5675
6357
  }
5676
- throw err;
5677
- }
5678
- }
5679
- async save(points) {
5680
- await fs7.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
5681
- }
5682
- };
5683
-
5684
- // src/utils/zip.ts
5685
- import { ZipFile } from "yazl";
5686
- import { fromBuffer } from "yauzl";
5687
-
5688
- // src/workflows/invoice-export-workflow.ts
5689
- init_polling();
5690
- async function doExport(client, filters, options) {
5691
- await client.crypto.init();
5692
- const encData = client.crypto.getEncryptionData();
5693
- const opResp = await client.invoices.exportInvoices({
5694
- encryption: encData.encryptionInfo,
5695
- filters,
5696
- onlyMetadata: options?.onlyMetadata
5697
- });
5698
- const result = await pollUntil(
5699
- () => client.invoices.getInvoiceExportStatus(opResp.referenceNumber),
5700
- (s) => s.status.code === 200 || s.status.code >= 400,
5701
- { ...options?.pollOptions, description: `export ${opResp.referenceNumber}` }
5702
- );
5703
- if (result.status.code !== 200) {
5704
- throw new Error(`Export failed: ${result.status.code} \u2014 ${result.status.description}`);
5705
- }
5706
- if (!result.package) {
5707
- throw new Error("Export completed but no package available");
5708
- }
5709
- return {
5710
- encData,
5711
- referenceNumber: opResp.referenceNumber,
5712
- result: {
5713
- parts: result.package.parts.map((p) => ({
5714
- ordinalNumber: p.ordinalNumber,
5715
- url: p.url,
5716
- method: p.method,
5717
- partSize: p.partSize,
5718
- encryptedPartSize: p.encryptedPartSize,
5719
- encryptedPartHash: p.encryptedPartHash,
5720
- expirationDate: p.expirationDate
5721
- })),
5722
- invoiceCount: result.package.invoiceCount,
5723
- isTruncated: result.package.isTruncated,
5724
- permanentStorageHwmDate: result.package.permanentStorageHwmDate,
5725
- lastPermanentStorageDate: result.package.lastPermanentStorageDate
5726
- }
5727
- };
5728
- }
5729
-
5730
- // src/workflows/hwm-coordinator.ts
5731
- function updateContinuationPoint(points, subjectType, pkg2) {
5732
- if (pkg2.isTruncated && pkg2.lastPermanentStorageDate) {
5733
- points[subjectType] = pkg2.lastPermanentStorageDate;
5734
- } else if (pkg2.permanentStorageHwmDate) {
5735
- points[subjectType] = pkg2.permanentStorageHwmDate;
5736
- } else {
5737
- delete points[subjectType];
5738
- }
5739
- }
5740
- function getEffectiveStartDate(points, subjectType, windowFrom) {
5741
- return points[subjectType] ?? windowFrom;
5742
- }
5743
-
5744
- // src/workflows/incremental-export-workflow.ts
5745
- async function incrementalExportAndDownload(client, options) {
5746
- const maxIterations = options.maxIterations ?? 20;
5747
- const points = options.continuationPoints;
5748
- if (options.store) {
5749
- const loaded = await options.store.load();
5750
- for (const [key, value] of Object.entries(loaded)) {
5751
- if (value !== void 0 && points[key] === void 0) {
5752
- points[key] = value;
6358
+ if (result.invoices.length === 0) {
6359
+ outputWarning("No invoices found.");
6360
+ return;
6361
+ }
6362
+ outputTable(
6363
+ result.invoices.map((inv) => ({
6364
+ ordinal: inv.ordinalNumber,
6365
+ invoiceNumber: inv.invoiceNumber ?? "N/A",
6366
+ ksefNumber: inv.ksefNumber ?? "N/A",
6367
+ status: `${inv.status.code} \u2014 ${inv.status.description}`,
6368
+ date: inv.invoicingDate
6369
+ })),
6370
+ [
6371
+ { key: "ordinal", label: "#" },
6372
+ { key: "invoiceNumber", label: "Invoice Number" },
6373
+ { key: "ksefNumber", label: "KSeF Number" },
6374
+ { key: "status", label: "Status" },
6375
+ { key: "date", label: "Date" }
6376
+ ],
6377
+ { json: false }
6378
+ );
6379
+ if (result.continuationToken) {
6380
+ consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
5753
6381
  }
5754
- }
5755
- }
5756
- const referenceNumbers = [];
5757
- const decryptedParts = [];
5758
- let previousFrom;
5759
- let iteration = 0;
5760
- for (; iteration < maxIterations; iteration++) {
5761
- const effectiveFrom = getEffectiveStartDate(points, options.subjectType, options.windowFrom);
5762
- if (previousFrom !== void 0 && effectiveFrom === previousFrom) {
5763
- break;
5764
- }
5765
- previousFrom = effectiveFrom;
5766
- const filters = options.filtersFactory ? options.filtersFactory(effectiveFrom, options.windowTo) : buildDefaultFilters(options.subjectType, effectiveFrom, options.windowTo);
5767
- const { result, encData, referenceNumber } = await doExport(client, filters, {
5768
- onlyMetadata: options.onlyMetadata,
5769
- pollOptions: options.pollOptions
5770
6382
  });
5771
- referenceNumbers.push(referenceNumber);
5772
- const download = options.transport ?? fetch;
5773
- for (const part of result.parts) {
5774
- const resp = await download(part.url, { method: part.method });
5775
- if (!resp.ok) {
5776
- throw new Error(`Download failed for part ${part.ordinalNumber}: HTTP ${resp.status}`);
6383
+ }
6384
+ });
6385
+ var failed = defineCommand3({
6386
+ meta: { name: "failed", description: "List failed invoices in a session" },
6387
+ args: {
6388
+ ref: { type: "positional", description: "Session reference (uses stored ref if omitted)", required: false },
6389
+ pageSize: { type: "string", description: "Number of results per page" },
6390
+ env: { type: "string", description: "Environment (test/demo/prod)" },
6391
+ json: { type: "boolean", description: "Output as JSON" },
6392
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
6393
+ timeout: { type: "string", description: "Request timeout (ms)" }
6394
+ },
6395
+ run({ args }) {
6396
+ return withErrorHandler(async () => {
6397
+ const globalOpts = getGlobalOpts2(args);
6398
+ const { client, session } = await requireSession(globalOpts);
6399
+ const ref = args.ref ?? session.onlineSessionRef;
6400
+ if (!ref) {
6401
+ throw new Error("No session reference. Provide a ref or run `ksef session open` first.");
6402
+ }
6403
+ const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
6404
+ const result = await client.sessionStatus.getSessionFailedInvoices(ref, pageSize);
6405
+ if (args.json) {
6406
+ outputResult(result, { json: true });
6407
+ return;
6408
+ }
6409
+ if (result.invoices.length === 0) {
6410
+ outputSuccess("No failed invoices.");
6411
+ return;
6412
+ }
6413
+ outputTable(
6414
+ result.invoices.map((inv) => ({
6415
+ ordinal: inv.ordinalNumber,
6416
+ invoiceNumber: inv.invoiceNumber ?? "N/A",
6417
+ status: `${inv.status.code} \u2014 ${inv.status.description}`,
6418
+ details: inv.status.details?.join("; ") ?? "",
6419
+ date: inv.invoicingDate
6420
+ })),
6421
+ [
6422
+ { key: "ordinal", label: "#" },
6423
+ { key: "invoiceNumber", label: "Invoice Number" },
6424
+ { key: "status", label: "Status" },
6425
+ { key: "details", label: "Details" },
6426
+ { key: "date", label: "Date" }
6427
+ ],
6428
+ { json: false }
6429
+ );
6430
+ if (result.continuationToken) {
6431
+ consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
5777
6432
  }
5778
- const encryptedData = new Uint8Array(await resp.arrayBuffer());
5779
- const decrypted = client.crypto.decryptAES256(encryptedData, encData.cipherKey, encData.cipherIv);
5780
- decryptedParts.push(decrypted);
5781
- }
5782
- updateContinuationPoint(points, options.subjectType, {
5783
- isTruncated: result.isTruncated,
5784
- lastPermanentStorageDate: result.lastPermanentStorageDate,
5785
- permanentStorageHwmDate: result.permanentStorageHwmDate
5786
6433
  });
5787
- if (options.store) {
5788
- await options.store.save(points);
5789
- }
5790
- options.onIterationComplete?.(iteration, result);
5791
- if (!result.isTruncated) {
5792
- iteration++;
5793
- break;
5794
- }
5795
6434
  }
5796
- return {
5797
- referenceNumbers,
5798
- invoices: [],
5799
- decryptedParts,
5800
- continuationPoints: points,
5801
- iterationCount: iteration
5802
- };
5803
- }
5804
- function buildDefaultFilters(subjectType, from, to) {
5805
- return {
5806
- subjectType,
5807
- dateRange: {
5808
- dateType: "PermanentStorage",
5809
- from,
5810
- to
5811
- }
5812
- };
5813
- }
5814
-
5815
- // src/cli/date-utils.ts
5816
- var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
5817
- function normalizeCliDate(date, position) {
5818
- if (!DATE_ONLY_RE.test(date)) return date;
5819
- if (isNaN(new Date(date).getTime())) {
5820
- throw new Error(`Invalid date: "${date}". Expected a valid YYYY-MM-DD date.`);
6435
+ });
6436
+ var upo = defineCommand3({
6437
+ meta: { name: "upo", description: "Download UPO (official receipt)" },
6438
+ args: {
6439
+ sessionRef: { type: "positional", description: "Session reference", required: true },
6440
+ upoRef: { type: "string", description: "UPO reference" },
6441
+ ksefNumber: { type: "string", description: "KSeF invoice number" },
6442
+ invoiceRef: { type: "string", description: "Invoice reference" },
6443
+ parsed: { type: "boolean", description: "Parse UPO XML and output as JSON" },
6444
+ o: { type: "string", description: "Output file path" },
6445
+ env: { type: "string", description: "Environment (test/demo/prod)" },
6446
+ json: { type: "boolean", description: "Output as JSON" },
6447
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
6448
+ timeout: { type: "string", description: "Request timeout (ms)" }
6449
+ },
6450
+ run({ args }) {
6451
+ return withErrorHandler(async () => {
6452
+ const globalOpts = getGlobalOpts2(args);
6453
+ const { client } = await requireSession(globalOpts);
6454
+ const sessionRef = args.sessionRef;
6455
+ let result;
6456
+ if (args.upoRef) {
6457
+ result = await client.sessionStatus.getSessionUpo(sessionRef, args.upoRef);
6458
+ } else if (args.ksefNumber) {
6459
+ result = await client.sessionStatus.getInvoiceUpoByKsefNumber(sessionRef, args.ksefNumber);
6460
+ } else if (args.invoiceRef) {
6461
+ result = await client.sessionStatus.getInvoiceUpoByReference(sessionRef, args.invoiceRef);
6462
+ } else {
6463
+ throw new Error("Provide one of: --upo-ref, --ksef-number, or --invoice-ref");
6464
+ }
6465
+ if (args.parsed) {
6466
+ const parsed = parseUpoXml(result.upo);
6467
+ const json = JSON.stringify(parsed, null, 2);
6468
+ if (args.o) {
6469
+ fs6.writeFileSync(args.o, json, "utf-8");
6470
+ outputSuccess(`Parsed UPO saved to ${args.o}`);
6471
+ } else {
6472
+ console.log(json);
6473
+ }
6474
+ return;
6475
+ }
6476
+ if (args.json) {
6477
+ outputResult(result, { json: true });
6478
+ return;
6479
+ }
6480
+ if (args.o) {
6481
+ fs6.writeFileSync(args.o, result.upo, "utf-8");
6482
+ outputSuccess(`UPO saved to ${args.o}`);
6483
+ } else {
6484
+ console.log(result.upo);
6485
+ }
6486
+ });
5821
6487
  }
5822
- return position === "from" ? `${date}T00:00:00+00:00` : `${date}T23:59:59.999+00:00`;
5823
- }
5824
-
5825
- // src/cli/commands/export-incremental.ts
5826
- function getGlobalOpts3(args) {
5827
- return {
5828
- env: args.env,
5829
- json: args.json,
5830
- verbose: args.verbose,
5831
- timeout: args.timeout,
5832
- nip: args.nip
5833
- };
5834
- }
5835
- var exportIncremental = defineCommand4({
5836
- meta: { name: "export-incremental", description: "Incremental invoice export with HWM state persistence" },
6488
+ });
6489
+ var active = defineCommand3({
6490
+ meta: { name: "active", description: "List active authentication sessions" },
5837
6491
  args: {
5838
- from: { type: "string", description: "Start date (YYYY-MM-DD) \u2014 required", required: true },
5839
- to: { type: "string", description: "End date (YYYY-MM-DD)" },
5840
- subjectType: { type: "string", description: "Subject type: Subject1|Subject2|Subject3|SubjectAuthorized (default: Subject1)" },
5841
- stateFile: { type: "string", description: "HWM state file path (default: ./ksef-hwm-state.json)" },
5842
- outputDir: { type: "string", description: "Output directory for exported parts (default: ./ksef-exports/)" },
5843
- maxIterations: { type: "string", description: "Max export iterations (default: 20)" },
6492
+ pageSize: { type: "string", description: "Number of results per page" },
5844
6493
  env: { type: "string", description: "Environment (test/demo/prod)" },
5845
6494
  json: { type: "boolean", description: "Output as JSON" },
5846
6495
  verbose: { type: "boolean", description: "Show HTTP request/response details" },
5847
- timeout: { type: "string", description: "Request timeout (ms)" },
5848
- nip: { type: "string", description: "NIP number" }
6496
+ timeout: { type: "string", description: "Request timeout (ms)" }
5849
6497
  },
5850
6498
  run({ args }) {
5851
6499
  return withErrorHandler(async () => {
5852
- const globalOpts = getGlobalOpts3(args);
6500
+ const globalOpts = getGlobalOpts2(args);
5853
6501
  const { client } = await requireSession(globalOpts);
5854
- const from = normalizeCliDate(args.from, "from");
5855
- const to = normalizeCliDate(args.to ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), "to");
5856
- const subjectType = args.subjectType ?? "Subject1";
5857
- const stateFile = args.stateFile ?? "./ksef-hwm-state.json";
5858
- const outputDir = args.outputDir ?? "./ksef-exports";
5859
- const maxIterations = args.maxIterations ? parseInt(args.maxIterations, 10) : 20;
5860
- const isJson = args.json;
5861
- const store = new FileHwmStore(stateFile);
5862
- const continuationPoints = {};
5863
- if (!fs8.existsSync(outputDir)) {
5864
- fs8.mkdirSync(outputDir, { recursive: true });
6502
+ const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
6503
+ const result = await client.activeSessions.getActiveSessions(pageSize);
6504
+ if (args.json) {
6505
+ outputResult(result, { json: true });
6506
+ return;
5865
6507
  }
5866
- if (!isJson) {
5867
- consola8.start(`Incremental export: ${from} \u2192 ${to}, subject: ${subjectType}`);
5868
- consola8.info(`State file: ${stateFile}`);
5869
- consola8.info(`Output dir: ${outputDir}`);
6508
+ if (result.items.length === 0) {
6509
+ outputWarning("No active sessions found.");
6510
+ return;
5870
6511
  }
5871
- const iterationParts = [];
5872
- const result = await incrementalExportAndDownload(client, {
5873
- subjectType,
5874
- windowFrom: from,
5875
- windowTo: to,
5876
- continuationPoints,
5877
- maxIterations,
5878
- store,
5879
- pollOptions: { intervalMs: 2e3 },
5880
- onIterationComplete: (iteration, iterResult) => {
5881
- iterationParts.push({ iteration, partCount: iterResult.parts.length });
5882
- if (!isJson) {
5883
- const hwmDate = continuationPoints[subjectType] ?? "complete";
5884
- consola8.info(
5885
- `Iteration ${iteration + 1}: ${iterResult.invoiceCount} invoices, truncated: ${iterResult.isTruncated}, HWM: ${hwmDate}`
5886
- );
5887
- }
6512
+ outputTable(
6513
+ result.items.map((s) => ({
6514
+ reference: s.referenceNumber,
6515
+ startDate: s.startDate,
6516
+ authMethod: s.authenticationMethodInfo?.category ?? "N/A",
6517
+ status: `${s.status.code} \u2014 ${s.status.description}`,
6518
+ isCurrent: s.isCurrent ? "Yes" : "No"
6519
+ })),
6520
+ [
6521
+ { key: "reference", label: "Reference" },
6522
+ { key: "startDate", label: "Start Date" },
6523
+ { key: "authMethod", label: "Auth Method" },
6524
+ { key: "status", label: "Status" },
6525
+ { key: "isCurrent", label: "Current" }
6526
+ ],
6527
+ { json: false }
6528
+ );
6529
+ if (result.continuationToken) {
6530
+ consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
6531
+ }
6532
+ });
6533
+ }
6534
+ });
6535
+ var revoke = defineCommand3({
6536
+ meta: { name: "revoke", description: "Revoke an active authentication session" },
6537
+ args: {
6538
+ ref: { type: "positional", description: "Session reference to revoke", required: false },
6539
+ current: { type: "boolean", description: "Revoke the current session" },
6540
+ env: { type: "string", description: "Environment (test/demo/prod)" },
6541
+ json: { type: "boolean", description: "Output as JSON" },
6542
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
6543
+ timeout: { type: "string", description: "Request timeout (ms)" }
6544
+ },
6545
+ run({ args }) {
6546
+ return withErrorHandler(async () => {
6547
+ const globalOpts = getGlobalOpts2(args);
6548
+ const { client } = await requireSession(globalOpts);
6549
+ if (args.current) {
6550
+ await client.activeSessions.revokeCurrentSession();
6551
+ if (args.json) {
6552
+ outputResult({ status: "revoked", reference: "current" }, { json: true });
6553
+ } else {
6554
+ outputSuccess("Current session revoked.");
5888
6555
  }
5889
- });
5890
- let partIndex = 0;
5891
- for (const { iteration, partCount } of iterationParts) {
5892
- for (let p = 0; p < partCount; p++) {
5893
- if (partIndex < result.decryptedParts.length) {
5894
- const fileName = `iter-${String(iteration + 1).padStart(3, "0")}-part-${String(p + 1).padStart(3, "0")}.zip`;
5895
- const filePath = path5.join(outputDir, fileName);
5896
- fs8.writeFileSync(filePath, result.decryptedParts[partIndex]);
5897
- partIndex++;
5898
- }
6556
+ } else if (args.ref) {
6557
+ await client.activeSessions.revokeSession(args.ref);
6558
+ if (args.json) {
6559
+ outputResult({ status: "revoked", reference: args.ref }, { json: true });
6560
+ } else {
6561
+ outputSuccess(`Session ${args.ref} revoked.`);
5899
6562
  }
6563
+ } else {
6564
+ throw new Error("Provide a session reference or use --current to revoke the current session.");
5900
6565
  }
5901
- if (isJson) {
5902
- outputResult({
5903
- referenceNumbers: result.referenceNumbers,
5904
- iterationCount: result.iterationCount,
5905
- totalParts: result.decryptedParts.length,
5906
- continuationPoints: result.continuationPoints,
5907
- outputDir
5908
- }, { json: true });
6566
+ });
6567
+ }
6568
+ });
6569
+ var invoice = defineCommand3({
6570
+ meta: { name: "invoice", description: "Get single invoice status in a session" },
6571
+ args: {
6572
+ invoiceRef: { type: "positional", description: "Invoice reference number", required: true },
6573
+ ref: { type: "string", description: "Session reference (uses stored ref if omitted)" },
6574
+ env: { type: "string", description: "Environment (test/demo/prod)" },
6575
+ json: { type: "boolean", description: "Output as JSON" },
6576
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
6577
+ timeout: { type: "string", description: "Request timeout (ms)" }
6578
+ },
6579
+ run({ args }) {
6580
+ return withErrorHandler(async () => {
6581
+ const globalOpts = getGlobalOpts2(args);
6582
+ const { client, session } = await requireSession(globalOpts);
6583
+ const sessionRef = args.ref ?? session.onlineSessionRef;
6584
+ if (!sessionRef) {
6585
+ throw new Error("No session reference. Provide --ref or run `ksef session open` first.");
6586
+ }
6587
+ const result = await client.sessionStatus.getSessionInvoice(sessionRef, args.invoiceRef);
6588
+ if (args.json) {
6589
+ outputResult(result, { json: true });
5909
6590
  } else {
5910
- outputSuccess(
5911
- `Export complete: ${result.iterationCount} iterations, ${result.decryptedParts.length} parts downloaded`
5912
- );
5913
- consola8.info(`Final HWM: ${continuationPoints[subjectType] ?? "complete"}`);
5914
- consola8.info(`Output: ${outputDir}`);
6591
+ outputKeyValue({
6592
+ "Ordinal": result.ordinalNumber,
6593
+ "Invoice Number": result.invoiceNumber ?? "N/A",
6594
+ "KSeF Number": result.ksefNumber ?? "N/A",
6595
+ "Reference": result.referenceNumber,
6596
+ "Hash": result.invoiceHash,
6597
+ "Status": `${result.status.code} \u2014 ${result.status.description}`,
6598
+ "Invoicing Date": result.invoicingDate,
6599
+ "Invoicing Mode": result.invoicingMode ?? "N/A"
6600
+ }, { json: false });
5915
6601
  }
5916
6602
  });
5917
6603
  }
5918
6604
  });
6605
+ var sessionCommand = defineCommand3({
6606
+ meta: { name: "session", description: "Session management commands" },
6607
+ subCommands: { open, close, status: status2, list, invoices, failed, upo, active, revoke, invoice }
6608
+ });
5919
6609
 
5920
- // src/validation/xml-to-object.ts
5921
- import { DOMParser as DOMParser2 } from "@xmldom/xmldom";
5922
- function xmlToObject(xml) {
5923
- const errors = [];
5924
- const doc = new DOMParser2({
5925
- errorHandler: {
5926
- warning: (_msg) => {
5927
- },
5928
- error: (msg) => errors.push(msg),
5929
- fatalError: (msg) => errors.push(msg)
5930
- }
5931
- }).parseFromString(xml, "text/xml");
5932
- if (errors.length > 0 || !doc || !doc.documentElement) {
5933
- return { object: null, rootElement: null, namespace: null, errors };
5934
- }
5935
- const root = doc.documentElement;
5936
- const rootName = getLocalName(root);
5937
- const namespace = root.namespaceURI || null;
5938
- const obj = elementToObject(root);
5939
- return {
5940
- object: typeof obj === "object" && obj !== null ? obj : { "#text": obj },
5941
- rootElement: rootName,
5942
- namespace,
5943
- errors: []
5944
- };
5945
- }
5946
- function getLocalName(node) {
5947
- if (node.localName) return node.localName;
5948
- const name = node.nodeName;
5949
- const idx = name.indexOf(":");
5950
- return idx === -1 ? name : name.substring(idx + 1);
5951
- }
5952
- function elementToObject(el) {
5953
- const result = {};
5954
- let hasChildElements = false;
5955
- for (let i = 0; i < el.attributes.length; i++) {
5956
- const a = el.attributes.item(i);
5957
- if (!a) continue;
5958
- const name = a.nodeName;
5959
- if (name === "xmlns" || name.startsWith("xmlns:")) continue;
5960
- const attrLocal = getLocalName(a);
5961
- result[`@${attrLocal}`] = a.value;
5962
- }
5963
- const childCounts = /* @__PURE__ */ new Map();
5964
- for (let i = 0; i < el.childNodes.length; i++) {
5965
- const child = el.childNodes.item(i);
5966
- if (!child || child.nodeType !== 1) continue;
5967
- const name = getLocalName(child);
5968
- childCounts.set(name, (childCounts.get(name) || 0) + 1);
5969
- hasChildElements = true;
5970
- }
5971
- if (!hasChildElements) {
5972
- const text = getTextContent(el);
5973
- const hasAttrs = Object.keys(result).length > 0;
5974
- if (hasAttrs) {
5975
- result["#text"] = text;
5976
- return result;
5977
- }
5978
- return text;
6610
+ // src/cli/commands/invoice.ts
6611
+ import * as fs9 from "fs";
6612
+ import * as path6 from "path";
6613
+ import { Readable } from "stream";
6614
+ import { defineCommand as defineCommand5 } from "citty";
6615
+ import { consola as consola9 } from "consola";
6616
+ init_document_structures();
6617
+
6618
+ // src/cli/commands/export-incremental.ts
6619
+ import * as fs8 from "fs";
6620
+ import * as path5 from "path";
6621
+ import { defineCommand as defineCommand4 } from "citty";
6622
+ import { consola as consola8 } from "consola";
6623
+
6624
+ // src/workflows/hwm-storage.ts
6625
+ import * as fs7 from "fs/promises";
6626
+ var FileHwmStore = class {
6627
+ constructor(filePath) {
6628
+ this.filePath = filePath;
5979
6629
  }
5980
- for (let i = 0; i < el.childNodes.length; i++) {
5981
- const child = el.childNodes.item(i);
5982
- if (!child || child.nodeType !== 1) continue;
5983
- const name = getLocalName(child);
5984
- const value = elementToObject(child);
5985
- const count = childCounts.get(name) || 1;
5986
- if (count > 1) {
5987
- if (!Array.isArray(result[name])) {
5988
- result[name] = [];
6630
+ async load() {
6631
+ try {
6632
+ const data = await fs7.readFile(this.filePath, "utf-8");
6633
+ return JSON.parse(data);
6634
+ } catch (err) {
6635
+ if (err.code === "ENOENT") {
6636
+ return {};
5989
6637
  }
5990
- result[name].push(value);
5991
- } else {
5992
- result[name] = value;
6638
+ throw err;
5993
6639
  }
5994
6640
  }
5995
- return result;
5996
- }
5997
- function getTextContent(el) {
5998
- let text = "";
5999
- for (let i = 0; i < el.childNodes.length; i++) {
6000
- const child = el.childNodes.item(i);
6001
- if (!child) continue;
6002
- if (child.nodeType === 3 || child.nodeType === 4) {
6003
- text += child.nodeValue || "";
6004
- }
6641
+ async save(points) {
6642
+ await fs7.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
6005
6643
  }
6006
- return text.trim();
6007
- }
6008
-
6009
- // src/validation/schemas/index.ts
6010
- init_fa3();
6011
- init_fa2();
6012
- init_rr1_v11e();
6013
- init_rr1_v10e();
6014
- init_pef3();
6015
- init_pef_kor3();
6016
- var SCHEMA_TYPES = ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
6017
- var NAMESPACE_MAP = {
6018
- "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
6019
- "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
6020
- "http://crd.gov.pl/wzor/2026/03/06/14189/": "RR1_V11E",
6021
- "http://crd.gov.pl/wzor/2026/02/17/14164/": "RR1_V10E",
6022
- "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2": "PEF3",
6023
- "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2": "PEF_KOR3"
6024
6644
  };
6025
6645
 
6026
- // src/validation/schema-registry.ts
6027
- var ROOT_ELEMENT_MAP = {
6028
- Invoice: "PEF3",
6029
- CreditNote: "PEF_KOR3"
6030
- };
6031
- var schemaCache = /* @__PURE__ */ new Map();
6032
- async function loadSchema(type) {
6033
- const cached = schemaCache.get(type);
6034
- if (cached) return cached;
6035
- let mod;
6036
- switch (type) {
6037
- case "FA3":
6038
- mod = await Promise.resolve().then(() => (init_fa3(), fa3_exports));
6039
- break;
6040
- case "FA2":
6041
- mod = await Promise.resolve().then(() => (init_fa2(), fa2_exports));
6042
- break;
6043
- case "RR1_V11E":
6044
- mod = await Promise.resolve().then(() => (init_rr1_v11e(), rr1_v11e_exports));
6045
- break;
6046
- case "RR1_V10E":
6047
- mod = await Promise.resolve().then(() => (init_rr1_v10e(), rr1_v10e_exports));
6048
- break;
6049
- case "PEF3":
6050
- mod = await Promise.resolve().then(() => (init_pef3(), pef3_exports));
6051
- break;
6052
- case "PEF_KOR3":
6053
- mod = await Promise.resolve().then(() => (init_pef_kor3(), pef_kor3_exports));
6054
- break;
6055
- default:
6056
- throw new Error(`Unknown schema type: ${type}`);
6646
+ // src/workflows/invoice-export-workflow.ts
6647
+ init_zip();
6648
+ init_polling();
6649
+ async function doExport(client, filters, options) {
6650
+ await client.crypto.init();
6651
+ const encData = client.crypto.getEncryptionData();
6652
+ const opResp = await client.invoices.exportInvoices({
6653
+ encryption: encData.encryptionInfo,
6654
+ filters,
6655
+ onlyMetadata: options?.onlyMetadata
6656
+ });
6657
+ const result = await pollUntil(
6658
+ () => client.invoices.getInvoiceExportStatus(opResp.referenceNumber),
6659
+ (s) => s.status.code === 200 || s.status.code >= 400,
6660
+ { ...options?.pollOptions, description: `export ${opResp.referenceNumber}` }
6661
+ );
6662
+ if (result.status.code !== 200) {
6663
+ throw new Error(`Export failed: ${result.status.code} \u2014 ${result.status.description}`);
6057
6664
  }
6058
- const exportName = `${type}Schema`;
6059
- const schema = mod[exportName];
6060
- if (!schema) {
6061
- throw new Error(`Schema export "${exportName}" not found in module for type "${type}"`);
6665
+ if (!result.package) {
6666
+ throw new Error("Export completed but no package available");
6062
6667
  }
6063
- schemaCache.set(type, schema);
6064
- return schema;
6065
- }
6066
- var SchemaRegistry = {
6067
- /**
6068
- * Get a Zod schema by type. Lazy-loads the module on first access.
6069
- */
6070
- async get(type) {
6071
- return loadSchema(type);
6072
- },
6073
- /**
6074
- * List all available schema types.
6075
- */
6076
- availableSchemas() {
6077
- return ["FA3", "FA2", "RR1_V11E", "RR1_V10E", "PEF3", "PEF_KOR3"];
6078
- },
6079
- /**
6080
- * Detect schema type from XML namespace URI and/or root element name.
6081
- *
6082
- * Detection priority:
6083
- * 1. Namespace URI match (unique per FA/RR schemas)
6084
- * 2. Root element name match (for PEF/PEF_KOR which use UBL namespaces)
6085
- */
6086
- detect(namespace, rootElement) {
6087
- if (namespace) {
6088
- const byNs = NAMESPACE_MAP[namespace];
6089
- if (byNs) return byNs;
6090
- }
6091
- if (rootElement) {
6092
- const byRoot = ROOT_ELEMENT_MAP[rootElement];
6093
- if (byRoot) return byRoot;
6668
+ return {
6669
+ encData,
6670
+ referenceNumber: opResp.referenceNumber,
6671
+ result: {
6672
+ parts: result.package.parts.map((p) => ({
6673
+ ordinalNumber: p.ordinalNumber,
6674
+ url: p.url,
6675
+ method: p.method,
6676
+ partSize: p.partSize,
6677
+ encryptedPartSize: p.encryptedPartSize,
6678
+ encryptedPartHash: p.encryptedPartHash,
6679
+ expirationDate: p.expirationDate
6680
+ })),
6681
+ invoiceCount: result.package.invoiceCount,
6682
+ isTruncated: result.package.isTruncated,
6683
+ permanentStorageHwmDate: result.package.permanentStorageHwmDate,
6684
+ lastPermanentStorageDate: result.package.lastPermanentStorageDate
6094
6685
  }
6095
- return null;
6096
- }
6097
- };
6686
+ };
6687
+ }
6098
6688
 
6099
- // src/validation/patterns.ts
6100
- var NIP_PATTERN_CORE = "[1-9]((\\d[1-9])|([1-9]\\d))\\d{7}";
6101
- var VAT_UE_PATTERN_CORE = "(ATU\\d{8}|BE[01]{1}\\d{9}|BG\\d{9,10}|CY\\d{8}[A-Z]|CZ\\d{8,10}|DE\\d{9}|DK\\d{8}|EE\\d{9}|EL\\d{9}|ES([A-Z]\\d{8}|\\d{8}[A-Z]|[A-Z]\\d{7}[A-Z])|FI\\d{8}|FR[A-Z0-9]{2}\\d{9}|HR\\d{11}|HU\\d{8}|IE(\\d{7}[A-Z]{2}|\\d[A-Z0-9+*]\\d{5}[A-Z])|IT\\d{11}|LT(\\d{9}|\\d{12})|LU\\d{8}|LV\\d{11}|MT\\d{8}|NL[A-Z0-9+*]{12}|PT\\d{9}|RO\\d{2,10}|SE\\d{12}|SI\\d{8}|SK\\d{10}|XI((\\d{9}|\\d{12})|(GD|HA)\\d{3}))";
6102
- var Nip = new RegExp(`^${NIP_PATTERN_CORE}$`);
6103
- var VatUe = new RegExp(`^${VAT_UE_PATTERN_CORE}$`);
6104
- var NipVatUe = new RegExp(`^${NIP_PATTERN_CORE}-${VAT_UE_PATTERN_CORE}$`);
6105
- var Pesel = /^\d{2}(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|4[1-9]|5[0-2]|6[1-9]|7[0-2]|8[1-9]|9[0-2])\d{7}$/;
6106
- var NIP_WEIGHTS = [6, 5, 7, 2, 3, 4, 5, 6, 7];
6107
- var PESEL_WEIGHTS = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3];
6108
- function isValidNip(value) {
6109
- if (!Nip.test(value)) return false;
6110
- let sum = 0;
6111
- for (let i = 0; i < 9; i++) {
6112
- sum += Number(value[i]) * NIP_WEIGHTS[i];
6689
+ // src/workflows/hwm-coordinator.ts
6690
+ function updateContinuationPoint(points, subjectType, pkg2) {
6691
+ if (pkg2.isTruncated && pkg2.lastPermanentStorageDate) {
6692
+ points[subjectType] = pkg2.lastPermanentStorageDate;
6693
+ } else if (pkg2.permanentStorageHwmDate) {
6694
+ points[subjectType] = pkg2.permanentStorageHwmDate;
6695
+ } else {
6696
+ delete points[subjectType];
6113
6697
  }
6114
- const checksum = sum % 11;
6115
- return checksum !== 10 && checksum === Number(value[9]);
6116
6698
  }
6117
- function isValidPesel(value) {
6118
- if (!Pesel.test(value)) return false;
6119
- let sum = 0;
6120
- for (let i = 0; i < 10; i++) {
6121
- sum += Number(value[i]) * PESEL_WEIGHTS[i];
6122
- }
6123
- const checksum = (10 - sum % 10) % 10;
6124
- return checksum === Number(value[10]);
6699
+ function getEffectiveStartDate(points, subjectType, windowFrom) {
6700
+ return points[subjectType] ?? windowFrom;
6125
6701
  }
6126
6702
 
6127
- // src/validation/invoice-validator.ts
6128
- function validateWellFormedness(xml, _parsed) {
6129
- if (!xml || !xml.trim()) {
6130
- return {
6131
- valid: false,
6132
- schemaType: null,
6133
- errors: [{ code: "MALFORMED_XML", message: "Empty XML input" }]
6134
- };
6703
+ // src/workflows/incremental-export-workflow.ts
6704
+ async function incrementalExportAndDownload(client, options) {
6705
+ const maxIterations = options.maxIterations ?? 20;
6706
+ const points = options.continuationPoints;
6707
+ if (options.store) {
6708
+ const loaded = await options.store.load();
6709
+ for (const [key, value] of Object.entries(loaded)) {
6710
+ if (value !== void 0 && points[key] === void 0) {
6711
+ points[key] = value;
6712
+ }
6713
+ }
6135
6714
  }
6136
- const { object, rootElement, namespace, errors } = _parsed ?? xmlToObject(xml);
6137
- if (errors.length > 0 || !object) {
6138
- return {
6139
- valid: false,
6140
- schemaType: null,
6141
- errors: errors.map((msg) => ({ code: "MALFORMED_XML", message: msg }))
6142
- };
6715
+ const referenceNumbers = [];
6716
+ const decryptedParts = [];
6717
+ let previousFrom;
6718
+ let iteration = 0;
6719
+ for (; iteration < maxIterations; iteration++) {
6720
+ const effectiveFrom = getEffectiveStartDate(points, options.subjectType, options.windowFrom);
6721
+ if (previousFrom !== void 0 && effectiveFrom === previousFrom) {
6722
+ break;
6723
+ }
6724
+ previousFrom = effectiveFrom;
6725
+ const filters = options.filtersFactory ? options.filtersFactory(effectiveFrom, options.windowTo) : buildDefaultFilters(options.subjectType, effectiveFrom, options.windowTo);
6726
+ const { result, encData, referenceNumber } = await doExport(client, filters, {
6727
+ onlyMetadata: options.onlyMetadata,
6728
+ pollOptions: options.pollOptions
6729
+ });
6730
+ referenceNumbers.push(referenceNumber);
6731
+ const download = options.transport ?? fetch;
6732
+ for (const part of result.parts) {
6733
+ const resp = await download(part.url, { method: part.method });
6734
+ if (!resp.ok) {
6735
+ throw new Error(`Download failed for part ${part.ordinalNumber}: HTTP ${resp.status}`);
6736
+ }
6737
+ const encryptedData = new Uint8Array(await resp.arrayBuffer());
6738
+ const decrypted = client.crypto.decryptAES256(encryptedData, encData.cipherKey, encData.cipherIv);
6739
+ decryptedParts.push(decrypted);
6740
+ }
6741
+ updateContinuationPoint(points, options.subjectType, {
6742
+ isTruncated: result.isTruncated,
6743
+ lastPermanentStorageDate: result.lastPermanentStorageDate,
6744
+ permanentStorageHwmDate: result.permanentStorageHwmDate
6745
+ });
6746
+ if (options.store) {
6747
+ await options.store.save(points);
6748
+ }
6749
+ options.onIterationComplete?.(iteration, result);
6750
+ if (!result.isTruncated) {
6751
+ iteration++;
6752
+ break;
6753
+ }
6143
6754
  }
6144
- const schemaType = SchemaRegistry.detect(namespace, rootElement);
6145
- return { valid: true, schemaType, errors: [] };
6755
+ return {
6756
+ referenceNumbers,
6757
+ invoices: [],
6758
+ decryptedParts,
6759
+ continuationPoints: points,
6760
+ iterationCount: iteration
6761
+ };
6146
6762
  }
6147
- async function validateSchema(xml, options, _parsed) {
6148
- const { object, rootElement, namespace, errors: parseErrors } = _parsed ?? xmlToObject(xml);
6149
- if (parseErrors.length > 0 || !object) {
6150
- return {
6151
- valid: false,
6152
- schemaType: null,
6153
- errors: parseErrors.map((msg) => ({ code: "MALFORMED_XML", message: msg }))
6154
- };
6155
- }
6156
- const schemaType = options?.schema ?? SchemaRegistry.detect(namespace, rootElement);
6157
- if (!schemaType) {
6158
- return {
6159
- valid: false,
6160
- schemaType: null,
6161
- errors: [{
6162
- code: "UNKNOWN_SCHEMA",
6163
- message: `Cannot detect schema type from namespace "${namespace}" and root element "${rootElement}"`
6164
- }]
6165
- };
6166
- }
6167
- const schema = await SchemaRegistry.get(schemaType);
6168
- const result = schema.safeParse(object);
6169
- if (result.success) {
6170
- return { valid: true, schemaType, errors: [] };
6171
- }
6172
- const prefix = rootElement ? `/${rootElement}/` : "/";
6173
- const validationErrors = result.error.issues.map((issue) => {
6174
- const zodPath = issue.path.join("/");
6175
- const path9 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
6176
- return {
6177
- code: mapZodErrorCode(issue),
6178
- message: issue.message,
6179
- path: path9
6180
- };
6181
- });
6182
- return { valid: false, schemaType, errors: validationErrors };
6763
+ function buildDefaultFilters(subjectType, from, to) {
6764
+ return {
6765
+ subjectType,
6766
+ dateRange: {
6767
+ dateType: "PermanentStorage",
6768
+ from,
6769
+ to
6770
+ }
6771
+ };
6183
6772
  }
6184
- function mapZodErrorCode(issue) {
6185
- switch (issue.code) {
6186
- case "invalid_type":
6187
- return issue.input === void 0 ? "MISSING_REQUIRED_ELEMENT" : "INVALID_VALUE";
6188
- case "invalid_enum_value":
6189
- // Zod v3
6190
- case "invalid_value":
6191
- return "INVALID_ENUM_VALUE";
6192
- case "invalid_string":
6193
- // Zod v3
6194
- case "invalid_format":
6195
- return "PATTERN_MISMATCH";
6196
- case "too_big":
6197
- return "MAX_OCCURS_EXCEEDED";
6198
- default:
6199
- return "SCHEMA_VALIDATION_ERROR";
6773
+
6774
+ // src/cli/date-utils.ts
6775
+ var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
6776
+ function normalizeCliDate(date, position) {
6777
+ if (!DATE_ONLY_RE.test(date)) return date;
6778
+ if (isNaN(new Date(date).getTime())) {
6779
+ throw new Error(`Invalid date: "${date}". Expected a valid YYYY-MM-DD date.`);
6200
6780
  }
6781
+ return position === "from" ? `${date}T00:00:00+00:00` : `${date}T23:59:59.999+00:00`;
6201
6782
  }
6202
- function validateBusinessRules(xml, _parsed) {
6203
- const { object, rootElement, namespace, errors: parseErrors } = _parsed ?? xmlToObject(xml);
6204
- if (parseErrors.length > 0 || !object) {
6205
- return {
6206
- valid: false,
6207
- schemaType: null,
6208
- errors: parseErrors.map((msg) => ({ code: "MALFORMED_XML", message: msg }))
6209
- };
6210
- }
6211
- const schemaType = SchemaRegistry.detect(namespace, rootElement);
6212
- const errors = [];
6213
- collectNipPeselErrors(object, rootElement ? `/${rootElement}` : "", errors);
6214
- collectDateErrors(object, rootElement, errors);
6215
- return { valid: errors.length === 0, schemaType, errors };
6783
+
6784
+ // src/cli/commands/export-incremental.ts
6785
+ function getGlobalOpts3(args) {
6786
+ return {
6787
+ env: args.env,
6788
+ json: args.json,
6789
+ verbose: args.verbose,
6790
+ timeout: args.timeout,
6791
+ nip: args.nip
6792
+ };
6216
6793
  }
6217
- function collectNipPeselErrors(obj, path9, errors) {
6218
- for (const [key, value] of Object.entries(obj)) {
6219
- const currentPath = path9 ? `${path9}/${key}` : key;
6220
- if (key === "NIP" && typeof value === "string") {
6221
- if (!isValidNip(value)) {
6222
- errors.push({
6223
- code: "INVALID_NIP_CHECKSUM",
6224
- message: `Invalid NIP checksum: ${value}`,
6225
- path: currentPath
6226
- });
6227
- }
6228
- } else if (key === "PESEL" && typeof value === "string") {
6229
- if (!isValidPesel(value)) {
6230
- errors.push({
6231
- code: "INVALID_PESEL_CHECKSUM",
6232
- message: `Invalid PESEL checksum: ${value}`,
6233
- path: currentPath
6234
- });
6794
+ var exportIncremental = defineCommand4({
6795
+ meta: { name: "export-incremental", description: "Incremental invoice export with HWM state persistence" },
6796
+ args: {
6797
+ from: { type: "string", description: "Start date (YYYY-MM-DD) \u2014 required", required: true },
6798
+ to: { type: "string", description: "End date (YYYY-MM-DD)" },
6799
+ subjectType: { type: "string", description: "Subject type: Subject1|Subject2|Subject3|SubjectAuthorized (default: Subject1)" },
6800
+ stateFile: { type: "string", description: "HWM state file path (default: ./ksef-hwm-state.json)" },
6801
+ outputDir: { type: "string", description: "Output directory for exported parts (default: ./ksef-exports/)" },
6802
+ maxIterations: { type: "string", description: "Max export iterations (default: 20)" },
6803
+ onlyMetadata: { type: "boolean", description: "Export metadata only (no invoice XML)" },
6804
+ env: { type: "string", description: "Environment (test/demo/prod)" },
6805
+ json: { type: "boolean", description: "Output as JSON" },
6806
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
6807
+ timeout: { type: "string", description: "Request timeout (ms)" },
6808
+ nip: { type: "string", description: "NIP number" }
6809
+ },
6810
+ run({ args }) {
6811
+ return withErrorHandler(async () => {
6812
+ const globalOpts = getGlobalOpts3(args);
6813
+ const { client } = await requireSession(globalOpts);
6814
+ const from = normalizeCliDate(args.from, "from");
6815
+ const to = normalizeCliDate(args.to ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), "to");
6816
+ const subjectType = args.subjectType ?? "Subject1";
6817
+ const stateFile = args.stateFile ?? "./ksef-hwm-state.json";
6818
+ const outputDir = args.outputDir ?? "./ksef-exports";
6819
+ const maxIterations = args.maxIterations ? parseInt(args.maxIterations, 10) : 20;
6820
+ const isJson = args.json;
6821
+ const store = new FileHwmStore(stateFile);
6822
+ const continuationPoints = {};
6823
+ if (!fs8.existsSync(outputDir)) {
6824
+ fs8.mkdirSync(outputDir, { recursive: true });
6235
6825
  }
6236
- } else if (typeof value === "object" && value !== null) {
6237
- if (Array.isArray(value)) {
6238
- for (let i = 0; i < value.length; i++) {
6239
- if (typeof value[i] === "object" && value[i] !== null) {
6240
- collectNipPeselErrors(value[i], `${currentPath}/${i}`, errors);
6826
+ if (!isJson) {
6827
+ consola8.start(`Incremental export: ${from} \u2192 ${to}, subject: ${subjectType}`);
6828
+ consola8.info(`State file: ${stateFile}`);
6829
+ consola8.info(`Output dir: ${outputDir}`);
6830
+ }
6831
+ const iterationParts = [];
6832
+ const result = await incrementalExportAndDownload(client, {
6833
+ subjectType,
6834
+ windowFrom: from,
6835
+ windowTo: to,
6836
+ continuationPoints,
6837
+ maxIterations,
6838
+ onlyMetadata: args.onlyMetadata,
6839
+ store,
6840
+ pollOptions: { intervalMs: 2e3 },
6841
+ onIterationComplete: (iteration, iterResult) => {
6842
+ iterationParts.push({ iteration, partCount: iterResult.parts.length });
6843
+ if (!isJson) {
6844
+ const hwmDate = continuationPoints[subjectType] ?? "complete";
6845
+ consola8.info(
6846
+ `Iteration ${iteration + 1}: ${iterResult.invoiceCount} invoices, truncated: ${iterResult.isTruncated}, HWM: ${hwmDate}`
6847
+ );
6848
+ }
6849
+ }
6850
+ });
6851
+ let partIndex = 0;
6852
+ for (const { iteration, partCount } of iterationParts) {
6853
+ for (let p = 0; p < partCount; p++) {
6854
+ if (partIndex < result.decryptedParts.length) {
6855
+ const fileName = `iter-${String(iteration + 1).padStart(3, "0")}-part-${String(p + 1).padStart(3, "0")}.zip`;
6856
+ const filePath = path5.join(outputDir, fileName);
6857
+ fs8.writeFileSync(filePath, result.decryptedParts[partIndex]);
6858
+ partIndex++;
6241
6859
  }
6242
6860
  }
6861
+ }
6862
+ if (isJson) {
6863
+ outputResult({
6864
+ referenceNumbers: result.referenceNumbers,
6865
+ iterationCount: result.iterationCount,
6866
+ totalParts: result.decryptedParts.length,
6867
+ continuationPoints: result.continuationPoints,
6868
+ outputDir
6869
+ }, { json: true });
6243
6870
  } else {
6244
- collectNipPeselErrors(value, currentPath, errors);
6871
+ outputSuccess(
6872
+ `Export complete: ${result.iterationCount} iterations, ${result.decryptedParts.length} parts downloaded`
6873
+ );
6874
+ consola8.info(`Final HWM: ${continuationPoints[subjectType] ?? "complete"}`);
6875
+ consola8.info(`Output: ${outputDir}`);
6245
6876
  }
6246
- }
6247
- }
6248
- }
6249
- function getPolandLocalDate() {
6250
- return new Intl.DateTimeFormat("sv-SE", { timeZone: "Europe/Warsaw" }).format(Date.now());
6251
- }
6252
- function collectDateErrors(obj, rootElement, errors) {
6253
- const fa = obj["Fa"];
6254
- if (!fa || typeof fa !== "object") return;
6255
- const p1 = fa["P_1"];
6256
- if (typeof p1 !== "string") return;
6257
- const today = getPolandLocalDate();
6258
- if (p1 > today) {
6259
- const prefix = rootElement ? `/${rootElement}` : "";
6260
- errors.push({
6261
- code: "FUTURE_INVOICE_DATE",
6262
- message: `Invoice date P_1 (${p1}) is in the future \u2014 KSeF rejects invoices with P_1 > today (${today})`,
6263
- path: `${prefix}/Fa/P_1`
6264
6877
  });
6265
6878
  }
6266
- }
6267
- async function validate(xml, options) {
6268
- const parsed = xml && xml.trim() ? xmlToObject(xml) : void 0;
6269
- const l1 = validateWellFormedness(xml, parsed);
6270
- if (!l1.valid) return l1;
6271
- const l2 = await validateSchema(xml, options, parsed);
6272
- if (!l2.valid) return l2;
6273
- const l3 = validateBusinessRules(xml, parsed);
6274
- return { ...l3, schemaType: l2.schemaType };
6275
- }
6879
+ });
6276
6880
 
6277
6881
  // src/cli/commands/invoice.ts
6882
+ init_invoice_validator();
6278
6883
  init_ksef_validation_error();
6884
+ init_schemas();
6279
6885
  function getGlobalOpts4(args) {
6280
6886
  return {
6281
6887
  env: args.env,
@@ -6365,7 +6971,7 @@ var send = defineCommand5({
6365
6971
  const stat = fs9.statSync(filePath);
6366
6972
  if (args.stream) {
6367
6973
  if (args.validate) {
6368
- consola9.warn("--validate is only supported for single-file sends, skipping validation.");
6974
+ consola9.warn("--validate is not supported in stream mode. Run `ksef invoice validate <path>` before sending, or remove --stream.");
6369
6975
  }
6370
6976
  if (!filePath.endsWith(".zip") || stat.isDirectory()) {
6371
6977
  throw new Error("--stream requires a .zip file path.");
@@ -6392,9 +6998,6 @@ var send = defineCommand5({
6392
6998
  return;
6393
6999
  }
6394
7000
  if (stat.isDirectory()) {
6395
- if (args.validate) {
6396
- consola9.warn("--validate is only supported for single-file sends, skipping validation.");
6397
- }
6398
7001
  const xmlFiles = fs9.readdirSync(filePath).filter((f) => f.endsWith(".xml")).map((f) => path6.join(filePath, f));
6399
7002
  if (xmlFiles.length === 0) {
6400
7003
  throw new Error(`No XML files found in ${filePath}`);
@@ -6405,11 +7008,28 @@ var send = defineCommand5({
6405
7008
  if (!validateFormCodeForSession(formCode, "batch")) {
6406
7009
  throw new Error(`Document type "${formCode.systemCode}" is not supported in batch sessions. PEF/PEF_KOR require online sessions.`);
6407
7010
  }
7011
+ const fileBuffers = xmlFiles.map((file) => ({ file, content: fs9.readFileSync(file) }));
7012
+ if (args.validate) {
7013
+ const { validateBatch: validateBatch2, batchValidationDetails: batchValidationDetails2 } = await Promise.resolve().then(() => (init_invoice_validator(), invoice_validator_exports));
7014
+ const invoicesToValidate = fileBuffers.map(({ file, content }) => ({
7015
+ fileName: path6.basename(file),
7016
+ xml: content.toString("utf-8")
7017
+ }));
7018
+ if (!args.json) consola9.start(`Validating ${invoicesToValidate.length} invoices...`);
7019
+ const batchResult = await validateBatch2(invoicesToValidate);
7020
+ if (!batchResult.valid) {
7021
+ const invalidCount = batchResult.results.filter((r) => !r.result.valid).length;
7022
+ throw new KSeFValidationError(
7023
+ `Validation failed: ${invalidCount} of ${xmlFiles.length} invoices invalid`,
7024
+ batchValidationDetails2(batchResult)
7025
+ );
7026
+ }
7027
+ if (!args.json) consola9.success(`All ${xmlFiles.length} invoices valid.`);
7028
+ }
6408
7029
  if (!args.json) consola9.start(`Sending ${xmlFiles.length} invoices via batch session...`);
6409
7030
  await client.crypto.init();
6410
7031
  const encryptionData = client.crypto.getEncryptionData();
6411
- const parts = xmlFiles.map((file, i) => {
6412
- const content = fs9.readFileSync(file);
7032
+ const parts = fileBuffers.map(({ content }, i) => {
6413
7033
  const metadata = client.crypto.getFileMetadata(new Uint8Array(content));
6414
7034
  return {
6415
7035
  data: content.buffer,
@@ -6417,7 +7037,7 @@ var send = defineCommand5({
6417
7037
  ordinalNumber: i + 1
6418
7038
  };
6419
7039
  });
6420
- const totalContent = Buffer.concat(xmlFiles.map((f) => fs9.readFileSync(f)));
7040
+ const totalContent = Buffer.concat(fileBuffers.map(({ content }) => content));
6421
7041
  const totalMetadata = client.crypto.getFileMetadata(new Uint8Array(totalContent));
6422
7042
  const batchFileInfo = {
6423
7043
  fileSize: totalMetadata.fileSize,
@@ -6572,6 +7192,7 @@ var exportCmd = defineCommand5({
6572
7192
  meta: { name: "export", description: "Start invoice export" },
6573
7193
  args: {
6574
7194
  ...QUERY_FILTER_ARGS,
7195
+ onlyMetadata: { type: "boolean", description: "Export metadata only (no invoice XML)" },
6575
7196
  env: { type: "string", description: "Environment (test/demo/prod)" },
6576
7197
  json: { type: "boolean", description: "Output as JSON" },
6577
7198
  verbose: { type: "boolean", description: "Show HTTP request/response details" },
@@ -6587,7 +7208,7 @@ var exportCmd = defineCommand5({
6587
7208
  const encryptionData = client.crypto.getEncryptionData();
6588
7209
  const filters = buildQueryFilters(args);
6589
7210
  const result = await client.invoices.exportInvoices(
6590
- { encryption: encryptionData.encryptionInfo, filters }
7211
+ { encryption: encryptionData.encryptionInfo, filters, onlyMetadata: args.onlyMetadata }
6591
7212
  );
6592
7213
  if (args.json) {
6593
7214
  outputResult(result, { json: true });
@@ -7415,12 +8036,12 @@ import fs10 from "fs";
7415
8036
  import path7 from "path";
7416
8037
 
7417
8038
  // src/crypto/certificate-service.ts
7418
- import * as crypto5 from "crypto";
8039
+ import * as crypto6 from "crypto";
7419
8040
  import * as x5092 from "@peculiar/x509";
7420
8041
  var CertificateService = class {
7421
8042
  static getSha256Fingerprint(certPem) {
7422
8043
  const der = extractDerFromPem2(certPem);
7423
- return crypto5.createHash("sha256").update(der).digest("hex").toUpperCase();
8044
+ return crypto6.createHash("sha256").update(der).digest("hex").toUpperCase();
7424
8045
  }
7425
8046
  static async generatePersonalCertificate(givenName, surname, serialNumber, commonName, method = "RSA") {
7426
8047
  const nameParts = [];
@@ -7443,7 +8064,7 @@ var CertificateService = class {
7443
8064
  }
7444
8065
  };
7445
8066
  async function generateSelfSigned(subject2, method) {
7446
- x5092.cryptoProvider.set(crypto5.webcrypto);
8067
+ x5092.cryptoProvider.set(crypto6.webcrypto);
7447
8068
  let algorithm;
7448
8069
  let signingAlgorithm;
7449
8070
  if (method === "ECDSA") {
@@ -7458,7 +8079,7 @@ async function generateSelfSigned(subject2, method) {
7458
8079
  };
7459
8080
  signingAlgorithm = algorithm;
7460
8081
  }
7461
- const keys = await crypto5.webcrypto.subtle.generateKey(
8082
+ const keys = await crypto6.webcrypto.subtle.generateKey(
7462
8083
  algorithm,
7463
8084
  true,
7464
8085
  ["sign", "verify"]
@@ -7475,9 +8096,9 @@ async function generateSelfSigned(subject2, method) {
7475
8096
  serialNumber: Date.now().toString(16)
7476
8097
  });
7477
8098
  const certPem = cert.toString("pem");
7478
- const pkcs8 = await crypto5.webcrypto.subtle.exportKey("pkcs8", keys.privateKey);
8099
+ const pkcs8 = await crypto6.webcrypto.subtle.exportKey("pkcs8", keys.privateKey);
7479
8100
  const privateKeyPem = pemEncode2(new Uint8Array(pkcs8), "PRIVATE KEY");
7480
- const fingerprint = crypto5.createHash("sha256").update(Buffer.from(cert.rawData)).digest("hex").toUpperCase();
8101
+ const fingerprint = crypto6.createHash("sha256").update(Buffer.from(cert.rawData)).digest("hex").toUpperCase();
7481
8102
  return { certificatePem: certPem, privateKeyPem, fingerprint };
7482
8103
  }
7483
8104
  function extractDerFromPem2(pem) {
@@ -7935,6 +8556,7 @@ var invoice2 = defineCommand9({
7935
8556
  format: { type: "string", description: "Output format: png or svg (default: png)" },
7936
8557
  size: { type: "string", description: "QR code size in pixels (default: 300)" },
7937
8558
  label: { type: "string", description: "Label text (SVG only)" },
8559
+ offline: { type: "boolean", description: 'Use "OFFLINE" as label (SVG, overrides --label)' },
7938
8560
  o: { type: "string", description: "Output file path" },
7939
8561
  env: { type: "string", description: "Environment (test/demo/prod)" },
7940
8562
  json: { type: "boolean", description: "Output as JSON" },
@@ -7954,7 +8576,8 @@ var invoice2 = defineCommand9({
7954
8576
  return;
7955
8577
  }
7956
8578
  if (format === "svg") {
7957
- const svg = args.label ? await QrCodeService.generateQrCodeSvgWithLabel(url2, args.label, { width: size }) : await QrCodeService.generateQrCodeSvg(url2, { width: size });
8579
+ const effectiveLabel = args.offline ? "OFFLINE" : args.label;
8580
+ const svg = effectiveLabel ? await QrCodeService.generateQrCodeSvgWithLabel(url2, effectiveLabel, { width: size }) : await QrCodeService.generateQrCodeSvg(url2, { width: size });
7958
8581
  if (args.o) {
7959
8582
  fs11.writeFileSync(args.o, svg);
7960
8583
  outputSuccess(`QR code saved to ${args.o}
@@ -8821,11 +9444,11 @@ var doctorCommand = defineCommand14({
8821
9444
  const controller = new AbortController();
8822
9445
  const timeout = setTimeout(() => controller.abort(), 5e3);
8823
9446
  try {
8824
- const status6 = await client.lighthouse.getStatus();
9447
+ const status7 = await client.lighthouse.getStatus();
8825
9448
  checks.push({
8826
9449
  name: "connectivity",
8827
9450
  status: "pass",
8828
- message: `API reachable (${status6.status})`
9451
+ message: `API reachable (${status7.status})`
8829
9452
  });
8830
9453
  } finally {
8831
9454
  clearTimeout(timeout);
@@ -9006,6 +9629,7 @@ import * as path8 from "path";
9006
9629
  import * as os5 from "os";
9007
9630
  import { defineCommand as defineCommand16 } from "citty";
9008
9631
  import { consola as consola14 } from "consola";
9632
+ init_patterns();
9009
9633
  init_auth_xml_builder();
9010
9634
  init_polling();
9011
9635
 
@@ -9268,11 +9892,474 @@ var setupCommand = defineCommand16({
9268
9892
  }
9269
9893
  });
9270
9894
 
9895
+ // src/cli/commands/offline.ts
9896
+ import * as fs14 from "fs";
9897
+ import { defineCommand as defineCommand17 } from "citty";
9898
+ import { consola as consola15 } from "consola";
9899
+
9900
+ // src/offline/file-storage.ts
9901
+ import * as fs13 from "fs/promises";
9902
+ import * as path9 from "path";
9903
+ import * as os6 from "os";
9904
+
9905
+ // src/offline/storage.ts
9906
+ function matchesFilter(invoice3, filter) {
9907
+ if (filter.status !== void 0) {
9908
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
9909
+ if (!statuses.includes(invoice3.status)) return false;
9910
+ }
9911
+ if (filter.mode !== void 0 && invoice3.mode !== filter.mode) return false;
9912
+ if (filter.sellerNip !== void 0 && invoice3.sellerNip !== filter.sellerNip) return false;
9913
+ if (filter.expiringBefore !== void 0) {
9914
+ const cutoff = typeof filter.expiringBefore === "string" ? new Date(filter.expiringBefore).getTime() : filter.expiringBefore.getTime();
9915
+ if (new Date(invoice3.submitBy).getTime() >= cutoff) return false;
9916
+ }
9917
+ return true;
9918
+ }
9919
+
9920
+ // src/offline/file-storage.ts
9921
+ function resolveDir(dir) {
9922
+ if (dir === "~" || dir.startsWith("~/")) {
9923
+ return path9.join(os6.homedir(), dir.slice(1));
9924
+ }
9925
+ return dir;
9926
+ }
9927
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9928
+ function validateId(id) {
9929
+ if (!UUID_RE.test(id)) {
9930
+ throw new Error(`Invalid invoice ID: ${id}`);
9931
+ }
9932
+ }
9933
+ var FileOfflineInvoiceStorage = class {
9934
+ dir;
9935
+ constructor(directory) {
9936
+ this.dir = resolveDir(directory ?? "~/.ksef/offline");
9937
+ }
9938
+ async ensureDir() {
9939
+ await fs13.mkdir(this.dir, { recursive: true });
9940
+ }
9941
+ filePath(id) {
9942
+ validateId(id);
9943
+ return path9.join(this.dir, `${id}.json`);
9944
+ }
9945
+ async save(invoice3) {
9946
+ await this.ensureDir();
9947
+ const file = this.filePath(invoice3.id);
9948
+ const tmp = `${file}.tmp`;
9949
+ await fs13.writeFile(tmp, JSON.stringify(invoice3, null, 2));
9950
+ await fs13.rename(tmp, file);
9951
+ }
9952
+ async get(id) {
9953
+ const file = this.filePath(id);
9954
+ try {
9955
+ return JSON.parse(await fs13.readFile(file, "utf-8"));
9956
+ } catch (err) {
9957
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
9958
+ return null;
9959
+ }
9960
+ console.warn(`Warning: Failed to read offline invoice ${id}: ${err instanceof Error ? err.message : String(err)}`);
9961
+ return null;
9962
+ }
9963
+ }
9964
+ async list(filter) {
9965
+ let files;
9966
+ try {
9967
+ files = (await fs13.readdir(this.dir)).filter((f) => f.endsWith(".json"));
9968
+ } catch {
9969
+ return [];
9970
+ }
9971
+ const results = [];
9972
+ for (const file of files) {
9973
+ try {
9974
+ const data = JSON.parse(
9975
+ await fs13.readFile(path9.join(this.dir, file), "utf-8")
9976
+ );
9977
+ if (!filter || matchesFilter(data, filter)) {
9978
+ results.push(data);
9979
+ }
9980
+ } catch (err) {
9981
+ console.warn(`Warning: Skipping corrupt offline invoice file ${file}: ${err instanceof Error ? err.message : String(err)}`);
9982
+ }
9983
+ }
9984
+ return results;
9985
+ }
9986
+ /**
9987
+ * Update invoice metadata (read-modify-write).
9988
+ *
9989
+ * Note: No file locking — concurrent updates to the same ID may cause
9990
+ * lost writes. Acceptable for CLI (single process). Library consumers
9991
+ * running parallel operations should use external locking.
9992
+ */
9993
+ async update(id, updates) {
9994
+ const existing = await this.get(id);
9995
+ if (!existing) throw new Error(`Offline invoice not found: ${id}`);
9996
+ await this.save({ ...existing, ...updates });
9997
+ }
9998
+ async delete(id) {
9999
+ const file = this.filePath(id);
10000
+ try {
10001
+ await fs13.unlink(file);
10002
+ } catch (e) {
10003
+ if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
10004
+ }
10005
+ }
10006
+ };
10007
+
10008
+ // src/cli/commands/offline.ts
10009
+ init_invoice_field_extractor();
10010
+ function getGlobalOpts14(args) {
10011
+ return {
10012
+ env: args.env,
10013
+ json: args.json,
10014
+ verbose: args.verbose,
10015
+ timeout: args.timeout,
10016
+ nip: args.nip
10017
+ };
10018
+ }
10019
+ function getStorage(args) {
10020
+ return new FileOfflineInvoiceStorage(args["store-dir"]);
10021
+ }
10022
+ var globalArgs = {
10023
+ env: { type: "string", description: "Environment (test/demo/prod)" },
10024
+ json: { type: "boolean", description: "Output as JSON" },
10025
+ verbose: { type: "boolean", description: "Verbose output" },
10026
+ timeout: { type: "string", description: "Request timeout (ms)" },
10027
+ nip: { type: "string", description: "NIP number" },
10028
+ "store-dir": { type: "string", description: "Offline invoice store directory" }
10029
+ };
10030
+ var generate3 = defineCommand17({
10031
+ meta: { name: "generate", description: "Generate offline invoice metadata with QR codes" },
10032
+ args: {
10033
+ ...globalArgs,
10034
+ xml: { type: "positional", description: "Invoice XML file path", required: true },
10035
+ mode: { type: "string", description: "Offline mode (offline24/offline/awaryjny)" },
10036
+ key: { type: "string", description: "Private key PEM file for KOD II signing" },
10037
+ "cert-serial": { type: "string", description: "Certificate serial number (hex)" },
10038
+ "context-type": { type: "string", description: "Seller context type (default: Nip)" },
10039
+ "context-id": { type: "string", description: "Seller context value" },
10040
+ "qr-format": { type: "string", description: "QR format: png or svg (default: png)" },
10041
+ "qr-out": { type: "string", description: "Directory to save QR images" },
10042
+ "no-store": { type: "boolean", description: "Do not save to local store" }
10043
+ },
10044
+ run({ args }) {
10045
+ return withErrorHandler(async () => {
10046
+ const globalOpts = getGlobalOpts14(args);
10047
+ const config = loadConfig();
10048
+ const xmlPath = args.xml;
10049
+ if (!fs14.existsSync(xmlPath)) {
10050
+ throw new Error(`File not found: ${xmlPath}`);
10051
+ }
10052
+ const invoiceXml = fs14.readFileSync(xmlPath, "utf-8");
10053
+ const sellerNip = args.nip ?? config.nip;
10054
+ if (!sellerNip) {
10055
+ throw new Error("NIP is required. Use --nip or set via `ksef config set --nip`");
10056
+ }
10057
+ const contextType = args["context-type"] ?? "Nip";
10058
+ const contextId = args["context-id"] ?? sellerNip;
10059
+ const client = createClient(globalOpts);
10060
+ const workflow = client.offline;
10061
+ if (args.key && !args["cert-serial"]) {
10062
+ throw new Error("--cert-serial is required when using --key");
10063
+ }
10064
+ const certificate2 = args.key ? {
10065
+ privateKeyPem: fs14.readFileSync(args.key, "utf-8"),
10066
+ certificateSerial: args["cert-serial"]
10067
+ } : void 0;
10068
+ const validModes = ["offline24", "offline", "awaryjny", "awaria_calkowita"];
10069
+ const modeArg = args.mode ?? "offline24";
10070
+ if (!validModes.includes(modeArg)) {
10071
+ throw new Error(`Invalid --mode "${modeArg}". Must be one of: ${validModes.join(", ")}`);
10072
+ }
10073
+ const storage = args["no-store"] ? void 0 : getStorage(args);
10074
+ const { invoiceNumber, invoiceDate } = extractInvoiceFields(invoiceXml);
10075
+ const metadata = await workflow.generate(
10076
+ {
10077
+ invoiceNumber,
10078
+ invoiceDate,
10079
+ invoiceXml,
10080
+ sellerNip,
10081
+ sellerIdentifier: { type: contextType, value: contextId }
10082
+ },
10083
+ {
10084
+ mode: modeArg,
10085
+ certificate: certificate2,
10086
+ storage
10087
+ }
10088
+ );
10089
+ if (args["qr-out"]) {
10090
+ const outDir = args["qr-out"];
10091
+ fs14.mkdirSync(outDir, { recursive: true });
10092
+ const format = args["qr-format"] ?? "png";
10093
+ if (format !== "png" && format !== "svg") {
10094
+ throw new Error(`Invalid --qr-format "${format}". Must be one of: png, svg`);
10095
+ }
10096
+ const shortId = metadata.id.slice(0, 8);
10097
+ if (format === "svg") {
10098
+ const svg1 = await QrCodeService.generateQrCodeSvgWithLabel(metadata.kod1Url, "OFFLINE");
10099
+ fs14.writeFileSync(`${outDir}/${shortId}-kod1.svg`, svg1);
10100
+ if (metadata.kod2Url) {
10101
+ const svg2 = await QrCodeService.generateQrCodeSvgWithLabel(metadata.kod2Url, "CERTYFIKAT");
10102
+ fs14.writeFileSync(`${outDir}/${shortId}-kod2.svg`, svg2);
10103
+ }
10104
+ } else {
10105
+ const png1 = await QrCodeService.generateQrCode(metadata.kod1Url);
10106
+ fs14.writeFileSync(`${outDir}/${shortId}-kod1.png`, png1);
10107
+ if (metadata.kod2Url) {
10108
+ const png2 = await QrCodeService.generateQrCode(metadata.kod2Url);
10109
+ fs14.writeFileSync(`${outDir}/${shortId}-kod2.png`, png2);
10110
+ }
10111
+ }
10112
+ outputSuccess(`QR codes saved to ${outDir}/`);
10113
+ }
10114
+ if (!certificate2) {
10115
+ outputWarning("No certificate provided \u2014 KOD II QR code was not generated. Use --key and --cert-serial for offline compliance.");
10116
+ }
10117
+ if (args.json) {
10118
+ outputResult(metadata, { json: true });
10119
+ } else {
10120
+ outputKeyValue({
10121
+ ID: metadata.id,
10122
+ Mode: metadata.mode,
10123
+ Status: metadata.status,
10124
+ Deadline: metadata.submitBy,
10125
+ "KOD I": metadata.kod1Url,
10126
+ "KOD II": metadata.kod2Url ?? "(not generated)"
10127
+ }, { json: false });
10128
+ }
10129
+ });
10130
+ }
10131
+ });
10132
+ var list4 = defineCommand17({
10133
+ meta: { name: "list", description: "List stored offline invoices" },
10134
+ args: {
10135
+ ...globalArgs,
10136
+ status: { type: "string", description: "Filter by status" },
10137
+ mode: { type: "string", description: "Filter by mode" },
10138
+ expiring: { type: "boolean", description: "Show only invoices expiring within 24h" }
10139
+ },
10140
+ run({ args }) {
10141
+ return withErrorHandler(async () => {
10142
+ const storage = getStorage(args);
10143
+ const filter = {};
10144
+ if (args.status) filter.status = args.status;
10145
+ if (args.mode) filter.mode = args.mode;
10146
+ if (args.expiring) {
10147
+ const cutoff = new Date(Date.now() + 24 * 60 * 60 * 1e3);
10148
+ filter.expiringBefore = cutoff.toISOString();
10149
+ }
10150
+ const invoices2 = await storage.list(Object.keys(filter).length > 0 ? filter : void 0);
10151
+ if (invoices2.length === 0) {
10152
+ if (args.json) {
10153
+ outputResult([], { json: true });
10154
+ } else {
10155
+ outputSuccess("No offline invoices found.");
10156
+ }
10157
+ return;
10158
+ }
10159
+ outputTable(
10160
+ invoices2.map((i) => ({
10161
+ id: i.id.slice(0, 8),
10162
+ number: i.invoiceNumber,
10163
+ mode: i.mode,
10164
+ status: i.status,
10165
+ deadline: i.submitBy.slice(0, 19),
10166
+ nip: i.sellerNip
10167
+ })),
10168
+ [
10169
+ { key: "id", label: "ID" },
10170
+ { key: "number", label: "Number" },
10171
+ { key: "mode", label: "Mode" },
10172
+ { key: "status", label: "Status" },
10173
+ { key: "deadline", label: "Deadline" },
10174
+ { key: "nip", label: "NIP" }
10175
+ ],
10176
+ { json: args.json }
10177
+ );
10178
+ });
10179
+ }
10180
+ });
10181
+ var status6 = defineCommand17({
10182
+ meta: { name: "status", description: "Show offline invoice details" },
10183
+ args: {
10184
+ ...globalArgs,
10185
+ id: { type: "positional", description: "Invoice ID", required: true }
10186
+ },
10187
+ run({ args }) {
10188
+ return withErrorHandler(async () => {
10189
+ const storage = getStorage(args);
10190
+ const invoice3 = await storage.get(args.id);
10191
+ if (!invoice3) {
10192
+ throw new Error(`Offline invoice not found: ${args.id}`);
10193
+ }
10194
+ if (args.json) {
10195
+ outputResult(invoice3, { json: true });
10196
+ } else {
10197
+ outputKeyValue({
10198
+ ID: invoice3.id,
10199
+ Number: invoice3.invoiceNumber,
10200
+ Date: invoice3.invoiceDate,
10201
+ Mode: invoice3.mode,
10202
+ Reason: invoice3.reason,
10203
+ Status: invoice3.status,
10204
+ "Seller NIP": invoice3.sellerNip,
10205
+ Deadline: invoice3.submitBy,
10206
+ "Generated At": invoice3.generatedAt,
10207
+ "Submitted At": invoice3.submittedAt ?? "-",
10208
+ "KSeF Reference": invoice3.ksefReferenceNumber ?? "-",
10209
+ "KOD I URL": invoice3.kod1Url,
10210
+ "KOD II URL": invoice3.kod2Url ?? "-",
10211
+ Error: invoice3.error ? `${invoice3.error.code}: ${invoice3.error.message}` : "-"
10212
+ }, { json: false });
10213
+ }
10214
+ });
10215
+ }
10216
+ });
10217
+ var submit = defineCommand17({
10218
+ meta: { name: "submit", description: "Submit offline invoices to KSeF" },
10219
+ args: {
10220
+ ...globalArgs,
10221
+ all: { type: "boolean", description: "Submit all pending invoices" },
10222
+ "no-check-expiry": { type: "boolean", description: "Skip expiry check" },
10223
+ ids: { type: "positional", description: "Invoice IDs to submit" }
10224
+ },
10225
+ run({ args }) {
10226
+ return withErrorHandler(async () => {
10227
+ const globalOpts = getGlobalOpts14(args);
10228
+ const { client } = await requireSession(globalOpts);
10229
+ const storage = getStorage(args);
10230
+ const invoiceIds = args.ids ? args.ids.split(",").map((s) => s.trim()) : void 0;
10231
+ if (args.all && invoiceIds) {
10232
+ throw new Error("Cannot use --all together with specific invoice IDs. Use one or the other.");
10233
+ }
10234
+ if (!args.all && !invoiceIds) {
10235
+ throw new Error("Specify invoice IDs or use --all to submit all pending invoices.");
10236
+ }
10237
+ const result = await client.offline.submit(client, {
10238
+ storage,
10239
+ invoiceIds: args.all ? void 0 : invoiceIds,
10240
+ checkExpiry: !args["no-check-expiry"]
10241
+ });
10242
+ if (result.total === 0) {
10243
+ outputSuccess("No pending invoices to submit.");
10244
+ return;
10245
+ }
10246
+ if (args.json) {
10247
+ outputResult(result, { json: true });
10248
+ } else {
10249
+ outputSuccess(
10250
+ `Submitted: ${result.submitted}, Accepted: ${result.accepted}, Rejected: ${result.rejected}, Expired: ${result.expired}`
10251
+ );
10252
+ if (result.results.length > 0) {
10253
+ outputTable(
10254
+ result.results.map((r) => ({
10255
+ id: r.invoiceId.slice(0, 8),
10256
+ number: r.invoiceNumber,
10257
+ status: r.status,
10258
+ ref: r.ksefReferenceNumber ?? "-"
10259
+ })),
10260
+ [
10261
+ { key: "id", label: "ID" },
10262
+ { key: "number", label: "Number" },
10263
+ { key: "status", label: "Status" },
10264
+ { key: "ref", label: "KSeF Ref" }
10265
+ ],
10266
+ { json: false }
10267
+ );
10268
+ }
10269
+ }
10270
+ });
10271
+ }
10272
+ });
10273
+ var correct = defineCommand17({
10274
+ meta: { name: "correct", description: "Technical correction for rejected offline invoice" },
10275
+ args: {
10276
+ ...globalArgs,
10277
+ id: { type: "positional", description: "Rejected invoice ID", required: true },
10278
+ xml: { type: "positional", description: "Corrected XML file path", required: true }
10279
+ },
10280
+ run({ args }) {
10281
+ return withErrorHandler(async () => {
10282
+ const globalOpts = getGlobalOpts14(args);
10283
+ const { client } = await requireSession(globalOpts);
10284
+ const storage = getStorage(args);
10285
+ const xmlPath = args.xml;
10286
+ if (!fs14.existsSync(xmlPath)) {
10287
+ throw new Error(`File not found: ${xmlPath}`);
10288
+ }
10289
+ const correctedXml = fs14.readFileSync(xmlPath, "utf-8");
10290
+ const result = await client.offline.correct(client, {
10291
+ rejectedInvoiceId: args.id,
10292
+ correctedInvoiceXml: correctedXml,
10293
+ storage
10294
+ });
10295
+ if (args.json) {
10296
+ outputResult(result, { json: true });
10297
+ } else {
10298
+ outputSuccess(`Correction submitted. KSeF ref: ${result.ksefReferenceNumber ?? "pending"}`);
10299
+ }
10300
+ });
10301
+ }
10302
+ });
10303
+ var del = defineCommand17({
10304
+ meta: { name: "delete", description: "Delete offline invoice from local store" },
10305
+ args: {
10306
+ ...globalArgs,
10307
+ id: { type: "positional", description: "Invoice ID to delete" },
10308
+ expired: { type: "boolean", description: "Delete all expired invoices" },
10309
+ force: { type: "boolean", description: "Skip confirmation prompt" }
10310
+ },
10311
+ run({ args }) {
10312
+ return withErrorHandler(async () => {
10313
+ const storage = getStorage(args);
10314
+ if (args.expired) {
10315
+ const expired = await storage.list({ status: "EXPIRED" });
10316
+ if (expired.length === 0) {
10317
+ outputSuccess("No expired invoices to delete.");
10318
+ return;
10319
+ }
10320
+ if (!args.force) {
10321
+ if (!process.stdin.isTTY) {
10322
+ throw new Error(
10323
+ `${expired.length} expired invoice(s) would be deleted. Use --force to confirm in non-interactive mode.`
10324
+ );
10325
+ }
10326
+ const confirmed = await consola15.prompt(
10327
+ `Delete ${expired.length} expired invoice(s)?`,
10328
+ { type: "confirm", initial: false }
10329
+ );
10330
+ if (!confirmed) {
10331
+ consola15.info("Cancelled.");
10332
+ return;
10333
+ }
10334
+ }
10335
+ for (const inv of expired) {
10336
+ await storage.delete(inv.id);
10337
+ }
10338
+ outputSuccess(`Deleted ${expired.length} expired invoice(s).`);
10339
+ return;
10340
+ }
10341
+ if (!args.id) {
10342
+ throw new Error("Specify an invoice ID or use --expired to delete all expired invoices.");
10343
+ }
10344
+ const invoice3 = await storage.get(args.id);
10345
+ if (!invoice3) {
10346
+ throw new Error(`Offline invoice not found: ${args.id}`);
10347
+ }
10348
+ await storage.delete(args.id);
10349
+ outputSuccess(`Deleted offline invoice ${args.id}`);
10350
+ });
10351
+ }
10352
+ });
10353
+ var offlineCommand = defineCommand17({
10354
+ meta: { name: "offline", description: "Offline invoice management" },
10355
+ subCommands: { generate: generate3, list: list4, status: status6, submit, correct, delete: del }
10356
+ });
10357
+
9271
10358
  // src/cli/index.ts
9272
10359
  var __dirname = dirname2(fileURLToPath(import.meta.url));
9273
- var pkg = JSON.parse(readFileSync8(resolve(__dirname, "..", "package.json"), "utf-8"));
10360
+ var pkg = JSON.parse(readFileSync9(resolve(__dirname, "..", "package.json"), "utf-8"));
9274
10361
  var version = pkg.version;
9275
- var main = defineCommand17({
10362
+ var main = defineCommand18({
9276
10363
  meta: {
9277
10364
  name: "ksef",
9278
10365
  version,
@@ -9292,6 +10379,7 @@ var main = defineCommand17({
9292
10379
  limits: limitsCommand,
9293
10380
  peppol: peppolCommand,
9294
10381
  "test-data": testDataCommand,
10382
+ offline: offlineCommand,
9295
10383
  doctor: doctorCommand,
9296
10384
  completion: completionCommand
9297
10385
  }