@devly-cl/sii-client 0.7.1 → 0.7.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +84 -1
  2. package/dist/application/document-status.d.ts +5 -5
  3. package/dist/application/document-status.js +14 -9
  4. package/dist/application/dte-import-mapper.d.ts +8 -0
  5. package/dist/application/dte-import-mapper.js +25 -0
  6. package/dist/application/dte-import-model.d.ts +28 -0
  7. package/dist/application/dte-import-model.js +2 -0
  8. package/dist/application/dte-import.d.ts +37 -0
  9. package/dist/application/dte-import.js +352 -0
  10. package/dist/application/invoice-queries.d.ts +12 -6
  11. package/dist/application/invoice-queries.js +9 -5
  12. package/dist/application/issuance.d.ts +2 -2
  13. package/dist/application/issuance.js +26 -10
  14. package/dist/contracts.d.ts +32 -0
  15. package/dist/contracts.js +17 -0
  16. package/dist/domain/civil-date.d.ts +2 -0
  17. package/dist/domain/civil-date.js +10 -0
  18. package/dist/domain/document-status.d.ts +0 -4
  19. package/dist/domain/document-status.js +18 -11
  20. package/dist/domain/document.js +49 -9
  21. package/dist/domain/dte-arithmetic.d.ts +35 -0
  22. package/dist/domain/dte-arithmetic.js +78 -0
  23. package/dist/domain/dte-components.d.ts +9 -0
  24. package/dist/domain/dte-components.js +37 -0
  25. package/dist/domain/dte-detail.d.ts +111 -0
  26. package/dist/domain/dte-detail.js +2 -0
  27. package/dist/domain/dte-identity.d.ts +19 -0
  28. package/dist/domain/dte-identity.js +52 -0
  29. package/dist/domain/dte-money.d.ts +41 -0
  30. package/dist/domain/dte-money.js +81 -0
  31. package/dist/domain/dte-reconciliation-model.d.ts +87 -0
  32. package/dist/domain/dte-reconciliation-model.js +2 -0
  33. package/dist/domain/dte-reconciliation.d.ts +15 -0
  34. package/dist/domain/dte-reconciliation.js +390 -0
  35. package/dist/domain/dte-validation.d.ts +7 -0
  36. package/dist/domain/dte-validation.js +84 -0
  37. package/dist/domain/invoice-xml.d.ts +17 -57
  38. package/dist/domain/invoice-xml.js +0 -10
  39. package/dist/domain/invoicing.d.ts +30 -4
  40. package/dist/domain/invoicing.js +75 -21
  41. package/dist/domain/issued-invoice.d.ts +0 -6
  42. package/dist/domain/rcv-document.d.ts +0 -4
  43. package/dist/domain/received-invoice.d.ts +1 -4
  44. package/dist/index.d.ts +19 -9
  45. package/dist/index.js +20 -4
  46. package/dist/infrastructure/document-status-gateway.d.ts +6 -4
  47. package/dist/infrastructure/document-status-gateway.js +34 -13
  48. package/dist/infrastructure/document-status-parser.js +38 -12
  49. package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
  50. package/dist/infrastructure/dte-xml-mapper.js +381 -0
  51. package/dist/infrastructure/dte-xml.d.ts +40 -4
  52. package/dist/infrastructure/dte-xml.js +117 -196
  53. package/dist/infrastructure/facturador-gateway.d.ts +10 -7
  54. package/dist/infrastructure/facturador-gateway.js +256 -56
  55. package/dist/infrastructure/facturador.d.ts +1 -1
  56. package/dist/infrastructure/facturador.js +18 -10
  57. package/dist/infrastructure/invoice-pdf.js +10 -3
  58. package/dist/infrastructure/rcv-gateway.d.ts +7 -4
  59. package/dist/infrastructure/rcv-gateway.js +53 -12
  60. package/dist/infrastructure/rcv-normalization.d.ts +8 -1
  61. package/dist/infrastructure/rcv-normalization.js +54 -12
  62. package/dist/infrastructure/read-options.d.ts +3 -0
  63. package/dist/infrastructure/read-options.js +25 -0
  64. package/dist/infrastructure/sii-client.d.ts +98 -13
  65. package/dist/infrastructure/sii-client.js +182 -31
  66. package/dist/infrastructure/sii-http-session.d.ts +2 -2
  67. package/dist/infrastructure/sii-http-session.js +134 -37
  68. package/dist/sii-error.d.ts +5 -0
  69. package/dist/sii-error.js +39 -13
  70. package/package.json +2 -2
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FacturadorGateway = void 0;
4
+ const contracts_1 = require("../contracts");
4
5
  const rut_1 = require("../domain/rut");
5
6
  const invoicing_1 = require("../domain/invoicing");
6
7
  const document_1 = require("../domain/document");
7
- const invoice_xml_1 = require("../domain/invoice-xml");
8
8
  const sii_error_1 = require("../sii-error");
9
9
  const dte_xml_1 = require("./dte-xml");
10
+ const read_options_1 = require("./read-options");
10
11
  const sii_http_session_1 = require("./sii-http-session");
11
12
  const facturador_1 = require("./facturador");
12
13
  const invoice_pdf_1 = require("./invoice-pdf");
@@ -22,16 +23,31 @@ class FacturadorGateway {
22
23
  this.session = session;
23
24
  this.closeSession = closeSession;
24
25
  }
