ksef-client-ts 0.6.2 → 0.7.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
@@ -43,6 +43,9 @@ var init_ksef_api_error = __esm({
43
43
  const message = details?.length ? details.map((d) => d.exceptionDescription ?? "").filter(Boolean).join("; ") || `KSeF API error: HTTP ${statusCode}` : `KSeF API error: HTTP ${statusCode}`;
44
44
  return new _KSeFApiError(message, statusCode, body);
45
45
  }
46
+ toProblemFields() {
47
+ return { detail: this.message };
48
+ }
46
49
  };
47
50
  }
48
51
  });
@@ -54,17 +57,20 @@ var init_ksef_rate_limit_error = __esm({
54
57
  "use strict";
55
58
  init_ksef_api_error();
56
59
  KSeFRateLimitError = class _KSeFRateLimitError extends KSeFApiError {
60
+ statusCode = 429;
57
61
  retryAfterSeconds;
58
62
  retryAfterDate;
59
63
  recommendedDelay;
60
- constructor(message, statusCode, errorResponse, retryAfterSeconds, retryAfterDate) {
64
+ problem;
65
+ constructor(message, statusCode, errorResponse, retryAfterSeconds, retryAfterDate, problem) {
61
66
  super(message, statusCode, errorResponse);
62
67
  this.name = "KSeFRateLimitError";
63
68
  this.retryAfterSeconds = retryAfterSeconds;
64
69
  this.retryAfterDate = retryAfterDate;
65
70
  this.recommendedDelay = retryAfterSeconds ?? 60;
71
+ this.problem = problem;
66
72
  }
67
- static fromRetryAfterHeader(statusCode, retryAfterHeader, body) {
73
+ static fromRetryAfterHeader(statusCode, retryAfterHeader, body, problem) {
68
74
  let retryAfterSeconds;
69
75
  let retryAfterDate;
70
76
  if (retryAfterHeader) {
@@ -79,8 +85,16 @@ var init_ksef_rate_limit_error = __esm({
79
85
  }
80
86
  }
81
87
  }
82
- const message = retryAfterSeconds != null ? `Rate limited. Retry after ${retryAfterSeconds}s` : "Rate limited by KSeF API";
83
- return new _KSeFRateLimitError(message, statusCode, body, retryAfterSeconds, retryAfterDate);
88
+ const message = retryAfterSeconds != null ? `Rate limited. Retry after ${retryAfterSeconds}s` : problem?.detail ?? "Rate limited by KSeF API";
89
+ return new _KSeFRateLimitError(message, statusCode, body, retryAfterSeconds, retryAfterDate, problem);
90
+ }
91
+ toProblemFields() {
92
+ return {
93
+ detail: this.problem?.detail,
94
+ traceId: this.problem?.traceId,
95
+ instance: this.problem?.instance,
96
+ timestamp: this.problem?.timestamp
97
+ };
84
98
  }
85
99
  };
86
100
  }
@@ -91,21 +105,29 @@ var KSeFUnauthorizedError;
91
105
  var init_ksef_unauthorized_error = __esm({
92
106
  "src/errors/ksef-unauthorized-error.ts"() {
93
107
  "use strict";
94
- init_ksef_error();
95
- KSeFUnauthorizedError = class extends KSeFError {
108
+ init_ksef_api_error();
109
+ KSeFUnauthorizedError = class extends KSeFApiError {
96
110
  statusCode = 401;
97
111
  detail;
98
112
  traceId;
99
113
  instance;
100
114
  timestamp;
101
115
  constructor(problemDetails) {
102
- super(problemDetails.detail || "Unauthorized");
116
+ super(problemDetails.detail || "Unauthorized", 401);
103
117
  this.name = "KSeFUnauthorizedError";
104
118
  this.detail = problemDetails.detail;
105
119
  this.traceId = problemDetails.traceId;
106
120
  this.instance = problemDetails.instance;
107
121
  this.timestamp = problemDetails.timestamp;
108
122
  }
123
+ toProblemFields() {
124
+ return {
125
+ detail: this.detail,
126
+ traceId: this.traceId,
127
+ instance: this.instance,
128
+ timestamp: this.timestamp
129
+ };
130
+ }
109
131
  };
110
132
  }
111
133
  });
@@ -115,8 +137,8 @@ var KSeFForbiddenError;
115
137
  var init_ksef_forbidden_error = __esm({
116
138
  "src/errors/ksef-forbidden-error.ts"() {
117
139
  "use strict";
118
- init_ksef_error();
119
- KSeFForbiddenError = class extends KSeFError {
140
+ init_ksef_api_error();
141
+ KSeFForbiddenError = class extends KSeFApiError {
120
142
  statusCode = 403;
121
143
  detail;
122
144
  reasonCode;
@@ -125,7 +147,7 @@ var init_ksef_forbidden_error = __esm({
125
147
  traceId;
126
148
  timestamp;
127
149
  constructor(problemDetails) {
128
- super(problemDetails.detail || "Forbidden");
150
+ super(problemDetails.detail || "Forbidden", 403);
129
151
  this.name = "KSeFForbiddenError";
130
152
  this.detail = problemDetails.detail;
131
153
  this.reasonCode = problemDetails.reasonCode;
@@ -134,10 +156,103 @@ var init_ksef_forbidden_error = __esm({
134
156
  this.traceId = problemDetails.traceId;
135
157
  this.timestamp = problemDetails.timestamp;
136
158
  }
159
+ toProblemFields() {
160
+ return {
161
+ detail: this.detail,
162
+ reasonCode: this.reasonCode,
163
+ security: this.security,
164
+ traceId: this.traceId,
165
+ instance: this.instance,
166
+ timestamp: this.timestamp
167
+ };
168
+ }
169
+ };
170
+ }
171
+ });
172
+
173
+ // src/errors/ksef-gone-error.ts
174
+ var KSeFGoneError;
175
+ var init_ksef_gone_error = __esm({
176
+ "src/errors/ksef-gone-error.ts"() {
177
+ "use strict";
178
+ init_ksef_api_error();
179
+ KSeFGoneError = class extends KSeFApiError {
180
+ statusCode = 410;
181
+ detail;
182
+ instance;
183
+ traceId;
184
+ timestamp;
185
+ constructor(problemDetails) {
186
+ super(problemDetails.detail || "Operation status no longer available (retention expired)", 410);
187
+ this.name = "KSeFGoneError";
188
+ this.detail = problemDetails.detail;
189
+ this.instance = problemDetails.instance;
190
+ this.traceId = problemDetails.traceId;
191
+ this.timestamp = problemDetails.timestamp;
192
+ }
193
+ toProblemFields() {
194
+ return {
195
+ detail: this.detail,
196
+ traceId: this.traceId,
197
+ instance: this.instance,
198
+ timestamp: this.timestamp
199
+ };
200
+ }
201
+ };
202
+ }
203
+ });
204
+
205
+ // src/errors/ksef-bad-request-error.ts
206
+ var KSeFBadRequestError;
207
+ var init_ksef_bad_request_error = __esm({
208
+ "src/errors/ksef-bad-request-error.ts"() {
209
+ "use strict";
210
+ init_ksef_api_error();
211
+ KSeFBadRequestError = class extends KSeFApiError {
212
+ statusCode = 400;
213
+ detail;
214
+ instance;
215
+ errors;
216
+ traceId;
217
+ timestamp;
218
+ constructor(problemDetails) {
219
+ super(problemDetails.detail || problemDetails.title || "Bad Request", 400);
220
+ this.name = "KSeFBadRequestError";
221
+ this.detail = problemDetails.detail;
222
+ this.instance = problemDetails.instance;
223
+ this.errors = problemDetails.errors ?? [];
224
+ this.traceId = problemDetails.traceId;
225
+ this.timestamp = problemDetails.timestamp;
226
+ }
227
+ toProblemFields() {
228
+ return {
229
+ detail: this.detail,
230
+ errors: this.errors.length ? this.errors : void 0,
231
+ traceId: this.traceId,
232
+ instance: this.instance,
233
+ timestamp: this.timestamp
234
+ };
235
+ }
137
236
  };
138
237
  }
139
238
  });
140
239
 
240
+ // src/errors/ksef-auth-status-error.ts
241
+ var init_ksef_auth_status_error = __esm({
242
+ "src/errors/ksef-auth-status-error.ts"() {
243
+ "use strict";
244
+ init_ksef_error();
245
+ }
246
+ });
247
+
248
+ // src/errors/ksef-session-expired-error.ts
249
+ var init_ksef_session_expired_error = __esm({
250
+ "src/errors/ksef-session-expired-error.ts"() {
251
+ "use strict";
252
+ init_ksef_error();
253
+ }
254
+ });
255
+
141
256
  // src/errors/ksef-validation-error.ts
142
257
  var ksef_validation_error_exports = {};
143
258
  __export(ksef_validation_error_exports, {
@@ -166,6 +281,72 @@ var init_ksef_validation_error = __esm({
166
281
  }
167
282
  });
168
283
 
284
+ // src/errors/error-codes.ts
285
+ function hasErrorCode(body, code) {
286
+ return !!body?.exception?.exceptionDetailList?.some((d) => d.exceptionCode === code);
287
+ }
288
+ var KSeFErrorCode;
289
+ var init_error_codes = __esm({
290
+ "src/errors/error-codes.ts"() {
291
+ "use strict";
292
+ KSeFErrorCode = {
293
+ BatchTimeout: 21208,
294
+ DuplicateInvoice: 440
295
+ };
296
+ }
297
+ });
298
+
299
+ // src/errors/ksef-batch-timeout-error.ts
300
+ var KSeFBatchTimeoutError;
301
+ var init_ksef_batch_timeout_error = __esm({
302
+ "src/errors/ksef-batch-timeout-error.ts"() {
303
+ "use strict";
304
+ init_ksef_api_error();
305
+ init_error_codes();
306
+ KSeFBatchTimeoutError = class _KSeFBatchTimeoutError extends KSeFApiError {
307
+ errorCode = KSeFErrorCode.BatchTimeout;
308
+ constructor(message, statusCode, errorResponse) {
309
+ super(message, statusCode, errorResponse);
310
+ this.name = "KSeFBatchTimeoutError";
311
+ }
312
+ static fromResponse(statusCode, body) {
313
+ const detail = body?.exception?.exceptionDetailList?.find(
314
+ (d) => d.exceptionCode === KSeFErrorCode.BatchTimeout
315
+ );
316
+ const message = detail?.exceptionDescription?.trim() || "Batch session timed out before the server completed processing (KSeF 21208).";
317
+ return new _KSeFBatchTimeoutError(message, statusCode, body);
318
+ }
319
+ };
320
+ }
321
+ });
322
+
323
+ // src/errors/assert-never.ts
324
+ var init_assert_never = __esm({
325
+ "src/errors/assert-never.ts"() {
326
+ "use strict";
327
+ }
328
+ });
329
+
330
+ // src/errors/index.ts
331
+ var init_errors = __esm({
332
+ "src/errors/index.ts"() {
333
+ "use strict";
334
+ init_ksef_error();
335
+ init_ksef_api_error();
336
+ init_ksef_rate_limit_error();
337
+ init_ksef_unauthorized_error();
338
+ init_ksef_forbidden_error();
339
+ init_ksef_gone_error();
340
+ init_ksef_bad_request_error();
341
+ init_ksef_auth_status_error();
342
+ init_ksef_session_expired_error();
343
+ init_ksef_validation_error();
344
+ init_ksef_batch_timeout_error();
345
+ init_error_codes();
346
+ init_assert_never();
347
+ }
348
+ });
349
+
169
350
  // src/config/environments.ts
170
351
  var Environment;
171
352
  var init_environments = __esm({
@@ -201,7 +382,8 @@ function resolveOptions(options = {}) {
201
382
  apiVersion: options.apiVersion ?? DEFAULT_API_VERSION,
202
383
  timeout: options.timeout ?? DEFAULT_TIMEOUT,
203
384
  customHeaders: options.customHeaders ?? {},
204
- environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST")
385
+ environmentName: options.environment ?? (options.baseUrl ? void 0 : "TEST"),
386
+ errorFormat: options.errorFormat ?? "problem-details"
205
387
  };
206
388
  }
207
389
  var DEFAULT_API_VERSION, DEFAULT_TIMEOUT;
@@ -223,69 +405,6 @@ var init_config = __esm({
223
405
  }
224
406
  });
225
407
 
226
- // src/errors/ksef-gone-error.ts
227
- var KSeFGoneError;
228
- var init_ksef_gone_error = __esm({
229
- "src/errors/ksef-gone-error.ts"() {
230
- "use strict";
231
- init_ksef_error();
232
- KSeFGoneError = class extends KSeFError {
233
- statusCode = 410;
234
- detail;
235
- instance;
236
- traceId;
237
- timestamp;
238
- constructor(problemDetails) {
239
- super(problemDetails.detail || "Operation status no longer available (retention expired)");
240
- this.name = "KSeFGoneError";
241
- this.detail = problemDetails.detail;
242
- this.instance = problemDetails.instance;
243
- this.traceId = problemDetails.traceId;
244
- this.timestamp = problemDetails.timestamp;
245
- }
246
- };
247
- }
248
- });
249
-
250
- // src/errors/error-codes.ts
251
- function hasErrorCode(body, code) {
252
- return !!body?.exception?.exceptionDetailList?.some((d) => d.exceptionCode === code);
253
- }
254
- var KSeFErrorCode;
255
- var init_error_codes = __esm({
256
- "src/errors/error-codes.ts"() {
257
- "use strict";
258
- KSeFErrorCode = {
259
- BatchTimeout: 21208,
260
- DuplicateInvoice: 440
261
- };
262
- }
263
- });
264
-
265
- // src/errors/ksef-batch-timeout-error.ts
266
- var KSeFBatchTimeoutError;
267
- var init_ksef_batch_timeout_error = __esm({
268
- "src/errors/ksef-batch-timeout-error.ts"() {
269
- "use strict";
270
- init_ksef_api_error();
271
- init_error_codes();
272
- KSeFBatchTimeoutError = class _KSeFBatchTimeoutError extends KSeFApiError {
273
- errorCode = KSeFErrorCode.BatchTimeout;
274
- constructor(message, statusCode, errorResponse) {
275
- super(message, statusCode, errorResponse);
276
- this.name = "KSeFBatchTimeoutError";
277
- }
278
- static fromResponse(statusCode, body) {
279
- const detail = body?.exception?.exceptionDetailList?.find(
280
- (d) => d.exceptionCode === KSeFErrorCode.BatchTimeout
281
- );
282
- const message = detail?.exceptionDescription?.trim() || "Batch session timed out before the server completed processing (KSeF 21208).";
283
- return new _KSeFBatchTimeoutError(message, statusCode, body);
284
- }
285
- };
286
- }
287
- });
288
-
289
408
  // src/http/route-builder.ts
290
409
  var RouteBuilder;
291
410
  var init_route_builder = __esm({
@@ -455,6 +574,27 @@ var init_presigned_url_policy = __esm({
455
574
 
456
575
  // src/http/rest-client.ts
457
576
  import { consola as consola3 } from "consola";
577
+ function isBadRequestProblem(value) {
578
+ if (typeof value !== "object" || value === null) return false;
579
+ const v = value;
580
+ if (typeof v.title !== "string") return false;
581
+ if (v.status !== void 0 && typeof v.status !== "number") return false;
582
+ if (v.errors !== void 0) {
583
+ if (!Array.isArray(v.errors)) return false;
584
+ for (const item of v.errors) {
585
+ if (typeof item !== "object" || item === null) return false;
586
+ const detail = item;
587
+ if (typeof detail.code !== "number") return false;
588
+ if (typeof detail.description !== "string") return false;
589
+ }
590
+ }
591
+ return true;
592
+ }
593
+ function isTooManyRequestsProblem(value) {
594
+ if (typeof value !== "object" || value === null) return false;
595
+ const v = value;
596
+ return typeof v.title === "string" && (v.status === void 0 || typeof v.status === "number") && (v.detail === void 0 || typeof v.detail === "string") && (v.instance === void 0 || typeof v.instance === "string") && (v.traceId === void 0 || typeof v.traceId === "string") && (v.timestamp === void 0 || typeof v.timestamp === "string");
597
+ }
458
598
  var RestClient;
459
599
  var init_rest_client = __esm({
460
600
  "src/http/rest-client.ts"() {
@@ -464,6 +604,7 @@ var init_rest_client = __esm({
464
604
  init_ksef_unauthorized_error();
465
605
  init_ksef_forbidden_error();
466
606
  init_ksef_gone_error();
607
+ init_ksef_bad_request_error();
467
608
  init_ksef_batch_timeout_error();
468
609
  init_error_codes();
469
610
  init_route_builder();
@@ -552,6 +693,10 @@ var init_rest_client = __esm({
552
693
  ...this.options.customHeaders,
553
694
  ...request.getHeaders()
554
695
  };
696
+ const hasHeader = (name) => Object.keys(headers).some((header) => header.toLowerCase() === name.toLowerCase());
697
+ if (this.options.errorFormat !== "legacy" && !hasHeader("x-error-format")) {
698
+ headers["X-Error-Format"] = "problem-details";
699
+ }
555
700
  if (!headers["Authorization"] && this.authManager) {
556
701
  const token = overrideToken ?? this.authManager.getAccessToken();
557
702
  if (token) {
@@ -590,19 +735,40 @@ var init_rest_client = __esm({
590
735
  async ensureSuccess(response) {
591
736
  if (response.ok) return;
592
737
  const text = await response.text().catch(() => "");
738
+ let jsonCache = null;
593
739
  const parseJson = () => {
594
- try {
595
- return JSON.parse(text);
596
- } catch {
597
- return void 0;
740
+ if (jsonCache === null) {
741
+ try {
742
+ jsonCache = { value: JSON.parse(text) };
743
+ } catch {
744
+ jsonCache = { value: void 0 };
745
+ }
598
746
  }
747
+ return jsonCache.value;
599
748
  };
600
- if (response.status === 429) {
749
+ const tryParseProblem = (guard) => {
601
750
  const parsed = parseJson();
751
+ return parsed !== void 0 && guard(parsed) ? parsed : void 0;
752
+ };
753
+ if (response.status === 400) {
754
+ const problem = tryParseProblem(isBadRequestProblem);
755
+ if (problem) {
756
+ throw new KSeFBadRequestError(problem);
757
+ }
758
+ const legacy = parseJson();
759
+ if (hasErrorCode(legacy, KSeFErrorCode.BatchTimeout)) {
760
+ throw KSeFBatchTimeoutError.fromResponse(400, legacy);
761
+ }
762
+ throw KSeFApiError.fromResponse(400, legacy);
763
+ }
764
+ if (response.status === 429) {
765
+ const problem = tryParseProblem(isTooManyRequestsProblem);
766
+ const legacy = problem ? void 0 : parseJson();
602
767
  throw KSeFRateLimitError.fromRetryAfterHeader(
603
768
  response.status,
604
769
  response.headers.get("Retry-After"),
605
- parsed
770
+ legacy,
771
+ problem
606
772
  );
607
773
  }
608
774
  if (response.status === 401) {
@@ -1336,9 +1502,10 @@ var PermissionsService;
1336
1502
  var init_permissions = __esm({
1337
1503
  "src/services/permissions.ts"() {
1338
1504
  "use strict";
1505
+ init_ksef_validation_error();
1339
1506
  init_rest_request();
1340
1507
  init_routes();
1341
- PermissionsService = class {
1508
+ PermissionsService = class _PermissionsService {
1342
1509
  restClient;
1343
1510
  constructor(restClient) {
1344
1511
  this.restClient = restClient;
@@ -1396,6 +1563,7 @@ var init_permissions = __esm({
1396
1563
  }
1397
1564
  // Search methods
1398
1565
  async queryPersonalGrants(options, pageOffset, pageSize) {
1566
+ _PermissionsService.validateContextIdentifier(options?.contextIdentifier);
1399
1567
  const req = RestRequest.post(Routes.Permissions.Query.personalGrants).body(options ?? {});
1400
1568
  if (pageOffset !== void 0) req.query("pageOffset", String(pageOffset));
1401
1569
  if (pageSize !== void 0) req.query("pageSize", String(pageSize));
@@ -1424,6 +1592,7 @@ var init_permissions = __esm({
1424
1592
  return response.body;
1425
1593
  }
1426
1594
  async queryEntitiesGrants(options, pageOffset, pageSize) {
1595
+ _PermissionsService.validateContextIdentifier(options?.contextIdentifier);
1427
1596
  const req = RestRequest.post(Routes.Permissions.Query.entitiesGrants).body(options ?? {});
1428
1597
  if (pageOffset !== void 0) req.query("pageOffset", String(pageOffset));
1429
1598
  if (pageSize !== void 0) req.query("pageSize", String(pageSize));
@@ -1462,17 +1631,90 @@ var init_permissions = __esm({
1462
1631
  const response = await this.restClient.execute(req);
1463
1632
  return response.body;
1464
1633
  }
1634
+ static validateContextIdentifier(ctx) {
1635
+ if (!ctx) return;
1636
+ if (ctx.type === "InternalId") {
1637
+ const len = ctx.value.length;
1638
+ if (len < 10 || len > 16) {
1639
+ throw KSeFValidationError.fromField(
1640
+ "contextIdentifier.value",
1641
+ `InternalId must be 10-16 characters, got ${len}`
1642
+ );
1643
+ }
1644
+ }
1645
+ }
1465
1646
  };
1466
1647
  }
1467
1648
  });
1468
1649
 
1650
+ // src/utils/jwt.ts
1651
+ function decodeJwtPayload(token) {
1652
+ const parts = token.split(".");
1653
+ if (parts.length !== 3) return null;
1654
+ try {
1655
+ const payload = parts[1];
1656
+ const json = Buffer.from(payload, "base64url").toString("utf-8");
1657
+ return JSON.parse(json);
1658
+ } catch {
1659
+ return null;
1660
+ }
1661
+ }
1662
+ function tryParseJson(value) {
1663
+ if (typeof value !== "string") return void 0;
1664
+ try {
1665
+ return JSON.parse(value);
1666
+ } catch {
1667
+ return void 0;
1668
+ }
1669
+ }
1670
+ function tryParseJsonArray(value) {
1671
+ if (typeof value !== "string") return void 0;
1672
+ try {
1673
+ const parsed = JSON.parse(value);
1674
+ return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : void 0;
1675
+ } catch {
1676
+ return void 0;
1677
+ }
1678
+ }
1679
+ function parseKSeFTokenContext(token) {
1680
+ const raw = decodeJwtPayload(token);
1681
+ if (!raw) return null;
1682
+ return {
1683
+ type: typeof raw["typ"] === "string" ? raw["typ"] : void 0,
1684
+ contextIdentifierType: typeof raw["cit"] === "string" ? raw["cit"] : void 0,
1685
+ contextIdentifierValue: typeof raw["civ"] === "string" ? raw["civ"] : void 0,
1686
+ authMethod: typeof raw["aum"] === "string" ? raw["aum"] : void 0,
1687
+ permissions: tryParseJsonArray(raw["per"]),
1688
+ subjectDetails: tryParseJson(raw["sud"]),
1689
+ authorSubjectIdentifier: tryParseJson(raw["asi"]),
1690
+ issuedAt: typeof raw["iat"] === "number" ? raw["iat"] : void 0,
1691
+ expiresAt: typeof raw["exp"] === "number" ? raw["exp"] : void 0
1692
+ };
1693
+ }
1694
+ var init_jwt = __esm({
1695
+ "src/utils/jwt.ts"() {
1696
+ "use strict";
1697
+ }
1698
+ });
1699
+
1469
1700
  // src/services/tokens.ts
1470
- var TokenService;
1701
+ function toTokenAuthorIdentifierType(value) {
1702
+ return TOKEN_AUTHOR_IDENTIFIER_TYPES.has(value) ? value : void 0;
1703
+ }
1704
+ var TOKEN_AUTHOR_IDENTIFIER_TYPES, TokenService;
1471
1705
  var init_tokens = __esm({
1472
1706
  "src/services/tokens.ts"() {
1473
1707
  "use strict";
1474
1708
  init_rest_request();
1475
1709
  init_routes();
1710
+ init_jwt();
1711
+ init_ksef_api_error();
1712
+ init_ksef_error();
1713
+ TOKEN_AUTHOR_IDENTIFIER_TYPES = /* @__PURE__ */ new Set([
1714
+ "Nip",
1715
+ "Pesel",
1716
+ "Fingerprint"
1717
+ ]);
1476
1718
  TokenService = class {
1477
1719
  restClient;
1478
1720
  constructor(restClient) {
@@ -1507,6 +1749,73 @@ var init_tokens = __esm({
1507
1749
  const req = RestRequest.delete(Routes.Tokens.byReference(ref));
1508
1750
  await this.restClient.executeVoid(req);
1509
1751
  }
1752
+ /**
1753
+ * Resolves the reference number of the token currently in use for authentication.
1754
+ * The only JWT payload field treated as authoritative is the KSeF-specific `trn`
1755
+ * (token reference number). Standard RFC 7519 claims such as `jti` are NOT a safe
1756
+ * fallback — a `jti` that differs from the KSeF reference would cause a DELETE to
1757
+ * hit a non-existent path, which `revokeSelf` treats as already-revoked, falsely
1758
+ * reporting success while leaving the token active on the server. When `trn` is
1759
+ * absent, we fall back to `GET /tokens` filtered by author and context; requires
1760
+ * exactly one active match and returns undefined when ambiguous.
1761
+ */
1762
+ async findSelfReferenceNumber(accessToken) {
1763
+ if (!accessToken) return void 0;
1764
+ const payload = decodeJwtPayload(accessToken);
1765
+ if (payload && typeof payload["trn"] === "string" && payload["trn"].length > 0) {
1766
+ return payload["trn"];
1767
+ }
1768
+ const ctx = parseKSeFTokenContext(accessToken);
1769
+ const author = ctx?.authorSubjectIdentifier;
1770
+ if (!author?.type || !author.value) return void 0;
1771
+ if (!ctx?.contextIdentifierType || !ctx?.contextIdentifierValue) return void 0;
1772
+ const authorType = toTokenAuthorIdentifierType(author.type);
1773
+ if (!authorType) return void 0;
1774
+ let continuationToken;
1775
+ let match;
1776
+ do {
1777
+ const list5 = await this.queryTokens({
1778
+ status: ["Active"],
1779
+ authorIdentifier: author.value,
1780
+ authorIdentifierType: authorType,
1781
+ pageSize: 50,
1782
+ continuationToken
1783
+ });
1784
+ for (const t of list5.tokens) {
1785
+ if (t.status === "Active" && t.contextIdentifier?.value === ctx.contextIdentifierValue && t.contextIdentifier?.type === ctx.contextIdentifierType) {
1786
+ if (match) return void 0;
1787
+ match = t.referenceNumber;
1788
+ }
1789
+ }
1790
+ continuationToken = list5.continuationToken ?? void 0;
1791
+ } while (continuationToken);
1792
+ return match;
1793
+ }
1794
+ /**
1795
+ * Revokes the token currently used for authentication.
1796
+ * Treats 404/409/410 on DELETE as "already revoked" and returns successfully with
1797
+ * `alreadyRevoked: true` so callers can still clear local state.
1798
+ */
1799
+ async revokeSelf(opts = {}) {
1800
+ let ref = opts.referenceNumber;
1801
+ if (!ref && opts.accessToken) {
1802
+ ref = await this.findSelfReferenceNumber(opts.accessToken);
1803
+ }
1804
+ if (!ref) {
1805
+ throw new KSeFError(
1806
+ "Could not determine the current token reference number: no cache, JWT lacks the field, and the active-token list had 0 or 2+ matches in the current context."
1807
+ );
1808
+ }
1809
+ try {
1810
+ await this.revokeToken(ref);
1811
+ return { referenceNumber: ref, alreadyRevoked: false };
1812
+ } catch (err) {
1813
+ if (err instanceof KSeFApiError && (err.statusCode === 404 || err.statusCode === 409 || err.statusCode === 410)) {
1814
+ return { referenceNumber: ref, alreadyRevoked: true };
1815
+ }
1816
+ throw err;
1817
+ }
1818
+ }
1510
1819
  };
1511
1820
  }
1512
1821
  });
@@ -1563,40 +1872,6 @@ var init_certificates = __esm({
1563
1872
  }
1564
1873
  });
1565
1874
 
1566
- // src/errors/ksef-auth-status-error.ts
1567
- var init_ksef_auth_status_error = __esm({
1568
- "src/errors/ksef-auth-status-error.ts"() {
1569
- "use strict";
1570
- init_ksef_error();
1571
- }
1572
- });
1573
-
1574
- // src/errors/ksef-session-expired-error.ts
1575
- var init_ksef_session_expired_error = __esm({
1576
- "src/errors/ksef-session-expired-error.ts"() {
1577
- "use strict";
1578
- init_ksef_error();
1579
- }
1580
- });
1581
-
1582
- // src/errors/index.ts
1583
- var init_errors = __esm({
1584
- "src/errors/index.ts"() {
1585
- "use strict";
1586
- init_ksef_error();
1587
- init_ksef_api_error();
1588
- init_ksef_rate_limit_error();
1589
- init_ksef_unauthorized_error();
1590
- init_ksef_forbidden_error();
1591
- init_ksef_gone_error();
1592
- init_ksef_auth_status_error();
1593
- init_ksef_session_expired_error();
1594
- init_ksef_validation_error();
1595
- init_ksef_batch_timeout_error();
1596
- init_error_codes();
1597
- }
1598
- });
1599
-
1600
1875
  // src/services/lighthouse.ts
1601
1876
  var LighthouseService;
1602
1877
  var init_lighthouse = __esm({
@@ -2761,8 +3036,8 @@ function computeRootDigest(doc) {
2761
3036
  return crypto4.createHash("sha256").update(canonical, "utf-8").digest("base64");
2762
3037
  }
2763
3038
  function computeSignedPropertiesDigest(qualifyingPropertiesXml) {
2764
- const parser = new DOMParser();
2765
- const qpDoc = parser.parseFromString(qualifyingPropertiesXml, "text/xml");
3039
+ const parser2 = new DOMParser();
3040
+ const qpDoc = parser2.parseFromString(qualifyingPropertiesXml, "text/xml");
2766
3041
  const signedProps = findElementByLocalName(qpDoc.documentElement, "SignedProperties");
2767
3042
  if (!signedProps) {
2768
3043
  throw new Error("SignedProperties element not found in QualifyingProperties");
@@ -2914,8 +3189,8 @@ var init_signature_service = __esm({
2914
3189
  const isEc = privateKey.asymmetricKeyType === "ec";
2915
3190
  const signatureAlgorithm = isEc ? ECDSA_SHA256_SIGNATURE : RSA_SHA256_SIGNATURE;
2916
3191
  const signingTime = new Date(Date.now() + CLOCK_SKEW_BUFFER_MS).toISOString();
2917
- const parser = new DOMParser();
2918
- const doc = parser.parseFromString(xml, "text/xml");
3192
+ const parser2 = new DOMParser();
3193
+ const doc = parser2.parseFromString(xml, "text/xml");
2919
3194
  const root = doc.documentElement;
2920
3195
  if (!root) {
2921
3196
  throw new Error("XML document has no root element");
@@ -2935,7 +3210,7 @@ var init_signature_service = __esm({
2935
3210
  rootDigest,
2936
3211
  signedPropertiesDigest
2937
3212
  );
2938
- const signedInfoDoc = parser.parseFromString(signedInfoXml, "text/xml");
3213
+ const signedInfoDoc = parser2.parseFromString(signedInfoXml, "text/xml");
2939
3214
  const canonicalSignedInfo = canonicalize(signedInfoDoc.documentElement);
2940
3215
  const signatureValue = computeSignatureValue(
2941
3216
  canonicalSignedInfo,
@@ -2948,7 +3223,7 @@ var init_signature_service = __esm({
2948
3223
  certBase64,
2949
3224
  qualifyingPropertiesXml
2950
3225
  );
2951
- const signatureDoc = parser.parseFromString(signatureXml, "text/xml");
3226
+ const signatureDoc = parser2.parseFromString(signatureXml, "text/xml");
2952
3227
  const importedNode = doc.importNode(signatureDoc.documentElement, true);
2953
3228
  root.appendChild(importedNode);
2954
3229
  return new XMLSerializer().serializeToString(doc);
@@ -3378,12 +3653,84 @@ var init_invoice_field_extractor = __esm({
3378
3653
  }
3379
3654
  });
3380
3655
 
3656
+ // src/xml/xml-engine.ts
3657
+ import { XMLBuilder, XMLParser as XMLParser3 } from "fast-xml-parser";
3658
+ var parser, builder;
3659
+ var init_xml_engine = __esm({
3660
+ "src/xml/xml-engine.ts"() {
3661
+ "use strict";
3662
+ parser = new XMLParser3({
3663
+ ignoreAttributes: false,
3664
+ preserveOrder: true,
3665
+ attributeNamePrefix: "@_",
3666
+ textNodeName: "#text",
3667
+ allowBooleanAttributes: true,
3668
+ // Preserve leading zeros and keep everything as strings — KSeF fields like
3669
+ // KRS (`\d{10}`) and NIP (`\d{10}`) would otherwise be lossy through parse.
3670
+ parseTagValue: false,
3671
+ parseAttributeValue: false,
3672
+ trimValues: false
3673
+ });
3674
+ builder = new XMLBuilder({
3675
+ ignoreAttributes: false,
3676
+ preserveOrder: true,
3677
+ attributeNamePrefix: "@_",
3678
+ textNodeName: "#text",
3679
+ format: false,
3680
+ suppressBooleanAttributes: false,
3681
+ suppressEmptyNode: false,
3682
+ processEntities: true
3683
+ });
3684
+ }
3685
+ });
3686
+
3687
+ // src/xml/order-map.ts
3688
+ var init_order_map = __esm({
3689
+ "src/xml/order-map.ts"() {
3690
+ "use strict";
3691
+ }
3692
+ });
3693
+
3694
+ // src/xml/faktura-builder.ts
3695
+ var init_faktura_builder = __esm({
3696
+ "src/xml/faktura-builder.ts"() {
3697
+ "use strict";
3698
+ init_xml_engine();
3699
+ init_order_map();
3700
+ }
3701
+ });
3702
+
3703
+ // src/xml/pef-builder.ts
3704
+ var init_pef_builder = __esm({
3705
+ "src/xml/pef-builder.ts"() {
3706
+ "use strict";
3707
+ init_ksef_validation_error();
3708
+ init_xml_engine();
3709
+ }
3710
+ });
3711
+
3712
+ // src/xml/invoice-serializer.ts
3713
+ var init_invoice_serializer = __esm({
3714
+ "src/xml/invoice-serializer.ts"() {
3715
+ "use strict";
3716
+ init_ksef_validation_error();
3717
+ init_faktura_builder();
3718
+ init_pef_builder();
3719
+ init_xml_engine();
3720
+ }
3721
+ });
3722
+
3381
3723
  // src/xml/index.ts
3382
3724
  var init_xml = __esm({
3383
3725
  "src/xml/index.ts"() {
3384
3726
  "use strict";
3385
3727
  init_upo_parser();
3386
3728
  init_invoice_field_extractor();
3729
+ init_xml_engine();
3730
+ init_order_map();
3731
+ init_faktura_builder();
3732
+ init_pef_builder();
3733
+ init_invoice_serializer();
3387
3734
  }
3388
3735
  });
3389
3736
 
@@ -5034,6 +5381,115 @@ var init_schema_registry = __esm({
5034
5381
  }
5035
5382
  });
5036
5383
 
5384
+ // src/validation/char-validity.ts
5385
+ function validateCharValidity(xml) {
5386
+ return [...findProcessingInstructions(xml), ...findDiscouragedUnicode(xml)];
5387
+ }
5388
+ function findProcessingInstructionTokens(xml) {
5389
+ const tokens = [];
5390
+ for (let i = 0; i < xml.length; ) {
5391
+ if (xml.startsWith("<!--", i)) {
5392
+ const end = xml.indexOf("-->", i + 4);
5393
+ i = end === -1 ? xml.length : end + 3;
5394
+ continue;
5395
+ }
5396
+ if (xml.startsWith("<![CDATA[", i)) {
5397
+ const end = xml.indexOf("]]>", i + 9);
5398
+ i = end === -1 ? xml.length : end + 3;
5399
+ continue;
5400
+ }
5401
+ if (xml.startsWith("<?", i)) {
5402
+ const end = xml.indexOf("?>", i + 2);
5403
+ if (end === -1) break;
5404
+ tokens.push({ token: xml.slice(i, end + 2), index: i });
5405
+ i = end + 2;
5406
+ continue;
5407
+ }
5408
+ i += 1;
5409
+ }
5410
+ return tokens;
5411
+ }
5412
+ function findProcessingInstructions(xml) {
5413
+ const errors = [];
5414
+ const matches = findProcessingInstructionTokens(xml);
5415
+ if (matches.length === 0) return errors;
5416
+ const firstMatch = matches[0];
5417
+ const firstTarget = firstMatch.token.match(PI_TARGET_RE)?.[1];
5418
+ const hasBom = xml.charCodeAt(0) === 65279;
5419
+ const prologPosition = hasBom ? 1 : 0;
5420
+ const firstIsProlog = firstMatch.index === prologPosition && firstTarget === "xml";
5421
+ for (let i = 0; i < matches.length; i++) {
5422
+ if (i === 0 && firstIsProlog) continue;
5423
+ const m = matches[i];
5424
+ const target = m.token.match(PI_TARGET_RE)?.[1] ?? "?";
5425
+ errors.push({
5426
+ code: "XML_PROCESSING_INSTRUCTION",
5427
+ message: `Processing instruction <?${target}?> at offset ${m.index} is not allowed (only <?xml ... ?> prolog is permitted)`,
5428
+ path: `offset:${m.index}`
5429
+ });
5430
+ }
5431
+ return errors;
5432
+ }
5433
+ function findDiscouragedUnicode(xml) {
5434
+ const errors = [];
5435
+ const seenRanges = /* @__PURE__ */ new Set();
5436
+ let utf16Offset = 0;
5437
+ for (const ch of xml) {
5438
+ const cp = ch.codePointAt(0);
5439
+ const idx = rangeIndex(cp);
5440
+ if (idx >= 0 && !seenRanges.has(idx)) {
5441
+ seenRanges.add(idx);
5442
+ errors.push({
5443
+ code: "XML_DISCOURAGED_UNICODE",
5444
+ message: `Discouraged Unicode character U+${cp.toString(16).toUpperCase().padStart(4, "0")} found at offset ${utf16Offset} (W3C XML 1.0 \xA72.2 rejects this range)`,
5445
+ path: `offset:${utf16Offset}`
5446
+ });
5447
+ }
5448
+ utf16Offset += ch.length;
5449
+ }
5450
+ return errors;
5451
+ }
5452
+ function rangeIndex(cp) {
5453
+ let lo = 0;
5454
+ let hi = DISCOURAGED_UNICODE_RANGES.length - 1;
5455
+ while (lo <= hi) {
5456
+ const mid = lo + hi >> 1;
5457
+ const [start, end] = DISCOURAGED_UNICODE_RANGES[mid];
5458
+ if (cp < start) hi = mid - 1;
5459
+ else if (cp > end) lo = mid + 1;
5460
+ else return mid;
5461
+ }
5462
+ return -1;
5463
+ }
5464
+ var DISCOURAGED_UNICODE_RANGES, PI_TARGET_RE;
5465
+ var init_char_validity = __esm({
5466
+ "src/validation/char-validity.ts"() {
5467
+ "use strict";
5468
+ DISCOURAGED_UNICODE_RANGES = [
5469
+ [127, 132],
5470
+ [134, 159],
5471
+ [64976, 65007],
5472
+ [131070, 131071],
5473
+ [196606, 196607],
5474
+ [262142, 262143],
5475
+ [327678, 327679],
5476
+ [393214, 393215],
5477
+ [458750, 458751],
5478
+ [524286, 524287],
5479
+ [589822, 589823],
5480
+ [655358, 655359],
5481
+ [720894, 720895],
5482
+ [786430, 786431],
5483
+ [851966, 851967],
5484
+ [917502, 917503],
5485
+ [983038, 983039],
5486
+ [1048574, 1048575],
5487
+ [1114110, 1114111]
5488
+ ];
5489
+ PI_TARGET_RE = /^<\?(\S+)/;
5490
+ }
5491
+ });
5492
+
5037
5493
  // src/validation/patterns.ts
5038
5494
  function isValidNip(value) {
5039
5495
  if (!Nip.test(value)) return false;
@@ -5220,6 +5676,12 @@ function collectDateErrors(obj, rootElement, errors) {
5220
5676
  }
5221
5677
  }
5222
5678
  async function validate(xml, options) {
5679
+ if (!options?.skipCharValidity) {
5680
+ const l1aErrors = validateCharValidity(xml);
5681
+ if (l1aErrors.length > 0) {
5682
+ return { valid: false, schemaType: null, errors: l1aErrors };
5683
+ }
5684
+ }
5223
5685
  const parsed = xml && xml.trim() ? xmlToObject(xml) : void 0;
5224
5686
  const l1 = validateWellFormedness(xml, parsed);
5225
5687
  if (!l1.valid) return l1;
@@ -5246,6 +5708,7 @@ var init_invoice_validator = __esm({
5246
5708
  "use strict";
5247
5709
  init_xml_to_object();
5248
5710
  init_schema_registry();
5711
+ init_char_validity();
5249
5712
  init_patterns();
5250
5713
  }
5251
5714
  });
@@ -5730,67 +6193,119 @@ function clearOnlineSessionRef() {
5730
6193
  }
5731
6194
  }
5732
6195
 
5733
- // src/cli/error-handler.ts
5734
- init_ksef_rate_limit_error();
5735
- init_ksef_unauthorized_error();
5736
- init_ksef_forbidden_error();
5737
- init_ksef_api_error();
5738
- init_ksef_validation_error();
6196
+ // src/cli/error-renderer.ts
6197
+ init_errors();
5739
6198
  import { consola as consola2 } from "consola";
5740
- async function withErrorHandler(fn) {
5741
- try {
5742
- await fn();
5743
- } catch (error) {
6199
+ function renderCliError(error, opts) {
6200
+ if (opts?.json) {
6201
+ const payload = error instanceof Error ? serializeError(error) : { name: "UnknownError", value: safeValue(error) };
6202
+ process.stdout.write(JSON.stringify({ error: payload }, null, 2) + "\n");
6203
+ return;
6204
+ }
6205
+ if (error instanceof KSeFApiError) {
5744
6206
  if (error instanceof KSeFRateLimitError) {
5745
6207
  consola2.error("Rate limited by KSeF API.");
5746
- consola2.info(`Hint: Retry after ${error.recommendedDelay}s.`);
5747
- process.exit(1);
5748
- }
5749
- if (error instanceof KSeFUnauthorizedError) {
5750
- consola2.error(`KSeF API error (HTTP 401): ${error.detail}`);
5751
- if (error.traceId) consola2.error(` Trace ID: ${error.traceId}`);
5752
- consola2.info("Hint: Your session may have expired. Run `ksef auth login` to re-authenticate.");
5753
- process.exit(1);
5754
- }
5755
- if (error instanceof KSeFForbiddenError) {
5756
- consola2.error(`KSeF API error (HTTP 403): ${error.detail}`);
5757
- consola2.error(` Reason: ${error.reasonCode}`);
5758
- if (error.traceId) consola2.error(` Trace ID: ${error.traceId}`);
5759
- consola2.info("Hint: Check your permissions for this operation.");
5760
- process.exit(1);
6208
+ } else {
6209
+ consola2.error(`KSeF API error (HTTP ${error.statusCode}): ${error.message}`);
5761
6210
  }
5762
- if (error instanceof KSeFValidationError) {
5763
- consola2.error(error.message);
5764
- for (const detail of error.details) {
5765
- consola2.error(` ${detail.field ? `[${detail.field}] ` : ""}${detail.message}`);
6211
+ renderProblemDetails(error.toProblemFields());
6212
+ const legacyDetails = error.errorResponse?.exception?.exceptionDetailList;
6213
+ if (legacyDetails?.length) {
6214
+ for (const d of legacyDetails) {
6215
+ consola2.error(` \u2514 [${d.exceptionCode}] ${d.exceptionDescription ?? ""}`);
5766
6216
  }
5767
- process.exit(1);
5768
6217
  }
5769
- if (error instanceof KSeFApiError) {
5770
- consola2.error(`KSeF API error (HTTP ${error.statusCode}): ${error.message}`);
5771
- if (error.errorResponse?.exception?.exceptionDetailList) {
5772
- for (const detail of error.errorResponse.exception.exceptionDetailList) {
5773
- consola2.error(` - [${detail.exceptionCode}] ${detail.exceptionDescription}`);
5774
- }
5775
- }
5776
- if (error.statusCode === 401 || error.statusCode === 403) {
5777
- consola2.info("Hint: Run `ksef auth login` to authenticate.");
5778
- } else if (error.statusCode === 404) {
5779
- consola2.info("Hint: Check if the resource reference is correct.");
5780
- }
5781
- process.exit(1);
6218
+ const hint = hintForStatus(error);
6219
+ if (hint) consola2.info(hint);
6220
+ return;
6221
+ }
6222
+ if (error instanceof KSeFValidationError) {
6223
+ consola2.error(error.message);
6224
+ for (const d of error.details) {
6225
+ consola2.error(` \u2514 ${d.field ? `[${d.field}] ` : ""}${d.message}`);
5782
6226
  }
5783
- if (error instanceof Error) {
5784
- const msg = error.message;
5785
- if (msg.includes("fetch failed") || msg.includes("ECONNREFUSED") || msg.includes("ETIMEDOUT") || msg.includes("ENOTFOUND")) {
5786
- consola2.error("Cannot reach KSeF API. Check your network connection and environment.");
5787
- consola2.info("Hint: Run `ksef doctor` to diagnose connectivity issues.");
5788
- process.exit(1);
5789
- }
6227
+ return;
6228
+ }
6229
+ if (error instanceof Error) {
6230
+ const msg = error.message;
6231
+ if (/fetch failed|ECONNREFUSED|ETIMEDOUT|ENOTFOUND/.test(msg)) {
6232
+ consola2.error("Cannot reach KSeF API. Check your network connection and environment.");
6233
+ consola2.info("Hint: Run `ksef doctor` to diagnose connectivity issues.");
6234
+ } else {
5790
6235
  consola2.error(msg);
5791
- process.exit(1);
5792
6236
  }
5793
- consola2.error("Unknown error", error);
6237
+ return;
6238
+ }
6239
+ consola2.error("Unknown error", error);
6240
+ }
6241
+ function renderProblemDetails(fields) {
6242
+ if (fields.detail) consola2.error(` \u2514 Detail: ${fields.detail}`);
6243
+ if (fields.reasonCode) consola2.error(` \u2514 Reason: ${fields.reasonCode}`);
6244
+ const required = fields.security?.requiredAnyOfPermissions;
6245
+ if (required?.length) {
6246
+ consola2.error(` \u2514 Required (any of): ${required.join(", ")}`);
6247
+ }
6248
+ const present = fields.security?.presentPermissions;
6249
+ if (present?.length) {
6250
+ consola2.error(` \u2514 Present: ${present.join(", ")}`);
6251
+ }
6252
+ if (fields.errors?.length) {
6253
+ consola2.error(` \u2514 Errors:`);
6254
+ for (const err of fields.errors) {
6255
+ consola2.error(` \u2022 [${err.code}] ${err.description}`);
6256
+ for (const d of err.details ?? []) {
6257
+ consola2.error(` \u2514 ${d}`);
6258
+ }
6259
+ }
6260
+ }
6261
+ if (fields.traceId) consola2.error(` \u2514 Trace ID: ${fields.traceId}`);
6262
+ if (fields.instance) consola2.error(` \u2514 Instance: ${fields.instance}`);
6263
+ if (fields.timestamp) consola2.error(` \u2514 Timestamp: ${fields.timestamp}`);
6264
+ }
6265
+ function safeValue(value) {
6266
+ try {
6267
+ return JSON.parse(JSON.stringify(value));
6268
+ } catch {
6269
+ return String(value);
6270
+ }
6271
+ }
6272
+ function serializeError(error) {
6273
+ if (error instanceof KSeFApiError) {
6274
+ return {
6275
+ ...error.toProblemFields(),
6276
+ name: error.name,
6277
+ statusCode: error.statusCode,
6278
+ message: error.message
6279
+ };
6280
+ }
6281
+ if (error instanceof KSeFValidationError) {
6282
+ return {
6283
+ name: error.name,
6284
+ message: error.message,
6285
+ details: error.details
6286
+ };
6287
+ }
6288
+ return {
6289
+ name: error.name,
6290
+ message: error.message
6291
+ };
6292
+ }
6293
+ function hintForStatus(error) {
6294
+ if (error instanceof KSeFRateLimitError) return `Hint: Retry after ${error.recommendedDelay}s.`;
6295
+ if (error instanceof KSeFUnauthorizedError) return "Hint: Your session may have expired. Run `ksef auth login` to re-authenticate.";
6296
+ if (error instanceof KSeFForbiddenError) return "Hint: Check your permissions for this operation.";
6297
+ if (error instanceof KSeFBadRequestError) return "Hint: Review the error list above; fix the flagged fields and retry.";
6298
+ if (error instanceof KSeFGoneError) return "Hint: The operation has aged out. Re-submit the request if still relevant.";
6299
+ if (error.statusCode === 404) return "Hint: Check if the resource reference is correct.";
6300
+ return void 0;
6301
+ }
6302
+
6303
+ // src/cli/error-handler.ts
6304
+ async function withErrorHandler(fn, opts) {
6305
+ try {
6306
+ await fn();
6307
+ } catch (error) {
6308
+ renderCliError(error, opts);
5794
6309
  process.exit(1);
5795
6310
  }
5796
6311
  }
@@ -5835,7 +6350,7 @@ var set = defineCommand({
5835
6350
  }
5836
6351
  saveConfig(config);
5837
6352
  outputSuccess("Configuration updated.");
5838
- });
6353
+ }, { json: Boolean(args.json) });
5839
6354
  }
5840
6355
  });
5841
6356
  var show = defineCommand({
@@ -5847,7 +6362,7 @@ var show = defineCommand({
5847
6362
  return withErrorHandler(async () => {
5848
6363
  const config = loadConfig();
5849
6364
  outputKeyValue(config, { json: args.json });
5850
- });
6365
+ }, { json: Boolean(args.json) });
5851
6366
  }
5852
6367
  });
5853
6368
  var reset = defineCommand({
@@ -5903,6 +6418,12 @@ function saveCredentials(creds) {
5903
6418
  mode: 384
5904
6419
  });
5905
6420
  }
6421
+ function clearCredentials() {
6422
+ try {
6423
+ fs3.unlinkSync(CREDENTIALS_FILE);
6424
+ } catch {
6425
+ }
6426
+ }
5906
6427
 
5907
6428
  // src/workflows/auth-workflow.ts
5908
6429
  init_polling();
@@ -6038,53 +6559,7 @@ function clearPendingChallenge() {
6038
6559
 
6039
6560
  // src/cli/commands/auth.ts
6040
6561
  init_polling();
6041
-
6042
- // src/utils/jwt.ts
6043
- function decodeJwtPayload(token) {
6044
- const parts = token.split(".");
6045
- if (parts.length !== 3) return null;
6046
- try {
6047
- const payload = parts[1];
6048
- const json = Buffer.from(payload, "base64url").toString("utf-8");
6049
- return JSON.parse(json);
6050
- } catch {
6051
- return null;
6052
- }
6053
- }
6054
- function tryParseJson(value) {
6055
- if (typeof value !== "string") return void 0;
6056
- try {
6057
- return JSON.parse(value);
6058
- } catch {
6059
- return void 0;
6060
- }
6061
- }
6062
- function tryParseJsonArray(value) {
6063
- if (typeof value !== "string") return void 0;
6064
- try {
6065
- const parsed = JSON.parse(value);
6066
- return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : void 0;
6067
- } catch {
6068
- return void 0;
6069
- }
6070
- }
6071
- function parseKSeFTokenContext(token) {
6072
- const raw = decodeJwtPayload(token);
6073
- if (!raw) return null;
6074
- return {
6075
- type: typeof raw["typ"] === "string" ? raw["typ"] : void 0,
6076
- contextIdentifierType: typeof raw["cit"] === "string" ? raw["cit"] : void 0,
6077
- contextIdentifierValue: typeof raw["civ"] === "string" ? raw["civ"] : void 0,
6078
- authMethod: typeof raw["aum"] === "string" ? raw["aum"] : void 0,
6079
- permissions: tryParseJsonArray(raw["per"]),
6080
- subjectDetails: tryParseJson(raw["sud"]),
6081
- authorSubjectIdentifier: tryParseJson(raw["asi"]),
6082
- issuedAt: typeof raw["iat"] === "number" ? raw["iat"] : void 0,
6083
- expiresAt: typeof raw["exp"] === "number" ? raw["exp"] : void 0
6084
- };
6085
- }
6086
-
6087
- // src/cli/commands/auth.ts
6562
+ init_jwt();
6088
6563
  async function readStdin(stream = process.stdin) {
6089
6564
  const chunks = [];
6090
6565
  for await (const chunk of stream) {
@@ -6115,7 +6590,7 @@ var challenge = defineCommand2({
6115
6590
  const client = createClient(globalOpts);
6116
6591
  const result = await client.auth.getChallenge();
6117
6592
  outputResult(result, { json: args.json });
6118
- });
6593
+ }, { json: Boolean(args.json) });
6119
6594
  }
6120
6595
  });
6121
6596
  var login = defineCommand2({
@@ -6172,13 +6647,27 @@ var login = defineCommand2({
6172
6647
  if (args.env && args.env !== config.environment) {
6173
6648
  saveConfig({ ...config, environment: session.environment });
6174
6649
  }
6650
+ if (args.token) {
6651
+ const prev = { ...loadCredentials() ?? {} };
6652
+ delete prev.tokenReferenceNumber;
6653
+ let ref;
6654
+ try {
6655
+ ref = await client.tokens.findSelfReferenceNumber(session.accessToken);
6656
+ } catch {
6657
+ }
6658
+ saveCredentials({
6659
+ ...prev,
6660
+ token: args.token,
6661
+ ...ref ? { tokenReferenceNumber: ref } : {}
6662
+ });
6663
+ }
6175
6664
  if (args.json) {
6176
6665
  console.log(JSON.stringify({ status: "ok", clientIp: loginResult.clientIp }, null, 2));
6177
6666
  } else {
6178
6667
  consola6.info(`Seen client IP: ${loginResult.clientIp}`);
6179
6668
  outputSuccess("Logged in successfully.");
6180
6669
  }
6181
- });
6670
+ }, { json: Boolean(args.json) });
6182
6671
  }
6183
6672
  });
6184
6673
  var status = defineCommand2({
@@ -6196,7 +6685,7 @@ var status = defineCommand2({
6196
6685
  const { client, session } = await requireSession(globalOpts);
6197
6686
  const result = await client.auth.getAuthStatus(args.ref, session.accessToken);
6198
6687
  outputResult(result, { json: args.json });
6199
- });
6688
+ }, { json: Boolean(args.json) });
6200
6689
  }
6201
6690
  });
6202
6691
  var logout = defineCommand2({
@@ -6208,6 +6697,102 @@ var logout = defineCommand2({
6208
6697
  });
6209
6698
  }
6210
6699
  });
6700
+ var revokeSelfToken = defineCommand2({
6701
+ meta: {
6702
+ name: "revoke-self-token",
6703
+ description: "Revoke the token currently used for authentication. Reference number is resolved via discovery first (JWT payload, then a filtered active-token list), falling back to local cache only if discovery fails; revocation is idempotent (404/409/410 treated as already-revoked)."
6704
+ },
6705
+ args: {
6706
+ "keep-local": { type: "boolean", description: "Revoke server-side but keep local session" },
6707
+ "dry-run": { type: "boolean", description: "Print what would happen without revoking the token (discovery may still query the API)" },
6708
+ env: { type: "string", description: "Environment (test/demo/prod)" },
6709
+ json: { type: "boolean", description: "Output as JSON" },
6710
+ verbose: { type: "boolean", description: "Show HTTP request/response details" },
6711
+ timeout: { type: "string", description: "Request timeout (ms)" }
6712
+ },
6713
+ run({ args }) {
6714
+ return withErrorHandler(async () => {
6715
+ const globalOpts = getGlobalOpts(args);
6716
+ const { client, session } = await requireSession(globalOpts);
6717
+ if (args.env && args.env !== session.environment) {
6718
+ throw new Error(
6719
+ `Current session is '${session.environment}', but --env='${args.env}'. Refusing to revoke a token from a different environment.`
6720
+ );
6721
+ }
6722
+ let discoveredRef;
6723
+ try {
6724
+ discoveredRef = await client.tokens.findSelfReferenceNumber(session.accessToken);
6725
+ } catch {
6726
+ discoveredRef = void 0;
6727
+ }
6728
+ const cachedRef = discoveredRef ? void 0 : loadCredentials()?.tokenReferenceNumber;
6729
+ const ref = discoveredRef ?? cachedRef;
6730
+ const source = discoveredRef ? "discovery" : cachedRef ? "cache-fallback" : "none";
6731
+ if (args["dry-run"]) {
6732
+ if (args.json) {
6733
+ outputResult(
6734
+ {
6735
+ status: "dry-run",
6736
+ referenceNumber: ref ?? null,
6737
+ source,
6738
+ wouldClearLocal: !args["keep-local"]
6739
+ },
6740
+ { json: true }
6741
+ );
6742
+ return;
6743
+ }
6744
+ if (source === "cache-fallback") {
6745
+ outputWarning(
6746
+ "Using cached reference (discovery failed). Verify this is the token you intend to revoke."
6747
+ );
6748
+ }
6749
+ outputKeyValue(
6750
+ {
6751
+ "Would revoke": ref ?? "(unknown \u2014 discovery failed)",
6752
+ Source: source,
6753
+ "Would clear local": args["keep-local"] ? "no" : "yes"
6754
+ },
6755
+ { json: false }
6756
+ );
6757
+ return;
6758
+ }
6759
+ if (source === "cache-fallback" && !args.json) {
6760
+ outputWarning(
6761
+ "Using cached reference (discovery failed). Verify this is the token you intend to revoke."
6762
+ );
6763
+ }
6764
+ const { referenceNumber, alreadyRevoked } = await client.tokens.revokeSelf({
6765
+ referenceNumber: ref,
6766
+ accessToken: session.accessToken
6767
+ });
6768
+ const localCleared = !args["keep-local"];
6769
+ if (localCleared) {
6770
+ clearSession();
6771
+ clearCredentials();
6772
+ }
6773
+ if (args.json) {
6774
+ outputResult(
6775
+ {
6776
+ status: alreadyRevoked ? "already-revoked" : "revoked",
6777
+ referenceNumber,
6778
+ source,
6779
+ localCleared
6780
+ },
6781
+ { json: true }
6782
+ );
6783
+ } else {
6784
+ if (alreadyRevoked) {
6785
+ outputWarning(`Token ${referenceNumber} was already revoked on the server.`);
6786
+ } else {
6787
+ outputSuccess(`Token ${referenceNumber} revoked.`);
6788
+ }
6789
+ if (localCleared) {
6790
+ outputSuccess("Local session and credentials cleared.");
6791
+ }
6792
+ }
6793
+ }, { json: Boolean(args.json) });
6794
+ }
6795
+ });
6211
6796
  var refresh = defineCommand2({
6212
6797
  meta: { name: "refresh", description: "Refresh the access token" },
6213
6798
  args: {
@@ -6232,7 +6817,7 @@ var refresh = defineCommand2({
6232
6817
  session.expiresAt = result.accessToken.validUntil;
6233
6818
  saveSession(session);
6234
6819
  outputSuccess("Token refreshed successfully.");
6235
- });
6820
+ }, { json: Boolean(args.json) });
6236
6821
  }
6237
6822
  });
6238
6823
  var whoami = defineCommand2({
@@ -6283,7 +6868,7 @@ var whoami = defineCommand2({
6283
6868
  info.context = context2;
6284
6869
  }
6285
6870
  outputKeyValue(info, { json: args.json });
6286
- });
6871
+ }, { json: Boolean(args.json) });
6287
6872
  }
6288
6873
  });
6289
6874
  var loginExternal = defineCommand2({
@@ -6377,12 +6962,21 @@ var loginExternal = defineCommand2({
6377
6962
  clearPendingChallenge();
6378
6963
  outputSuccess("Logged in successfully via external signature.");
6379
6964
  }
6380
- });
6965
+ }, { json: Boolean(args.json) });
6381
6966
  }
6382
6967
  });
6383
6968
  var authCommand = defineCommand2({
6384
6969
  meta: { name: "auth", description: "Authentication commands" },
6385
- subCommands: { challenge, login, "login-external": loginExternal, status, logout, refresh, whoami }
6970
+ subCommands: {
6971
+ challenge,
6972
+ login,
6973
+ "login-external": loginExternal,
6974
+ status,
6975
+ logout,
6976
+ "revoke-self-token": revokeSelfToken,
6977
+ refresh,
6978
+ whoami
6979
+ }
6386
6980
  });
6387
6981
 
6388
6982
  // src/cli/commands/session.ts
@@ -6451,7 +7045,7 @@ var open = defineCommand3({
6451
7045
  "Valid Until": result.validUntil
6452
7046
  }, { json: false });
6453
7047
  }
6454
- });
7048
+ }, { json: Boolean(args.json) });
6455
7049
  }
6456
7050
  });
6457
7051
  var close = defineCommand3({
@@ -6475,7 +7069,7 @@ var close = defineCommand3({
6475
7069
  await client.onlineSession.closeSession(ref);
6476
7070
  clearOnlineSessionRef();
6477
7071
  outputSuccess(`Session ${ref} closed.`);
6478
- });
7072
+ }, { json: Boolean(args.json) });
6479
7073
  }
6480
7074
  });
6481
7075
  var status2 = defineCommand3({
@@ -6509,7 +7103,7 @@ var status2 = defineCommand3({
6509
7103
  "Failed": result.failedInvoiceCount ?? 0
6510
7104
  }, { json: false });
6511
7105
  }
6512
- });
7106
+ }, { json: Boolean(args.json) });
6513
7107
  }
6514
7108
  });
6515
7109
  var list = defineCommand3({
@@ -6561,7 +7155,7 @@ var list = defineCommand3({
6561
7155
  if (result.continuationToken) {
6562
7156
  consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
6563
7157
  }
6564
- });
7158
+ }, { json: Boolean(args.json) });
6565
7159
  }
6566
7160
  });
6567
7161
  var invoices = defineCommand3({
@@ -6612,7 +7206,7 @@ var invoices = defineCommand3({
6612
7206
  if (result.continuationToken) {
6613
7207
  consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
6614
7208
  }
6615
- });
7209
+ }, { json: Boolean(args.json) });
6616
7210
  }
6617
7211
  });
