ksef-client-ts 0.2.0 → 0.4.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
@@ -32,6 +32,74 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  mod
33
33
  ));
34
34
 
35
+ // src/errors/ksef-error.ts
36
+ var KSeFError;
37
+ var init_ksef_error = __esm({
38
+ "src/errors/ksef-error.ts"() {
39
+ "use strict";
40
+ KSeFError = class extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "KSeFError";
44
+ }
45
+ };
46
+ }
47
+ });
48
+
49
+ // src/errors/ksef-validation-error.ts
50
+ var KSeFValidationError;
51
+ var init_ksef_validation_error = __esm({
52
+ "src/errors/ksef-validation-error.ts"() {
53
+ "use strict";
54
+ init_ksef_error();
55
+ KSeFValidationError = class _KSeFValidationError extends KSeFError {
56
+ details;
57
+ constructor(message, details = []) {
58
+ super(message);
59
+ this.name = "KSeFValidationError";
60
+ this.details = details;
61
+ }
62
+ static fromField(field, message) {
63
+ return new _KSeFValidationError(message, [{ field, message }]);
64
+ }
65
+ static fromMessages(messages2) {
66
+ const details = messages2.map((m) => ({ message: m }));
67
+ return new _KSeFValidationError(messages2.join("; "), details);
68
+ }
69
+ };
70
+ }
71
+ });
72
+
73
+ // src/crypto/auth-xml-builder.ts
74
+ var auth_xml_builder_exports = {};
75
+ __export(auth_xml_builder_exports, {
76
+ buildUnsignedAuthTokenRequestXml: () => buildUnsignedAuthTokenRequestXml
77
+ });
78
+ function buildUnsignedAuthTokenRequestXml(options) {
79
+ const { challenge: challenge2, contextIdentifier, subjectIdentifierType = "certificateSubject" } = options;
80
+ const identifierElement = `<${contextIdentifier.type}>${xmlEscape(contextIdentifier.value)}</${contextIdentifier.type}>`;
81
+ return [
82
+ '<?xml version="1.0" encoding="utf-8"?>',
83
+ `<AuthTokenRequest xmlns="${AUTH_TOKEN_REQUEST_NS}">`,
84
+ `<Challenge>${xmlEscape(challenge2)}</Challenge>`,
85
+ `<ContextIdentifier>`,
86
+ identifierElement,
87
+ `</ContextIdentifier>`,
88
+ `<SubjectIdentifierType>${xmlEscape(subjectIdentifierType)}</SubjectIdentifierType>`,
89
+ `</AuthTokenRequest>`
90
+ ].join("");
91
+ }
92
+ function xmlEscape(str) {
93
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
94
+ }
95
+ var AUTH_TOKEN_REQUEST_NS;
96
+ var init_auth_xml_builder = __esm({
97
+ "src/crypto/auth-xml-builder.ts"() {
98
+ "use strict";
99
+ AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
100
+ }
101
+ });
102
+
35
103
  // node_modules/@xmldom/xmldom/lib/conventions.js
