priority-axi 0.0.0-stage → 0.1.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,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
+ }
@@ -0,0 +1,264 @@
1
+ // get, changes and show: reads through $filter, never with a key in the path.
2
+ import { AxiError, usage } from '../errors.js';
3
+ import { rowsOf } from '../http.js';
4
+ import { resolveField, resolveScreen, resolveSub, } from '../index/build.js';
5
+ import { combineFilters, literal, orderBy, parseWhere, queryString, whereToFilter, } from '../odata.js';
6
+ import { defaultColumns, recordView, tableRow } from '../output/shape.js';
7
+ import { bounded, render } from '../output/toon.js';
8
+ import { builtNote, commandLine, intFlag, open, readScreen, screenIndex, shellWord, sinceFlag, str, strings, } from './common.js';
9
+ /** Fields asked for when no --fields is given: the key and the first candidates in form order. */
10
+ const CANDIDATES = 12;
11
+ /** Sub-screen lines shown per record without --full. */
12
+ const LINES = 5;
13
+ function candidateSelect(type) {
14
+ const keys = type.key.filter((k) => type.fields.some((f) => f.name === k));
15
+ const rest = type.fields
16
+ .filter((f) => !f.internalId && !keys.includes(f.name))
17
+ .slice(0, CANDIDATES)
18
+ .map((f) => f.name);
19
+ return [...keys, ...rest];
20
+ }
21
+ /**
22
+ * $expand for --with. Without --full, each line list is narrowed and capped on
23
+ * the server: Priority 23.1 honours $select and $top inside $expand (live S9),
24
+ * so a large order does not send every line. One extra line shows that more exist.
25
+ */
26
+ function expandOf(subs, full) {
27
+ if (!subs.length)
28
+ return undefined;
29
+ return subs
30
+ .map((x) => !x.many || full
31
+ ? x.nav
32
+ : `${x.nav}($select=${candidateSelect(x.def).join(',')};$top=${LINES + 1})`)
33
+ .join(',');
34
+ }
35
+ function explicitFields(type, screen, raw) {
36
+ if (raw === undefined)
37
+ return undefined;
38
+ const names = raw
39
+ .split(',')
40
+ .map((n) => n.trim())
41
+ .filter(Boolean);
42
+ if (!names.length)
43
+ throw usage('--fields needs field names, such as --fields CUSTNAME,CDES.');
44
+ const keys = type.key.filter((k) => type.fields.some((f) => f.name === k));
45
+ const chosen = names.map((n) => resolveField(type, screen, n).name);
46
+ return [...keys, ...chosen.filter((n) => !keys.includes(n))];
47
+ }
48
+ /** Lines of one sub-screen in a record, as a small table or one record. */
49
+ function subView(sub, value, fieldLimit, full) {
50
+ if (!sub.many) {
51
+ const one = value && typeof value === 'object' && !Array.isArray(value)
52
+ ? value
53
+ : undefined;
54
+ return { [sub.name]: one ? recordView(sub.def, one, fieldLimit) : null };
55
+ }
56
+ const lines = Array.isArray(value) ? value : [];
57
+ const shown = full ? lines : lines.slice(0, LINES);
58
+ const columns = defaultColumns(sub.def, shown);
59
+ return {
60
+ [sub.name]: shown.map((line) => tableRow(sub.def, line, columns, fieldLimit)),
61
+ ...(shown.length < lines.length
62
+ ? { [`${sub.name}_more`]: 'more lines exist; --full shows all' }
63
+ : {}),
64
+ };
65
+ }
66
+ function resolveWith(index, screen, raw) {
67
+ const subs = strings(raw).map((w) => resolveSub(index, screen, w));
68
+ return subs.filter((sub, i) => subs.findIndex((x) => x.nav === sub.nav) === i);
69
+ }
70
+ async function list(input, mode) {
71
+ const s = open(input);
72
+ const loaded = await screenIndex(s);
73
+ const { index } = loaded;
74
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
75
+ const v = input.values;
76
+ const limit = intFlag(v.limit, 'limit', 20, 1, 500);
77
+ const page = intFlag(v.page, 'page', 1, 1, 1_000_000);
78
+ const full = v.full === true;
79
+ const since = mode === 'changes' ? sinceFlag(v.since, input.io.now()) : undefined;
80
+ const filter = combineFilters(whereToFilter(strings(v.where), screen.type, screen.name), str(v.filter));
81
+ const keys = screen.type.key.filter((k) => screen.type.fields.some((f) => f.name === k));
82
+ const order = str(v.sort)
83
+ ? orderBy(String(v.sort), screen.type, screen.name)
84
+ : keys.join(',') || undefined;
85
+ const explicit = explicitFields(screen.type, screen.name, str(v.fields));
86
+ const subs = resolveWith(index, screen, v.with);
87
+ const select = explicit ?? (full ? undefined : candidateSelect(screen.type));
88
+ const answer = await readScreen(s, screen.name, queryString({
89
+ $filter: filter,
90
+ $select: select?.join(','),
91
+ $orderby: order,
92
+ $top: limit + 1,
93
+ $skip: page > 1 ? (page - 1) * limit : undefined,
94
+ $expand: expandOf(subs, full),
95
+ $since: since,
96
+ }));
97
+ const fetched = rowsOf(answer);
98
+ const more = fetched.length > limit;
99
+ const rows = fetched.slice(0, limit);
100
+ const columns = explicit ??
101
+ (full
102
+ ? screen.type.fields
103
+ .filter((f) => keys.includes(f.name) ||
104
+ (!f.internalId &&
105
+ rows.some((r) => r[f.name] !== null &&
106
+ r[f.name] !== '' &&
107
+ r[f.name] !== undefined)))
108
+ .map((f) => f.name)
109
+ : defaultColumns(screen.type, rows));
110
+ const noun = rows.length === 1 ? 'record' : 'records';
111
+ const place = mode === 'changes' ? ` changed since ${since}` : '';
112
+ const pageNote = page > 1 ? ` (page ${page})` : '';
113
+ const summary = `${rows.length} ${noun} from ${screen.name}${place}${pageNote}${more ? ', more exist' : ''}`;
114
+ if (!rows.length) {
115
+ const help = filter || since
116
+ ? [
117
+ `Run \`priority-axi fields ${screen.name}\` to check value types if you expected records; the filter's field names are valid, so no record matched`,
118
+ ]
119
+ : [];
120
+ return render({ summary, ...builtNote(loaded) }, help);
121
+ }
122
+ return bounded({
123
+ total: rows.length,
124
+ narrower: commandLine(mode, [screen.name], v, {
125
+ full: null,
126
+ limit: '20',
127
+ }),
128
+ build: (shown, fieldLimit) => {
129
+ const records = rows.slice(0, shown).map((row) => {
130
+ const base = tableRow(screen.type, row, columns, fieldLimit);
131
+ for (const sub of subs) {
132
+ Object.assign(base, subView(sub, row[sub.nav], fieldLimit, full));
133
+ }
134
+ return base;
135
+ });
136
+ const help = [];
137
+ if (more) {
138
+ help.push(`Run \`${commandLine(mode, [screen.name], v, { page: String(page + 1) })}\` for the next ${limit}`);
139
+ }
140
+ if (keys.length === 1) {
141
+ help.push(`Run \`priority-axi show ${screen.name} <${keys[0]}>\` for one record`);
142
+ }
143
+ return render({
144
+ summary,
145
+ ...builtNote(loaded),
146
+ records,
147
+ ...(shown < rows.length
148
+ ? {
149
+ omitted: `${rows.length - shown} records not shown; use --limit ${Math.max(1, shown)} or --full`,
150
+ }
151
+ : {}),
152
+ }, help);
153
+ },
154
+ }, full);
155
+ }
156
+ export const get = (input) => list(input, 'get');
157
+ export const changes = (input) => list(input, 'changes');
158
+ /** Key terms from a positional value (one-field keys) or --key F=V flags (compound keys). */
159
+ function keyTerms(screen, positional, flags) {
160
+ const keys = screen.type.key.filter((k) => screen.type.fields.some((f) => f.name === k));
161
+ if (!keys.length) {
162
+ throw usage(`${screen.name} has no key. Use \`priority-axi get ${screen.name} --where F=V\` instead.`);
163
+ }
164
+ if (positional !== undefined && flags.length)
165
+ throw usage('Give the key as an argument or with --key, not both.');
166
+ if (positional !== undefined) {
167
+ if (keys.length > 1) {
168
+ throw usage(`${screen.name} has a compound key (${keys.join(', ')}). Use ${keys.map((k) => `--key ${k}=<value>`).join(' ')}.`);
169
+ }
170
+ return [[keys[0] ?? '', positional]];
171
+ }
172
+ if (!flags.length) {
173
+ throw usage(keys.length === 1
174
+ ? `Missing the ${keys[0]} value: priority-axi show ${screen.name} <${keys[0]}>.`
175
+ : `Missing the key: ${keys.map((k) => `--key ${k}=<value>`).join(' ')}.`);
176
+ }
177
+ const terms = flags.map((flag) => {
178
+ const term = parseWhere(flag);
179
+ if (term.op !== '=')
180
+ throw usage('--key takes FIELD=VALUE.');
181
+ return [
182
+ resolveField(screen.type, screen.name, term.field).name,
183
+ term.value,
184
+ ];
185
+ });
186
+ const named = terms.map(([f]) => f);
187
+ const missing = keys.filter((k) => !named.includes(k));
188
+ const extra = named.filter((f) => !keys.includes(f));
189
+ if (missing.length || extra.length || new Set(named).size !== named.length) {
190
+ throw usage(`${screen.name}'s key is ${keys.join(', ')}; give each exactly once with --key.`);
191
+ }
192
+ return terms;
193
+ }
194
+ export async function show(input) {
195
+ const s = open(input);
196
+ const { index } = await screenIndex(s);
197
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
198
+ const v = input.values;
199
+ const full = v.full === true;
200
+ const all = v.all === true;
201
+ const terms = keyTerms(screen, input.positionals[1], strings(v.key));
202
+ const fieldOf = (name) => screen.type.fields.find((f) => f.name === name);
203
+ const filter = terms
204
+ .map(([name, value]) => {
205
+ const field = fieldOf(name);
206
+ if (!field)
207
+ throw usage(`${screen.name} has no field ${name}.`);
208
+ return `${name} eq ${literal(field, value)}`;
209
+ })
210
+ .join(' and ');
211
+ const subs = resolveWith(index, screen, v.with);
212
+ const answer = await readScreen(s, screen.name, queryString({
213
+ $filter: filter,
214
+ $top: 2,
215
+ $expand: expandOf(subs, full),
216
+ }));
217
+ const rows = rowsOf(answer);
218
+ const keyText = terms.map(([f, value]) => `${f} ${value}`).join(', ');
219
+ if (!rows.length) {
220
+ throw new AxiError('not_found', `No ${screen.name} record has ${keyText}. Run \`priority-axi get ${screen.name} --limit 5\` to see records.`, { screen: screen.name });
221
+ }
222
+ if (rows.length > 1) {
223
+ throw new AxiError('priority_rejected', `More than one ${screen.name} record has ${keyText}.`, {
224
+ screen: screen.name,
225
+ });
226
+ }
227
+ const row = rows[0] ?? {};
228
+ const keyNames = terms.map(([f]) => f);
229
+ const fullCommand = commandLine('show', input.positionals, v, { full: '' });
230
+ return bounded({
231
+ total: screen.type.fields.length,
232
+ narrower: `priority-axi show ${input.positionals.map(shellWord).join(' ')}`,
233
+ build: (shown, fieldLimit) => {
234
+ const view = recordView(screen.type, row, fieldLimit, all);
235
+ const ordered = {};
236
+ for (const k of keyNames)
237
+ if (k in view)
238
+ ordered[k] = view[k];
239
+ for (const [k, value] of Object.entries(view))
240
+ if (!(k in ordered))
241
+ ordered[k] = value;
242
+ const entries = Object.entries(ordered);
243
+ const record = Object.fromEntries(entries.slice(0, shown));
244
+ const omitted = entries.length - Math.min(shown, entries.length);
245
+ const lines = {};
246
+ for (const sub of subs) {
247
+ Object.assign(lines, subView(sub, row[sub.nav], fieldLimit, full));
248
+ }
249
+ // Fields cut at the standard 500 carry their own marker; say more only
250
+ // when fields were dropped or cut shorter to fit.
251
+ const shortened = omitted > 0 || fieldLimit < 500;
252
+ return render({
253
+ screen: screen.name,
254
+ record,
255
+ ...lines,
256
+ ...(shortened
257
+ ? {
258
+ more: `${omitted ? `${omitted} more fields; ` : ''}run ${fullCommand}`,
259
+ }
260
+ : {}),
261
+ });
262
+ },
263
+ }, full);
264
+ }
@@ -0,0 +1,26 @@
1
+ // Rebuild the screen index now.
2
+ import { loadIndex } from '../index/cache.js';
3
+ import { render } from '../output/toon.js';
4
+ import { checkCompany, indexSource, open, priorityVersion } from './common.js';
5
+ export async function refresh(input) {
6
+ const s = open(input);
7
+ const version = await priorityVersion(s);
8
+ await checkCompany(s, true);
9
+ const { index, rebuilt } = await loadIndex(s.dir, indexSource(s), {
10
+ now: input.io.now(),
11
+ refresh: true,
12
+ liveVersion: version,
13
+ });
14
+ const types = Object.values(index.types);
15
+ const doc = {
16
+ index: 'rebuilt',
17
+ version: index.version,
18
+ screens: Object.keys(index.sets).length,
19
+ types: types.length,
20
+ fields: types.reduce((n, t) => n + t.fields.length, 0),
21
+ };
22
+ if (rebuilt) {
23
+ doc.metadata = `${(rebuilt.bytes / 2 ** 20).toFixed(1)} MB in ${(rebuilt.ms / 1000).toFixed(1)} s`;
24
+ }
25
+ return render(doc, ['Run `priority-axi` for the home view']);
26
+ }
package/dist/config.js ADDED
@@ -0,0 +1,76 @@
1
+ // Settings come from the environment and from flags; flags win. The password
2
+ // is only ever read from PRIORITY_PASSWORD, which inside Comis holds a
3
+ // placeholder that the Gate swaps for the real one.
4
+ import { AxiError, usage } from './errors.js';
5
+ // The Gate's named path segment: [A-Za-z0-9._~-]+. A segment outside it, such
6
+ // as "tabula.ini,3", would not match any Gate rule.
7
+ const SEGMENT = /^[A-Za-z0-9._~-]+$/;
8
+ const SERVICE_ROOT = /^(https?:\/\/[^/]+)\/odata\/Priority\/([^/]+)\/([^/]+)\/?$/i;
9
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1)$/;
10
+ function originOf(raw) {
11
+ let url;
12
+ try {
13
+ url = new URL(raw);
14
+ }
15
+ catch {
16
+ throw usage('PRIORITY_URL is not a URL. Use https://host or the full service root https://host/odata/Priority/<ini>/<company>.');
17
+ }
18
+ if (url.username || url.password) {
19
+ throw usage('PRIORITY_URL must not contain a username or password.');
20
+ }
21
+ const plainLocal = url.protocol === 'http:' && LOCAL_HOST.test(url.hostname);
22
+ if (url.protocol !== 'https:' && !plainLocal) {
23
+ throw usage('PRIORITY_URL must use https.');
24
+ }
25
+ if ((url.pathname !== '/' && url.pathname !== '') || url.search || url.hash) {
26
+ throw usage('PRIORITY_URL must be https://host or the full service root https://host/odata/Priority/<ini>/<company>.');
27
+ }
28
+ return url.origin;
29
+ }
30
+ function segment(value, name) {
31
+ if (!SEGMENT.test(value)) {
32
+ throw usage(`${name} may contain only letters, digits and . _ ~ - (no commas or slashes).`);
33
+ }
34
+ return value;
35
+ }
36
+ export function readSettings(env, flags = {}) {
37
+ const rawUrl = (env.PRIORITY_URL ?? '').trim();
38
+ const password = env.PRIORITY_PASSWORD ?? '';
39
+ if (!rawUrl || !password) {
40
+ const missing = !rawUrl ? 'PRIORITY_URL' : 'PRIORITY_PASSWORD';
41
+ throw new AxiError('not_connected', `Priority is not connected: ${missing} is not set. Ask the owner to run \`comis connect priority\`.`);
42
+ }
43
+ let fromUrl = {};
44
+ let origin;
45
+ const root = SERVICE_ROOT.exec(rawUrl);
46
+ if (root?.[1] && root[2] && root[3]) {
47
+ origin = originOf(root[1]);
48
+ fromUrl = { ini: root[2], company: root[3] };
49
+ }
50
+ else {
51
+ origin = originOf(rawUrl.replace(/\/+$/, ''));
52
+ }
53
+ const ini = flags.ini || env.PRIORITY_INI || fromUrl.ini || 'tabula.ini';
54
+ const company = flags.company || env.PRIORITY_COMPANY || fromUrl.company || '';
55
+ const user = flags.user || env.PRIORITY_USER || '';
56
+ if (!company) {
57
+ throw new AxiError('missing_setting', 'No Priority company code. Ask the owner for it, then pass --company <code>.');
58
+ }
59
+ if (!user) {
60
+ throw new AxiError('missing_setting', 'No Priority API username. Ask the owner for it, then pass --user <name>.');
61
+ }
62
+ // Basic authentication cannot carry a colon in the username.
63
+ if (user.includes(':') || /\p{Cc}/u.test(user)) {
64
+ throw usage('The username (--user or PRIORITY_USER) must not contain a colon or control characters.');
65
+ }
66
+ return {
67
+ origin,
68
+ ini: segment(ini, 'The ini (--ini or PRIORITY_INI)'),
69
+ company: segment(company, 'The company (--company or PRIORITY_COMPANY)'),
70
+ user,
71
+ password,
72
+ };
73
+ }
74
+ export function serviceRoot(settings) {
75
+ return `${settings.origin}/odata/Priority/${settings.ini}/${settings.company}`;
76
+ }