6618
7212
  var failed = defineCommand3({
@@ -6663,7 +7257,7 @@ var failed = defineCommand3({
6663
7257
  if (result.continuationToken) {
6664
7258
  consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
6665
7259
  }
6666
- });
7260
+ }, { json: Boolean(args.json) });
6667
7261
  }
6668
7262
  });
6669
7263
  var upo = defineCommand3({
@@ -6716,7 +7310,7 @@ var upo = defineCommand3({
6716
7310
  } else {
6717
7311
  console.log(result.upo);
6718
7312
  }
6719
- });
7313
+ }, { json: Boolean(args.json) });
6720
7314
  }
6721
7315
  });
6722
7316
  var active = defineCommand3({
@@ -6762,7 +7356,7 @@ var active = defineCommand3({
6762
7356
  if (result.continuationToken) {
6763
7357
  consola7.info(`More results available. Continuation token: ${result.continuationToken}`);
6764
7358
  }
6765
- });
7359
+ }, { json: Boolean(args.json) });
6766
7360
  }
6767
7361
  });
6768
7362
  var revoke = defineCommand3({
@@ -6796,7 +7390,7 @@ var revoke = defineCommand3({
6796
7390
  } else {
6797
7391
  throw new Error("Provide a session reference or use --current to revoke the current session.");
6798
7392
  }
6799
- });
7393
+ }, { json: Boolean(args.json) });
6800
7394
  }
