documents.js 1.51.0 → 1.53.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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AttributeSchema, BinaryPartSchema, CommentSchema, CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, DefinedNameSchema, PackageSchema, PartSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, attr, attr as attr$1, base64ToBytes, base64ToBytes as base64ToBytes$1, buildXlsxPackage, buildXml, bytesToBase64, bytesToBase64 as bytesToBase64$1, childrenWithTag, compactCodec, compactPackageCodec, decodeCompactPackage, decodeEntities, decodePackage, decodePackage as decodePackage$1, elementsWithTag, elementsWithTag as elementsWithTag$1, encodeCompactPackage, encodePackage, encodePackage as encodePackage$1, fromCompact, isCompactXmlNode, isXmlNode, packageCodec, parsePackage, parseXml, readDocx, readPptx, readXlsxContent, resolveRelationships, resolveRelationships as resolveRelationships$1, rootElement, rootElement as rootElement$1, serializePackage, textContent as textContent$1, textContent as textContent$2, toCompact, unzipPackage, walk, xmlCodec, zipPackage } from "ooxml.js";
2
- import { COLOR_BLACK, COLOR_BLACK as COLOR_BLACK$1, ContentBlockSchema, ContentCellValueSchema, ContentDrawPageSchema, ContentDrawPageSchema as ContentDrawPageSchema$1, ContentImageBlockSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentPathPointSchema, ContentPathSegmentSchema, ContentRunSchema, ContentSectionSchema, ContentSectionSchema as ContentSectionSchema$1, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSheetSchema as ContentSheetSchema$1, ContentSlideSchema, ContentSlideSchema as ContentSlideSchema$1, ContentStrokeSchema, ContentSubpathSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, ContentVectorSchema, DEFAULT_LAYOUT_FONT, LAYOUT_FORMAT_VERSION, LAYOUT_FORMAT_VERSION as LAYOUT_FORMAT_VERSION$1, LayoutDocumentSchema, LayoutMetadataSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, colorToRgbHex, isContentBlock, rgbHexToColor } from "document-content-model";
2
+ import { COLOR_BLACK, COLOR_BLACK as COLOR_BLACK$1, ContentBlockSchema, ContentCellValueSchema, ContentDrawPageSchema, ContentDrawPageSchema as ContentDrawPageSchema$1, ContentImageBlockSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentPathPointSchema, ContentPathSegmentSchema, ContentRunSchema, ContentSectionSchema, ContentSectionSchema as ContentSectionSchema$1, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSheetSchema as ContentSheetSchema$1, ContentSlideSchema, ContentSlideSchema as ContentSlideSchema$1, ContentStrokeSchema, ContentSubpathSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, ContentVectorSchema, DEFAULT_LAYOUT_FONT, DOCUMENT_PACKAGE_FORMAT_VERSION, LAYOUT_FORMAT_VERSION, LAYOUT_FORMAT_VERSION as LAYOUT_FORMAT_VERSION$1, LayoutDocumentSchema, LayoutMetadataSchema, PAGE_SIZE_A4, PAGE_SIZE_LETTER, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, colorToRgbHex, isContentBlock, rgbHexToColor } from "document-content-model";
3
3
  import { z } from "zod";
4
4
  import { ODF_MEDIA_TYPES, StyleRegistry, applyOdfTransform, attrValue, base64ToBytes as base64ToBytes$2, buildOdfSubpaths, bytesToBase64 as bytesToBase64$2, childrenWithTag as childrenWithTag$1, decodeOdfText, decodePackage as decodePackage$2, encodePackage as encodePackage$2, findChildElement, findStyleElement, formatOdfColor, formatOdfLength, parseBox, parseCellReference, parseLinePoints, parseMargins, parseOdfColor, parseOdfLength, parseOdfPathData, parseOdfViewBox, parsePageSize, readDrawFrame, readManifest, readOdbInventory, readOdfFormula, readOdfMetadata, readOdfParagraph, readOdfTable, readOdg, readOdm, readOdp, readOds, readOdt, resolveOdfShapeGeometry, resolvePageLayoutProperties, resolveStyle, rootElement as rootElement$2, setDocumentMediaType, syncManifest, syncManifest as syncManifest$1, xmlnsAttributes } from "odf.js";
5
5
  import { Unzlib, inflateSync, unzlibSync, zlibSync } from "fflate";
@@ -9210,12 +9210,12 @@ function textToPdfString(text) {
9210
9210
  }
9211
9211
  return pdfHexString(bytes);
9212
9212
  }