25
- assertReady() { this.session.assertReady(); }
26
- close() { return this.closeSession(); }
27
- clearPreparation() { this.#ready = false; this.#preparation = undefined; this.#signing = undefined; }
26
+ assertReady() {
27
+ this.session.assertReady();
28
+ }
29
+ close() {
30
+ return this.closeSession();
31
+ }
32
+ clearPreparation() {
33
+ this.#ready = false;
34
+ this.#preparation = undefined;
35
+ this.#signing = undefined;
36
+ }
28
37
  async companyInfo(rut) {
29
38
  this.session.assertReady();
30
39
  const receiver = (0, rut_1.parseRut)(rut);
31
40
  if (this.#preparation || this.#signing)
32
41
  throw new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS');
33
42
  await this.#ensurePortal(DESTINATION, undefined, true);
34
- const fields = new URLSearchParams({ PTDC_CODIGO: '33', EHDR_CODIGO: '', EFXP_FOLIO: '', ES_BORR: 'FALSE', esCRED_EC: 'FALSE', esFACT_TUR: 'FALSE' });
43
+ const fields = new URLSearchParams({
44
+ PTDC_CODIGO: '33',
45
+ EHDR_CODIGO: '',
46
+ EFXP_FOLIO: '',
47
+ ES_BORR: 'FALSE',
48
+ esCRED_EC: 'FALSE',
49
+ esFACT_TUR: 'FALSE'
50
+ });
35
51
  const lookup = await this.#lookupReceiver(fields, receiver);
36
52
  let returnedRut;
37
53
  try {
@@ -55,7 +71,12 @@ class FacturadorGateway {
55
71
  throw this.session.failure('SII_PROTOCOL_CHANGED', 'mipeGenFacEx.cgi', 'INVALID_RESPONSE', undefined, { stage: 'COMPANY_LOOKUP' });
56
72
  }
57
73
  this.session.assertReady();
58
- return { rut: returnedRut, legalName, ...options, source: 'SII_FACTURADOR', observedAt: new Date().toISOString() };
74
+ return {
75
+ rut: returnedRut,
76
+ legalName, ...options,
77
+ source: 'SII_FACTURADOR',
78
+ observedAt: new Date().toISOString()
79
+ };
59
80
  }
60
81
  async prepareInvoice(input) {
61
82
  this.session.assertReady();
@@ -79,25 +100,56 @@ class FacturadorGateway {
79
100
  const requester = invoice.requesterRut ? (0, rut_1.parseRut)(invoice.requesterRut) : undefined;
80
101
  const carrier = invoice.transport ? (0, rut_1.parseRut)(invoice.transport.carrierRut) : undefined, driver = invoice.transport ? (0, rut_1.parseRut)(invoice.transport.driverRut) : undefined;
81
102
  const values = {
82
- PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, CANT_DET: String(invoice.items.length), ES_BORR: 'FALSE',
83
- EFXP_DIR_ORIGEN: invoice.issuer.address, EFXP_CMNA_ORIGEN: invoice.issuer.commune, EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
84
- EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '', EFXP_FONO_EMISOR: invoice.issuer.phone ?? issuerAddress[4]?.trim() ?? '',
103
+ PTDC_CODIGO: '33',
104
+ EFXP_FCH_EMIS: invoice.issuedDate,
105
+ CANT_DET: String(invoice.items.length),
106
+ ES_BORR: 'FALSE',
107
+ EFXP_DIR_ORIGEN: invoice.issuer.address,
108
+ EFXP_CMNA_ORIGEN: invoice.issuer.commune,
109
+ EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
110
+ EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '',
111
+ EFXP_FONO_EMISOR: invoice.issuer.phone ?? issuerAddress[4]?.trim() ?? '',
85
112
  EFXP_EMAIL_EMISOR: invoice.issuer.email ?? fields.get('EFXP_EMAIL_EMISOR')?.trim() ?? '',
86
- EFXP_ACTECO: invoice.issuer.activityCode, EFXP_ACTECO_SELECT: invoice.issuer.activityCode, EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
87
- EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
88
- EFXP_DIR_RECEP: invoice.receiver.address, EFXP_CMNA_RECEP: invoice.receiver.commune, EFXP_CIUDAD_RECEP: invoice.receiver.city,
89
- EFXP_GIRO_RECEP: invoice.receiver.businessActivity, EFXP_CONTACTO: invoice.receiver.contact ?? '', EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
90
- EFXP_RUT_SOLICITA: requester?.rut ?? '', EFXP_DV_SOLICITA: requester?.dv ?? '', EFXP_FMA_PAGO: String(invoice.paymentForm),
91
- EFXP_RUT_TRANSPORTE: carrier?.rut ?? '', EFXP_DV_TRANSPORTE: carrier?.dv ?? '', EFXP_PATENTE: invoice.transport?.licensePlate ?? '',
92
- EFXP_RUT_CHOFER: driver?.rut ?? '', EFXP_DV_CHOFER: driver?.dv ?? '', EFXP_NOMBRE_CHOFER: invoice.transport?.driverName ?? '',
93
- EFXP_SUBTOTAL: String(breakdown.subtotal), EFXP_PCT_DESC: breakdown.discountPercent, EFXP_MNT_DESC: String(breakdown.discountAmount), MNT_NETO_TEMP: String(totals.netAmount), IVA_TEMP: String(totals.vatAmount),
94
- EFXP_MNT_NETO: String(totals.netAmount), EFXP_TASA_IVA: '19', EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount), EFXP_OTRO_IMP_TOTAL: String(breakdown.additionalTaxAmount),
113
+ EFXP_ACTECO: invoice.issuer.activityCode,
114
+ EFXP_ACTECO_SELECT: invoice.issuer.activityCode,
115
+ EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
116
+ EFXP_RUT_RECEP: receiver.rut,
117
+ EFXP_DV_RECEP: receiver.dv,
118
+ EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
119
+ EFXP_DIR_RECEP: invoice.receiver.address,
120
+ EFXP_CMNA_RECEP: invoice.receiver.commune,
121
+ EFXP_CIUDAD_RECEP: invoice.receiver.city,
122
+ EFXP_GIRO_RECEP: invoice.receiver.businessActivity,
123
+ EFXP_CONTACTO: invoice.receiver.contact ?? '',
124
+ EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
125
+ EFXP_RUT_SOLICITA: requester?.rut ?? '',
126
+ EFXP_DV_SOLICITA: requester?.dv ?? '',
127
+ EFXP_FMA_PAGO: String(invoice.paymentForm),
128
+ EFXP_RUT_TRANSPORTE: carrier?.rut ?? '',
129
+ EFXP_DV_TRANSPORTE: carrier?.dv ?? '',
130
+ EFXP_PATENTE: invoice.transport?.licensePlate ?? '',
131
+ EFXP_RUT_CHOFER: driver?.rut ?? '',
132
+ EFXP_DV_CHOFER: driver?.dv ?? '',
133
+ EFXP_NOMBRE_CHOFER: invoice.transport?.driverName ?? '',
134
+ EFXP_SUBTOTAL: String(breakdown.subtotal),
135
+ EFXP_PCT_DESC: breakdown.discountPercent,
136
+ EFXP_MNT_DESC: String(breakdown.discountAmount),
137
+ MNT_NETO_TEMP: String(totals.netAmount),
138
+ IVA_TEMP: String(totals.vatAmount),
139
+ EFXP_MNT_NETO: String(totals.netAmount),
140
+ EFXP_TASA_IVA: '19',
141
+ EFXP_IVA: String(totals.vatAmount),
142
+ EFXP_MNT_TOTAL: String(totals.totalAmount),
143
+ EFXP_OTRO_IMP_TOTAL: String(breakdown.additionalTaxAmount),
95
144
  };
96
145
  for (const [key, value] of Object.entries(values))
97
146
  fields.set(key, value);
98
147
  const optionalPreview = {};
99
- const optionalField = (key, value) => { fields.set(key, value); if (value)
100
- optionalPreview[key] = value; };
148
+ const optionalField = (key, value) => {
149
+ fields.set(key, value);
150
+ if (value)
151
+ optionalPreview[key] = value;
152
+ };
101
153
  if (invoice.items.some(item => item.productCode))
102
154
  fields.set('COD_SI_NO', 'SiChecked');
103
155
  if (invoice.items.some(item => item.additionalTaxCode !== undefined))
@@ -116,7 +168,15 @@ class FacturadorGateway {
116
168
  optionalPreview.EFXP_FONO_EMISOR = invoice.issuer.phone;
117
169
  for (const [index, item] of invoice.items.entries()) {
118
170
  const suffix = String(index + 1).padStart(2, '0');
119
- for (const [field, value] of Object.entries({ NMB: item.name, QTY: item.quantity, PRC: item.unitNetPriceClp, UNMD: item.unit ?? '', DSC_ITEM: item.description ?? '', PCTD: item.discountPercent ?? '', SUBT: String(breakdown.lineAmounts[index].amount) }))
171
+ for (const [field, value] of Object.entries({
172
+ NMB: item.name,
173
+ QTY: item.quantity,
174
+ PRC: item.unitNetPriceClp,
175
+ UNMD: item.unit ?? '',
176
+ DSC_ITEM: item.description ?? '',
177
+ PCTD: item.discountPercent ?? '',
178
+ SUBT: String(breakdown.lineAmounts[index].amount)
179
+ }))
120
180
  fields.set(`EFXP_${field}_${suffix}`, value);
121
181
  if (item.productCode) {
122
182
  optionalField(`EFXP_TPO_COD_${suffix}`, item.productCode.type);
@@ -138,7 +198,14 @@ class FacturadorGateway {
138
198
  fields.set('REF_SI_NO', 'SiChecked');
139
199
  invoice.references.forEach((ref, index) => {
140
200
  const suffix = String(index + 1).padStart(3, '0');
141
- for (const [key, value] of Object.entries({ TPO_DOC_REF: ref.documentType, IND_GLOBAL: ref.global ? '1' : '', FOLIO_REF: ref.folio, FCH_REF: ref.date, CODIGO_REF: '', RAZON_REF: ref.reason ?? '' }))
201
+ for (const [key, value] of Object.entries({
202
+ TPO_DOC_REF: ref.documentType,
203
+ IND_GLOBAL: ref.global ? '1' : '',
204
+ FOLIO_REF: ref.folio,
205
+ FCH_REF: ref.date,
206
+ CODIGO_REF: '',
207
+ RAZON_REF: ref.reason ?? ''
208
+ }))
142
209
  optionalField(`EFXP_${key}_${suffix}`, value);
143
210
  scheduleDate('ref', index, ref.date);
144
211
  });
@@ -147,24 +214,56 @@ class FacturadorGateway {
147
214
  fields.set('PAGO_SI_NO', 'SiChecked');
148
215
  invoice.payments.forEach((payment, index) => {
149
216
  const suffix = String(index + 1).padStart(3, '0');
150
- for (const [key, value] of Object.entries({ FCH_PAGO: payment.date, MNT_PAGO: String(payment.amountClp), GLOSA_PAGOS: payment.description ?? '' }))
217
+ for (const [key, value] of Object.entries({
218
+ FCH_PAGO: payment.date,
219
+ MNT_PAGO: String(payment.amountClp),
220
+ GLOSA_PAGOS: payment.description ?? ''
221
+ }))
151
222
  optionalField(`EFXP_${key}_${suffix}`, value);
152
223
  scheduleDate('pago', index, payment.date);
153
224
  });
154
225
  }
155
226
  page = await this.#portal('mipeDisplayPreView.cgi', fields);
156
227
  const preview = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
157
- this.#assertFields(preview, { PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_MNT_NETO: String(totals.netAmount), EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount) });
228
+ this.#assertFields(preview, {
229
+ PTDC_CODIGO: '33',
230
+ EFXP_FCH_EMIS: invoice.issuedDate,
231
+ EFXP_RUT_RECEP: receiver.rut,
232
+ EFXP_DV_RECEP: receiver.dv,
233
+ EFXP_MNT_NETO: String(totals.netAmount),
234
+ EFXP_IVA: String(totals.vatAmount),
235
+ EFXP_MNT_TOTAL: String(totals.totalAmount)
236
+ });
158
237
  this.#assertFields(preview, optionalPreview);
159
238
  if (!invoice.smallBusiness && preview.get('EMP_MENOR_TAMANO') === 'SiChecked')
160
239
  throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
161
240
  this.#preparation = preview;
162
- return { issuerRut: this.session.company.formatted, receiverRut: receiver.formatted, documentType: 33, issuedDate: invoice.issuedDate, ...totals, invoice, issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '', issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '', issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '', issuerContact: { email: values.EFXP_EMAIL_EMISOR, phone: values.EFXP_FONO_EMISOR } };
241
+ return {
242
+ issuerRut: this.session.company.formatted,
243
+ receiverRut: receiver.formatted,
244
+ documentType: 33,
245
+ issuedDate: invoice.issuedDate, ...totals,
246
+ invoice,
247
+ issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '',
248
+ issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '',
249
+ issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '',
250
+ issuerContact: { email: values.EFXP_EMAIL_EMISOR, phone: values.EFXP_FONO_EMISOR }
251
+ };
163
252
  }
164
253
  async prepareCancellationCreditNote({ factura, issuedDate }) {
165
254
  this.session.assertReady();
166
255
  const original = await this.issuedDocumentXml(factura);
167
- const query = new URLSearchParams({ RUT_RECP: '', FOLIO: factura.folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: '33', ESTADO: '', ORDEN: '', NUM_PAG: '1' });
256
+ const query = new URLSearchParams({
257
+ RUT_RECP: '',
258
+ FOLIO: factura.folio,
259
+ RZN_SOC: '',
260
+ FEC_DESDE: '',
261
+ FEC_HASTA: '',
262
+ TPO_DOC: '33',
263
+ ESTADO: '',
264
+ ORDEN: '',
265
+ NUM_PAG: '1'
266
+ });
168
267
  const history = await this.#portal('mipeAdminDocsEmi.cgi', undefined, `?${query}`);
169
268
  const codes = new Set();
170
269
  for (const element of htmlElements(history.document))
@@ -177,18 +276,41 @@ class FacturadorGateway {
177
276
  if (link.origin === 'https://www1.sii.cl' && link.pathname === '/cgi-bin/Portal001/mipeGesDocEmi.cgi' && /^\d{1,20}$/.test(link.searchParams.get('CODIGO') ?? ''))
178
277
  codes.add(link.searchParams.get('CODIGO'));
179
278
  }
180
- catch { /* Non-document links are ignored. */ }
279
+ catch { /* Non-document links are ignored. */
280
+ }
181
281
  }
182
282
  if (codes.size !== 1)
183
283
  throw this.session.failure('SII_DOCUMENT_RECOVERY_FAILED', 'mipeAdminDocsEmi.cgi', codes.size === 0 ? 'DOCUMENT_NOT_FOUND' : 'INVALID_RESPONSE');
184
284
  const page = await this.#portal('mipeDisplayPreView.cgi', undefined, `?EHDR_CODIGO=${[...codes][0]}&TIPO_NOTA=61`);
185
285
  const fields = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
186
286
  const d = original.detail;
187
- this.#assertFields(fields, { PTDC_CODIGO: '61', EFXP_FCH_EMIS: issuedDate, EFXP_RUT_RECEP: (0, rut_1.parseRut)(d.receiverRut).rut, EFXP_DV_RECEP: (0, rut_1.parseRut)(d.receiverRut).dv, EFXP_TPO_DOC_REF_001: '33', EFXP_FOLIO_REF_001: d.folio, EFXP_FCH_REF_001: d.issuedDate, EFXP_CODIGO_REF_001: '1', EFXP_MNT_NETO: String(d.netAmount), EFXP_IVA: String(d.vatAmount), EFXP_MNT_TOTAL: String(d.totalAmount) });
287
+ this.#assertFields(fields, {
288
+ PTDC_CODIGO: '61',
289
+ EFXP_FCH_EMIS: issuedDate,
290
+ EFXP_RUT_RECEP: (0, rut_1.parseRut)(d.receiverRut).rut,
291
+ EFXP_DV_RECEP: (0, rut_1.parseRut)(d.receiverRut).dv,
292
+ EFXP_TPO_DOC_REF_001: '33',
293
+ EFXP_FOLIO_REF_001: d.folio,
294
+ EFXP_FCH_REF_001: d.issuedDate,
295
+ EFXP_CODIGO_REF_001: '1',
296
+ EFXP_MNT_NETO: String(d.netAmount),
297
+ EFXP_IVA: String(d.vatAmount),
298
+ EFXP_MNT_TOTAL: String(d.totalAmount)
299
+ });
188
300
  if (fields.get('EFXP_FOLIO_REF_002')?.trim() || fields.get('EFXP_FOLIO_REF_003')?.trim() || d.netAmount === null || d.vatAmount === null)
189
301
  throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
190
302
  this.#preparation = fields;
191
- return { issuerRut: d.issuerRut, receiverRut: d.receiverRut, documentType: 61, issuedDate, netAmount: d.netAmount, vatAmount: d.vatAmount, totalAmount: d.totalAmount, originalInvoice: d, reference: { documentType: 33, folio: d.folio, issuedDate: d.issuedDate, code: 1 } };
303
+ return {
304
+ issuerRut: d.issuerRut,
305
+ receiverRut: d.receiverRut,
306
+ documentType: 61,
307
+ issuedDate,
308
+ netAmount: d.netAmount,
309
+ vatAmount: d.vatAmount,
310
+ totalAmount: d.totalAmount,
311
+ originalInvoice: d,
312
+ reference: { documentType: 33, folio: d.folio, issuedDate: d.issuedDate, code: 1 }
313
+ };
192
314
  }
193
315
  async unsignedDocument(approved) {
194
316
  if (!this.#preparation)
@@ -199,10 +321,15 @@ class FacturadorGateway {
199
321
  if (!/^[1-9]\d{0,19}$/.test(folio))
200
322
  throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_RESPONSE');
201
323
  const plain = fields.get('txtPlainText') ?? '';
202
- const expected = { issuerRut: approved.issuerRut, receiverRut: approved.receiverRut, documentType: approved.documentType, folio };
324
+ const expected = {
325
+ issuerRut: approved.issuerRut,
326
+ receiverRut: approved.receiverRut,
327
+ documentType: approved.documentType,
328
+ folio
329
+ };
203
330
  let unsigned;
204
331
  try {
205
- unsigned = (0, dte_xml_1.parseDteDocumentXml)((0, facturador_1.encodeUnsignedDteXml)(plain), expected);
332
+ unsigned = (0, dte_xml_1.parseDteDocumentXmlForIssuance)((0, facturador_1.encodeUnsignedDteXml)(plain), expected);
206
333
  }
207
334
  catch {
208
335
  throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_XML');
@@ -226,14 +353,23 @@ class FacturadorGateway {
226
353
  if (!Array.isArray(certs) || certs.length !== 1 || !(0, sii_http_session_1.isRecord)(certs[0]) || typeof certs[0].nombre !== 'string' || !certs[0].nombre || certs[0].nombre.length > 256)
227
354
  throw this.session.failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
228
355
  const name = certs[0].nombre;
229
- const fields = new URLSearchParams({ nombre: name, dato: signing.plain, rut: identity.rut, dv: identity.dv, clave: password, nodo: 'dte:DTE', nodoId: 'dte:Documento', nameSpace: 'http://www.sii.cl/SiiDte' });
356
+ const fields = new URLSearchParams({
357
+ nombre: name,
358
+ dato: signing.plain,
359
+ rut: identity.rut,
360
+ dv: identity.dv,
361
+ clave: password,
362
+ nodo: 'dte:DTE',
363
+ nodoId: 'dte:Documento',
364
+ nameSpace: 'http://www.sii.cl/SiiDte'
365
+ });
230
366
  return this.session.request(`${sii_http_session_1.FACTURADOR}postFirmaDigital.cgi`, async (response) => {
231
367
  const signedBytes = await this.session.readBounded(response, 'postFirmaDigital.cgi');
232
368
  if (!signedBytes.length)
233
369
  throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'EMPTY_RESPONSE', response);
234
370
  let signed;
235
371
  try {
236
- signed = (0, dte_xml_1.parseDteDocumentXml)(signedBytes, signing.expected);
372
+ signed = (0, dte_xml_1.parseDteDocumentXmlForIssuance)(signedBytes, signing.expected);
237
373
  }
238
374
  catch {
239
375
  const text = (0, facturador_1.readPortalHtml)(signedBytes);
@@ -246,7 +382,14 @@ class FacturadorGateway {
246
382
  throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'SIGNATURE_INVALID', response);
247
383
  signing.certificate = name;
248
384
  return { ...signed, ...signing.expected, issuedDate: approved.issuedDate, contentHash: approved.contentHash };
249
- }, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: `${sii_http_session_1.FACTURADOR}mipeGenXMLFirma.cgi` }, body: fields.toString() });
385
+ }, {
386
+ method: 'POST',
387
+ headers: {
388
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
389
+ Referer: `${sii_http_session_1.FACTURADOR}mipeGenXMLFirma.cgi`
390
+ },
391
+ body: fields.toString()
392
+ });
250
393
  }
251
394
  async sendDocument(document, password) {
252
395
  const signing = this.#signing;
@@ -269,20 +412,34 @@ class FacturadorGateway {
269
412
  throw this.session.failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
270
413
  }
271
414
  }
272
- issuedInvoiceXml(input) {
415
+ issuedInvoiceXml(input, options) {
273
416
  if (![33, 34].includes(input.documentType))
274
417
  return Promise.reject(new TypeError('Identidad de factura inválida'));
275
- return this.#documentXml(input, undefined, true);
418
+ return this.#documentXml(input, undefined, true, false, options);
276
419
  }
277
- receivedInvoiceXml(input) {
420
+ receivedInvoiceXml(input, options) {
278
421
  if (![33, 34].includes(input.documentType))
279
422
  return Promise.reject(new TypeError('Identidad de factura inválida'));
280
- return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), true);
423
+ return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), true, false, options);
424
+ }
425
+ issuedDocumentXml(input, options) {
426
+ return this.#documentXml(input, undefined, false, false, options);
427
+ }
428
+ async receivedDocumentXml(input, options) {
429
+ return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), false, false, options);
430
+ }
431
+ issuedDocumentXmlExact(input, options) {
432
+ return this.#documentXml(input, undefined, false, true, options);
433
+ }
434
+ receivedDocumentXmlExact(input, options) {
435
+ return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), false, true, options);
436
+ }
437
+ issuedInvoicePdf(input, options) {
438
+ return this.#documentPdf(input, undefined, options);
439
+ }
440
+ async receivedInvoicePdf(input, options) {
441
+ return this.#documentPdf(input, (0, rut_1.parseRut)(input.issuerRut), options);
281
442
  }
