@basaltkit/deploy-ui 0.0.0-stage → 0.1.1

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,57 @@
1
+ import { confirmDialog } from './dialog.js';
2
+ import { button, card, el, emptyState, pageHead, pill, replace, when } from './dom.js';
3
+ import { icon } from './icons.js';
4
+ import { problem } from './reply.js';
5
+ import { short } from './sanitize.js';
6
+ /** History: the last 10 releases, and rollback (to the last healthy release, or one picked here). */
7
+ export function renderHistory(app) {
8
+ const status = app.status;
9
+ const releases = status?.releases ?? [];
10
+ const message = el('div', { aria: { live: 'polite' } });
11
+ const current = releases.find((r) => r.status === 'ok');
12
+ const choices = releases.filter((r) => r.status === 'ok' && r !== current);
13
+ const select = el('select', { id: 'rollback-to' }, el('option', { value: '' }, 'the last healthy release (the deploy decides)'), ...choices.map((r) => el('option', { value: r.sha }, `${short(r.sha)} — ${when(r.at)}`)));
14
+ return el('section', { aria: { labelledby: 'history-title' } }, pageHead('history-title', 'History', 'The last 10 releases the server recorded, newest first.', el('button', { type: 'button', on: { click: () => { void app.refreshStatus(); } } }, icon('refresh'), 'Refresh')), !status ? emptyState('history', 'Load the status first.', 'The releases come with the status of the target.') : null, releases.length > 0 ? card('Releases', [table(releases)], { bodyClass: 'flush', actions: [el('span', { class: 'muted num' }, `${releases.length} recorded`)] }) : status ? emptyState('inbox', 'No release recorded yet.', 'The first deploy of this target will show here.') : null, status ? card('Roll back', [
15
+ el('div', { class: 'field' }, el('label', { for: 'rollback-to' }, 'Back to'), select),
16
+ el('p', { class: 'form-note' }, icon('alert'), 'Code only: the database is not rolled back. The commit it leaves is held: a scheduled run will not redeploy it until the branch moves on.'),
17
+ message,
18
+ ], { foot: [button('Roll back…', () => { void rollback(app, select.value, message); }, { class: 'danger' })] }) : null);
19
+ }
20
+ function table(releases) {
21
+ return el('div', { class: 'table-wrap' }, el('table', {}, el('thead', {}, el('tr', {}, ...['Commit', 'When', 'Status', 'Actor', 'Via', 'Client', 'Migrations', 'Backup', 'Note'].map((h) => el('th', { scope: 'col' }, h)))), el('tbody', {}, ...releases.map((r) => el('tr', {}, el('td', { class: 'nowrap' }, el('code', {}, short(r.sha))), el('td', { class: 'nowrap num' }, when(r.at)), el('td', {}, pill(r.status === 'ok' ? 'ok' : 'err', r.status)), el('td', {}, r.actor ?? r.user), el('td', { class: 'muted' }, r.via ?? ''), el('td', { class: 'mono' }, r.client ?? ''), el('td', { class: 'mono wrap' }, r.migrations.join(', ')), el('td', { class: 'mono wrap' }, r.backup ?? ''), el('td', { class: 'wrap' }, r.note ?? ''))))));
22
+ }
23
+ async function rollback(app, to, message) {
24
+ const t = app.current;
25
+ if (!t)
26
+ return;
27
+ const ok = await confirmDialog({
28
+ title: `Roll back ${t.name}?`,
29
+ context: `${t.ssh} · ${t.dir}${app.hello ? ` · host ${app.hello.host}` : ''}`,
30
+ lines: [
31
+ to ? `Back to ${short(to)}.` : 'Back to the last healthy release.',
32
+ 'The commit it leaves is held until the branch moves on.',
33
+ ],
34
+ confirmLabel: 'Roll back',
35
+ danger: true,
36
+ ...(t.protected ? { typeToConfirm: t.name } : {}),
37
+ });
38
+ if (!ok)
39
+ return;
40
+ replace(message, el('p', { class: 'muted' }, 'Starting the rollback…'));
41
+ let reply;
42
+ try {
43
+ reply = await app.api.post('rollback', { target: t.name, confirm: true, confirmedTarget: t, ...(t.protected ? { confirmName: t.name } : {}), ...(to ? { to } : {}) });
44
+ }
45
+ catch (error) {
46
+ replace(message, problem(undefined, error));
47
+ void app.noticeChange(error);
48
+ return;
49
+ }
50
+ const result = reply.result;
51
+ if (reply.ok && result?.runId) {
52
+ replace(message);
53
+ app.watch(result.runId, `rollback ${result.runId}`);
54
+ return;
55
+ }
56
+ replace(message, problem(reply));
57
+ }
@@ -0,0 +1,171 @@
1
+ import { confirmDialog } from './dialog.js';
2
+ import { append, button, card, el, emptyState, pageHead, replace } from './dom.js';
3
+ import { icon } from './icons.js';
4
+ import { banner, describe, diagnosticsBlock, problem } from './reply.js';
5
+ import { ApiError } from './api.js';
6
+ /** Plan & deploy: what a run would do, the questions it would ask, and the `.env` form. */
7
+ export function renderPlan(app) {
8
+ const reply = app.planReply;
9
+ const plan = app.plan;
10
+ const root = el('section', { aria: { labelledby: 'plan-title' } }, pageHead('plan-title', 'Plan & deploy', 'plan changes nothing on the server. Its preflight may reach the git remote, so it can take a while.', button(app.planBusy ? 'Planning…' : plan ? 'Plan again' : 'Run plan', () => { void app.runPlan(); }, { disabled: app.planBusy, class: plan ? '' : 'primary' })));
11
+ if (!reply) {
12
+ append(root, app.planBusy
13
+ ? emptyState('refresh', 'Planning…', 'Preflight checks and the plan run on the server; nothing changes there.')
14
+ : emptyState('plan', 'No plan yet', 'Run a plan to see what a deploy would do, the questions it would ask, and anything that would stop it.'));
15
+ return root;
16
+ }
17
+ if (!plan) {
18
+ append(root, problem(reply) ?? el('p', {}, 'No plan came back.'));
19
+ return root;
20
+ }
21
+ append(root, ...findings(plan.findings));
22
+ if (plan.lines.length > 0) {
23
+ append(root, card('What a run would do', [el('div', { class: 'table-wrap' }, el('table', { class: 'plan-lines' }, el('tbody', {}, ...plan.lines.map((line) => el('tr', {}, el('th', { scope: 'row' }, el('span', { class: 'step-chip' }, line.step)), el('td', {}, line.text))))))], { bodyClass: 'flush' }));
24
+ }
25
+ if (reply.diagnostics.length > 0)
26
+ append(root, diagnosticsBlock(reply.diagnostics));
27
+ append(root, deployForm(app, plan.questions, plan.blocking));
28
+ return root;
29
+ }
30
+ function findings(list) {
31
+ if (list.length === 0)
32
+ return [banner('ok', 'No problem found.')];
33
+ const sorted = [...list].sort((a, b) => (a.level === b.level ? 0 : a.level === 'error' ? -1 : 1));
34
+ const errors = list.filter((f) => f.level === 'error').length;
35
+ return [card('Findings', [findingList(sorted)], {
36
+ bodyClass: 'flush',
37
+ actions: [el('span', { class: 'muted' }, `${errors} error${errors === 1 ? '' : 's'}, ${list.length - errors} warning${list.length - errors === 1 ? '' : 's'}`)],
38
+ })];
39
+ }
40
+ /** Findings with a severity badge; the fix is copyable text, never run by the page. */
41
+ export function findingList(list, label) {
42
+ return el('ul', { class: 'findings', ...(label ? { aria: { label } } : {}) }, ...list.map((f) => findingItem(f)));
43
+ }
44
+ export function findingItem(f) {
45
+ return el('li', { class: 'finding' }, el('span', { class: `sev sev-${f.level === 'error' ? 'error' : 'warning'}` }, f.level === 'error' ? 'Error ' : 'Warning '), el('span', { class: 'finding-msg' }, f.id ? el('span', { class: 'finding-id' }, `[${f.id}] `) : null, f.message), f.fix ? el('div', { class: 'fix' }, el('span', { class: 'fix-label' }, 'Fix: '), el('code', {}, f.fix)) : null);
46
+ }
47
+ function questionField(question, index) {
48
+ const id = `q-${index}`;
49
+ const label = el('label', { for: id }, question.message, question.optional ? '' : el('span', { class: 'required', title: 'required' }, ' *'), question.key ? el('span', { class: 'field-key' }, ` (${question.key})`) : null);
50
+ let input;
51
+ if (question.kind === 'secret') {
52
+ // No default, no autocomplete, no spellcheck: a secret is typed, sent once, and the field is emptied.
53
+ input = el('input', { type: 'password', id, autocomplete: 'off', spellcheck: false, required: !question.optional, aria: { describedby: `${id}-error` } });
54
+ }
55
+ else if (question.kind === 'choice') {
56
+ input = el('select', { id, aria: { describedby: `${id}-error` } }, ...(question.optional ? [el('option', { value: '' }, '(none)')] : []), ...(question.choices ?? []).map((c) => el('option', { value: c }, c)));
57
+ if (question.default !== undefined)
58
+ input.value = question.default;
59
+ }
60
+ else if (question.kind === 'confirm') {
61
+ input = el('input', { type: 'checkbox', id, checked: question.default === 'yes' || question.default === 'true', aria: { describedby: `${id}-error` } });
62
+ return { node: el('div', { class: 'field check' }, el('label', { for: id }, input, el('span', {}, question.message, question.optional ? '' : el('span', { class: 'required', title: 'required' }, ' *'), question.key ? el('span', { class: 'field-key' }, ` (${question.key})`) : null)), el('span', { id: `${id}-error`, class: 'field-error' })), field: { question, input } };
63
+ }
64
+ else {
65
+ input = el('input', { type: 'text', id, value: question.default ?? '', autocomplete: 'off', spellcheck: false, required: !question.optional, aria: { describedby: `${id}-error` } });
66
+ }
67
+ return { node: el('div', { class: 'field' }, label, input, el('span', { id: `${id}-error`, class: 'field-error' })), field: { question, input } };
68
+ }
69
+ /** The answers the operator typed: empty optional fields are left out (the deploy keeps its default or nothing). */
70
+ function collectAnswers(fields) {
71
+ const answers = [];
72
+ for (const { question, input } of fields) {
73
+ const value = question.kind === 'confirm' ? (input.checked ? 'yes' : 'no') : input.value;
74
+ if (value === '' && question.optional)
75
+ continue;
76
+ answers.push({ id: question.id, value });
77
+ }
78
+ return answers;
79
+ }
80
+ /** Every field emptied, so no value lingers in the page after it was sent. */
81
+ function clearFields(fields) {
82
+ for (const { input } of fields) {
83
+ if (input instanceof HTMLInputElement && input.type === 'checkbox')
84
+ input.checked = false;
85
+ else
86
+ input.value = '';
87
+ }
88
+ }
89
+ function deployForm(app, questions, blocking) {
90
+ const t = app.current;
91
+ const fields = [];
92
+ const nodes = questions.map((q, i) => {
93
+ const { node, field } = questionField(q, i);
94
+ fields.push(field);
95
+ return node;
96
+ });
97
+ const message = el('div', { aria: { live: 'polite' } });
98
+ const hold = app.status?.hold;
99
+ const unhold = el('input', { type: 'checkbox', id: 'unhold' });
100
+ const attended = el('input', { type: 'checkbox', id: 'attended' });
101
+ const showFieldError = (id, text) => {
102
+ const index = questions.findIndex((q) => q.id === id);
103
+ const slot = index === -1 ? undefined : app.shell.main.querySelector(`#q-${index}-error`);
104
+ if (slot)
105
+ replace(slot, text);
106
+ };
107
+ const send = async (route) => {
108
+ if (!t)
109
+ return;
110
+ replace(message);
111
+ for (let i = 0; i < questions.length; i++) {
112
+ const slot = app.shell.main.querySelector(`#q-${i}-error`);
113
+ if (slot)
114
+ replace(slot);
115
+ }
116
+ const deploy = route === 'run';
117
+ const ok = await confirmDialog({
118
+ title: deploy ? `Deploy to ${t.name}?` : `Write the .env on ${t.name}?`,
119
+ context: `${t.ssh} · ${t.dir}${app.hello ? ` · host ${app.hello.host}` : ''}${app.status ? ` · app ${app.status.app}` : ''}`,
120
+ lines: [
121
+ deploy ? 'Fetch, .env, build, migrate, restart, health check — the run goes on on the server if this page closes (unless attended).' : 'The .env and the dedicated infra only; nothing is built or restarted.',
122
+ deploy && app.plan?.lines.some((l) => /migrat/i.test(l.step) || /migrat/i.test(l.text)) ? el('strong', {}, 'This will migrate the database.') : null,
123
+ ],
124
+ confirmLabel: deploy ? 'Deploy' : 'Write .env',
125
+ danger: true,
126
+ ...(t.protected ? { typeToConfirm: t.name } : {}),
127
+ });
128
+ if (!ok)
129
+ return;
130
+ const answers = collectAnswers(fields);
131
+ clearFields(fields);
132
+ const body = { target: t.name, confirm: true, confirmedTarget: t, answers, ...(t.protected ? { confirmName: t.name } : {}) };
133
+ if (!deploy) {
134
+ app.attended(`env on ${t.name}`, 'env', body);
135
+ return;
136
+ }
137
+ if (unhold.checked)
138
+ body['unhold'] = true;
139
+ if (attended.checked) {
140
+ body['attended'] = true;
141
+ app.attended(`run on ${t.name} (attended)`, 'run', body);
142
+ return;
143
+ }
144
+ replace(message, el('p', { class: 'muted' }, 'Starting the run on the server…'));
145
+ let reply;
146
+ try {
147
+ reply = await app.api.post('run', body);
148
+ }
149
+ catch (error) {
150
+ const field = error instanceof ApiError && typeof error.body['field'] === 'string' ? error.body['field'] : undefined;
151
+ if (field)
152
+ showFieldError(field, describe(error));
153
+ replace(message, problem(undefined, error));
154
+ void app.noticeChange(error);
155
+ return;
156
+ }
157
+ const result = reply.result;
158
+ if (reply.ok && result?.runId) {
159
+ replace(message);
160
+ app.watch(result.runId, `run ${result.runId}`);
161
+ return;
162
+ }
163
+ if (reply.error && /^answer-/.test(reply.error.code)) {
164
+ const id = /env\.[A-Z_][A-Z0-9_]*/.exec(reply.error.message)?.[0];
165
+ if (id)
166
+ showFieldError(id, `${reply.error.message} — type it again`);
167
+ }
168
+ replace(message, problem(reply));
169
+ };
170
+ return el('form', { class: 'card', aria: { label: 'Deploy' }, on: { submit: (event) => { event.preventDefault(); void send('run'); } } }, el('div', { class: 'card-head' }, el('h3', {}, questions.length > 0 ? 'What the run will ask' : 'Deploy'), t?.protected ? el('span', { class: 'badge badge-protected' }, icon('shield'), 'PROTECTED') : null), el('div', { class: 'card-body' }, el('p', { class: 'form-note' }, icon(questions.length > 0 ? 'lock' : 'ok'), questions.length > 0 ? 'Secrets are sent once, over your ssh, to the deploy on the server; they are never stored here and the fields are emptied after sending.' : 'Nothing to answer: the .env is complete.'), nodes.length > 0 ? el('div', { class: 'form-section' }, ...nodes) : null, el('div', { class: 'form-section' }, hold ? el('div', { class: 'field check' }, el('label', { for: 'unhold' }, unhold, el('span', {}, ' Deploy anyway: the held commit ', el('code', {}, hold.sha.slice(0, 12)), ' may be deployed (--unhold)'))) : null, el('details', { class: 'advanced' }, el('summary', {}, 'Advanced'), el('div', { class: 'field check' }, el('label', { for: 'attended' }, attended, el('span', {}, ' Attended: the run stops at its next step if this page closes or the UI quits'))))), blocking ? banner('err', 'The plan found problems that stop a run: fix them first.') : null, message), el('div', { class: 'card-foot' }, button('Write .env only…', () => { void send('env'); }), el('button', { type: 'submit', class: 'primary', disabled: blocking }, 'Deploy…')));
171
+ }
@@ -0,0 +1,338 @@
1
+ import { ApiError } from './api.js';
2
+ import { confirmDialog } from './dialog.js';
3
+ import { append, button, el, quiet, replace } from './dom.js';
4
+ import { icon } from './icons.js';
5
+ import { findingItem } from './view-plan.js';
6
+ import { banner, describe, errorBanner, problem } from './reply.js';
7
+ import { clean } from './sanitize.js';
8
+ /** The log lines kept in the page; the full log stays on the server ("Show from the start" replays it). */
9
+ export const MAX_LOG_LINES = 5000;
10
+ const SEQ_KEY = (runId) => `basalt-deploy-ui:seq:${runId}`;
11
+ /**
12
+ * One run, live: steps, findings, the log and a final banner, fed by stream
13
+ * messages. Dispatch is on the event's `type` only — never on its text, so a
14
+ * build that prints a fake `done` is a log line.
15
+ */
16
+ export class RunView {
17
+ app;
18
+ target;
19
+ runId;
20
+ element;
21
+ ended = false;
22
+ following = false;
23
+ /** The run's last seq this view showed (the resume key). */
24
+ lastSeq;
25
+ controller;
26
+ stateLine;
27
+ steps;
28
+ stepNodes = new Map();
29
+ stepTitles = new Map();
30
+ /** The run's own `done` was seen (or attach said it had finished): nothing more will come. */
31
+ runFinished = false;
32
+ findings;
33
+ findingsCard;
34
+ log;
35
+ outcome;
36
+ actions;
37
+ diagnostics;
38
+ dropped = 0;
39
+ cancels = 0;
40
+ exitCode;
41
+ failed;
42
+ lastError;
43
+ constructor(app, target, title, runId) {
44
+ this.app = app;
45
+ this.target = target;
46
+ this.runId = runId;
47
+ this.stateLine = el('p', { class: 'run-state', role: 'status', aria: { live: 'polite' } });
48
+ this.steps = el('ol', { class: 'steps', aria: { label: 'Steps' } });
49
+ this.findings = el('ul', { class: 'findings', aria: { label: 'Findings' } });
50
+ this.log = el('ol', { class: 'log', aria: { label: 'Log' } });
51
+ this.outcome = el('div', { class: 'run-outcome' });
52
+ this.actions = el('div', { class: 'page-actions' });
53
+ this.diagnostics = el('pre', { class: 'diagnostics', hidden: true });
54
+ this.findingsCard = el('div', { class: 'card', hidden: true }, el('div', { class: 'card-head' }, el('h3', {}, 'Findings')), el('div', { class: 'card-body flush' }, this.findings));
55
+ this.element = el('section', { aria: { labelledby: 'run-title' } }, el('header', { class: 'page-head' }, el('div', { class: 'page-title' }, el('h2', { id: 'run-title', class: 'mono-title' }, title), el('p', { class: 'page-sub' }, `${target.name} · ${target.ssh} · ${target.dir}`)), this.actions), this.stateLine, this.outcome, el('div', { class: 'run-grid' }, el('div', { class: 'card' }, el('div', { class: 'card-head' }, el('h3', {}, 'Steps')), el('div', { class: 'card-body' }, this.steps)), el('div', { class: 'console' }, el('div', { class: 'console-head' }, el('h3', {}, icon('terminal'), 'Log'), el('span', { class: 'console-meta' }, target.name)), this.log)), this.findingsCard, this.diagnostics);
56
+ this.renderActions();
57
+ }
58
+ /** Where to resume: the seq after the last one this tab saw for this run, kept in sessionStorage (not a secret). */
59
+ resumeSeq() {
60
+ if (!this.runId)
61
+ return 0;
62
+ try {
63
+ const stored = this.app.storage?.getItem(SEQ_KEY(this.runId));
64
+ const seq = stored === null || stored === undefined ? NaN : Number(stored);
65
+ return Number.isSafeInteger(seq) && seq >= 0 ? seq + 1 : 0;
66
+ }
67
+ catch {
68
+ return 0;
69
+ }
70
+ }
71
+ stop() {
72
+ this.controller?.abort();
73
+ this.following = false;
74
+ }
75
+ async attach(fromSeq) {
76
+ if (!this.runId)
77
+ return;
78
+ if (fromSeq > 0)
79
+ this.note(`(resuming from event ${fromSeq}: earlier events were shown before; "Show from the start" replays them)`);
80
+ await this.consume('attach', { target: this.target.name, runId: this.runId, fromSeq });
81
+ }
82
+ async streamAttended(route, body) {
83
+ await this.consume(route, body);
84
+ }
85
+ async consume(route, body) {
86
+ this.controller = new AbortController();
87
+ this.following = true;
88
+ this.ended = false;
89
+ this.failed = undefined;
90
+ this.renderActions();
91
+ try {
92
+ await this.app.api.stream(route, body, (message) => this.handle(message), this.controller.signal);
93
+ }
94
+ catch (error) {
95
+ if (!this.controller.signal.aborted) {
96
+ this.failed = { code: 'local', reason: describe(error) };
97
+ replace(this.outcome, problem(undefined, error));
98
+ void this.app.noticeChange(error);
99
+ }
100
+ }
101
+ finally {
102
+ this.following = false;
103
+ if (!this.ended) {
104
+ this.settleSteps();
105
+ this.setState(this.controller.signal.aborted ? 'Stopped watching (the run goes on on the server).' : 'The stream ended.');
106
+ }
107
+ this.renderActions();
108
+ }
109
+ }
110
+ handle(message) {
111
+ switch (message.kind) {
112
+ case 'hello':
113
+ this.app.hello = message.hello;
114
+ this.app.renderBar();
115
+ return;
116
+ case 'diagnostic':
117
+ this.diagnostics.hidden = false;
118
+ append(this.diagnostics, `${message.text}\n`);
119
+ return;
120
+ case 'state':
121
+ return this.state(message);
122
+ case 'event':
123
+ return this.event(message.event, message.known);
124
+ }
125
+ }
126
+ state(message) {
127
+ if (message.state === 'connecting')
128
+ return this.setState(`Connecting to ${this.target.ssh}…`, 'live');
129
+ if (message.state === 'reconnecting') {
130
+ return this.setState(`Connection lost (${clean(message.reason)}); reconnecting in ${Math.round((message.retryInMs ?? 0) / 1000)} s from event ${this.lastSeq === undefined ? 0 : this.lastSeq + 1}…`, 'live');
131
+ }
132
+ this.ended = true;
133
+ if (message.exitCode !== undefined)
134
+ this.exitCode = message.exitCode;
135
+ if (this.runId && message.exitCode !== undefined && !message.code) {
136
+ this.runFinished = true;
137
+ if (message.reason)
138
+ this.note(`(${clean(message.reason)})`);
139
+ }
140
+ if (message.code) {
141
+ this.failed = { code: message.code, ...(message.reason ? { reason: message.reason } : {}), ...(message.hint ? { hint: message.hint } : {}) };
142
+ }
143
+ this.finish();
144
+ }
145
+ event(event, known) {
146
+ this.lastSeq = event.seq;
147
+ if (this.runId) {
148
+ try {
149
+ this.app.storage?.setItem(SEQ_KEY(this.runId), String(event.seq));
150
+ }
151
+ catch {
152
+ // No storage (private mode): resume from 0 instead.
153
+ }
154
+ }
155
+ if (!known)
156
+ return this.line('warn', `an event this UI does not know (${event.type}): ignored`);
157
+ switch (event.type) {
158
+ case 'hello':
159
+ return;
160
+ case 'step-start': {
161
+ const node = el('li', { class: 'step is-running' }, el('span', { class: 'step-icon', aria: { hidden: 'true' } }, '▸'), ' ', el('span', { class: 'step-title' }, event.title), el('span', { class: 'step-meta' }, quiet(' '), quiet('…'), el('span', { class: 'step-status', aria: { hidden: 'true' } }, 'running')));
162
+ this.stepNodes.set(event.id, node);
163
+ this.stepTitles.set(event.id, event.title);
164
+ this.steps.append(node);
165
+ this.setState(`Step: ${event.title}`, 'live');
166
+ return;
167
+ }
168
+ case 'step-end': {
169
+ const node = this.stepNodes.get(event.id) ?? el('li');
170
+ const mark = event.status === 'ok' ? '✓' : event.status === 'skipped' ? '–' : '✗';
171
+ // A step that started before the resume point has no node: its id names it.
172
+ const title = this.stepTitles.get(event.id) ?? event.id;
173
+ node.className = `step is-${event.status === 'ok' ? 'ok' : event.status === 'skipped' ? 'skipped' : 'failed'}`;
174
+ // The text reads "✓ build — ok, 1.5 s"; the layout draws the mark as an icon and the duration in a column.
175
+ replace(node, el('span', { class: 'step-icon', aria: { hidden: 'true' } }, mark), quiet(' '), el('span', { class: 'step-title' }, title), el('span', { class: 'step-meta' }, quiet(' — '), el('span', { class: 'step-status' }, event.status), quiet(', '), el('span', { class: 'step-dur' }, `${(event.durationMs / 1000).toFixed(1)} s`)));
176
+ if (!node.parentNode)
177
+ this.steps.append(node);
178
+ return;
179
+ }
180
+ case 'log':
181
+ return this.line(event.level, event.text, event.source, event.ts);
182
+ case 'finding':
183
+ this.findingsCard.hidden = false;
184
+ this.findings.append(findingItem(event));
185
+ return;
186
+ case 'prompt':
187
+ return this.line('warn', `the deploy asks: ${event.message} (answer it in the form and run again)`);
188
+ case 'result':
189
+ this.outcome.append(resultBanner(event.command, event.data));
190
+ return;
191
+ case 'error':
192
+ this.lastError = event;
193
+ this.outcome.append(errorBanner(event));
194
+ return;
195
+ case 'done':
196
+ this.exitCode = event.exitCode;
197
+ if (this.runId)
198
+ this.runFinished = true;
199
+ return;
200
+ case 'event':
201
+ // Only the server unwraps attach; a nested wrapper here is a log-worthy oddity.
202
+ return this.line('warn', 'an unexpected wrapped event was ignored');
203
+ }
204
+ }
205
+ line(level, textValue, source, ts) {
206
+ if (this.log.childElementCount >= MAX_LOG_LINES) {
207
+ this.log.firstElementChild?.remove();
208
+ this.dropped++;
209
+ this.setDropped();
210
+ }
211
+ const mark = level === 'error' ? '✗ ' : level === 'warn' ? '! ' : '';
212
+ const node = el('li', { class: level === 'error' || level === 'warn' || level === 'ok' ? level : '' }, mark, source ? el('span', { class: 'src' }, `[${source}] `) : null, textValue);
213
+ // The time column is drawn from an attribute: the line's text stays exactly what the deploy printed.
214
+ const time = /T(\d\d:\d\d:\d\d)/.exec(clean(ts))?.[1];
215
+ if (time)
216
+ node.dataset['ts'] = time;
217
+ this.log.append(node);
218
+ }
219
+ note(textValue) {
220
+ this.log.append(el('li', { class: 'src' }, textValue));
221
+ }
222
+ /** A step still running when this view stopped following: its end is not known here (it is not drawn as running). */
223
+ settleSteps() {
224
+ for (const node of this.stepNodes.values()) {
225
+ if (!node.classList.contains('is-running'))
226
+ continue;
227
+ node.classList.replace('is-running', 'is-aborted');
228
+ const status = node.querySelector('.step-status');
229
+ if (status)
230
+ replace(status, 'no end seen');
231
+ }
232
+ }
233
+ setDropped() {
234
+ this.stateLine.dataset['dropped'] = String(this.dropped);
235
+ }
236
+ setState(textValue, tone) {
237
+ this.stateLine.className = `run-state${tone ? ` is-${tone}` : ''}`;
238
+ replace(this.stateLine, textValue, this.dropped > 0 ? ` (${this.dropped} older log lines dropped from the page)` : '');
239
+ }
240
+ finish() {
241
+ // Status is refreshed once after any action (no polling loop).
242
+ void this.app.refreshStatus();
243
+ this.settleSteps();
244
+ if (this.failed && this.exitCode === undefined) {
245
+ const reconnectable = this.runId !== undefined;
246
+ this.setState(`Stopped: ${clean(this.failed.reason ?? this.failed.code)}`, 'err');
247
+ this.outcome.append(banner('err', this.failed.reason ?? 'the stream ended', [this.failed.hint ?? '', reconnectable ? 'The run may still be going on the server: re-attach to see.' : ''], [], this.failed.code));
248
+ }
249
+ else if (this.exitCode === 0) {
250
+ this.setState('Done.', 'ok');
251
+ this.outcome.append(banner('ok', 'Finished: exit 0'));
252
+ }
253
+ else {
254
+ this.setState(`Finished with exit ${this.exitCode ?? 'unknown'}`, 'err');
255
+ if (!this.lastError)
256
+ this.outcome.append(banner('err', `Finished with exit ${this.exitCode ?? 'unknown'}`));
257
+ }
258
+ this.renderActions();
259
+ }
260
+ renderActions() {
261
+ const buttons = [];
262
+ if (this.runId && !this.ended && this.following) {
263
+ buttons.push(button(this.cancels > 0 ? 'Cancel again (stop now)…' : 'Cancel…', () => { void this.cancel(this.cancels > 0); }, { class: 'danger' }));
264
+ buttons.push(button('Stop watching', () => this.stop()));
265
+ }
266
+ if (this.runId && !this.following) {
267
+ // A finished run has nothing more to attach to: only a replay makes sense.
268
+ if (!this.runFinished)
269
+ buttons.push(button('Re-attach', () => { void this.attach(this.lastSeq === undefined ? 0 : this.lastSeq + 1); }, { class: 'primary' }));
270
+ buttons.push(button('Show from the start', () => { this.app.watch(this.runId, `run ${this.runId}`, true); }, this.runFinished ? { class: 'primary' } : {}));
271
+ }
272
+ if (!this.following)
273
+ buttons.push(button('Refresh status', () => { void this.app.refreshStatus().then(() => this.app.show('status')); }));
274
+ replace(this.actions, ...buttons);
275
+ }
276
+ /** Two separate confirmations: the second one ends the deploy at once. */
277
+ async cancel(second) {
278
+ if (!this.runId)
279
+ return;
280
+ const ok = await confirmDialog(second
281
+ ? {
282
+ title: 'Stop the deploy NOW?',
283
+ lines: [
284
+ 'This ends the deploy at once, mid-step.',
285
+ el('strong', {}, 'A migration may be left half-applied'),
286
+ 'The restore command for the pre-deploy dump is in the log. The lock is left stale.',
287
+ ],
288
+ confirmLabel: 'Stop it now',
289
+ danger: true,
290
+ }
291
+ : {
292
+ title: `Cancel the run on ${this.target.name}?`,
293
+ lines: [
294
+ 'It stops at the next step boundary before the migration; from the migration on, the deploy finishes first.',
295
+ 'A second cancel would stop it at once. If this run was already cancelled once (from a terminal or another session), nothing is sent now: you are asked again first.',
296
+ ],
297
+ confirmLabel: 'Cancel the run',
298
+ danger: true,
299
+ });
300
+ if (!ok)
301
+ return;
302
+ let reply;
303
+ try {
304
+ reply = await this.app.api.post('cancel', { target: this.target.name, runId: this.runId, confirm: true, ...(second ? { second: true } : {}) });
305
+ }
306
+ catch (error) {
307
+ if (error instanceof ApiError && error.body['second'] === true && !second)
308
+ return this.cancel(true);
309
+ this.outcome.append(problem(undefined, error));
310
+ return;
311
+ }
312
+ if (reply.ok) {
313
+ this.cancels++;
314
+ const result = reply.result;
315
+ this.note(result?.second ? 'cancel sent a second time: the deploy stops at once' : 'cancel sent: the deploy stops at its next safe point');
316
+ this.renderActions();
317
+ return;
318
+ }
319
+ this.outcome.append(problem(reply));
320
+ }
321
+ }
322
+ function resultBanner(command, data) {
323
+ const d = (data ?? {});
324
+ if (command === 'run') {
325
+ return banner(d['status'] === 'ok' ? 'ok' : 'err', `Release ${clean(d['sha']).slice(0, 12)}: ${clean(d['status'])}`, [
326
+ d['url'] ? `${clean(d['url'])}` : '',
327
+ Array.isArray(d['migrations']) && d['migrations'].length > 0 ? `migrations: ${d['migrations'].map(clean).join(', ')}` : '',
328
+ d['note'] ? clean(d['note']) : '',
329
+ ]);
330
+ }
331
+ if (command === 'rollback')
332
+ return banner(d['status'] === 'ok' ? 'ok' : 'err', `Rolled back to ${clean(d['to']).slice(0, 12)}: ${clean(d['status'])}`, [`${clean(d['held']).slice(0, 12)} is held`]);
333
+ if (command === 'env') {
334
+ const changes = Array.isArray(d['changes']) ? d['changes'] : [];
335
+ return banner('ok', `.env written (${changes.length} change${changes.length === 1 ? '' : 's'})`, changes.map((c) => `${clean(c['kind'])} ${clean(c['key'])}: ${clean(c['reason'])}`));
336
+ }
337
+ return banner('ok', `${clean(command)} result`);
338
+ }
@@ -0,0 +1,60 @@
1
+ import { button, card, el, emptyState, kv, pageHead, pill, quiet, when } from './dom.js';
2
+ import { icon } from './icons.js';
3
+ import { banner, diagnosticsBlock, problem } from './reply.js';
4
+ import { short } from './sanitize.js';
5
+ /** Status: from `StatusResult` — release, process, lock, active and last run, hold. Refresh is manual (and once after an action). */
6
+ export function renderStatus(app) {
7
+ const reply = app.statusReply;
8
+ const status = app.status;
9
+ return el('section', { aria: { labelledby: 'status-title' } }, pageHead('status-title', 'Status', 'What runs on the server now: the release, the process, the lock and the last runs.', el('button', { type: 'button', disabled: app.statusBusy, on: { click: () => { void app.refreshStatus(); } } }, icon('refresh'), app.statusBusy ? 'Refreshing…' : 'Refresh')), !reply && !app.statusBusy ? emptyState('status', 'Not loaded yet.', 'Refresh to ask the server for its state.') : null, !reply && app.statusBusy ? emptyState('refresh', 'Asking the server…', 'Over your ssh; this can take a few seconds.') : null, reply && !status ? problem(reply) : null, ...(status ? statusPanels(app, status) : []), status && reply?.error ? problem(reply) : null, reply && reply.diagnostics.length > 0 && status ? diagnosticsBlock(reply.diagnostics) : null);
10
+ }
11
+ function statusPanels(app, s) {
12
+ const current = s.releases.find((r) => r.status === 'ok');
13
+ const panels = [];
14
+ if (s.hold) {
15
+ panels.push(banner('warn', `Commit ${short(s.hold.sha)} is held since ${when(s.hold.at)} by ${s.hold.actor}`, [
16
+ s.hold.note,
17
+ 'A run refuses it until the branch moves on; "Deploy anyway" in Plan & deploy overrides that once.',
18
+ ]));
19
+ }
20
+ if (s.activeRun) {
21
+ const run = s.activeRun;
22
+ panels.push(card('Active run', [
23
+ el('p', { class: 'lead' }, run.alive ? pill('run', 'alive') : pill('warn', 'not seen alive'), el('span', { class: 'mono' }, run.runId)),
24
+ kv([['Command', run.command], ['Actor', run.actor], ['Started', el('span', { class: 'num' }, when(run.startedAt))]]),
25
+ ], { class: 'accent', actions: [button('Attach', () => { app.watch(run.runId, `${run.command} ${run.runId}`); }, { class: 'primary' })] }));
26
+ }
27
+ const releaseCard = card('Current release', current
28
+ ? [
29
+ el('p', { class: 'lead' }, pill('ok', 'healthy'), el('code', {}, short(current.sha))),
30
+ kv([
31
+ ['Deployed', el('span', { class: 'num' }, when(current.at))],
32
+ ['By', `${current.actor ?? current.user}${current.via ? ` via ${current.via}` : ''}`],
33
+ current.migrations.length > 0 ? ['Migrations', el('span', { class: 'mono' }, current.migrations.join(', '))] : null,
34
+ ]),
35
+ ]
36
+ : [el('p', { class: 'muted' }, 'No healthy release recorded yet.')]);
37
+ const processCard = card('Process', s.process.kind === 'pm2'
38
+ ? [
39
+ el('p', { class: 'lead' }, el('span', { class: 'mono' }, `pm2 ${s.process.name}`), quiet(': '), s.process.running ? pill('ok', 'running') : pill('err', 'not running'), s.process.status ? el('span', { class: 'muted' }, ` (${s.process.status})`) : ''),
40
+ kv([['Manager', 'pm2'], ['Name', el('span', { class: 'mono' }, s.process.name)], s.process.pid !== undefined ? ['PID', el('span', { class: 'num mono' }, String(s.process.pid))] : null]),
41
+ ]
42
+ : [el('pre', { class: 'diagnostics' }, s.process.lines.join('\n'))]);
43
+ const lock = s.lock;
44
+ const lockCard = card('Lock', !lock
45
+ ? [el('p', { class: 'lead' }, pill('ok', 'free'), el('span', { class: 'muted' }, 'Free. No deploy holds it.'))]
46
+ : [
47
+ el('p', { class: 'lead' }, lock.corrupt ? pill('err', 'corrupt') : lock.stale ? pill('warn', 'stale') : pill('run', 'held'), lock.corrupt ? el('strong', { class: 'status-err' }, 'Corrupt lock file. ') : null),
48
+ lock.holder ? el('p', {}, `Held by pid ${lock.holder.pid} on ${lock.holder.host} — ${lock.holder.actor}, ${lock.holder.command}, since ${when(lock.holder.startedAt)}`) : null,
49
+ lock.stale ? el('p', { class: 'status-warn' }, el('strong', {}, ' (stale: that process is gone)')) : null,
50
+ ]);
51
+ const lastRunCard = s.lastRun ? lastRun(app, s.lastRun) : card('Last run', [el('p', { class: 'muted' }, 'No run recorded yet.')]);
52
+ panels.push(el('div', { class: 'grid-2' }, releaseCard, processCard, lockCard, lastRunCard));
53
+ return panels;
54
+ }
55
+ function lastRun(app, run) {
56
+ return card('Last run', [
57
+ el('p', { class: 'lead' }, run.complete ? pill(run.exitCode === 0 ? 'ok' : 'err', `exit ${run.exitCode}`) : pill('warn', 'did not end with done'), el('span', { class: 'mono' }, run.runId)),
58
+ kv([['Command', run.command || 'unknown command'], run.endedAt ? ['Ended', el('span', { class: 'num' }, when(run.endedAt))] : null]),
59
+ ], { actions: [button('Show its log', () => { app.watch(run.runId, `${run.command} ${run.runId}`, true); }, { class: 'sm' })] });
60
+ }