6801
7395
  });
6802
7396
  var invoice = defineCommand3({
@@ -6832,7 +7426,7 @@ var invoice = defineCommand3({
6832
7426
  "Invoicing Mode": result.invoicingMode ?? "N/A"
6833
7427
  }, { json: false });
6834
7428
  }
6835
- });
7429
+ }, { json: Boolean(args.json) });
6836
7430
  }
6837
7431
  });
6838
7432
  var sessionCommand = defineCommand3({
@@ -7122,7 +7716,7 @@ var exportIncremental = defineCommand4({
7122
7716
  consola8.info(`Final HWM: ${continuationPoints[subjectType] ?? "complete"}`);
7123
7717
  consola8.info(`Output: ${outputDir}`);
7124
7718
  }
7125
- });
7719
+ }, { json: Boolean(args.json) });
7126
7720
  }
7127
7721
  });
7128
7722
 
@@ -7354,7 +7948,7 @@ var send = defineCommand5({
7354
7948
  outputSuccess(`Invoice sent. Ref: ${result.referenceNumber}`);
7355
7949
  }
7356
7950
  }
7357
- });
7951
+ }, { json: Boolean(args.json) });
7358
7952
  }
7359
7953
  });
7360
7954
  var get = defineCommand5({
@@ -7382,7 +7976,7 @@ var get = defineCommand5({
7382
7976
  } else {
7383
7977
  console.log(xml);
7384
7978
  }
7385
- });
7979
+ }, { json: Boolean(args.json) });
7386
7980
  }
