@evotecit/officeimo 0.1.1 → 0.1.3
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/README.md +43 -49
- package/bundles/officeimo-canopyx.js +1047 -193
- package/bundles/officeimo-canopyx.mjs +958 -111
- package/bundles/officeimo-csv.js +18 -15
- package/bundles/officeimo-csv.mjs +16 -13
- package/bundles/officeimo-datatables.js +249 -153
- package/bundles/officeimo-datatables.mjs +169 -73
- package/bundles/officeimo-pdf.js +151 -67
- package/bundles/officeimo-pdf.mjs +127 -43
- package/bundles/officeimo-xlsx.js +78 -69
- package/bundles/officeimo-xlsx.mjs +26 -17
- package/bundles/officeimo.js +249 -153
- package/bundles/officeimo.mjs +169 -73
- package/dist/csv/index.js +16 -13
- package/dist/integrations/canopyx/diagnostics.d.ts +3 -0
- package/dist/integrations/canopyx/diagnostics.js +17 -0
- package/dist/integrations/canopyx/grouping.d.ts +6 -0
- package/dist/integrations/canopyx/grouping.js +188 -0
- package/dist/integrations/canopyx/index.d.ts +2 -2
- package/dist/integrations/canopyx/index.js +72 -15
- package/dist/integrations/canopyx/metadata.d.ts +4 -0
- package/dist/integrations/canopyx/metadata.js +51 -0
- package/dist/integrations/canopyx/presentation.d.ts +8 -0
- package/dist/integrations/canopyx/presentation.js +40 -0
- package/dist/integrations/canopyx/rule-predicates.d.ts +3 -0
- package/dist/integrations/canopyx/rule-predicates.js +110 -0
- package/dist/integrations/canopyx/rules.d.ts +6 -0
- package/dist/integrations/canopyx/rules.js +176 -0
- package/dist/integrations/canopyx/source.js +24 -22
- package/dist/integrations/canopyx/types.d.ts +89 -8
- package/dist/integrations/canopyx/workbook.d.ts +6 -0
- package/dist/integrations/canopyx/workbook.js +52 -0
- package/dist/opc/index.js +14 -9
- package/dist/pdf/font-resources.js +33 -14
- package/dist/pdf/pages.js +63 -16
- package/dist/pdf/table-band-flow.js +7 -2
- package/dist/pdf/table-band-plan.js +9 -1
- package/dist/pdf/table-layout.js +6 -2
- package/dist/pdf/table-structure.js +9 -8
- package/dist/xlsx/workbook.js +7 -4
- package/dist/xlsx/worksheet.js +2 -1
- package/dist/xml/index.js +3 -3
- package/package.json +1 -1
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { createGroupedReport } from "../../core/grouped-report.js";
|
|
2
|
+
import { ExportCell } from "../../core/presentation.js";
|
|
3
|
+
import { checkAbort } from "../../core/iteration.js";
|
|
4
|
+
import { createTotals } from "../../internal/totals.js";
|
|
5
|
+
import { captureFields } from "../../internal/capture.js";
|
|
6
|
+
import { datetime } from "./dates.js";
|
|
7
|
+
const identity = (value) => value instanceof Date ? "date:" + value.getTime() : typeof value + ":" + String(value);
|
|
8
|
+
const scalar = (value) => value instanceof ExportCell ? value.value : value;
|
|
9
|
+
/** Validate captured ranges, then use the owned grouping factory and its existing writers.
|
|
10
|
+
* Only ranges, labels and at most four active aggregate vectors are retained; no detail body is buffered. */
|
|
11
|
+
export function canopyGrouped(source, request, options, limits, report, format) {
|
|
12
|
+
const input = request.grouping;
|
|
13
|
+
if (input === undefined)
|
|
14
|
+
return undefined; // query.groupBy never manufactures a group snapshot.
|
|
15
|
+
if (request.values !== "raw") {
|
|
16
|
+
report({ code: "GROUPING_REQUIRES_RAW_VALUES" });
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
if (source.rowCount === null)
|
|
20
|
+
throw new TypeError("Captured grouping requires its exact scope recordCount.");
|
|
21
|
+
const grouping = captureFields(input, ["levels", "aggregates", "totals", "groups"]);
|
|
22
|
+
if (!Array.isArray(grouping.levels) || grouping.levels.length < 1 || grouping.levels.length > 4 || !Array.isArray(grouping.aggregates) || !Array.isArray(grouping.groups))
|
|
23
|
+
throw new TypeError("Canopy grouping needs one through four levels, aggregates and ordered groups.");
|
|
24
|
+
const levels = grouping.levels.map(level => Object.freeze(captureFields(level, ["column", "direction", "title"])));
|
|
25
|
+
if (levels.some(level => typeof level.column !== "string" || !level.column || level.direction !== "asc" && level.direction !== "desc") ||
|
|
26
|
+
new Set(levels.map(level => level.column)).size !== levels.length)
|
|
27
|
+
throw new TypeError("Canopy grouping levels need unique stable columns and directions.");
|
|
28
|
+
const declarations = grouping.aggregates.map(aggregate => Object.freeze(captureFields(aggregate, ["id", "column", "operation", "label"])));
|
|
29
|
+
const ids = new Set(), totals = Object.create(null);
|
|
30
|
+
const operations = { sum: "sum", count: "count", average: "average", minimum: "min", maximum: "max" };
|
|
31
|
+
for (const aggregate of declarations) {
|
|
32
|
+
if (typeof aggregate.id !== "string" || !aggregate.id || ids.has(aggregate.id))
|
|
33
|
+
throw new TypeError("Canopy aggregate IDs must be unique nonempty strings.");
|
|
34
|
+
ids.add(aggregate.id);
|
|
35
|
+
const column = source.columns.find(column => column.key === aggregate.column);
|
|
36
|
+
if (!column || column.type !== "number")
|
|
37
|
+
throw new TypeError("Canopy aggregate declarations require an exported raw numeric column.");
|
|
38
|
+
if (Object.hasOwn(totals, aggregate.column))
|
|
39
|
+
throw new TypeError("The grouped report supports one aggregate operation per column.");
|
|
40
|
+
const operation = operations[aggregate.operation];
|
|
41
|
+
if (operation === undefined) {
|
|
42
|
+
report({ code: "UNSUPPORTED_GROUP_AGGREGATE:" + aggregate.operation, columnId: aggregate.column });
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
totals[aggregate.column] = operation;
|
|
46
|
+
}
|
|
47
|
+
// Reuse the canonical operation validator rather than implementing aggregate semantics here.
|
|
48
|
+
createTotals(source.columns, totals);
|
|
49
|
+
const expected = (input) => {
|
|
50
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
51
|
+
throw new TypeError("Canopy aggregate values must be an ID-keyed object.");
|
|
52
|
+
const snapshot = { ...input };
|
|
53
|
+
if (Object.keys(snapshot).some(key => !ids.has(key)) || declarations.some(aggregate => !Object.hasOwn(snapshot, aggregate.id)))
|
|
54
|
+
throw new TypeError("Canopy aggregate values must reference exactly the captured declarations.");
|
|
55
|
+
for (const value of Object.values(snapshot))
|
|
56
|
+
if (value !== null && (typeof value !== "number" || !Number.isFinite(value)))
|
|
57
|
+
throw new TypeError("Canopy aggregate values must be finite numbers or null.");
|
|
58
|
+
return Object.freeze(snapshot);
|
|
59
|
+
};
|
|
60
|
+
const grandExpected = expected(grouping.totals), byDepth = levels.map(() => []), labels = levels.map(() => new Map());
|
|
61
|
+
let groups = 0, characters = 0;
|
|
62
|
+
const ranges = (inputs, offset, end, depth) => {
|
|
63
|
+
if (!Array.isArray(inputs))
|
|
64
|
+
throw new TypeError("Canopy groups must be ordered arrays.");
|
|
65
|
+
let cursor = offset;
|
|
66
|
+
const keys = new Set(), values = new Set();
|
|
67
|
+
for (const input of inputs) {
|
|
68
|
+
const group = captureFields(input, ["key", "value", "text", "offset", "count", "aggregates", "groups"]);
|
|
69
|
+
if (!group || typeof group.key !== "string" || keys.has(group.key) || !Number.isSafeInteger(group.offset) || !Number.isSafeInteger(group.count) ||
|
|
70
|
+
group.count <= 0 || group.offset !== cursor || group.count > end - group.offset)
|
|
71
|
+
throw new TypeError("Canopy group ranges must be nonempty contiguous half-open partitions within their parent.");
|
|
72
|
+
if (group.value !== null && !["string", "number", "boolean"].includes(typeof group.value) ||
|
|
73
|
+
typeof group.value === "number" && !Number.isFinite(group.value))
|
|
74
|
+
throw new TypeError("Canopy group values must be portable finite scalars.");
|
|
75
|
+
const dateColumn = request.columns.find(column => column.id === levels[depth].column)?.kind === "datetime";
|
|
76
|
+
const value = format === "xlsx" && dateColumn && typeof group.value === "string"
|
|
77
|
+
? datetime(group.value, options.datetime ?? "preserve", options.xlsx?.dateMode ?? request.timeZone) : group.value;
|
|
78
|
+
const key = identity(value), text = group.text ?? String(group.value ?? "");
|
|
79
|
+
if (typeof text !== "string" || values.has(key))
|
|
80
|
+
throw new TypeError("A Canopy group key cannot recur within the same parent.");
|
|
81
|
+
const previousLabel = labels[depth].get(key);
|
|
82
|
+
if (previousLabel !== undefined && previousLabel !== text)
|
|
83
|
+
throw new TypeError("The same grouping value needs consistent captured text at one level.");
|
|
84
|
+
labels[depth].set(key, text);
|
|
85
|
+
keys.add(group.key);
|
|
86
|
+
values.add(key);
|
|
87
|
+
if (++groups > 1000 || (characters += group.key.length + key.length + text.length) > 1000000)
|
|
88
|
+
throw new RangeError("Canopy group metadata exceeds the existing bounded report profile.");
|
|
89
|
+
const next = group.offset + group.count;
|
|
90
|
+
byDepth[depth].push(Object.freeze({ offset: group.offset, end: next, value, text, expected: expected(group.aggregates) }));
|
|
91
|
+
if (depth + 1 < levels.length)
|
|
92
|
+
ranges(group.groups ?? [], group.offset, next, depth + 1);
|
|
93
|
+
else if (group.groups !== undefined && group.groups.length)
|
|
94
|
+
throw new TypeError("Canopy nested groups exceed their declared levels.");
|
|
95
|
+
cursor = next;
|
|
96
|
+
}
|
|
97
|
+
if (cursor !== end)
|
|
98
|
+
throw new TypeError("Canopy grouping does not cover its complete exported detail range.");
|
|
99
|
+
};
|
|
100
|
+
ranges(grouping.groups, 0, source.rowCount, 0);
|
|
101
|
+
// Validate the producer's wire arithmetic separately from the grouped writer's native formula caches.
|
|
102
|
+
// Canopy sum/average use compensated accumulation and return null without numeric inputs.
|
|
103
|
+
const wireTotals = () => {
|
|
104
|
+
const ordinary = createTotals(source.columns, totals), sums = source.columns.map(() => 0), corrections = source.columns.map(() => 0), counts = source.columns.map(() => 0);
|
|
105
|
+
return {
|
|
106
|
+
accept(values) {
|
|
107
|
+
for (let index = 0; index < values.length; index++) {
|
|
108
|
+
const value = scalar(values[index]), operation = totals[source.columns[index].key];
|
|
109
|
+
if (operation !== "sum" && operation !== "average") {
|
|
110
|
+
ordinary[index].accept(value);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
114
|
+
continue;
|
|
115
|
+
counts[index] = counts[index] + 1;
|
|
116
|
+
const next = value - corrections[index], total = sums[index] + next;
|
|
117
|
+
corrections[index] = total - sums[index] - next;
|
|
118
|
+
sums[index] = total;
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
value(index) {
|
|
122
|
+
const operation = totals[source.columns[index].key];
|
|
123
|
+
return operation === "sum" || operation === "average" ? !counts[index] ? null
|
|
124
|
+
: operation === "sum" ? sums[index] : sums[index] / counts[index] : ordinary[index].value();
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const indexes = levels.map(() => 0), active = levels.map(() => undefined);
|
|
129
|
+
const at = (depth, row) => {
|
|
130
|
+
const list = byDepth[depth];
|
|
131
|
+
while (list[indexes[depth]] && list[indexes[depth]].end <= row)
|
|
132
|
+
indexes[depth] = indexes[depth] + 1;
|
|
133
|
+
const range = list[indexes[depth]];
|
|
134
|
+
if (!range || row < range.offset || row >= range.end)
|
|
135
|
+
throw new TypeError("A detail row is outside its captured Canopy grouping.");
|
|
136
|
+
return range;
|
|
137
|
+
};
|
|
138
|
+
const verify = (actual, expected) => {
|
|
139
|
+
for (const declaration of declarations) {
|
|
140
|
+
const position = source.columns.findIndex(column => column.key === declaration.column), observed = actual.value(position), declared = expected[declaration.id];
|
|
141
|
+
// Exact producer-wire comparison retains wrong-scope rejection without rounding native caches or applying an epsilon.
|
|
142
|
+
if (observed !== declared)
|
|
143
|
+
throw new TypeError("Canopy captured aggregate differs from its consumed rows: " + declaration.id + ".");
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
const same = (actual, expected) => actual instanceof Date && expected instanceof Date
|
|
147
|
+
? actual.getTime() === expected.getTime() : actual === expected;
|
|
148
|
+
async function* rows() {
|
|
149
|
+
let index = 0;
|
|
150
|
+
const grand = wireTotals();
|
|
151
|
+
for await (const values of source.rows()) {
|
|
152
|
+
checkAbort(options.signal);
|
|
153
|
+
for (let depth = 0; depth < levels.length; depth++) {
|
|
154
|
+
const range = at(depth, index), column = source.columns.findIndex(column => column.key === levels[depth].column);
|
|
155
|
+
if (column >= 0 && !same(scalar(values[column]), range.value))
|
|
156
|
+
throw new TypeError("Canopy detail value disagrees with its captured group range.");
|
|
157
|
+
if (range.offset === index)
|
|
158
|
+
active[depth] = { range, aggregates: wireTotals() };
|
|
159
|
+
}
|
|
160
|
+
grand.accept(values);
|
|
161
|
+
for (const group of active)
|
|
162
|
+
group.aggregates.accept(values);
|
|
163
|
+
yield values;
|
|
164
|
+
index++;
|
|
165
|
+
for (let depth = levels.length - 1; depth >= 0; depth--) {
|
|
166
|
+
const group = active[depth];
|
|
167
|
+
if (group.range.end === index) {
|
|
168
|
+
verify(group.aggregates, group.range.expected);
|
|
169
|
+
active[depth] = undefined;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
verify(grand, grandExpected);
|
|
174
|
+
}
|
|
175
|
+
const groupBy = levels.map((level, depth) => {
|
|
176
|
+
const visible = source.columns.some(column => column.key === level.column);
|
|
177
|
+
return { key: level.column,
|
|
178
|
+
...(visible ? {} : { value: (_row, context) => at(depth, context.rowIndex).value }),
|
|
179
|
+
label: (value) => labels[depth].get(identity(value)) ?? String(value ?? "") };
|
|
180
|
+
});
|
|
181
|
+
const sourceLimits = limits === undefined ? undefined : {
|
|
182
|
+
...(limits.maxRows === undefined ? {} : { maxRows: limits.maxRows }),
|
|
183
|
+
...(limits.maxCells === undefined ? {} : { maxCells: limits.maxCells }),
|
|
184
|
+
...(limits.maxTextCharacters === undefined ? {} : { maxTextCharacters: limits.maxTextCharacters })
|
|
185
|
+
};
|
|
186
|
+
return createGroupedReport(rows(), { columns: source.columns, groupBy, totals,
|
|
187
|
+
...(options.signal === undefined ? {} : { signal: options.signal }), ...(sourceLimits === undefined ? {} : { limits: sourceLimits }) });
|
|
188
|
+
}
|
|
@@ -3,8 +3,8 @@ import type { CanopyCapture, CanopyFormat, CanopyWriteOptions } from "./types.js
|
|
|
3
3
|
export { createCanopyExport } from "./source.js";
|
|
4
4
|
export { ExportCell } from "../../core/presentation.js";
|
|
5
5
|
export { PdfFont } from "../../pdf/font.js";
|
|
6
|
-
export type { CanopyCapture, CanopyExportCell, CanopyExportColumn, CanopyExportRow, CanopyExport, CanopyFormat, CanopyDiagnostic, CanopySourceOptions, CanopyWriteOptions } from "./types.js";
|
|
7
|
-
/** Write a captured CanopyX grid to a caller-owned destination;
|
|
6
|
+
export type { CanopyCapture, CanopyExportCell, CanopyExportColumn, CanopyExportRow, CanopyExport, CanopyFormat, CanopyDiagnostic, CanopySourceOptions, CanopyWriteOptions, CanopyNumberFormat, CanopyExportGroup, CanopyExportGrouping, CanopyRuleFilter, CanopyRulePredicate, CanopyFormatRule } from "./types.js";
|
|
7
|
+
/** Write a captured CanopyX grid to a caller-owned destination; partial bytes remain caller-owned on failure. */
|
|
8
8
|
export declare function writeCanopyTo(capture: CanopyCapture, format: CanopyFormat, destination: OutputDestination, options?: CanopyWriteOptions): Promise<ExportResult>;
|
|
9
9
|
/** Export an immutable native capture as a Blob without loading or registering CanopyX. */
|
|
10
10
|
export declare function exportCanopy(capture: CanopyCapture, format: CanopyFormat, options?: CanopyWriteOptions): Promise<Blob>;
|
|
@@ -1,34 +1,91 @@
|
|
|
1
|
-
import { BlobByteSink } from "../../core/index.js";
|
|
1
|
+
import { BlobByteSink, ExportCell } from "../../core/index.js";
|
|
2
2
|
import { notifyProgress } from "../../core/progress.js";
|
|
3
3
|
import { captureFields } from "../../internal/capture.js";
|
|
4
4
|
import { captureCommonLimits, captureXlsxOptions, captureCsvOptions, capturePdfOptions, mergeAdapterLimits } from "../options.js";
|
|
5
5
|
import { writeXlsxTo } from "../../xlsx/index.js";
|
|
6
6
|
import { writeCsvTo } from "../../csv/index.js";
|
|
7
|
-
import { writePdfTo } from "../../pdf/index.js";
|
|
8
|
-
import {
|
|
7
|
+
import { writePdfTo, writeGroupedPdfTo } from "../../pdf/index.js";
|
|
8
|
+
import { prepareCanopyExport } from "./source.js";
|
|
9
|
+
import { canopyPins } from "./presentation.js";
|
|
10
|
+
import { canopyRules } from "./rules.js";
|
|
11
|
+
import { canopyGrouped } from "./grouping.js";
|
|
12
|
+
import { canopyAbout } from "./metadata.js";
|
|
13
|
+
import { writeCanopyWorkbook } from "./workbook.js";
|
|
9
14
|
export { createCanopyExport } from "./source.js";
|
|
10
15
|
export { ExportCell } from "../../core/presentation.js";
|
|
11
16
|
export { PdfFont } from "../../pdf/font.js";
|
|
12
|
-
/** Write a captured CanopyX grid to a caller-owned destination;
|
|
17
|
+
/** Write a captured CanopyX grid to a caller-owned destination; partial bytes remain caller-owned on failure. */
|
|
13
18
|
export async function writeCanopyTo(capture, format, destination, options = {}) {
|
|
14
|
-
const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress"]);
|
|
19
|
+
const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress", "grouped", "about"]);
|
|
15
20
|
const { signal, onProgress } = selected, limits = captureCommonLimits(selected.limits);
|
|
16
21
|
const xlsx = captureXlsxOptions(format === "xlsx" ? selected.xlsx : undefined);
|
|
17
22
|
const csv = captureCsvOptions(format === "csv" ? selected.csv : undefined);
|
|
18
23
|
const pdf = capturePdfOptions(format === "pdf" ? selected.pdf : undefined);
|
|
19
|
-
const
|
|
24
|
+
const prepared = prepareCanopyExport(capture, format, { ...selected, xlsx }), { request, report, tones } = prepared;
|
|
25
|
+
if (selected.about !== undefined && typeof selected.about !== "boolean")
|
|
26
|
+
throw new TypeError("Canopy about must be boolean.");
|
|
27
|
+
const labels = selected.grouped === undefined ? undefined : captureFields(selected.grouped, ["labelColumn", "subtotalLabel", "grandTotalLabel", "includeGrandTotal", "continuationLabel", "groupHeadingLevel"]);
|
|
28
|
+
const capturedLabels = labels && { ...labels, ...(labels.labelColumn === undefined ? {} : { labelColumn: Object.freeze({ header: labels.labelColumn.header }) }) };
|
|
29
|
+
const about = format === "xlsx" && selected.about ? canopyAbout(request, xlsx) : undefined;
|
|
30
|
+
const ruleCellTypes = new Map();
|
|
31
|
+
let consumed = 0;
|
|
32
|
+
const source = Object.freeze({ ...prepared.source, async *rows() {
|
|
33
|
+
for await (const row of prepared.source.rows()) {
|
|
34
|
+
for (const [column, type] of ruleCellTypes) {
|
|
35
|
+
const cell = row[column], raw = cell instanceof ExportCell ? cell.value : cell;
|
|
36
|
+
if (raw == null || type === "number" && typeof raw === "number" && Number.isFinite(raw) || type === "date" && raw instanceof Date && Number.isFinite(raw.getTime()))
|
|
37
|
+
continue;
|
|
38
|
+
const code = "UNSUPPORTED_NATIVE_RULE_CELL_TYPE:" + type;
|
|
39
|
+
report({ code, columnId: source.columns[column].key });
|
|
40
|
+
// Text fallback cannot retract an already captured native declaration after streaming starts.
|
|
41
|
+
throw new TypeError("Unsupported Canopy presentation: " + code + " (" + source.columns[column].key + ")");
|
|
42
|
+
}
|
|
43
|
+
consumed++;
|
|
44
|
+
yield row;
|
|
45
|
+
}
|
|
46
|
+
} });
|
|
20
47
|
const progress = onProgress ? { onProgress: (event) => {
|
|
21
|
-
|
|
48
|
+
// About and generated group rows consume output budgets, but never become exported source details.
|
|
49
|
+
notifyProgress(onProgress, { ...event, rows: consumed,
|
|
50
|
+
...(event.sheetRows === undefined ? {} : { sheetRows: about !== undefined && event.sheetName === "About" ? 0 : consumed }),
|
|
51
|
+
...(source.rowCount === null ? {} : { totalRows: source.rowCount }) });
|
|
22
52
|
} } : {};
|
|
23
53
|
const stream = { ...(signal ? { signal } : {}), ...progress };
|
|
24
|
-
if (format === "xlsx")
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
54
|
+
if (format === "xlsx") {
|
|
55
|
+
const formatLimits = mergeAdapterLimits(xlsx.limits, limits), grouped = canopyGrouped(source, request, { ...selected, xlsx }, formatLimits, report, format);
|
|
56
|
+
const pinned = canopyPins(request.columns, report), rules = canopyRules(request, format, grouped !== undefined, tones, report, { ...selected, xlsx }, ruleCellTypes);
|
|
57
|
+
const sheet = { ...xlsx.sheet,
|
|
58
|
+
freezeHeader: xlsx.sheet?.freezeHeader ?? (xlsx.sheet?.includeHeader !== false),
|
|
59
|
+
freezeColumns: xlsx.sheet?.freezeColumns ?? (pinned ? pinned + (grouped ? 1 : 0) : 0),
|
|
60
|
+
conditionalFormats: [...rules, ...(xlsx.sheet?.conditionalFormats ?? [])] };
|
|
61
|
+
const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits };
|
|
62
|
+
if (grouped || about)
|
|
63
|
+
return writeCanopyWorkbook(source, grouped, destination, settings, capturedLabels, about);
|
|
64
|
+
return writeXlsxTo(source.rows(), destination, settings);
|
|
65
|
+
}
|
|
66
|
+
if (format === "pdf") {
|
|
67
|
+
const formatLimits = mergeAdapterLimits(pdf.limits, limits), grouped = canopyGrouped(source, request, selected, formatLimits, report, format);
|
|
68
|
+
canopyRules(request, format, grouped !== undefined, tones, report, selected);
|
|
69
|
+
// CSS pixels become points before the existing fit/band policy. Explicit PDF point widths win.
|
|
70
|
+
const fitted = request.columns.every(column => column.width !== undefined) ? request.columns.map(column => column.width.preferred * 72 / 96) : undefined;
|
|
71
|
+
const widths = pdf.columnWidths ?? fitted;
|
|
72
|
+
const settings = { ...(fitted === undefined ? {} : { orientation: "landscape", wideTable: "fit" }), ...pdf, ...stream, limits: formatLimits };
|
|
73
|
+
if (grouped) {
|
|
74
|
+
if (pdf.headerRows !== undefined || pdf.footer !== undefined)
|
|
75
|
+
throw new TypeError("Grouped Canopy PDF owns heading and summary rows.");
|
|
76
|
+
const { headerRows: _headers, footer: _footer, ...groupedSettings } = settings;
|
|
77
|
+
return writeGroupedPdfTo(grouped, destination, { ...groupedSettings,
|
|
78
|
+
...(widths === undefined ? {} : { columnWidths: [72, ...widths] }),
|
|
79
|
+
labelColumn: { header: capturedLabels?.labelColumn?.header ?? "Group", width: 12 },
|
|
80
|
+
subtotalLabel: capturedLabels?.subtotalLabel ?? (group => group.label + " total"),
|
|
81
|
+
grandTotalLabel: capturedLabels?.grandTotalLabel ?? (() => "Grand total"),
|
|
82
|
+
...(capturedLabels?.includeGrandTotal === undefined ? {} : { includeGrandTotal: capturedLabels.includeGrandTotal }),
|
|
83
|
+
...(capturedLabels?.continuationLabel === undefined ? {} : { continuationLabel: capturedLabels.continuationLabel }),
|
|
84
|
+
...(capturedLabels?.groupHeadingLevel === undefined ? {} : { groupHeadingLevel: capturedLabels.groupHeadingLevel }) });
|
|
85
|
+
}
|
|
86
|
+
return writePdfTo(source.rows(), destination, { ...settings, columns: source.columns, ...(widths === undefined ? {} : { columnWidths: widths }) });
|
|
87
|
+
}
|
|
88
|
+
return writeCsvTo(source.rows(), destination, { ...csv, ...stream, columns: source.columns, valueMode: request.values,
|
|
32
89
|
limits: mergeAdapterLimits(csv.limits, limits) });
|
|
33
90
|
}
|
|
34
91
|
/** Export an immutable native capture as a Blob without loading or registering CanopyX. */
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { CanopyCapture } from "./types.js";
|
|
2
|
+
import type { XlsxOptions } from "../../xlsx/index.js";
|
|
3
|
+
/** Snapshot optional About metadata before enumeration. The accepted query is serialized, never evaluated. */
|
|
4
|
+
export declare function canopyAbout(request: CanopyCapture["request"], options: Pick<XlsxOptions, "oversizedText" | "invalidCharacterPolicy">): readonly (readonly [string, string | number])[];
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { cellText } from "../../xlsx/values.js";
|
|
2
|
+
import { cleanXml } from "../../xml/index.js";
|
|
3
|
+
/** Snapshot optional About metadata before enumeration. The accepted query is serialized, never evaluated. */
|
|
4
|
+
export function canopyAbout(request, options) {
|
|
5
|
+
const result = [["revision", request.revision], ["recordCount", request.recordCount === null ? "unknown" : request.recordCount]];
|
|
6
|
+
if (request.scope !== undefined) {
|
|
7
|
+
if (!["filtered", "selected", "all"].includes(request.scope))
|
|
8
|
+
throw new TypeError("Invalid Canopy export scope.");
|
|
9
|
+
result.push(["scope", request.scope]);
|
|
10
|
+
}
|
|
11
|
+
for (const key of ["total", "matched"])
|
|
12
|
+
if (request[key] !== undefined) {
|
|
13
|
+
const value = request[key];
|
|
14
|
+
if (value === null) {
|
|
15
|
+
result.push([key, "unknown"]);
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
19
|
+
throw new TypeError("Canopy metadata counts must be nonnegative safe integers.");
|
|
20
|
+
result.push([key, value]);
|
|
21
|
+
}
|
|
22
|
+
if (request.generatedAt !== undefined) {
|
|
23
|
+
if (typeof request.generatedAt !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(request.generatedAt) || !Number.isFinite(new Date(request.generatedAt).getTime()))
|
|
24
|
+
throw new TypeError("Canopy generatedAt must be a captured UTC ISO instant.");
|
|
25
|
+
result.push(["generatedAt", request.generatedAt]);
|
|
26
|
+
}
|
|
27
|
+
if (request.selection !== undefined) {
|
|
28
|
+
if (!Array.isArray(request.selection) || request.selection.some(id => typeof id !== "string"))
|
|
29
|
+
throw new TypeError("Canopy selection metadata must contain stable string IDs.");
|
|
30
|
+
result.push(["selection", JSON.stringify(request.selection)]);
|
|
31
|
+
}
|
|
32
|
+
if (request.query !== undefined) {
|
|
33
|
+
if (!request.query || typeof request.query !== "object" || Array.isArray(request.query))
|
|
34
|
+
throw new TypeError("Canopy accepted query must be a captured object.");
|
|
35
|
+
const query = JSON.stringify(request.query);
|
|
36
|
+
if (typeof query !== "string")
|
|
37
|
+
throw new TypeError("Canopy accepted query must serialize as JSON metadata.");
|
|
38
|
+
result.push(["query", query]);
|
|
39
|
+
}
|
|
40
|
+
if (result.reduce((sum, row) => sum + row[0].length + String(row[1]).length, 0) > 65536)
|
|
41
|
+
throw new RangeError("Canopy About metadata exceeds 65,536 captured characters.");
|
|
42
|
+
// Validate known cell text before consuming details; overflow preservation and XML policy stay workbook-owned.
|
|
43
|
+
for (const [field, value] of result) {
|
|
44
|
+
cellText(field, options.invalidCharacterPolicy);
|
|
45
|
+
if (options.oversizedText === "preserve")
|
|
46
|
+
cleanXml(value, options.invalidCharacterPolicy);
|
|
47
|
+
else
|
|
48
|
+
cellText(value, options.invalidCharacterPolicy);
|
|
49
|
+
}
|
|
50
|
+
return Object.freeze(result.map(row => Object.freeze(row)));
|
|
51
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { CanopyExportColumn, CanopyNumberFormat, CanopyDiagnostic } from "./types.js";
|
|
2
|
+
/** Calibri 11, 96-DPI CSS pixels, seven-pixel maximum digit and five-pixel cell padding.
|
|
3
|
+
* Quantize to native 1/256-character units; this is a reproducible profile, not pixel-identical rendering. */
|
|
4
|
+
export declare function canopyXlsxWidth(pixels: number): number;
|
|
5
|
+
/** Escape literal prefixes/suffixes; no browser formatter or CSS becomes workbook code. */
|
|
6
|
+
export declare function canopyNumberFormat(input: CanopyNumberFormat, report: (diagnostic: CanopyDiagnostic) => void, id: string): string | undefined;
|
|
7
|
+
/** Only a contiguous leading left pin can be represented by an Excel freeze pane. */
|
|
8
|
+
export declare function canopyPins(columns: readonly CanopyExportColumn[], report: (diagnostic: CanopyDiagnostic) => void): number;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Calibri 11, 96-DPI CSS pixels, seven-pixel maximum digit and five-pixel cell padding.
|
|
2
|
+
* Quantize to native 1/256-character units; this is a reproducible profile, not pixel-identical rendering. */
|
|
3
|
+
export function canopyXlsxWidth(pixels) {
|
|
4
|
+
const width = Math.floor((pixels < 12 ? pixels / 12 : (pixels - 5) / 7) * 256) / 256;
|
|
5
|
+
if (!Number.isFinite(width) || width <= 0 || width > 255)
|
|
6
|
+
throw new RangeError("Captured width exceeds the Calibri-11 XLSX width profile.");
|
|
7
|
+
return width;
|
|
8
|
+
}
|
|
9
|
+
/** Escape literal prefixes/suffixes; no browser formatter or CSS becomes workbook code. */
|
|
10
|
+
export function canopyNumberFormat(input, report, id) {
|
|
11
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
12
|
+
throw new TypeError("Canopy numeric format must be an object.");
|
|
13
|
+
if (Object.keys(input).some(key => !["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"].includes(key))) {
|
|
14
|
+
report({ code: "UNSUPPORTED_NUMBER_FORMAT", columnId: id });
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
const { minimumFractionDigits: minimum = 0, maximumFractionDigits: maximum = 3, prefix = "", suffix = "" } = input;
|
|
18
|
+
if (!Number.isInteger(minimum) || !Number.isInteger(maximum) || minimum < 0 || maximum < minimum || maximum > 10 ||
|
|
19
|
+
typeof prefix !== "string" || typeof suffix !== "string" || prefix.length > 16 || suffix.length > 16)
|
|
20
|
+
throw new TypeError("Canopy numeric fraction bounds must be ordered integers from zero through ten, with literal affixes of at most sixteen characters.");
|
|
21
|
+
const literal = (value) => value ? '"' + value.replace(/"/g, '"\\""') + '"' : "";
|
|
22
|
+
return literal(prefix) + "0" + (maximum ? "." + "0".repeat(minimum) + "#".repeat(maximum - minimum) : "") + literal(suffix);
|
|
23
|
+
}
|
|
24
|
+
/** Only a contiguous leading left pin can be represented by an Excel freeze pane. */
|
|
25
|
+
export function canopyPins(columns, report) {
|
|
26
|
+
let leading = 0, ended = false;
|
|
27
|
+
for (const column of columns) {
|
|
28
|
+
const pin = column.pinned;
|
|
29
|
+
if (pin !== undefined && pin !== null && pin !== "left" && pin !== "right")
|
|
30
|
+
throw new TypeError("Invalid Canopy pin.");
|
|
31
|
+
if (!ended && pin === "left")
|
|
32
|
+
leading++;
|
|
33
|
+
else {
|
|
34
|
+
ended = true;
|
|
35
|
+
if (pin === "left" || pin === "right")
|
|
36
|
+
report({ code: "UNREPRESENTABLE_PIN:" + pin, columnId: column.id });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return leading;
|
|
40
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { CanopyCapture, CanopyRulePredicate, CanopySourceOptions } from "./types.js";
|
|
2
|
+
/** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
|
|
3
|
+
export declare function canopyPredicate(request: CanopyCapture["request"], grouped: boolean, options: CanopySourceOptions, root: CanopyRulePredicate, unsupported: (code: string) => never, cellTypes: Map<number, "number" | "date">): string;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { columnName, excelDate } from "../../xlsx/values.js";
|
|
2
|
+
import { captureFields } from "../../internal/capture.js";
|
|
3
|
+
import { datetime } from "./dates.js";
|
|
4
|
+
/** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
|
|
5
|
+
export function canopyPredicate(request, grouped, options, root, unsupported, cellTypes) {
|
|
6
|
+
let nodes = 0;
|
|
7
|
+
const operations = { eq: "=", ne: "<>", gt: ">", ge: ">=", lt: "<", le: "<=" };
|
|
8
|
+
const numeric = (value) => {
|
|
9
|
+
const number = typeof value === "boolean" ? Number(value) : typeof value === "string" ? Number(value) : value;
|
|
10
|
+
// Use platform decimal conversion; separator/culture profiles need a diagnostic, not a second parser.
|
|
11
|
+
if (typeof value === "string") {
|
|
12
|
+
const text = value.trim().toLowerCase();
|
|
13
|
+
if (Number.parseFloat(value) !== number || ["0x", "0b", "0o"].some(prefix => text.startsWith(prefix)))
|
|
14
|
+
return unsupported("UNSUPPORTED_NUMERIC_RULE_LITERAL");
|
|
15
|
+
}
|
|
16
|
+
if (!Number.isFinite(number) || Math.abs(number) > Number.MAX_SAFE_INTEGER)
|
|
17
|
+
throw new TypeError("Canopy rule comparison values must be finite safe-range numbers.");
|
|
18
|
+
return number;
|
|
19
|
+
};
|
|
20
|
+
const date = (value) => {
|
|
21
|
+
if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
|
|
22
|
+
return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
|
|
23
|
+
if (typeof value === "boolean")
|
|
24
|
+
return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
|
|
25
|
+
if (typeof value === "number" && !Number.isSafeInteger(value))
|
|
26
|
+
return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
|
|
27
|
+
try {
|
|
28
|
+
const literal = typeof value === "number" ? new Date(value).toISOString() : value;
|
|
29
|
+
const captured = datetime(literal, "typed", "utc");
|
|
30
|
+
if (!(captured instanceof Date))
|
|
31
|
+
return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
|
|
32
|
+
const serial = excelDate(captured, "utc");
|
|
33
|
+
if (serial === null)
|
|
34
|
+
return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
|
|
35
|
+
return serial;
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (!(error instanceof TypeError) && !(error instanceof RangeError))
|
|
39
|
+
throw error;
|
|
40
|
+
return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const leaf = (input) => {
|
|
44
|
+
if (++nodes > 64)
|
|
45
|
+
return unsupported("RULE_PREDICATE_LIMIT");
|
|
46
|
+
const filter = captureFields(input, ["column", "operator", "values"]), operation = operations[filter.operator];
|
|
47
|
+
if (Object.keys(filter).some(key => !["column", "operator", "values"].includes(key)))
|
|
48
|
+
return unsupported("UNSUPPORTED_RULE_FILTER_OPTIONS");
|
|
49
|
+
const index = request.columns.findIndex(column => column.id === filter.column);
|
|
50
|
+
if (index < 0)
|
|
51
|
+
return unsupported("RULE_COLUMN_NOT_EXPORTED:" + filter.column);
|
|
52
|
+
const column = request.columns[index], letter = columnName(index + 1 + (grouped ? 1 : 0));
|
|
53
|
+
const reference = "INDEX($" + letter + ":$" + letter + ",ROW())", present = "NOT(ISBLANK(" + reference + "))";
|
|
54
|
+
if (column.kind === "number")
|
|
55
|
+
cellTypes.set(index, "number");
|
|
56
|
+
if (column.kind === "datetime") {
|
|
57
|
+
if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
|
|
58
|
+
return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
|
|
59
|
+
cellTypes.set(index, "date");
|
|
60
|
+
}
|
|
61
|
+
if (filter.operator === "isNull" || filter.operator === "isNotNull") {
|
|
62
|
+
if (filter.values !== undefined && filter.values.length)
|
|
63
|
+
return unsupported("UNSUPPORTED_NULL_RULE_OPERANDS");
|
|
64
|
+
return filter.operator === "isNull" ? "ISBLANK(" + reference + ")" : present;
|
|
65
|
+
}
|
|
66
|
+
if (!operation || !Array.isArray(filter.values) || filter.values.length !== 1)
|
|
67
|
+
return unsupported("UNSUPPORTED_RULE_FILTER:" + filter.operator);
|
|
68
|
+
const value = filter.values[0];
|
|
69
|
+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
|
|
70
|
+
throw new TypeError("Canopy rule values must be portable scalars.");
|
|
71
|
+
if (column.kind === "number" || column.kind === "datetime") {
|
|
72
|
+
const operand = column.kind === "number" ? numeric(value) : date(value);
|
|
73
|
+
return "AND(" + present + ",ISNUMBER(" + reference + ")," + reference + operation + String(operand) + ")";
|
|
74
|
+
}
|
|
75
|
+
if (filter.operator !== "eq" && filter.operator !== "ne")
|
|
76
|
+
return unsupported("UNSUPPORTED_TEXT_RULE_COMPARISON");
|
|
77
|
+
// Canopy's Unicode text folding is not the native workbook's comparison contract.
|
|
78
|
+
if (typeof value === "string")
|
|
79
|
+
return unsupported("UNQUALIFIED_NATIVE_TEXT_COMPARISON");
|
|
80
|
+
const kind = typeof value === "boolean" ? "ISLOGICAL" : "ISNUMBER";
|
|
81
|
+
const literal = typeof value === "boolean" ? value ? "TRUE" : "FALSE" : String(numeric(value));
|
|
82
|
+
const sameType = kind + "(" + reference + ")", comparison = reference + operation + literal;
|
|
83
|
+
return filter.operator === "eq" ? "AND(" + present + "," + sameType + "," + comparison + ")"
|
|
84
|
+
: "AND(" + present + ",OR(NOT(" + sameType + ")," + comparison + "))";
|
|
85
|
+
};
|
|
86
|
+
const visit = (input, depth) => {
|
|
87
|
+
if (depth > 4 || ++nodes > 64)
|
|
88
|
+
return unsupported("RULE_PREDICATE_LIMIT");
|
|
89
|
+
if (!input || typeof input !== "object")
|
|
90
|
+
throw new TypeError("Canopy rule predicate must be an object.");
|
|
91
|
+
const captured = captureFields(input, ["operator", "filters", "groups"]);
|
|
92
|
+
if (captured.operator !== "and" && captured.operator !== "or")
|
|
93
|
+
return unsupported("UNSUPPORTED_RULE_BOOLEAN:" + captured.operator);
|
|
94
|
+
const filters = captured.filters ?? [], groups = captured.groups ?? [];
|
|
95
|
+
if (!Array.isArray(filters) || !Array.isArray(groups))
|
|
96
|
+
throw new TypeError("Canopy predicate filters and groups must be arrays.");
|
|
97
|
+
const terms = [];
|
|
98
|
+
for (const filter of filters)
|
|
99
|
+
terms.push(leaf(filter));
|
|
100
|
+
for (const group of groups)
|
|
101
|
+
terms.push(visit(group, depth + 1));
|
|
102
|
+
if (!terms.length)
|
|
103
|
+
return unsupported("EMPTY_RULE_PREDICATE");
|
|
104
|
+
return captured.operator.toUpperCase() + "(" + terms.join(",") + ")";
|
|
105
|
+
};
|
|
106
|
+
const formula = visit(root, 1);
|
|
107
|
+
if (formula.length > 8192)
|
|
108
|
+
return unsupported("RULE_FORMULA_LIMIT");
|
|
109
|
+
return formula;
|
|
110
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CellPresentation } from "../../core/index.js";
|
|
2
|
+
import type { ConditionalFormat } from "../../xlsx/index.js";
|
|
3
|
+
import type { CanopyCapture, CanopyDiagnostic, CanopyFormat, CanopySourceOptions } from "./types.js";
|
|
4
|
+
/** Compile declarations in source order, then emit native target/aspect priorities.
|
|
5
|
+
* Data-column selectors let grouped writers exclude generated headings, subtotals and grand totals. */
|
|
6
|
+
export declare function canopyRules(request: CanopyCapture["request"], format: CanopyFormat, grouped: boolean, tones: ReadonlyMap<string, Readonly<CellPresentation>>, report: (diagnostic: CanopyDiagnostic) => void, options?: CanopySourceOptions, cellTypes?: Map<number, "number" | "date">): readonly ConditionalFormat[];
|