282
- issuedDocumentXml(input) { return this.#documentXml(input); }
283
- async receivedDocumentXml(input) { return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut)); }
284
- issuedInvoicePdf(input, options) { return this.#documentPdf(input, undefined, options); }
285
- async receivedInvoicePdf(input, options) { return this.#documentPdf(input, (0, rut_1.parseRut)(input.issuerRut), options); }
286
443
  async #documentPdf({ documentType, folio }, supplier, options = {}) {
287
444
  this.session.assertReady();
288
445
  if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
@@ -291,7 +448,17 @@ class FacturadorGateway {
291
448
  const historyEndpoint = supplier ? 'mipeAdminDocsRcp.cgi' : 'mipeAdminDocsEmi.cgi';
292
449
  return this.session.pdfOperation(endpoint, async (signal, trackStream) => {
293
450
  await this.#ensurePortal(supplier ? 'OPCION=1&TIPO=4' : DESTINATION, signal, true);
294
- const query = new URLSearchParams({ ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }), FOLIO: folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: String(documentType), ESTADO: '', ORDEN: '', NUM_PAG: '1' });
451
+ const query = new URLSearchParams({
452
+ ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }),
453
+ FOLIO: folio,
454
+ RZN_SOC: '',
455
+ FEC_DESDE: '',
456
+ FEC_HASTA: '',
457
+ TPO_DOC: String(documentType),
458
+ ESTADO: '',
459
+ ORDEN: '',
460
+ NUM_PAG: '1'
461
+ });
295
462
  const history = await this.#portal(historyEndpoint, undefined, `?${query}`, signal);
296
463
  await this.#assertCompany(historyEndpoint);
297
464
  let code;
@@ -311,12 +478,23 @@ class FacturadorGateway {
311
478
  return { stream, contentType: 'application/pdf', filename: `factura-${documentType}-${folio}.pdf` };
312
479
  }, options.signal);