7387
7981
  });
7388
7982
  var query = defineCommand5({
@@ -7439,7 +8033,7 @@ var query = defineCommand5({
7439
8033
  if (result.hasMore) {
7440
8034
  consola9.info("More results available. Use --page to fetch the next page.");
7441
8035
  }
7442
- });
8036
+ }, { json: Boolean(args.json) });
7443
8037
  }
7444
8038
  });
7445
8039
  var exportCmd = defineCommand5({
@@ -7470,7 +8064,7 @@ var exportCmd = defineCommand5({
7470
8064
  outputSuccess(`Export started. Ref: ${result.referenceNumber}`);
7471
8065
  consola9.info("Check status with: ksef invoice export-status " + result.referenceNumber);
7472
8066
  }
7473
- });
8067
+ }, { json: Boolean(args.json) });
7474
8068
  }
7475
8069
  });
7476
8070
  var exportStatus = defineCommand5({
@@ -7520,7 +8114,7 @@ var exportStatus = defineCommand5({
7520
8114
  );
7521
8115
  }
7522
8116
  }
7523
- });
8117
+ }, { json: Boolean(args.json) });
7524
8118
  }
7525
8119
  });
7526
8120
  var VALID_SCHEMA_TYPES = SCHEMA_TYPES;
@@ -7590,7 +8184,7 @@ var validateCmd = defineCommand5({
7590
8184
  if (invalidCount > 0) {
7591
8185
  process.exitCode = 1;
7592
8186
  }
7593
- });
8187
+ }, { json: Boolean(args.json) });
7594
8188
  }
