@zalosai/zalos-cli 0.2.27 → 0.2.28

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.
@@ -1,3 +1,4 @@
1
+ import { registerOnboardInput } from './onboard-input.js';
1
2
  import { readFile } from 'node:fs/promises';
2
3
  import { parse as parseYaml } from 'yaml';
3
4
  import { client } from '../client.js';
@@ -134,5 +135,6 @@ export function registerCloseCommand(program) {
134
135
  digest: o.digest,
135
136
  }, { timeoutMs: APPLY_TIMEOUT_MS })));
136
137
  }));
138
+ registerOnboardInput(registry);
137
139
  }
138
140
  //# sourceMappingURL=close.js.map
@@ -0,0 +1,152 @@
1
+ import { basename, extname } from 'node:path';
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { client } from '../client.js';
4
+ import { readProfile } from '../credentials.js';
5
+ import { printJson } from '../utils/output.js';
6
+ import { action, dataRow, resourceId } from '../utils/product-api.js';
7
+ import { profileSample } from './registry-sample.js';
8
+ export async function onboardInput(o) {
9
+ const ref = o.teamId ?? readProfile(process.env.ZL_PROFILE ?? 'default')?.team?.id;
10
+ if (!ref)
11
+ throw new Error('Select a team or specify --team-id');
12
+ const teamId = resourceId(ref), workflowId = resourceId(o.workflowId), field = o.field;
13
+ const [inputResponse, registryResponse] = await Promise.all([
14
+ client.get('/developer/finance/registry/inspect-input', { teamId, workflowId, field }),
15
+ client.get('/developer/finance/registry', { teamId }),
16
+ ]);
17
+ const input = dataRow(inputResponse);
18
+ if (input.registeredAgent === false)
19
+ throw new Error('Register this workflow as a finance registry agent before onboarding its inputs');
20
+ const registry = dataRow(registryResponse);
21
+ if (registry.sourceOfTruth !== 'mesh')
22
+ throw new Error('Dataset onboarding requires a Mesh-owned registry');
23
+ const extension = extname(o.sample).toLowerCase();
24
+ if (input.input.acceptedFileTypes?.length &&
25
+ !input.input.acceptedFileTypes.map((t) => t.toLowerCase()).includes(extension))
26
+ throw new Error('Sample extension does not match the deployed input');
27
+ const terminal = process.stdin.isTTY && process.stderr.isTTY
28
+ ? createInterface({ input: process.stdin, output: process.stderr })
29
+ : null;
30
+ const ask = async (label, fallback) => {
31
+ if (!terminal) {
32
+ if (o.preview && fallback !== undefined)
33
+ return fallback;
34
+ throw new Error('Operator input required: ' +
35
+ label +
36
+ '. Run interactively or supply the corresponding preview option.');
37
+ }
38
+ return ((await terminal.question(label + (fallback ? ' [' + fallback + ']' : '') + ' ')).trim() ||
39
+ fallback ||
40
+ '');
41
+ };
42
+ try {
43
+ const previous = input.binding;
44
+ const sources = registry.sources.filter((s) => !s.retired).map((s) => s.key);
45
+ const source = o.source ??
46
+ previous?.source ??
47
+ (sources.length === 1
48
+ ? sources[0]
49
+ : await ask('Choose the source (' + sources.join(', ') + ')'));
50
+ if (!sources.includes(source))
51
+ throw new Error('Choose an existing active source');
52
+ 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);
54
+ if (!o.preview) {
55
+ process.stderr.write('Inferred headers (row ' +
56
+ sample.headerRow +
57
+ '): ' +
58
+ JSON.stringify(sample.columns.map((c) => c.fieldName)) +
59
+ '\n');
60
+ const headerRow = await ask('Confirm header row or enter another row number', String(sample.headerRow));
61
+ if (headerRow !== String(sample.headerRow))
62
+ sample = await profileSample(o.sample, { ...o, ...sample.format, headerRow }, ask, current?.spec.parser?.sheet, input.input.maxFileSizeMb);
63
+ }
64
+ if (!o.preview) {
65
+ for (const header of sample.ambiguousDates) {
66
+ const type = await ask(JSON.stringify(header) +
67
+ ' contains numbers consistent with Excel dates. Interpret as date, number or text?', 'date');
68
+ if (!['date', 'number', 'text'].includes(type))
69
+ throw new Error('Choose date, number or text');
70
+ const column = sample.columns.find((c) => c.fieldName === header);
71
+ if (column)
72
+ column.fieldType = type;
73
+ }
74
+ }
75
+ const name = basename(o.sample, extname(o.sample))
76
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
77
+ .trim() || field;
78
+ const prefix = previous?.source === source ? previous.datasetKey.split('.')[0] : source;
79
+ const suggested = prefix + '.' + name.toLowerCase().replace(/ +/g, '_');
80
+ const occupied = new Set(registry.datasets.map((dataset) => dataset.key));
81
+ let datasetKey = o.datasetKey ?? (await ask('New dataset key', suggested));
82
+ while (occupied.has(datasetKey) || !/^[a-z0-9_]+\.[a-z0-9_]+$/.test(datasetKey)) {
83
+ if (o.datasetKey || !terminal)
84
+ throw new Error('Choose a new key in source.dataset format with --dataset-key');
85
+ datasetKey = await ask('Choose an unused key in source.dataset format');
86
+ }
87
+ const window = o.window ??
88
+ previous?.window ??
89
+ (await ask('Input window (period or prior_period)', 'period'));
90
+ const compatible = current?.spec.parser?.kind === sample.format.kind;
91
+ const rules = o.rules ??
92
+ (compatible
93
+ ? await ask('Use the bound dataset’s existing date, key, coverage and fact rules (inherit), or create a plain table (table)?', 'inherit')
94
+ : 'table');
95
+ const request = {
96
+ teamId,
97
+ workflowId,
98
+ field,
99
+ authoredDate: new Date().toISOString().slice(0, 10),
100
+ expectedVersion: input.registryVersion,
101
+ workflowVersionId: input.workflowVersionId,
102
+ archiveSha256: input.package.archiveSha256,
103
+ format: sample.format,
104
+ columns: sample.columns,
105
+ sizeBytes: sample.sizeBytes,
106
+ source,
107
+ datasetKey,
108
+ name,
109
+ window,
110
+ rules,
111
+ };
112
+ const path = '/developer/finance/registry/onboard-input';
113
+ const preview = dataRow(await client.post(path, request));
114
+ printJson({
115
+ ...preview,
116
+ headerRow: sample.headerRow,
117
+ possibleExcelDates: sample.ambiguousDates,
118
+ });
119
+ if (o.preview)
120
+ return;
121
+ const message = previous
122
+ ? 'Replace ' + previous.datasetKey + ' with ' + datasetKey + ' for ' + field + ' and publish?'
123
+ : 'Bind ' + datasetKey + ' to ' + field + ' and publish?';
124
+ if ((await ask(message + ' Type publish to confirm', 'cancel')) !== 'publish')
125
+ return;
126
+ if (typeof preview.confirmation !== 'string')
127
+ throw new Error('Mesh did not return a confirmed proposal digest');
128
+ printJson(dataRow(await client.post(path, { ...request, confirm: preview.confirmation })));
129
+ }
130
+ finally {
131
+ terminal?.close();
132
+ }
133
+ }
134
+ export function registerOnboardInput(registry) {
135
+ registry
136
+ .command('onboard-input')
137
+ .description('Infer a new dataset from a local sample, review the binding and publish to Mesh')
138
+ .requiredOption('--sample <file>', 'Local CSV or XLSX sample')
139
+ .requiredOption('--workflow-id <id>', 'Existing deployed workflow')
140
+ .requiredOption('--field <name>', 'Existing file input')
141
+ .option('--team-id <ref>', 'Team (defaults to selected team)')
142
+ .option('--source <key>', 'Existing registry source')
143
+ .option('--dataset-key <key>', 'New dataset key')
144
+ .option('--rules <mode>', 'inherit compatible rules from the bound dataset, or table')
145
+ .option('--window <window>', 'period or prior_period')
146
+ .option('--sheet <name>', 'Workbook worksheet')
147
+ .option('--header-row <number>', 'One-based sample header row')
148
+ .option('--delimiter <character>', 'CSV delimiter')
149
+ .option('--preview', 'Print the proposed changes without publishing')
150
+ .action(async (o) => action(() => onboardInput(o)));
151
+ }
152
+ //# sourceMappingURL=onboard-input.js.map
@@ -0,0 +1,140 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
3
+ import { parse } from 'csv-parse/sync';
4
+ import readWorkbook from 'read-excel-file/node';
5
+ export async function profileSample(path, options, ask, preferredSheet, maxMb) {
6
+ const sizeBytes = (await stat(path)).size;
7
+ if (sizeBytes > Math.min(maxMb ?? 64, 64) * 1024 * 1024)
8
+ throw new Error('Use a smaller representative sample');
9
+ const data = await readFile(path);
10
+ let format;
11
+ let rows;
12
+ const extension = extname(path).toLowerCase();
13
+ if (extension === '.xlsx') {
14
+ if (data.length < 4 || data.readUInt16LE(0) !== 0x4b50)
15
+ throw new Error('Expected an XLSX workbook');
16
+ const sheets = await readWorkbook(data);
17
+ const names = sheets.map((s) => s.sheet);
18
+ const requested = options.sheet ??
19
+ (preferredSheet && names.includes(preferredSheet) ? preferredSheet : undefined) ??
20
+ (names.length === 1 ? names[0] : await ask('Choose worksheet (' + names.join(', ') + ')'));
21
+ const selected = sheets.find((s) => s.sheet === requested);
22
+ if (!selected)
23
+ throw new Error('Unknown worksheet');
24
+ if (!selected.data.length || selected.data.slice(0, 100).some((row) => row.length > 512))
25
+ throw new Error('Choose a populated worksheet with at most 512 columns');
26
+ // The reader returns JS Date instances for date-formatted cells.
27
+ rows = selected.data
28
+ .slice(0, 100)
29
+ .map((row) => row.map((cell) => (typeof cell === 'function' ? String(cell) : cell)));
30
+ const sheet = selected.sheet;
31
+ format = { kind: 'xlsx', sheet };
32
+ }
33
+ else if (extension === '.csv') {
34
+ let encoding = 'utf-8';
35
+ let text;
36
+ const bom = data.length >= 2 ? data.readUInt16BE(0) : 0;
37
+ if (bom === 0xfffe || bom === 0xfeff) {
38
+ text = new TextDecoder(bom === 0xfffe ? 'utf-16le' : 'utf-16be', { fatal: true }).decode(data);
39
+ encoding = 'utf-16';
40
+ }
41
+ else {
42
+ try {
43
+ text = new TextDecoder('utf-8', { fatal: true }).decode(data);
44
+ }
45
+ catch {
46
+ encoding = 'cp1252';
47
+ text = new TextDecoder('windows-1252').decode(data);
48
+ }
49
+ }
50
+ const delimiters = options.delimiter ? [options.delimiter] : [',', ';', '\t', '|'];
51
+ const candidates = delimiters.flatMap((delimiter) => {
52
+ if (![',', ';', '\t', '|'].includes(delimiter))
53
+ throw new Error('Unsupported CSV delimiter');
54
+ try {
55
+ const records = parse(text, {
56
+ delimiter,
57
+ bom: true,
58
+ to: 100,
59
+ relax_column_count: true,
60
+ });
61
+ return records.some((r) => r.length > 1) || options.delimiter
62
+ ? [{ delimiter, records }]
63
+ : [];
64
+ }
65
+ catch {
66
+ return [];
67
+ }
68
+ });
69
+ if (!candidates.length)
70
+ throw new Error('Cannot infer CSV delimiter. Specify --delimiter for a single-column file.');
71
+ const delimiter = candidates.length === 1
72
+ ? candidates[0].delimiter
73
+ : await ask('Choose CSV delimiter (' +
74
+ candidates.map((c) => JSON.stringify(c.delimiter)).join(', ') +
75
+ ')');
76
+ const match = candidates.find((c) => c.delimiter === delimiter);
77
+ if (!match)
78
+ throw new Error('Invalid delimiter');
79
+ rows = match.records;
80
+ format = { kind: 'csv', delimiter, encoding };
81
+ }
82
+ else
83
+ throw new Error('Use a CSV or XLSX sample');
84
+ // Match the loader's first widest row heuristic, considering only plausible text headers.
85
+ const candidates = rows
86
+ .slice(0, 50)
87
+ .map((r, index) => ({
88
+ r,
89
+ index,
90
+ width: r.filter((v) => typeof v === 'string' && v.trim()).length,
91
+ }))
92
+ .filter(({ r, width }) => width > 0 && r.filter((v) => v != null && String(v).trim()).length === width);
93
+ const inferred = candidates.sort((a, b) => b.width - a.width)[0]?.index;
94
+ const index = options.headerRow !== undefined ? Number(options.headerRow) - 1 : inferred;
95
+ if (index === undefined ||
96
+ !Number.isInteger(index) ||
97
+ index < 0 ||
98
+ index >= Math.min(rows.length, 50))
99
+ throw new Error('Choose a header row between 1 and 50');
100
+ const header = rows[index].map((v) => String(v ?? '').trim());
101
+ while (header.length && !header[header.length - 1])
102
+ header.pop();
103
+ if (!header.length ||
104
+ header.some((h) => !h || h.length > 256 || /\p{Cc}/u.test(h)) ||
105
+ new Set(header.map((h) => h.toLowerCase())).size !== header.length)
106
+ throw new Error('Choose a header row with distinct, nonempty column names');
107
+ const ambiguousDates = [];
108
+ const columns = header.map((fieldName, i) => {
109
+ const values = rows
110
+ .slice(index + 1)
111
+ .map((r) => r[i])
112
+ .filter((v) => v != null && v !== '');
113
+ let fieldType = 'text';
114
+ if (/(?:^|[ _])(id|account|reference|zip|postal)(?:$|[ _])/i.test(fieldName))
115
+ fieldType = 'text';
116
+ else if (extension === '.xlsx' &&
117
+ /(?:^|[ _])date(?:$|[ _])/i.test(fieldName) &&
118
+ values.length &&
119
+ values.every((v) => typeof v === 'number' && v >= 20000 && v <= 90000)) {
120
+ fieldType = 'date';
121
+ ambiguousDates.push(fieldName);
122
+ }
123
+ else if (/(?:^|[ _])date(?:$|[ _])/i.test(fieldName) &&
124
+ values.length &&
125
+ values.every((v) => v instanceof Date ||
126
+ /^(?:19|20)\d{6}$/.test(String(v)) ||
127
+ /^\d{4}-\d{2}-\d{2}$/.test(String(v))))
128
+ fieldType = 'date';
129
+ else if (values.length &&
130
+ values.every((v) => v instanceof Date || /^\d{4}-\d{2}-\d{2}$/.test(String(v))))
131
+ fieldType = 'date';
132
+ else if (values.length && values.every((v) => /^(true|false)$/i.test(String(v))))
133
+ fieldType = 'boolean';
134
+ else if (values.length && values.every((v) => /^-?(0|[1-9]\d*)(\.\d+)?$/.test(String(v))))
135
+ fieldType = values.some((v) => String(v).includes('.')) ? 'decimal' : 'number';
136
+ return { fieldName, fieldType };
137
+ });
138
+ return { format, columns, ambiguousDates, sizeBytes, headerRow: index + 1 };
139
+ }
140
+ //# sourceMappingURL=registry-sample.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalosai/zalos-cli",
3
- "version": "0.2.27",
3
+ "version": "0.2.28",
4
4
  "description": "API-only product command-line interface for Zalos",
5
5
  "repository": {
6
6
  "type": "git",
@@ -43,6 +43,8 @@
43
43
  "@tiptap/static-renderer": "3.33.1",
44
44
  "@tiptap/starter-kit": "3.33.1",
45
45
  "commander": "^13.1.0",
46
+ "csv-parse": "7.0.3",
47
+ "read-excel-file": "9.3.15",
46
48
  "yaml": "2.9.0"
47
49
  },
48
50
  "devDependencies": {