@zalosai/zalos-cli 0.2.28 → 0.2.29
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.
|
@@ -5,6 +5,61 @@ import { readProfile } from '../credentials.js';
|
|
|
5
5
|
import { printJson } from '../utils/output.js';
|
|
6
6
|
import { action, dataRow, resourceId } from '../utils/product-api.js';
|
|
7
7
|
import { profileSample } from './registry-sample.js';
|
|
8
|
+
function matchingHeaders(sample, spec) {
|
|
9
|
+
const parser = spec.parser;
|
|
10
|
+
if (!parser ||
|
|
11
|
+
parser.kind !== sample.format.kind ||
|
|
12
|
+
sample.headerRow !== sample.registryHeaderRow)
|
|
13
|
+
return;
|
|
14
|
+
if (sample.format.kind === 'xlsx' && (parser.sheet ?? sample.firstSheet) !== sample.format.sheet)
|
|
15
|
+
return;
|
|
16
|
+
if (sample.format.kind === 'csv') {
|
|
17
|
+
if ((parser.delimiter ?? sample.defaultDelimiter) !== sample.format.delimiter)
|
|
18
|
+
return;
|
|
19
|
+
const encoding = parser.encoding?.toLowerCase().replace(/[-_]/g, '');
|
|
20
|
+
if (encoding
|
|
21
|
+
? encoding !== sample.format.encoding.replace(/-/g, '')
|
|
22
|
+
: sample.format.encoding === 'cp1252')
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const snake = (name) => name
|
|
26
|
+
.trim()
|
|
27
|
+
.toLowerCase()
|
|
28
|
+
.replace(/[^a-z0-9]+/g, '_')
|
|
29
|
+
.replace(/^_+|_+$/g, '') || 'col';
|
|
30
|
+
const headers = new Map();
|
|
31
|
+
for (const { fieldName } of sample.columns) {
|
|
32
|
+
const base = snake(fieldName);
|
|
33
|
+
let key = base;
|
|
34
|
+
for (let n = 2; headers.has(key); n++)
|
|
35
|
+
key = base + '_' + n;
|
|
36
|
+
headers.set(key, fieldName);
|
|
37
|
+
}
|
|
38
|
+
const fact = spec.fact;
|
|
39
|
+
const needed = new Set([
|
|
40
|
+
...(spec.contract?.requiredColumns ?? []).map(snake),
|
|
41
|
+
spec.dateColumn,
|
|
42
|
+
spec.amountColumn,
|
|
43
|
+
...(spec.keyColumns ?? []),
|
|
44
|
+
fact?.reference,
|
|
45
|
+
fact?.description,
|
|
46
|
+
fact?.counterparty,
|
|
47
|
+
fact?.currency,
|
|
48
|
+
].filter((s) => Boolean(s)));
|
|
49
|
+
// Treat unfamiliar SQL names as column requirements: an unrecognized expression must not establish a match.
|
|
50
|
+
for (const [token] of (fact?.amountExpr ?? '').matchAll(/'(?:''|[^'])*'|"(?:""|[^"])*"|[a-z_][a-z0-9_]*/gi)) {
|
|
51
|
+
if (token.startsWith("'") || /^(?:coalesce|try_cast|cast|nullif|trim|as|decimal)$/i.test(token))
|
|
52
|
+
continue;
|
|
53
|
+
needed.add(token.replace(/^"|"$/g, '').replace(/""/g, '"').toLowerCase());
|
|
54
|
+
}
|
|
55
|
+
if ([...needed].some((column) => !headers.has(column)))
|
|
56
|
+
return;
|
|
57
|
+
const matched = new Set([
|
|
58
|
+
...(parser.headerContains ?? []),
|
|
59
|
+
...Array.from(needed, (key) => headers.get(key)),
|
|
60
|
+
]);
|
|
61
|
+
return matched.size ? [...matched] : undefined;
|
|
62
|
+
}
|
|
8
63
|
export async function onboardInput(o) {
|
|
9
64
|
const ref = o.teamId ?? readProfile(process.env.ZL_PROFILE ?? 'default')?.team?.id;
|
|
10
65
|
if (!ref)
|
|
@@ -50,7 +105,45 @@ export async function onboardInput(o) {
|
|
|
50
105
|
if (!sources.includes(source))
|
|
51
106
|
throw new Error('Choose an existing active source');
|
|
52
107
|
const current = registry.datasets.find((d) => d.key === previous?.datasetKey);
|
|
53
|
-
let sample = await profileSample(o.sample, o, ask, current?.spec.parser?.sheet, input.input.maxFileSizeMb);
|
|
108
|
+
let sample = await profileSample(o.sample, o, ask, current?.spec.parser?.sheet, input.input.maxFileSizeMb, current?.spec.parser?.headerContains);
|
|
109
|
+
const mime = sample.format.kind === 'csv'
|
|
110
|
+
? 'text/csv'
|
|
111
|
+
: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
|
112
|
+
if (input.input.acceptedContentTypes?.length &&
|
|
113
|
+
!input.input.acceptedContentTypes.some((type) => type === mime || type === '*/*' || type === mime.split('/')[0] + '/*'))
|
|
114
|
+
throw new Error('Sample content type does not match the deployed input');
|
|
115
|
+
if (previous &&
|
|
116
|
+
current &&
|
|
117
|
+
!current.retired &&
|
|
118
|
+
current.source === source &&
|
|
119
|
+
previous.source === source &&
|
|
120
|
+
current.spec.contract?.sha256 &&
|
|
121
|
+
current.spec.contract.sha256 === previous.contract?.sha256 &&
|
|
122
|
+
registry.latestVersion?.version === input.registryVersion &&
|
|
123
|
+
(!o.datasetKey || o.datasetKey === previous.datasetKey) &&
|
|
124
|
+
(!o.window || o.window === previous.window) &&
|
|
125
|
+
(!o.rules || o.rules === 'inherit')) {
|
|
126
|
+
const matchedHeaders = matchingHeaders(sample, current.spec);
|
|
127
|
+
if (matchedHeaders) {
|
|
128
|
+
printJson({
|
|
129
|
+
action: 'keep',
|
|
130
|
+
message: 'Sample matches the existing dataset. Keeping the current binding.',
|
|
131
|
+
teamId,
|
|
132
|
+
workflowId,
|
|
133
|
+
field,
|
|
134
|
+
registryVersion: input.registryVersion,
|
|
135
|
+
previousBinding: previous,
|
|
136
|
+
binding: previous,
|
|
137
|
+
source,
|
|
138
|
+
format: sample.format,
|
|
139
|
+
headerRow: sample.headerRow,
|
|
140
|
+
matchedHeaders,
|
|
141
|
+
diff: { added: [], changed: [], retired: [] },
|
|
142
|
+
published: false,
|
|
143
|
+
});
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
54
147
|
if (!o.preview) {
|
|
55
148
|
process.stderr.write('Inferred headers (row ' +
|
|
56
149
|
sample.headerRow +
|
|
@@ -140,7 +233,7 @@ export function registerOnboardInput(registry) {
|
|
|
140
233
|
.requiredOption('--field <name>', 'Existing file input')
|
|
141
234
|
.option('--team-id <ref>', 'Team (defaults to selected team)')
|
|
142
235
|
.option('--source <key>', 'Existing registry source')
|
|
143
|
-
.option('--dataset-key <key>', '
|
|
236
|
+
.option('--dataset-key <key>', 'Choose a new dataset key even if the sample matches the current binding')
|
|
144
237
|
.option('--rules <mode>', 'inherit compatible rules from the bound dataset, or table')
|
|
145
238
|
.option('--window <window>', 'period or prior_period')
|
|
146
239
|
.option('--sheet <name>', 'Workbook worksheet')
|
|
@@ -2,19 +2,22 @@ import { readFile, stat } from 'node:fs/promises';
|
|
|
2
2
|
import { extname } from 'node:path';
|
|
3
3
|
import { parse } from 'csv-parse/sync';
|
|
4
4
|
import readWorkbook from 'read-excel-file/node';
|
|
5
|
-
export async function profileSample(path, options, ask, preferredSheet, maxMb) {
|
|
5
|
+
export async function profileSample(path, options, ask, preferredSheet, maxMb, headerContains = []) {
|
|
6
6
|
const sizeBytes = (await stat(path)).size;
|
|
7
7
|
if (sizeBytes > Math.min(maxMb ?? 64, 64) * 1024 * 1024)
|
|
8
8
|
throw new Error('Use a smaller representative sample');
|
|
9
9
|
const data = await readFile(path);
|
|
10
10
|
let format;
|
|
11
11
|
let rows;
|
|
12
|
+
let firstSheet;
|
|
13
|
+
let defaultDelimiter;
|
|
12
14
|
const extension = extname(path).toLowerCase();
|
|
13
15
|
if (extension === '.xlsx') {
|
|
14
16
|
if (data.length < 4 || data.readUInt16LE(0) !== 0x4b50)
|
|
15
17
|
throw new Error('Expected an XLSX workbook');
|
|
16
18
|
const sheets = await readWorkbook(data);
|
|
17
19
|
const names = sheets.map((s) => s.sheet);
|
|
20
|
+
firstSheet = names[0];
|
|
18
21
|
const requested = options.sheet ??
|
|
19
22
|
(preferredSheet && names.includes(preferredSheet) ? preferredSheet : undefined) ??
|
|
20
23
|
(names.length === 1 ? names[0] : await ask('Choose worksheet (' + names.join(', ') + ')'));
|
|
@@ -47,6 +50,8 @@ export async function profileSample(path, options, ask, preferredSheet, maxMb) {
|
|
|
47
50
|
text = new TextDecoder('windows-1252').decode(data);
|
|
48
51
|
}
|
|
49
52
|
}
|
|
53
|
+
const probe = text.split(/\r\n|\r|\n/, 60).join('\n');
|
|
54
|
+
defaultDelimiter = probe.split('\t').length > probe.split(',').length ? '\t' : ',';
|
|
50
55
|
const delimiters = options.delimiter ? [options.delimiter] : [',', ';', '\t', '|'];
|
|
51
56
|
const candidates = delimiters.flatMap((delimiter) => {
|
|
52
57
|
if (![',', ';', '\t', '|'].includes(delimiter))
|
|
@@ -90,7 +95,21 @@ export async function profileSample(path, options, ask, preferredSheet, maxMb) {
|
|
|
90
95
|
width: r.filter((v) => typeof v === 'string' && v.trim()).length,
|
|
91
96
|
}))
|
|
92
97
|
.filter(({ r, width }) => width > 0 && r.filter((v) => v != null && String(v).trim()).length === width);
|
|
93
|
-
|
|
98
|
+
// The runtime locates the first row containing every anchor, or the first widest row.
|
|
99
|
+
const probe = rows.slice(0, 60).map((row) => new Set(row
|
|
100
|
+
.map((cell) => String(cell ?? '')
|
|
101
|
+
.trim()
|
|
102
|
+
.toLowerCase())
|
|
103
|
+
.filter(Boolean)));
|
|
104
|
+
const widths = rows
|
|
105
|
+
.slice(0, 60)
|
|
106
|
+
.map((row) => row.filter((cell) => String(cell ?? '').trim()).length);
|
|
107
|
+
const registryIndex = headerContains.length
|
|
108
|
+
? probe.findIndex((headers) => headerContains.every((anchor) => headers.has(anchor.trim().toLowerCase())))
|
|
109
|
+
: widths.indexOf(Math.max(...widths));
|
|
110
|
+
const inferred = headerContains.length && registryIndex >= 0 && registryIndex < 50
|
|
111
|
+
? registryIndex
|
|
112
|
+
: candidates.sort((a, b) => b.width - a.width)[0]?.index;
|
|
94
113
|
const index = options.headerRow !== undefined ? Number(options.headerRow) - 1 : inferred;
|
|
95
114
|
if (index === undefined ||
|
|
96
115
|
!Number.isInteger(index) ||
|
|
@@ -135,6 +154,15 @@ export async function profileSample(path, options, ask, preferredSheet, maxMb) {
|
|
|
135
154
|
fieldType = values.some((v) => String(v).includes('.')) ? 'decimal' : 'number';
|
|
136
155
|
return { fieldName, fieldType };
|
|
137
156
|
});
|
|
138
|
-
return {
|
|
157
|
+
return {
|
|
158
|
+
format,
|
|
159
|
+
columns,
|
|
160
|
+
ambiguousDates,
|
|
161
|
+
sizeBytes,
|
|
162
|
+
headerRow: index + 1,
|
|
163
|
+
registryHeaderRow: registryIndex + 1,
|
|
164
|
+
firstSheet,
|
|
165
|
+
defaultDelimiter,
|
|
166
|
+
};
|
|
139
167
|
}
|
|
140
168
|
//# sourceMappingURL=registry-sample.js.map
|