7595
8189
  });
7596
8190
  var invoiceCommand = defineCommand5({
@@ -7600,6 +8194,7 @@ var invoiceCommand = defineCommand5({
7600
8194
 
7601
8195
  // src/cli/commands/permission.ts
7602
8196
  import { defineCommand as defineCommand6 } from "citty";
8197
+ init_ksef_validation_error();
7603
8198
  function getGlobalOpts5(args) {
7604
8199
  return {
7605
8200
  env: args.env,
@@ -7788,7 +8383,7 @@ var grant = defineCommand6({
7788
8383
  } else {
7789
8384
  outputSuccess(`Permission granted. Ref: ${result.referenceNumber}`);
7790
8385
  }
7791
- });
8386
+ }, { json: Boolean(args.json) });
7792
8387
  }
7793
8388
  });
7794
8389
  var revoke2 = defineCommand6({
@@ -7817,7 +8412,7 @@ var revoke2 = defineCommand6({
7817
8412
  } else {
7818
8413
  outputSuccess(`Permission grant ${args.grantId} revoked. Ref: ${result.referenceNumber}`);
7819
8414
  }
7820
- });
8415
+ }, { json: Boolean(args.json) });
7821
8416
  }
7822
8417
  });
7823
8418
  var search = defineCommand6({
@@ -7827,6 +8422,8 @@ var search = defineCommand6({
7827
8422
  identifier: { type: "string", description: "Subject identifier value" },
7828
8423
  identifierType: { type: "string", description: "Subject identifier type" },
7829
8424
  queryType: { type: "string", description: "Query type (e.g. PermissionsInCurrentContext, Granted)" },
8425
+ contextType: { type: "string", description: "Context identifier type: Nip | InternalId (for --type personal and --type entities-grants)" },
8426
+ contextValue: { type: "string", description: "Context identifier value (NIP or 10-16 char InternalId)" },
7830
8427
  page: { type: "string", description: "Page offset (default: 0)" },
7831
8428
  pageSize: { type: "string", description: "Page size" },
7832
8429
  env: { type: "string", description: "Environment (test/demo/prod)" },
@@ -7841,9 +8438,33 @@ var search = defineCommand6({
7841
8438
  const { client } = await requireSession(globalOpts);
7842
8439
  const page = args.page ? parseInt(args.page, 10) : void 0;
7843
8440
  const pageSize = args.pageSize ? parseInt(args.pageSize, 10) : void 0;
8441
+ const resolveContextBody = () => {
8442
+ const hasType = Boolean(args.contextType);
8443
+ const hasValue = Boolean(args.contextValue);
8444
+ if (hasType !== hasValue) {
8445
+ throw KSeFValidationError.fromField(
8446
+ hasType ? "--context-value" : "--context-type",
8447
+ "--context-type and --context-value must be provided together."
8448
+ );
8449
+ }
8450
+ if (!hasType) return {};
8451
+ if (args.contextType !== "Nip" && args.contextType !== "InternalId") {
8452
+ throw KSeFValidationError.fromField(
8453
+ "--context-type",
8454
+ `--context-type must be "Nip" or "InternalId", got "${args.contextType}".`
8455
+ );
8456
+ }
8457
+ return {
8458
+ contextIdentifier: {
8459
+ type: args.contextType,
8460
+ value: args.contextValue
8461
+ }
8462
+ };
8463
+ };
7844
8464
  switch (args.type) {
7845
8465
  case "personal": {
7846
- const response = await client.permissions.queryPersonalGrants({}, page, pageSize);
8466
+ const body = resolveContextBody();
8467
+ const response = await client.permissions.queryPersonalGrants(body, page, pageSize);
7847
8468
  if (args.json) {
7848
8469
  outputResult(response, { json: true });
7849
8470
  return;
@@ -7949,7 +8570,8 @@ var search = defineCommand6({
7949
8570
  break;
7950
8571
  }
7951
8572
  case "entities-grants": {
7952
- const response = await client.permissions.queryEntitiesGrants({}, page, pageSize);
8573
+ const body = resolveContextBody();
8574
+ const response = await client.permissions.queryEntitiesGrants(body, page, pageSize);
7953
8575
  if (args.json) {
7954
8576
  outputResult(response, { json: true });
7955
8577
  return;
@@ -8056,7 +8678,7 @@ var search = defineCommand6({
8056
8678
  default:
8057
8679
  throw new Error(`Unknown search type: ${args.type}. Use: personal, persons, subunits, entities, entities-grants, subordinate-entities, authorizations, eu-entities`);
8058
8680
  }
8059
- });
8681
+ }, { json: Boolean(args.json) });
8060
8682
  }
8061
8683
  });
8062
8684
  var status3 = defineCommand6({
@@ -8082,7 +8704,7 @@ var status3 = defineCommand6({
8082
8704
  "Status Description": result.status.description
8083
8705
  }, { json: false });
8084
8706
  }
8085
- });
8707
+ }, { json: Boolean(args.json) });
8086
8708
  }
8087
8709
  });
