@winning-sales/nexo 0.6.0 → 0.7.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,71 @@
1
+ export function isAgent(value) {
2
+ if (typeof value !== 'object' || value === null) {
3
+ return false;
4
+ }
5
+ const fields = value;
6
+ return (typeof fields.id === 'string' &&
7
+ typeof fields.name === 'string' &&
8
+ typeof fields.status === 'string' &&
9
+ typeof fields.pairedAt === 'string' &&
10
+ Array.isArray(fields.connectors) &&
11
+ Array.isArray(fields.reach));
12
+ }
13
+ export function isAgentList(value) {
14
+ return Array.isArray(value) && value.every(isAgent);
15
+ }
16
+ export function isPairingCode(value) {
17
+ if (typeof value !== 'object' || value === null) {
18
+ return false;
19
+ }
20
+ const fields = value;
21
+ return typeof fields.code === 'string' && typeof fields.expiresAt === 'string';
22
+ }
23
+ function connectionOf(agent) {
24
+ if (agent.status === 'revoked') {
25
+ return 'revogado';
26
+ }
27
+ return agent.connected ? 'conectado' : 'desconectado';
28
+ }
29
+ function connectorNames(agent) {
30
+ return agent.connectors.length === 0
31
+ ? 'nenhum conector'
32
+ : agent.connectors.map((connector) => connector.name).join(', ');
33
+ }
34
+ export function describeAgentRow(agent) {
35
+ return `${agent.id} ${connectionOf(agent).padEnd(12)} v${agent.agentVersion} último contato ${agent.lastSeenAt ?? '-'} ${agent.name} (${connectorNames(agent)})`;
36
+ }
37
+ function describeReach(reach) {
38
+ const where = reach.port === undefined ? reach.host : `${reach.host}:${String(reach.port)}`;
39
+ const extra = [reach.engine, reach.database].filter((part) => part !== undefined).join('/');
40
+ return `${reach.kind} ${where}${extra === '' ? '' : ` (${extra})`}`;
41
+ }
42
+ export function describeAgent(agent) {
43
+ return [
44
+ `${agent.name} ${agent.id}`,
45
+ ` Estado: ${connectionOf(agent)}, versão ${agent.agentVersion}, último contato ${agent.lastSeenAt ?? '-'}`,
46
+ ` Máquina: ${agent.hostname} (${agent.os}, ${agent.arch}), pareada em ${agent.pairedAt}`,
47
+ ...(agent.revokedAt === null ? [] : [` Revogado em ${agent.revokedAt}`]),
48
+ ` Conectores: ${connectorNames(agent)}`,
49
+ agent.reach.length === 0 ? ' A lista local dele não alcança nada que ele tenha informado.' : ' A lista local dele alcança:',
50
+ ...agent.reach.map((reach) => ` - ${describeReach(reach)}`)
51
+ ];
52
+ }
53
+ export function revokePreview(agent) {
54
+ return {
55
+ title: `Revogar o agente local ${agent.name}`,
56
+ changes: [
57
+ `A máquina é ${agent.hostname} (${agent.os}, ${agent.arch}); o programa instalado nela fica parado até alguém desinstalá-lo.`,
58
+ agent.connectors.length === 0
59
+ ? 'Nenhum conector usa este agente agora.'
60
+ : `Os conectores que passam por ele deixam de alcançar o ERP até o manifesto apontar para outro agente: ${connectorNames(agent)}.`,
61
+ 'O túnel é cortado na hora e sem volta: não há como reativá-lo. Para ter um agente de novo, instale outro com um código novo.'
62
+ ]
63
+ };
64
+ }
65
+ /** O agente ativo que não estava na lista de antes do pedido (o mais novo), sem depender de relógio; ou `null`. */
66
+ export function newlyPaired(agents, known) {
67
+ const paired = agents
68
+ .filter((agent) => agent.status === 'active' && !known.has(agent.id))
69
+ .sort((a, b) => b.pairedAt.localeCompare(a.pairedAt));
70
+ return paired[0] ?? null;
71
+ }
@@ -7,7 +7,7 @@ function isPreview(value) {
7
7
  const fields = value;
8
8
  return typeof fields.title === 'string' && Array.isArray(fields.changes) && typeof fields.confirmation === 'object';
9
9
  }