9213
- function pad2(n) {
9213
+ function pad2$2(n) {
9214
9214
  return n.toString().padStart(2, "0");
9215
9215
  }
9216
9216
  function formatPdfDate(iso) {
9217
9217
  const date = new Date(iso);
9218
- return `D:${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`;
9218
+ return `D:${date.getUTCFullYear()}${pad2$2(date.getUTCMonth() + 1)}${pad2$2(date.getUTCDate())}${pad2$2(date.getUTCHours())}${pad2$2(date.getUTCMinutes())}${pad2$2(date.getUTCSeconds())}Z`;
9219
9219
  }
9220
9220
  function buildInfoDict(doc) {
9221
9221
  const entries = /* @__PURE__ */ new Map();
@@ -14570,6 +14570,1030 @@ function buildOdbTableCsv(tables, tableName) {
14570
14570
  return new TextEncoder().encode(`${lines.join("\r\n")}\r\n`);
14571
14571
  }
14572
14572
  //#endregion
14573
+ //#region src/hsqldb/rowformat.ts
14574
+ var HsqldbRowFormatError = class extends Error {
14575
+ constructor(message) {
14576
+ super(`HSQLDB binary row format error: ${message}`);
14577
+ this.name = "HsqldbRowFormatError";
14578
+ }
14579
+ };
14580
+ const SQL_TYPE_NAME_TO_CODE = {
14581
+ INTEGER: 4,
14582
+ INT: 4,
14583
+ IDENTITY: 4,
14584
+ DOUBLE: 8,
14585
+ FLOAT: 6,
14586
+ REAL: 7,
14587
+ VARCHAR: 12,
14588
+ CHAR: 1,
14589
+ CHARACTER: 1,
14590
+ LONGVARCHAR: -1,
14591
+ VARCHAR_IGNORECASE: 100,
14592
+ DATE: 91,
14593
+ TIME: 92,
14594
+ TIMESTAMP: 93,
14595
+ DATETIME: 93,
14596
+ DECIMAL: 3,
14597
+ NUMERIC: 2,
14598
+ BIT: 16,
14599
+ BOOLEAN: 16,
14600
+ TINYINT: -6,
14601
+ SMALLINT: 5,
14602
+ BIGINT: -5
14603
+ };
14604
+ const UNSUPPORTED_SQL_TYPE_NAMES = /* @__PURE__ */ new Set([
14605
+ "BINARY",
14606
+ "VARBINARY",
14607
+ "LONGVARBINARY",
14608
+ "OTHER",
14609
+ "OBJECT"
14610
+ ]);
14611
+ const LEADING_WORD_RE = /^([A-Za-z_][A-Za-z0-9_]*)/;
14612
+ function resolveHsqldbTypeCode(declaredType) {
14613
+ const word = LEADING_WORD_RE.exec(declaredType.trim())?.[1]?.toUpperCase();
14614
+ if (word === void 0) throw new HsqldbRowFormatError(`cannot resolve a SQL type name from column type clause "${declaredType}"`);
14615
+ if (UNSUPPORTED_SQL_TYPE_NAMES.has(word)) throw new HsqldbRowFormatError(`column type "${word}" has no document-content-model ContentCellValue equivalent (binary/object column types are not representable) -- from declared type "${declaredType}"`);
14616
+ const code = SQL_TYPE_NAME_TO_CODE[word];
14617
+ if (code === void 0) throw new HsqldbRowFormatError(`unrecognised HSQLDB column type "${word}" -- from declared type "${declaredType}"`);
14618
+ return code;
14619
+ }
14620
+ var HsqldbDataCursor = class {
14621
+ bytes;
14622
+ view;
14623
+ position;
14624
+ constructor(bytes, offset = 0) {
14625
+ this.bytes = bytes;
14626
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14627
+ this.position = offset;
14628
+ }
14629
+ readUint8() {
14630
+ const value = this.view.getUint8(this.position);
14631
+ this.position += 1;
14632
+ return value;
14633
+ }
14634
+ readInt16() {
14635
+ const value = this.view.getInt16(this.position, false);
14636
+ this.position += 2;
14637
+ return value;
14638
+ }
14639
+ readInt32() {
14640
+ const value = this.view.getInt32(this.position, false);
14641
+ this.position += 4;
14642
+ return value;
14643
+ }
14644
+ readBigInt64() {
14645
+ const value = this.view.getBigInt64(this.position, false);
14646
+ this.position += 8;
14647
+ return value;
14648
+ }
14649
+ readFloat64() {
14650
+ const value = this.view.getFloat64(this.position, false);
14651
+ this.position += 8;
14652
+ return value;
14653
+ }
14654
+ readBytes(length) {
14655
+ const slice = this.bytes.subarray(this.position, this.position + length);
14656
+ this.position += length;
14657
+ return slice;
14658
+ }
14659
+ };
14660
+ function readModifiedUtf8(bytes) {
14661
+ let result = "";
14662
+ let i = 0;
14663
+ while (i < bytes.length) {
14664
+ const b0 = bytes[i];
14665
+ if (b0 === void 0) throw new HsqldbRowFormatError("truncated modified-UTF-8 byte sequence");
14666
+ if (b0 > 0 && b0 < 128) {
14667
+ result += String.fromCharCode(b0);
14668
+ i += 1;
14669
+ continue;
14670
+ }
14671
+ const leadNibble = b0 >> 4;
14672
+ if (leadNibble === 12 || leadNibble === 13) {
14673
+ const b1 = bytes[i + 1];
14674
+ if (b1 === void 0 || (b1 & 192) !== 128) throw new HsqldbRowFormatError("malformed modified-UTF-8 2-byte sequence");
14675
+ result += String.fromCharCode((b0 & 31) << 6 | b1 & 63);
14676
+ i += 2;
14677
+ continue;
14678
+ }
14679
+ if (leadNibble === 14) {
14680
+ const b1 = bytes[i + 1];
14681
+ const b2 = bytes[i + 2];
14682
+ if (b1 === void 0 || b2 === void 0 || (b1 & 192) !== 128 || (b2 & 192) !== 128) throw new HsqldbRowFormatError("malformed modified-UTF-8 3-byte sequence");
14683
+ result += String.fromCharCode((b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63);
14684
+ i += 3;
14685
+ continue;
14686
+ }
14687
+ throw new HsqldbRowFormatError(`malformed modified-UTF-8 lead byte 0x${b0.toString(16)}`);
14688
+ }
14689
+ return result;
14690
+ }
14691
+ function signedBigIntFromBytes(bytes) {
14692
+ if (bytes.length === 0) return 0n;
14693
+ let magnitude = 0n;
14694
+ for (const byte of bytes) magnitude = magnitude << 8n | BigInt(byte);
14695
+ const firstByte = bytes[0];
14696
+ return firstByte !== void 0 && (firstByte & 128) !== 0 ? magnitude - (1n << BigInt(8 * bytes.length)) : magnitude;
14697
+ }
14698
+ function decimalNumberFromUnscaled(unscaled, scale) {
14699
+ const isNegative = unscaled < 0n;
14700
+ const magnitudeDigits = (isNegative ? -unscaled : unscaled).toString();
14701
+ const sign = isNegative ? "-" : "";
14702
+ if (scale <= 0) return Number(`${sign}${magnitudeDigits}${"0".repeat(-scale)}`);
14703
+ const padded = magnitudeDigits.padStart(scale + 1, "0");
14704
+ const wholePart = padded.slice(0, padded.length - scale);
14705
+ const fractionPart = padded.slice(padded.length - scale);
14706
+ return Number(`${sign}${wholePart}.${fractionPart}`);
14707
+ }
14708
+ function pad2$1(n) {
14709
+ return String(n).padStart(2, "0");
14710
+ }
14711
+ function epochMillisToLocalDate(epochMillis) {
14712
+ return new Date(Number(epochMillis));
14713
+ }
14714
+ function formatLocalDate(epochMillis) {
14715
+ const date = epochMillisToLocalDate(epochMillis);
14716
+ return `${date.getFullYear()}-${pad2$1(date.getMonth() + 1)}-${pad2$1(date.getDate())}`;
14717
+ }
14718
+ function formatLocalTime(epochMillis) {
14719
+ const date = epochMillisToLocalDate(epochMillis);
14720
+ const base = `${pad2$1(date.getHours())}:${pad2$1(date.getMinutes())}:${pad2$1(date.getSeconds())}`;
14721
+ return date.getMilliseconds() === 0 ? base : `${base}.${String(date.getMilliseconds()).padStart(3, "0")}`;
14722
+ }
14723
+ function formatLocalTimestamp(epochMillis, nanos) {
14724
+ const date = epochMillisToLocalDate(epochMillis);
14725
+ const base = `${date.getFullYear()}-${pad2$1(date.getMonth() + 1)}-${pad2$1(date.getDate())} ${pad2$1(date.getHours())}:${pad2$1(date.getMinutes())}:${pad2$1(date.getSeconds())}`;
14726
+ return nanos === 0 ? base : `${base}.${String(nanos).padStart(9, "0")}`;
14727
+ }
14728
+ function readHsqldbColumnValue(cursor, typeCode) {
14729
+ if (cursor.readUint8() === 0) return { kind: "empty" };
14730
+ switch (typeCode) {
14731
+ case 1:
14732
+ case 12:
14733
+ case -1:
14734
+ case 100: {
14735
+ const byteLength = cursor.readInt32();
14736
+ return {
14737
+ kind: "string",
14738
+ value: readModifiedUtf8(cursor.readBytes(byteLength))
14739
+ };
14740
+ }
14741
+ case 5:
14742
+ case -6: return {
14743
+ kind: "number",
14744
+ value: cursor.readInt16()
14745
+ };
14746
+ case 4: return {
14747
+ kind: "number",
14748
+ value: cursor.readInt32()
14749
+ };
14750
+ case -5: return {
14751
+ kind: "number",
14752
+ value: Number(cursor.readBigInt64())
14753
+ };
14754
+ case 6:
14755
+ case 7:
14756
+ case 8: return {
14757
+ kind: "number",
14758
+ value: cursor.readFloat64()
14759
+ };
14760
+ case 2:
14761
+ case 3: {
14762
+ const byteLength = cursor.readInt32();
14763
+ const magnitudeBytes = cursor.readBytes(byteLength);
14764
+ const scale = cursor.readInt32();
14765
+ return {
14766
+ kind: "number",
14767
+ value: decimalNumberFromUnscaled(signedBigIntFromBytes(magnitudeBytes), scale)
14768
+ };
14769
+ }
14770
+ case 16: return {
14771
+ kind: "boolean",
14772
+ value: cursor.readUint8() !== 0
14773
+ };
14774
+ case 91: return {
14775
+ kind: "date",
14776
+ value: formatLocalDate(cursor.readBigInt64())
14777
+ };
14778
+ case 92: return {
14779
+ kind: "time",
14780
+ value: formatLocalTime(cursor.readBigInt64())
14781
+ };
14782
+ case 93: return {
14783
+ kind: "date",
14784
+ value: formatLocalTimestamp(cursor.readBigInt64(), cursor.readInt32())
14785
+ };
14786
+ default: throw new HsqldbRowFormatError(`unsupported SQL type code ${typeCode} while decoding a row value`);
14787
+ }
14788
+ }
14789
+ //#endregion
14790
+ //#region src/hsqldb/cache.ts
14791
+ const SUPPORTED_COMPATIBLE_VERSION_PREFIXES = ["1.7.", "1.8."];
14792
+ function parseHsqldbProperties(text) {
14793
+ const props = /* @__PURE__ */ new Map();
14794
+ for (const rawLine of text.split("\n")) {
14795
+ const line = rawLine.trim();
14796
+ if (line.length === 0 || line.startsWith("#")) continue;
14797
+ const eq = line.indexOf("=");
14798
+ if (eq === -1) continue;
14799
+ props.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
14800
+ }
14801
+ const compatibleVersion = props.get("hsqldb.compatible_version");
14802
+ if (compatibleVersion !== void 0 && !SUPPORTED_COMPATIBLE_VERSION_PREFIXES.some((prefix) => compatibleVersion.startsWith(prefix))) throw new HsqldbRowFormatError(`database/properties declares hsqldb.compatible_version "${compatibleVersion}" -- this decoder is scoped to the HSQLDB 1.7.x/1.8.x CACHED-table row-store format (the version LibreOffice's own embedded driver ships) and does not know this version's own on-disk row-store layout`);
14803
+ return {
14804
+ cacheFileScale: Number(props.get("hsqldb.cache_file_scale") ?? "1") === 1 ? 1 : 8,
14805
+ compatibleVersion
14806
+ };
14807
+ }
14808
+ const SET_TABLE_INDEX_RE = /^SET\s+TABLE\s+("(?:[^"]|"")*"|[A-Za-z_][A-Za-z0-9_$#]*)\s+INDEX'((?:[^']|'')*)'\s*$/i;
14809
+ function unquoteIdentifier(raw) {
14810
+ if (raw.length >= 2 && raw.startsWith("\"") && raw.endsWith("\"")) return raw.slice(1, -1).replace(/""/g, "\"");
14811
+ return raw;
14812
+ }
14813
+ function parseHsqldbIndexRoots(scriptText) {
14814
+ const roots = /* @__PURE__ */ new Map();
14815
+ for (const rawLine of scriptText.split("\n")) {
14816
+ const match = SET_TABLE_INDEX_RE.exec(rawLine.trim());
14817
+ if (match === null) continue;
14818
+ const rawName = match[1] ?? "";
14819
+ const tokensText = match[2] ?? "";
14820
+ const tableName = unquoteIdentifier(rawName).toUpperCase();
14821
+ const tokens = tokensText.trim().length === 0 ? [] : tokensText.trim().split(/\s+/);
14822
+ if (tokens.length !== 2) throw new HsqldbRowFormatError(`table "${tableName}" declares ${Math.max(tokens.length - 1, 0)} index root(s) in its SET TABLE...INDEX line -- only a single-index (primary-key-only) CACHED table is supported`);
14823
+ const rootToken = tokens[0] ?? "";
14824
+ const rootPos = Number(rootToken);
14825
+ if (!Number.isInteger(rootPos)) throw new HsqldbRowFormatError(`table "${tableName}"'s SET TABLE...INDEX line has a non-integer root position "${rootToken}"`);
14826
+ roots.set(tableName, rootPos);
14827
+ }
14828
+ return roots;
14829
+ }
14830
+ function readHsqldbCachedTableRows(dataBytes, rootPos, cacheFileScale, columns) {
14831
+ const typeCodes = columns.map((column) => resolveHsqldbTypeCode(column.type));
14832
+ const results = [];
14833
+ function visit(pos) {
14834
+ if (pos <= 0) return;
14835
+ const byteOffset = pos * cacheFileScale;
14836
+ if (byteOffset < 0 || byteOffset + 4 > dataBytes.length) throw new HsqldbRowFormatError(`row position ${pos} (byte offset ${byteOffset}) falls outside database/data (${dataBytes.length} bytes)`);
14837
+ const cursor = new HsqldbDataCursor(dataBytes, byteOffset);
14838
+ const storageSize = cursor.readInt32();
14839
+ const rowEnd = byteOffset + storageSize;
14840
+ if (storageSize <= 0 || rowEnd > dataBytes.length) throw new HsqldbRowFormatError(`row at position ${pos} declares an invalid storage size ${storageSize}`);
14841
+ cursor.readInt32();
14842
+ const iLeft = cursor.readInt32();
14843
+ const iRight = cursor.readInt32();
14844
+ cursor.readInt32();
14845
+ const values = columns.map((_column, index) => {
14846
+ const typeCode = typeCodes[index];
14847
+ if (typeCode === void 0) throw new HsqldbRowFormatError("internal error: column/type-code alignment failure");
14848
+ return readHsqldbColumnValue(cursor, typeCode);
14849
+ });
14850
+ if (cursor.position > rowEnd) throw new HsqldbRowFormatError(`row at position ${pos} overran its own declared storage size (consumed ${cursor.position - byteOffset} bytes, declared ${storageSize})`);
14851
+ visit(iLeft);
14852
+ results.push(values);
14853
+ visit(iRight);
14854
+ }
14855
+ visit(rootPos);
14856
+ return results;
14857
+ }
14858
+ function decodeHsqldbCachedTables(tables, scriptText, dataBytes, propertiesText) {
14859
+ const { cacheFileScale } = parseHsqldbProperties(propertiesText);
14860
+ const roots = parseHsqldbIndexRoots(scriptText);
14861
+ return tables.map((table) => {
14862
+ const rootPos = roots.get(table.tableName.toUpperCase());
14863
+ if (rootPos === void 0) return table;
14864
+ const rows = readHsqldbCachedTableRows(dataBytes, rootPos, cacheFileScale, table.columns);
14865
+ return {
14866
+ ...table,
14867
+ rows
14868
+ };
14869
+ });
14870
+ }
14871
+ //#endregion
14872
+ //#region src/firebird/reader.ts
14873
+ var FirebirdBackupParseError = class extends Error {
14874
+ offset;
14875
+ constructor(message, offset) {
14876
+ super(`Firebird backup parse error at byte offset ${offset}: ${message}`);
14877
+ this.name = "FirebirdBackupParseError";
14878
+ this.offset = offset;
14879
+ }
14880
+ };
14881
+ var FirebirdBackupReader = class {
14882
+ bytes;
14883
+ position = 0;
14884
+ constructor(bytes) {
14885
+ this.bytes = bytes;
14886
+ }
14887
+ get offset() {
14888
+ return this.position;
14889
+ }
14890
+ atEnd() {
14891
+ return this.position >= this.bytes.length;
14892
+ }
14893
+ readTag() {
14894
+ const byte = this.bytes[this.position];
14895
+ if (byte === void 0) throw new FirebirdBackupParseError("unexpected end of stream reading a tag byte", this.position);
14896
+ this.position++;
14897
+ return byte;
14898
+ }
14899
+ peekTag() {
14900
+ return this.bytes[this.position];
14901
+ }
14902
+ readLengthByte() {
14903
+ const byte = this.bytes[this.position];
14904
+ if (byte === void 0) throw new FirebirdBackupParseError("unexpected end of stream reading an attribute length byte", this.position);
14905
+ this.position++;
14906
+ return byte;
14907
+ }
14908
+ readRawBytes(length) {
14909
+ if (this.position + length > this.bytes.length) throw new FirebirdBackupParseError(`unexpected end of stream reading ${length} raw byte(s)`, this.position);
14910
+ const slice = this.bytes.subarray(this.position, this.position + length);
14911
+ this.position += length;
14912
+ return slice;
14913
+ }
14914
+ readAttributeBytes() {
14915
+ const length = this.readLengthByte();
14916
+ return this.readRawBytes(length);
14917
+ }
14918
+ readInt32Attribute() {
14919
+ const bytes = this.readAttributeBytes();
14920
+ if (bytes.length !== 4) throw new FirebirdBackupParseError(`expected a 4-byte int32 attribute, found ${bytes.length} byte(s)`, this.position);
14921
+ return (bytes[0] ?? 0) | (bytes[1] ?? 0) << 8 | (bytes[2] ?? 0) << 16 | (bytes[3] ?? 0) << 24;
14922
+ }
14923
+ readTextAttribute() {
14924
+ const bytes = this.readAttributeBytes();
14925
+ return new TextDecoder("utf-8").decode(bytes);
14926
+ }
14927
+ skipAttributeValue() {
14928
+ this.readAttributeBytes();
14929
+ }
14930
+ skipFlatRecordAttributes() {
14931
+ for (;;) {
14932
+ if (this.readTag() === 0) return;
14933
+ this.skipAttributeValue();
14934
+ }
14935
+ }
14936
+ readRawPayload(length) {
14937
+ return this.readRawBytes(length);
14938
+ }
14939
+ readBlobSegmentLength() {
14940
+ return this.readLengthByte() | this.readLengthByte() << 8;
14941
+ }
14942
+ readSignedByte() {
14943
+ const byte = this.bytes[this.position];
14944
+ if (byte === void 0) throw new FirebirdBackupParseError("unexpected end of stream reading a compression control byte", this.position);
14945
+ this.position++;
14946
+ return byte >= 128 ? byte - 256 : byte;
14947
+ }
14948
+ readCompressedPayload(decompressedLength) {
14949
+ const output = new Uint8Array(decompressedLength);
14950
+ let written = 0;
14951
+ while (written < decompressedLength) {
14952
+ const count = this.readSignedByte();
14953
+ if (count > 0) {
14954
+ const remaining = decompressedLength - written;
14955
+ const take = Math.min(count, remaining);
14956
+ const literal = this.readRawBytes(take);
14957
+ output.set(literal, written);
14958
+ written += take;
14959
+ } else if (count < 0) {
14960
+ const repeatCount = Math.min(-count, decompressedLength - written);
14961
+ const fillByte = this.readLengthByte();
14962
+ output.fill(fillByte, written, written + repeatCount);
14963
+ written += repeatCount;
14964
+ }
14965
+ }
14966
+ return output;
14967
+ }
14968
+ };
14969
+ var XdrReader = class {
14970
+ bytes;
14971
+ position;
14972
+ end;
14973
+ constructor(bytes, start = 0, end = bytes.length) {
14974
+ this.bytes = bytes;
14975
+ this.position = start;
14976
+ this.end = end;
14977
+ }
14978
+ get offset() {
14979
+ return this.position;
14980
+ }
14981
+ atEnd() {
14982
+ return this.position >= this.end;
14983
+ }
14984
+ readInt32() {
14985
+ if (this.position + 4 > this.end) throw new FirebirdBackupParseError("unexpected end of XDR data reading a 4-byte integer", this.position);
14986
+ const b0 = this.bytes[this.position] ?? 0;
14987
+ const b1 = this.bytes[this.position + 1] ?? 0;
14988
+ const b2 = this.bytes[this.position + 2] ?? 0;
14989
+ const b3 = this.bytes[this.position + 3] ?? 0;
14990
+ this.position += 4;
14991
+ return b0 << 24 | b1 << 16 | b2 << 8 | b3 | 0;
14992
+ }
14993
+ readInt16() {
14994
+ return this.readInt32() << 16 >> 16;
14995
+ }
14996
+ readInt64() {
14997
+ const high = this.readInt32();
14998
+ const low = this.readInt32();
14999
+ return BigInt(high) << 32n | BigInt(low) & 4294967295n;
15000
+ }
15001
+ readDouble() {
15002
+ if (this.position + 8 > this.end) throw new FirebirdBackupParseError("unexpected end of XDR data reading an 8-byte double", this.position);
15003
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
15004
+ for (let i = 0; i < 8; i++) view.setUint8(i, this.bytes[this.position + i] ?? 0);
15005
+ this.position += 8;
15006
+ return view.getFloat64(0, false);
15007
+ }
15008
+ readFloat() {
15009
+ if (this.position + 4 > this.end) throw new FirebirdBackupParseError("unexpected end of XDR data reading a 4-byte float", this.position);
15010
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4));
15011
+ for (let i = 0; i < 4; i++) view.setUint8(i, this.bytes[this.position + i] ?? 0);
15012
+ this.position += 4;
15013
+ return view.getFloat32(0, false);
15014
+ }
15015
+ readOpaque(len) {
15016
+ if (this.position + len > this.end) throw new FirebirdBackupParseError(`unexpected end of XDR data reading ${len} opaque byte(s)`, this.position);
15017
+ const slice = this.bytes.subarray(this.position, this.position + len);
15018
+ this.position += len;
15019
+ const padding = (4 - len % 4) % 4;
15020
+ this.position += padding;
15021
+ return slice;
15022
+ }
15023
+ };
15024
+ const BLR_TO_PHYSICAL_TYPE = /* @__PURE__ */ new Map([
15025
+ [7, "short"],
15026
+ [8, "long"],
15027
+ [9, "quad"],
15028
+ [10, "real"],
15029
+ [11, "double"],
15030
+ [12, "sql_date"],
15031
+ [13, "sql_time"],
15032
+ [14, "text"],
15033
+ [15, "text"],
15034
+ [16, "int64"],
15035
+ [23, "boolean"],
15036
+ [24, "dec64"],
15037
+ [25, "dec128"],
15038
+ [26, "int128"],
15039
+ [27, "double"],
15040
+ [28, "unsupported-tz"],
15041
+ [29, "unsupported-tz"],
15042
+ [30, "unsupported-tz"],
15043
+ [31, "unsupported-tz"],
15044
+ [35, "timestamp"],
15045
+ [37, "varying"],
15046
+ [38, "varying"],
15047
+ [40, "cstring"],
15048
+ [41, "cstring"],
15049
+ [261, "blob"]
15050
+ ]);
15051
+ var FirebirdUnsupportedFieldTypeError = class extends Error {
15052
+ blrType;
15053
+ constructor(blrType) {
15054
+ super(`Firebird backup: field has BLR type ${blrType}, which is not a recognised column datatype opcode for a Firebird-embedded .odb's own user/system tables`);
15055
+ this.name = "FirebirdUnsupportedFieldTypeError";
15056
+ this.blrType = blrType;
15057
+ }
15058
+ };
15059
+ function decodeBlrType(blrType) {
15060
+ const physical = BLR_TO_PHYSICAL_TYPE.get(blrType);
15061
+ if (physical === void 0) throw new FirebirdUnsupportedFieldTypeError(blrType);
15062
+ return physical;
15063
+ }
15064
+ function describeFieldType(physical, lengthBytes, scale, characterLength) {
15065
+ switch (physical) {
15066
+ case "short": return scale === 0 ? "SMALLINT" : `NUMERIC(4,${-scale})`;
15067
+ case "long": return scale === 0 ? "INTEGER" : `NUMERIC(9,${-scale})`;
15068
+ case "int64": return scale === 0 ? "BIGINT" : `NUMERIC(18,${-scale})`;
15069
+ case "real": return "FLOAT";
15070
+ case "double": return "DOUBLE PRECISION";
15071
+ case "sql_date": return "DATE";
15072
+ case "sql_time": return "TIME";
15073
+ case "timestamp": return "TIMESTAMP";
15074
+ case "text": return `CHAR(${characterLength ?? lengthBytes})`;
15075
+ case "varying": return `VARCHAR(${characterLength ?? lengthBytes})`;
15076
+ case "cstring": return `CSTRING(${characterLength ?? lengthBytes})`;
15077
+ case "boolean": return "BOOLEAN";
15078
+ case "blob": return "BLOB";
15079
+ case "quad": return "ARRAY";
15080
+ case "int128": return `NUMERIC(38,${-scale})`;
15081
+ case "dec64": return "DECFLOAT(16)";
15082
+ case "dec128": return "DECFLOAT(34)";
15083
+ case "unsupported-tz": return "TIMESTAMP/TIME WITH TIME ZONE";
15084
+ }
15085
+ }
15086
+ //#endregion
15087
+ //#region src/firebird/schema.ts
15088
+ const REC_FIELD = 4;
15089
+ const REC_RELATION_END$1 = 9;
15090
+ var FirebirdSchemaParseError = class extends Error {
15091
+ constructor(message) {
15092
+ super(`Firebird backup schema parse error: ${message}`);
15093
+ this.name = "FirebirdSchemaParseError";
15094
+ }
15095
+ };
15096
+ const ATT_RELATION_NAME$1 = 1;
15097
+ const ATT_FIELD_NAME = 1;
15098
+ const ATT_FIELD_TYPE = 8;
15099
+ const ATT_FIELD_LENGTH = 10;
15100
+ const ATT_FIELD_SCALE = 11;
15101
+ const ATT_FIELD_COMPUTED_FLAG = 23;
15102
+ const ATT_FIELD_CHARACTER_LENGTH = 41;
15103
+ function readField(reader) {
15104
+ let name;
15105
+ let blrType;
15106
+ let lengthBytes = 0;
15107
+ let scale = 0;
15108
+ let characterLength;
15109
+ let computed = false;
15110
+ for (;;) {
15111
+ const attribute = reader.readTag();
15112
+ if (attribute === 0) break;
15113
+ switch (attribute) {
15114
+ case ATT_FIELD_NAME:
15115
+ name = reader.readTextAttribute();
15116
+ break;
15117
+ case ATT_FIELD_TYPE:
15118
+ blrType = reader.readInt32Attribute();
15119
+ break;
15120
+ case ATT_FIELD_LENGTH:
15121
+ lengthBytes = reader.readInt32Attribute();
15122
+ break;
15123
+ case ATT_FIELD_SCALE:
15124
+ scale = reader.readInt32Attribute();
15125
+ break;
15126
+ case ATT_FIELD_CHARACTER_LENGTH:
15127
+ characterLength = reader.readInt32Attribute();
15128
+ break;
15129
+ case ATT_FIELD_COMPUTED_FLAG:
15130
+ computed = reader.readInt32Attribute() !== 0;
15131
+ break;
15132
+ default: reader.skipAttributeValue();
15133
+ }
15134
+ }
15135
+ if (name === void 0) throw new FirebirdSchemaParseError("a rec_field record had no att_field_name attribute");
15136
+ if (blrType === void 0) throw new FirebirdSchemaParseError(`field "${name}" had no att_field_type attribute`);
15137
+ const physicalType = decodeBlrType(blrType);
15138
+ const typeLabel = describeFieldType(physicalType, lengthBytes, scale, characterLength);
15139
+ return {
15140
+ name,
15141
+ physicalType,
15142
+ lengthBytes,
15143
+ scale,
15144
+ characterLength,
15145
+ typeLabel,
15146
+ computed
15147
+ };
15148
+ }
15149
+ function readRelationSchema(reader, onUnhandledNested) {
15150
+ let name;
15151
+ for (;;) {
15152
+ const attribute = reader.readTag();
15153
+ if (attribute === 0) break;
15154
+ if (attribute === ATT_RELATION_NAME$1) name = reader.readTextAttribute();
15155
+ else reader.skipAttributeValue();
15156
+ }
15157
+ if (name === void 0) throw new FirebirdSchemaParseError("a rec_relation record had no att_relation_name attribute");
15158
+ const fields = [];
15159
+ for (;;) {
15160
+ const recordType = reader.readTag();
15161
+ if (recordType === REC_RELATION_END$1) break;
15162
+ if (recordType === REC_FIELD) {
15163
+ fields.push(readField(reader));
15164
+ continue;
15165
+ }
15166
+ onUnhandledNested(recordType);
15167
+ }
15168
+ return {
15169
+ name,
15170
+ fields
15171
+ };
15172
+ }
15173
+ //#endregion
15174
+ //#region src/firebird/date.ts
15175
+ const ISC_TIME_SECONDS_PRECISION = 1e4;
15176
+ function decodeFirebirdDate(days) {
15177
+ let nday = days + 2400001 - 1721119;
15178
+ const century = Math.floor((4 * nday - 1) / 146097);
15179
+ nday = 4 * nday - 1 - 146097 * century;
15180
+ let day = Math.floor(nday / 4);
15181
+ nday = Math.floor((4 * day + 3) / 1461);
15182
+ day = 4 * day + 3 - 1461 * nday;
15183
+ day = Math.floor((day + 4) / 4);
15184
+ let month = Math.floor((5 * day - 3) / 153);
15185
+ day = 5 * day - 3 - 153 * month;
15186
+ day = Math.floor((day + 5) / 5);
15187
+ let year = 100 * century + nday;
15188
+ if (month < 10) month += 3;
15189
+ else {
15190
+ month -= 9;
15191
+ year += 1;
15192
+ }
15193
+ return {
15194
+ year,
15195
+ month,
15196
+ day
15197
+ };
15198
+ }
15199
+ function decodeFirebirdTime(ticks) {
15200
+ let remaining = ticks;
15201
+ const hours = Math.floor(remaining / (3600 * ISC_TIME_SECONDS_PRECISION));
15202
+ remaining %= 3600 * ISC_TIME_SECONDS_PRECISION;
15203
+ const minutes = Math.floor(remaining / (60 * ISC_TIME_SECONDS_PRECISION));
15204
+ remaining %= 60 * ISC_TIME_SECONDS_PRECISION;
15205
+ return {
15206
+ hours,
15207
+ minutes,
15208
+ seconds: Math.floor(remaining / ISC_TIME_SECONDS_PRECISION),
15209
+ fractions: remaining % ISC_TIME_SECONDS_PRECISION
15210
+ };
15211
+ }
15212
+ function pad2(value) {
15213
+ return String(value).padStart(2, "0");
15214
+ }
15215
+ function pad4(value) {
15216
+ return String(value).padStart(4, "0");
15217
+ }
15218
+ function formatFirebirdDate(days) {
15219
+ const { year, month, day } = decodeFirebirdDate(days);
15220
+ return `${pad4(year)}-${pad2(month)}-${pad2(day)}`;
15221
+ }
15222
+ function formatFirebirdTime(ticks) {
15223
+ const { hours, minutes, seconds, fractions } = decodeFirebirdTime(ticks);
15224
+ const millis = Math.round(fractions / 10);
15225
+ return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}.${String(millis).padStart(3, "0")}`;
15226
+ }
15227
+ function formatFirebirdTimestamp(days, ticks) {
15228
+ return `${formatFirebirdDate(days)} ${formatFirebirdTime(ticks)}`;
15229
+ }
15230
+ //#endregion
15231
+ //#region src/firebird/data.ts
15232
+ const REC_DATA = 6;
15233
+ const REC_BLOB = 7;
15234
+ const REC_RELATION_END = 9;
15235
+ const REC_GEN_ID = 18;
15236
+ const REC_INDEX = 5;
15237
+ const REC_TRIGGER = 13;
15238
+ const ATT_RELATION_NAME = 1;
15239
+ const ATT_DATA_LENGTH = 1;
15240
+ const ATT_DATA_DATA = 2;
15241
+ const ATT_XDR_LENGTH = 17;
15242
+ var FirebirdDataParseError = class extends Error {
15243
+ constructor(message) {
15244
+ super(`Firebird backup data parse error: ${message}`);
15245
+ this.name = "FirebirdDataParseError";
15246
+ }
15247
+ };
15248
+ var FirebirdCompositeRecordUnsupportedError = class extends Error {
15249
+ recordType;
15250
+ constructor(recordType, context) {
15251
+ super(`Firebird backup: encountered record type ${recordType} while ${context}, which this reader's own bounded implementation does not know how to skip safely (its own attribute/sub-record shape has not been verified against a real fixture) -- refusing to guess rather than risk silently desynchronising the rest of the stream`);
15252
+ this.name = "FirebirdCompositeRecordUnsupportedError";
15253
+ this.recordType = recordType;
15254
+ }
15255
+ };
15256
+ function skipBlobRecord(reader) {
15257
+ let segmentCount;
15258
+ for (;;) {
15259
+ const attribute = reader.readTag();
15260
+ if (attribute === 0) break;
15261
+ if (attribute === 5) segmentCount = reader.readInt32Attribute();
15262
+ else if (attribute === 7) {
15263
+ const count = segmentCount ?? 0;
15264
+ for (let i = 0; i < count; i++) {
15265
+ const length = reader.readBlobSegmentLength();
15266
+ reader.readRawPayload(length);
15267
+ }
15268
+ } else reader.skipAttributeValue();
15269
+ }
15270
+ }
15271
+ function decodeRowValues(fields, payload) {
15272
+ const storedFields = fields.filter((field) => !field.computed);
15273
+ const xdr = new XdrReader(payload);
15274
+ const rawValues = [];
15275
+ for (const field of storedFields) switch (field.physicalType) {
15276
+ case "short":
15277
+ rawValues.push({
15278
+ kind: "number",
15279
+ value: field.scale === 0 ? xdr.readInt16() : xdr.readInt16() * 10 ** field.scale
15280
+ });
15281
+ break;
15282
+ case "long":
15283
+ rawValues.push({
15284
+ kind: "number",
15285
+ value: field.scale === 0 ? xdr.readInt32() : xdr.readInt32() * 10 ** field.scale
15286
+ });
15287
+ break;
15288
+ case "int64": {
15289
+ const raw = xdr.readInt64();
15290
+ const scaled = field.scale === 0 ? Number(raw) : Number(raw) * 10 ** field.scale;
15291
+ rawValues.push({
15292
+ kind: "number",
15293
+ value: scaled
15294
+ });
15295
+ break;
15296
+ }
15297
+ case "real":
15298
+ rawValues.push({
15299
+ kind: "number",
15300
+ value: xdr.readFloat()
15301
+ });
15302
+ break;
15303
+ case "double":
15304
+ rawValues.push({
15305
+ kind: "number",
15306
+ value: xdr.readDouble()
15307
+ });
15308
+ break;
15309
+ case "sql_date": {
15310
+ const days = xdr.readInt32();
15311
+ rawValues.push({
15312
+ kind: "date",
15313
+ value: formatFirebirdDate(days)
15314
+ });
15315
+ break;
15316
+ }
15317
+ case "sql_time": {
15318
+ const ticks = xdr.readInt32() >>> 0;
15319
+ rawValues.push({
15320
+ kind: "time",
15321
+ value: formatFirebirdTime(ticks)
15322
+ });
15323
+ break;
15324
+ }
15325
+ case "timestamp": {
15326
+ const days = xdr.readInt32();
15327
+ const ticks = xdr.readInt32() >>> 0;
15328
+ rawValues.push({
15329
+ kind: "date",
15330
+ value: formatFirebirdTimestamp(days, ticks)
15331
+ });
15332
+ break;
15333
+ }
15334
+ case "text": {
15335
+ const bytes = xdr.readOpaque(field.lengthBytes);
15336
+ rawValues.push({
15337
+ kind: "string",
15338
+ value: new TextDecoder("utf-8").decode(bytes).replace(/\s+$/, "")
15339
+ });
15340
+ break;
15341
+ }
15342
+ case "varying": {
15343
+ const stringLength = xdr.readInt16();
15344
+ const bytes = xdr.readOpaque(stringLength);
15345
+ rawValues.push({
15346
+ kind: "string",
15347
+ value: new TextDecoder("utf-8").decode(bytes)
15348
+ });
15349
+ break;
15350
+ }
15351
+ case "cstring": {
15352
+ const stringLength = xdr.readInt16();
15353
+ const bytes = xdr.readOpaque(stringLength);
15354
+ rawValues.push({
15355
+ kind: "string",
15356
+ value: new TextDecoder("utf-8").decode(bytes)
15357
+ });
15358
+ break;
15359
+ }
15360
+ case "boolean": {
15361
+ const bytes = xdr.readOpaque(field.lengthBytes);
15362
+ rawValues.push({
15363
+ kind: "boolean",
15364
+ value: (bytes[0] ?? 0) !== 0
15365
+ });
15366
+ break;
15367
+ }
15368
+ case "blob":
15369
+ xdr.readInt32();
15370
+ xdr.readInt32();
15371
+ rawValues.push({ kind: "empty" });
15372
+ break;
15373
+ case "quad":
15374
+ xdr.readInt32();
15375
+ xdr.readInt32();
15376
+ rawValues.push({ kind: "empty" });
15377
+ break;
15378
+ case "int128":
15379
+ case "dec64":
15380
+ case "dec128":
15381
+ case "unsupported-tz": throw new FirebirdDataParseError(`column "${field.name}" has physical type "${field.physicalType}", which this reader's own bounded implementation does not decode (FB4+-only types not exercised by this reader's Firebird 3.0-era real fixture) -- see the README's .odb Tier 3 Fidelity note`);
15382
+ }
15383
+ for (let i = 0; i < storedFields.length; i++) if (xdr.readInt16() !== 0) rawValues[i] = { kind: "empty" };
15384
+ return rawValues.map((value) => value ?? { kind: "empty" });
15385
+ }
15386
+ function readRowGroup(reader, relation, compressed) {
15387
+ const rows = [];
15388
+ let terminator;
15389
+ for (;;) {
15390
+ const lengthTag = reader.readTag();
15391
+ if (lengthTag !== ATT_DATA_LENGTH) throw new FirebirdDataParseError(`relation "${relation.name}": expected att_data_length (tag ${ATT_DATA_LENGTH}), found tag ${lengthTag}`);
15392
+ let xdrLength = reader.readInt32Attribute();
15393
+ const maybeXdrTag = reader.readTag();
15394
+ if (maybeXdrTag === ATT_XDR_LENGTH) xdrLength = reader.readInt32Attribute();
15395
+ else if (maybeXdrTag !== ATT_DATA_DATA) throw new FirebirdDataParseError(`relation "${relation.name}": expected att_xdr_length or att_data_data, found tag ${maybeXdrTag}`);
15396
+ if (maybeXdrTag !== ATT_DATA_DATA) {
15397
+ const dataTag = reader.readTag();
15398
+ if (dataTag !== ATT_DATA_DATA) throw new FirebirdDataParseError(`relation "${relation.name}": expected att_data_data (tag ${ATT_DATA_DATA}), found tag ${dataTag}`);
15399
+ }
15400
+ const payload = compressed ? reader.readCompressedPayload(xdrLength) : reader.readRawPayload(xdrLength);
15401
+ rows.push(decodeRowValues(relation.fields, payload));
15402
+ let next = reader.readTag();
15403
+ while (next === REC_BLOB) {
15404
+ skipBlobRecord(reader);
15405
+ next = reader.readTag();
15406
+ }
15407
+ if (next !== REC_DATA) {
15408
+ terminator = next;
15409
+ break;
15410
+ }
15411
+ }
15412
+ return {
15413
+ rows,
15414
+ terminator
15415
+ };
15416
+ }
15417
+ function readRelationData(reader, schema, compressed) {
15418
+ let name;
15419
+ for (;;) {
15420
+ const attribute = reader.readTag();
15421
+ if (attribute === 0) break;
15422
+ if (attribute === ATT_RELATION_NAME) name = reader.readTextAttribute();
15423
+ else reader.skipAttributeValue();
15424
+ }
15425
+ if (name === void 0) throw new FirebirdDataParseError("a rec_relation_data record had no att_relation_name attribute");
15426
+ const relation = schema.get(name);
15427
+ if (relation === void 0) throw new FirebirdDataParseError(`rec_relation_data references relation "${name}", which no earlier rec_relation declared`);
15428
+ const rows = [];
15429
+ let recordType = reader.readTag();
15430
+ for (;;) {
15431
+ if (recordType === REC_RELATION_END) break;
15432
+ if (recordType === REC_DATA) {
15433
+ const group = readRowGroup(reader, relation, compressed);
15434
+ rows.push(...group.rows);
15435
+ recordType = group.terminator;
15436
+ continue;
15437
+ }
15438
+ if (recordType === REC_GEN_ID) {
15439
+ reader.readAttributeBytes();
15440
+ recordType = reader.readTag();
15441
+ continue;
15442
+ }
15443
+ if (recordType === REC_INDEX || recordType === REC_TRIGGER) {
15444
+ reader.skipFlatRecordAttributes();
15445
+ recordType = reader.readTag();
15446
+ continue;
15447
+ }
15448
+ throw new FirebirdCompositeRecordUnsupportedError(recordType, `reading relation data for "${name}"`);
15449
+ }
15450
+ return {
15451
+ relationName: name,
15452
+ rows
15453
+ };
15454
+ }
15455
+ //#endregion
15456
+ //#region src/firebird/backup.ts
15457
+ const REC_DATABASE = 1;
15458
+ const REC_RELATION = 3;
15459
+ const REC_RELATION_DATA = 8;
15460
+ const REC_END = 10;
15461
+ const REC_PHYSICAL_DB = 14;
15462
+ const FLAT_SKIPPABLE_RECORD_TYPES = /* @__PURE__ */ new Set([
15463
+ 2,
15464
+ 24,
15465
+ 31,
15466
+ 32,
15467
+ 33,
15468
+ 34,
15469
+ 35,
15470
+ 19,
15471
+ 20,
15472
+ 26,
15473
+ 12,
15474
+ 25,
15475
+ 36,
15476
+ 37,
15477
+ 39,
15478
+ 21,
15479
+ 22,
15480
+ 40,
15481
+ 41,
15482
+ 42,
15483
+ 43
15484
+ ]);
15485
+ var FirebirdBackupFormatError = class extends Error {
15486
+ constructor(message) {
15487
+ super(`Firebird backup: ${message}`);
15488
+ this.name = "FirebirdBackupFormatError";
15489
+ }
15490
+ };
15491
+ const ATT_BACKUP_FORMAT = 2;
15492
+ const ATT_BACKUP_COMPRESS = 4;
15493
+ const ATT_BACKUP_TRANSPORTABLE = 5;
15494
+ const ATT_PAGE_SIZE = 5;
15495
+ function readBurpHeader(reader) {
15496
+ let backupFormatVersion;
15497
+ let transportable = false;
15498
+ let compressed = false;
15499
+ for (;;) {
15500
+ const attribute = reader.readTag();
15501
+ if (attribute === 0) break;
15502
+ switch (attribute) {
15503
+ case ATT_BACKUP_FORMAT:
15504
+ backupFormatVersion = reader.readInt32Attribute();
15505
+ break;
15506
+ case ATT_BACKUP_TRANSPORTABLE:
15507
+ transportable = reader.readInt32Attribute() !== 0;
15508
+ break;
15509
+ case ATT_BACKUP_COMPRESS:
15510
+ compressed = reader.readInt32Attribute() !== 0;
15511
+ break;
15512
+ default: reader.skipAttributeValue();
15513
+ }
15514
+ }
15515
+ if (backupFormatVersion === void 0) throw new FirebirdBackupFormatError("the leading rec_burp record had no att_backup_format attribute -- not a recognisable gbak backup stream");
15516
+ return {
15517
+ backupFormatVersion,
15518
+ transportable,
15519
+ compressed
15520
+ };
15521
+ }
15522
+ function readDatabaseHeader(reader) {
15523
+ let pageSizeBytes;
15524
+ for (;;) {
15525
+ const attribute = reader.readTag();
15526
+ if (attribute === 0) break;
15527
+ if (attribute === ATT_PAGE_SIZE) pageSizeBytes = reader.readInt32Attribute();
15528
+ else reader.skipAttributeValue();
15529
+ }
15530
+ return { pageSizeBytes };
15531
+ }
15532
+ const SUPPORTED_BACKUP_FORMAT_VERSION = 10;
15533
+ function relationToColumns(relation) {
15534
+ return relation.fields.filter((field) => !field.computed).map((field) => ({
15535
+ name: field.name,
15536
+ type: field.typeLabel
15537
+ }));
15538
+ }
15539
+ function readFirebirdBackup(bytes) {
15540
+ const reader = new FirebirdBackupReader(bytes);
15541
+ const leadingRecordType = reader.readTag();
15542
+ if (leadingRecordType !== 0) throw new FirebirdBackupFormatError(`expected the stream to open with rec_burp (tag 0), found tag ${leadingRecordType} -- not a recognisable gbak backup stream`);
15543
+ const { backupFormatVersion, transportable, compressed } = readBurpHeader(reader);
15544
+ if (backupFormatVersion !== 10) throw new FirebirdBackupFormatError(`backup format version ${backupFormatVersion} is not supported -- this reader has only been built and verified against format version 10 (Firebird 3.0-era gbak output). Refusing to guess at a different format's own attribute/record shape rather than risk silently misdecoding it.`);
15545
+ if (!transportable) throw new FirebirdBackupFormatError("backup is in non-transportable (native binary) row format (att_backup_transportable=false) -- this reader only decodes the transportable/XDR row encoding, the one every real fixture it was built against actually uses (gbak's own default).");
15546
+ let pageSizeBytes;
15547
+ const schema = /* @__PURE__ */ new Map();
15548
+ const tablesInOrder = [];
15549
+ const rowsByRelation = /* @__PURE__ */ new Map();
15550
+ for (;;) {
15551
+ const recordType = reader.readTag();
15552
+ if (recordType === REC_END) break;
15553
+ if (recordType === REC_DATABASE || recordType === REC_PHYSICAL_DB) {
15554
+ pageSizeBytes = readDatabaseHeader(reader).pageSizeBytes ?? pageSizeBytes;
15555
+ continue;
15556
+ }
15557
+ if (recordType === REC_RELATION) {
15558
+ const relation = readRelationSchema(reader, (nestedRecordType) => {
15559
+ throw new FirebirdCompositeRecordUnsupportedError(nestedRecordType, "reading a relation's own schema (a rec_view child, most likely)");
15560
+ });
15561
+ schema.set(relation.name, relation);
15562
+ tablesInOrder.push(relation.name);
15563
+ continue;
15564
+ }
15565
+ if (recordType === REC_RELATION_DATA) {
15566
+ const result = readRelationData(reader, schema, compressed);
15567
+ rowsByRelation.set(result.relationName, result.rows);
15568
+ continue;
15569
+ }
15570
+ if (FLAT_SKIPPABLE_RECORD_TYPES.has(recordType)) {
15571
+ reader.skipFlatRecordAttributes();
15572
+ continue;
15573
+ }
15574
+ throw new FirebirdCompositeRecordUnsupportedError(recordType, "walking the backup stream's own top-level record sequence");
15575
+ }
15576
+ const tables = tablesInOrder.map((name) => {
15577
+ const relation = schema.get(name);
15578
+ if (relation === void 0) throw new FirebirdBackupFormatError(`internal error: relation "${name}" missing from its own schema map`);
15579
+ const rows = rowsByRelation.get(name) ?? [];
15580
+ return {
15581
+ tableName: relation.name,
15582
+ columns: relationToColumns(relation),
15583
+ rows
15584
+ };
15585
+ });
15586
+ return {
15587
+ summary: {
15588
+ backupFormatVersion,
15589
+ transportable,
15590
+ compressed,
15591
+ pageSizeBytes
15592
+ },
15593
+ tables
15594
+ };
15595
+ }
15596
+ //#endregion
14573
15597
  //#region src/odb/read.ts