8088
8710
  var attachmentStatus = defineCommand6({
@@ -8106,7 +8728,7 @@ var attachmentStatus = defineCommand6({
8106
8728
  "Attachments": result.isAttachmentAllowed ? "Allowed" : "Not Allowed"
8107
8729
  }, { json: false });
8108
8730
  }
8109
- });
8731
+ }, { json: Boolean(args.json) });
8110
8732
  }
8111
8733
  });
8112
8734
  var permissionCommand = defineCommand6({
@@ -8159,7 +8781,7 @@ var generate = defineCommand7({
8159
8781
  "Token": result.token
8160
8782
  }, { json: false });
8161
8783
  }
8162
- });
8784
+ }, { json: Boolean(args.json) });
8163
8785
  }
8164
8786
  });
8165
8787
  var list2 = defineCommand7({
@@ -8218,7 +8840,7 @@ var list2 = defineCommand7({
8218
8840
  if (result.continuationToken) {
8219
8841
  consola10.info(`More results available. Continuation token: ${result.continuationToken}`);
8220
8842
  }
8221
- });
8843
+ }, { json: Boolean(args.json) });
8222
8844
  }
8223
8845
  });
8224
8846
  var get2 = defineCommand7({
@@ -8251,7 +8873,7 @@ var get2 = defineCommand7({
8251
8873
  "Last Used": result.lastUseDate ?? "Never"
8252
8874
  }, { json: false });
8253
8875
  }
8254
- });
8876
+ }, { json: Boolean(args.json) });
8255
8877
  }
