The front-end is plain JavaScript served as is: no build step to run before the bot starts, and no second toolchain to keep alive. A simple/advanced switch hides the technical panels without ever standing in for a permission. `npm run setup` starts the wizard alone, because the bot refuses to boot without a token and the `.env` has to be writable from somewhere. When the webhook and the dashboard share a port, a single HTTP server is started. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
395 lines
12 KiB
JavaScript
395 lines
12 KiB
JavaScript
import { api } from '../core/api.js';
|
||
import { h, mount, richText } from '../core/dom.js';
|
||
import { button, card, field, input, notice, select, spinner, toast, toggle } from '../core/ui.js';
|
||
|
||
/**
|
||
* Step by step `.env` wizard (M16-T09).
|
||
*
|
||
* Walks through one section at a time: what the section is for, how to obtain
|
||
* each value, then the fields themselves with live validation. Nothing is
|
||
* written until « Enregistrer » is pressed, and the previous file is backed up.
|
||
*/
|
||
|
||
const stateOf = (data) => ({
|
||
data,
|
||
/** Only the fields the user actually touched. */
|
||
edits: {},
|
||
step: 0,
|
||
showAdvanced: false,
|
||
errors: { ...data.errors },
|
||
warnings: [...data.warnings],
|
||
missing: [...data.missingRequired],
|
||
diff: [],
|
||
lastSave: null,
|
||
});
|
||
|
||
const valueOf = (view, key) => view.edits[key] ?? view.data.values[key] ?? '';
|
||
|
||
/** Step texts reference other fields, so they always show the values being typed. */
|
||
const fillPlaceholders = (view, text) =>
|
||
text
|
||
.replaceAll('{WEB_PUBLIC_URL}', valueOf(view, 'WEB_PUBLIC_URL') || 'https://ton-domaine')
|
||
.replaceAll('{WEBHOOK_PATH}', valueOf(view, 'WEBHOOK_PATH') || '/webhooks/gitea');
|
||
|
||
/** A section is complete when none of its variables is in error or missing. */
|
||
function sectionStatus(view, sectionId) {
|
||
const variables = view.data.variables.filter((variable) => variable.section === sectionId);
|
||
const invalid = variables.some((variable) => view.errors[variable.key]);
|
||
const missing = variables.some((variable) => view.missing.includes(variable.key));
|
||
const filled = variables.some((variable) => {
|
||
const value = valueOf(view, variable.key);
|
||
return value !== '' || view.data.secrets[variable.key];
|
||
});
|
||
return { invalid, missing, filled };
|
||
}
|
||
|
||
export async function render(host, { standalone = false } = {}) {
|
||
mount(host, spinner('Lecture de la configuration…'));
|
||
|
||
const data = await api.get('/api/configuration');
|
||
const view = stateOf(data);
|
||
const container = standalone
|
||
? h('div', { class: 'main', style: { maxWidth: '1100px', margin: '0 auto' } })
|
||
: h('div', {});
|
||
mount(host, container);
|
||
|
||
let validateTimer = null;
|
||
const scheduleValidation = () => {
|
||
clearTimeout(validateTimer);
|
||
validateTimer = setTimeout(async () => {
|
||
const result = await api.post('/api/configuration/validate', { values: view.edits }).catch(() => null);
|
||
if (!result) return;
|
||
view.errors = result.errors;
|
||
view.warnings = result.warnings;
|
||
view.missing = result.missingRequired;
|
||
view.diff = result.diff;
|
||
draw();
|
||
}, 350);
|
||
};
|
||
|
||
const setValue = (key, value) => {
|
||
view.edits[key] = value;
|
||
scheduleValidation();
|
||
};
|
||
|
||
function controlFor(variable) {
|
||
const key = variable.key;
|
||
const current = valueOf(view, key);
|
||
|
||
if (variable.type === 'bool') {
|
||
return toggle(current === 'true', (checked) => {
|
||
setValue(key, checked ? 'true' : 'false');
|
||
draw();
|
||
});
|
||
}
|
||
|
||
if (variable.type === 'enum') {
|
||
return select(
|
||
variable.options.map((option) => ({ value: option, label: option })),
|
||
{ value: current, onChange: (event) => setValue(key, event.target.value) },
|
||
);
|
||
}
|
||
|
||
const control = input({
|
||
type: variable.type === 'secret' ? 'password' : 'text',
|
||
value: current,
|
||
placeholder: variable.placeholder ?? variable.default ?? '',
|
||
autocomplete: 'off',
|
||
spellcheck: 'false',
|
||
onInput: (event) => setValue(key, event.target.value),
|
||
});
|
||
|
||
if (variable.type !== 'secret' && !variable.generator && !variable.testable) return control;
|
||
|
||
const extras = [control];
|
||
if (variable.generator) {
|
||
extras.push(
|
||
button(
|
||
'Générer',
|
||
async () => {
|
||
const { value } = await api.post('/api/configuration/generate', { kind: variable.generator });
|
||
control.value = value;
|
||
setValue(key, value);
|
||
toast('Secret généré. Il ne sera visible qu’ici.', 'info');
|
||
},
|
||
{ tone: 'ghost' },
|
||
),
|
||
);
|
||
}
|
||
if (variable.testable) {
|
||
extras.push(
|
||
button(
|
||
'Tester',
|
||
async () => {
|
||
const result = await api.post(`/api/configuration/test/${variable.testable}`, {
|
||
values: view.edits,
|
||
});
|
||
toast(result.detail, result.ok ? (result.warning ? 'info' : 'success') : 'error');
|
||
},
|
||
{ tone: 'ghost' },
|
||
),
|
||
);
|
||
}
|
||
return h('div', { class: 'secret-row' }, ...extras);
|
||
}
|
||
|
||
function fieldFor(variable) {
|
||
const key = variable.key;
|
||
const isSecretSet = variable.type === 'secret' && view.data.secrets[key] && !(key in view.edits);
|
||
const help = [
|
||
variable.help,
|
||
isSecretSet ? 'Une valeur est déjà enregistrée : laisse vide pour la conserver.' : null,
|
||
variable.restartRequired ? 'Prise en compte au prochain démarrage du bot.' : null,
|
||
]
|
||
.filter(Boolean)
|
||
.join(' ');
|
||
|
||
const wrapper = field(`${variable.label}${variable.required ? ' *' : ''}`, controlFor(variable), {
|
||
help,
|
||
error: view.errors[key],
|
||
});
|
||
wrapper.append(
|
||
h('span', { class: 'field-help', text: key, style: { fontFamily: 'var(--mono)', opacity: '0.6' } }),
|
||
);
|
||
return variable.advanced ? h('div', { class: 'advanced-wrapper' }, wrapper) : wrapper;
|
||
}
|
||
|
||
async function showPreview() {
|
||
const { content } = await api.post('/api/configuration/preview', { values: view.edits });
|
||
mount(
|
||
previewHost,
|
||
card(
|
||
'Aperçu du fichier .env',
|
||
{ subtitle: 'Les secrets sont masqués dans cet aperçu.' },
|
||
h('pre', {}, h('code', { text: content })),
|
||
),
|
||
);
|
||
}
|
||
|
||
async function save({ force = false } = {}) {
|
||
try {
|
||
const result = await api.post('/api/configuration/save', { values: view.edits, force });
|
||
view.lastSave = result;
|
||
view.edits = {};
|
||
view.data = await api.get('/api/configuration');
|
||
view.errors = view.data.errors;
|
||
view.warnings = view.data.warnings;
|
||
view.missing = view.data.missingRequired;
|
||
view.diff = [];
|
||
toast(result.written ? 'Configuration enregistrée.' : 'Aucun changement à enregistrer.', 'success');
|
||
draw();
|
||
} catch (error) {
|
||
toast(error.message, 'error');
|
||
if (error.details) {
|
||
view.errors = error.details;
|
||
draw();
|
||
}
|
||
}
|
||
}
|
||
|
||
const previewHost = h('div', {});
|
||
|
||
function stepList() {
|
||
return h(
|
||
'div',
|
||
{ class: 'wizard-steps' },
|
||
view.data.sections.map((section, index) => {
|
||
const status = sectionStatus(view, section.id);
|
||
const classes = ['wizard-step'];
|
||
if (index === view.step) classes.push('active');
|
||
if (status.invalid || status.missing) classes.push('invalid');
|
||
else if (status.filled) classes.push('done');
|
||
|
||
return h(
|
||
'button',
|
||
{
|
||
class: classes.join(' '),
|
||
type: 'button',
|
||
onClick: () => {
|
||
view.step = index;
|
||
draw();
|
||
},
|
||
},
|
||
h('span', { class: 'dot', text: status.invalid || status.missing ? '!' : String(index + 1) }),
|
||
h(
|
||
'span',
|
||
{},
|
||
h('strong', { text: section.title }),
|
||
h('span', { class: 'muted', text: section.summary }),
|
||
),
|
||
);
|
||
}),
|
||
);
|
||
}
|
||
|
||
function stepBody() {
|
||
const section = view.data.sections[view.step];
|
||
const variables = view.data.variables.filter(
|
||
(variable) => variable.section === section.id && (view.showAdvanced || !variable.advanced),
|
||
);
|
||
const hiddenCount = view.data.variables.filter(
|
||
(variable) => variable.section === section.id && variable.advanced,
|
||
).length;
|
||
|
||
return card(
|
||
section.title,
|
||
{
|
||
subtitle: section.summary,
|
||
actions: [
|
||
button(
|
||
view.step === 0 ? '' : '← Précédent',
|
||
() => {
|
||
view.step = Math.max(0, view.step - 1);
|
||
draw();
|
||
},
|
||
{ tone: 'ghost', disabled: view.step === 0 },
|
||
),
|
||
button(
|
||
'Suivant →',
|
||
() => {
|
||
view.step = Math.min(view.data.sections.length - 1, view.step + 1);
|
||
draw();
|
||
},
|
||
{ tone: 'ghost', disabled: view.step === view.data.sections.length - 1 },
|
||
),
|
||
],
|
||
},
|
||
section.intro && h('p', { text: section.intro }),
|
||
|
||
section.steps?.length > 0 &&
|
||
h(
|
||
'ol',
|
||
{ class: 'steps-list' },
|
||
section.steps.map((step) => h('li', {}, richText(fillPlaceholders(view, step), 'rich-inline'))),
|
||
),
|
||
|
||
section.links?.length > 0 &&
|
||
h(
|
||
'div',
|
||
{ class: 'row' },
|
||
section.links.map((link) =>
|
||
h('a', {
|
||
class: 'btn btn-ghost',
|
||
href: link.url,
|
||
target: '_blank',
|
||
rel: 'noreferrer',
|
||
text: `↗ ${link.label}`,
|
||
}),
|
||
),
|
||
),
|
||
|
||
hiddenCount > 0 &&
|
||
toggle(
|
||
view.showAdvanced,
|
||
(checked) => {
|
||
view.showAdvanced = checked;
|
||
draw();
|
||
},
|
||
`Afficher les ${hiddenCount} options avancées`,
|
||
),
|
||
|
||
...variables.map(fieldFor),
|
||
);
|
||
}
|
||
|
||
function summary() {
|
||
const blocking = view.missing.length > 0 || Object.keys(view.errors).length > 0;
|
||
|
||
return card(
|
||
'Enregistrement',
|
||
{
|
||
subtitle: view.data.exists
|
||
? 'Le fichier .env actuel sera sauvegardé avant d’être remplacé.'
|
||
: 'Aucun .env pour l’instant : il sera créé avec les permissions 600.',
|
||
actions: [
|
||
button('Aperçu', showPreview, { tone: 'ghost' }),
|
||
button('Enregistrer le .env', () => save(), { tone: 'primary', disabled: blocking }),
|
||
],
|
||
},
|
||
|
||
view.missing.length > 0 &&
|
||
notice(`Valeurs obligatoires manquantes : ${view.missing.join(', ')}.`, 'error'),
|
||
|
||
Object.keys(view.errors).length > 0 &&
|
||
notice(
|
||
`${Object.keys(view.errors).length} champ(s) invalide(s) : ${Object.keys(view.errors).join(', ')}.`,
|
||
'error',
|
||
),
|
||
|
||
...view.warnings.map((warning) => notice(warning, 'warning')),
|
||
|
||
view.diff.length > 0 &&
|
||
h(
|
||
'div',
|
||
{ class: 'stack' },
|
||
h('h3', { text: `${view.diff.length} changement(s) en attente` }),
|
||
h(
|
||
'div',
|
||
{ class: 'diff stack' },
|
||
view.diff.map((entry) =>
|
||
h(
|
||
'div',
|
||
{},
|
||
h('strong', { text: `${entry.key} ` }),
|
||
h('del', { text: entry.before || '(vide)' }),
|
||
' → ',
|
||
h('ins', { text: entry.after || '(vide)' }),
|
||
entry.restartRequired && h('span', { class: 'muted', text: ' · redémarrage requis' }),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
|
||
view.lastSave?.written &&
|
||
notice(
|
||
`Fichier écrit.${view.lastSave.backup ? ` Sauvegarde : ${view.lastSave.backup}.` : ''}${
|
||
view.lastSave.restartRequired ? ' Redémarre le bot pour appliquer les changements.' : ''
|
||
}`,
|
||
'success',
|
||
),
|
||
|
||
view.data.unknownKeys.length > 0 &&
|
||
notice(
|
||
`Variables inconnues conservées telles quelles : ${view.data.unknownKeys.join(', ')}.`,
|
||
'info',
|
||
),
|
||
);
|
||
}
|
||
|
||
function draw() {
|
||
mount(
|
||
container,
|
||
h(
|
||
'div',
|
||
{ class: 'stack' },
|
||
h(
|
||
'div',
|
||
{ class: 'page-head' },
|
||
h(
|
||
'div',
|
||
{},
|
||
h('h1', { text: 'Configuration du bot' }),
|
||
h('p', {
|
||
class: 'muted',
|
||
text: 'Chaque valeur est expliquée, vérifiée puis écrite dans le fichier .env. Rien n’est enregistré avant ta validation.',
|
||
}),
|
||
),
|
||
),
|
||
standalone &&
|
||
notice(
|
||
'Session d’amorçage : seule cette page est accessible. Une fois le .env enregistré, redémarre le bot et connecte-toi avec Discord.',
|
||
'info',
|
||
),
|
||
h(
|
||
'div',
|
||
{ class: 'wizard' },
|
||
stepList(),
|
||
h('div', { class: 'stack' }, stepBody(), summary(), previewHost),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
draw();
|
||
}
|