313
480
  }
314
- async #documentXml({ documentType, folio }, supplier, legacy = false) {
481
+ async #documentXml({ documentType, folio }, supplier, legacy = false, exact = false, options) {
315
482
  this.session.assertReady();
316
483
  if (![33, 34, 61].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
317
484
  throw new TypeError('Identidad de documento inválida');
485
+ (0, read_options_1.assertDteXmlReadOptions)(options);
318
486
  await this.#ensurePortal();
319
- const query = new URLSearchParams({ ORIGEN: supplier ? 'RCP' : 'ENV', ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }), FOLIO: folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: String(documentType), ESTADO: '', ORDEN: '', DOWNLOAD: 'XML' });
487
+ const query = new URLSearchParams({
488
+ ORIGEN: supplier ? 'RCP' : 'ENV', ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }),
489
+ FOLIO: folio,
490
+ RZN_SOC: '',
491
+ FEC_DESDE: '',
492
+ FEC_HASTA: '',
493
+ TPO_DOC: String(documentType),
494
+ ESTADO: '',
495
+ ORDEN: '',
496
+ DOWNLOAD: 'XML'
497
+ });
320
498
  return this.session.request(`${sii_http_session_1.FACTURADOR}mipeDownLoad.cgi?${query}`, async (response) => {
321
499
  const bytes = await this.session.readBounded(response, 'mipeDownLoad.cgi');
322
500
  const format = (0, sii_http_session_1.responseFormat)(response, bytes);
@@ -337,17 +515,25 @@ class FacturadorGateway {
337
515
  throw this.session.failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
338
516
  }
339
517
  try {
340
- const identity = { issuerRut: supplier?.formatted ?? this.session.company.formatted, ...(supplier ? { receiverRut: this.session.company.formatted } : {}), folio };
518
+ const identity = {
519
+ issuerRut: supplier?.formatted ?? this.session.company.formatted, ...(supplier ? { receiverRut: this.session.company.formatted } : {}),
520
+ folio
521
+ };
522
+ if (exact)
523
+ return (0, dte_xml_1.parseDteDocumentXmlExact)(bytes, { ...identity, documentType }, options);
341
524
  if (legacy) {
342
525
  if (documentType !== 33 && documentType !== 34)
343
- throw new invoice_xml_1.DteXmlError('SII_XML_INVALID');
344
- return (0, dte_xml_1.parseDteXml)(bytes, { ...identity, documentType });
526
+ throw new contracts_1.DteXmlError('SII_XML_INVALID');
527
+ return (0, dte_xml_1.parseDteXml)(bytes, { ...identity, documentType }, options);
345
528
  }
346
- return (0, dte_xml_1.parseDteDocumentXml)(bytes, { ...identity, documentType });
529
+ return (0, dte_xml_1.parseDteDocumentXml)(bytes, { ...identity, documentType }, options);
347
530
  }
348
531
  catch (error) {
349
- const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
350
- throw this.session.failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
532
+ const code = error instanceof contracts_1.DteXmlError ? error.code : 'SII_XML_INVALID';
533
+ throw this.session.failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, {
534
+ ...format,
535
+ stage: 'XML_PARSE'
536
+ });
351
537
  }
352
538
  }, {}, true);