14574
15598
  var OdbNoEmbeddedDataSourceError = class extends Error {
14575
15599
  url;
@@ -14588,12 +15612,21 @@ var OdbUnsupportedFormatError = class extends Error {
14588
15612
  }
14589
15613
  };
14590
15614
  const DATABASE_SCRIPT_PART = "database/script";
15615
+ const DATABASE_DATA_PART = "database/data";
15616
+ const DATABASE_PROPERTIES_PART = "database/properties";
15617
+ const DATABASE_FIREBIRD_PART = "database/firebird.fbk";
14591
15618
  function isXmlMediaType(mediaType) {
14592
15619
  return mediaType === "text/xml" || mediaType === "application/xml" || mediaType.endsWith("+xml");
14593
15620
  }
14594
- const GZIP_MAGIC = [31, 139];
15621
+ function isZlibHeader(bytes) {
15622
+ if (bytes.length < 2) return false;
15623
+ const cmf = bytes[0];
15624
+ const flg = bytes[1];
15625
+ if (cmf === void 0 || flg === void 0) return false;
15626
+ return (cmf & 15) === 8 && (cmf * 256 + flg) % 31 === 0;
15627
+ }
14595
15628
  function classifyScriptBytes(bytes) {
14596
- if (bytes.length >= GZIP_MAGIC.length && bytes[0] === GZIP_MAGIC[0] && bytes[1] === GZIP_MAGIC[1]) return "compressed";
15629
+ if (isZlibHeader(bytes)) return "compressed";
14597
15630
  for (const byte of bytes) if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) return "binary";
