priority-axi 0.0.0-stage → 0.2.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.
@@ -0,0 +1,173 @@
1
+ // Shared steps for commands that talk to Priority.
2
+ import { readSettings } from '../config.js';
3
+ import { AxiError, usage } from '../errors.js';
4
+ import { rowsOf, send, stringValue } from '../http.js';
5
+ import { cacheDir, loadIndex, readCompany, readIndex, recordReach, staleReason, writeCompany, } from '../index/cache.js';
6
+ import { screenSegment, utc } from '../odata.js';
7
+ const text = (v) => (typeof v === 'string' ? v : undefined);
8
+ export function open(input) {
9
+ const settings = readSettings(input.io.env, {
10
+ company: text(input.values.company),
11
+ user: text(input.values.user),
12
+ ini: text(input.values.ini),
13
+ });
14
+ return { settings, dir: cacheDir(settings, input.io.env), input };
15
+ }
16
+ export async function priorityVersion(s) {
17
+ const answer = await send(s.settings, { method: 'GET', path: 'GetPriorityVersion()' }, s.input.io.http);
18
+ return stringValue(answer, 'version');
19
+ }
20
+ /**
21
+ * Prove the company exists. Function calls such as GetPriorityVersion()
22
+ * accept any company code, so only GETCOMPANIES can tell. The answer is
23
+ * cached for seven days; `live` always asks Priority.
24
+ */
25
+ export async function checkCompany(s, live) {
26
+ const now = s.input.io.now();
27
+ if (!live) {
28
+ const cached = readCompany(s.dir, s.settings.company, now);
29
+ if (cached)
30
+ return cached;
31
+ }
32
+ const answer = await send(s.settings, { method: 'GET', path: 'GETCOMPANIES' }, s.input.io.http);
33
+ const rows = rowsOf(answer);
34
+ const row = rows.find((r) => r.NAME === s.settings.company);
35
+ if (!row) {
36
+ const known = rows
37
+ .map((r) => r.NAME)
38
+ .filter((n) => typeof n === 'string');
39
+ throw new AxiError('company_not_found', `Priority does not list company ${s.settings.company} for this user.${known.length ? ` Companies: ${known.slice(0, 20).join(', ')}.` : ''} Check the code with the owner.`);
40
+ }
41
+ const check = {
42
+ code: s.settings.company,
43
+ title: typeof row.TITLE === 'string' ? row.TITLE : '',
44
+ checkedAt: now.toISOString(),
45
+ };
46
+ writeCompany(s.dir, check);
47
+ return check;
48
+ }
49
+ export function indexSource(s) {
50
+ return {
51
+ fetchVersion: () => priorityVersion(s),
52
+ fetchMetadata: async () => {
53
+ const answer = await send(s.settings, { method: 'GET', path: '$metadata', query: '?$format=json' }, s.input.io.http);
54
+ if (!answer.json)
55
+ throw new AxiError('priority_error', 'Priority returned metadata that is not JSON.');
56
+ return { csdl: answer.json, bytes: answer.bytes, ms: answer.ms };
57
+ },
58
+ };
59
+ }
60
+ /**
61
+ * The screen index, offline while the cache is fresh. Before downloading the
62
+ * metadata, the company is checked, so a typo never builds a cache.
63
+ */
64
+ export async function screenIndex(s) {
65
+ const now = s.input.io.now();
66
+ const cached = readIndex(s.dir);
67
+ if (cached && !staleReason(cached, { now }))
68
+ return { index: cached };
69
+ await checkCompany(s, false);
70
+ return loadIndex(s.dir, indexSource(s), { now });
71
+ }
72
+ /** A note for output when this command had to build the index first. */
73
+ export function builtNote(loaded) {
74
+ if (!loaded.rebuilt)
75
+ return {};
76
+ const mb = (loaded.rebuilt.bytes / 2 ** 20).toFixed(1);
77
+ return { index: `built now from Priority's metadata (${mb} MB)` };
78
+ }
79
+ /** Send a read for a screen, recording whether Priority allowed API access to it. */
80
+ export async function readScreen(s, screen, query) {
81
+ const now = s.input.io.now();
82
+ try {
83
+ const answer = await send(s.settings, {
84
+ method: 'GET',
85
+ path: screenSegment(screen),
86
+ query,
87
+ context: { screen },
88
+ }, s.input.io.http);
89
+ recordReach(s.dir, screen, 'yes', now);
90
+ return answer;
91
+ }
92
+ catch (error) {
93
+ if (error instanceof AxiError && error.code === 'screen_not_enabled') {
94
+ recordReach(s.dir, screen, 'no', now);
95
+ }
96
+ throw error;
97
+ }
98
+ }
99
+ // ---------- flag helpers ----------
100
+ export const str = (v) => typeof v === 'string' ? v : undefined;
101
+ export const strings = (v) => Array.isArray(v)
102
+ ? v.filter((x) => typeof x === 'string')
103
+ : typeof v === 'string'
104
+ ? [v]
105
+ : [];
106
+ export function intFlag(v, name, fallback, min, max) {
107
+ if (v === undefined)
108
+ return fallback;
109
+ const n = typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : Number.NaN;
110
+ if (!Number.isSafeInteger(n) || n < min || n > max) {
111
+ throw usage(`--${name} takes a whole number from ${min} to ${max}.`);
112
+ }
113
+ return n;
114
+ }
115
+ /** --since as a date, a full time, or a relative 7d or 24h. */
116
+ export function sinceFlag(v, now) {
117
+ if (typeof v !== 'string' || !v) {
118
+ throw usage('changes needs --since <time>, such as --since 7d, --since 24h or --since 2026-11-01.');
119
+ }
120
+ const rel = /^(\d{1,4})([dh])$/.exec(v);
121
+ if (rel) {
122
+ const hours = Number(rel[1]) * (rel[2] === 'd' ? 24 : 1);
123
+ return new Date(now.getTime() - hours * 3600_000)
124
+ .toISOString()
125
+ .replace(/\.\d{3}Z$/, 'Z');
126
+ }
127
+ return utc(v, '--since');
128
+ }
129
+ const SAFE_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
130
+ /** A shell word: bare when safe, otherwise single-quoted. */
131
+ export function shellWord(word) {
132
+ return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
133
+ }
134
+ /** Rebuild a command line for a help hint, with some flags replaced or removed. */
135
+ export function commandLine(name, positionals, values, change = {}) {
136
+ const parts = [`priority-axi ${name}`, ...positionals.map(shellWord)];
137
+ const seen = new Set();
138
+ const emit = (flag, value) => {
139
+ if (value === true)
140
+ parts.push(`--${flag}`);
141
+ else if (typeof value === 'string')
142
+ parts.push(`--${flag}`, shellWord(value));
143
+ };
144
+ for (const [flag, value] of Object.entries(values)) {
145
+ if (value === undefined || flag in change)
146
+ continue;
147
+ seen.add(flag);
148
+ if (Array.isArray(value))
149
+ for (const item of value)
150
+ emit(flag, item);
151
+ else
152
+ emit(flag, value);
153
+ }
154
+ for (const [flag, value] of Object.entries(change)) {
155
+ if (value !== null && !seen.has(flag))
156
+ emit(flag, value === '' ? true : value);
157
+ }
158
+ return parts.join(' ');
159
+ }
160
+ /** Rebuild a command in the order given, for commands where order carries meaning (create). */
161
+ export function tokenLine(name, tokens, drop = []) {
162
+ const parts = [`priority-axi ${name}`];
163
+ for (const token of tokens) {
164
+ if (token.kind === 'positional')
165
+ parts.push(shellWord(token.value));
166
+ else if (!drop.includes(token.name)) {
167
+ parts.push(`--${token.name}`);
168
+ if (token.value !== undefined)
169
+ parts.push(shellWord(token.value));
170
+ }
171
+ }
172
+ return parts.join(' ');
173
+ }
@@ -0,0 +1,207 @@
1
+ // create: check everything against the index, build one deep-insert body,
2
+ // and send it once. Inside Comis the Gate holds it for the owner's approval.
3
+ import { readFileSync } from 'node:fs';
4
+ import { serviceRoot } from '../config.js';
5
+ import { AxiError, usage } from '../errors.js';
6
+ import { send } from '../http.js';
7
+ import { resolveField, resolveScreen, resolveSub, } from '../index/build.js';
8
+ import { recordReach } from '../index/cache.js';
9
+ import { parseWhere, screenSegment, utc } from '../odata.js';
10
+ import { defaultColumns, tableRow } from '../output/shape.js';
11
+ import { render } from '../output/toon.js';
12
+ import { open, screenIndex, shellWord, str, strings, tokenLine, } from './common.js';
13
+ const INTEGER = new Set(['Int16', 'Int32', 'Int64', 'Byte', 'SByte']);
14
+ const DECIMAL = new Set(['Decimal', 'Double', 'Single']);
15
+ function writable(field, where) {
16
+ if (field.readOnly)
17
+ throw usage(`${field.name} is read-only in ${where}; Priority fills it.`);
18
+ if (field.internalId)
19
+ throw usage(`${field.name} is an internal ID in ${where}; Priority assigns it.`);
20
+ }
21
+ /** Convert one value to the JSON type Priority expects for this field. */
22
+ export function typedValue(field, raw, where) {
23
+ writable(field, where);
24
+ if (field.type === 'String') {
25
+ const length = [...raw].length;
26
+ if (field.max !== undefined && length > field.max) {
27
+ throw usage(`${field.name} holds at most ${field.max} characters; the value has ${length}.`);
28
+ }
29
+ return raw;
30
+ }
31
+ if (INTEGER.has(field.type)) {
32
+ const n = /^-?\d+$/.test(raw) ? Number(raw) : Number.NaN;
33
+ if (!Number.isSafeInteger(n))
34
+ throw usage(`${field.name} is a whole number.`);
35
+ return n;
36
+ }
37
+ if (DECIMAL.has(field.type)) {
38
+ if (!/^-?\d+(\.\d+)?$/.test(raw))
39
+ throw usage(`${field.name} is a number; write it with a point, such as 12.50.`);
40
+ return Number(raw);
41
+ }
42
+ if (field.type === 'Boolean') {
43
+ if (raw !== 'true' && raw !== 'false')
44
+ throw usage(`${field.name} is true or false.`);
45
+ return raw === 'true';
46
+ }
47
+ if (field.type === 'DateTimeOffset')
48
+ return utc(raw, field.name);
49
+ throw usage(`${field.name} has type ${field.type}, which create cannot set.`);
50
+ }
51
+ export function assign(type, where, target, term) {
52
+ const t = parseWhere(term);
53
+ if (t.op !== '=')
54
+ throw usage(`Set fields with FIELD=VALUE; ${t.field} uses ${t.op}.`);
55
+ const field = resolveField(type, where, t.field);
56
+ if (field.name in target)
57
+ throw usage(`${field.name} is set more than once in ${where}.`);
58
+ target[field.name] = typedValue(field, t.value, where);
59
+ }
60
+ /** Build the body from --set and --line flags, in the order given. */
61
+ function fromFlags(index, screen, input) {
62
+ const body = {};
63
+ const lines = [];
64
+ let current;
65
+ let screenSeen = false;
66
+ for (const token of input.tokens) {
67
+ if (token.kind === 'positional') {
68
+ if (!screenSeen) {
69
+ screenSeen = true;
70
+ continue;
71
+ }
72
+ if (!current) {
73
+ throw usage('A FIELD=VALUE after the screen belongs to a --line <SUB>. Use --set FIELD=VALUE for the record itself.');
74
+ }
75
+ assign(current.sub.def, `${screen.name} > ${current.sub.name}`, current.body, token.value);
76
+ continue;
77
+ }
78
+ if (token.name === 'set') {
79
+ current = undefined;
80
+ assign(screen.type, screen.name, body, token.value ?? '');
81
+ }
82
+ else if (token.name === 'line') {
83
+ current = { sub: resolveSub(index, screen, token.value ?? ''), body: {} };
84
+ lines.push(current);
85
+ }
86
+ else {
87
+ current = undefined;
88
+ }
89
+ }
90
+ return { body, lines };
91
+ }
92
+ const scalar = (value, where) => {
93
+ if (typeof value === 'string')
94
+ return value;
95
+ if (typeof value === 'number' || typeof value === 'boolean')
96
+ return String(value);
97
+ throw usage(`${where}: each value must be text, a number or true/false. Leave out fields with no value.`);
98
+ };
99
+ /** Build the body from a JSON file of the same shape, through the same checks. */
100
+ function fromFile(index, screen, path) {
101
+ let raw;
102
+ try {
103
+ raw = JSON.parse(readFileSync(path, 'utf8'));
104
+ }
105
+ catch {
106
+ throw usage('--json-file must name a readable JSON file.');
107
+ }
108
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
109
+ throw usage('--json-file must hold one JSON object.');
110
+ const body = {};
111
+ const lines = [];
112
+ for (const [name, value] of Object.entries(raw)) {
113
+ const isSub = screen.type.subs.some((s) => s.nav === name || s.name === name);
114
+ if (!isSub) {
115
+ const field = resolveField(screen.type, screen.name, name);
116
+ body[field.name] = typedValue(field, scalar(value, field.name), screen.name);
117
+ continue;
118
+ }
119
+ const sub = resolveSub(index, screen, name);
120
+ const items = Array.isArray(value) ? value : [value];
121
+ for (const item of items) {
122
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
123
+ throw usage(`${sub.nav} must hold objects of FIELD: value.`);
124
+ }
125
+ const line = {};
126
+ for (const [f, v] of Object.entries(item)) {
127
+ const field = resolveField(sub.def, `${screen.name} > ${sub.name}`, f);
128
+ line[field.name] = typedValue(field, scalar(v, field.name), `${screen.name} > ${sub.name}`);
129
+ }
130
+ lines.push({ sub, body: line });
131
+ }
132
+ }
133
+ return { body, lines };
134
+ }
135
+ function assemble(body, lines) {
136
+ const out = { ...body };
137
+ for (const { sub, body: line } of lines) {
138
+ if (!Object.keys(line).length)
139
+ throw usage(`--line ${sub.name} needs at least one FIELD=VALUE.`);
140
+ if (sub.many) {
141
+ const list = out[sub.nav] ?? [];
142
+ list.push(line);
143
+ out[sub.nav] = list;
144
+ }
145
+ else {
146
+ if (out[sub.nav])
147
+ throw usage(`${sub.name} holds one record; give it one --line.`);
148
+ out[sub.nav] = line;
149
+ }
150
+ }
151
+ return out;
152
+ }
153
+ export async function create(input) {
154
+ const s = open(input);
155
+ const { index } = await screenIndex(s);
156
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
157
+ const file = str(input.values['json-file']);
158
+ const flagged = strings(input.values.set).length > 0 ||
159
+ strings(input.values.line).length > 0 ||
160
+ input.positionals.length > 1;
161
+ if (file && flagged)
162
+ throw usage('Use --json-file or --set/--line, not both.');
163
+ const { body, lines } = file
164
+ ? fromFile(index, screen, file)
165
+ : fromFlags(index, screen, input);
166
+ const payload = assemble(body, lines);
167
+ if (!Object.keys(payload).length)
168
+ throw usage('Nothing to create: give --set FIELD=VALUE or --json-file <path>.');
169
+ const transactions = 1 + lines.length;
170
+ const path = `${new URL(serviceRoot(s.settings)).pathname}/${screenSegment(screen.name)}`;
171
+ if (input.values['dry-run'] === true) {
172
+ return render({ dry_run: true, request: `POST ${path}`, body: payload, transactions }, [
173
+ `Run \`${tokenLine('create', input.tokens, ['dry-run'])}\` to send it; inside Comis the owner approves it first`,
174
+ ]);
175
+ }
176
+ const now = input.io.now();
177
+ let answer;
178
+ try {
179
+ // Sent once. A write is never retried; a held write is waited on with comis action wait.
180
+ answer = await send(s.settings, {
181
+ method: 'POST',
182
+ path: screenSegment(screen.name),
183
+ body: payload,
184
+ context: { screen: screen.name },
185
+ }, input.io.http);
186
+ }
187
+ catch (error) {
188
+ if (error instanceof AxiError && error.code === 'screen_not_enabled')
189
+ recordReach(s.dir, screen.name, 'no', now);
190
+ throw error;
191
+ }
192
+ recordReach(s.dir, screen.name, 'yes', now);
193
+ const record = answer.json && typeof answer.json === 'object' ? answer.json : {};
194
+ const keys = screen.type.key.filter((k) => record[k] !== undefined && record[k] !== null && record[k] !== '');
195
+ const keyText = keys.map((k) => String(record[k])).join(', ');
196
+ const columns = defaultColumns(screen.type, [record]);
197
+ return render({
198
+ created: screen.name,
199
+ key: keyText || null,
200
+ transactions,
201
+ record: tableRow(screen.type, record, columns, 500),
202
+ }, keys.length === 1 && screen.type.key.length === 1
203
+ ? [
204
+ `Run \`priority-axi show ${screen.name} ${shellWord(keyText)}\` to read it`,
205
+ ]
206
+ : []);
207
+ }
@@ -0,0 +1,153 @@
1
+ // find: text search over a screen's catalog (key, description, unit, family,
2
+ // status), kept locally because Priority cannot search text. Records that are
3
+ // not in use (not active, cancelled, finished, closed) are left out unless
4
+ // --all. With --sub, the lines of a sub-screen are searched together with
5
+ // their parent, such as the projects of every customer; a project screen's
6
+ // customer name is searched too. The `matched` column says `own` when every
7
+ // word was in the record itself, or `parent` / `customer` when some were only
8
+ // there.
9
+ import { usage } from '../errors.js';
10
+ import { rowsOf } from '../http.js';
11
+ import { resolveScreen, resolveSub } from '../index/build.js';
12
+ import { layout, pullCatalog, readCatalog, writeCatalog, } from '../index/catalog.js';
13
+ import { bounded, cut, render } from '../output/toon.js';
14
+ import { haystack, missing, queryTerms, rank } from '../search.js';
15
+ import { builtNote, commandLine, intFlag, open, readScreen, screenIndex, str, } from './common.js';
16
+ /**
17
+ * A status that means the record is not in use, in Priority's Hebrew and
18
+ * English words: not active, cancelled, finished, closed.
19
+ */
20
+ const INACTIVE = /לא\s*פעיל|מבוטל|הסתיים|סגור|\b(inactive|not active|cancel+ed|finished|closed)\b/i;
21
+ const when = (iso) => iso.slice(0, 16).replace('T', ' ');
22
+ export async function find(input) {
23
+ const s = open(input);
24
+ const v = input.values;
25
+ const words = input.positionals.slice(1);
26
+ const terms = queryTerms(words);
27
+ if (!terms.length) {
28
+ throw usage('find needs words to look for, such as `priority-axi find LOGPART צינור 110`. One-letter words are ignored.');
29
+ }
30
+ const limit = intFlag(v.limit, 'limit', 20, 1, 200);
31
+ const page = intFlag(v.page, 'page', 1, 1, 100_000);
32
+ const all = v.all === true;
33
+ const loaded = await screenIndex(s);
34
+ const { index } = loaded;
35
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
36
+ const subName = str(v.sub);
37
+ const sub = subName ? resolveSub(index, screen, subName) : undefined;
38
+ const lay = layout(screen, sub);
39
+ const label = sub ? `${screen.name} > ${sub.name}` : screen.name;
40
+ const now = input.io.now();
41
+ let catalog = v.refresh === true
42
+ ? undefined
43
+ : readCatalog(s.dir, screen.name, sub?.name, lay.columns, now);
44
+ let pulled;
45
+ if (!catalog) {
46
+ const started = performance.now();
47
+ catalog = await pullCatalog(screen, sub, lay, async (query) => rowsOf(await readScreen(s, screen.name, query)), now);
48
+ writeCatalog(s.dir, catalog);
49
+ const seconds = Math.max(1, Math.round((performance.now() - started) / 1000));
50
+ pulled = `built now: ${catalog.rows.length} ${sub ? 'lines' : 'records'} from Priority in ${seconds} s`;
51
+ }
52
+ const at = (name) => catalog.columns.indexOf(name);
53
+ const statusAt = lay.status.map(at).filter((i) => i >= 0);
54
+ const searchAt = lay.search.map(at).filter((i) => i >= 0);
55
+ // The searched columns of the record itself, without its parent's or customer's.
56
+ const ownAt = lay.own.map(at).filter((i) => i >= 0);
57
+ const active = (row) => statusAt.every((i) => !INACTIVE.test(String(row[i] ?? '')));
58
+ const pool = all ? catalog.rows : catalog.rows.filter(active);
59
+ const text = (row) => haystack(searchAt.map((i) => row[i]));
60
+ const ranked = rank(pool, text, terms);
61
+ // Nothing in use has every word: say so when records not in use do, such as
62
+ // a cancelled project, rather than offering unrelated close matches.
63
+ const retired = !all && !ranked.all.length
64
+ ? rank(catalog.rows.filter((r) => !active(r)), text, terms).all.length
65
+ : 0;
66
+ // Show the status when the records searched do not all share one.
67
+ const statusVaries = new Set(pool.map((r) => statusAt.map((i) => r[i]).join('|'))).size > 1;
68
+ const unit = sub ? 'lines' : 'records';
69
+ const kept = all ? catalog.rows.length : pool.length;
70
+ const catalogNote = `${pulled ? `${pulled}; ` : ''}${kept}${all ? '' : ' active'} of ${catalog.rows.length} ${unit}${catalog.partial ? ' (partial: the first 200,000 records)' : ''}, built ${when(catalog.builtAt)} UTC; rebuilt after a day, or with --refresh`;
71
+ const query = words.join(' ');
72
+ const noun = (n) => (n === 1 ? (sub ? 'line' : 'record') : unit);
73
+ const columns = [...lay.show, ...(all || statusVaries ? lay.status : [])];
74
+ const closest = !retired && !ranked.all.length && ranked.closest.length;
75
+ const matches = closest
76
+ ? ranked.closest.map((c) => ({ row: c.row, lacking: c.lacking }))
77
+ : ranked.all.map((row) => ({ row, lacking: [] }));
78
+ const notInUse = (n) => `${n} ${noun(n)} not in use (inactive, cancelled, finished or closed) match every word; --all shows them with their status`;
79
+ const from = (page - 1) * limit;
80
+ const slice = matches.slice(from, from + limit);
81
+ const more = matches.length > from + limit;
82
+ const summary = closest
83
+ ? `0 ${unit} from ${label} match all of: ${query}`
84
+ : `${matches.length} ${noun(matches.length)} from ${label} match ${query}${matches.length > limit || page > 1 ? ` (showing ${slice.length ? `${from + 1}-${from + slice.length}` : 'none'})` : ''}`;
85
+ const head = {
86
+ summary,
87
+ ...builtNote(loaded),
88
+ catalog: catalogNote,
89
+ ...(retired ? { not_in_use: notInUse(retired) } : {}),
90
+ ...(closest
91
+ ? {
92
+ closest: `${matches.length} ${noun(matches.length)} match ${terms.length - (matches[0]?.lacking.length ?? 0)} of ${terms.length} words`,
93
+ }
94
+ : {}),
95
+ };
96
+ const help = [];
97
+ if (more) {
98
+ help.push(`Run \`${commandLine('find', input.positionals, v, { page: String(page + 1) })}\` for the next ${limit}`);
99
+ }
100
+ if (retired) {
101
+ help.push(`Run \`${commandLine('find', input.positionals, v, { all: '' })}\` to see the ${retired} not in use, then ask before using one`);
102
+ }
103
+ else if (!matches.length || closest) {
104
+ help.push(`Run \`priority-axi find ${screen.name}${sub ? ` --sub ${sub.name}` : ''} <other words>\` with fewer or different words: a number, a size or one distinctive word`);
105
+ }
106
+ if (!retired && !all && kept < catalog.rows.length && !matches.length) {
107
+ help.push(`Run \`${commandLine('find', input.positionals, v, { all: '' })}\` to include ${unit} not in use`);
108
+ }
109
+ if (matches.length) {
110
+ help.push(sub
111
+ ? `Run \`priority-axi show ${screen.name} <${lay.parentKey.join(', ')}> --with ${sub.name}\` for the record`
112
+ : lay.key.length === 1
113
+ ? `Run \`priority-axi show ${screen.name} <${lay.key[0]}>\` for one record`
114
+ : `Run \`priority-axi show ${screen.name} ${lay.key.map((k) => `--key ${k}=<value>`).join(' ')}\` for one record`);
115
+ }
116
+ if (!slice.length)
117
+ return render(head, help);
118
+ return bounded({
119
+ total: slice.length,
120
+ narrower: commandLine('find', input.positionals, v, { limit: '5' }),
121
+ build: (shown, fieldLimit) => {
122
+ const records = slice.slice(0, shown).map(({ row, lacking }) => {
123
+ const out = {};
124
+ for (const name of columns) {
125
+ const value = row[at(name)];
126
+ out[name] =
127
+ value === '' || value === undefined
128
+ ? null
129
+ : typeof value === 'string' && Number.isFinite(fieldLimit)
130
+ ? cut(value, fieldLimit)
131
+ : value;
132
+ }
133
+ if (lay.context && !closest)
134
+ out.matched = missing(terms, haystack(ownAt.map((i) => row[i])))
135
+ .length
136
+ ? lay.context
137
+ : 'own';
138
+ if (closest)
139
+ out.lacking = lacking.join(' ');
140
+ return out;
141
+ });
142
+ return render({
143
+ ...head,
144
+ [sub ? 'lines' : 'records']: records,
145
+ ...(shown < slice.length
146
+ ? {
147
+ omitted: `${slice.length - shown} not shown; use --limit ${Math.max(1, shown)}`,
148
+ }
149
+ : {}),
150
+ }, help);
151
+ },
152
+ }, false);
153
+ }
@@ -0,0 +1,56 @@
1
+ // The home view: connection, live Priority version, company, index state and
2
+ // next steps. Two small GETs; it never downloads the metadata.
3
+ import { readIndex, readReach, staleReason } from '../index/cache.js';
4
+ import { render } from '../output/toon.js';
5
+ import { checkCompany, open, priorityVersion } from './common.js';
6
+ const SHOWN = 20;
7
+ function names(list) {
8
+ return list.length > SHOWN
9
+ ? [...list.slice(0, SHOWN), `${list.length - SHOWN} more`]
10
+ : list;
11
+ }
12
+ export async function home(input) {
13
+ const s = open(input);
14
+ const now = input.io.now();
15
+ const version = await priorityVersion(s);
16
+ const company = await checkCompany(s, true);
17
+ const index = readIndex(s.dir);
18
+ const reason = staleReason(index, { now, liveVersion: version });
19
+ let indexLine;
20
+ if (!index) {
21
+ indexLine =
22
+ 'not built yet; it is built on first use (about 8 MB from Priority)';
23
+ }
24
+ else {
25
+ const screens = Object.keys(index.sets).length;
26
+ const built = index.builtAt.slice(0, 10);
27
+ indexLine = reason
28
+ ? `${screens} screens, built ${built} for Priority ${index.version}; rebuilt on next use (${reason === 'age' ? 'older than 7 days' : 'new Priority version'})`
29
+ : `${screens} screens, built ${built}`;
30
+ }
31
+ const reach = readReach(s.dir);
32
+ const enabled = Object.keys(reach)
33
+ .filter((k) => reach[k]?.api === 'yes')
34
+ .sort();
35
+ const refused = Object.keys(reach)
36
+ .filter((k) => reach[k]?.api === 'no')
37
+ .sort();
38
+ const doc = {
39
+ priority: `${s.settings.origin} · ${s.settings.ini} · company ${s.settings.company}`,
40
+ company: company.title || company.code,
41
+ version,
42
+ login: s.settings.user,
43
+ index: indexLine,
44
+ screens_read: enabled.length ? names(enabled) : 'none yet',
45
+ };
46
+ if (refused.length)
47
+ doc.not_enabled = names(refused);
48
+ doc.note = `screens_read lists the screens read so far, not every screen open to the API; try any other.${refused.length ? ' Screens under not_enabled refused API access; the Priority administrator adds them in Limited Access/API Forms.' : ''}`;
49
+ const help = [
50
+ 'Run `priority-axi screens <text>` to find a screen',
51
+ 'Run `priority-axi get <SCREEN> --limit 5` to read records',
52
+ ];
53
+ if (index && reason)
54
+ help.push('Run `priority-axi refresh` to rebuild the screen index now');
55
+ return render(doc, help);
56
+ }