36
104
  var require_conventions = __commonJS({
37
105
  "node_modules/@xmldom/xmldom/lib/conventions.js"(exports) {
@@ -456,7 +524,7 @@ var require_dom = __commonJS({
456
524
  * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
457
525
  * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
458
526
  */
459
- hasFeature: function(feature, version) {
527
+ hasFeature: function(feature, version2) {
460
528
  return true;
461
529
  },
462
530
  /**
@@ -577,8 +645,8 @@ var require_dom = __commonJS({
577
645
  }
578
646
  },
579
647
  // Introduced in DOM Level 2:
580
- isSupported: function(feature, version) {
581
- return this.ownerDocument.implementation.hasFeature(feature, version);
648
+ isSupported: function(feature, version2) {
649
+ return this.ownerDocument.implementation.hasFeature(feature, version2);
582
650
  },
583
651
  // Introduced in DOM Level 2:
584
652
  hasAttributes: function() {
@@ -4845,8 +4913,542 @@ var init_pkcs12_loader = __esm({
4845
4913
  }
4846
4914
  });
4847
4915
 
4916
+ // src/workflows/polling.ts
4917
+ async function pollUntil(action, condition, options) {
4918
+ const intervalMs = options?.intervalMs ?? 2e3;
4919
+ const maxAttempts = options?.maxAttempts ?? 60;
4920
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
4921
+ const result = await action();
4922
+ if (condition(result)) return result;
4923
+ options?.onProgress?.(attempt, maxAttempts);
4924
+ if (attempt < maxAttempts) {
4925
+ await new Promise((r) => setTimeout(r, intervalMs));
4926
+ }
4927
+ }
4928
+ throw new Error(
4929
+ `Polling timeout: ${options?.description ?? "condition"} after ${maxAttempts} attempts`
4930
+ );
4931
+ }
4932
+ var init_polling = __esm({
4933
+ "src/workflows/polling.ts"() {
4934
+ "use strict";
4935
+ }
4936
+ });
4937
+
4938
+ // src/models/document-structures/types.ts
4939
+ var SystemCode, FORM_CODES, INVOICE_TYPES_BY_SYSTEM_CODE, FORM_CODE_KEYS;
4940
+ var init_types = __esm({
4941
+ "src/models/document-structures/types.ts"() {
4942
+ "use strict";
4943
+ SystemCode = {
4944
+ FA_2: "FA (2)",
4945
+ FA_3: "FA (3)",
4946
+ PEF_3: "PEF (3)",
4947
+ PEF_KOR_3: "PEF_KOR (3)",
4948
+ FA_RR_1: "FA_RR (1)"
4949
+ };
4950
+ FORM_CODES = {
4951
+ FA_2: { systemCode: "FA (2)", schemaVersion: "1-0E", value: "FA" },
4952
+ FA_3: { systemCode: "FA (3)", schemaVersion: "1-0E", value: "FA" },
4953
+ PEF_3: { systemCode: "PEF (3)", schemaVersion: "2-1", value: "PEF" },
4954
+ PEF_KOR_3: { systemCode: "PEF_KOR (3)", schemaVersion: "2-1", value: "PEF" },
4955
+ FA_RR_1_LEGACY: { systemCode: "FA_RR (1)", schemaVersion: "1-0E", value: "RR" },
4956
+ FA_RR_1_TRANSITION: { systemCode: "FA_RR (1)", schemaVersion: "1-1E", value: "RR" },
4957
+ FA_RR_1: { systemCode: "FA_RR (1)", schemaVersion: "1-1E", value: "FA_RR" }
4958
+ };
4959
+ INVOICE_TYPES_BY_SYSTEM_CODE = {
4960
+ [SystemCode.FA_2]: ["Vat", "Zal", "Kor", "Roz", "Upr", "KorZal", "KorRoz"],
4961
+ [SystemCode.FA_3]: ["Vat", "Zal", "Kor", "Roz", "Upr", "KorZal", "KorRoz"],
4962
+ [SystemCode.PEF_3]: ["VatPef", "VatPefSp", "KorPef"],
4963
+ [SystemCode.PEF_KOR_3]: ["KorPef"],
4964
+ [SystemCode.FA_RR_1]: ["VatRr", "KorVatRr"]
4965
+ };
4966
+ FORM_CODE_KEYS = {
4967
+ FA2: FORM_CODES.FA_2,
4968
+ FA3: FORM_CODES.FA_3,
4969
+ PEF3: FORM_CODES.PEF_3,
4970
+ PEFKOR3: FORM_CODES.PEF_KOR_3,
4971
+ FARR1: FORM_CODES.FA_RR_1
4972
+ };
4973
+ }
4974
+ });
4975
+
4976
+ // src/models/document-structures/helpers.ts
4977
+ function validateFormCodeForSession(formCode, sessionType) {
4978
+ if (sessionType === "online") return true;
4979
+ return !BATCH_DISALLOWED_SYSTEM_CODES.has(formCode.systemCode);
4980
+ }
4981
+ var SYSTEM_CODE_TO_FORM_CODE, ALL_FORM_CODES, BATCH_DISALLOWED_SYSTEM_CODES;
4982
+ var init_helpers = __esm({
4983
+ "src/models/document-structures/helpers.ts"() {
4984
+ "use strict";
4985
+ init_types();
4986
+ SYSTEM_CODE_TO_FORM_CODE = {
4987
+ [SystemCode.FA_2]: FORM_CODES.FA_2,
4988
+ [SystemCode.FA_3]: FORM_CODES.FA_3,
4989
+ [SystemCode.PEF_3]: FORM_CODES.PEF_3,
4990
+ [SystemCode.PEF_KOR_3]: FORM_CODES.PEF_KOR_3,
4991
+ [SystemCode.FA_RR_1]: FORM_CODES.FA_RR_1
4992
+ };
4993
+ ALL_FORM_CODES = Object.values(FORM_CODES);
4994
+ BATCH_DISALLOWED_SYSTEM_CODES = /* @__PURE__ */ new Set([
4995
+ SystemCode.PEF_3,
4996
+ SystemCode.PEF_KOR_3
4997
+ ]);
4998
+ }
4999
+ });
5000
+
5001
+ // src/models/document-structures/index.ts
5002
+ var init_document_structures = __esm({
5003
+ "src/models/document-structures/index.ts"() {
5004
+ "use strict";
5005
+ init_types();
5006
+ init_helpers();
5007
+ }
5008
+ });
5009
+
5010
+ // src/xml/upo-parser.ts
5011
+ import { XMLParser } from "fast-xml-parser";
5012
+ function isRecord(value) {
5013
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5014
+ }
5015
+ function requireRecord(value, at) {
5016
+ if (!isRecord(value)) {
5017
+ throw KSeFValidationError.fromField(at, `Expected object at ${at}`);
5018
+ }
5019
+ return value;
5020
+ }
5021
+ function requireString(value, at) {
5022
+ if (typeof value !== "string" || value.length === 0) {
5023
+ throw KSeFValidationError.fromField(at, `Expected non-empty string at ${at}`);
5024
+ }
5025
+ return value;
5026
+ }
5027
+ function optionalRecord(value) {
5028
+ return isRecord(value) ? value : void 0;
5029
+ }
5030
+ function optionalString(value) {
5031
+ return typeof value === "string" && value.length > 0 ? value : void 0;
5032
+ }
5033
+ function requireNumberFromString(value, at) {
5034
+ const raw = requireString(value, at);
5035
+ const parsed = Number.parseInt(raw, 10);
5036
+ if (!Number.isFinite(parsed)) {
5037
+ throw KSeFValidationError.fromField(at, `Expected integer at ${at}, got "${raw}"`);
5038
+ }
5039
+ return parsed;
5040
+ }
5041
+ function ensureArray(value) {
5042
+ if (value == null) return [];
5043
+ return Array.isArray(value) ? value : [value];
5044
+ }
5045
+ function parseIdKontekstu(obj) {
5046
+ const nip = optionalString(obj.Nip);
5047
+ if (nip) return { kind: "Nip", nip };
5048
+ const idWewnetrzny = optionalString(obj.IdWewnetrzny);
5049
+ if (idWewnetrzny) return { kind: "IdWewnetrzny", idWewnetrzny };
5050
+ const idZlozonyVatUE = optionalString(obj.IdZlozonyVatUE);
5051
+ if (idZlozonyVatUE) return { kind: "IdZlozonyVatUE", idZlozonyVatUE };
5052
+ const idDostawcyUslugPeppol = optionalString(obj.IdDostawcyUslugPeppol);
5053
+ if (idDostawcyUslugPeppol) return { kind: "IdDostawcyUslugPeppol", idDostawcyUslugPeppol };
5054
+ throw KSeFValidationError.fromField(
5055
+ "Uwierzytelnienie.IdKontekstu",
5056
+ "Unsupported context identifier. Expected Nip | IdWewnetrzny | IdZlozonyVatUE | IdDostawcyUslugPeppol"
5057
+ );
5058
+ }
5059
+ function parseProof(obj) {
5060
+ const tokenRef = optionalString(obj.NumerReferencyjnyTokenaKSeF);
5061
+ if (tokenRef) return { kind: "NumerReferencyjnyTokenaKSeF", numerReferencyjnyTokenaKSeF: tokenRef };
5062
+ const docHash = optionalString(obj.SkrotDokumentuUwierzytelniajacego);
5063
+ if (docHash) return { kind: "SkrotDokumentuUwierzytelniajacego", skrotDokumentuUwierzytelniajacego: docHash };
5064
+ throw KSeFValidationError.fromField(
5065
+ "Uwierzytelnienie",
5066
+ "Unsupported auth proof. Expected NumerReferencyjnyTokenaKSeF | SkrotDokumentuUwierzytelniajacego"
5067
+ );
5068
+ }
5069
+ function parseUwierzytelnienie(obj) {
5070
+ const idKontekstu = parseIdKontekstu(
5071
+ requireRecord(obj.IdKontekstu, "Uwierzytelnienie.IdKontekstu")
5072
+ );
5073
+ const proof = parseProof(obj);
5074
+ return { idKontekstu, proof };
5075
+ }
5076
+ function parseOpisPotwierdzenia(obj) {
5077
+ return {
5078
+ strona: requireNumberFromString(obj.Strona, "OpisPotwierdzenia.Strona"),
5079
+ liczbaStron: requireNumberFromString(obj.LiczbaStron, "OpisPotwierdzenia.LiczbaStron"),
5080
+ zakresDokumentowOd: requireNumberFromString(obj.ZakresDokumentowOd, "OpisPotwierdzenia.ZakresDokumentowOd"),
5081
+ zakresDokumentowDo: requireNumberFromString(obj.ZakresDokumentowDo, "OpisPotwierdzenia.ZakresDokumentowDo"),
5082
+ calkowitaLiczbaDokumentow: requireNumberFromString(obj.CalkowitaLiczbaDokumentow, "OpisPotwierdzenia.CalkowitaLiczbaDokumentow")
5083
+ };
5084
+ }
5085
+ function parseDokument(obj) {
5086
+ return {
5087
+ nipSprzedawcy: requireString(obj.NipSprzedawcy, "Dokument.NipSprzedawcy"),
5088
+ numerKSeFDokumentu: requireString(obj.NumerKSeFDokumentu, "Dokument.NumerKSeFDokumentu"),
5089
+ numerFaktury: requireString(obj.NumerFaktury, "Dokument.NumerFaktury"),
5090
+ dataWystawieniaFaktury: requireString(obj.DataWystawieniaFaktury, "Dokument.DataWystawieniaFaktury"),
5091
+ dataPrzeslaniaDokumentu: requireString(obj.DataPrzeslaniaDokumentu, "Dokument.DataPrzeslaniaDokumentu"),
5092
+ dataNadaniaNumeruKSeF: requireString(obj.DataNadaniaNumeruKSeF, "Dokument.DataNadaniaNumeruKSeF"),
5093
+ skrotDokumentu: requireString(obj.SkrotDokumentu, "Dokument.SkrotDokumentu"),
5094
+ trybWysylki: requireString(obj.TrybWysylki, "Dokument.TrybWysylki")
5095
+ };
5096
+ }
5097
+ function parseUpoXml(xml) {
5098
+ const text = Buffer.isBuffer(xml) ? xml.toString("utf8") : xml;
5099
+ const parsed = upoParser.parse(text);
5100
+ const potwierdzenie = requireRecord(parsed?.Potwierdzenie, "Potwierdzenie");
5101
+ const opisPotwierdzenia = optionalRecord(potwierdzenie.OpisPotwierdzenia);
5102
+ const dokumenty = ensureArray(potwierdzenie.Dokument).map(
5103
+ (doc, i) => parseDokument(requireRecord(doc, `Dokument[${i}]`))
5104
+ );
5105
+ if (dokumenty.length === 0) {
5106
+ throw KSeFValidationError.fromField("Dokument", "Expected at least one Dokument in UPO");
5107
+ }
5108
+ return {
5109
+ nazwaPodmiotuPrzyjmujacego: requireString(potwierdzenie.NazwaPodmiotuPrzyjmujacego, "NazwaPodmiotuPrzyjmujacego"),
5110
+ numerReferencyjnySesji: requireString(potwierdzenie.NumerReferencyjnySesji, "NumerReferencyjnySesji"),
5111
+ uwierzytelnienie: parseUwierzytelnienie(requireRecord(potwierdzenie.Uwierzytelnienie, "Uwierzytelnienie")),
5112
+ ...opisPotwierdzenia && { opisPotwierdzenia: parseOpisPotwierdzenia(opisPotwierdzenia) },
5113
+ nazwaStrukturyLogicznej: requireString(potwierdzenie.NazwaStrukturyLogicznej, "NazwaStrukturyLogicznej"),
5114
+ kodFormularza: requireString(potwierdzenie.KodFormularza, "KodFormularza"),
5115
+ dokumenty
5116
+ };
5117
+ }
5118
+ var upoParser;
5119
+ var init_upo_parser = __esm({
5120
+ "src/xml/upo-parser.ts"() {
5121
+ "use strict";
5122
+ init_ksef_validation_error();
5123
+ upoParser = new XMLParser({
5124
+ ignoreAttributes: false,
5125
+ attributeNamePrefix: "@_",
5126
+ parseTagValue: false,
5127
+ parseAttributeValue: false,
5128
+ removeNSPrefix: true,
5129
+ trimValues: false
5130
+ });
5131
+ }
5132
+ });
5133
+
5134
+ // src/xml/index.ts
5135
+ var init_xml = __esm({
5136
+ "src/xml/index.ts"() {
5137
+ "use strict";
5138
+ init_upo_parser();
5139
+ }
5140
+ });
5141
+
5142
+ // src/builders/batch-file.ts
5143
+ import * as crypto4 from "crypto";
5144
+ function splitBuffer(data, maxPartSize) {
5145
+ if (data.length <= maxPartSize) {
5146
+ return [data];
5147
+ }
5148
+ const parts = [];
5149
+ for (let offset = 0; offset < data.length; offset += maxPartSize) {
5150
+ parts.push(data.subarray(offset, Math.min(offset + maxPartSize, data.length)));
5151
+ }
5152
+ return parts;
5153
+ }
5154
+ function sha256Base64(data) {
5155
+ return crypto4.createHash("sha256").update(data).digest("base64");
5156
+ }
5157
+ var BATCH_MAX_PART_SIZE, BATCH_MAX_TOTAL_SIZE, BATCH_MAX_PARTS, BatchFileBuilder;
5158
+ var init_batch_file = __esm({
5159
+ "src/builders/batch-file.ts"() {
5160
+ "use strict";
5161
+ init_ksef_validation_error();
5162
+ BATCH_MAX_PART_SIZE = 1e8;
5163
+ BATCH_MAX_TOTAL_SIZE = 5e9;
5164
+ BATCH_MAX_PARTS = 50;
5165
+ BatchFileBuilder = class {
5166
+ /**
5167
+ * Build batch file metadata and encrypted parts from a raw ZIP.
5168
+ *
5169
+ * @param zipBytes - Unencrypted ZIP data
5170
+ * @param encryptFn - AES-256-CBC encryption function (called per part)
5171
+ * @param options - Optional configuration
5172
+ */
5173
+ static build(zipBytes, encryptFn, options) {
5174
+ const maxPartSize = options?.maxPartSize ?? BATCH_MAX_PART_SIZE;
5175
+ if (maxPartSize <= 0) {
5176
+ throw new KSeFValidationError("maxPartSize must be a positive number");
5177
+ }
5178
+ if (zipBytes.length === 0) {
5179
+ throw new KSeFValidationError("ZIP data must not be empty");
5180
+ }
5181
+ if (zipBytes.length > BATCH_MAX_TOTAL_SIZE) {
5182
+ throw new KSeFValidationError(
5183
+ `ZIP size ${zipBytes.length} exceeds maximum of ${BATCH_MAX_TOTAL_SIZE} bytes (5 GB)`
5184
+ );
5185
+ }
5186
+ const rawParts = splitBuffer(zipBytes, maxPartSize);
5187
+ if (rawParts.length > BATCH_MAX_PARTS) {
5188
+ throw new KSeFValidationError(
5189
+ `Data requires ${rawParts.length} parts, exceeding maximum of ${BATCH_MAX_PARTS}`
5190
+ );
5191
+ }
5192
+ const zipHash = sha256Base64(zipBytes);
5193
+ const encryptedParts = [];
5194
+ const fileParts = rawParts.map((raw, i) => {
5195
+ const encrypted = encryptFn(raw);
5196
+ encryptedParts.push(encrypted);
5197
+ return {
5198
+ ordinalNumber: i + 1,
5199
+ fileSize: encrypted.length,
5200
+ fileHash: sha256Base64(encrypted)
5201
+ };
5202
+ });
5203
+ return {
5204
+ batchFile: {
5205
+ fileSize: zipBytes.length,
5206
+ fileHash: zipHash,
5207
+ fileParts
5208
+ },
5209
+ encryptedParts
5210
+ };
5211
+ }
5212
+ /**
5213
+ * Stream-based variant: two-pass build from a stream factory.
5214
+ *
5215
+ * Pass 1: consume stream to compute ZIP hash.
5216
+ * Pass 2: re-create stream, split into parts, encrypt each, compute per-part metadata.
5217
+ *
5218
+ * @param zipStreamFactory - Factory that creates a fresh ReadableStream of the ZIP data
5219
+ * @param zipSize - Total ZIP byte size (from fs.stat or known in advance)
5220
+ * @param encryptStreamFn - Stream-to-stream AES-256-CBC encryption function
5221
+ * @param hashStreamFn - Stream-to-FileMetadata hashing function
5222
+ * @param options - Optional configuration
5223
+ */
5224
+ static async buildFromStream(zipStreamFactory, zipSize, encryptStreamFn, hashStreamFn, options) {
5225
+ const maxPartSize = options?.maxPartSize ?? BATCH_MAX_PART_SIZE;
5226
+ if (maxPartSize <= 0) {
5227
+ throw new KSeFValidationError("maxPartSize must be a positive number");
5228
+ }
5229
+ if (zipSize === 0) {
5230
+ throw new KSeFValidationError("ZIP data must not be empty");
5231
+ }
5232
+ if (zipSize > BATCH_MAX_TOTAL_SIZE) {
5233
+ throw new KSeFValidationError(
5234
+ `ZIP size ${zipSize} exceeds maximum of ${BATCH_MAX_TOTAL_SIZE} bytes (5 GB)`
5235
+ );
5236
+ }
5237
+ const partCount = Math.ceil(zipSize / maxPartSize);
5238
+ if (partCount > BATCH_MAX_PARTS) {
5239
+ throw new KSeFValidationError(
5240
+ `Data requires ${partCount} parts, exceeding maximum of ${BATCH_MAX_PARTS}`
5241
+ );
5242
+ }
5243
+ const zipMeta = await hashStreamFn(zipStreamFactory());
5244
+ const fileParts = [];
5245
+ const streamParts = [];
5246
+ const reader = zipStreamFactory().getReader();
5247
+ let pending = [];
5248
+ let pendingSize = 0;
5249
+ for (let partIndex = 0; partIndex < partCount; partIndex++) {
5250
+ const isLastPart = partIndex === partCount - 1;
5251
+ const targetSize = isLastPart ? zipSize - partIndex * maxPartSize : maxPartSize;
5252
+ while (pendingSize < targetSize) {
5253
+ const { done, value } = await reader.read();
5254
+ if (done) break;
5255
+ pending.push(value);
5256
+ pendingSize += value.byteLength;
5257
+ }
5258
+ const buffer = new Uint8Array(Buffer.concat(pending));
5259
+ const partData = buffer.subarray(0, targetSize);
5260
+ if (buffer.byteLength > targetSize) {
5261
+ const remainder = buffer.subarray(targetSize);
5262
+ pending = [remainder];
5263
+ pendingSize = remainder.byteLength;
5264
+ } else {
5265
+ pending = [];
5266
+ pendingSize = 0;
5267
+ }
5268
+ const partStream = new ReadableStream({
5269
+ start(controller) {
5270
+ controller.enqueue(partData);
5271
+ controller.close();
5272
+ }
5273
+ });
5274
+ const encryptedStream = encryptStreamFn(partStream);
5275
+ const encryptedChunks = [];
5276
+ const encReader = encryptedStream.getReader();
5277
+ for (; ; ) {
5278
+ const { done, value } = await encReader.read();
5279
+ if (done) break;
5280
+ encryptedChunks.push(value);
5281
+ }
5282
+ const encryptedData = new Uint8Array(Buffer.concat(encryptedChunks));
5283
+ const encryptedMeta = sha256Base64(encryptedData);
5284
+ fileParts.push({
5285
+ ordinalNumber: partIndex + 1,
5286
+ fileSize: encryptedData.byteLength,
5287
+ fileHash: encryptedMeta
5288
+ });
5289
+ const uploadStream = new ReadableStream({
5290
+ start(controller) {
5291
+ controller.enqueue(encryptedData);
5292
+ controller.close();
5293
+ }
5294
+ });
5295
+ streamParts.push({
5296
+ dataStream: uploadStream,
5297
+ metadata: {
5298
+ hashSHA: encryptedMeta,
5299
+ fileSize: encryptedData.byteLength
5300
+ },
5301
+ ordinalNumber: partIndex + 1
5302
+ });
5303
+ }
5304
+ reader.releaseLock();
5305
+ return {
5306
+ batchFile: {
5307
+ fileSize: zipSize,
5308
+ fileHash: zipMeta.hashSHA,
5309
+ fileParts
5310
+ },
5311
+ streamParts
5312
+ };
5313
+ }
5314
+ };
5315
+ }
5316
+ });
5317
+
5318
+ // src/workflows/batch-session-workflow.ts
5319
+ var batch_session_workflow_exports = {};
5320
+ __export(batch_session_workflow_exports, {
5321
+ uploadBatch: () => uploadBatch,
5322
+ uploadBatchParsed: () => uploadBatchParsed,
5323
+ uploadBatchStream: () => uploadBatchStream,
5324
+ uploadBatchStreamParsed: () => uploadBatchStreamParsed
5325
+ });
5326
+ async function uploadBatch(client, zipData, options) {
5327
+ await client.crypto.init();
5328
+ const encData = client.crypto.getEncryptionData();
5329
+ const formCode = options?.formCode ?? FORM_CODES.FA_2;
5330
+ const encryptFn = (part) => client.crypto.encryptAES256(part, encData.cipherKey, encData.cipherIv);
5331
+ const { batchFile, encryptedParts } = BatchFileBuilder.build(zipData, encryptFn, {
5332
+ maxPartSize: options?.maxPartSize
5333
+ });
5334
+ const openResp = await client.batchSession.openSession(
5335
+ {
5336
+ formCode,
5337
+ encryption: encData.encryptionInfo,
5338
+ batchFile,
5339
+ offlineMode: options?.offlineMode
5340
+ },
5341
+ options?.upoVersion
5342
+ );
5343
+ const sendingParts = encryptedParts.map((part, i) => ({
5344
+ data: part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength),
5345
+ metadata: {
5346
+ hashSHA: batchFile.fileParts[i].fileHash,
5347
+ fileSize: batchFile.fileParts[i].fileSize
5348
+ },
5349
+ ordinalNumber: i + 1
5350
+ }));
5351
+ await client.batchSession.sendParts(openResp, sendingParts);
5352
+ await client.batchSession.closeSession(openResp.referenceNumber);
5353
+ const result = await pollUntil(
5354
+ () => client.sessionStatus.getSessionStatus(openResp.referenceNumber),
5355
+ (s) => s.status.code === 200 || s.status.code >= 400,
5356
+ { ...options?.pollOptions, description: `UPO for batch ${openResp.referenceNumber}` }
5357
+ );
5358
+ if (result.status.code !== 200) {
5359
+ throw new Error(`Batch session failed: ${result.status.code} \u2014 ${result.status.description}`);
5360
+ }
5361
+ return {
5362
+ sessionRef: openResp.referenceNumber,
5363
+ upo: {
5364
+ pages: result.upo?.pages ?? [],
5365
+ invoiceCount: result.invoiceCount,
5366
+ successfulInvoiceCount: result.successfulInvoiceCount,
5367
+ failedInvoiceCount: result.failedInvoiceCount
5368
+ }
5369
+ };
5370
+ }
5371
+ async function uploadBatchStream(client, zipStreamFactory, zipSize, options) {
5372
+ await client.crypto.init();
5373
+ const encData = client.crypto.getEncryptionData();
5374
+ const formCode = options?.formCode ?? FORM_CODES.FA_2;
5375
+ const encryptStreamFn = (stream) => client.crypto.encryptAES256Stream(stream, encData.cipherKey, encData.cipherIv);
5376
+ const hashStreamFn = (stream) => client.crypto.getFileMetadataFromStream(stream);
5377
+ const { batchFile, streamParts } = await BatchFileBuilder.buildFromStream(
5378
+ zipStreamFactory,
5379
+ zipSize,
5380
+ encryptStreamFn,
5381
+ hashStreamFn,
5382
+ { maxPartSize: options?.maxPartSize }
5383
+ );
5384
+ const openResp = await client.batchSession.openSession(
5385
+ {
5386
+ formCode,
5387
+ encryption: encData.encryptionInfo,
5388
+ batchFile,
5389
+ offlineMode: options?.offlineMode
5390
+ },
5391
+ options?.upoVersion
5392
+ );
5393
+ await client.batchSession.sendPartsWithStream(openResp, streamParts);
5394
+ await client.batchSession.closeSession(openResp.referenceNumber);
5395
+ const result = await pollUntil(
5396
+ () => client.sessionStatus.getSessionStatus(openResp.referenceNumber),
5397
+ (s) => s.status.code === 200 || s.status.code >= 400,
5398
+ { ...options?.pollOptions, description: `UPO for batch ${openResp.referenceNumber}` }
5399
+ );
5400
+ if (result.status.code !== 200) {
5401
+ throw new Error(`Batch session failed: ${result.status.code} \u2014 ${result.status.description}`);
5402
+ }
5403
+ return {
5404
+ sessionRef: openResp.referenceNumber,
5405
+ upo: {
5406
+ pages: result.upo?.pages ?? [],
5407
+ invoiceCount: result.invoiceCount,
5408
+ successfulInvoiceCount: result.successfulInvoiceCount,
5409
+ failedInvoiceCount: result.failedInvoiceCount
5410
+ }
5411
+ };
5412
+ }
5413
+ async function uploadBatchStreamParsed(client, zipStreamFactory, zipSize, options) {
5414
+ const result = await uploadBatchStream(client, zipStreamFactory, zipSize, options);
5415
+ const parsed = [];
5416
+ for (const page of result.upo.pages) {
5417
+ const upoResult = await client.sessionStatus.getSessionUpo(result.sessionRef, page.referenceNumber);
5418
+ parsed.push(parseUpoXml(upoResult.upo));
5419
+ }
5420
+ return {
5421
+ sessionRef: result.sessionRef,
5422
+ upo: { ...result.upo, parsed }
5423
+ };
5424
+ }
5425
+ async function uploadBatchParsed(client, zipData, options) {
5426
+ const result = await uploadBatch(client, zipData, options);
5427
+ const parsed = [];
5428
+ for (const page of result.upo.pages) {
5429
+ const upoResult = await client.sessionStatus.getSessionUpo(result.sessionRef, page.referenceNumber);
5430
+ parsed.push(parseUpoXml(upoResult.upo));
5431
+ }
5432
+ return {
5433
+ sessionRef: result.sessionRef,
5434
+ upo: { ...result.upo, parsed }
5435
+ };
5436
+ }
5437
+ var init_batch_session_workflow = __esm({
5438
+ "src/workflows/batch-session-workflow.ts"() {
5439
+ "use strict";
5440
+ init_document_structures();
5441
+ init_batch_file();
5442
+ init_polling();
5443
+ init_xml();
5444
+ }
5445
+ });
5446
+
4848
5447
  // src/cli/index.ts
4849
- import { defineCommand as defineCommand15, runMain } from "citty";
5448
+ import { readFileSync as readFileSync6 } from "fs";
5449
+ import { fileURLToPath } from "url";
5450
+ import { dirname as dirname2, resolve } from "path";
5451
+ import { defineCommand as defineCommand16, runMain } from "citty";
4850
5452
 
4851
5453
  // src/cli/commands/config.ts
4852
5454
  import { defineCommand } from "citty";
@@ -4935,15 +5537,8 @@ function outputWarning(msg) {
4935
5537
  // src/cli/error-handler.ts
4936
5538
  import { consola as consola2 } from "consola";
4937
5539
 
4938
- // src/errors/ksef-error.ts
4939
- var KSeFError = class extends Error {
4940
- constructor(message) {
4941
- super(message);
4942
- this.name = "KSeFError";
4943
- }
4944
- };
4945
-
4946
5540
  // src/errors/ksef-api-error.ts
5541
+ init_ksef_error();
4947
5542
  var KSeFApiError = class _KSeFApiError extends KSeFError {
4948
5543
  statusCode;
4949
5544
  errorResponse;
@@ -4993,6 +5588,7 @@ var KSeFRateLimitError = class _KSeFRateLimitError extends KSeFApiError {
4993
5588
  };
4994
5589
 
4995
5590
  // src/errors/ksef-unauthorized-error.ts
5591
+ init_ksef_error();
4996
5592
  var KSeFUnauthorizedError = class extends KSeFError {
4997
5593
  statusCode = 401;
4998
5594
  detail;
@@ -5008,6 +5604,7 @@ var KSeFUnauthorizedError = class extends KSeFError {
5008
5604
  };
5009
5605
 
5010
5606
  // src/errors/ksef-forbidden-error.ts
5607
+ init_ksef_error();
5011
5608
  var KSeFForbiddenError = class extends KSeFError {
5012
5609
  statusCode = 403;
5013
5610
  detail;
@@ -5144,6 +5741,9 @@ var configCommand = defineCommand({
5144
5741
  });
5145
5742
 
5146
5743
  // src/cli/commands/auth.ts
5744
+ import * as fs3 from "fs";
5745
+ import * as path3 from "path";
5746
+ import * as os3 from "os";
5147
5747
  import { defineCommand as defineCommand2 } from "citty";
5148
5748
 
5149
5749
  // src/cli/client-factory.ts
@@ -5179,7 +5779,8 @@ function resolveOptions(options = {}) {
5179
5779
  lighthouseUrl: options.lighthouseUrl ?? env.lighthouseUrl,
5180
5780
  apiVersion: options.apiVersion ?? DEFAULT_API_VERSION,
5181
5781
  timeout: options.timeout ?? DEFAULT_TIMEOUT,
5182
- customHeaders: options.customHeaders ?? {}
5782
+ customHeaders: options.customHeaders ?? {},
5783
+ environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST")
5183
5784
  };
5184
5785
  }
5185
5786
 
@@ -5193,8 +5794,8 @@ var RouteBuilder = class {
5193
5794
  this.apiVersion = apiVersion;
5194
5795
  }
5195
5796
  build(endpoint, apiVersion) {
5196
- const version = apiVersion ?? this.apiVersion;
5197
- return `/${version}/${endpoint}`;
5797
+ const version2 = apiVersion ?? this.apiVersion;
5798
+ return `/${version2}/${endpoint}`;
5198
5799
  }
5199
5800
  };
5200
5801
 
@@ -5246,27 +5847,11 @@ function isRetryableStatus(status6, policy) {
5246
5847
  return policy.retryableStatusCodes.includes(status6);
5247
5848
  }
5248
5849
  function sleep(ms) {
5249
- return new Promise((resolve) => setTimeout(resolve, ms));
5850
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
5250
5851
  }
5251
5852
 
5252
- // src/errors/ksef-validation-error.ts
5253
- var KSeFValidationError = class _KSeFValidationError extends KSeFError {
5254
- details;
5255
- constructor(message, details = []) {
5256
- super(message);
5257
- this.name = "KSeFValidationError";
5258
- this.details = details;
5259
- }
5260
- static fromField(field, message) {
5261
- return new _KSeFValidationError(message, [{ field, message }]);
5262
- }
5263
- static fromMessages(messages2) {
5264
- const details = messages2.map((m) => ({ message: m }));
5265
- return new _KSeFValidationError(messages2.join("; "), details);
5266
- }
5267
- };
5268
-
5269
5853
  // src/http/presigned-url-policy.ts
5854
+ init_ksef_validation_error();
5270
5855
  function defaultPresignedUrlPolicy() {
5271
5856
  return {
5272
5857
  allowedHosts: ["*.ksef.mf.gov.pl"],
@@ -5454,9 +6039,9 @@ var RestClient = class {
5454
6039
  return response;
5455
6040
  }
5456
6041
  buildUrl(request) {
5457
- const path5 = this.routeBuilder.build(request.path);
6042
+ const path7 = this.routeBuilder.build(request.path);
5458
6043
  const base = this.options.baseUrl;
5459
- const url2 = new URL(`${base}${path5}`);
6044
+ const url2 = new URL(`${base}${path7}`);
5460
6045
  const query2 = request.getQuery();
5461
6046
  for (const [key, value] of query2) {
5462
6047
  url2.searchParams.append(key, value);
@@ -5517,7 +6102,7 @@ var TokenBucket = class {
5517
6102
  return;
5518
6103
  }
5519
6104
  const waitMs = Math.ceil((1 - this.tokens) / this.refillRate);
5520
- await new Promise((resolve) => setTimeout(resolve, waitMs));
6105
+ await new Promise((resolve2) => setTimeout(resolve2, waitMs));
5521
6106
  this.refill();
5522
6107
  this.tokens -= 1;
5523
6108
  }
@@ -5538,8 +6123,8 @@ var RateLimitPolicy = class {
5538
6123
  this.endpointLimits = config.endpointLimits ?? {};
5539
6124
  }
5540
6125
  async acquire(endpoint) {
5541
- return new Promise((resolve, reject) => {
5542
- this.chain = this.chain.then(() => this.doAcquire(endpoint)).then(resolve, reject);
6126
+ return new Promise((resolve2, reject) => {
6127
+ this.chain = this.chain.then(() => this.doAcquire(endpoint)).then(resolve2, reject);
5543
6128
  });
5544
6129
  }
5545
6130
  async doAcquire(endpoint) {
@@ -5603,21 +6188,21 @@ var RestRequest = class _RestRequest {
5603
6188
  _query = [];
5604
6189
  _presigned = false;
5605
6190
  _skipAuthRetry = false;
5606
- constructor(method, path5) {
6191
+ constructor(method, path7) {
5607
6192
  this.method = method;
5608
- this.path = path5;
6193
+ this.path = path7;
5609
6194
  }
5610
- static get(path5) {
5611
- return new _RestRequest("GET", path5);
6195
+ static get(path7) {
6196
+ return new _RestRequest("GET", path7);
5612
6197
  }
5613
- static post(path5) {
5614
- return new _RestRequest("POST", path5);
6198
+ static post(path7) {
6199
+ return new _RestRequest("POST", path7);
5615
6200
  }
5616
- static put(path5) {
5617
- return new _RestRequest("PUT", path5);
6201
+ static put(path7) {
6202
+ return new _RestRequest("PUT", path7);
5618
6203
  }
5619
- static delete(path5) {
5620
- return new _RestRequest("DELETE", path5);
6204
+ static delete(path7) {
6205
+ return new _RestRequest("DELETE", path7);
5621
6206
  }
5622
6207
  body(data) {
5623
6208
  this._body = data;
@@ -5911,6 +6496,36 @@ var BatchSessionService = class {
5911
6496
  });
5912
6497
  await Promise.all(tasks);
5913
6498
  }
6499
+ /**
6500
+ * Upload parts sequentially (not in parallel) because each part uses a
6501
+ * streaming body (`duplex: 'half'`). Parallel streaming uploads can cause
6502
+ * backpressure issues and exceed memory limits for large payloads.
6503
+ */
6504
+ async sendPartsWithStream(openResponse, parts) {
6505
+ const uploadRequests = openResponse.partUploadRequests;
6506
+ for (const part of parts) {
6507
+ const uploadReq = uploadRequests.find(
6508
+ (r) => r.ordinalNumber === part.ordinalNumber
6509
+ );
6510
+ if (!uploadReq) {
6511
+ throw new Error(`No upload request found for part ${part.ordinalNumber}`);
6512
+ }
6513
+ const headers = {};
6514
+ for (const [k, v] of Object.entries(uploadReq.headers)) {
6515
+ if (v != null) headers[k] = v;
6516
+ }
6517
+ const resp = await fetch(uploadReq.url, {
6518
+ method: uploadReq.method,
6519
+ headers,
6520
+ body: part.dataStream,
6521
+ // @ts-expect-error -- Node 18+ undici supports duplex for streaming body
6522
+ duplex: "half"
6523
+ });
6524
+ if (!resp.ok) {
6525
+ throw new Error(`Upload failed for part ${part.ordinalNumber}: HTTP ${resp.status}`);
6526
+ }
6527
+ }
6528
+ }
5914
6529
  async closeSession(batchRef) {
5915
6530
  const req = RestRequest.post(Routes.Sessions.Batch.close(batchRef));
5916
6531
  await this.restClient.executeVoid(req);
@@ -6234,6 +6849,18 @@ var CertificateApiService = class {
6234
6849
  }
6235
6850
  };
6236
6851
 
6852
+ // src/errors/index.ts
6853
+ init_ksef_error();
6854
+
6855
+ // src/errors/ksef-auth-status-error.ts
6856
+ init_ksef_error();
6857
+
6858
+ // src/errors/ksef-session-expired-error.ts
6859
+ init_ksef_error();
6860
+
6861
+ // src/errors/index.ts
6862
+ init_ksef_validation_error();
6863
+
6237
6864
  // src/services/lighthouse.ts
6238
6865
  var LighthouseService = class {
6239
6866
  lighthouseUrl;
@@ -6242,20 +6869,20 @@ var LighthouseService = class {
6242
6869
  this.lighthouseUrl = options.lighthouseUrl;
6243
6870
  this.timeout = options.timeout;
6244
6871
  }
6245
- async fetchJson(path5) {
6872
+ async fetchJson(path7) {
6246
6873
  if (!this.lighthouseUrl) {
6247
6874
  throw new KSeFError(
6248
6875
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
6249
6876
  );
6250
6877
  }
6251
- const response = await fetch(`${this.lighthouseUrl}${path5}`, {
6878
+ const response = await fetch(`${this.lighthouseUrl}${path7}`, {
6252
6879
  headers: { Accept: "application/json" },
6253
6880
  signal: AbortSignal.timeout(this.timeout)
6254
6881
  });
6255
6882
  if (!response.ok) {
6256
6883
  const body = await response.text();
6257
6884
  throw new KSeFError(
6258
- `Lighthouse ${path5} failed: HTTP ${response.status} \u2014 ${body}`
6885
+ `Lighthouse ${path7} failed: HTTP ${response.status} \u2014 ${body}`
6259
6886
  );
6260
6887
  }
6261
6888
  return await response.json();
@@ -6308,84 +6935,111 @@ var PeppolService = class {
6308
6935
  };
6309
6936
 
6310
6937
  // src/services/test-data.ts
6938
+ init_ksef_error();
6311
6939
  var TestDataService = class {
6312
6940
  restClient;
6313
- constructor(restClient) {
6941
+ environmentName;
6942
+ constructor(restClient, environmentName) {
6314
6943
  this.restClient = restClient;
6944
+ this.environmentName = environmentName;
6945
+ }
6946
+ ensureTestEnvironment() {
6947
+ if (this.environmentName && this.environmentName !== "TEST") {
6948
+ throw new KSeFError(
6949
+ `Test data APIs are only available on the TEST environment (current: ${this.environmentName})`
6950
+ );
6951
+ }
6315
6952
  }
6316
6953
  // Subject management
6317
6954
  async createSubject(request) {
6955
+ this.ensureTestEnvironment();
6318
6956
  const req = RestRequest.post(Routes.TestData.createSubject).body(request);
6319
6957
  await this.restClient.executeVoid(req);
6320
6958
  }
6321
6959
  async removeSubject(request) {
6960
+ this.ensureTestEnvironment();
6322
6961
  const req = RestRequest.post(Routes.TestData.removeSubject).body(request);
6323
6962
  await this.restClient.executeVoid(req);
6324
6963
  }
6325
6964
  // Person management
6326
6965
  async createPerson(request) {
6966
+ this.ensureTestEnvironment();
6327
6967
  const req = RestRequest.post(Routes.TestData.createPerson).body(request);
6328
6968
  await this.restClient.executeVoid(req);
6329
6969
  }
6330
6970
  async removePerson(request) {
6971
+ this.ensureTestEnvironment();
6331
6972
  const req = RestRequest.post(Routes.TestData.removePerson).body(request);
6332
6973
  await this.restClient.executeVoid(req);
6333
6974
  }
6334
6975
  // Permissions
6335
6976
  async grantPermissions(request) {
6977
+ this.ensureTestEnvironment();
6336
6978
  const req = RestRequest.post(Routes.TestData.grantPerms).body(request);
6337
6979
  await this.restClient.executeVoid(req);
6338
6980
  }
6339
6981
  async revokePermissions(request) {
6982
+ this.ensureTestEnvironment();
6340
6983
  const req = RestRequest.post(Routes.TestData.revokePerms).body(request);
6341
6984
  await this.restClient.executeVoid(req);
6342
6985
  }
6343
6986
  // Attachment permissions
6344
6987
  async enableAttachment(request) {
6988
+ this.ensureTestEnvironment();
6345
6989
  const req = RestRequest.post(Routes.TestData.enableAttach).body(request);
6346
6990
  await this.restClient.executeVoid(req);
6347
6991
  }
6348
6992
  async disableAttachment(request) {
6993
+ this.ensureTestEnvironment();
6349
6994
  const req = RestRequest.post(Routes.TestData.disableAttach).body(request);
6350
6995
  await this.restClient.executeVoid(req);
6351
6996
  }
6352
6997
  // Session limits
6353
6998
  async changeSessionLimits(request) {
6999
+ this.ensureTestEnvironment();
6354
7000
  const req = RestRequest.post(Routes.TestData.changeSessionLimitsInCurrentContext).body(request);
6355
7001
  await this.restClient.executeVoid(req);
6356
7002
  }
6357
7003
  async restoreDefaultSessionLimits() {
7004
+ this.ensureTestEnvironment();
6358
7005
  const req = RestRequest.delete(Routes.TestData.restoreDefaultSessionLimitsInCurrentContext);
6359
7006
  await this.restClient.executeVoid(req);
6360
7007
  }
6361
7008
  // Certificate limits
6362
7009
  async changeCertificatesLimit(request) {
7010
+ this.ensureTestEnvironment();
6363
7011
  const req = RestRequest.post(Routes.TestData.changeCertificatesLimitInCurrentSubject).body(request);
6364
7012
  await this.restClient.executeVoid(req);
6365
7013
  }
6366
7014
  async restoreDefaultCertificatesLimit() {
7015
+ this.ensureTestEnvironment();
6367
7016
  const req = RestRequest.delete(Routes.TestData.restoreDefaultCertificatesLimitInCurrentSubject);
6368
7017
  await this.restClient.executeVoid(req);
6369
7018
  }
6370
7019
  // Rate limits
6371
7020
  async setRateLimits(request) {
7021
+ this.ensureTestEnvironment();
6372
7022
  const req = RestRequest.post(Routes.TestData.rateLimits).body(request);
6373
7023
  await this.restClient.executeVoid(req);
6374
7024
  }
6375
7025
  async restoreDefaultRateLimits() {
7026
+ this.ensureTestEnvironment();
6376
7027
  const req = RestRequest.delete(Routes.TestData.rateLimits);
6377
7028
  await this.restClient.executeVoid(req);
6378
7029
  }
6379
7030
  async setProductionRateLimits() {
7031
+ this.ensureTestEnvironment();
6380
7032
  const req = RestRequest.post(Routes.TestData.productionRateLimits);
6381
7033
  await this.restClient.executeVoid(req);
6382
7034
  }
6383
7035
  // Context blocking
6384
7036
  async blockContext(request) {
7037
+ this.ensureTestEnvironment();
6385
7038
  const req = RestRequest.post(Routes.TestData.blockContext).body(request);
6386
7039
  await this.restClient.executeVoid(req);
6387
7040
  }
6388
7041
  async unblockContext(request) {
7042
+ this.ensureTestEnvironment();
6389
7043
  const req = RestRequest.post(Routes.TestData.unblockContext).body(request);
6390
7044
  await this.restClient.executeVoid(req);
6391
7045
  }
@@ -6471,6 +7125,28 @@ var CryptographyService = class {
6471
7125
  const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
6472
7126
  return new Uint8Array(Buffer.concat([cipher.update(content), cipher.final()]));
6473
7127
  }
7128
+ /**
7129
+ * Encrypt with AES-256-CBC as a streaming transform.
7130
+ * Returns a ReadableStream that yields encrypted chunks as the input is read.
7131
+ */
7132
+ encryptAES256Stream(input, key, iv) {
7133
+ const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
7134
+ const transform = new TransformStream({
7135
+ transform(chunk, controller) {
7136
+ const encrypted = cipher.update(chunk);
7137
+ if (encrypted.length > 0) {
7138
+ controller.enqueue(new Uint8Array(encrypted));
7139
+ }
7140
+ },
7141
+ flush(controller) {
7142
+ const final = cipher.final();
7143
+ if (final.length > 0) {
7144
+ controller.enqueue(new Uint8Array(final));
7145
+ }
7146
+ }
7147
+ });
7148
+ return input.pipeThrough(transform);
7149
+ }
6474
7150
  /** Decrypt with AES-256-CBC. */
6475
7151
  decryptAES256(content, key, iv) {
6476
7152
  const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
@@ -6543,6 +7219,23 @@ var CryptographyService = class {
6543
7219
  const hash = crypto.createHash("sha256").update(file).digest("base64");
6544
7220
  return { hashSHA: hash, fileSize: file.length };
6545
7221
  }
7222
+ /** Compute SHA-256 hash (base64) and byte length from a ReadableStream. */
7223
+ async getFileMetadataFromStream(stream) {
7224
+ const hash = crypto.createHash("sha256");
7225
+ let fileSize = 0;
7226
+ const reader = stream.getReader();
7227
+ try {
7228
+ for (; ; ) {
7229
+ const { done, value } = await reader.read();
7230
+ if (done) break;
7231
+ hash.update(value);
7232
+ fileSize += value.byteLength;
7233
+ }
7234
+ } finally {
7235
+ reader.releaseLock();
7236
+ }
7237
+ return { hashSHA: hash.digest("base64"), fileSize };
7238
+ }
6546
7239
  // ---------------------------------------------------------------------------
6547
7240
  // CSR generation
6548
7241
  // ---------------------------------------------------------------------------
@@ -6719,6 +7412,7 @@ var VerificationLinkService = class {
6719
7412
  };
6720
7413
 
6721
7414
  // src/client.ts
7415
+ init_auth_xml_builder();
6722
7416
  var KSeFClient = class {
6723
7417
  auth;
6724
7418
  activeSessions;
@@ -6762,7 +7456,7 @@ var KSeFClient = class {
6762
7456
  this.lighthouse = new LighthouseService(this.options);
6763
7457
  this.limits = new LimitsService(restClient);
6764
7458
  this.peppol = new PeppolService(restClient);
6765
- this.testData = new TestDataService(restClient);
7459
+ this.testData = new TestDataService(restClient, this.options.environmentName);
6766
7460
  this.qr = new VerificationLinkService(this.options.baseQrUrl);
6767
7461
  }
6768
7462
  async loginWithToken(token, nip) {
@@ -6812,21 +7506,12 @@ var KSeFClient = class {
6812
7506
  this.authManager.setRefreshToken(void 0);
6813
7507
  }
6814
7508
  };
6815
- var AUTH_TOKEN_REQUEST_NS = "http://ksef.mf.gov.pl/auth/token/2.0";
6816
7509
  function buildAuthTokenRequestXml(challenge2, nip, subjectIdentifierType = "certificateSubject") {
6817
- return [
6818
- '<?xml version="1.0" encoding="utf-8"?>',
6819
- `<AuthTokenRequest xmlns="${AUTH_TOKEN_REQUEST_NS}">`,
6820
- `<Challenge>${xmlEscape(challenge2)}</Challenge>`,
6821
- `<ContextIdentifier>`,
6822
- `<Nip>${xmlEscape(nip)}</Nip>`,
6823
- `</ContextIdentifier>`,
6824
- `<SubjectIdentifierType>${xmlEscape(subjectIdentifierType)}</SubjectIdentifierType>`,
6825
- `</AuthTokenRequest>`
6826
- ].join("");
6827
- }
6828
- function xmlEscape(str) {
6829
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
7510
+ return buildUnsignedAuthTokenRequestXml({
7511
+ challenge: challenge2,
7512
+ contextIdentifier: { type: "Nip", value: nip },
7513
+ subjectIdentifierType
7514
+ });
6830
7515
  }
6831
7516
  function buildRestClientConfig(options, authManager) {
6832
7517
  const config = { authManager };
@@ -6936,6 +7621,29 @@ function requireSession(globalOpts) {
6936
7621
  }
6937
7622
 
6938
7623
  // src/cli/commands/auth.ts
7624
+ init_polling();
7625
+ var PENDING_CHALLENGE_FILE = path3.join(os3.homedir(), ".ksef", "pending-challenge.json");
7626
+ function savePendingChallenge(data) {
7627
+ const dir = path3.dirname(PENDING_CHALLENGE_FILE);
7628
+ fs3.mkdirSync(dir, { recursive: true });
7629
+ fs3.writeFileSync(PENDING_CHALLENGE_FILE, JSON.stringify(data, null, 2) + "\n", {
7630
+ encoding: "utf-8",
7631
+ mode: 384
7632
+ });
7633
+ }
7634
+ function clearPendingChallenge() {
7635
+ try {
7636
+ fs3.unlinkSync(PENDING_CHALLENGE_FILE);
7637
+ } catch {
7638
+ }
7639
+ }
7640
+ async function readStdin(stream = process.stdin) {
7641
+ const chunks = [];
7642
+ for await (const chunk of stream) {
7643
+ chunks.push(chunk);
7644
+ }
7645
+ return Buffer.concat(chunks).toString("utf-8");
7646
+ }
6939
7647
  function getGlobalOpts(args) {
6940
7648
  return {
6941
7649
  env: args.env,
@@ -6988,13 +7696,13 @@ var login = defineCommand2({
6988
7696
  if (args.token) {
6989
7697
  await client.loginWithToken(args.token, nip);
6990
7698
  } else if (args.p12) {
6991
- const fs7 = await import("fs");
6992
- const p12Buffer = fs7.readFileSync(args.p12);
7699
+ const fs10 = await import("fs");
7700
+ const p12Buffer = fs10.readFileSync(args.p12);
6993
7701
  await client.loginWithPkcs12(p12Buffer, args["p12-password"] ?? "", nip);
6994
7702
  } else if (args.cert && args.key) {
6995
- const fs7 = await import("fs");
6996
- const certPem = fs7.readFileSync(args.cert, "utf-8");
6997
- const keyPem = fs7.readFileSync(args.key, "utf-8");
7703
+ const fs10 = await import("fs");
7704
+ const certPem = fs10.readFileSync(args.cert, "utf-8");
7705
+ const keyPem = fs10.readFileSync(args.key, "utf-8");
6998
7706
  await client.loginWithCertificate(certPem, keyPem, nip);
6999
7707
  } else {
7000
7708
  throw new Error("Provide --token, --p12, or both --cert and --key for authentication.");
@@ -7096,15 +7804,109 @@ var whoami = defineCommand2({
7096
7804
  });
7097
7805
  }
7098
7806
  });
7807
+ var loginExternal = defineCommand2({
7808
+ meta: { name: "login-external", description: "Authenticate with externally-signed XAdES XML" },
7809
+ args: {
7810
+ generate: { type: "boolean", description: "Generate unsigned auth request XML" },
7811
+ submit: { type: "boolean", description: "Submit externally-signed XML" },
7812
+ nip: { type: "string", description: "NIP number (or identifier value for non-Nip context types)" },
7813
+ "context-type": { type: "string", description: "Context identifier type: Nip, InternalId, NipVatUe, PeppolId (default: Nip)" },
7814
+ output: { type: "string", description: "Write unsigned XML to file instead of stdout (--generate)" },
7815
+ input: { type: "string", description: "Read signed XML from file instead of stdin (--submit)" },
7816
+ env: { type: "string", description: "Environment (test/demo/prod)" },
7817
+ json: { type: "boolean", description: "Output as JSON" },
7818
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
7819
+ timeout: { type: "string", description: "Request timeout (ms)" }
7820
+ },
7821
+ run({ args }) {
7822
+ return withErrorHandler(async () => {
7823
+ const globalOpts = getGlobalOpts(args);
7824
+ const config = loadConfig();
7825
+ const nip = args.nip ?? config.nip;
7826
+ if (!nip) {
7827
+ throw new Error("NIP/identifier is required. Provide --nip or set it via `ksef config set --nip <nip>`.");
7828
+ }
7829
+ const contextType = args["context-type"] ?? "Nip";
7830
+ const validTypes = ["Nip", "InternalId", "NipVatUe", "PeppolId"];
7831
+ if (!validTypes.includes(contextType)) {
7832
+ throw new Error(`Invalid --context-type "${contextType}". Must be one of: ${validTypes.join(", ")}`);
7833
+ }
7834
+ if (!args.generate && !args.submit) {
7835
+ throw new Error("Specify --generate to create unsigned XML, or --submit to send signed XML.");
7836
+ }
7837
+ const client = createClient(globalOpts);
7838
+ if (args.generate) {
7839
+ const { buildUnsignedAuthTokenRequestXml: buildUnsignedAuthTokenRequestXml2 } = await Promise.resolve().then(() => (init_auth_xml_builder(), auth_xml_builder_exports));
7840
+ const challengeResult = await client.auth.getChallenge();
7841
+ const unsignedXml = buildUnsignedAuthTokenRequestXml2({
7842
+ challenge: challengeResult.challenge,
7843
+ contextIdentifier: { type: contextType, value: nip }
7844
+ });
7845
+ if (args.output) {
7846
+ fs3.writeFileSync(args.output, unsignedXml, "utf-8");
7847
+ process.stderr.write(`Unsigned XML written to ${args.output}
7848
+ `);
7849
+ } else {
7850
+ process.stdout.write(unsignedXml);
7851
+ }
7852
+ savePendingChallenge({
7853
+ challenge: challengeResult.challenge,
7854
+ timestamp: challengeResult.timestamp,
7855
+ contextIdentifier: { type: contextType, value: nip },
7856
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
7857
+ });
7858
+ process.stderr.write(`Challenge: ${challengeResult.challenge}
7859
+ `);
7860
+ process.stderr.write(`Timestamp: ${challengeResult.timestamp}
7861
+ `);
7862
+ process.stderr.write(`Note: Sign this XML and submit with --submit before the challenge expires.
7863
+ `);
7864
+ }
7865
+ if (args.submit) {
7866
+ let signedXml;
7867
+ if (args.input) {
7868
+ signedXml = fs3.readFileSync(args.input, "utf-8");
7869
+ } else {
7870
+ signedXml = await readStdin();
7871
+ }
7872
+ if (!signedXml.trim()) {
7873
+ throw new Error("No signed XML provided. Pipe signed XML to stdin or use --input <file>.");
7874
+ }
7875
+ const submitResult = await client.auth.submitXadesAuthRequest(signedXml);
7876
+ const authToken = submitResult.authenticationToken.token;
7877
+ await pollUntil(
7878
+ () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
7879
+ (s) => s.status.code !== 100,
7880
+ { intervalMs: 1e3, maxAttempts: 30, description: `auth ${submitResult.referenceNumber}` }
7881
+ );
7882
+ const tokens = await client.auth.getAccessToken(authToken);
7883
+ const session = {
7884
+ accessToken: tokens.accessToken.token,
7885
+ refreshToken: tokens.refreshToken.token,
7886
+ expiresAt: tokens.accessToken.validUntil,
7887
+ environment: args.env ?? config.environment
7888
+ };
7889
+ saveSession(session);
7890
+ if (args.env && args.env !== config.environment) {
7891
+ saveConfig({ ...config, environment: session.environment });
7892
+ }
7893
+ clearPendingChallenge();
7894
+ outputSuccess("Logged in successfully via external signature.");
7895
+ }
7896
+ });
7897
+ }
7898
+ });
7099
7899
  var authCommand = defineCommand2({
7100
7900
  meta: { name: "auth", description: "Authentication commands" },
7101
- subCommands: { challenge, login, status, logout, refresh, whoami }
7901
+ subCommands: { challenge, login, "login-external": loginExternal, status, logout, refresh, whoami }
7102
7902
  });
7103
7903
 
7104
7904
  // src/cli/commands/session.ts
7105
- import * as fs3 from "fs";
7905
+ import * as fs4 from "fs";
7106
7906
  import { defineCommand as defineCommand3 } from "citty";
7107
7907
  import { consola as consola5 } from "consola";
7908
+ init_document_structures();
7909
+ init_xml();
7108
7910
  function getGlobalOpts2(args) {
7109
7911
  return {
7110
7912
  env: args.env,
@@ -7118,6 +7920,7 @@ var open = defineCommand3({
7118
7920
  meta: { name: "open", description: "Open a KSeF session (online or batch)" },
7119
7921
  args: {
7120
7922
  batch: { type: "boolean", description: "Open a batch session instead of online" },
7923
+ formCode: { type: "string", description: "Document type: FA2, FA3, PEF3, PEFKOR3, FARR1 (default: FA2)" },
7121
7924
  env: { type: "string", description: "Environment (test/demo/prod)" },
7122
7925
  json: { type: "boolean", description: "Output as JSON" },
7123
7926
  verbose: { type: "boolean", description: "Show HTTP request/response details" },
@@ -7135,7 +7938,15 @@ var open = defineCommand3({
7135
7938
  }
7136
7939
  await client.crypto.init();
7137
7940
  const encryptionData = client.crypto.getEncryptionData();
7138
- const formCode = { systemCode: "FA (2)", schemaVersion: "1-0E", value: "FA" };
7941
+ const formCodeKey = args.formCode;
7942
+ let formCode = FORM_CODES.FA_2;
7943
+ if (formCodeKey) {
7944
+ const resolved = FORM_CODE_KEYS[formCodeKey];
7945
+ if (!resolved) {
7946
+ throw new Error(`Invalid form code "${formCodeKey}". Valid keys: ${Object.keys(FORM_CODE_KEYS).join(", ")}`);
7947
+ }
7948
+ formCode = resolved;
7949
+ }
7139
7950
  if (args.batch) {
7140
7951
  throw new Error("Batch session open is used internally by `ksef invoice send <dir>`. Use `ksef session open` for online sessions.");
7141
7952
  }
@@ -7373,6 +8184,7 @@ var upo = defineCommand3({
7373
8184
  upoRef: { type: "string", description: "UPO reference" },
7374
8185
  ksefNumber: { type: "string", description: "KSeF invoice number" },
7375
8186
  invoiceRef: { type: "string", description: "Invoice reference" },
8187
+ parsed: { type: "boolean", description: "Parse UPO XML and output as JSON" },
7376
8188
  o: { type: "string", description: "Output file path" },
7377
8189
  env: { type: "string", description: "Environment (test/demo/prod)" },
7378
8190
  json: { type: "boolean", description: "Output as JSON" },
@@ -7394,12 +8206,23 @@ var upo = defineCommand3({
7394
8206
  } else {
7395
8207
  throw new Error("Provide one of: --upo-ref, --ksef-number, or --invoice-ref");
7396
8208
  }
8209
+ if (args.parsed) {
8210
+ const parsed = parseUpoXml(result.upo);
8211
+ const json = JSON.stringify(parsed, null, 2);
8212
+ if (args.o) {
8213
+ fs4.writeFileSync(args.o, json, "utf-8");
8214
+ outputSuccess(`Parsed UPO saved to ${args.o}`);
8215
+ } else {
8216
+ console.log(json);
8217
+ }
8218
+ return;
8219
+ }
7397
8220
  if (args.json) {
7398
8221
  outputResult(result, { json: true });
7399
8222
  return;
7400
8223
  }
7401
8224
  if (args.o) {
7402
- fs3.writeFileSync(args.o, result.upo, "utf-8");
8225
+ fs4.writeFileSync(args.o, result.upo, "utf-8");
7403
8226
  outputSuccess(`UPO saved to ${args.o}`);
7404
8227
  } else {
7405
8228
  console.log(result.upo);
@@ -7529,10 +8352,173 @@ var sessionCommand = defineCommand3({
7529
8352
  });
7530
8353
 
7531
8354
  // src/cli/commands/invoice.ts
7532
- import * as fs4 from "fs";
7533
- import * as path3 from "path";
8355
+ import * as fs7 from "fs";
8356
+ import * as path5 from "path";
8357
+ import { Readable } from "stream";
8358
+ import { defineCommand as defineCommand5 } from "citty";
8359
+ import { consola as consola7 } from "consola";
8360
+ init_document_structures();
8361
+
8362
+ // src/cli/commands/export-incremental.ts
8363
+ import * as fs6 from "fs";
8364
+ import * as path4 from "path";
7534
8365
  import { defineCommand as defineCommand4 } from "citty";
7535
8366
  import { consola as consola6 } from "consola";
8367
+
8368
+ // src/workflows/hwm-storage.ts
8369
+ import * as fs5 from "fs/promises";
8370
+ var FileHwmStore = class {
8371
+ constructor(filePath) {
8372
+ this.filePath = filePath;
8373
+ }
8374
+ async load() {
8375
+ try {
8376
+ const data = await fs5.readFile(this.filePath, "utf-8");
8377
+ return JSON.parse(data);
8378
+ } catch (err) {
8379
+ if (err.code === "ENOENT") {
8380
+ return {};
8381
+ }
8382
+ throw err;
8383
+ }
8384
+ }
8385
+ async save(points) {
8386
+ await fs5.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8387
+ }
8388
+ };
8389
+
8390
+ // src/utils/zip.ts
8391
+ import { ZipFile } from "yazl";
8392
+ import { fromBuffer } from "yauzl";
8393
+
8394
+ // src/workflows/invoice-export-workflow.ts
8395
+ init_polling();
8396
+ async function doExport(client, filters, options) {
8397
+ await client.crypto.init();
8398
+ const encData = client.crypto.getEncryptionData();
8399
+ const opResp = await client.invoices.exportInvoices({
8400
+ encryption: encData.encryptionInfo,
8401
+ filters,
8402
+ onlyMetadata: options?.onlyMetadata
8403
+ });
8404
+ const result = await pollUntil(
8405
+ () => client.invoices.getInvoiceExportStatus(opResp.referenceNumber),
8406
+ (s) => s.status.code === 200 || s.status.code >= 400,
8407
+ { ...options?.pollOptions, description: `export ${opResp.referenceNumber}` }
8408
+ );
8409
+ if (result.status.code !== 200) {
8410
+ throw new Error(`Export failed: ${result.status.code} \u2014 ${result.status.description}`);
8411
+ }
8412
+ if (!result.package) {
8413
+ throw new Error("Export completed but no package available");
8414
+ }
8415
+ return {
8416
+ encData,
8417
+ referenceNumber: opResp.referenceNumber,
8418
+ result: {
8419
+ parts: result.package.parts.map((p) => ({
8420
+ ordinalNumber: p.ordinalNumber,
8421
+ url: p.url,
8422
+ method: p.method,
8423
+ partSize: p.partSize,
8424
+ encryptedPartSize: p.encryptedPartSize,
8425
+ encryptedPartHash: p.encryptedPartHash,
8426
+ expirationDate: p.expirationDate
8427
+ })),
8428
+ invoiceCount: result.package.invoiceCount,
8429
+ isTruncated: result.package.isTruncated,
8430
+ permanentStorageHwmDate: result.package.permanentStorageHwmDate,
8431
+ lastPermanentStorageDate: result.package.lastPermanentStorageDate
8432
+ }
8433
+ };
8434
+ }
8435
+
8436
+ // src/workflows/hwm-coordinator.ts
8437
+ function updateContinuationPoint(points, subjectType, pkg2) {
8438
+ if (pkg2.isTruncated && pkg2.lastPermanentStorageDate) {
8439
+ points[subjectType] = pkg2.lastPermanentStorageDate;
8440
+ } else if (pkg2.permanentStorageHwmDate) {
8441
+ points[subjectType] = pkg2.permanentStorageHwmDate;
8442
+ } else {
8443
+ delete points[subjectType];
8444
+ }
8445
+ }
8446
+ function getEffectiveStartDate(points, subjectType, windowFrom) {
8447
+ return points[subjectType] ?? windowFrom;
8448
+ }
8449
+
8450
+ // src/workflows/incremental-export-workflow.ts
8451
+ async function incrementalExportAndDownload(client, options) {
8452
+ const maxIterations = options.maxIterations ?? 20;
8453
+ const points = options.continuationPoints;
8454
+ if (options.store) {
8455
+ const loaded = await options.store.load();
8456
+ for (const [key, value] of Object.entries(loaded)) {
8457
+ if (value !== void 0 && points[key] === void 0) {
8458
+ points[key] = value;
8459
+ }
8460
+ }
8461
+ }
8462
+ const referenceNumbers = [];
8463
+ const decryptedParts = [];
8464
+ let previousFrom;
8465
+ let iteration = 0;
8466
+ for (; iteration < maxIterations; iteration++) {
8467
+ const effectiveFrom = getEffectiveStartDate(points, options.subjectType, options.windowFrom);
8468
+ if (previousFrom !== void 0 && effectiveFrom === previousFrom) {
8469
+ break;
8470
+ }
8471
+ previousFrom = effectiveFrom;
8472
+ const filters = options.filtersFactory ? options.filtersFactory(effectiveFrom, options.windowTo) : buildDefaultFilters(options.subjectType, effectiveFrom, options.windowTo);
8473
+ const { result, encData, referenceNumber } = await doExport(client, filters, {
8474
+ onlyMetadata: options.onlyMetadata,
8475
+ pollOptions: options.pollOptions
8476
+ });
8477
+ referenceNumbers.push(referenceNumber);
8478
+ const download = options.transport ?? fetch;
8479
+ for (const part of result.parts) {
8480
+ const resp = await download(part.url, { method: part.method });
8481
+ if (!resp.ok) {
8482
+ throw new Error(`Download failed for part ${part.ordinalNumber}: HTTP ${resp.status}`);
8483
+ }
8484
+ const encryptedData = new Uint8Array(await resp.arrayBuffer());
8485
+ const decrypted = client.crypto.decryptAES256(encryptedData, encData.cipherKey, encData.cipherIv);
8486
+ decryptedParts.push(decrypted);
8487
+ }
8488
+ updateContinuationPoint(points, options.subjectType, {
8489
+ isTruncated: result.isTruncated,
8490
+ lastPermanentStorageDate: result.lastPermanentStorageDate,
8491
+ permanentStorageHwmDate: result.permanentStorageHwmDate
8492
+ });
8493
+ if (options.store) {
8494
+ await options.store.save(points);
8495
+ }
8496
+ options.onIterationComplete?.(iteration, result);
8497
+ if (!result.isTruncated) {
8498
+ iteration++;
8499
+ break;
8500
+ }
8501
+ }
8502
+ return {
8503
+ referenceNumbers,
8504
+ invoices: [],
8505
+ decryptedParts,
8506
+ continuationPoints: points,
8507
+ iterationCount: iteration
8508
+ };
8509
+ }
8510
+ function buildDefaultFilters(subjectType, from, to) {
8511
+ return {
8512
+ subjectType,
8513
+ dateRange: {
8514
+ dateType: "PermanentStorage",
8515
+ from,
8516
+ to
8517
+ }
8518
+ };
8519
+ }
8520
+
8521
+ // src/cli/commands/export-incremental.ts
7536
8522
  function getGlobalOpts3(args) {
7537
8523
  return {
7538
8524
  env: args.env,
@@ -7542,6 +8528,101 @@ function getGlobalOpts3(args) {
7542
8528
  nip: args.nip
7543
8529
  };
7544
8530
  }
8531
+ var exportIncremental = defineCommand4({
8532
+ meta: { name: "export-incremental", description: "Incremental invoice export with HWM state persistence" },
8533
+ args: {
8534
+ from: { type: "string", description: "Start date (YYYY-MM-DD) \u2014 required", required: true },
8535
+ to: { type: "string", description: "End date (YYYY-MM-DD)" },
8536
+ subjectType: { type: "string", description: "Subject type: Subject1|Subject2|Subject3|SubjectAuthorized (default: Subject1)" },
8537
+ stateFile: { type: "string", description: "HWM state file path (default: ./ksef-hwm-state.json)" },
8538
+ outputDir: { type: "string", description: "Output directory for exported parts (default: ./ksef-exports/)" },
8539
+ maxIterations: { type: "string", description: "Max export iterations (default: 20)" },
8540
+ env: { type: "string", description: "Environment (test/demo/prod)" },
8541
+ json: { type: "boolean", description: "Output as JSON" },
8542
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
8543
+ timeout: { type: "string", description: "Request timeout (ms)" },
8544
+ nip: { type: "string", description: "NIP number" }
8545
+ },
8546
+ run({ args }) {
8547
+ return withErrorHandler(async () => {
8548
+ const globalOpts = getGlobalOpts3(args);
8549
+ const { client } = requireSession(globalOpts);
8550
+ const from = args.from;
8551
+ const to = args.to ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8552
+ const subjectType = args.subjectType ?? "Subject1";
8553
+ const stateFile = args.stateFile ?? "./ksef-hwm-state.json";
8554
+ const outputDir = args.outputDir ?? "./ksef-exports";
8555
+ const maxIterations = args.maxIterations ? parseInt(args.maxIterations, 10) : 20;
8556
+ const isJson = args.json;
8557
+ const store = new FileHwmStore(stateFile);
8558
+ const continuationPoints = {};
8559
+ if (!fs6.existsSync(outputDir)) {
8560
+ fs6.mkdirSync(outputDir, { recursive: true });
8561
+ }
8562
+ if (!isJson) {
8563
+ consola6.start(`Incremental export: ${from} \u2192 ${to}, subject: ${subjectType}`);
8564
+ consola6.info(`State file: ${stateFile}`);
8565
+ consola6.info(`Output dir: ${outputDir}`);
8566
+ }
8567
+ const iterationParts = [];
8568
+ const result = await incrementalExportAndDownload(client, {
8569
+ subjectType,
8570
+ windowFrom: from,
8571
+ windowTo: to,
8572
+ continuationPoints,
8573
+ maxIterations,
8574
+ store,
8575
+ pollOptions: { intervalMs: 2e3 },
8576
+ onIterationComplete: (iteration, iterResult) => {
8577
+ iterationParts.push({ iteration, partCount: iterResult.parts.length });
8578
+ if (!isJson) {
8579
+ const hwmDate = continuationPoints[subjectType] ?? "complete";
8580
+ consola6.info(
8581
+ `Iteration ${iteration + 1}: ${iterResult.invoiceCount} invoices, truncated: ${iterResult.isTruncated}, HWM: ${hwmDate}`
8582
+ );
8583
+ }
8584
+ }
8585
+ });
8586
+ let partIndex = 0;
8587
+ for (const { iteration, partCount } of iterationParts) {
8588
+ for (let p = 0; p < partCount; p++) {
8589
+ if (partIndex < result.decryptedParts.length) {
8590
+ const fileName = `iter-${String(iteration + 1).padStart(3, "0")}-part-${String(p + 1).padStart(3, "0")}.zip`;
8591
+ const filePath = path4.join(outputDir, fileName);
8592
+ fs6.writeFileSync(filePath, result.decryptedParts[partIndex]);
8593
+ partIndex++;
8594
+ }
8595
+ }
8596
+ }
8597
+ if (isJson) {
8598
+ outputResult({
8599
+ referenceNumbers: result.referenceNumbers,
8600
+ iterationCount: result.iterationCount,
8601
+ totalParts: result.decryptedParts.length,
8602
+ continuationPoints: result.continuationPoints,
8603
+ outputDir
8604
+ }, { json: true });
8605
+ } else {
8606
+ outputSuccess(
8607
+ `Export complete: ${result.iterationCount} iterations, ${result.decryptedParts.length} parts downloaded`
8608
+ );
8609
+ consola6.info(`Final HWM: ${continuationPoints[subjectType] ?? "complete"}`);
8610
+ consola6.info(`Output: ${outputDir}`);
8611
+ }
8612
+ });
8613
+ }
8614
+ });
8615
+
8616
+ // src/cli/commands/invoice.ts
8617
+ function getGlobalOpts4(args) {
8618
+ return {
8619
+ env: args.env,
8620
+ json: args.json,
8621
+ verbose: args.verbose,
8622
+ timeout: args.timeout,
8623
+ nip: args.nip
8624
+ };
8625
+ }
7545
8626
  function buildQueryFilters(args) {
7546
8627
  const from = args.from;
7547
8628
  if (!from) {
@@ -7585,11 +8666,13 @@ var QUERY_FILTER_ARGS = {
7585
8666
  amountType: { type: "string", description: "Amount type: Brutto|Netto|Vat (default: Brutto)" },
7586
8667
  currency: { type: "string", description: "Currency code (e.g. PLN, EUR)" }
7587
8668
  };
7588
- var send = defineCommand4({
8669
+ var send = defineCommand5({
7589
8670
  meta: { name: "send", description: "Send invoice(s) \u2014 single XML file or directory for batch" },
7590
8671
  args: {
7591
- path: { type: "positional", description: "Path to XML file or directory of XMLs", required: true },
8672
+ path: { type: "positional", description: "Path to XML file, directory of XMLs, or ZIP for batch", required: true },
7592
8673
  sessionRef: { type: "string", description: "Override online session reference" },
8674
+ stream: { type: "boolean", description: "Use stream-based batch upload (for ZIP files, reduces memory usage)" },
8675
+ formCode: { type: "string", description: "Document type: FA2, FA3, PEF3, PEFKOR3, FARR1 (default: FA2)" },
7593
8676
  env: { type: "string", description: "Environment (test/demo/prod)" },
7594
8677
  json: { type: "boolean", description: "Output as JSON" },
7595
8678
  verbose: { type: "boolean", description: "Show HTTP request/response details" },
@@ -7598,29 +8681,65 @@ var send = defineCommand4({
7598
8681
  },
7599
8682
  run({ args }) {
7600
8683
  return withErrorHandler(async () => {
7601
- const globalOpts = getGlobalOpts3(args);
8684
+ const globalOpts = getGlobalOpts4(args);
7602
8685
  const { client, session } = requireSession(globalOpts);
7603
8686
  const config = loadConfig();
7604
8687
  const nip = args.nip ?? config.nip;
7605
8688
  const filePath = args.path;
7606
- if (!fs4.existsSync(filePath)) {
8689
+ const formCodeKey = args.formCode;
8690
+ let formCode = FORM_CODES.FA_2;
8691
+ if (formCodeKey) {
8692
+ const resolved = FORM_CODE_KEYS[formCodeKey];
8693
+ if (!resolved) {
8694
+ throw new Error(`Invalid form code "${formCodeKey}". Valid keys: ${Object.keys(FORM_CODE_KEYS).join(", ")}`);
8695
+ }
8696
+ formCode = resolved;
8697
+ }
8698
+ if (!fs7.existsSync(filePath)) {
7607
8699
  throw new Error(`Path not found: ${filePath}`);
7608
8700
  }
7609
- const stat = fs4.statSync(filePath);
8701
+ const stat = fs7.statSync(filePath);
8702
+ if (args.stream) {
8703
+ if (!filePath.endsWith(".zip") || stat.isDirectory()) {
8704
+ throw new Error("--stream requires a .zip file path.");
8705
+ }
8706
+ if (!nip) {
8707
+ throw new Error("NIP is required. Provide --nip or set it via `ksef config set --nip <nip>`.");
8708
+ }
8709
+ if (!validateFormCodeForSession(formCode, "batch")) {
8710
+ throw new Error(`Document type "${formCode.systemCode}" is not supported in batch sessions. PEF/PEF_KOR require online sessions.`);
8711
+ }
8712
+ const { uploadBatchStream: uploadBatchStream2 } = await Promise.resolve().then(() => (init_batch_session_workflow(), batch_session_workflow_exports));
8713
+ const zipSize = stat.size;
8714
+ const zipStreamFactory = () => Readable.toWeb(fs7.createReadStream(filePath));
8715
+ if (!args.json) consola7.start(`Sending batch via stream (${(zipSize / 1e6).toFixed(1)} MB)...`);
8716
+ const result = await uploadBatchStream2(client, zipStreamFactory, zipSize, {
8717
+ formCode,
8718
+ pollOptions: { intervalMs: 3e3 }
8719
+ });
8720
+ if (args.json) {
8721
+ outputResult(result, { json: true });
8722
+ } else {
8723
+ outputSuccess(`Batch sent via stream. Ref: ${result.sessionRef}, invoices: ${result.upo.invoiceCount ?? "unknown"}`);
8724
+ }
8725
+ return;
8726
+ }
7610
8727
  if (stat.isDirectory()) {
7611
- const xmlFiles = fs4.readdirSync(filePath).filter((f) => f.endsWith(".xml")).map((f) => path3.join(filePath, f));
8728
+ const xmlFiles = fs7.readdirSync(filePath).filter((f) => f.endsWith(".xml")).map((f) => path5.join(filePath, f));
7612
8729
  if (xmlFiles.length === 0) {
7613
8730
  throw new Error(`No XML files found in ${filePath}`);
7614
8731
  }
7615
8732
  if (!nip) {
7616
8733
  throw new Error("NIP is required. Provide --nip or set it via `ksef config set --nip <nip>`.");
7617
8734
  }
7618
- if (!args.json) consola6.start(`Sending ${xmlFiles.length} invoices via batch session...`);
8735
+ if (!validateFormCodeForSession(formCode, "batch")) {
8736
+ throw new Error(`Document type "${formCode.systemCode}" is not supported in batch sessions. PEF/PEF_KOR require online sessions.`);
8737
+ }
8738
+ if (!args.json) consola7.start(`Sending ${xmlFiles.length} invoices via batch session...`);
7619
8739
  await client.crypto.init();
7620
8740
  const encryptionData = client.crypto.getEncryptionData();
7621
- const formCode = { systemCode: "FA (2)", schemaVersion: "1-0E", value: "FA" };
7622
8741
  const parts = xmlFiles.map((file, i) => {
7623
- const content = fs4.readFileSync(file);
8742
+ const content = fs7.readFileSync(file);
7624
8743
  const metadata = client.crypto.getFileMetadata(new Uint8Array(content));
7625
8744
  return {
7626
8745
  data: content.buffer,
@@ -7628,7 +8747,7 @@ var send = defineCommand4({
7628
8747
  ordinalNumber: i + 1
7629
8748
  };
7630
8749
  });
7631
- const totalContent = Buffer.concat(xmlFiles.map((f) => fs4.readFileSync(f)));
8750
+ const totalContent = Buffer.concat(xmlFiles.map((f) => fs7.readFileSync(f)));
7632
8751
  const totalMetadata = client.crypto.getFileMetadata(new Uint8Array(totalContent));
7633
8752
  const batchFileInfo = {
7634
8753
  fileSize: totalMetadata.fileSize,
@@ -7656,10 +8775,10 @@ var send = defineCommand4({
7656
8775
  if (!ref) {
7657
8776
  throw new Error("No active online session. Run `ksef session open` or provide --session-ref.");
7658
8777
  }
7659
- if (!args.json) consola6.start("Sending invoice...");
8778
+ if (!args.json) consola7.start("Sending invoice...");
7660
8779
  await client.crypto.init();
7661
8780
  const encryptionData = client.crypto.getEncryptionData();
7662
- const xmlContent = fs4.readFileSync(filePath);
8781
+ const xmlContent = fs7.readFileSync(filePath);
7663
8782
  const xmlBytes = new Uint8Array(xmlContent);
7664
8783
  const plainMetadata = client.crypto.getFileMetadata(xmlBytes);
7665
8784
  const encrypted = client.crypto.encryptAES256(xmlBytes, encryptionData.cipherKey, encryptionData.cipherIv);
@@ -7680,7 +8799,7 @@ var send = defineCommand4({
7680
8799
  });
7681
8800
  }
7682
8801
  });
7683
- var get = defineCommand4({
8802
+ var get = defineCommand5({
7684
8803
  meta: { name: "get", description: "Download invoice by KSeF number" },
7685
8804
  args: {
7686
8805
  ksefNumber: { type: "positional", description: "KSeF invoice number", required: true },
@@ -7692,7 +8811,7 @@ var get = defineCommand4({
7692
8811
  },
7693
8812
  run({ args }) {
7694
8813
  return withErrorHandler(async () => {
7695
- const globalOpts = getGlobalOpts3(args);
8814
+ const globalOpts = getGlobalOpts4(args);
7696
8815
  const { client } = requireSession(globalOpts);
7697
8816
  const xml = await client.invoices.getInvoice(args.ksefNumber);
7698
8817
  if (args.json) {
@@ -7700,7 +8819,7 @@ var get = defineCommand4({
7700
8819
  return;
7701
8820
  }
7702
8821
  if (args.o) {
7703
- fs4.writeFileSync(args.o, xml, "utf-8");
8822
+ fs7.writeFileSync(args.o, xml, "utf-8");
7704
8823
  outputSuccess(`Invoice saved to ${args.o}`);
7705
8824
  } else {
7706
8825
  console.log(xml);
@@ -7708,7 +8827,7 @@ var get = defineCommand4({
7708
8827
  });
7709
8828
  }
7710
8829
  });
7711
- var query = defineCommand4({
8830
+ var query = defineCommand5({
7712
8831
  meta: { name: "query", description: "Query invoice metadata" },
7713
8832
  args: {
7714
8833
  ...QUERY_FILTER_ARGS,
@@ -7722,7 +8841,7 @@ var query = defineCommand4({
7722
8841
  },
7723
8842
  run({ args }) {
7724
8843
  return withErrorHandler(async () => {
7725
- const globalOpts = getGlobalOpts3(args);
8844
+ const globalOpts = getGlobalOpts4(args);
7726
8845
  const { client } = requireSession(globalOpts);
7727
8846
  const filters = buildQueryFilters(args);
7728
8847
  const pageOffset = args.page ? parseInt(args.page, 10) : void 0;
@@ -7737,7 +8856,7 @@ var query = defineCommand4({
7737
8856
  return;
7738
8857
  }
7739
8858
  if (result.invoices.length === 0) {
7740
- consola6.info("No invoices found matching the criteria.");
8859
+ consola7.info("No invoices found matching the criteria.");
7741
8860
  return;
7742
8861
  }
7743
8862
  outputTable(
@@ -7760,12 +8879,12 @@ var query = defineCommand4({
7760
8879
  { json: false }
7761
8880
  );
7762
8881
  if (result.hasMore) {
7763
- consola6.info("More results available. Use --page to fetch the next page.");
8882
+ consola7.info("More results available. Use --page to fetch the next page.");
7764
8883
  }
7765
8884
  });
7766
8885
  }
7767
8886
  });
7768
- var exportCmd = defineCommand4({
8887
+ var exportCmd = defineCommand5({
7769
8888
  meta: { name: "export", description: "Start invoice export" },
7770
8889
  args: {
7771
8890
  ...QUERY_FILTER_ARGS,
@@ -7777,9 +8896,9 @@ var exportCmd = defineCommand4({
7777
8896
  },
7778
8897
  run({ args }) {
7779
8898
  return withErrorHandler(async () => {
7780
- const globalOpts = getGlobalOpts3(args);
8899
+ const globalOpts = getGlobalOpts4(args);
7781
8900
  const { client } = requireSession(globalOpts);
7782
- if (!args.json) consola6.start("Starting invoice export...");
8901
+ if (!args.json) consola7.start("Starting invoice export...");
7783
8902
  await client.crypto.init();
7784
8903
  const encryptionData = client.crypto.getEncryptionData();
7785
8904
  const filters = buildQueryFilters(args);
@@ -7790,12 +8909,12 @@ var exportCmd = defineCommand4({
7790
8909
  outputResult(result, { json: true });
7791
8910
  } else {
7792
8911
  outputSuccess(`Export started. Ref: ${result.referenceNumber}`);
7793
- consola6.info("Check status with: ksef invoice export-status " + result.referenceNumber);
8912
+ consola7.info("Check status with: ksef invoice export-status " + result.referenceNumber);
7794
8913
  }
7795
8914
  });
7796
8915
  }
7797
8916
  });
7798
- var exportStatus = defineCommand4({
8917
+ var exportStatus = defineCommand5({
7799
8918
  meta: { name: "export-status", description: "Check invoice export status" },
7800
8919
  args: {
7801
8920
  ref: { type: "positional", description: "Export reference number", required: true },
@@ -7806,22 +8925,22 @@ var exportStatus = defineCommand4({
7806
8925
  },
7807
8926
  run({ args }) {
7808
8927
  return withErrorHandler(async () => {
7809
- const globalOpts = getGlobalOpts3(args);
8928
+ const globalOpts = getGlobalOpts4(args);
7810
8929
  const { client } = requireSession(globalOpts);
7811
8930
  const result = await client.invoices.getInvoiceExportStatus(args.ref);
7812
8931
  if (args.json) {
7813
8932
  outputResult(result, { json: true });
7814
8933
  return;
7815
8934
  }
7816
- consola6.info(`Status: ${result.status.code} \u2014 ${result.status.description}`);
8935
+ consola7.info(`Status: ${result.status.code} \u2014 ${result.status.description}`);
7817
8936
  if (result.completedDate) {
7818
- consola6.info(`Completed: ${result.completedDate}`);
8937
+ consola7.info(`Completed: ${result.completedDate}`);
7819
8938
  }
7820
8939
  if (result.packageExpirationDate) {
7821
- consola6.info(`Package expires: ${result.packageExpirationDate}`);
8940
+ consola7.info(`Package expires: ${result.packageExpirationDate}`);
7822
8941
  }
7823
8942
  if (result.package) {
7824
- consola6.info(`Invoices: ${result.package.invoiceCount}, Size: ${result.package.size} bytes`);
8943
+ consola7.info(`Invoices: ${result.package.invoiceCount}, Size: ${result.package.size} bytes`);
7825
8944
  if (result.package.parts.length > 0) {
7826
8945
  outputTable(
7827
8946
  result.package.parts.map((p) => ({
@@ -7845,14 +8964,14 @@ var exportStatus = defineCommand4({
7845
8964
  });
7846
8965
  }
7847
8966
  });
7848
- var invoiceCommand = defineCommand4({
8967
+ var invoiceCommand = defineCommand5({
7849
8968
  meta: { name: "invoice", description: "Invoice commands" },
7850
- subCommands: { send, get, query, export: exportCmd, "export-status": exportStatus }
8969
+ subCommands: { send, get, query, export: exportCmd, "export-status": exportStatus, "export-incremental": exportIncremental }
7851
8970
  });
7852
8971
 
7853
8972
  // src/cli/commands/permission.ts
7854
- import { defineCommand as defineCommand5 } from "citty";
7855
- function getGlobalOpts4(args) {
8973
+ import { defineCommand as defineCommand6 } from "citty";
8974
+ function getGlobalOpts5(args) {
7856
8975
  return {
7857
8976
  env: args.env,
7858
8977
  json: args.json,
@@ -7861,7 +8980,7 @@ function getGlobalOpts4(args) {
7861
8980
  nip: args.nip
7862
8981
  };
7863
8982
  }
7864
- var grant = defineCommand5({
8983
+ var grant = defineCommand6({
7865
8984
  meta: { name: "grant", description: "Grant permissions to a subject" },
7866
8985
  args: {
7867
8986
  type: { type: "string", description: "Grant type: person, entity, authorization, indirect, subunit, eu-entity-admin, eu-entity-representative", required: true },
@@ -7886,7 +9005,7 @@ var grant = defineCommand5({
7886
9005
  },
7887
9006
  run({ args }) {
7888
9007
  return withErrorHandler(async () => {
7889
- const globalOpts = getGlobalOpts4(args);
9008
+ const globalOpts = getGlobalOpts5(args);
7890
9009
  const { client } = requireSession(globalOpts);
7891
9010
  let result;
7892
9011
  switch (args.type) {
@@ -8042,7 +9161,7 @@ var grant = defineCommand5({
8042
9161
  });
8043
9162
  }
8044
9163
  });
8045
- var revoke2 = defineCommand5({
9164
+ var revoke2 = defineCommand6({
8046
9165
  meta: { name: "revoke", description: "Revoke a permission grant" },
8047
9166
  args: {
8048
9167
  grantId: { type: "positional", description: "Grant ID to revoke", required: true },
@@ -8055,7 +9174,7 @@ var revoke2 = defineCommand5({
8055
9174
  },
8056
9175
  run({ args }) {
8057
9176
  return withErrorHandler(async () => {
8058
- const globalOpts = getGlobalOpts4(args);
9177
+ const globalOpts = getGlobalOpts5(args);
8059
9178
  const { client } = requireSession(globalOpts);
8060
9179
  let result;
8061
9180
  if (args.authorization) {
@@ -8071,7 +9190,7 @@ var revoke2 = defineCommand5({
8071
9190
  });
8072
9191
  }
8073
9192
  });
8074
- var search = defineCommand5({
9193
+ var search = defineCommand6({
8075
9194
  meta: { name: "search", description: "Search permissions" },
8076
9195
  args: {
8077
9196
  type: { type: "string", description: "Search type: personal, persons, subunits, entities, entities-grants, subordinate-entities, authorizations, eu-entities", required: true },
@@ -8088,7 +9207,7 @@ var search = defineCommand5({
8088
9207
  },
8089
9208
  run({ args }) {
8090
9209
  return withErrorHandler(async () => {
8091
- const globalOpts = getGlobalOpts4(args);
9210
+ const globalOpts = getGlobalOpts5(args);
8092
9211
  const { client } = requireSession(globalOpts);
8093
9212
  const page = args.page ? parseInt(args.page, 10) : void 0;
8094
9213
  const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
@@ -8310,7 +9429,7 @@ var search = defineCommand5({
8310
9429
  });
8311
9430
  }
8312
9431
  });
8313
- var status3 = defineCommand5({
9432
+ var status3 = defineCommand6({
8314
9433
  meta: { name: "status", description: "Check permission operation status" },
8315
9434
  args: {
8316
9435
  ref: { type: "positional", description: "Operation reference number", required: true },
@@ -8322,7 +9441,7 @@ var status3 = defineCommand5({
8322
9441
  },
8323
9442
  run({ args }) {
8324
9443
  return withErrorHandler(async () => {
8325
- const globalOpts = getGlobalOpts4(args);
9444
+ const globalOpts = getGlobalOpts5(args);
8326
9445
  const { client } = requireSession(globalOpts);
8327
9446
  const result = await client.permissions.getOperationStatus(args.ref);
8328
9447
  if (args.json) {
@@ -8336,7 +9455,7 @@ var status3 = defineCommand5({
8336
9455
  });
8337
9456
  }
8338
9457
  });
8339
- var attachmentStatus = defineCommand5({
9458
+ var attachmentStatus = defineCommand6({
8340
9459
  meta: { name: "attachment-status", description: "Check if attachment permissions are allowed" },
8341
9460
  args: {
8342
9461
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -8347,7 +9466,7 @@ var attachmentStatus = defineCommand5({
8347
9466
  },
8348
9467
  run({ args }) {
8349
9468
  return withErrorHandler(async () => {
8350
- const globalOpts = getGlobalOpts4(args);
9469
+ const globalOpts = getGlobalOpts5(args);
8351
9470
  const { client } = requireSession(globalOpts);
8352
9471
  const result = await client.permissions.getAttachmentStatus();
8353
9472
  if (args.json) {
@@ -8360,15 +9479,15 @@ var attachmentStatus = defineCommand5({
8360
9479
  });
8361
9480
  }
8362
9481
  });
8363
- var permissionCommand = defineCommand5({
9482
+ var permissionCommand = defineCommand6({
8364
9483
  meta: { name: "permission", description: "Permission management commands" },
8365
9484
  subCommands: { grant, revoke: revoke2, search, status: status3, "attachment-status": attachmentStatus }
8366
9485
  });
8367
9486
 
8368
9487
  // src/cli/commands/token.ts
8369
- import { defineCommand as defineCommand6 } from "citty";
8370
- import { consola as consola7 } from "consola";
8371
- function getGlobalOpts5(args) {
9488
+ import { defineCommand as defineCommand7 } from "citty";
9489
+ import { consola as consola8 } from "consola";
9490
+ function getGlobalOpts6(args) {
8372
9491
  return {
8373
9492
  env: args.env,
8374
9493
  json: args.json,
@@ -8377,7 +9496,7 @@ function getGlobalOpts5(args) {
8377
9496
  nip: args.nip
8378
9497
  };
8379
9498
  }
8380
- var generate = defineCommand6({
9499
+ var generate = defineCommand7({
8381
9500
  meta: { name: "generate", description: "Generate a new KSeF token" },
8382
9501
  args: {
8383
9502
  permissions: { type: "string", description: "Comma-separated permissions (e.g. InvoiceRead,InvoiceWrite)", required: true },
@@ -8390,7 +9509,7 @@ var generate = defineCommand6({
8390
9509
  },
8391
9510
  run({ args }) {
8392
9511
  return withErrorHandler(async () => {
8393
- const globalOpts = getGlobalOpts5(args);
9512
+ const globalOpts = getGlobalOpts6(args);
8394
9513
  const { client } = requireSession(globalOpts);
8395
9514
  if (!args.permissions) {
8396
9515
  throw new Error("--permissions is required. Provide comma-separated values (e.g. InvoiceRead,InvoiceWrite).");
@@ -8413,7 +9532,7 @@ var generate = defineCommand6({
8413
9532
  });
8414
9533
  }
8415
9534
  });
8416
- var list2 = defineCommand6({
9535
+ var list2 = defineCommand7({
8417
9536
  meta: { name: "list", description: "List KSeF tokens" },
8418
9537
  args: {
8419
9538
  status: { type: "string", description: "Comma-separated statuses (e.g. Active,Pending)" },
@@ -8430,7 +9549,7 @@ var list2 = defineCommand6({
8430
9549
  },
8431
9550
  run({ args }) {
8432
9551
  return withErrorHandler(async () => {
8433
- const globalOpts = getGlobalOpts5(args);
9552
+ const globalOpts = getGlobalOpts6(args);
8434
9553
  const { client } = requireSession(globalOpts);
8435
9554
  const options = {
8436
9555
  continuationToken: args.continue,
@@ -8467,12 +9586,12 @@ var list2 = defineCommand6({
8467
9586
  { json: false }
8468
9587
  );
8469
9588
  if (result.continuationToken) {
8470
- consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
9589
+ consola8.info(`More results available. Continuation token: ${result.continuationToken}`);
8471
9590
  }
8472
9591
  });
8473
9592
  }
8474
9593
  });
8475
- var get2 = defineCommand6({
9594
+ var get2 = defineCommand7({
8476
9595
  meta: { name: "get", description: "Get token details" },
8477
9596
  args: {
8478
9597
  ref: { type: "positional", description: "Token reference number", required: true },
@@ -8484,7 +9603,7 @@ var get2 = defineCommand6({
8484
9603
  },
8485
9604
  run({ args }) {
8486
9605
  return withErrorHandler(async () => {
8487
- const globalOpts = getGlobalOpts5(args);
9606
+ const globalOpts = getGlobalOpts6(args);
8488
9607
  const { client } = requireSession(globalOpts);
8489
9608
  const ref = args.ref;
8490
9609
  const result = await client.tokens.getToken(ref);
@@ -8505,7 +9624,7 @@ var get2 = defineCommand6({
8505
9624
  });
8506
9625
  }
8507
9626
  });
8508
- var revoke3 = defineCommand6({
9627
+ var revoke3 = defineCommand7({
8509
9628
  meta: { name: "revoke", description: "Revoke a KSeF token" },
8510
9629
  args: {
8511
9630
  ref: { type: "positional", description: "Token reference number", required: true },
@@ -8517,7 +9636,7 @@ var revoke3 = defineCommand6({
8517
9636
  },
8518
9637
  run({ args }) {
8519
9638
  return withErrorHandler(async () => {
8520
- const globalOpts = getGlobalOpts5(args);
9639
+ const globalOpts = getGlobalOpts6(args);
8521
9640
  const { client } = requireSession(globalOpts);
8522
9641
  const ref = args.ref;
8523
9642
  await client.tokens.revokeToken(ref);
@@ -8529,24 +9648,24 @@ var revoke3 = defineCommand6({
8529
9648
  });
8530
9649
  }
8531
9650
  });
8532
- var tokenCommand = defineCommand6({
9651
+ var tokenCommand = defineCommand7({
8533
9652
  meta: { name: "token", description: "Token management commands" },
8534
9653
  subCommands: { generate, list: list2, get: get2, revoke: revoke3 }
8535
9654
  });
8536
9655
 
8537
9656
  // src/cli/commands/cert.ts
8538
- import { defineCommand as defineCommand7 } from "citty";
8539
- import { consola as consola8 } from "consola";
8540
- import fs5 from "fs";
8541
- import path4 from "path";
9657
+ import { defineCommand as defineCommand8 } from "citty";
9658
+ import { consola as consola9 } from "consola";
9659
+ import fs8 from "fs";
9660
+ import path6 from "path";
8542
9661
 
8543
9662
  // src/crypto/certificate-service.ts
8544
- import * as crypto4 from "crypto";
9663
+ import * as crypto5 from "crypto";
8545
9664
  import * as x5092 from "@peculiar/x509";
8546
9665
  var CertificateService = class {
8547
9666
  static getSha256Fingerprint(certPem) {
8548
9667
  const der = extractDerFromPem2(certPem);
8549
- return crypto4.createHash("sha256").update(der).digest("hex").toUpperCase();
9668
+ return crypto5.createHash("sha256").update(der).digest("hex").toUpperCase();
8550
9669
  }
8551
9670
  static async generatePersonalCertificate(givenName, surname, serialNumber, commonName, method = "RSA") {
8552
9671
  const nameParts = [];
@@ -8569,7 +9688,7 @@ var CertificateService = class {
8569
9688
  }
8570
9689
  };
8571
9690
  async function generateSelfSigned(subject2, method) {
8572
- x5092.cryptoProvider.set(crypto4.webcrypto);
9691
+ x5092.cryptoProvider.set(crypto5.webcrypto);
8573
9692
  let algorithm;
8574
9693
  let signingAlgorithm;
8575
9694
  if (method === "ECDSA") {
@@ -8584,7 +9703,7 @@ async function generateSelfSigned(subject2, method) {
8584
9703
  };
8585
9704
  signingAlgorithm = algorithm;
8586
9705
  }
8587
- const keys = await crypto4.webcrypto.subtle.generateKey(
9706
+ const keys = await crypto5.webcrypto.subtle.generateKey(
8588
9707
  algorithm,
8589
9708
  true,
8590
9709
  ["sign", "verify"]
@@ -8601,9 +9720,9 @@ async function generateSelfSigned(subject2, method) {
8601
9720
  serialNumber: Date.now().toString(16)
8602
9721
  });
8603
9722
  const certPem = cert.toString("pem");
8604
- const pkcs8 = await crypto4.webcrypto.subtle.exportKey("pkcs8", keys.privateKey);
9723
+ const pkcs8 = await crypto5.webcrypto.subtle.exportKey("pkcs8", keys.privateKey);
8605
9724
  const privateKeyPem = pemEncode2(new Uint8Array(pkcs8), "PRIVATE KEY");
8606
- const fingerprint = crypto4.createHash("sha256").update(Buffer.from(cert.rawData)).digest("hex").toUpperCase();
9725
+ const fingerprint = crypto5.createHash("sha256").update(Buffer.from(cert.rawData)).digest("hex").toUpperCase();
8607
9726
  return { certificatePem: certPem, privateKeyPem, fingerprint };
8608
9727
  }
8609
9728
  function extractDerFromPem2(pem) {
@@ -8622,7 +9741,7 @@ ${lines.join("\n")}
8622
9741
  }
8623
9742
 
8624
9743
  // src/cli/commands/cert.ts
8625
- function getGlobalOpts6(args) {
9744
+ function getGlobalOpts7(args) {
8626
9745
  return {
8627
9746
  env: args.env,
8628
9747
  json: args.json,
@@ -8631,7 +9750,7 @@ function getGlobalOpts6(args) {
8631
9750
  nip: args.nip
8632
9751
  };
8633
9752
  }
8634
- var generate2 = defineCommand7({
9753
+ var generate2 = defineCommand8({
8635
9754
  meta: { name: "generate", description: "Generate a self-signed certificate locally" },
8636
9755
  args: {
8637
9756
  type: { type: "string", description: "Certificate type: personal or company-seal", required: true },
@@ -8656,21 +9775,21 @@ var generate2 = defineCommand7({
8656
9775
  const certType = args.type;
8657
9776
  const cn = args.cn;
8658
9777
  const method = args.method || "RSA";
8659
- const outDir = path4.resolve(args.out || ".");
9778
+ const outDir = path6.resolve(args.out || ".");
8660
9779
  if (certType !== "personal" && certType !== "company-seal") {
8661
9780
  throw new Error('--type must be "personal" or "company-seal".');
8662
9781
  }
8663
9782
  if (method !== "RSA" && method !== "ECDSA") {
8664
9783
  throw new Error('--method must be "RSA" or "ECDSA".');
8665
9784
  }
8666
- fs5.mkdirSync(outDir, { recursive: true });
8667
- const certPath = path4.join(outDir, "cert.pem");
8668
- const keyPath = path4.join(outDir, "key.pem");
9785
+ fs8.mkdirSync(outDir, { recursive: true });
9786
+ const certPath = path6.join(outDir, "cert.pem");
9787
+ const keyPath = path6.join(outDir, "key.pem");
8669
9788
  if (!args.force) {
8670
- if (fs5.existsSync(certPath)) {
9789
+ if (fs8.existsSync(certPath)) {
8671
9790
  throw new Error(`File already exists: ${certPath}. Use --force to overwrite.`);
8672
9791
  }
8673
- if (fs5.existsSync(keyPath)) {
9792
+ if (fs8.existsSync(keyPath)) {
8674
9793
  throw new Error(`File already exists: ${keyPath}. Use --force to overwrite.`);
8675
9794
  }
8676
9795
  }
@@ -8697,8 +9816,8 @@ var generate2 = defineCommand7({
8697
9816
  method
8698
9817
  );
8699
9818
  }
8700
- fs5.writeFileSync(certPath, result.certificatePem, "utf-8");
8701
- fs5.writeFileSync(keyPath, result.privateKeyPem, "utf-8");
9819
+ fs8.writeFileSync(certPath, result.certificatePem, "utf-8");
9820
+ fs8.writeFileSync(keyPath, result.privateKeyPem, "utf-8");
8702
9821
  if (args.json) {
8703
9822
  outputResult({ certPath, keyPath, fingerprint: result.fingerprint }, { json: true });
8704
9823
  } else {
@@ -8712,7 +9831,7 @@ var generate2 = defineCommand7({
8712
9831
  });
8713
9832
  }
8714
9833
  });
8715
- var enroll = defineCommand7({
9834
+ var enroll = defineCommand8({
8716
9835
  meta: { name: "enroll", description: "Submit certificate enrollment" },
8717
9836
  args: {
8718
9837
  cert: { type: "string", description: "Path to certificate PEM file", required: true },
@@ -8727,9 +9846,9 @@ var enroll = defineCommand7({
8727
9846
  },
8728
9847
  run({ args }) {
8729
9848
  return withErrorHandler(async () => {
8730
- const globalOpts = getGlobalOpts6(args);
9849
+ const globalOpts = getGlobalOpts7(args);
8731
9850
  const { client } = requireSession(globalOpts);
8732
- const certPem = fs5.readFileSync(args.cert, "utf-8");
9851
+ const certPem = fs8.readFileSync(args.cert, "utf-8");
8733
9852
  await client.crypto.init();
8734
9853
  const request = {
8735
9854
  certificateName: args.name,
@@ -8750,7 +9869,7 @@ var enroll = defineCommand7({
8750
9869
  });
8751
9870
  }
8752
9871
  });
8753
- var status4 = defineCommand7({
9872
+ var status4 = defineCommand8({
8754
9873
  meta: { name: "status", description: "Check certificate enrollment status" },
8755
9874
  args: {
8756
9875
  ref: { type: "positional", description: "Enrollment reference number", required: true },
@@ -8762,7 +9881,7 @@ var status4 = defineCommand7({
8762
9881
  },
8763
9882
  run({ args }) {
8764
9883
  return withErrorHandler(async () => {
8765
- const globalOpts = getGlobalOpts6(args);
9884
+ const globalOpts = getGlobalOpts7(args);
8766
9885
  const { client } = requireSession(globalOpts);
8767
9886
  const ref = args.ref;
8768
9887
  const result = await client.certificates.getEnrollmentStatus(ref);
@@ -8782,7 +9901,7 @@ var status4 = defineCommand7({
8782
9901
  });
8783
9902
  }
8784
9903
  });
8785
- var list3 = defineCommand7({
9904
+ var list3 = defineCommand8({
8786
9905
  meta: { name: "list", description: "Query certificates" },
8787
9906
  args: {
8788
9907
  serial: { type: "string", description: "Filter by serial number" },
@@ -8800,7 +9919,7 @@ var list3 = defineCommand7({
8800
9919
  },
8801
9920
  run({ args }) {
8802
9921
  return withErrorHandler(async () => {
8803
- const globalOpts = getGlobalOpts6(args);
9922
+ const globalOpts = getGlobalOpts7(args);
8804
9923
  const { client } = requireSession(globalOpts);
8805
9924
  const request = {
8806
9925
  certificateSerialNumber: args.serial,
@@ -8840,12 +9959,12 @@ var list3 = defineCommand7({
8840
9959
  { json: false }
8841
9960
  );
8842
9961
  if (result.hasMore) {
8843
- consola8.info("More results available. Use --page to paginate.");
9962
+ consola9.info("More results available. Use --page to paginate.");
8844
9963
  }
8845
9964
  });
8846
9965
  }
8847
9966
  });
8848
- var revoke4 = defineCommand7({
9967
+ var revoke4 = defineCommand8({
8849
9968
  meta: { name: "revoke", description: "Revoke a certificate" },
8850
9969
  args: {
8851
9970
  serial: { type: "positional", description: "Certificate serial number", required: true },
@@ -8858,7 +9977,7 @@ var revoke4 = defineCommand7({
8858
9977
  },
8859
9978
  run({ args }) {
8860
9979
  return withErrorHandler(async () => {
8861
- const globalOpts = getGlobalOpts6(args);
9980
+ const globalOpts = getGlobalOpts7(args);
8862
9981
  const { client } = requireSession(globalOpts);
8863
9982
  const serial = args.serial;
8864
9983
  await client.certificates.revoke(serial, {
@@ -8872,7 +9991,7 @@ var revoke4 = defineCommand7({
8872
9991
  });
8873
9992
  }
8874
9993
  });
8875
- var limits = defineCommand7({
9994
+ var limits = defineCommand8({
8876
9995
  meta: { name: "limits", description: "View certificate limits" },
8877
9996
  args: {
8878
9997
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -8883,7 +10002,7 @@ var limits = defineCommand7({
8883
10002
  },
8884
10003
  run({ args }) {
8885
10004
  return withErrorHandler(async () => {
8886
- const globalOpts = getGlobalOpts6(args);
10005
+ const globalOpts = getGlobalOpts7(args);
8887
10006
  const { client } = requireSession(globalOpts);
8888
10007
  const result = await client.certificates.getLimits();
8889
10008
  if (args.json) {
@@ -8900,7 +10019,7 @@ var limits = defineCommand7({
8900
10019
  });
8901
10020
  }
8902
10021
  });
8903
- var enrollmentData = defineCommand7({
10022
+ var enrollmentData = defineCommand8({
8904
10023
  meta: { name: "enrollment-data", description: "Get enrollment data template from KSeF" },
8905
10024
  args: {
8906
10025
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -8911,7 +10030,7 @@ var enrollmentData = defineCommand7({
8911
10030
  },
8912
10031
  run({ args }) {
8913
10032
  return withErrorHandler(async () => {
8914
- const globalOpts = getGlobalOpts6(args);
10033
+ const globalOpts = getGlobalOpts7(args);
8915
10034
  const { client } = requireSession(globalOpts);
8916
10035
  const result = await client.certificates.getEnrollmentData();
8917
10036
  if (args.json) {
@@ -8931,7 +10050,7 @@ var enrollmentData = defineCommand7({
8931
10050
  });
8932
10051
  }
8933
10052
  });
8934
- var retrieve = defineCommand7({
10053
+ var retrieve = defineCommand8({
8935
10054
  meta: { name: "retrieve", description: "Retrieve certificates by serial numbers" },
8936
10055
  args: {
8937
10056
  serial: { type: "string", description: "Comma-separated certificate serial numbers", required: true },
@@ -8943,7 +10062,7 @@ var retrieve = defineCommand7({
8943
10062
  },
8944
10063
  run({ args }) {
8945
10064
  return withErrorHandler(async () => {
8946
- const globalOpts = getGlobalOpts6(args);
10065
+ const globalOpts = getGlobalOpts7(args);
8947
10066
  const { client } = requireSession(globalOpts);
8948
10067
  const serials = args.serial.split(",").map((s) => s.trim()).filter(Boolean);
8949
10068
  if (serials.length === 0) {
@@ -8974,14 +10093,14 @@ var retrieve = defineCommand7({
8974
10093
  });
8975
10094
  }
8976
10095
  });
8977
- var certCommand = defineCommand7({
10096
+ var certCommand = defineCommand8({
8978
10097
  meta: { name: "cert", description: "Certificate management commands" },
8979
10098
  subCommands: { generate: generate2, enroll, status: status4, list: list3, revoke: revoke4, limits, "enrollment-data": enrollmentData, retrieve }
8980
10099
  });
8981
10100
 
8982
10101
  // src/cli/commands/qr.ts
8983
- import * as fs6 from "fs";
8984
- import { defineCommand as defineCommand8 } from "citty";
10102
+ import * as fs9 from "fs";
10103
+ import { defineCommand as defineCommand9 } from "citty";
8985
10104
 
8986
10105
  // src/qr/qrcode-service.ts
8987
10106
  import * as QRCode from "qrcode";
@@ -9043,7 +10162,7 @@ function escapeXml2(str) {
9043
10162
  }
9044
10163
 
9045
10164
  // src/cli/commands/qr.ts
9046
- function getGlobalOpts7(args) {
10165
+ function getGlobalOpts8(args) {
9047
10166
  return {
9048
10167
  env: args.env,
9049
10168
  json: args.json,
@@ -9052,7 +10171,7 @@ function getGlobalOpts7(args) {
9052
10171
  nip: args.nip
9053
10172
  };
9054
10173
  }
9055
- var invoice2 = defineCommand8({
10174
+ var invoice2 = defineCommand9({
9056
10175
  meta: { name: "invoice", description: "Generate invoice QR code" },
9057
10176
  args: {
9058
10177
  nip: { type: "string", description: "NIP number", required: true },
@@ -9069,7 +10188,7 @@ var invoice2 = defineCommand8({
9069
10188
  },
9070
10189
  run({ args }) {
9071
10190
  return withErrorHandler(async () => {
9072
- const globalOpts = getGlobalOpts7(args);
10191
+ const globalOpts = getGlobalOpts8(args);
9073
10192
  const client = createClient(globalOpts);
9074
10193
  const size = args.size ? parseInt(args.size, 10) : 300;
9075
10194
  const format = args.format ?? "png";
@@ -9082,7 +10201,7 @@ var invoice2 = defineCommand8({
9082
10201
  if (format === "svg") {
9083
10202
  const svg = args.label ? await QrCodeService.generateQrCodeSvgWithLabel(url2, args.label, { width: size }) : await QrCodeService.generateQrCodeSvg(url2, { width: size });
9084
10203
  if (args.o) {
9085
- fs6.writeFileSync(args.o, svg);
10204
+ fs9.writeFileSync(args.o, svg);
9086
10205
  outputSuccess(`QR code saved to ${args.o}
9087
10206
  URL: ${url2}`);
9088
10207
  } else {
@@ -9091,7 +10210,7 @@ URL: ${url2}`);
9091
10210
  } else {
9092
10211
  const buffer = await QrCodeService.generateQrCode(url2, { width: size });
9093
10212
  if (args.o) {
9094
- fs6.writeFileSync(args.o, buffer);
10213
+ fs9.writeFileSync(args.o, buffer);
9095
10214
  outputSuccess(`QR code saved to ${args.o}
9096
10215
  URL: ${url2}`);
9097
10216
  } else {
@@ -9101,7 +10220,7 @@ URL: ${url2}`);
9101
10220
  });
9102
10221
  }
9103
10222
  });
9104
- var certificate = defineCommand8({
10223
+ var certificate = defineCommand9({
9105
10224
  meta: { name: "certificate", description: "Generate certificate QR code" },
9106
10225
  args: {
9107
10226
  "context-type": { type: "string", description: "Context identifier type", required: true },
@@ -9122,11 +10241,11 @@ var certificate = defineCommand8({
9122
10241
  },
9123
10242
  run({ args }) {
9124
10243
  return withErrorHandler(async () => {
9125
- const globalOpts = getGlobalOpts7(args);
10244
+ const globalOpts = getGlobalOpts8(args);
9126
10245
  const client = createClient(globalOpts);
9127
10246
  const size = args.size ? parseInt(args.size, 10) : 300;
9128
10247
  const format = args.format ?? "png";
9129
- const privateKeyPem = fs6.readFileSync(args.key, "utf-8");
10248
+ const privateKeyPem = fs9.readFileSync(args.key, "utf-8");
9130
10249
  const url2 = client.qr.buildCertificateVerificationUrl(
9131
10250
  args["context-type"],
9132
10251
  args["context-id"],
@@ -9143,7 +10262,7 @@ var certificate = defineCommand8({
9143
10262
  if (format === "svg") {
9144
10263
  const svg = args.label ? await QrCodeService.generateQrCodeSvgWithLabel(url2, args.label, { width: size }) : await QrCodeService.generateQrCodeSvg(url2, { width: size });
9145
10264
  if (args.o) {
9146
- fs6.writeFileSync(args.o, svg);
10265
+ fs9.writeFileSync(args.o, svg);
9147
10266
  outputSuccess(`QR code saved to ${args.o}
9148
10267
  URL: ${url2}`);
9149
10268
  } else {
@@ -9152,7 +10271,7 @@ URL: ${url2}`);
9152
10271
  } else {
9153
10272
  const buffer = await QrCodeService.generateQrCode(url2, { width: size });
9154
10273
  if (args.o) {
9155
- fs6.writeFileSync(args.o, buffer);
10274
+ fs9.writeFileSync(args.o, buffer);
9156
10275
  outputSuccess(`QR code saved to ${args.o}
9157
10276
  URL: ${url2}`);
9158
10277
  } else {
@@ -9162,7 +10281,7 @@ URL: ${url2}`);
9162
10281
  });
9163
10282
  }
9164
10283
  });
9165
- var url = defineCommand8({
10284
+ var url = defineCommand9({
9166
10285
  meta: { name: "url", description: "Print invoice verification URL (no QR image)" },
9167
10286
  args: {
9168
10287
  nip: { type: "string", description: "NIP number", required: true },
@@ -9175,7 +10294,7 @@ var url = defineCommand8({
9175
10294
  },
9176
10295
  run({ args }) {
9177
10296
  return withErrorHandler(async () => {
9178
- const globalOpts = getGlobalOpts7(args);
10297
+ const globalOpts = getGlobalOpts8(args);
9179
10298
  const client = createClient(globalOpts);
9180
10299
  const verificationUrl = client.qr.buildInvoiceVerificationUrl(args.nip, args.date, args.hash);
9181
10300
  if (args.json) {
@@ -9186,14 +10305,14 @@ var url = defineCommand8({
9186
10305
  });
9187
10306
  }
9188
10307
  });
9189
- var qrCommand = defineCommand8({
10308
+ var qrCommand = defineCommand9({
9190
10309
  meta: { name: "qr", description: "QR code generation commands" },
9191
10310
  subCommands: { invoice: invoice2, certificate, url }
9192
10311
  });
9193
10312
 
9194
10313
  // src/cli/commands/lighthouse.ts
9195
- import { defineCommand as defineCommand9 } from "citty";
9196
- function getGlobalOpts8(args) {
10314
+ import { defineCommand as defineCommand10 } from "citty";
10315
+ function getGlobalOpts9(args) {
9197
10316
  return {
9198
10317
  env: args.env ?? "prod",
9199
10318
  json: args.json,
@@ -9202,7 +10321,7 @@ function getGlobalOpts8(args) {
9202
10321
  nip: args.nip
9203
10322
  };
9204
10323
  }
9205
- var status5 = defineCommand9({
10324
+ var status5 = defineCommand10({
9206
10325
  meta: { name: "status", description: "Check KSeF system status" },
9207
10326
  args: {
9208
10327
  env: { type: "string", description: "Environment (test/prod, default: prod)" },
@@ -9213,7 +10332,7 @@ var status5 = defineCommand9({
9213
10332
  },
9214
10333
  run({ args }) {
9215
10334
  return withErrorHandler(async () => {
9216
- const globalOpts = getGlobalOpts8(args);
10335
+ const globalOpts = getGlobalOpts9(args);
9217
10336
  const client = createClient(globalOpts);
9218
10337
  const result = await client.lighthouse.getStatus();
9219
10338
  if (args.json) {
@@ -9230,7 +10349,7 @@ var status5 = defineCommand9({
9230
10349
  });
9231
10350
  }
9232
10351
  });
9233
- var messages = defineCommand9({
10352
+ var messages = defineCommand10({
9234
10353
  meta: { name: "messages", description: "View KSeF system messages" },
9235
10354
  args: {
9236
10355
  env: { type: "string", description: "Environment (test/prod, default: prod)" },
@@ -9241,7 +10360,7 @@ var messages = defineCommand9({
9241
10360
  },
9242
10361
  run({ args }) {
9243
10362
  return withErrorHandler(async () => {
9244
- const globalOpts = getGlobalOpts8(args);
10363
+ const globalOpts = getGlobalOpts9(args);
9245
10364
  const client = createClient(globalOpts);
9246
10365
  const msgs = await client.lighthouse.getMessages();
9247
10366
  if (args.json) {
@@ -9272,14 +10391,14 @@ var messages = defineCommand9({
9272
10391
  });
9273
10392
  }
9274
10393
  });
9275
- var lighthouseCommand = defineCommand9({
10394
+ var lighthouseCommand = defineCommand10({
9276
10395
  meta: { name: "lighthouse", description: "KSeF system status commands" },
9277
10396
  subCommands: { status: status5, messages }
9278
10397
  });
9279
10398
 
9280
10399
  // src/cli/commands/test-data.ts
9281
- import { defineCommand as defineCommand10 } from "citty";
9282
- function getGlobalOpts9(args) {
10400
+ import { defineCommand as defineCommand11 } from "citty";
10401
+ function getGlobalOpts10(args) {
9283
10402
  return {
9284
10403
  env: args.env,
9285
10404
  json: args.json,
@@ -9301,7 +10420,7 @@ function outputDone(json) {
9301
10420
  outputSuccess("Done.");
9302
10421
  }
9303
10422
  }
9304
- var createSubject = defineCommand10({
10423
+ var createSubject = defineCommand11({
9305
10424
  meta: { name: "create-subject", description: "Create a test subject" },
9306
10425
  args: {
9307
10426
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9315,7 +10434,7 @@ var createSubject = defineCommand10({
9315
10434
  },
9316
10435
  run({ args }) {
9317
10436
  return withErrorHandler(async () => {
9318
- const globalOpts = getGlobalOpts9(args);
10437
+ const globalOpts = getGlobalOpts10(args);
9319
10438
  requireNonProd(globalOpts);
9320
10439
  const request = {
9321
10440
  subjectNip: args.nip,
@@ -9328,7 +10447,7 @@ var createSubject = defineCommand10({
9328
10447
  });
9329
10448
  }
9330
10449
  });
9331
- var removeSubject = defineCommand10({
10450
+ var removeSubject = defineCommand11({
9332
10451
  meta: { name: "remove-subject", description: "Remove a test subject" },
9333
10452
  args: {
9334
10453
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9339,7 +10458,7 @@ var removeSubject = defineCommand10({
9339
10458
  },
9340
10459
  run({ args }) {
9341
10460
  return withErrorHandler(async () => {
9342
- const globalOpts = getGlobalOpts9(args);
10461
+ const globalOpts = getGlobalOpts10(args);
9343
10462
  requireNonProd(globalOpts);
9344
10463
  const request = { subjectNip: args.nip };
9345
10464
  await createClient(globalOpts).testData.removeSubject(request);
@@ -9347,7 +10466,7 @@ var removeSubject = defineCommand10({
9347
10466
  });
9348
10467
  }
9349
10468
  });
9350
- var createPerson = defineCommand10({
10469
+ var createPerson = defineCommand11({
9351
10470
  meta: { name: "create-person", description: "Create a test person" },
9352
10471
  args: {
9353
10472
  nip: { type: "string", description: "Person NIP", required: true },
@@ -9363,7 +10482,7 @@ var createPerson = defineCommand10({
9363
10482
  },
9364
10483
  run({ args }) {
9365
10484
  return withErrorHandler(async () => {
9366
- const globalOpts = getGlobalOpts9(args);
10485
+ const globalOpts = getGlobalOpts10(args);
9367
10486
  requireNonProd(globalOpts);
9368
10487
  const request = {
9369
10488
  nip: args.nip,
@@ -9378,7 +10497,7 @@ var createPerson = defineCommand10({
9378
10497
  });
9379
10498
  }
9380
10499
  });
9381
- var removePerson = defineCommand10({
10500
+ var removePerson = defineCommand11({
9382
10501
  meta: { name: "remove-person", description: "Remove a test person" },
9383
10502
  args: {
9384
10503
  nip: { type: "string", description: "Person NIP", required: true },
@@ -9389,7 +10508,7 @@ var removePerson = defineCommand10({
9389
10508
  },
9390
10509
  run({ args }) {
9391
10510
  return withErrorHandler(async () => {
9392
- const globalOpts = getGlobalOpts9(args);
10511
+ const globalOpts = getGlobalOpts10(args);
9393
10512
  requireNonProd(globalOpts);
9394
10513
  const request = { nip: args.nip };
9395
10514
  await createClient(globalOpts).testData.removePerson(request);
@@ -9397,7 +10516,7 @@ var removePerson = defineCommand10({
9397
10516
  });
9398
10517
  }
9399
10518
  });
9400
- var grantPermissions = defineCommand10({
10519
+ var grantPermissions = defineCommand11({
9401
10520
  meta: { name: "grant-permissions", description: "Grant test data permissions" },
9402
10521
  args: {
9403
10522
  "context-nip": { type: "string", description: "Context NIP", required: true },
@@ -9412,7 +10531,7 @@ var grantPermissions = defineCommand10({
9412
10531
  },
9413
10532
  run({ args }) {
9414
10533
  return withErrorHandler(async () => {
9415
- const globalOpts = getGlobalOpts9(args);
10534
+ const globalOpts = getGlobalOpts10(args);
9416
10535
  requireNonProd(globalOpts);
9417
10536
  const permissions = args.permissions.split(",").map((p) => ({ permissionType: p.trim(), description: "" }));
9418
10537
  const request = {
@@ -9428,7 +10547,7 @@ var grantPermissions = defineCommand10({
9428
10547
  });
9429
10548
  }
9430
10549
  });
9431
- var revokePermissions = defineCommand10({
10550
+ var revokePermissions = defineCommand11({
9432
10551
  meta: { name: "revoke-permissions", description: "Revoke test data permissions" },
9433
10552
  args: {
9434
10553
  "context-nip": { type: "string", description: "Context NIP", required: true },
@@ -9442,7 +10561,7 @@ var revokePermissions = defineCommand10({
9442
10561
  },
9443
10562
  run({ args }) {
9444
10563
  return withErrorHandler(async () => {
9445
- const globalOpts = getGlobalOpts9(args);
10564
+ const globalOpts = getGlobalOpts10(args);
9446
10565
  requireNonProd(globalOpts);
9447
10566
  const request = {
9448
10567
  contextIdentifier: { type: "Nip", value: args["context-nip"] },
@@ -9456,7 +10575,7 @@ var revokePermissions = defineCommand10({
9456
10575
  });
9457
10576
  }
9458
10577
  });
9459
- var enableAttachment = defineCommand10({
10578
+ var enableAttachment = defineCommand11({
9460
10579
  meta: { name: "enable-attachment", description: "Enable attachment permission for a subject" },
9461
10580
  args: {
9462
10581
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9467,7 +10586,7 @@ var enableAttachment = defineCommand10({
9467
10586
  },
9468
10587
  run({ args }) {
9469
10588
  return withErrorHandler(async () => {
9470
- const globalOpts = getGlobalOpts9(args);
10589
+ const globalOpts = getGlobalOpts10(args);
9471
10590
  requireNonProd(globalOpts);
9472
10591
  const request = { nip: args.nip };
9473
10592
  await createClient(globalOpts).testData.enableAttachment(request);
@@ -9475,7 +10594,7 @@ var enableAttachment = defineCommand10({
9475
10594
  });
9476
10595
  }
9477
10596
  });
9478
- var disableAttachment = defineCommand10({
10597
+ var disableAttachment = defineCommand11({
9479
10598
  meta: { name: "disable-attachment", description: "Disable attachment permission for a subject" },
9480
10599
  args: {
9481
10600
  nip: { type: "string", description: "Subject NIP", required: true },
@@ -9487,7 +10606,7 @@ var disableAttachment = defineCommand10({
9487
10606
  },
9488
10607
  run({ args }) {
9489
10608
  return withErrorHandler(async () => {
9490
- const globalOpts = getGlobalOpts9(args);
10609
+ const globalOpts = getGlobalOpts10(args);
9491
10610
  requireNonProd(globalOpts);
9492
10611
  const request = {
9493
10612
  nip: args.nip,
@@ -9498,7 +10617,7 @@ var disableAttachment = defineCommand10({
9498
10617
  });
9499
10618
  }
9500
10619
  });
9501
- var changeSessionLimits = defineCommand10({
10620
+ var changeSessionLimits = defineCommand11({
9502
10621
  meta: { name: "change-session-limits", description: "Change session limits in current context" },
9503
10622
  args: {
9504
10623
  "online-max-size": { type: "string", description: "Online session: max invoice size in MB (0-5)", required: true },
@@ -9515,7 +10634,7 @@ var changeSessionLimits = defineCommand10({
9515
10634
  },
9516
10635
  run({ args }) {
9517
10636
  return withErrorHandler(async () => {
9518
- const globalOpts = getGlobalOpts9(args);
10637
+ const globalOpts = getGlobalOpts10(args);
9519
10638
  requireNonProd(globalOpts);
9520
10639
  const { client } = requireSession(globalOpts);
9521
10640
  const request = {
@@ -9535,7 +10654,7 @@ var changeSessionLimits = defineCommand10({
9535
10654
  });
9536
10655
  }
9537
10656
  });
9538
- var restoreSessionLimits = defineCommand10({
10657
+ var restoreSessionLimits = defineCommand11({
9539
10658
  meta: { name: "restore-session-limits", description: "Restore default session limits" },
9540
10659
  args: {
9541
10660
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9546,7 +10665,7 @@ var restoreSessionLimits = defineCommand10({
9546
10665
  },
9547
10666
  run({ args }) {
9548
10667
  return withErrorHandler(async () => {
9549
- const globalOpts = getGlobalOpts9(args);
10668
+ const globalOpts = getGlobalOpts10(args);
9550
10669
  requireNonProd(globalOpts);
9551
10670
  const { client } = requireSession(globalOpts);
9552
10671
  await client.testData.restoreDefaultSessionLimits();
@@ -9554,7 +10673,7 @@ var restoreSessionLimits = defineCommand10({
9554
10673
  });
9555
10674
  }
9556
10675
  });
9557
- var changeCertLimits = defineCommand10({
10676
+ var changeCertLimits = defineCommand11({
9558
10677
  meta: { name: "change-cert-limits", description: "Change subject limits (enrollment/certificate) in current subject" },
9559
10678
  args: {
9560
10679
  "identifier-type": { type: "string", description: "Subject identifier type (Nip/Pesel/Fingerprint)" },
@@ -9568,7 +10687,7 @@ var changeCertLimits = defineCommand10({
9568
10687
  },
9569
10688
  run({ args }) {
9570
10689
  return withErrorHandler(async () => {
9571
- const globalOpts = getGlobalOpts9(args);
10690
+ const globalOpts = getGlobalOpts10(args);
9572
10691
  requireNonProd(globalOpts);
9573
10692
  const { client } = requireSession(globalOpts);
9574
10693
  const request = {
@@ -9581,7 +10700,7 @@ var changeCertLimits = defineCommand10({
9581
10700
  });
9582
10701
  }
9583
10702
  });
9584
- var restoreCertLimits = defineCommand10({
10703
+ var restoreCertLimits = defineCommand11({
9585
10704
  meta: { name: "restore-cert-limits", description: "Restore default certificates limit" },
9586
10705
  args: {
9587
10706
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9592,7 +10711,7 @@ var restoreCertLimits = defineCommand10({
9592
10711
  },
9593
10712
  run({ args }) {
9594
10713
  return withErrorHandler(async () => {
9595
- const globalOpts = getGlobalOpts9(args);
10714
+ const globalOpts = getGlobalOpts10(args);
9596
10715
  requireNonProd(globalOpts);
9597
10716
  const { client } = requireSession(globalOpts);
9598
10717
  await client.testData.restoreDefaultCertificatesLimit();
@@ -9600,7 +10719,7 @@ var restoreCertLimits = defineCommand10({
9600
10719
  });
9601
10720
  }
9602
10721
  });
9603
- var setRateLimits = defineCommand10({
10722
+ var setRateLimits = defineCommand11({
9604
10723
  meta: { name: "set-rate-limits", description: "Set effective API rate limits" },
9605
10724
  args: {
9606
10725
  limits: { type: "string", description: "Rate limits as JSON string (ApiRateLimitsOverride)", required: true },
@@ -9612,7 +10731,7 @@ var setRateLimits = defineCommand10({
9612
10731
  },
9613
10732
  run({ args }) {
9614
10733
  return withErrorHandler(async () => {
9615
- const globalOpts = getGlobalOpts9(args);
10734
+ const globalOpts = getGlobalOpts10(args);
9616
10735
  requireNonProd(globalOpts);
9617
10736
  const { client } = requireSession(globalOpts);
9618
10737
  const request = {
@@ -9623,7 +10742,7 @@ var setRateLimits = defineCommand10({
9623
10742
  });
9624
10743
  }
9625
10744
  });
9626
- var restoreRateLimits = defineCommand10({
10745
+ var restoreRateLimits = defineCommand11({
9627
10746
  meta: { name: "restore-rate-limits", description: "Restore default API rate limits" },
9628
10747
  args: {
9629
10748
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9634,7 +10753,7 @@ var restoreRateLimits = defineCommand10({
9634
10753
  },
9635
10754
  run({ args }) {
9636
10755
  return withErrorHandler(async () => {
9637
- const globalOpts = getGlobalOpts9(args);
10756
+ const globalOpts = getGlobalOpts10(args);
9638
10757
  requireNonProd(globalOpts);
9639
10758
  const { client } = requireSession(globalOpts);
9640
10759
  await client.testData.restoreDefaultRateLimits();
@@ -9642,7 +10761,7 @@ var restoreRateLimits = defineCommand10({
9642
10761
  });
9643
10762
  }
9644
10763
  });
9645
- var setProductionRateLimits = defineCommand10({
10764
+ var setProductionRateLimits = defineCommand11({
9646
10765
  meta: { name: "set-production-rate-limits", description: "Set production API rate limits" },
9647
10766
  args: {
9648
10767
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9653,7 +10772,7 @@ var setProductionRateLimits = defineCommand10({
9653
10772
  },
9654
10773
  run({ args }) {
9655
10774
  return withErrorHandler(async () => {
9656
- const globalOpts = getGlobalOpts9(args);
10775
+ const globalOpts = getGlobalOpts10(args);
9657
10776
  requireNonProd(globalOpts);
9658
10777
  const { client } = requireSession(globalOpts);
9659
10778
  await client.testData.setProductionRateLimits();
@@ -9661,7 +10780,7 @@ var setProductionRateLimits = defineCommand10({
9661
10780
  });
9662
10781
  }
9663
10782
  });
9664
- var blockContext = defineCommand10({
10783
+ var blockContext = defineCommand11({
9665
10784
  meta: { name: "block-context", description: "Block a context" },
9666
10785
  args: {
9667
10786
  "context-value": { type: "string", description: "Context identifier value", required: true },
@@ -9674,7 +10793,7 @@ var blockContext = defineCommand10({
9674
10793
  },
9675
10794
  run({ args }) {
9676
10795
  return withErrorHandler(async () => {
9677
- const globalOpts = getGlobalOpts9(args);
10796
+ const globalOpts = getGlobalOpts10(args);
9678
10797
  requireNonProd(globalOpts);
9679
10798
  const { client } = requireSession(globalOpts);
9680
10799
  const request = {
@@ -9688,7 +10807,7 @@ var blockContext = defineCommand10({
9688
10807
  });
9689
10808
  }
9690
10809
  });
9691
- var unblockContext = defineCommand10({
10810
+ var unblockContext = defineCommand11({
9692
10811
  meta: { name: "unblock-context", description: "Unblock a context" },
9693
10812
  args: {
9694
10813
  "context-value": { type: "string", description: "Context identifier value", required: true },
@@ -9701,7 +10820,7 @@ var unblockContext = defineCommand10({
9701
10820
  },
9702
10821
  run({ args }) {
9703
10822
  return withErrorHandler(async () => {
9704
- const globalOpts = getGlobalOpts9(args);
10823
+ const globalOpts = getGlobalOpts10(args);
9705
10824
  requireNonProd(globalOpts);
9706
10825
  const { client } = requireSession(globalOpts);
9707
10826
  const request = {
@@ -9715,7 +10834,7 @@ var unblockContext = defineCommand10({
9715
10834
  });
9716
10835
  }
9717
10836
  });
9718
- var testDataCommand = defineCommand10({
10837
+ var testDataCommand = defineCommand11({
9719
10838
  meta: { name: "test-data", description: "Test environment data management (test/demo only)" },
9720
10839
  subCommands: {
9721
10840
  "create-subject": createSubject,
@@ -9739,8 +10858,8 @@ var testDataCommand = defineCommand10({
9739
10858
  });
9740
10859
 
9741
10860
  // src/cli/commands/limits.ts
9742
- import { defineCommand as defineCommand11 } from "citty";
9743
- function getGlobalOpts10(args) {
10861
+ import { defineCommand as defineCommand12 } from "citty";
10862
+ function getGlobalOpts11(args) {
9744
10863
  return {
9745
10864
  env: args.env,
9746
10865
  json: args.json,
@@ -9749,7 +10868,7 @@ function getGlobalOpts10(args) {
9749
10868
  nip: args.nip
9750
10869
  };
9751
10870
  }
9752
- var context = defineCommand11({
10871
+ var context = defineCommand12({
9753
10872
  meta: { name: "context", description: "View effective context limits" },
9754
10873
  args: {
9755
10874
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9759,7 +10878,7 @@ var context = defineCommand11({
9759
10878
  },
9760
10879
  run({ args }) {
9761
10880
  return withErrorHandler(async () => {
9762
- const globalOpts = getGlobalOpts10(args);
10881
+ const globalOpts = getGlobalOpts11(args);
9763
10882
  const { client } = requireSession(globalOpts);
9764
10883
  const result = await client.limits.getContextLimits();
9765
10884
  if (args.json) {
@@ -9777,7 +10896,7 @@ var context = defineCommand11({
9777
10896
  });
9778
10897
  }
9779
10898
  });
9780
- var subject = defineCommand11({
10899
+ var subject = defineCommand12({
9781
10900
  meta: { name: "subject", description: "View effective subject limits" },
9782
10901
  args: {
9783
10902
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9787,7 +10906,7 @@ var subject = defineCommand11({
9787
10906
  },
9788
10907
  run({ args }) {
9789
10908
  return withErrorHandler(async () => {
9790
- const globalOpts = getGlobalOpts10(args);
10909
+ const globalOpts = getGlobalOpts11(args);
9791
10910
  const { client } = requireSession(globalOpts);
9792
10911
  const result = await client.limits.getSubjectLimits();
9793
10912
  if (args.json) {
@@ -9801,7 +10920,7 @@ var subject = defineCommand11({
9801
10920
  });
9802
10921
  }
9803
10922
  });
9804
- var rate = defineCommand11({
10923
+ var rate = defineCommand12({
9805
10924
  meta: { name: "rate", description: "View effective API rate limits" },
9806
10925
  args: {
9807
10926
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9811,7 +10930,7 @@ var rate = defineCommand11({
9811
10930
  },
9812
10931
  run({ args }) {
9813
10932
  return withErrorHandler(async () => {
9814
- const globalOpts = getGlobalOpts10(args);
10933
+ const globalOpts = getGlobalOpts11(args);
9815
10934
  const { client } = requireSession(globalOpts);
9816
10935
  const result = await client.limits.getRateLimits();
9817
10936
  if (args.json) {
@@ -9837,15 +10956,15 @@ var rate = defineCommand11({
9837
10956
  });
9838
10957
  }
9839
10958
  });
9840
- var limitsCommand = defineCommand11({
10959
+ var limitsCommand = defineCommand12({
9841
10960
  meta: { name: "limits", description: "View KSeF API limits" },
9842
10961
  subCommands: { context, subject, rate }
9843
10962
  });
9844
10963
 
9845
10964
  // src/cli/commands/peppol.ts
9846
- import { defineCommand as defineCommand12 } from "citty";
9847
- import { consola as consola9 } from "consola";
9848
- function getGlobalOpts11(args) {
10965
+ import { defineCommand as defineCommand13 } from "citty";
10966
+ import { consola as consola10 } from "consola";
10967
+ function getGlobalOpts12(args) {
9849
10968
  return {
9850
10969
  env: args.env,
9851
10970
  json: args.json,
@@ -9854,7 +10973,7 @@ function getGlobalOpts11(args) {
9854
10973
  nip: args.nip
9855
10974
  };
9856
10975
  }
9857
- var providers = defineCommand12({
10976
+ var providers = defineCommand13({
9858
10977
  meta: { name: "providers", description: "Query Peppol providers" },
9859
10978
  args: {
9860
10979
  page: { type: "string", description: "Page offset" },
@@ -9866,7 +10985,7 @@ var providers = defineCommand12({
9866
10985
  },
9867
10986
  run({ args }) {
9868
10987
  return withErrorHandler(async () => {
9869
- const globalOpts = getGlobalOpts11(args);
10988
+ const globalOpts = getGlobalOpts12(args);
9870
10989
  const { client } = requireSession(globalOpts);
9871
10990
  const pageOffset = args.page ? parseInt(args.page, 10) : void 0;
9872
10991
  const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
@@ -9893,20 +11012,20 @@ var providers = defineCommand12({
9893
11012
  { json: false }
9894
11013
  );
9895
11014
  if (result.hasMore) {
9896
- consola9.info("More results available. Use --page to paginate.");
11015
+ consola10.info("More results available. Use --page to paginate.");
9897
11016
  }
9898
11017
  });
9899
11018
  }
9900
11019
  });
9901
- var peppolCommand = defineCommand12({
11020
+ var peppolCommand = defineCommand13({
9902
11021
  meta: { name: "peppol", description: "Peppol integration commands" },
9903
11022
  subCommands: { providers }
9904
11023
  });
9905
11024
 
9906
11025
  // src/cli/commands/doctor.ts
9907
- import { defineCommand as defineCommand13 } from "citty";
9908
- import { consola as consola10 } from "consola";
9909
- function getGlobalOpts12(args) {
11026
+ import { defineCommand as defineCommand14 } from "citty";
11027
+ import { consola as consola11 } from "consola";
11028
+ function getGlobalOpts13(args) {
9910
11029
  return {
9911
11030
  env: args.env,
9912
11031
  json: args.json,
@@ -9915,7 +11034,7 @@ function getGlobalOpts12(args) {
9915
11034
  verbose: args.verbose
9916
11035
  };
9917
11036
  }
9918
- var doctorCommand = defineCommand13({
11037
+ var doctorCommand = defineCommand14({
9919
11038
  meta: { name: "doctor", description: "Check CLI configuration and connectivity" },
9920
11039
  args: {
9921
11040
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -9926,7 +11045,7 @@ var doctorCommand = defineCommand13({
9926
11045
  },
9927
11046
  run({ args }) {
9928
11047
  return withErrorHandler(async () => {
9929
- const globalOpts = getGlobalOpts12(args);
11048
+ const globalOpts = getGlobalOpts13(args);
9930
11049
  const checks = [];
9931
11050
  try {
9932
11051
  const config = loadConfig();
@@ -9996,14 +11115,14 @@ var doctorCommand = defineCommand13({
9996
11115
  }
9997
11116
  for (const check of checks) {
9998
11117
  const icon = check.status === "pass" ? "\u2713" : check.status === "warn" ? "\u26A0" : "\u2717";
9999
- const log = check.status === "pass" ? consola10.success : check.status === "warn" ? consola10.warn : consola10.error;
11118
+ const log = check.status === "pass" ? consola11.success : check.status === "warn" ? consola11.warn : consola11.error;
10000
11119
  log(`${icon} ${check.message}`);
10001
11120
  }
10002
11121
  if (passed === total) {
10003
- consola10.success(`
11122
+ consola11.success(`
10004
11123
  ${passed}/${total} checks passed.`);
10005
11124
  } else {
10006
- consola10.warn(`
11125
+ consola11.warn(`
10007
11126
  ${passed}/${total} checks passed.`);
10008
11127
  }
10009
11128
  });
@@ -10011,7 +11130,7 @@ ${passed}/${total} checks passed.`);
10011
11130
  });
10012
11131
 
10013
11132
  // src/cli/commands/completion.ts
10014
- import { defineCommand as defineCommand14 } from "citty";
11133
+ import { defineCommand as defineCommand15 } from "citty";
10015
11134
  var COMMAND_TREE = {
10016
11135
  config: ["set", "show", "reset"],
10017
11136
  auth: ["challenge", "login", "status", "logout", "refresh", "whoami"],
@@ -10103,34 +11222,37 @@ function generateFish() {
10103
11222
  }
10104
11223
  return lines.join("\n") + "\n";
10105
11224
  }
10106
- var bash = defineCommand14({
11225
+ var bash = defineCommand15({
10107
11226
  meta: { name: "bash", description: "Generate bash completion script" },
10108
11227
  run() {
10109
11228
  console.log(generateBash());
10110
11229
  }
10111
11230
  });
10112
- var zsh = defineCommand14({
11231
+ var zsh = defineCommand15({
10113
11232
  meta: { name: "zsh", description: "Generate zsh completion script" },
10114
11233
  run() {
10115
11234
  console.log(generateZsh());
10116
11235
  }
10117
11236
  });
10118
- var fish = defineCommand14({
11237
+ var fish = defineCommand15({
10119
11238
  meta: { name: "fish", description: "Generate fish completion script" },
10120
11239
  run() {
10121
11240
  console.log(generateFish());
10122
11241
  }
10123
11242
  });
10124
- var completionCommand = defineCommand14({
11243
+ var completionCommand = defineCommand15({
10125
11244
  meta: { name: "completion", description: "Generate shell completion scripts" },
10126
11245
  subCommands: { bash, zsh, fish }
10127
11246
  });
10128
11247
 
10129
11248
  // src/cli/index.ts
10130
- var main = defineCommand15({
11249
+ var __dirname = dirname2(fileURLToPath(import.meta.url));
11250
+ var pkg = JSON.parse(readFileSync6(resolve(__dirname, "..", "package.json"), "utf-8"));
11251
+ var version = pkg.version;
11252
+ var main = defineCommand16({
10131
11253
  meta: {
10132
11254
  name: "ksef",
10133
- version: "0.1.0",
11255
+ version,
10134
11256
  description: "CLI for the Polish National e-Invoice System (KSeF)"
10135
11257
  },
10136
11258
  subCommands: {