353
539
  }
@@ -385,7 +571,10 @@ class FacturadorGateway {
385
571
  if (selection && (submitted || hop >= 4))
386
572
  throw this.session.failure('SII_XML_COMPANY_SELECTION_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'COMPANY_SELECTION_REQUIRED', response);
387
573
  return { selection };
388
- }, { ...options, signal }, (destination === DESTINATION || Boolean(signal)) && options.method !== 'POST', true);
574
+ }, {
575
+ ...options,
576
+ signal
577
+ }, (destination === DESTINATION || Boolean(signal)) && options.method !== 'POST', true);
389
578
  if (result.next) {
390
579
  url = result.next;
391
580
  options = {};
@@ -394,7 +583,11 @@ class FacturadorGateway {
394
583
  if (result.selection) {
395
584
  submitted = true;
396
585
  url = `${sii_http_session_1.FACTURADOR}mipeSelEmpresa.cgi`;
397
- options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: result.selection.toString() };
586
+ options = {
587
+ method: 'POST',
588
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
589
+ body: result.selection.toString()
590
+ };
398
591
  continue;
399
592
  }
400
593
  break;
@@ -426,7 +619,12 @@ class FacturadorGateway {
426
619
  throw this.session.failure('SII_SERVICE_ERROR', endpoint, 'PROVIDER_ERROR_PAGE', response, code ? { siiMessageCode: code } : {});
427
620
  }
428
621
  return { text, document };
429
- }, fields === undefined ? { signal } : { method: 'POST', signal, headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: `${sii_http_session_1.FACTURADOR}${endpoint}` }, body: typeof fields === 'string' ? fields : (0, facturador_1.encodePortalForm)(fields) }, Boolean(signal) && fields === undefined);
622
+ }, fields === undefined ? { signal } : {
623
+ method: 'POST',
624
+ signal,
625
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: `${sii_http_session_1.FACTURADOR}${endpoint}` },
626
+ body: typeof fields === 'string' ? fields : (0, facturador_1.encodePortalForm)(fields)
627
+ }, Boolean(signal) && fields === undefined);
430
628
  }
