ksef-client-ts 0.9.0 → 0.10.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/index.cjs CHANGED
@@ -30,13 +30,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // node_modules/tsup/assets/cjs_shims.js
34
- var getImportMetaUrl, importMetaUrl;
33
+ // ../../node_modules/tsup/assets/cjs_shims.js
35
34
  var init_cjs_shims = __esm({
36
- "node_modules/tsup/assets/cjs_shims.js"() {
35
+ "../../node_modules/tsup/assets/cjs_shims.js"() {
37
36
  "use strict";
38
- getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
- importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
37
  }
41
38
  });
42
39
 
@@ -401,6 +398,25 @@ var init_ksef_validation_error = __esm({
401
398
  }
402
399
  });
403
400
 
401
+ // src/errors/ksef-metadata-pagination-error.ts
402
+ var KSeFMetadataPaginationError;
403
+ var init_ksef_metadata_pagination_error = __esm({
404
+ "src/errors/ksef-metadata-pagination-error.ts"() {
405
+ "use strict";
406
+ init_cjs_shims();
407
+ init_ksef_error();
408
+ KSeFMetadataPaginationError = class extends KSeFError {
409
+ /** The boundary date value that failed to advance. */
410
+ boundaryValue;
411
+ constructor(message, boundaryValue) {
412
+ super(message);
413
+ this.name = "KSeFMetadataPaginationError";
414
+ this.boundaryValue = boundaryValue;
415
+ }
416
+ };
417
+ }
418
+ });
419
+
404
420
  // src/errors/error-codes.ts