14598
15631
  try {
14599
15632
  new TextDecoder("utf-8", { fatal: true }).decode(bytes);
@@ -14608,18 +15641,32 @@ function readOdbTables(pkg) {
14608
15641
  const url = inventory.connection.url;
14609
15642
  if (url === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", "an embedded connection with no connection url to identify its engine");
14610
15643
  const engine = url.slice(14);
14611
- if (engine === "firebird") throw new OdbUnsupportedFormatError("firebird", `Firebird's embedded database engine ("${url}")`);
15644
+ if (engine === "firebird") {
15645
+ const firebirdPart = pkg.parts[DATABASE_FIREBIRD_PART];
15646
+ if (firebirdPart === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", `an embedded Firebird engine with no ${DATABASE_FIREBIRD_PART} part -- an unrecognised embedded storage shape`);
15647
+ if (firebirdPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_FIREBIRD_PART} is not a binary part (found kind "${firebirdPart.kind}") -- malformed .odb package`);
15648
+ return readFirebirdBackup(base64ToBytes$2(firebirdPart.base64)).tables;
15649
+ }
14612
15650
  if (engine !== "hsqldb") throw new OdbUnsupportedFormatError("unrecognised-engine", `the embedded "${engine}" database engine`);
14613
15651
  const manifestEntry = readManifest(pkg).entries.find((entry) => entry.fullPath === DATABASE_SCRIPT_PART);
14614
15652
  if (manifestEntry !== void 0 && isXmlMediaType(manifestEntry.mediaType)) throw new Error(`readOdbTables: ${DATABASE_SCRIPT_PART} is declared as an XML sub-document in the manifest (media type "${manifestEntry.mediaType}") -- not a recognised HSQLDB script part`);
14615
15653
  const scriptPart = pkg.parts[DATABASE_SCRIPT_PART];
14616
- if (scriptPart === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", `an embedded HSQLDB engine with no ${DATABASE_SCRIPT_PART} part -- binary HSQLDB cache-only storage, or an unrecognised embedded storage shape`);
15654
+ if (scriptPart === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", `an embedded HSQLDB engine with no ${DATABASE_SCRIPT_PART} part -- an unrecognised embedded storage shape`);
14617
15655
  if (scriptPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_SCRIPT_PART} is not a binary part (found kind "${scriptPart.kind}") -- malformed .odb package`);
14618
15656
  const scriptBytes = base64ToBytes$2(scriptPart.base64);
14619
15657
  const classification = classifyScriptBytes(scriptBytes);
14620
- if (classification === "compressed") throw new OdbUnsupportedFormatError("hsqldb-compressed", "HSQLDB's compressed script format (hsqldb.script_format=3)");
14621
- if (classification === "binary") throw new OdbUnsupportedFormatError("hsqldb-binary", "HSQLDB's binary script format (hsqldb.script_format=1)");
14622
- return parseHsqldbScript(scriptBytes);
15658
+ if (classification === "compressed") throw new OdbUnsupportedFormatError("hsqldb-compressed", "HSQLDB's compressed whole-script format (hsqldb.script_format=3) -- a zlib-wrapped copy of the same length-prefixed binary DDL/DML statement encoding hsqldb.script_format=1 uses, not compressed SQL text");
15659
+ if (classification === "binary") throw new OdbUnsupportedFormatError("hsqldb-binary", "HSQLDB's binary whole-script format (hsqldb.script_format=1) -- a length-prefixed, COMMAND-tagged binary encoding of the script's own DDL/DML statements themselves, a materially different and larger undertaking than CACHED-table row-store decoding (Tier 2)");
15660
+ return withCachedTableRows(pkg, parseHsqldbScript(scriptBytes), scriptBytes);
15661
+ }
15662
+ function withCachedTableRows(pkg, tables, scriptBytes) {
15663
+ const dataPart = pkg.parts[DATABASE_DATA_PART];
15664
+ if (dataPart === void 0) return tables;
15665
+ if (dataPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_DATA_PART} is not a binary part (found kind "${dataPart.kind}") -- malformed .odb package`);
15666
+ const propertiesPart = pkg.parts[DATABASE_PROPERTIES_PART];
15667
+ if (propertiesPart === void 0) throw new Error(`readOdbTables: ${DATABASE_DATA_PART} is present but ${DATABASE_PROPERTIES_PART} is not -- malformed .odb package (a CACHED-table row store always ships alongside its own properties file, which this decoder needs for the cache file's own scale)`);
15668
+ if (propertiesPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_PROPERTIES_PART} is not a binary part (found kind "${propertiesPart.kind}") -- malformed .odb package`);
15669
+ return decodeHsqldbCachedTables(tables, new TextDecoder("utf-8", { fatal: true }).decode(scriptBytes), base64ToBytes$2(dataPart.base64), new TextDecoder("utf-8", { fatal: true }).decode(base64ToBytes$2(propertiesPart.base64)));
14623
15670
  }
14624
15671
  //#endregion
14625
15672
  //#region src/odb/spreadsheet.ts
@@ -14690,6 +15737,11 @@ function docxToPdf(bytes, options) {
14690
15737
  const content = readDocxContent(openDocx(bytes).toPackage());
14691
15738
  if (content.kind !== "wordprocessing") throw new Error("readDocxContent returned a non-wordprocessing ContentDocument");
14692
15739
  const { document: layout, formulas } = convertWordprocessingToLayout(content, { measurer: createStandardFontMeasurer() });
15740
+ options?.onDocument?.({
15741
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15742
+ content,
15743
+ layout
15744
+ });
14693
15745
  return writePdf(layout, {
14694
15746
  signal: options?.signal,
14695
15747
  onSubstitution: options?.onSubstitution,
@@ -14703,6 +15755,11 @@ function odtToPdf(bytes, options) {
14703
15755
  measurer: createStandardFontMeasurer(),
14704
15756
  formulas: content.formulas
14705
15757
  });
15758
+ options?.onDocument?.({
15759
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15760
+ content: content.document,
15761
+ layout
15762
+ });
14706
15763
  return writePdf(layout, {
14707
15764
  signal: options?.signal,
14708
15765
  onSubstitution: options?.onSubstitution,
@@ -14713,6 +15770,11 @@ function pptxToPdf(bytes, options) {
14713
15770
  const content = readPptxContent(openPptx(bytes).toPackage());
14714
15771
  if (content.kind !== "presentation") throw new Error("readPptxContent returned a non-presentation ContentDocument");
14715
15772
  const { document: layout } = convertPresentationToLayout(content, { measurer: createStandardFontMeasurer() });
15773
+ options?.onDocument?.({
15774
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15775
+ content,
15776
+ layout
15777
+ });
14716
15778
  return writePdf(layout, {
14717
15779
  signal: options?.signal,
14718
15780
  onSubstitution: options?.onSubstitution
@@ -14725,6 +15787,11 @@ function odpToPdf(bytes, options) {
14725
15787
  measurer: createStandardFontMeasurer(),
14726
15788
  formulas: content.formulas
14727
15789
  });
15790
+ options?.onDocument?.({
15791
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15792
+ content: content.document,
15793
+ layout
15794
+ });
14728
15795
  return writePdf(layout, {
14729
15796
  signal: options?.signal,
14730
15797
  onSubstitution: options?.onSubstitution,
@@ -14734,10 +15801,16 @@ function odpToPdf(bytes, options) {
14734
15801
  function odsToPdf(bytes, options) {
14735
15802
  const content = readOdsContent(decodePackage$2(bytes));
14736
15803
  if (content.kind !== "spreadsheet") throw new Error("readOdsContent returned a non-spreadsheet ContentDocument");
14737
- return writePdf(convertSpreadsheetToLayout(content, {
15804
+ const layout = convertSpreadsheetToLayout(content, {
14738
15805
  measurer: createStandardFontMeasurer(),
14739
15806
  signal: options?.signal
14740
- }), {
15807
+ });
15808
+ options?.onDocument?.({
15809
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15810
+ content,
15811
+ layout
15812
+ });
15813
+ return writePdf(layout, {
14741
15814
  signal: options?.signal,
14742
15815
  onSubstitution: options?.onSubstitution
14743
15816
  });
@@ -14745,7 +15818,13 @@ function odsToPdf(bytes, options) {
14745
15818
  function odgToPdf(bytes, options) {
14746
15819
  const content = readOdgContent(decodePackage$2(bytes));
14747
15820
  if (content.kind !== "drawing") throw new Error("readOdgContent returned a non-drawing ContentDocument");
14748
- return writePdf(convertDrawingToLayout(content, { measurer: createStandardFontMeasurer() }), {
15821
+ const layout = convertDrawingToLayout(content, { measurer: createStandardFontMeasurer() });
15822
+ options?.onDocument?.({
15823
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15824
+ content,
15825
+ layout
15826
+ });
15827
+ return writePdf(layout, {
14749
15828
  signal: options?.signal,
14750
15829
  onSubstitution: options?.onSubstitution
14751
15830
  });
@@ -14789,45 +15868,81 @@ function odfToPdf(bytes, options) {
14789
15868
  });
14790
15869
  }
14791
15870
  function pdfToDocx(bytes, options) {
14792
- const content = reconstructWordprocessing(readPdf(bytes, {
15871
+ const layout = readPdf(bytes, {
14793
15872
  signal: options?.signal,
14794
15873
  sink: options?.sink
14795
- }), { signal: options?.signal });
15874
+ });
15875
+ const content = reconstructWordprocessing(layout, { signal: options?.signal });
15876
+ options?.onDocument?.({
15877
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15878
+ content,
15879
+ layout
15880
+ });
14796
15881
  return encodePackage$1(buildDocxPackage(content));
14797
15882
  }
14798
15883
  function pdfToPptx(bytes, options) {
14799
- const content = reconstructPresentation(readPdf(bytes, {
15884
+ const layout = readPdf(bytes, {
14800
15885
  signal: options?.signal,
14801
15886
  sink: options?.sink
14802
- }), { signal: options?.signal });
15887
+ });
15888
+ const content = reconstructPresentation(layout, { signal: options?.signal });
15889
+ options?.onDocument?.({
15890
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15891
+ content,
15892
+ layout
15893
+ });
14803
15894
  return encodePackage$1(buildPptxPackage(content));
14804
15895
  }
14805
15896
  function pdfToOdt(bytes, options) {
14806
- const content = reconstructWordprocessing(readPdf(bytes, {
15897
+ const layout = readPdf(bytes, {
14807
15898
  signal: options?.signal,
14808
15899
  sink: options?.sink
14809
- }), { signal: options?.signal });
15900
+ });
15901
+ const content = reconstructWordprocessing(layout, { signal: options?.signal });
15902
+ options?.onDocument?.({
15903
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15904
+ content,
15905
+ layout
15906
+ });
14810
15907
  return encodePackage$2(buildOdtPackage(content));
14811
15908
  }
14812
15909
  function pdfToOdp(bytes, options) {
14813
- const content = reconstructPresentation(readPdf(bytes, {
15910
+ const layout = readPdf(bytes, {
14814
15911
  signal: options?.signal,
14815
15912
  sink: options?.sink
14816
- }), { signal: options?.signal });
15913
+ });
15914
+ const content = reconstructPresentation(layout, { signal: options?.signal });
15915
+ options?.onDocument?.({
15916
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15917
+ content,
15918
+ layout
15919
+ });
14817
15920
  return encodePackage$2(buildOdpPackage(content));
14818
15921
  }
14819
15922
  function pdfToOdg(bytes, options) {
14820
- const content = reconstructDrawing(readPdf(bytes, {
15923
+ const layout = readPdf(bytes, {
14821
15924
  signal: options?.signal,
14822
15925
  sink: options?.sink
14823
- }), { signal: options?.signal });
15926
+ });
15927
+ const content = reconstructDrawing(layout, { signal: options?.signal });
15928
+ options?.onDocument?.({
15929
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15930
+ content,
15931
+ layout
15932
+ });
14824
15933
  return encodePackage$2(buildOdgPackage(content));
14825
15934
  }
14826
15935
  function pdfToOds(bytes, options) {
14827
- const content = reconstructSpreadsheet(readPdf(bytes, {
15936
+ const layout = readPdf(bytes, {
14828
15937
  signal: options?.signal,
14829
15938
  sink: options?.sink
14830
- }), { signal: options?.signal });
15939
+ });
15940
+ const content = reconstructSpreadsheet(layout, { signal: options?.signal });
15941
+ options?.onDocument?.({
15942
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15943
+ content,
15944
+ layout
15945
+ });
14831
15946
  return encodePackage$2(buildOdsPackage(content));
14832
15947
  }
14833
15948
  function odtToDocx(bytes, options) {
@@ -14835,6 +15950,10 @@ function odtToDocx(bytes, options) {
14835
15950
  const content = readOdtContent(decodePackage$2(bytes)).document;
14836
15951
  if (content.kind !== "wordprocessing") throw new Error("readOdtContent returned a non-wordprocessing ContentDocument");
14837
15952
  throwIfAborted(options?.signal);
15953
+ options?.onDocument?.({
15954
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15955
+ content
15956
+ });
14838
15957
  return encodePackage$1(buildDocxPackage(content));
14839
15958
  }
14840
15959
  function docxToOdt(bytes, options) {
@@ -14842,6 +15961,10 @@ function docxToOdt(bytes, options) {
14842
15961
  const content = readDocxContent(decodePackage$1(bytes));
14843
15962
  if (content.kind !== "wordprocessing") throw new Error("readDocxContent returned a non-wordprocessing ContentDocument");
14844
15963
  throwIfAborted(options?.signal);
15964
+ options?.onDocument?.({
15965
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15966
+ content
15967
+ });
14845
15968
  return encodePackage$2(buildOdtPackage(content));
14846
15969
  }
14847
15970
  function odpToPptx(bytes, options) {
@@ -14849,6 +15972,10 @@ function odpToPptx(bytes, options) {
14849
15972
  const content = readOdpContent(decodePackage$2(bytes)).document;
14850
15973
  if (content.kind !== "presentation") throw new Error("readOdpContent returned a non-presentation ContentDocument");
14851
15974
  throwIfAborted(options?.signal);
15975
+ options?.onDocument?.({
15976
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15977
+ content
15978
+ });
14852
15979
  return encodePackage$1(buildPptxPackage(content));
14853
15980
  }
14854
15981
  function pptxToOdp(bytes, options) {
@@ -14856,6 +15983,10 @@ function pptxToOdp(bytes, options) {
14856
15983
  const content = readPptxContent(decodePackage$1(bytes));
14857
15984
  if (content.kind !== "presentation") throw new Error("readPptxContent returned a non-presentation ContentDocument");
14858
15985
  throwIfAborted(options?.signal);
15986
+ options?.onDocument?.({
15987
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15988
+ content
15989
+ });
14859
15990
  return encodePackage$2(buildOdpPackage(content));
14860
15991
  }
14861
15992
  function odsToXlsx(bytes, options) {
@@ -14863,6 +15994,10 @@ function odsToXlsx(bytes, options) {
14863
15994
  const content = readOdsContent(decodePackage$2(bytes));
14864
15995
  if (content.kind !== "spreadsheet") throw new Error("readOdsContent returned a non-spreadsheet ContentDocument");
14865
15996
  throwIfAborted(options?.signal);
15997
+ options?.onDocument?.({
15998
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
15999
+ content
16000
+ });
14866
16001
  return encodePackage$1(buildXlsxPackage(content));
14867
16002
  }
14868
16003
  function xlsxToOds(bytes, options) {
@@ -14871,6 +16006,10 @@ function xlsxToOds(bytes, options) {
14871
16006
  const content = readXlsxContent(pkg);
14872
16007
  if (content.kind !== "spreadsheet") throw new Error("readXlsxContent returned a non-spreadsheet ContentDocument");
14873
16008
  throwIfAborted(options?.signal);
16009
+ options?.onDocument?.({
16010
+ formatVersion: DOCUMENT_PACKAGE_FORMAT_VERSION,
16011
+ content
16012
+ });
14874
16013
  return encodePackage$2(buildOdsPackage(content));
14875
16014
  }
14876
16015
  var OdmUnresolvedSectionError = class extends Error {
@@ -15099,238 +16238,292 @@ function fromPdfDiagnostic(diagnostic) {
15099
16238
  }
15100
16239
  function createLocalDocumentConverter() {
15101
16240
  return {
15102
- contractVersion: 1,
16241
+ contractVersion: 2,
15103
16242
  conversions: SUPPORTED_CONVERSIONS,
15104
16243
  convert(request, options) {
15105
16244
  const { source, targetFormat } = request;
15106
16245
  const diagnostics = [];
16246
+ let documentPackage;
16247
+ const onDocument = (pkg) => {
16248
+ documentPackage = pkg;
16249
+ };
15107
16250
  if (source.format === "docx" && targetFormat === "pdf") {
15108
16251
  const bytes = docxToPdf(source.bytes, {
15109
16252
  signal: options.signal,
15110
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16253
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16254
+ onDocument
15111
16255
  });
15112
16256
  return Promise.resolve({
15113
16257
  document: {
15114
16258
  format: "pdf",
15115
16259
  bytes
15116
16260
  },
15117
- diagnostics
16261
+ diagnostics,
16262
+ package: documentPackage
15118
16263
  });
15119
16264
  }
15120
16265
  if (source.format === "pptx" && targetFormat === "pdf") {
15121
16266
  const bytes = pptxToPdf(source.bytes, {
15122
16267
  signal: options.signal,
15123
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16268
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16269
+ onDocument
15124
16270
  });
15125
16271
  return Promise.resolve({
15126
16272
  document: {
15127
16273
  format: "pdf",
15128
16274
  bytes
15129
16275
  },
15130
- diagnostics
16276
+ diagnostics,
16277
+ package: documentPackage
15131
16278
  });
15132
16279
  }
15133
16280
  if (source.format === "odt" && targetFormat === "pdf") {
15134
16281
  const bytes = odtToPdf(source.bytes, {
15135
16282
  signal: options.signal,
15136
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16283
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16284
+ onDocument
15137
16285
  });
15138
16286
  return Promise.resolve({
15139
16287
  document: {
15140
16288
  format: "pdf",
15141
16289
  bytes
15142
16290
  },
15143
- diagnostics
16291
+ diagnostics,
16292
+ package: documentPackage
15144
16293
  });
15145
16294
  }
15146
16295
  if (source.format === "odp" && targetFormat === "pdf") {
15147
16296
  const bytes = odpToPdf(source.bytes, {
15148
16297
  signal: options.signal,
15149
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16298
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16299
+ onDocument
15150
16300
  });
15151
16301
  return Promise.resolve({
15152
16302
  document: {
15153
16303
  format: "pdf",
15154
16304
  bytes
15155
16305
  },
15156
- diagnostics
16306
+ diagnostics,
16307
+ package: documentPackage
15157
16308
  });
15158
16309
  }
15159
16310
  if (source.format === "ods" && targetFormat === "pdf") {
15160
16311
  const bytes = odsToPdf(source.bytes, {
15161
16312
  signal: options.signal,
15162
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16313
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16314
+ onDocument
15163
16315
  });
15164
16316
  return Promise.resolve({
15165
16317
  document: {
15166
16318
  format: "pdf",
15167
16319
  bytes
15168
16320
  },
15169
- diagnostics
16321
+ diagnostics,
16322
+ package: documentPackage
15170
16323
  });
15171
16324
  }
15172
16325
  if (source.format === "odg" && targetFormat === "pdf") {
15173
16326
  const bytes = odgToPdf(source.bytes, {
15174
16327
  signal: options.signal,
15175
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16328
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16329
+ onDocument
15176
16330
  });
15177
16331
  return Promise.resolve({
15178
16332
  document: {
15179
16333
  format: "pdf",
15180
16334
  bytes
15181
16335
  },
15182
- diagnostics
16336
+ diagnostics,
16337
+ package: documentPackage
15183
16338
  });
15184
16339
  }
15185
16340
  if (source.format === "odf" && targetFormat === "pdf") {
15186
16341
  const bytes = odfToPdf(source.bytes, {
15187
16342
  signal: options.signal,
15188
- onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c))
16343
+ onSubstitution: (s, c) => diagnostics.push(substitutionDiagnostic(s, c)),
16344
+ onDocument
15189
16345
  });
15190
16346
  return Promise.resolve({
15191
16347
  document: {
15192
16348
  format: "pdf",
15193
16349
  bytes
15194
16350
  },
15195
- diagnostics
16351
+ diagnostics,
16352
+ package: documentPackage
15196
16353
  });
15197
16354
  }
15198
16355
  if (source.format === "pdf" && targetFormat === "docx") {
15199
16356
  const bytes = pdfToDocx(source.bytes, {
15200
16357
  signal: options.signal,
15201
- sink: (d) => diagnostics.push(fromPdfDiagnostic(d))
16358
+ sink: (d) => diagnostics.push(fromPdfDiagnostic(d)),
16359
+ onDocument
15202
16360
  });
15203
16361
  return Promise.resolve({
15204
16362
  document: {
15205
16363
  format: "docx",
15206
16364
  bytes
15207
16365
  },
15208
- diagnostics
16366
+ diagnostics,
16367
+ package: documentPackage
15209
16368
  });
15210
16369
  }
15211
16370
  if (source.format === "pdf" && targetFormat === "pptx") {
15212
16371
  const bytes = pdfToPptx(source.bytes, {
15213
16372
  signal: options.signal,
15214
- sink: (d) => diagnostics.push(fromPdfDiagnostic(d))
16373
+ sink: (d) => diagnostics.push(fromPdfDiagnostic(d)),
16374
+ onDocument
15215
16375
  });
15216
16376
  return Promise.resolve({
15217
16377
  document: {
15218
16378
  format: "pptx",
15219
16379
  bytes
15220
16380
  },
15221
- diagnostics
16381
+ diagnostics,
16382
+ package: documentPackage
15222
16383
  });
15223
16384
  }
15224
16385
  if (source.format === "pdf" && targetFormat === "odt") {
15225
16386
  const bytes = pdfToOdt(source.bytes, {
15226
16387
  signal: options.signal,
15227
- sink: (d) => diagnostics.push(fromPdfDiagnostic(d))
16388
+ sink: (d) => diagnostics.push(fromPdfDiagnostic(d)),
16389
+ onDocument
15228
16390
  });
15229
16391
  return Promise.resolve({
15230
16392
  document: {
15231
16393
  format: "odt",
15232
16394
  bytes
15233
16395
  },
15234
- diagnostics
16396
+ diagnostics,
16397
+ package: documentPackage
15235
16398
  });
15236
16399
  }
15237
16400
  if (source.format === "pdf" && targetFormat === "odp") {
15238
16401
  const bytes = pdfToOdp(source.bytes, {
15239
16402
  signal: options.signal,
15240
- sink: (d) => diagnostics.push(fromPdfDiagnostic(d))
16403
+ sink: (d) => diagnostics.push(fromPdfDiagnostic(d)),
16404
+ onDocument
15241
16405
  });
15242
16406
  return Promise.resolve({
15243
16407
  document: {
15244
16408
  format: "odp",
15245
16409
  bytes
15246
16410
  },
15247
- diagnostics
16411
+ diagnostics,
16412
+ package: documentPackage
15248
16413
  });
15249
16414
  }
15250
16415
  if (source.format === "pdf" && targetFormat === "ods") {
15251
16416
  const bytes = pdfToOds(source.bytes, {
15252
16417
  signal: options.signal,
15253
- sink: (d) => diagnostics.push(fromPdfDiagnostic(d))
16418
+ sink: (d) => diagnostics.push(fromPdfDiagnostic(d)),
16419
+ onDocument
15254
16420
  });
15255
16421
  return Promise.resolve({
15256
16422
  document: {
15257
16423
  format: "ods",
15258
16424
  bytes
15259
16425
  },
15260
- diagnostics
16426
+ diagnostics,
16427
+ package: documentPackage
15261
16428
  });
15262
16429
  }
15263
16430
  if (source.format === "pdf" && targetFormat === "odg") {
15264
16431
  const bytes = pdfToOdg(source.bytes, {
15265
16432
  signal: options.signal,
15266
- sink: (d) => diagnostics.push(fromPdfDiagnostic(d))
16433
+ sink: (d) => diagnostics.push(fromPdfDiagnostic(d)),
16434
+ onDocument
15267
16435
  });
15268
16436
  return Promise.resolve({
15269
16437
  document: {
15270
16438
  format: "odg",
15271
16439
  bytes
15272
16440
  },
15273
- diagnostics
16441
+ diagnostics,
16442
+ package: documentPackage
15274
16443
  });
15275
16444
  }
15276
16445
  if (source.format === "odt" && targetFormat === "docx") {
15277
- const bytes = odtToDocx(source.bytes, { signal: options.signal });
16446
+ const bytes = odtToDocx(source.bytes, {
16447
+ signal: options.signal,
16448
+ onDocument
16449
+ });
15278
16450
  return Promise.resolve({
15279
16451
  document: {
15280
16452
  format: "docx",
15281
16453
  bytes
15282
16454
  },
15283
- diagnostics
16455
+ diagnostics,
16456
+ package: documentPackage
15284
16457
  });
15285
16458
  }
15286
16459
  if (source.format === "docx" && targetFormat === "odt") {
15287
- const bytes = docxToOdt(source.bytes, { signal: options.signal });
16460
+ const bytes = docxToOdt(source.bytes, {
16461
+ signal: options.signal,
16462
+ onDocument
16463
+ });
15288
16464
  return Promise.resolve({
15289
16465
  document: {
15290
16466
  format: "odt",
15291
16467
  bytes
15292
16468
  },
15293
- diagnostics
16469
+ diagnostics,
16470
+ package: documentPackage
15294
16471
  });
15295
16472
  }
15296
16473
  if (source.format === "odp" && targetFormat === "pptx") {
15297
- const bytes = odpToPptx(source.bytes, { signal: options.signal });
16474
+ const bytes = odpToPptx(source.bytes, {
16475
+ signal: options.signal,
16476
+ onDocument
16477
+ });
15298
16478
  return Promise.resolve({
15299
16479
  document: {
15300
16480
  format: "pptx",
15301
16481
  bytes
15302
16482
  },
15303
- diagnostics
16483
+ diagnostics,
16484
+ package: documentPackage
15304
16485
  });
15305
16486
  }
15306
16487
  if (source.format === "pptx" && targetFormat === "odp") {
15307
- const bytes = pptxToOdp(source.bytes, { signal: options.signal });
16488
+ const bytes = pptxToOdp(source.bytes, {
16489
+ signal: options.signal,
16490
+ onDocument
16491
+ });
15308
16492
  return Promise.resolve({
15309
16493
  document: {
15310
16494
  format: "odp",
15311
16495
  bytes
15312
16496
  },
15313
- diagnostics
16497
+ diagnostics,
16498
+ package: documentPackage
15314
16499
  });
15315
16500
  }
15316
16501
  if (source.format === "ods" && targetFormat === "xlsx") {
15317
- const bytes = odsToXlsx(source.bytes, { signal: options.signal });
16502
+ const bytes = odsToXlsx(source.bytes, {
16503
+ signal: options.signal,
16504
+ onDocument
16505
+ });
15318
16506
  return Promise.resolve({
15319
16507
  document: {
15320
16508
  format: "xlsx",
15321
16509
  bytes
15322
16510
  },
15323
- diagnostics
16511
+ diagnostics,
16512
+ package: documentPackage
15324
16513
  });
15325
16514
  }
15326
16515
  if (source.format === "xlsx" && targetFormat === "ods") {
15327
- const bytes = xlsxToOds(source.bytes, { signal: options.signal });
16516
+ const bytes = xlsxToOds(source.bytes, {
16517
+ signal: options.signal,
16518
+ onDocument
16519
+ });
15328
16520
  return Promise.resolve({
15329
16521
  document: {
15330
16522
  format: "ods",
15331
16523
  bytes
15332
16524
  },
15333
- diagnostics
16525
+ diagnostics,
16526
+ package: documentPackage
15334
16527
  });
15335
16528
  }
15336
16529
  return Promise.reject(/* @__PURE__ */ new Error(`unsupported conversion: ${source.format} -> ${targetFormat}`));
@@ -15344,4 +16537,4 @@ function fixedClock(date) {
15344
16537
  return { now: () => date };
15345
16538
  }
15346
16539
  //#endregion
15347
- export { AttributeSchema, BinaryPartSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, CommentSchema, CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentDrawPageSchema, ContentImageBlockSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentPathPointSchema, ContentPathSegmentSchema, ContentRunSchema, ContentSectionSchema, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentStrokeSchema, ContentSubpathSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, ContentVectorSchema, DEFAULT_LAYOUT_FONT, DefinedNameSchema, DocxBytesSchema, DocxEditor, DocxParagraph, DocxRun, DocxTable, DocxTableCell, DocxTableRow, HsqldbScriptParseError, LAYOUT_FORMAT_VERSION, NOOP_DIAGNOSTIC_SINK, OdbNoEmbeddedDataSourceError, OdbTableNotFoundError, OdbTableNotSpecifiedError, OdbUnsupportedFormatError, OdgBoxVector, OdgBytesSchema, OdgEditor, OdgLineVector, OdgPage, OdgPathVector, OdmUnresolvedSectionError, OdpBytesSchema, OdpEditor, OdpShape, OdpSlide, OdsBytesSchema, OdsCell, OdsEditor, OdsSheet, OdtBytesSchema, OdtEditor, OdtList, OdtListItem, OdtParagraph, OdtRun, OdtTable, OdtTableCell, OdtTableRow, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PackageSchema, PartSchema, PdfBytesSchema, PdfEncryptedError, PdfParseError, PptxBytesSchema, PptxEditor, PptxShape, PptxSlide, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, XlsxBytesSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, applyMathVariant, attr, base64ToBytes, buildDocxPackage, buildOdgPackage, buildOdpPackage, buildOdsPackage, buildOdtPackage, buildPptxPackage, buildXml, bytesToBase64, childrenWithTag, compactCodec, compactPackageCodec, convertDrawingToLayout, convertPresentationToLayout, convertSpreadsheetToLayout, convertWordprocessingToLayout, createDocx, createLocalDocumentConverter, createOdg, createOdp, createOds, createOdt, createPptx, decodeCompactPackage, decodeEntities, decodePackage, docxPdfCodec, docxToOdt, docxToPdf, elementChildren, elementLocalName, elementsWithTag, encodeCompactPackage, encodePackage, firstChildByLocalName, fixedClock, flipY, fromCompact, displayTextFor as hsqldbCellDisplayText, isCompactXmlNode, isContentBlock, isMathMlElement, isMathVariant, isXmlNode, layoutFormula, loadMathFont, localName, mapMathVariant, textContent as mathMlTextContent, odbTablesToSpreadsheetDocument, odbToCsv, odbToXlsx, odfToPdf, odgPdfCodec, odgToPdf, odmToPdf, odpPdfCodec, odpPptxCodec, odpToPdf, odpToPptx, odsPdfCodec, odsToPdf, odsToXlsx, odsXlsxCodec, odtDocxCodec, odtPdfCodec, odtToDocx, odtToPdf, openDocx, openOdg, openOdp, openOds, openOdt, openPptx, operatorProperties, packageCodec, parseHsqldbScript, parsePackage, parseXml, pdfCodec, pdfToDocx, pdfToOdg, pdfToOdp, pdfToOds, pdfToOdt, pdfToPptx, pptxPdfCodec, pptxToOdp, pptxToPdf, readDocxContent, readOdbTables, readOdfEmbeddedFormula, readOdfFormulaContent, readOdgContent, readOdpContent, readOdsContent, readOdtContent, readPdf, readPptxContent, reconstructDrawing, reconstructPresentation, reconstructSpreadsheet, reconstructWordprocessing, resolveRelationships, rgbHexToColor, rootElement, serializePackage, systemClock, textContent$1 as textContent, throwIfAborted, toCompact, unzipPackage, walk, writePdf, xlsxToOds, xmlCodec, zipPackage };
16540
+ export { AttributeSchema, BinaryPartSchema, COLOR_BLACK, CONTENT_FORMAT_VERSION, CommentSchema, CompactPackageSchema, CompactPartSchema, CompactXmlNodeSchema, ContentBlockSchema, ContentCellValueSchema, ContentDocumentSchema, ContentDrawPageSchema, ContentImageBlockSchema, ContentPageBreakSchema, ContentParagraphSchema, ContentPathPointSchema, ContentPathSegmentSchema, ContentRunSchema, ContentSectionSchema, ContentShapeSchema, ContentSheetCellSchema, ContentSheetColumnSchema, ContentSheetPrintRangeSchema, ContentSheetPrintSettingsSchema, ContentSheetRepeatRangeSchema, ContentSheetRowSchema, ContentSheetSchema, ContentSlideSchema, ContentStrokeSchema, ContentSubpathSchema, ContentTableCellSchema, ContentTableRowSchema, ContentTableSchema, ContentVectorSchema, DEFAULT_LAYOUT_FONT, DefinedNameSchema, DocxBytesSchema, DocxEditor, DocxParagraph, DocxRun, DocxTable, DocxTableCell, DocxTableRow, SUPPORTED_BACKUP_FORMAT_VERSION as FIREBIRD_SUPPORTED_BACKUP_FORMAT_VERSION, FirebirdBackupFormatError, FirebirdBackupParseError, FirebirdCompositeRecordUnsupportedError, FirebirdDataParseError, FirebirdSchemaParseError, FirebirdUnsupportedFieldTypeError, HsqldbRowFormatError, HsqldbScriptParseError, LAYOUT_FORMAT_VERSION, NOOP_DIAGNOSTIC_SINK, OdbNoEmbeddedDataSourceError, OdbTableNotFoundError, OdbTableNotSpecifiedError, OdbUnsupportedFormatError, OdgBoxVector, OdgBytesSchema, OdgEditor, OdgLineVector, OdgPage, OdgPathVector, OdmUnresolvedSectionError, OdpBytesSchema, OdpEditor, OdpShape, OdpSlide, OdsBytesSchema, OdsCell, OdsEditor, OdsSheet, OdtBytesSchema, OdtEditor, OdtList, OdtListItem, OdtParagraph, OdtRun, OdtTable, OdtTableCell, OdtTableRow, PAGE_SIZE_A4, PAGE_SIZE_LETTER, PackageSchema, PartSchema, PdfBytesSchema, PdfEncryptedError, PdfParseError, PptxBytesSchema, PptxEditor, PptxShape, PptxSlide, SLIDE_SIZE_STANDARD, SLIDE_SIZE_WIDESCREEN, XlsxBytesSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, applyMathVariant, attr, base64ToBytes, buildDocxPackage, buildOdgPackage, buildOdpPackage, buildOdsPackage, buildOdtPackage, buildPptxPackage, buildXml, bytesToBase64, childrenWithTag, compactCodec, compactPackageCodec, convertDrawingToLayout, convertPresentationToLayout, convertSpreadsheetToLayout, convertWordprocessingToLayout, createDocx, createLocalDocumentConverter, createOdg, createOdp, createOds, createOdt, createPptx, decodeCompactPackage, decodeEntities, decodeHsqldbCachedTables, decodePackage, docxPdfCodec, docxToOdt, docxToPdf, elementChildren, elementLocalName, elementsWithTag, encodeCompactPackage, encodePackage, firstChildByLocalName, fixedClock, flipY, fromCompact, displayTextFor as hsqldbCellDisplayText, isCompactXmlNode, isContentBlock, isMathMlElement, isMathVariant, isXmlNode, layoutFormula, loadMathFont, localName, mapMathVariant, textContent as mathMlTextContent, odbTablesToSpreadsheetDocument, odbToCsv, odbToXlsx, odfToPdf, odgPdfCodec, odgToPdf, odmToPdf, odpPdfCodec, odpPptxCodec, odpToPdf, odpToPptx, odsPdfCodec, odsToPdf, odsToXlsx, odsXlsxCodec, odtDocxCodec, odtPdfCodec, odtToDocx, odtToPdf, openDocx, openOdg, openOdp, openOds, openOdt, openPptx, operatorProperties, packageCodec, parseHsqldbScript, parsePackage, parseXml, pdfCodec, pdfToDocx, pdfToOdg, pdfToOdp, pdfToOds, pdfToOdt, pdfToPptx, pptxPdfCodec, pptxToOdp, pptxToPdf, readDocxContent, readFirebirdBackup, readOdbTables, readOdfEmbeddedFormula, readOdfFormulaContent, readOdgContent, readOdpContent, readOdsContent, readOdtContent, readPdf, readPptxContent, reconstructDrawing, reconstructPresentation, reconstructSpreadsheet, reconstructWordprocessing, resolveRelationships, rgbHexToColor, rootElement, serializePackage, systemClock, textContent$1 as textContent, throwIfAborted, toCompact, unzipPackage, walk, writePdf, xlsxToOds, xmlCodec, zipPackage };