431
629
  #form(page, name, endpoint, alternative) {
432
630
  try {
@@ -437,7 +635,8 @@ class FacturadorGateway {
437
635
  try {
438
636
  return (0, facturador_1.readForm)(page.document, name, alternative);
439
637
  }
440
- catch { /* Only known form actions are allowed. */ }
638
+ catch { /* Only known form actions are allowed. */
639
+ }
441
640
  }
442
641
  const source = name === 'VIEW_EFXP' ? 'mipeGenFacEx.cgi' : name === 'PreViewDTE' ? 'mipeDisplayPreView.cgi' : 'mipeGenXMLFirma.cgi';
443
642
  throw this.session.failure('SII_PROTOCOL_CHANGED', source, 'INVALID_RESPONSE');
@@ -460,7 +659,8 @@ class FacturadorGateway {
460
659
  if (rows.length === 1 && rows[0])
461
660
  return rows[0];
462
661
  }
463
- catch { /* No provider scripts execute. */ }
662
+ catch { /* No provider scripts execute. */
663
+ }
464
664
  throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
465
665
  }
466
666
  #assertFields(fields, expected) {
@@ -6,7 +6,7 @@ export declare function element(node: Html.Node): node is Html.Element;
6
6
  export declare function parsePortalPage(html: string): Html.Document;