10
- async function ask(context, question) {
10
+ export async function ask(context, question) {
11
11
  const reader = createInterface({ input: context.stdin, output: context.stderr, terminal: true });
12
12
  try {
13
13
  const answer = await new Promise((resolve) => {
@@ -21,23 +21,51 @@ async function ask(context, question) {
21
21
  }
22
22
  async function apply(context, session, request, token) {
23
23
  const response = await clientOf(context, session).request({
24
- method: 'POST',
25
- path: `/v1/connect/connectors/${request.connectorId}/${request.kind}`,
26
- body: { confirmationToken: token }
24
+ method: request.applyAs?.method ?? 'POST',
25
+ path: `/v1/connect/connectors/${request.connectorId}${request.applyAs === undefined ? `/${request.path}` : request.applyAs.path}`,
26
+ body: { ...request.body, confirmationToken: token }
27
27
  });
28
28
  if (request.json) {
29
29
  printJson(context, response.body);
30
30
  return;
31
31
  }
32
32
  printLine(context, 'Feito.');
33
+ for (const line of request.summarize?.(response.body) ?? []) {
34
+ printLine(context, line);
35
+ }
33
36
  }
34
- function showPreview(context, preview) {
37
+ export function showPreview(context, preview) {
35
38
  printLine(context, preview.title);
36
39
  for (const change of preview.changes) {
37
40
  printLine(context, ` - ${change}`);
38
41
  }
39
42
  }
43
+ async function typedName(context, expected) {
44
+ const reader = createInterface({ input: context.stdin, output: context.stderr, terminal: true });
45
+ try {
46
+ const answer = await new Promise((resolve) => {
47
+ reader.question(`Para apagar, digite o nome do conector (${expected}): `, resolve);
48
+ });
49
+ return answer.trim() === expected;
50
+ }
51
+ finally {
52
+ reader.close();
53
+ }
54
+ }
40
55
  async function decide(context, session, request, preview) {
56
+ if (request.typeToConfirm !== undefined) {
57
+ if (context.stdin.isTTY === true && (await typedName(context, request.typeToConfirm))) {
58
+ await apply(context, session, request, preview.confirmation.token);
59
+ return;
60
+ }
61
+ if (context.stdin.isTTY === true) {
62
+ printNotice(context, 'O nome não confere. Nada mudou.');
63
+ return;
64
+ }
65
+ printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez (-y sozinho não basta):');
66
+ printNotice(context, ` ${request.command} --confirm ${preview.confirmation.token}`);
67
+ return;
68
+ }
41
69
  if (request.yes || (context.stdin.isTTY === true && (await ask(context, 'Confirma? (s/N) ')))) {
42
70
  await apply(context, session, request, preview.confirmation.token);
43
71
  return;
@@ -47,7 +75,7 @@ async function decide(context, session, request, preview) {
47
75
  return;
48
76
  }
49
77
  printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez:');
50
- printNotice(context, ` nexo connect ${request.kind} --confirm ${preview.confirmation.token}`);
78
+ printNotice(context, ` ${request.command} --confirm ${preview.confirmation.token}`);
51
79
  }
52
80
  export async function requestChange(context, session, request) {
53
81
  if (request.confirm !== undefined) {
@@ -56,7 +84,8 @@ export async function requestChange(context, session, request) {
56
84
  }
57
85
  const response = await clientOf(context, session).request({
58
86
  method: 'POST',
59
- path: `/v1/connect/connectors/${request.connectorId}/${request.kind}/preview`
87
+ path: `/v1/connect/connectors/${request.connectorId}/${request.path}/preview`,
88
+ ...(request.body === undefined ? {} : { body: request.body })
60
89
  });
61
90
  if (!isPreview(response.body)) {
62
91
  throw new Error('Prévia em formato inesperado.');
@@ -68,3 +97,35 @@ export async function requestChange(context, session, request) {
68
97
  showPreview(context, response.body);
69
98
  await decide(context, session, request, response.body);
70
99
  }
100
+ function reportApplied(context, change, response) {
101
+ if (change.json) {
102
+ printJson(context, response.body);
103
+ return;
104
+ }
105
+ if (change.report === undefined) {
106
+ printLine(context, 'Feito.');
107
+ return;
108
+ }
109
+ change.report(response.body);
110
+ }
111
+ /** Mudança sem prévia no `/v1`: a prévia é montada aqui e o sim é local (`--confirm` sem token). */
112
+ export async function requestLocalChange(context, change) {
113
+ const approved = change.yes || change.confirmed;
114
+ if (change.json && !approved) {
115
+ printJson(context, change.preview);
116
+ return;
117
+ }
118
+ if (!change.json) {
119
+ showPreview(context, change.preview);
120
+ }
121
+ if (approved || (context.stdin.isTTY === true && (await ask(context, 'Confirma? (s/N) ')))) {
122
+ reportApplied(context, change, await change.apply());
123
+ return;
124
+ }
125
+ if (context.stdin.isTTY === true) {
126
+ printNotice(context, 'Nada mudou.');
127
+ return;
128
+ }
129
+ printNotice(context, 'Mostre isto à pessoa. Depois do sim dela, aplique uma vez:');
130
+ printNotice(context, ` ${change.command} --confirm`);
131
+ }
@@ -0,0 +1,30 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { usageError } from '../errors.js';
3
+ function parsed(text, origin) {
4
+ let value;
5
+ try {
6
+ value = JSON.parse(text);
7
+ }
8
+ catch {
9
+ throw usageError(`${origin} não é JSON válido.`, 'Passe um objeto, como --args \'{"cnpj":"123"}\' ou --args @args.json.');
10
+ }
11
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
12
+ throw usageError(`${origin} precisa ser um objeto JSON.`);
13
+ }
14
+ return { ...value };
15
+ }
16
+ /** O valor de `--args`: um JSON na linha, ou `@arquivo`. Recusa antes de chamar o Nexo. */
17
+ export function readArgs(raw) {
18
+ if (!raw.startsWith('@')) {
19
+ return parsed(raw, '--args');
20
+ }
21
+ const path = raw.slice(1);
22
+ let text;
23
+ try {
24
+ text = readFileSync(path, 'utf8');
25
+ }
26
+ catch {
27
+ throw usageError(`Não consegui ler ${path}.`);
28
+ }
29
+ return parsed(text, path);
30
+ }
@@ -0,0 +1,106 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { usageError } from '../errors.js';
3
+ const PROPERTIES_PREFIX = 'properties.';
4
+ export function isQuarantineList(value) {
5
+ return Array.isArray(value);
6
+ }
7
+ export function isExternalWrites(value) {
8
+ return typeof value === 'object' && value !== null && typeof value.externalWrites === 'boolean';
9
+ }
10
+ function isProperty(key) {
11
+ return key.startsWith(PROPERTIES_PREFIX) && key.length > PROPERTIES_PREFIX.length;
12
+ }
13
+ function scalar(text) {
14
+ if (text === 'true') {
15
+ return true;
16
+ }
17
+ if (text === 'false') {
18
+ return false;
19
+ }
20
+ return text;
21
+ }
22
+ function fileSection(file, name) {
23
+ const section = file[name];
24
+ if (section === undefined) {
25
+ return {};
26
+ }
27
+ if (typeof section !== 'object' || section === null || Array.isArray(section)) {
28
+ throw usageError(`"${name}" no arquivo precisa ser um objeto.`);
29
+ }
30
+ return { ...section };
31
+ }
32
+ export function readFixFile(path) {
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
36
+ }
37
+ catch {
38
+ throw usageError(`Não consegui ler o JSON de ${path}.`, 'O arquivo tem o formato do PATCH: { "values": {...}, "properties": {...} }.');
39
+ }
40
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
41
+ throw usageError('O arquivo precisa ser um objeto JSON.', 'Formato: { "values": {...}, "properties": {...} }.');
42
+ }
43
+ const file = parsed;
44
+ return { values: fileSection(file, 'values'), properties: fileSection(file, 'properties') };
45
+ }
46
+ /**
47
+ * `campo=valor` vai para os campos nativos (`values`); `properties.chave=valor` para as propriedades.
48
+ * `true` e `false` viram booleano; o resto é texto (para outro tipo, use `--file`).
49
+ */
50
+ export function fixFrom(sets, file) {
51
+ const values = { ...file?.values };
52
+ const properties = { ...file?.properties };
53
+ for (const entry of sets) {
54
+ const at = entry.indexOf('=');
55
+ if (at <= 0) {
56
+ throw usageError(`"${entry}" não está no formato campo=valor.`, 'Exemplo: --set cnpj=12345678000190');
57
+ }
58
+ const key = entry.slice(0, at);
59
+ const value = scalar(entry.slice(at + 1));
60
+ const target = isProperty(key) ? properties : values;
61
+ target[isProperty(key) ? key.slice(PROPERTIES_PREFIX.length) : key] = value;
62
+ }
63
+ if (Object.keys(values).length === 0 && Object.keys(properties).length === 0) {
64
+ throw usageError('Nada para corrigir.', 'Use --set campo=valor ou --file <json>.');
65
+ }
66
+ return { values, properties };
67
+ }
68
+ function show(value) {
69
+ return typeof value === 'string' ? value : JSON.stringify(value);
70
+ }
71
+ export function describeItem(item) {
72
+ const fields = [
73
+ ...Object.entries(item.record.values).map(([key, value]) => ` ${key}: ${show(value)}`),
74
+ ...Object.entries(item.record.properties).map(([key, value]) => ` ${PROPERTIES_PREFIX}${key}: ${show(value)}`)
75
+ ];
76
+ return [
77
+ `${item.id} ${item.objectType} execução ${item.runId}`,
78
+ ` motivo: ${item.reason}`,
79
+ ...(fields.length === 0 ? [] : [' valores:', ...fields])
80
+ ];
81
+ }
82
+ export function fixPreview(item, fix) {
83
+ const lines = (kind, prefix) => Object.entries(fix[kind]).map(([key, value]) => `${prefix}${key}: ${show(item.record[kind][key] ?? '(vazio)')} → ${show(value)}`);
84
+ return {
85
+ title: `Corrigir o registro ${item.id} (${item.objectType}) da quarentena`,
86
+ changes: [...lines('values', ''), ...lines('properties', PROPERTIES_PREFIX), 'O registro volta ao Nexo no próximo reprocessamento.']
87
+ };
88
+ }
89
+ export function describeWrites(writes) {
90
+ const lines = [`Escreve no outro sistema: ${writes.externalWrites ? 'sim' : 'não'}`];
91
+ lines.push(`Hosts confirmados: ${(writes.confirmed?.hosts ?? []).join(', ') || 'nenhum'}`);
92
+ if (writes.needsConfirmation) {
93
+ lines.push('Uma escrita espera a confirmação de uma pessoa.');
94
+ }
95
+ const held = writes.held;
96
+ if (held !== null) {
97
+ lines.push(`Escrita retida ${held.id} (${held.status}), execução ${held.runId}:`, ` ${held.method} ${held.url}`);
98
+ if (held.body !== null) {
99
+ lines.push(` corpo: ${held.body}`);
100
+ }
101
+ if (held.failureNotice !== null) {
102
+ lines.push(` ${held.failureNotice}`);
103
+ }
104
+ }
105
+ return lines;
106
+ }
@@ -1,6 +1,9 @@
1
1
  import { clientOf, printLine } from '../context.js';
2
2
  import { CliError } from '../errors.js';
3
3
  import { EXIT_CODES } from '../exit-codes.types.js';
4
+ /** O que se corta na tela; o `--json` traz tudo. */
5
+ export const MAX_OUTPUT_LINES = 20;
6
+ export const MAX_QUARANTINE_ITEMS = 10;
4
7
  export const DEFAULT_WAIT = { intervalMs: 2000, timeoutMs: 10 * 60_000 };
5
8
  function isRun(value) {
6
9
  return typeof value === 'object' && value !== null && typeof value.status === 'string';
@@ -23,7 +26,7 @@ export async function waitForRun(context, session, ids, wait) {
23
26
  let run = await fetchRun(context, session, ids.connectorId, ids.runId);
24
27
  while (run.status === 'running') {
25
28
  if (Date.now() > deadline) {
26
- throw new CliError('O ensaio ainda está rodando.', EXIT_CODES.failure, `Acompanhe com \`nexo connect run ${ids.runId}\`.`);
29
+ throw new CliError('A execução ainda está rodando.', EXIT_CODES.failure, `Acompanhe com \`nexo connect run ${ids.runId}\`.`);
27
30
  }
28
31
  await pause(wait.intervalMs);
29
32
  run = await fetchRun(context, session, ids.connectorId, ids.runId);
@@ -45,7 +48,46 @@ function failedSteps(steps) {
45
48
  .slice(0, 10)
46
49
  .map((step) => ` ${step.kind} ${step.target ?? ''} → ${step.errorCode ?? String(step.status)}: ${step.message ?? ''}`.trimEnd());
47
50
  }
48
- export function describeRun(run) {
51
+ export function cut(lines, max, what) {
52
+ return lines.length <= max ? lines : [...lines.slice(0, max), ` … mais ${String(lines.length - max)} ${what} (veja com --json)`];
53
+ }
54
+ function compact(value) {
55
+ return JSON.stringify(value);
56
+ }
57
+ function timeOf(at) {
58
+ return at === undefined || at === null ? '' : `${at.slice(11, 19)} `;
59
+ }
60
+ function logLines(steps) {
61
+ const logs = (steps ?? []).filter((step) => step.kind === 'log');
62
+ if (logs.length === 0) {
63
+ return [];
64
+ }
65
+ const lines = logs.map((log) => ` ${timeOf(log.at)}${log.message ?? ''}${log.data === undefined || log.data === null ? '' : ` ${compact(log.data)}`}`.trimEnd());
66
+ return ['Logs do script:', ...cut(lines, MAX_OUTPUT_LINES, 'logs')];
67
+ }
68
+ function outputLines(output) {
69
+ if (output === undefined || output === null || Object.keys(output).length === 0) {
70
+ return [];
71
+ }
72
+ const lines = JSON.stringify(output, null, 2)
73
+ .split('\n')
74
+ .map((line) => ` ${line}`);
75
+ return ['Resultado da operação:', ...cut(lines, MAX_OUTPUT_LINES, 'linhas')];
76
+ }
77
+ function quarantineLines(planned) {
78
+ if (planned === undefined || planned === null || (planned.total === 0 && planned.items.length === 0)) {
79
+ return [];
80
+ }
81
+ const shown = planned.items.slice(0, MAX_QUARANTINE_ITEMS);
82
+ const lines = shown.map((item) => ` ${item.object} ${item.externalId ?? '-'}: ${item.reason} (${item.code}) ${compact({ ...item.values, ...(item.properties === undefined ? {} : { properties: item.properties }) })}`);
83
+ const total = Math.max(planned.total, planned.items.length);
84
+ return [
85
+ `Iriam para a quarentena (${String(total)}):`,
86
+ ...lines,
87
+ ...(total > shown.length ? [` … mais ${String(total - shown.length)} (veja com --json)`] : [])
88
+ ];
89
+ }
90
+ function headLines(run) {
49
91
  const lines = [`Execução ${run.id}: ${run.status}${run.mode === 'dry_run' ? ' (ensaio)' : ''}`];
50
92
  if (run.failureReason !== null) {
51
93
  lines.push(`Motivo: ${run.failureReason}`);
@@ -53,18 +95,31 @@ export function describeRun(run) {
53
95
  if (run.counters !== null && Object.keys(run.counters).length > 0) {
54
96
  lines.push(`Contadores: ${JSON.stringify(run.counters)}`);
55
97
  }
56
- lines.push(...plannedLines('Escreveria no Nexo:', run.plannedNexoWrites), ...plannedLines('Escreveria no outro sistema:', run.plannedWrites));
98
+ return lines;
99
+ }
100
+ function errorLines(run) {
57
101
  const failed = failedSteps(run.steps);
58
- if (failed.length > 0) {
59
- lines.push('Passos com erro:', ...failed);
60
- }
61
- if (run.error !== null) {
62
- lines.push(`Erro: ${run.error.name ?? 'Error'}: ${run.error.message ?? ''}`, ...(run.error.stack === null ? [] : [run.error.stack]));
102
+ return [
103
+ ...(failed.length > 0 ? ['Passos com erro:', ...failed] : []),
104
+ ...(run.error === null
105
+ ? []
106
+ : [`Erro: ${run.error.name ?? 'Error'}: ${run.error.message ?? ''}`, ...(run.error.stack === null ? [] : [run.error.stack])])
107
+ ];
108
+ }
109
+ export function describeRun(run, options = {}) {
110
+ const lines = [
111
+ ...headLines(run),
112
+ ...plannedLines('Escreveria no Nexo:', run.plannedNexoWrites),
113
+ ...plannedLines('Escreveria no outro sistema:', run.plannedWrites),
114
+ ...errorLines(run)
115
+ ];
116
+ if (options.quiet !== true) {
117
+ lines.push(...logLines(run.steps), ...outputLines(run.output), ...quarantineLines(run.plannedQuarantine));
63
118
  }
64
119
  return lines;
65
120
  }
66
- export function printRun(context, run) {
67
- for (const line of describeRun(run)) {
121
+ export function printRun(context, run, options = {}) {
122
+ for (const line of describeRun(run, options)) {
68
123
  printLine(context, line);
69
124
  }
70
125
  }
@@ -0,0 +1,38 @@
1
+ import { fetchMe } from '../commands/whoami.js';
2
+ /** O fuso da empresa (`/v1/me`); só se pergunta quando há uma próxima execução para mostrar. */
3
+ export async function companyTimeZone(context, session) {
4
+ return (await fetchMe(context, session)).company.timezone;
5
+ }
6
+ export function formatNextRun(iso, timeZone) {
7
+ const parts = {};
8
+ for (const part of new Intl.DateTimeFormat('pt-BR', {
9
+ timeZone,
10
+ day: '2-digit',
11
+ month: '2-digit',
12
+ hour: '2-digit',
13
+ minute: '2-digit',
14
+ hourCycle: 'h23'
15
+ }).formatToParts(new Date(iso))) {
16
+ parts[part.type] = part.value;
17
+ }
18
+ return `${parts.day ?? ''}/${parts.month ?? ''} ${parts.hour ?? ''}:${parts.minute ?? ''}`;
19
+ }
20
+ export function hasNextRun(rows) {
21
+ return rows.some((row) => typeof row.nextRunAt === 'string');
22
+ }
23
+ /** A linha "Agenda" do `status`; nada quando a resposta é antiga e não traz a agenda. */
24
+ export function scheduleLine(fields, timeZone) {
25
+ if (fields.schedule === undefined) {
26
+ return null;
27
+ }
28
+ if (fields.schedule === null) {
29
+ return 'Agenda: sem agenda.';
30
+ }
31
+ if (typeof fields.nextRunAt === 'string') {
32
+ return `Agenda: ${fields.schedule}. Próxima: ${formatNextRun(fields.nextRunAt, timeZone ?? 'UTC')}${timeZone === null ? ' UTC' : ''}.`;
33
+ }
34
+ if (fields.status === 'paused') {
35
+ return `Agenda: ${fields.schedule} (pausado).`;
36
+ }
37
+ return `Agenda: ${fields.schedule} (não está ligado).`;
38
+ }
@@ -29,3 +29,26 @@ export const TEMPLATE_TSCONFIG = `${JSON.stringify({
29
29
  },
30
30
  include: ['connector.ts', 'connect-sdk.d.ts']
31
31
  }, null, 2)}\n`;
32
+ export const TEMPLATE_README = `# Conector
33
+
34
+ \`connector.ts\` é o código e \`manifest.json\` diz no que ele mexe. Suba com \`nexo connect push -m "o que mudou"\`.
35
+
36
+ ## Quando ele roda
37
+
38
+ O gatilho \`cron\` do manifesto tem duas formas. Use uma por gatilho.
39
+
40
+ A cada tanto tempo:
41
+
42
+ \`\`\`json
43
+ { "type": "cron", "everyMinutes": 60 }
44
+ \`\`\`
45
+
46
+ Em horário fixo, no fuso da empresa (\`at\` aceita um horário ou uma lista; \`days\` é opcional e, sem ele, vale todo dia):
47
+
48
+ \`\`\`json
49
+ { "type": "cron", "at": "22:00" }
50
+ { "type": "cron", "at": ["08:00", "18:00"], "days": ["mon", "tue", "wed", "thu", "fri"] }
51
+ \`\`\`
52
+
53
+ A agenda muda no manifesto, com \`nexo connect push\` e \`nexo connect publish\`. \`nexo connect status\` mostra a agenda e a próxima execução.
54
+ `;
@@ -0,0 +1,60 @@
1
+ import { createHash } from 'node:crypto';
2
+ const ORIGINS = {
3
+ copilot: 'copiloto',
4
+ mcp: 'MCP',
5
+ api: 'API/CLI',
6
+ restore: 'restauração'
7
+ };
8
+ function isRecord(value) {
9
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
10
+ }
11
+ export function isVersionList(value) {
12
+ return Array.isArray(value) && value.every((item) => isRecord(item) && typeof item.seq === 'number');
13
+ }
14
+ export function isVersionFiles(value) {
15
+ return isRecord(value) && typeof value.seq === 'number' && typeof value.code === 'string' && isRecord(value.manifest);
16
+ }
17
+ export function isVersionDiff(value) {
18
+ return isRecord(value) && typeof value.same === 'boolean' && typeof value.code === 'string' && typeof value.manifest === 'string';
19
+ }
20
+ export function describeVersion(version, marks) {
21
+ const flags = [
22
+ ...(version.seq === marks.published ? ['publicada'] : []),
23
+ ...(version.seq === marks.head ? ['em edição'] : []),
24
+ ...(version.rehearsed ? ['ensaio limpo'] : version.needsFullRehearsal === true ? ['falta ensaio completo'] : [])
25
+ ];
26
+ const origin = ORIGINS[version.origin] ?? version.origin;
27
+ const author = version.authorUserId === null ? '' : ` ${version.authorUserId.slice(0, 8)}`;
28
+ const restored = version.restoredFromSeq === null ? '' : ` da v${String(version.restoredFromSeq)}`;
29
+ return [
30
+ `v${String(version.seq).padEnd(3)} ${version.createdAt.slice(0, 16).replace('T', ' ')} ${origin}${restored}${author}`,
31
+ version.summary ?? '(sem resumo)',
32
+ flags.length === 0 ? '' : `[${flags.join(', ')}]`
33
+ ]
34
+ .filter((part) => part !== '')
35
+ .join(' ');
36
+ }
37
+ /** Mesma comparação do que sobe com `push`: o código sem a quebra final, o manifesto como JSON. */
38
+ export function sameFiles(local, remote) {
39
+ return (local.code.trimEnd() === remote.code.trimEnd() &&
40
+ JSON.stringify(sortKeys(local.manifest)) === JSON.stringify(sortKeys(remote.manifest)));
41
+ }
42
+ /** Resumo estável do que `sameFiles` compara: o mesmo digest para os mesmos arquivos. */
43
+ export function filesDigest(files) {
44
+ return createHash('sha256')
45
+ .update(files.code.trimEnd())
46
+ .update('\0')
47
+ .update(JSON.stringify(sortKeys(files.manifest)))
48
+ .digest('hex');
49
+ }
50
+ function sortKeys(value) {
51
+ if (Array.isArray(value)) {
52
+ return value.map(sortKeys);
53
+ }
54
+ if (isRecord(value)) {
55
+ return Object.fromEntries(Object.keys(value)
56
+ .sort()
57
+ .map((key) => [key, sortKeys(value[key])]));
58
+ }
59
+ return value;
60
+ }
@@ -0,0 +1,87 @@
1
+ import { MAX_OUTPUT_LINES, cut } from '../connect/runs.js';
2
+ function isRecord(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ }
5
+ function unexpected(what) {
6
+ return new Error(`${what} em formato inesperado.`);
7
+ }
8
+ export function catalogOf(response) {
9
+ const body = response.body;
10
+ if (!isRecord(body) || !Array.isArray(body.operacoes)) {
11
+ throw unexpected('Lista de operações');
12
+ }
13
+ return body;
14
+ }
15
+ export function queryOf(response) {
16
+ if (!isRecord(response.body) || !isRecord(response.body.saida)) {
17
+ throw unexpected('Resposta da consulta');
18
+ }
19
+ return response.body;
20
+ }
21
+ export function previewOf(response) {
22
+ if (!isRecord(response.body) || !Array.isArray(response.body.escritas)) {
23
+ throw unexpected('Prévia da ação');
24
+ }
25
+ return response.body;
26
+ }
27
+ export function appliedOf(response) {
28
+ if (!isRecord(response.body) || typeof response.body.repetida !== 'boolean') {
29
+ throw unexpected('Resposta da ação');
30
+ }
31
+ return response.body;
32
+ }
33
+ function argLine(arg) {
34
+ const key = typeof arg.key === 'string' ? arg.key : '?';
35
+ const type = typeof arg.type === 'string' ? arg.type : '';
36
+ return `${key}${type === '' ? '' : `:${type}`}${arg.required === true ? '*' : ''}`;
37
+ }
38
+ function isNote(value) {
39
+ return isRecord(value) && typeof value.texto === 'string';
40
+ }
41
+ export function noteLine(label, note) {
42
+ return ` ${label}: ${note.texto}${note.autor === null ? '' : ` (${note.autor})`}`;
43
+ }
44
+ function noteLines(operation) {
45
+ const own = isNote(operation.notaDaEmpresa) ? [noteLine('nota da empresa', operation.notaDaEmpresa)] : [];
46
+ const ofArgs = operation.args.flatMap((arg) => isNote(arg.notaDaEmpresa) ? [noteLine(`nota da empresa em ${String(arg.key)}`, arg.notaDaEmpresa)] : []);
47
+ const ofOutput = (operation.saida?.fields ?? []).flatMap((field) => isNote(field.notaDaEmpresa) ? [noteLine(`nota da empresa no campo de saída ${String(field.key)}`, field.notaDaEmpresa)] : []);
48
+ return [...own, ...ofArgs, ...ofOutput];
49
+ }
50
+ export function operationLines(operation) {
51
+ const args = operation.args.length === 0 ? 'sem argumentos' : `args: ${operation.args.map(argLine).join(', ')}`;
52
+ return [
53
+ `${operation.id} ${operation.kind === 'action' ? 'ação ' : 'consulta'} ${operation.label} [${operation.conector}]`,
54
+ ` chave ${operation.key}; ${args}`,
55
+ ...noteLines(operation)
56
+ ];
57
+ }
58
+ /** O guia de cada conector vem antes das operações dele; os conectores seguem a ordem da resposta. */
59
+ export function catalogLines(catalog) {
60
+ const guides = new Map((catalog.guias ?? []).map((entry) => [entry.conector, entry.guia]));
61
+ const byConnector = new Map();
62
+ for (const operation of catalog.operacoes) {
63
+ byConnector.set(operation.conector, [...(byConnector.get(operation.conector) ?? []), operation]);
64
+ }
65
+ return [...byConnector].flatMap(([connector, operations]) => {
66
+ const guide = guides.get(connector);
67
+ const head = guide === undefined ? [] : [`Guia do conector ${connector}:`, ...guide.split('\n').map((line) => ` ${line}`)];
68
+ return [...head, ...operations.flatMap(operationLines)];
69
+ });
70
+ }
71
+ export function outputLines(output) {
72
+ if (output === null || Object.keys(output).length === 0) {
73
+ return [];
74
+ }
75
+ const lines = JSON.stringify(output, null, 2)
76
+ .split('\n')
77
+ .map((line) => ` ${line}`);
78
+ return cut(lines, MAX_OUTPUT_LINES, 'linhas');
79
+ }
80
+ export function writeLines(writes) {
81
+ return writes.flatMap((write) => [
82
+ ` - ${write.metodo} ${write.host}${write.url}${write.operacao === undefined ? '' : ` (${write.operacao})`}`,
83
+ ...(write.corpo === null
84
+ ? []
85
+ : cut(write.corpo.split('\n').map((line) => ` ${line}`), 5, 'linhas do corpo'))
86
+ ]);
87
+ }