8256
8878
  });
8257
8879
  var revoke3 = defineCommand7({
@@ -8275,7 +8897,7 @@ var revoke3 = defineCommand7({
8275
8897
  } else {
8276
8898
  outputSuccess(`Token ${ref} revoked.`);
8277
8899
  }
8278
- });
8900
+ }, { json: Boolean(args.json) });
8279
8901
  }
8280
8902
  });
8281
8903
  var tokenCommand = defineCommand7({
@@ -8458,7 +9080,7 @@ var generate2 = defineCommand8({
8458
9080
  "Private Key": keyPath
8459
9081
  }, { json: false });
8460
9082
  }
8461
- });
9083
+ }, { json: Boolean(args.json) });
8462
9084
  }
8463
9085
  });
8464
9086
  var enroll = defineCommand8({
@@ -8496,7 +9118,7 @@ var enroll = defineCommand8({
8496
9118
  "Timestamp": result.timestamp
8497
9119
  }, { json: false });
8498
9120
  }
8499
- });
9121
+ }, { json: Boolean(args.json) });
8500
9122
  }
8501
9123
  });
8502
9124
  var status4 = defineCommand8({
@@ -8528,7 +9150,7 @@ var status4 = defineCommand8({
8528
9150
  }
8529
9151
  outputKeyValue(kv, { json: false });
8530
9152
  }
8531
- });
9153
+ }, { json: Boolean(args.json) });
8532
9154
  }
8533
9155
  });
8534
9156
  var list3 = defineCommand8({
@@ -8591,7 +9213,7 @@ var list3 = defineCommand8({
8591
9213
  if (result.hasMore) {
8592
9214
  consola11.info("More results available. Use --page to paginate.");
8593
9215
  }
8594
- });
9216
+ }, { json: Boolean(args.json) });
8595
9217
  }
8596
9218
  });
8597
9219
  var revoke4 = defineCommand8({
@@ -8618,7 +9240,7 @@ var revoke4 = defineCommand8({
8618
9240
  } else {
8619
9241
  outputSuccess(`Certificate ${serial} revoked.`);
8620
9242
  }
8621
- });
9243
+ }, { json: Boolean(args.json) });
8622
9244
  }
8623
9245
  });
8624
9246
  var limits = defineCommand8({
@@ -8646,7 +9268,7 @@ var limits = defineCommand8({
8646
9268
  "Certificate Remaining": result.certificate.remaining
8647
9269
  }, { json: false });
8648
9270
  }
8649
- });
9271
+ }, { json: Boolean(args.json) });
8650
9272
  }
8651
9273
  });
8652
9274
  var enrollmentData = defineCommand8({
@@ -8677,7 +9299,7 @@ var enrollmentData = defineCommand8({
8677
9299
  if (result.organizationIdentifier) kv["Organization ID"] = result.organizationIdentifier;
8678
9300
  outputKeyValue(kv, { json: false });
8679
9301
  }
8680
- });
9302
+ }, { json: Boolean(args.json) });
8681
9303
  }
8682
9304
  });
8683
9305
  var retrieve = defineCommand8({
@@ -8720,7 +9342,7 @@ var retrieve = defineCommand8({
8720
9342
  ],
8721
9343
  { json: false }
8722
9344
  );
8723
- });
9345
+ }, { json: Boolean(args.json) });
8724
9346
  }
8725
9347
  });
8726
9348
  var certCommand = defineCommand8({
@@ -8849,7 +9471,7 @@ URL: ${url2}`);
8849
9471
  console.log(buffer.toString("base64"));
8850
9472
  }
8851
9473
  }
8852
- });
9474
+ }, { json: Boolean(args.json) });
8853
9475
  }
8854
9476
  });
8855
9477
  var certificate = defineCommand9({
@@ -8910,7 +9532,7 @@ URL: ${url2}`);
8910
9532
  console.log(buffer.toString("base64"));
8911
9533
  }
8912
9534
  }
8913
- });
9535
+ }, { json: Boolean(args.json) });
8914
9536
  }
8915
9537
  });
8916
9538
  var url = defineCommand9({
@@ -8934,7 +9556,7 @@ var url = defineCommand9({
8934
9556
  } else {
8935
9557
  console.log(verificationUrl);
8936
9558
  }
8937
- });
9559
+ }, { json: Boolean(args.json) });
8938
9560
  }
8939
9561
  });
8940
9562
  var qrCommand = defineCommand9({
@@ -8978,7 +9600,7 @@ var status5 = defineCommand10({
8978
9600
  "Timestamp": result.timestamp
8979
9601
  }, { json: false });
8980
9602
  }
8981
- });
9603
+ }, { json: Boolean(args.json) });
8982
9604
  }
8983
9605
  });
8984
9606
  var messages = defineCommand10({
@@ -9020,7 +9642,7 @@ var messages = defineCommand10({
9020
9642
  ],
9021
9643
  { json: false }
9022
9644
  );
9023
- });
9645
+ }, { json: Boolean(args.json) });
9024
9646
  }