7
7
  /** Serialize only inert successful controls; provider scripts are never executed. */
8
8
  export declare function readForm(html: string | Html.Document, name: string, endpoint: string): URLSearchParams;
9
- /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
9
+ /** Decode bounded JSON option tables, never JavaScript expressions. */
10
10
  export declare function readLiteralRows(html: string | Html.Document, variable: string): string[][];
11
11
  /** The final all-zero row is a portal placeholder, never a company address or giro. */
12
12
  export declare function readCompanyOptions(html: string | Html.Document): Pick<CompanyInfo, 'addresses' | 'businessActivities'>;
@@ -13,13 +13,15 @@ exports.encodeUnsignedDteXml = encodeUnsignedDteXml;
13
13
  exports.readVisiblePortalText = readVisiblePortalText;
14
14
  exports.hasInteractiveCaptcha = hasInteractiveCaptcha;
15
15
  const parse5_1 = require("parse5");
16
- const invoice_xml_1 = require("../domain/invoice-xml");
16
+ const contracts_1 = require("../contracts");
17
17
  const PORTAL = 'https://www1.sii.cl/cgi-bin/Portal001/';
18
18
  const MAX_HTML_BYTES = 2 * 1024 * 1024;
19
19
  const ROW_VARIABLES = new Set(['emisorDir', 'emisorActEco', 'recptorDir', 'recptoActEco']);
20
20
  const decoder = new TextDecoder('windows-1252', { fatal: true });
21
21
  const cp1252 = new Map(Array.from({ length: 256 }, (_, byte) => [decoder.decode(Uint8Array.of(byte)), byte]));