405
421
  function hasErrorCode(body, code) {
406
422
  return !!body?.exception?.exceptionDetailList?.some((d) => d.exceptionCode === code);
@@ -548,6 +564,7 @@ var init_errors = __esm({
548
564
  init_ksef_auth_status_error();
549
565
  init_ksef_session_expired_error();
550
566
  init_ksef_validation_error();
567
+ init_ksef_metadata_pagination_error();
551
568
  init_ksef_batch_timeout_error();
552
569
  init_ksef_unknown_public_key_error();
553
570
  init_ksef_circuit_open_error();
@@ -590,21 +607,21 @@ var init_rest_request = __esm({
590
607
  _query = [];
591
608
  _presigned = false;
592
609
  _skipAuthRetry = false;
593
- constructor(method, path3) {
610
+ constructor(method, path) {
594
611
  this.method = method;
595
- this.path = path3;
612
+ this.path = path;
596
613
  }
597
- static get(path3) {
598
- return new _RestRequest("GET", path3);
614
+ static get(path) {
615
+ return new _RestRequest("GET", path);
599
616
  }
600
- static post(path3) {
601
- return new _RestRequest("POST", path3);
617
+ static post(path) {
618
+ return new _RestRequest("POST", path);
602
619
  }
603
- static put(path3) {
604
- return new _RestRequest("PUT", path3);
620
+ static put(path) {
621
+ return new _RestRequest("PUT", path);
605
622
  }
606
- static delete(path3) {
607
- return new _RestRequest("DELETE", path3);
623
+ static delete(path) {
624
+ return new _RestRequest("DELETE", path);
608
625
  }
609
626
  body(data) {
610
627
  this._body = data;
@@ -968,13 +985,13 @@ var init_rest_client = __esm({
968
985
  }
969
986
  throw lastError;
970
987
  }
971
- recordCircuitOutcome(path3, status) {
988
+ recordCircuitOutcome(path, status) {
972
989
  if (!this.circuitBreakerPolicy) return;
973
990
  if (status >= 500) {
974
- this.circuitBreakerPolicy.recordFailure(path3);
991
+ this.circuitBreakerPolicy.recordFailure(path);
975
992
  return;
976
993
  }
977
- this.circuitBreakerPolicy.recordSuccess(path3);
994
+ this.circuitBreakerPolicy.recordSuccess(path);
978
995
  }
979
996
  async doRequest(request, url, overrideToken) {
980
997
  const headers = {
@@ -1011,9 +1028,9 @@ var init_rest_client = __esm({
1011
1028
  return response;
1012
1029
  }
1013
1030
  buildUrl(request) {
1014
- const path3 = this.routeBuilder.build(request.path);
1031
+ const path = this.routeBuilder.build(request.path);
1015
1032
  const base = this.options.baseUrl;
1016
- const url = new URL(`${base}${path3}`);
1033
+ const url = new URL(`${base}${path}`);
1017
1034
  const query = request.getQuery();
1018
1035
  for (const [key, value] of query) {
1019
1036
  url.searchParams.append(key, value);
@@ -1569,6 +1586,9 @@ function isValidCertificateName(value) {
1569
1586
  function isValidCertificateFingerprint(value) {
1570
1587
  return CertificateFingerprint.test(value);
1571
1588
  }
1589
+ function isValidCertificateSerialNumber(value) {
1590
+ return CertificateSerialNumber.test(value);
1591
+ }
1572
1592
  function isValidBase64(value) {
1573
1593
  return Base64String.test(value);
1574
1594
  }
@@ -1578,7 +1598,7 @@ function isValidIp4Address(value) {
1578
1598
  function isValidSha256Base64(value) {
1579
1599
  return Sha256Base64.test(value);
1580
1600
  }
1581
- var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, PeppolId, ReferenceNumber, KsefNumber, KsefNumberV35, KsefNumberV36, CertificateName, Pesel, CertificateFingerprint, Base64String, Ip4Address, Ip4Range, Ip4Mask, Sha256Base64, NIP_WEIGHTS, PESEL_WEIGHTS, CRC8_POLY;
1601
+ var NIP_PATTERN_CORE, VAT_UE_PATTERN_CORE, Nip, VatUe, NipVatUe, InternalId, PeppolId, ReferenceNumber, KsefNumber, KsefNumberV35, KsefNumberV36, CertificateName, Pesel, CertificateFingerprint, CertificateSerialNumber, Base64String, Ip4Address, Ip4Range, Ip4Mask, Sha256Base64, NIP_WEIGHTS, PESEL_WEIGHTS, CRC8_POLY;
1582
1602
  var init_patterns = __esm({
1583
1603
  "src/validation/patterns.ts"() {
1584
1604
  "use strict";
@@ -1597,6 +1617,7 @@ var init_patterns = __esm({
1597
1617
  CertificateName = /^[a-zA-Z0-9_\- ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+$/;
1598
1618
  Pesel = /^\d{2}(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|4[1-9]|5[0-2]|6[1-9]|7[0-2]|8[1-9]|9[0-2])\d{7}$/;
1599
1619
  CertificateFingerprint = /^[0-9A-F]{64}$/;
1620
+ CertificateSerialNumber = /^[0-9A-F]{16}$/;
1600
1621
  Base64String = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
1601
1622
  Ip4Address = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
1602
1623
  Ip4Range = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}-((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
@@ -2861,11 +2882,6 @@ var init_schemas = __esm({
2861
2882
  "src/validation/schemas/index.ts"() {
2862
2883
  "use strict";
2863
2884
  init_cjs_shims();
2864
- init_fa3();
2865
- init_fa2();
2866
- init_fa_rr1();
2867
- init_pef3();
2868
- init_pef_kor3();
2869
2885
  NAMESPACE_MAP = {
2870
2886
  "http://crd.gov.pl/wzor/2025/06/25/13775/": "FA3",
2871
2887
  "http://crd.gov.pl/wzor/2023/06/29/12648/": "FA2",
@@ -3121,11 +3137,11 @@ async function validateSchema(xml, options, _parsed) {
3121
3137
  const prefix = rootElement ? `/${rootElement}/` : "/";
3122
3138
  const validationErrors = result.error.issues.map((issue) => {
3123
3139
  const zodPath = issue.path.join("/");
3124
- const path3 = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3140
+ const path = zodPath ? `${prefix}${zodPath}` : rootElement ? `/${rootElement}` : void 0;
3125
3141
  return {
3126
3142
  code: mapZodErrorCode(issue),
3127
3143
  message: issue.message,
3128
- path: path3
3144
+ path
3129
3145
  };
3130
3146
  });
3131
3147
  return { valid: false, schemaType, errors: validationErrors };
@@ -3165,9 +3181,9 @@ function validateBusinessRules(xml, _parsed) {
3165
3181
  collectDateErrors(object, rootElement, errors);
3166
3182
  return { valid: errors.length === 0, schemaType, errors };
3167
3183
  }
3168
- function collectNipPeselErrors(obj, path3, errors) {
3184
+ function collectNipPeselErrors(obj, path, errors) {
3169
3185
  for (const [key, value] of Object.entries(obj)) {
3170
- const currentPath = path3 ? `${path3}/${key}` : key;
3186
+ const currentPath = path ? `${path}/${key}` : key;
3171
3187
  if (key === "NIP" && typeof value === "string") {
3172
3188
  if (!isValidNip(value)) {
3173
3189
  errors.push({
@@ -4053,6 +4069,8 @@ var init_certificates = __esm({
4053
4069
  init_cjs_shims();
4054
4070
  init_rest_request();
4055
4071
  init_routes();
4072
+ init_ksef_validation_error();
4073
+ init_patterns();
4056
4074
  CertificateApiService = class {
4057
4075
  restClient;
4058
4076
  constructor(restClient) {
@@ -4079,6 +4097,14 @@ var init_certificates = __esm({
4079
4097
  return response.body;
4080
4098
  }
4081
4099
  async retrieve(request) {
4100
+ for (const serial of request.certificateSerialNumbers ?? []) {
4101
+ if (!isValidCertificateSerialNumber(serial)) {
4102
+ throw KSeFValidationError.fromField(
4103
+ "certificateSerialNumbers",
4104
+ `Invalid certificate serial number "${serial}": must be exactly 16 uppercase hex characters (^[0-9A-F]{16}$)`
4105
+ );
4106
+ }
4107
+ }
4082
4108
  const req = RestRequest.post(Routes.Certificates.retrieve).body(request);
4083
4109
  const response = await this.restClient.execute(req);
4084
4110
  return response.body;
@@ -4112,20 +4138,20 @@ var init_lighthouse = __esm({
4112
4138
  this.lighthouseUrl = options.lighthouseUrl;
4113
4139
  this.timeout = options.timeout;
4114
4140
  }
4115
- async fetchJson(path3) {
4141
+ async fetchJson(path) {
4116
4142
  if (!this.lighthouseUrl) {
4117
4143
  throw new KSeFError(
4118
4144
  "Lighthouse API is not available for the DEMO environment. Use TEST or PROD instead."
4119
4145
  );
4120
4146
  }
4121
- const response = await fetch(`${this.lighthouseUrl}${path3}`, {
4147
+ const response = await fetch(`${this.lighthouseUrl}${path}`, {
4122
4148
  headers: { Accept: "application/json" },
4123
4149
  signal: AbortSignal.timeout(this.timeout)
4124
4150
  });
4125
4151
  if (!response.ok) {
4126
4152
  const body = await response.text();
4127
4153
  throw new KSeFError(
4128
- `Lighthouse ${path3} failed: HTTP ${response.status} \u2014 ${body}`
4154
+ `Lighthouse ${path} failed: HTTP ${response.status} \u2014 ${body}`
4129
4155
  );
4130
4156
  }
4131
4157
  return await response.json();
@@ -5096,6 +5122,7 @@ var init_verification_link_service = __esm({
5096
5122
  constructor(baseQrUrl) {
5097
5123
  this.baseQrUrl = baseQrUrl;
5098
5124
  }
5125
+ baseQrUrl;
5099
5126
  /**
5100
5127
  * Build invoice verification URL (Code I).
5101
5128
  * Format: {baseQrUrl}/invoice/{NIP}/{DD-MM-YYYY}/{hash_base64url}
@@ -5576,6 +5603,7 @@ var init_offline_invoice_workflow = __esm({
5576
5603
  constructor(qrService) {
5577
5604
  this.qrService = qrService;
5578
5605
  }
5606
+ qrService;
5579
5607
  async generate(input, options) {
5580
5608
  if (!input.invoiceXml || input.invoiceXml.trim().length === 0) {
5581
5609
  throw new Error("invoiceXml must not be empty");
@@ -6069,6 +6097,7 @@ __export(index_exports, {
6069
6097
  CertificateFetcher: () => CertificateFetcher,
6070
6098
  CertificateFingerprint: () => CertificateFingerprint,
6071
6099
  CertificateName: () => CertificateName,
6100
+ CertificateSerialNumber: () => CertificateSerialNumber,
6072
6101
  CertificateService: () => CertificateService,
6073
6102
  CircuitBreakerPolicy: () => CircuitBreakerPolicy,
6074
6103
  CryptographyService: () => CryptographyService,
@@ -6080,11 +6109,8 @@ __export(index_exports, {
6080
6109
  EntityPermissionGrantBuilder: () => EntityPermissionGrantBuilder,
6081
6110
  Environment: () => Environment,
6082
6111
  FAKTURA_NAMESPACE: () => FAKTURA_NAMESPACE,
6083
- FA_XSD_PATHS: () => FA_XSD_PATHS,
6084
6112
  FORM_CODES: () => FORM_CODES,
6085
6113
  FORM_CODE_KEYS: () => FORM_CODE_KEYS,
6086
- FileHwmStore: () => FileHwmStore,
6087
- FileOfflineInvoiceStorage: () => FileOfflineInvoiceStorage,
6088
6114
  INVOICE_TYPES_BY_SYSTEM_CODE: () => INVOICE_TYPES_BY_SYSTEM_CODE,
6089
6115
  InMemoryHwmStore: () => InMemoryHwmStore,
6090
6116
  InMemoryOfflineInvoiceStorage: () => InMemoryOfflineInvoiceStorage,
@@ -6105,6 +6131,7 @@ __export(index_exports, {
6105
6131
  KSeFErrorCode: () => KSeFErrorCode,
6106
6132
  KSeFForbiddenError: () => KSeFForbiddenError,
6107
6133
  KSeFGoneError: () => KSeFGoneError,
6134
+ KSeFMetadataPaginationError: () => KSeFMetadataPaginationError,
6108
6135
  KSeFRateLimitError: () => KSeFRateLimitError,
6109
6136
  KSeFSessionExpiredError: () => KSeFSessionExpiredError,
6110
6137
  KSeFUnauthorizedError: () => KSeFUnauthorizedError,
@@ -6122,7 +6149,6 @@ __export(index_exports, {
6122
6149
  OfflineInvoiceWorkflow: () => OfflineInvoiceWorkflow,
6123
6150
  OnlineSessionService: () => OnlineSessionService,
6124
6151
  PEF_NAMESPACE: () => PEF_NAMESPACE,
6125
- PEF_XSD_PATHS: () => PEF_XSD_PATHS,
6126
6152
  PERMISSION_DESCRIPTION_MAX_LENGTH: () => PERMISSION_DESCRIPTION_MAX_LENGTH,
6127
6153
  PERMISSION_DESCRIPTION_MIN_LENGTH: () => PERMISSION_DESCRIPTION_MIN_LENGTH,
6128
6154
  PeppolId: () => PeppolId,
@@ -6166,6 +6192,7 @@ __export(index_exports, {
6166
6192
  buildXmlFromObject: () => buildXmlFromObject,
6167
6193
  calculateBackoff: () => calculateBackoff,
6168
6194
  calculateOfflineDeadline: () => calculateOfflineDeadline,
6195
+ collectAllInvoiceMetadata: () => collectAllInvoiceMetadata,
6169
6196
  comparePKey: () => comparePKey,
6170
6197
  createTarGz: () => createTarGz,
6171
6198
  createZip: () => createZip,
@@ -6190,7 +6217,6 @@ __export(index_exports, {
6190
6217
  isExpired: () => isExpired,
6191
6218
  isFakturaInput: () => isFakturaInput,
6192
6219
  isFormCodeShape: () => isFormCodeShape,
6193
- isMissingLibxmljsError: () => isMissingLibxmljsError,
6194
6220
  isPefUblDocumentInput: () => isPefUblDocumentInput,
6195
6221
  isPolishHoliday: () => isPolishHoliday,
6196
6222
  isRetryableError: () => isRetryableError,
@@ -6198,6 +6224,7 @@ __export(index_exports, {
6198
6224
  isValidBase64: () => isValidBase64,
6199
6225
  isValidCertificateFingerprint: () => isValidCertificateFingerprint,
6200
6226
  isValidCertificateName: () => isValidCertificateName,
6227
+ isValidCertificateSerialNumber: () => isValidCertificateSerialNumber,
6201
6228
  isValidInternalId: () => isValidInternalId,
6202
6229
  isValidIp4Address: () => isValidIp4Address,
6203
6230
  isValidKsefNumber: () => isValidKsefNumber,
@@ -6210,7 +6237,6 @@ __export(index_exports, {
6210
6237
  isValidReferenceNumber: () => isValidReferenceNumber,
6211
6238
  isValidSha256Base64: () => isValidSha256Base64,
6212
6239
  isValidVatUe: () => isValidVatUe,
6213
- libxmljsAvailable: () => libxmljsAvailable,
6214
6240
  nextBusinessDay: () => nextBusinessDay,
6215
6241
  openOnlineSession: () => openOnlineSession,
6216
6242
  openSendAndClose: () => openSendAndClose,
@@ -6221,8 +6247,8 @@ __export(index_exports, {
6221
6247
  parseUpoXml: () => parseUpoXml,
6222
6248
  parseXml: () => parseXml,
6223
6249
  pollUntil: () => pollUntil,
6250
+ queryAllInvoiceMetadata: () => queryAllInvoiceMetadata,
6224
6251
  resolveOptions: () => resolveOptions,
6225
- resolveXsdFor: () => resolveXsdFor,
6226
6252
  resumeOnlineSession: () => resumeOnlineSession,
6227
6253
  runWithConcurrency: () => runWithConcurrency,
6228
6254
  serializeInvoiceXml: () => serializeInvoiceXml,
@@ -6237,7 +6263,6 @@ __export(index_exports, {
6237
6263
  uploadBatchStream: () => uploadBatchStream,
6238
6264
  uploadBatchStreamParsed: () => uploadBatchStreamParsed,
6239
6265
  validate: () => validate,
6240
- validateAgainstXsd: () => validateAgainstXsd,
6241
6266
  validateBatch: () => validateBatch,
6242
6267
  validateBusinessRules: () => validateBusinessRules,
6243
6268
  validateCharValidity: () => validateCharValidity,
@@ -6287,219 +6312,6 @@ init_schema_registry();
6287
6312
  init_invoice_validator();
6288
6313
  init_char_validity();
6289
6314
 
6290
- // src/validation/xsd-validator.ts
6291
- init_cjs_shims();
6292
- var import_node_module = require("node:module");
6293
- var fs = __toESM(require("node:fs"), 1);
6294
- var path = __toESM(require("node:path"), 1);
6295
- var import_node_url = require("node:url");
6296
- var cachedPkgRoot = null;
6297
- function locatePackageRoot() {
6298
- if (cachedPkgRoot !== null) return cachedPkgRoot;
6299
- let dir = path.dirname((0, import_node_url.fileURLToPath)(importMetaUrl));
6300
- const root = path.parse(dir).root;
6301
- while (dir !== root) {
6302
- const candidate = path.join(dir, "docs", "schemas");
6303
- if (fs.existsSync(candidate)) {
6304
- cachedPkgRoot = dir;
6305
- return dir;
6306
- }
6307
- dir = path.dirname(dir);
6308
- }
6309
- throw new Error("Could not locate ksef-client-ts package root (docs/schemas not found).");
6310
- }
6311
- var XSD_RELATIVE = {
6312
- FA2: ["FA", "schemat_FA(2)_v1-0E.xsd"],
6313
- FA3: ["FA", "schemat_FA(3)_v1-0E.xsd"],
6314
- PEF: ["PEF", "Schemat_PEF(3)_v2-1.xsd"],
6315
- PEF_KOR: ["PEF", "Schemat_PEF_KOR(3)_v2-1.xsd"]
6316
- };
6317
- var FA_XSD_PATHS = {
6318
- get FA2() {
6319
- return resolveXsdFor("FA2");
6320
- },
6321
- get FA3() {
6322
- return resolveXsdFor("FA3");
6323
- }
6324
- };
6325
- var PEF_XSD_PATHS = {
6326
- get PEF() {
6327
- return resolveXsdFor("PEF");
6328
- },
6329
- get PEF_KOR() {
6330
- return resolveXsdFor("PEF_KOR");
6331
- }
6332
- };
6333
- function resolveXsdFor(schema) {
6334
- const rel = XSD_RELATIVE[schema];
6335
- if (!rel) throw new Error(`Unknown invoice schema: ${String(schema)}`);
6336
- return path.join(locatePackageRoot(), "docs", "schemas", ...rel);
6337
- }
6338
- var requireModule = (0, import_node_module.createRequire)(importMetaUrl);
6339
- var libxmljs = null;
6340
- var libxmljsLoadError = null;
6341
- try {
6342
- libxmljs = requireModule("libxmljs2");
6343
- } catch (err) {
6344
- const code = err?.code;
6345
- if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
6346
- libxmljs = null;
6347
- } else {
6348
- libxmljs = null;
6349
- libxmljsLoadError = err instanceof Error ? err : new Error(String(err));
6350
- }
6351
- }
6352
- var libxmljsAvailable = libxmljs !== null;
6353
- var MISSING_LIBXMLJS_MESSAGE_PREFIX = "libxmljs2 is not installed";
6354
- function isMissingLibxmljsError(err) {
6355
- return err instanceof Error && err.message.startsWith(MISSING_LIBXMLJS_MESSAGE_PREFIX);
6356
- }
6357
- var EXTERNAL_STRUKTURY_DANYCH_URL = /schemaLocation="http:\/\/crd\.gov\.pl\/xml\/schematy\/dziedzinowe\/mf\/2022\/01\/05\/eD\/DefinicjeTypy\/StrukturyDanych_v10-0E\.xsd"/;
6358
- function rewriteSchemaLocations(xsdContent) {
6359
- if (!EXTERNAL_STRUKTURY_DANYCH_URL.test(xsdContent)) {
6360
- return xsdContent;
6361
- }
6362
- const bazoweStrukturyPath = path.join(
6363
- locatePackageRoot(),
6364
- "docs",
6365
- "schemas",
6366
- "FA",
6367
- "bazowe",
6368
- "StrukturyDanych_v10-0E.xsd"
6369
- );
6370
- const bazoweStrukturyUrl = (0, import_node_url.pathToFileURL)(bazoweStrukturyPath).href;
6371
- const rewritten = xsdContent.replace(
6372
- EXTERNAL_STRUKTURY_DANYCH_URL,
6373
- `schemaLocation="${bazoweStrukturyUrl}"`
6374
- );
6375
- if (rewritten === xsdContent) {
6376
- throw new Error(
6377
- "FA XSD schemaLocation rewrite produced no replacement despite URL being present; regex likely out of sync with docs/schemas/FA/. Re-check after `yarn sync-schemas`."
6378
- );
6379
- }
6380
- return rewritten;
6381
- }
6382
- function validateAgainstXsd(xml, xsdPath) {
6383
- if (!libxmljs) {
6384
- const loadSuffix = libxmljsLoadError ? ` (load failed: ${libxmljsLoadError.message})` : "";
6385
- throw new Error(
6386
- `${MISSING_LIBXMLJS_MESSAGE_PREFIX}${loadSuffix}; cannot run XSD validation. Install it as an optional peer dependency (e.g. \`yarn add -O libxmljs2\` or \`npm i -O libxmljs2\`).`
6387
- );
6388
- }
6389
- const xsdDir = path.dirname(xsdPath);
6390
- const rawXsd = fs.readFileSync(xsdPath, "utf8");
6391
- const rewrittenXsd = rewriteSchemaLocations(rawXsd);
6392
- const baseUrl = (0, import_node_url.pathToFileURL)(xsdDir + path.sep).href;
6393
- let schemaDoc;
6394
- try {
6395
- schemaDoc = libxmljs.parseXml(rewrittenXsd, { baseUrl });
6396
- } catch (err) {
6397
- return { valid: false, errors: [`XSD parse failed: ${err.message}`] };
6398
- }
6399
- let xmlDoc;
6400
- try {
6401
- xmlDoc = libxmljs.parseXml(xml);
6402
- } catch (err) {
6403
- return { valid: false, errors: [`XML parse failed: ${err.message}`] };
6404
- }
6405
- const valid = xmlDoc.validate(schemaDoc);
6406
- const errors = valid ? [] : xmlDoc.validationErrors.map((err) => err.message.trim());
6407
- return { valid, errors };
6408
- }
6409
-
6410
- // src/models/index.ts
6411
- init_cjs_shims();
6412
-
6413
- // src/models/common.ts
6414
- init_cjs_shims();
6415
-
6416
- // src/models/auth/index.ts
6417
- init_cjs_shims();
6418
-
6419
- // src/models/auth/types.ts
6420
- init_cjs_shims();
6421
-
6422
- // src/models/auth/active-sessions-types.ts
6423
- init_cjs_shims();
6424
-
6425
- // src/models/sessions/index.ts
6426
- init_cjs_shims();
6427
-
6428
- // src/models/sessions/online-types.ts
6429
- init_cjs_shims();
6430
-
6431
- // src/models/sessions/batch-types.ts
6432
- init_cjs_shims();
6433
-
6434
- // src/models/sessions/status-types.ts
6435
- init_cjs_shims();
6436
-
6437
- // src/models/sessions/session-state.ts
6438
- init_cjs_shims();
6439
-
6440
- // src/models/invoices/index.ts
6441
- init_cjs_shims();
6442
-
6443
- // src/models/invoices/types.ts
6444
- init_cjs_shims();
6445
-
6446
- // src/models/permissions/index.ts
6447
- init_cjs_shims();
6448
-
6449
- // src/models/permissions/types.ts
6450
- init_cjs_shims();
6451
-
6452
- // src/models/tokens/index.ts
6453
- init_cjs_shims();
6454
-
6455
- // src/models/tokens/types.ts
6456
- init_cjs_shims();
6457
-
6458
- // src/models/certificates/index.ts
6459
- init_cjs_shims();
6460
-
6461
- // src/models/certificates/types.ts
6462
- init_cjs_shims();
6463
-
6464
- // src/models/lighthouse/index.ts
6465
- init_cjs_shims();
6466
-
6467
- // src/models/lighthouse/types.ts
6468
- init_cjs_shims();
6469
-
6470
- // src/models/limits/index.ts
6471
- init_cjs_shims();
6472
-
6473
- // src/models/limits/types.ts
6474
- init_cjs_shims();
6475
-
6476
- // src/models/peppol/index.ts
6477
- init_cjs_shims();
6478
-
6479
- // src/models/peppol/types.ts
6480
- init_cjs_shims();
6481
-
6482
- // src/models/test-data/index.ts
6483
- init_cjs_shims();
6484
-
6485
- // src/models/test-data/types.ts
6486
- init_cjs_shims();
6487
-
6488
- // src/models/crypto/index.ts
6489
- init_cjs_shims();
6490
-
6491
- // src/models/crypto/types.ts
6492
- init_cjs_shims();
6493
-
6494
- // src/models/qrcode/index.ts
6495
- init_cjs_shims();
6496
-
6497
- // src/models/qrcode/types.ts
6498
- init_cjs_shims();
6499
-
6500
- // src/models/index.ts
6501
- init_document_structures();
6502
-
6503
6315
  // src/services/index.ts
6504
6316
  init_cjs_shims();
6505
6317
  init_auth();
@@ -8417,7 +8229,6 @@ function buildDefaultFilters(subjectType, from, to) {
8417
8229
 
8418
8230
  // src/workflows/hwm-storage.ts
8419
8231
  init_cjs_shims();
8420
- var fs2 = __toESM(require("node:fs/promises"), 1);
8421
8232
  var InMemoryHwmStore = class {
8422
8233
  points = {};
8423
8234
  async load() {
@@ -8427,30 +8238,38 @@ var InMemoryHwmStore = class {
8427
8238
  this.points = { ...points };
8428
8239
  }
8429
8240
  };
8430
- var FileHwmStore = class {
8431
- constructor(filePath) {
8432
- this.filePath = filePath;
8433
- }
8434
- async load() {
8435
- try {
8436
- const data = await fs2.readFile(this.filePath, "utf-8");
8437
- return JSON.parse(data);
8438
- } catch (err) {
8439
- if (err.code === "ENOENT") {
8440
- return {};
8441
- }
8442
- throw err;
8443
- }
8444
- }
8445
- async save(points) {
8446
- await fs2.writeFile(this.filePath, JSON.stringify(points, null, 2), "utf-8");
8447
- }
8448
- };
8449
8241
 
8450
8242
  // src/workflows/auth-workflow.ts
8451
8243
  init_cjs_shims();
8452
8244
  init_auth_xml_builder();
8453
8245
  init_with_key_rotation_retry();
8246
+ init_ksef_auth_status_error();
8247
+ var AUTH_STATUS_SUCCESS = 200;
8248
+ var AUTH_STATUS_IN_PROGRESS = 100;
8249
+ async function awaitAuthentication(client, referenceNumber, authToken, pollOptions) {
8250
+ const final = await pollUntil(
8251
+ () => client.auth.getAuthStatus(referenceNumber, authToken),
8252
+ (s) => s.status.code !== AUTH_STATUS_IN_PROGRESS,
8253
+ { ...pollOptions, description: `auth ${referenceNumber}` }
8254
+ );
8255
+ if (final.status.code !== AUTH_STATUS_SUCCESS) {
8256
+ const details = final.status.details?.length ? ` (${final.status.details.join("; ")})` : "";
8257
+ throw new KSeFAuthStatusError(
8258
+ `Authentication failed with status ${final.status.code}: ${final.status.description}${details}`,
8259
+ referenceNumber,
8260
+ final.status.description
8261
+ );
8262
+ }
8263
+ const tokens = await client.auth.getAccessToken(authToken);
8264
+ client.authManager.setAccessToken(tokens.accessToken.token);
8265
+ client.authManager.setRefreshToken(tokens.refreshToken.token);
8266
+ return {
8267
+ accessToken: tokens.accessToken.token,
8268
+ accessTokenValidUntil: tokens.accessToken.validUntil,
8269
+ refreshToken: tokens.refreshToken.token,
8270
+ refreshTokenValidUntil: tokens.refreshToken.validUntil
8271
+ };
8272
+ }
8454
8273
  async function authenticateWithToken(client, options) {
8455
8274
  const challenge = await client.auth.getChallenge();
8456
8275
  await client.crypto.init();
@@ -8465,20 +8284,7 @@ async function authenticateWithToken(client, options) {
8465
8284
  });
8466
8285
  });
8467
8286
  const authToken = submitResult.authenticationToken.token;
8468
- await pollUntil(
8469
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8470
- (s) => s.status.code !== 100,
8471
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8472
- );
8473
- const tokens = await client.auth.getAccessToken(authToken);
8474
- client.authManager.setAccessToken(tokens.accessToken.token);
8475
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8476
- return {
8477
- accessToken: tokens.accessToken.token,
8478
- accessTokenValidUntil: tokens.accessToken.validUntil,
8479
- refreshToken: tokens.refreshToken.token,
8480
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8481
- };
8287
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8482
8288
  }
8483
8289
  async function authenticateWithCertificate(client, options) {
8484
8290
  const challenge = await client.auth.getChallenge();
@@ -8492,20 +8298,7 @@ async function authenticateWithCertificate(client, options) {
8492
8298
  options.enforceXadesCompliance ?? false
8493
8299
  );
8494
8300
  const authToken = submitResult.authenticationToken.token;
8495
- await pollUntil(
8496
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8497
- (s) => s.status.code !== 100,
8498
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8499
- );
8500
- const tokens = await client.auth.getAccessToken(authToken);
8501
- client.authManager.setAccessToken(tokens.accessToken.token);
8502
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8503
- return {
8504
- accessToken: tokens.accessToken.token,
8505
- accessTokenValidUntil: tokens.accessToken.validUntil,
8506
- refreshToken: tokens.refreshToken.token,
8507
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8508
- };
8301
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8509
8302
  }
8510
8303
  async function authenticateWithExternalSignature(client, options) {
8511
8304
  const challenge = await client.auth.getChallenge();
@@ -8520,20 +8313,7 @@ async function authenticateWithExternalSignature(client, options) {
8520
8313
  options.enforceXadesCompliance ?? false
8521
8314
  );
8522
8315
  const authToken = submitResult.authenticationToken.token;
8523
- await pollUntil(
8524
- () => client.auth.getAuthStatus(submitResult.referenceNumber, authToken),
8525
- (s) => s.status.code !== 100,
8526
- { ...options.pollOptions, description: `auth ${submitResult.referenceNumber}` }
8527
- );
8528
- const tokens = await client.auth.getAccessToken(authToken);
8529
- client.authManager.setAccessToken(tokens.accessToken.token);
8530
- client.authManager.setRefreshToken(tokens.refreshToken.token);
8531
- return {
8532
- accessToken: tokens.accessToken.token,
8533
- accessTokenValidUntil: tokens.accessToken.validUntil,
8534
- refreshToken: tokens.refreshToken.token,
8535
- refreshTokenValidUntil: tokens.refreshToken.validUntil
8536
- };
8316
+ return awaitAuthentication(client, submitResult.referenceNumber, authToken, options.pollOptions);
8537
8317
  }
8538
8318
  async function authenticateWithPkcs12(client, options) {
8539
8319
  const { Pkcs12Loader: Pkcs12Loader2 } = await Promise.resolve().then(() => (init_pkcs12_loader(), pkcs12_loader_exports));
@@ -8548,6 +8328,95 @@ async function authenticateWithPkcs12(client, options) {
8548
8328
  });
8549
8329
  }
8550
8330
 
8331
+ // src/workflows/metadata-query-paging.ts
8332
+ init_cjs_shims();
8333
+ init_ksef_metadata_pagination_error();
8334
+ init_ksef_validation_error();
8335
+ var DEFAULT_PAGE_SIZE = 100;
8336
+ var DEFAULT_MAX_BOUNDARY_CROSSINGS = 1e3;
8337
+ function boundaryFieldFor(dateType) {
8338
+ switch (dateType) {
8339
+ case "Issue":
8340
+ return "issueDate";
8341
+ case "Invoicing":
8342
+ return "invoicingDate";
8343
+ case "PermanentStorage":
8344
+ return "permanentStorageDate";
8345
+ }
8346
+ }
8347
+ async function* queryAllInvoiceMetadata(client, filters, options = {}) {
8348
+ const sortOrder = options.sortOrder ?? "Asc";
8349
+ const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
8350
+ const maxBoundaryCrossings = options.maxBoundaryCrossings ?? DEFAULT_MAX_BOUNDARY_CROSSINGS;
8351
+ if (!Number.isInteger(pageSize) || pageSize <= 0) {
8352
+ throw new KSeFValidationError("`pageSize` must be a positive integer.");
8353
+ }
8354
+ if (!Number.isInteger(maxBoundaryCrossings) || maxBoundaryCrossings < 0) {
8355
+ throw new KSeFValidationError("`maxBoundaryCrossings` must be a non-negative integer.");
8356
+ }
8357
+ const boundaryField = boundaryFieldFor(filters.dateRange.dateType);
8358
+ let dateRange = { ...filters.dateRange };
8359
+ let boundaryCrossings = 0;
8360
+ let carryKeys = /* @__PURE__ */ new Set();
8361
+ let carryValue;
8362
+ for (; ; ) {
8363
+ let pageIndex = 0;
8364
+ let lastBoundaryValue;
8365
+ let isTruncated = false;
8366
+ let boundaryKeys = /* @__PURE__ */ new Set();
8367
+ for (; ; ) {
8368
+ const window = { ...filters, dateRange };
8369
+ const response = await client.invoices.queryInvoiceMetadata(
8370
+ window,
8371
+ pageIndex,
8372
+ pageSize,
8373
+ sortOrder
8374
+ );
8375
+ isTruncated = response.isTruncated;
8376
+ for (const invoice of response.invoices) {
8377
+ const boundaryValue = invoice[boundaryField];
8378
+ const key = invoice.ksefNumber.toLowerCase();
8379
+ if (boundaryValue === carryValue && carryKeys.has(key)) continue;
8380
+ if (boundaryValue !== lastBoundaryValue) {
8381
+ lastBoundaryValue = boundaryValue;
8382
+ boundaryKeys = /* @__PURE__ */ new Set();
8383
+ }
8384
+ boundaryKeys.add(key);
8385
+ yield invoice;
8386
+ }
8387
+ if (response.hasMore) {
8388
+ pageIndex += 1;
8389
+ continue;
8390
+ }
8391
+ break;
8392
+ }
8393
+ if (!isTruncated || lastBoundaryValue === void 0) return;
8394
+ const previousBoundary = sortOrder === "Asc" ? dateRange.from : dateRange.to;
8395
+ if (previousBoundary === lastBoundaryValue) {
8396
+ throw new KSeFMetadataPaginationError(
8397
+ `Metadata paging stalled: a truncated window did not advance past ${boundaryField}=${lastBoundaryValue}. The result set likely exceeds the server cap within a single ${boundaryField} value; narrow the query further.`,
8398
+ lastBoundaryValue
8399
+ );
8400
+ }
8401
+ if (++boundaryCrossings > maxBoundaryCrossings) {
8402
+ throw new KSeFMetadataPaginationError(
8403
+ `Metadata paging exceeded ${maxBoundaryCrossings} truncation boundaries; aborting to avoid an unbounded loop.`,
8404
+ lastBoundaryValue
8405
+ );
8406
+ }
8407
+ carryKeys = boundaryKeys;
8408
+ carryValue = lastBoundaryValue;
8409
+ dateRange = sortOrder === "Asc" ? { ...dateRange, from: lastBoundaryValue } : { ...dateRange, to: lastBoundaryValue };
8410
+ }
8411
+ }
8412
+ async function collectAllInvoiceMetadata(client, filters, options = {}) {
8413
+ const all = [];
8414
+ for await (const invoice of queryAllInvoiceMetadata(client, filters, options)) {
8415
+ all.push(invoice);
8416
+ }
8417
+ return all;
8418
+ }
8419
+
8551
8420
  // src/offline/index.ts
8552
8421
  init_cjs_shims();
8553
8422
  init_deadline();
@@ -8592,98 +8461,6 @@ var InMemoryOfflineInvoiceStorage = class {
8592
8461
  }
8593
8462
  };
8594
8463
 
8595
- // src/offline/file-storage.ts
8596
- init_cjs_shims();
8597
- var fs3 = __toESM(require("node:fs/promises"), 1);
8598
- var path2 = __toESM(require("node:path"), 1);
8599
- var os = __toESM(require("node:os"), 1);
8600
- function resolveDir(dir) {
8601
- if (dir === "~" || dir.startsWith("~/")) {
8602
- return path2.join(os.homedir(), dir.slice(1));
8603
- }
8604
- return dir;
8605
- }
8606
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8607
- function validateId(id) {
8608
- if (!UUID_RE.test(id)) {
8609
- throw new Error(`Invalid invoice ID: ${id}`);
8610
- }
8611
- }
8612
- var FileOfflineInvoiceStorage = class {
8613
- dir;
8614
- constructor(directory) {
8615
- this.dir = resolveDir(directory ?? "~/.ksef/offline");
8616
- }
8617
- async ensureDir() {
8618
- await fs3.mkdir(this.dir, { recursive: true });
8619
- }
8620
- filePath(id) {
8621
- validateId(id);
8622
- return path2.join(this.dir, `${id}.json`);
8623
- }
8624
- async save(invoice) {
8625
- await this.ensureDir();
8626
- const file = this.filePath(invoice.id);
8627
- const tmp = `${file}.tmp`;
8628
- await fs3.writeFile(tmp, JSON.stringify(invoice, null, 2));
8629
- await fs3.rename(tmp, file);
8630
- }
8631
- async get(id) {
8632
- const file = this.filePath(id);
8633
- try {
8634
- return JSON.parse(await fs3.readFile(file, "utf-8"));
8635
- } catch (err) {
8636
- if (err instanceof Error && "code" in err && err.code === "ENOENT") {
8637
- return null;
8638
- }
8639
- console.warn(`Warning: Failed to read offline invoice ${id}: ${err instanceof Error ? err.message : String(err)}`);
8640
- return null;
8641
- }
8642
- }
8643
- async list(filter) {
8644
- let files;
8645
- try {
8646
- files = (await fs3.readdir(this.dir)).filter((f) => f.endsWith(".json"));
8647
- } catch {
8648
- return [];
8649
- }
8650
- const results = [];
8651
- for (const file of files) {
8652
- try {
8653
- const data = JSON.parse(
8654
- await fs3.readFile(path2.join(this.dir, file), "utf-8")
8655
- );
8656
- if (!filter || matchesFilter(data, filter)) {
8657
- results.push(data);
8658
- }
8659
- } catch (err) {
8660
- console.warn(`Warning: Skipping corrupt offline invoice file ${file}: ${err instanceof Error ? err.message : String(err)}`);
8661
- }
8662
- }
8663
- return results;
8664
- }
8665
- /**
8666
- * Update invoice metadata (read-modify-write).
8667
- *
8668
- * Note: No file locking — concurrent updates to the same ID may cause
8669
- * lost writes. Acceptable for CLI (single process). Library consumers
8670
- * running parallel operations should use external locking.
8671
- */
8672
- async update(id, updates) {
8673
- const existing = await this.get(id);
8674
- if (!existing) throw new Error(`Offline invoice not found: ${id}`);
8675
- await this.save({ ...existing, ...updates });
8676
- }
8677
- async delete(id) {
8678
- const file = this.filePath(id);
8679
- try {
8680
- await fs3.unlink(file);
8681
- } catch (e) {
8682
- if (e instanceof Error && "code" in e && e.code !== "ENOENT") throw e;
8683
- }
8684
- }
8685
- };
8686
-
8687
8464
  // src/index.ts
8688
8465
  init_offline_invoice_workflow();
8689
8466
  init_client();
@@ -8706,6 +8483,7 @@ init_client();
8706
8483
  CertificateFetcher,
8707
8484
  CertificateFingerprint,
8708
8485
  CertificateName,
8486
+ CertificateSerialNumber,
8709
8487
  CertificateService,
8710
8488
  CircuitBreakerPolicy,
8711
8489
  CryptographyService,
@@ -8717,11 +8495,8 @@ init_client();
8717
8495
  EntityPermissionGrantBuilder,
8718
8496
  Environment,
8719
8497
  FAKTURA_NAMESPACE,
8720
- FA_XSD_PATHS,
8721
8498
  FORM_CODES,
8722
8499
  FORM_CODE_KEYS,
8723
- FileHwmStore,
8724
- FileOfflineInvoiceStorage,
8725
8500
  INVOICE_TYPES_BY_SYSTEM_CODE,
8726
8501
  InMemoryHwmStore,
8727
8502
  InMemoryOfflineInvoiceStorage,
@@ -8742,6 +8517,7 @@ init_client();
8742
8517
  KSeFErrorCode,
8743
8518
  KSeFForbiddenError,
8744
8519
  KSeFGoneError,
8520
+ KSeFMetadataPaginationError,
8745
8521
  KSeFRateLimitError,
8746
8522
  KSeFSessionExpiredError,
8747
8523
  KSeFUnauthorizedError,
@@ -8759,7 +8535,6 @@ init_client();
8759
8535
  OfflineInvoiceWorkflow,
8760
8536
  OnlineSessionService,
8761
8537
  PEF_NAMESPACE,
8762
- PEF_XSD_PATHS,
8763
8538
  PERMISSION_DESCRIPTION_MAX_LENGTH,
8764
8539
  PERMISSION_DESCRIPTION_MIN_LENGTH,
8765
8540
  PeppolId,
@@ -8803,6 +8578,7 @@ init_client();
8803
8578
  buildXmlFromObject,
8804
8579
  calculateBackoff,
8805
8580
  calculateOfflineDeadline,
8581
+ collectAllInvoiceMetadata,
8806
8582
  comparePKey,
8807
8583
  createTarGz,
8808
8584
  createZip,
@@ -8827,7 +8603,6 @@ init_client();
8827
8603
  isExpired,
8828
8604
  isFakturaInput,
8829
8605
  isFormCodeShape,
8830
- isMissingLibxmljsError,
8831
8606
  isPefUblDocumentInput,
8832
8607
  isPolishHoliday,
8833
8608
  isRetryableError,
@@ -8835,6 +8610,7 @@ init_client();
8835
8610
  isValidBase64,
8836
8611
  isValidCertificateFingerprint,
8837
8612
  isValidCertificateName,
8613
+ isValidCertificateSerialNumber,
8838
8614
  isValidInternalId,
8839
8615
  isValidIp4Address,
8840
8616
  isValidKsefNumber,
@@ -8847,7 +8623,6 @@ init_client();
8847
8623
  isValidReferenceNumber,
8848
8624
  isValidSha256Base64,
8849
8625
  isValidVatUe,
8850
- libxmljsAvailable,
8851
8626
  nextBusinessDay,
8852
8627
  openOnlineSession,
8853
8628
  openSendAndClose,
@@ -8858,8 +8633,8 @@ init_client();
8858
8633
  parseUpoXml,
8859
8634
  parseXml,
8860
8635
  pollUntil,
8636
+ queryAllInvoiceMetadata,
8861
8637
  resolveOptions,
8862
- resolveXsdFor,
8863
8638
  resumeOnlineSession,
8864
8639
  runWithConcurrency,
8865
8640
  serializeInvoiceXml,
@@ -8874,7 +8649,6 @@ init_client();
8874
8649
  uploadBatchStream,
8875
8650
  uploadBatchStreamParsed,
8876
8651
  validate,
8877
- validateAgainstXsd,
8878
8652
  validateBatch,
8879
8653
  validateBusinessRules,
8880
8654
  validateCharValidity,