9025
9647
  });
9026
9648
  var lighthouseCommand = defineCommand10({
@@ -9076,7 +9698,7 @@ var createSubject = defineCommand11({
9076
9698
  };
9077
9699
  await createClient(globalOpts).testData.createSubject(request);
9078
9700
  outputDone(args.json);
9079
- });
9701
+ }, { json: Boolean(args.json) });
9080
9702
  }
9081
9703
  });
9082
9704
  var removeSubject = defineCommand11({
@@ -9095,7 +9717,7 @@ var removeSubject = defineCommand11({
9095
9717
  const request = { subjectNip: args.nip };
9096
9718
  await createClient(globalOpts).testData.removeSubject(request);
9097
9719
  outputDone(args.json);
9098
- });
9720
+ }, { json: Boolean(args.json) });
9099
9721
  }
9100
9722
  });
9101
9723
  var createPerson = defineCommand11({
@@ -9126,7 +9748,7 @@ var createPerson = defineCommand11({
9126
9748
  };
9127
9749
  await createClient(globalOpts).testData.createPerson(request);
9128
9750
  outputDone(args.json);
9129
- });
9751
+ }, { json: Boolean(args.json) });
9130
9752
  }
9131
9753
  });
9132
9754
  var removePerson = defineCommand11({
@@ -9145,7 +9767,7 @@ var removePerson = defineCommand11({
9145
9767
  const request = { nip: args.nip };
9146
9768
  await createClient(globalOpts).testData.removePerson(request);
9147
9769
  outputDone(args.json);
9148
- });
9770
+ }, { json: Boolean(args.json) });
9149
9771
  }
9150
9772
  });
9151
9773
  var grantPermissions = defineCommand11({
@@ -9176,7 +9798,7 @@ var grantPermissions = defineCommand11({
9176
9798
  };
9177
9799
  await createClient(globalOpts).testData.grantPermissions(request);
9178
9800
  outputDone(args.json);
9179
- });
9801
+ }, { json: Boolean(args.json) });
9180
9802
  }
9181
9803
  });
9182
9804
  var revokePermissions = defineCommand11({
@@ -9204,7 +9826,7 @@ var revokePermissions = defineCommand11({
9204
9826
  };
9205
9827
  await createClient(globalOpts).testData.revokePermissions(request);
9206
9828
  outputDone(args.json);
9207
- });
9829
+ }, { json: Boolean(args.json) });
9208
9830
  }
9209
9831
  });
9210
9832
  var enableAttachment = defineCommand11({
@@ -9223,7 +9845,7 @@ var enableAttachment = defineCommand11({
9223
9845
  const request = { nip: args.nip };
9224
9846
  await createClient(globalOpts).testData.enableAttachment(request);
9225
9847
  outputDone(args.json);
9226
- });
9848
+ }, { json: Boolean(args.json) });
9227
9849
  }
9228
9850
  });
9229
9851
  var disableAttachment = defineCommand11({
@@ -9246,7 +9868,7 @@ var disableAttachment = defineCommand11({
9246
9868
  };
9247
9869
  await createClient(globalOpts).testData.disableAttachment(request);
9248
9870
  outputDone(args.json);
9249
- });
9871
+ }, { json: Boolean(args.json) });
9250
9872
  }
9251
9873
  });
9252
9874
  var changeSessionLimits = defineCommand11({
@@ -9283,7 +9905,7 @@ var changeSessionLimits = defineCommand11({
9283
9905
  };
9284
9906
  await client.testData.changeSessionLimits(request);
9285
9907
  outputDone(args.json);
9286
- });
9908
+ }, { json: Boolean(args.json) });
9287
9909
  }
9288
9910
  });
9289
9911
  var restoreSessionLimits = defineCommand11({
@@ -9302,7 +9924,7 @@ var restoreSessionLimits = defineCommand11({
9302
9924
  const { client } = await requireSession(globalOpts);
9303
9925
  await client.testData.restoreDefaultSessionLimits();
9304
9926
  outputDone(args.json);
9305
- });
9927
+ }, { json: Boolean(args.json) });
9306
9928
  }
9307
9929
  });
9308
9930
  var changeCertLimits = defineCommand11({
@@ -9329,7 +9951,7 @@ var changeCertLimits = defineCommand11({
9329
9951
  };
9330
9952
  await client.testData.changeCertificatesLimit(request);
9331
9953
  outputDone(args.json);
9332
- });
9954
+ }, { json: Boolean(args.json) });
9333
9955
  }
9334
9956
  });
9335
9957
  var restoreCertLimits = defineCommand11({
@@ -9348,7 +9970,7 @@ var restoreCertLimits = defineCommand11({
9348
9970
  const { client } = await requireSession(globalOpts);
9349
9971
  await client.testData.restoreDefaultCertificatesLimit();
9350
9972
  outputDone(args.json);
9351
- });
9973
+ }, { json: Boolean(args.json) });
9352
9974
  }
9353
9975
  });
9354
9976
  var setRateLimits = defineCommand11({
@@ -9371,7 +9993,7 @@ var setRateLimits = defineCommand11({
9371
9993
  };
9372
9994
  await client.testData.setRateLimits(request);
9373
9995
  outputDone(args.json);
9374
- });
9996
+ }, { json: Boolean(args.json) });
9375
9997
  }
9376
9998
  });
9377
9999
  var restoreRateLimits = defineCommand11({
@@ -9390,7 +10012,7 @@ var restoreRateLimits = defineCommand11({
9390
10012
  const { client } = await requireSession(globalOpts);
9391
10013
  await client.testData.restoreDefaultRateLimits();
9392
10014
  outputDone(args.json);
9393
- });
10015
+ }, { json: Boolean(args.json) });
9394
10016
  }
9395
10017
  });
9396
10018
  var setProductionRateLimits = defineCommand11({
@@ -9409,7 +10031,7 @@ var setProductionRateLimits = defineCommand11({
9409
10031
  const { client } = await requireSession(globalOpts);
9410
10032
  await client.testData.setProductionRateLimits();
9411
10033
  outputDone(args.json);
9412
- });
10034
+ }, { json: Boolean(args.json) });
9413
10035
  }
9414
10036
  });
9415
10037
  var blockContext = defineCommand11({
@@ -9436,7 +10058,7 @@ var blockContext = defineCommand11({
9436
10058
  };
9437
10059
  await client.testData.blockContext(request);
9438
10060
  outputDone(args.json);
9439
- });
10061
+ }, { json: Boolean(args.json) });
9440
10062
  }
9441
10063
  });
9442
10064
  var unblockContext = defineCommand11({
@@ -9463,7 +10085,7 @@ var unblockContext = defineCommand11({
9463
10085
  };
9464
10086
  await client.testData.unblockContext(request);
9465
10087
  outputDone(args.json);
9466
- });
10088
+ }, { json: Boolean(args.json) });
9467
10089
  }
9468
10090
  });
9469
10091
  var testDataCommand = defineCommand11({
@@ -9525,7 +10147,7 @@ var context = defineCommand12({
9525
10147
  "Batch \u2014 Max Invoices": result.batchSession.maxInvoices
9526
10148
  }, { json: false });
9527
10149
  }
9528
- });
10150
+ }, { json: Boolean(args.json) });
9529
10151
  }
9530
10152
  });
9531
10153
  var subject = defineCommand12({
@@ -9549,7 +10171,7 @@ var subject = defineCommand12({
9549
10171
  "Max Certificates": result.certificate?.maxCertificates ?? "Unlimited"
9550
10172
  }, { json: false });
9551
10173
  }
9552
- });
10174
+ }, { json: Boolean(args.json) });
9553
10175
  }
9554
10176
  });
9555
10177
  var rate = defineCommand12({
@@ -9585,7 +10207,7 @@ var rate = defineCommand12({
9585
10207
  ],
9586
10208
  { json: false }
9587
10209
  );
9588
- });
10210
+ }, { json: Boolean(args.json) });
9589
10211
  }
9590
10212
  });
9591
10213
  var limitsCommand = defineCommand12({
@@ -9646,7 +10268,7 @@ var providers = defineCommand13({
9646
10268
  if (result.hasMore) {
9647
10269
  consola12.info("More results available. Use --page to paginate.");
9648
10270
  }
9649
- });
10271
+ }, { json: Boolean(args.json) });
9650
10272
  }
9651
10273
  });
9652
10274
  var peppolCommand = defineCommand13({
@@ -9757,7 +10379,7 @@ ${passed}/${total} checks passed.`);
9757
10379
  consola13.warn(`
9758
10380
  ${passed}/${total} checks passed.`);
9759
10381
  }
9760
- });
10382
+ }, { json: Boolean(args.json) });
9761
10383
  }
9762
10384
  });
9763
10385
 
@@ -10142,7 +10764,7 @@ var setupCommand = defineCommand16({
10142
10764
  " ksef session open \u2014 Open an online session",
10143
10765
  " ksef auth whoami \u2014 Check current session"
10144
10766
  ].join("\n"));
10145
- });
10767
+ }, { json: Boolean(args.json) });
10146
10768
  }
10147
10769
  });
10148
10770
 
@@ -10380,7 +11002,7 @@ var generate3 = defineCommand17({
10380
11002
  "KOD II": metadata.kod2Url ?? "(not generated)"
10381
11003
  }, { json: false });
10382
11004
  }
10383
- });
11005
+ }, { json: Boolean(args.json) });
10384
11006
  }
10385
11007
  });
10386
11008
  var list4 = defineCommand17({
@@ -10429,7 +11051,7 @@ var list4 = defineCommand17({
10429
11051
  ],
10430
11052
  { json: args.json }
10431
11053
  );
10432
- });
11054
+ }, { json: Boolean(args.json) });
10433
11055
  }
10434
11056
  });
10435
11057
  var status6 = defineCommand17({
@@ -10465,7 +11087,7 @@ var status6 = defineCommand17({
10465
11087
  Error: invoice3.error ? `${invoice3.error.code}: ${invoice3.error.message}` : "-"
10466
11088
  }, { json: false });
10467
11089
  }
10468
- });
11090
+ }, { json: Boolean(args.json) });
10469
11091
  }
10470
11092
  });
10471
11093
  var submit = defineCommand17({
@@ -10521,7 +11143,7 @@ var submit = defineCommand17({
10521
11143
  );
10522
11144
  }
10523
11145
  }
10524
- });
11146
+ }, { json: Boolean(args.json) });
10525
11147
  }
10526
11148
  });
10527
11149
  var correct = defineCommand17({
@@ -10551,7 +11173,7 @@ var correct = defineCommand17({
10551
11173
  } else {
10552
11174
  outputSuccess(`Correction submitted. KSeF ref: ${result.ksefReferenceNumber ?? "pending"}`);
10553
11175
  }
10554
- });
11176
+ }, { json: Boolean(args.json) });
10555
11177
  }
10556
11178
  });
10557
11179
  var del = defineCommand17({
@@ -10601,7 +11223,7 @@ var del = defineCommand17({
10601
11223
  }
10602
11224
  await storage.delete(args.id);
10603
11225
  outputSuccess(`Deleted offline invoice ${args.id}`);
10604
- });
11226
+ }, { json: Boolean(args.json) });
10605
11227
  }
10606
11228
  });
10607
11229
  var offlineCommand = defineCommand17({