22
- function invalid(reason = 'INVALID_RESPONSE') { throw new TypeError(`Formulario del facturador inválido: ${reason}`); }
22
+ function invalid(reason = 'INVALID_RESPONSE') {
23
+ throw new TypeError(`Formulario del facturador inválido: ${reason}`);
24
+ }
23
25
  function attr(element, name) {
24
26
  return element.attrs.find(attribute => attribute.name === name)?.value;
25
27
  }
@@ -127,7 +129,7 @@ function readForm(html, name, endpoint) {
127
129
  }
128
130
  return fields;
129
131
  }
130
- /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
132
+ /** Decode bounded JSON option tables, never JavaScript expressions. */
131
133
  function readLiteralRows(html, variable) {
132
134
  if (!ROW_VARIABLES.has(variable))
133
135
  invalid();
@@ -140,7 +142,7 @@ function readLiteralRows(html, variable) {
140
142
  declarations.push(match[1]);
141
143
  }
142
144
  const literal = declarations[0];
143
- if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 16 * 1024)
145
+ if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 256 * 1024)
144
146
  invalid();
145
147
  let rows;
146
148
  try {
@@ -149,7 +151,8 @@ function readLiteralRows(html, variable) {
149
151
  catch {
150
152
  invalid();
151
153
  }
152
- if (!Array.isArray(rows) || rows.length > 20 || !rows.every((row) => Array.isArray(row) && row.length > 0 && row.length <= 5 && row.every(value => typeof value === 'string' && value.length <= 200)))
154
+ const maxRows = variable.endsWith('Dir') ? 1000 : 100;
155
+ if (!Array.isArray(rows) || rows.length > maxRows || !rows.every((row) => Array.isArray(row) && row.length > 0 && row.length <= 5 && row.every(value => typeof value === 'string' && value.length <= 200)))
153
156
  invalid();
154
157
  return rows;
155
158
  }
@@ -157,8 +160,11 @@ function readLiteralRows(html, variable) {
157
160
  function readCompanyOptions(html) {
158
161
  const rows = (variable, widths) => readLiteralRows(html, variable)
159
162
  .map(row => row.map(value => value.trim()))
160
- .filter(row => { if (!widths.includes(row.length))
161
- invalid(); return !row.every(value => value === '0'); })
163
+ .filter(row => {
164
+ if (!widths.includes(row.length))
165
+ invalid();
166
+ return !row.every(value => value === '0');
167
+ })
162
168
  .map(row => {
163
169
  if (!row[0] || !row[1] || row.some(value => /[\u0000-\u001f\u007f]/u.test(value)))
164
170
  invalid();
@@ -190,8 +196,10 @@ function readPortalHtml(bytes) {
190
196
  }
191
197
  /** Encode unsigned XML as declared, without changing its text or silently truncating Unicode. */
192
198
  function encodeUnsignedDteXml(value) {
193
- const invalidXml = () => { throw new TypeError('XML sin firmar inválido'); };
194
- if (typeof value !== 'string' || !value.length || value.length > invoice_xml_1.MAX_DTE_XML_BYTES)
199
+ const invalidXml = () => {
200
+ throw new TypeError('XML sin firmar inválido');
201
+ };
202
+ if (typeof value !== 'string' || !value.length || value.length > contracts_1.MAX_DTE_XML_BYTES)
195
203
  invalidXml();
196
204
  const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(value.slice(0, 200))?.[1]?.toUpperCase() ?? 'UTF-8';
197
205
  if (declared === 'ISO-8859-1') {
@@ -200,7 +208,7 @@ function encodeUnsignedDteXml(value) {
200
208
  return Buffer.from(value, 'latin1');
201
209
  }
202
210
  if (declared === 'UTF-8' || declared === 'UTF8') {
203
- if (Buffer.byteLength(value, 'utf8') > invoice_xml_1.MAX_DTE_XML_BYTES)
211
+ if (Buffer.byteLength(value, 'utf8') > contracts_1.MAX_DTE_XML_BYTES)
204
212
  invalidXml();
205
213
  const bytes = Buffer.from(value, 'utf8');
206
214
  if (bytes.toString('utf8') !== value)
@@ -80,7 +80,8 @@ async function readInvoicePdfStream(response, session, endpoint, signal, trackSt
80
80
  const prefix = new Uint8Array(5);
81
81
  let prefixSize = 0, size = 0, reading = false;
82
82
  let cancellation;
83
- const cancelSource = () => cancellation ??= reader.cancel().catch(() => { });
83
+ const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
84
+ });
84
85
  const onAbort = () => {
85
86
  void cancelSource();
86
87
  stream?.destroy(session.abortFailure(signal, endpoint));
@@ -149,12 +150,18 @@ async function readInvoicePdfStream(response, session, endpoint, signal, trackSt
149
150
  this.push(value);
150
151
  return;
151
152
  }
152
- })().catch(error => { reading = false; this.destroy(error instanceof sii_error_1.SiiError ? error : session.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response)); });
153
+ })().catch(error => {
154
+ reading = false;
155
+ this.destroy(error instanceof sii_error_1.SiiError ? error : session.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response));
156
+ });
153
157
  },
154
158
  destroy(error, callback) {
155
159
  signal.removeEventListener('abort', onAbort);
156
160
  prefixChunks.length = 0;
157
- void cancelSource().then(() => { reader.releaseLock(); callback(error); });
161
+ void cancelSource().then(() => {
162
+ reader.releaseLock();
163
+ callback(error);
164
+ });
158
165
  },
159
166
  });
160
167
  // Track before yielding: abort can happen between creation and public handoff.