rob-revisited/ide/ui/js/dotenv.js

606 lines
39 KiB
JavaScript

// The .env editor (editor.js renderView hands .env files here): Code (Monaco, the dotenv language), Split, Table (the
// file's variables: name, value, effective value, comment, file; add / rename / delete, move to another file, copy to
// the environments, value editors by kind: DSN builder, booleans, numbers, multi-line), Variables (the folder's files
// merged in the application's load order, per environment) and Vault (Symfony's secrets: secrets:list / set / remove /
// generate-keys through the Console window's runner). The PHP side: ide/src/Dotenv (dotenv.* commands).
//
// Secrets: values whose name says so (PASSWORD, SECRET, TOKEN, KEY...) or DSNs with a password are masked until their
// eye is clicked; a secret in a file git tracks is a warning (marker + banner) with "move to .env.local". No value is
// ever put in a notification, a log or a command line (the vault's values go on the console's stdin).
import { backend } from './backend.js';
import { el, clear, icon, notify, debounce, prefs, menu, confirm, prompt, dialog, t, basename, dirname } from './ui.js';
import { isSecret, maskValue, valueKind, toggleBool, isTrue, parseDsn, buildDsn, dsnPreset, diffRange, targetFiles } from './dotenv-model.js';
export { isDotenvPath } from './dotenv-model.js';
export { registerDotenv } from './dotenv-lang.js';
let cssLoaded = false;
const put = (node, ...children) => node.append(...children.flat().filter((c) => c !== null && c !== undefined && c !== false));
function loadCss() {
if (cssLoaded) return;
cssLoaded = true;
document.head.append(el('link', { rel: 'stylesheet', href: 'css/dotenv.css' }));
}
// one parse per model, kept up to date: the markers (problems, secrets in a committed file) whatever the view
const watchers = new WeakMap();
function watch(file, path) {
let w = watchers.get(file.model);
if (w) return w;
w = { parsed: null, listeners: new Set(), tracked: false, path };
const run = async () => {
if (file.model.isDisposed()) return;
const parsed = await backend.invoke('dotenv.parse', { text: file.model.getValue() }).catch(() => null);
if (!parsed || file.model.isDisposed()) return;
w.parsed = parsed;
w.mark();
for (const fn of w.listeners) fn(parsed);
};
w.mark = () => {
const monaco = window.monaco;
if (!monaco || !w.parsed || file.model.isDisposed()) return;
const S = monaco.MarkerSeverity;
const markers = w.parsed.problems.map((p) => ({ startLineNumber: p.line, startColumn: p.column, endLineNumber: p.endLine, endColumn: Math.max(p.endColumn, p.column + 1),
severity: p.severity === 'error' ? S.Error : S.Warning, message: p.message, source: '.env' }));
if (w.tracked) {
for (const e of w.parsed.entries) {
if (e.secret && !e.placeholder) {
markers.push({ startLineNumber: e.line, startColumn: 1, endLineNumber: e.line, endColumn: e.key.length + 1, severity: S.Warning, source: '.env',
message: t('A secret in a file git tracks: everyone who clones the project can read it. Move it to .env.local (Table view).') });
}
}
}
monaco.editor.setModelMarkers(file.model, 'dotenv', markers);
};
w.run = run;
// the file tracked by git: its secrets are warnings (markers) in every view
backend.invoke('dotenv.git', { paths: [path] }).then((r) => { w.tracked = r.tracked.includes(path); w.mark(); }, () => {});
const sub = file.model.onDidChangeContent(debounce(run, 250));
file.model.onWillDispose(() => sub.dispose());
watchers.set(file.model, w);
run();
return w;
}
/** the model's text replaced by another with the smallest edit (undo works, the cursor stays where it was) */
function applyText(model, text) {
const d = diffRange(model.getValue(), text);
if (!d) return;
const s = model.getPositionAt(d.start);
const e = model.getPositionAt(d.end);
model.pushEditOperations([], [{ range: new window.monaco.Range(s.lineNumber, s.column, e.lineNumber, e.column), text: d.text }], () => null);
}
/** Shows a .env file in its group (editor.js renderView). */
export function renderDotenv(area, group, tab, file) {
loadCss();
const w = watch(file, tab.path);
const folder = dirname(tab.path);
const vault = area.app.project?.capabilities?.console === 'bin/console' && !tab.path.startsWith('ssh://');
const modes = ['code', 'split', 'table', 'variables', ...(vault ? ['vault'] : [])];
const mode = modes.includes(tab.mode) ? tab.mode : (modes.includes(prefs.get('envMode', 'table')) ? prefs.get('envMode', 'table') : 'table');
group.host.append(el('div.mode-switch', {}, modes.map((m) => el(`button${m === mode ? '.on' : ''}`, {
onclick: () => { tab.mode = m; prefs.set('envMode', m); area.renderView(group, tab); area.renderTabs(group); },
}, { code: t('Code'), split: t('Split'), table: t('Table'), variables: t('Variables'), vault: t('Vault') }[m]))));
group.textView.style.right = '';
group.textView.style.width = '';
if (mode === 'code') {
group.textView.style.display = '';
return area.showModel(group, tab, file);
}
const view = el('div.view.dotenv-view');
if (mode === 'split') {
group.textView.style.display = '';
group.textView.style.right = '50%';
group.textView.style.width = '50%';
Object.assign(view.style, { left: '50%', borderLeft: '1px solid var(--border-2)' });
area.showModel(group, tab, file);
} else {
group.textView.style.display = 'none';
}
group.host.append(view);
const ui = new DotenvView({ area, group, tab, file, view, mode, folder, watcher: w });
group.designer = { destroy: () => { ui.destroy(); group.textView.style.right = ''; group.textView.style.width = ''; } };
}
class DotenvView {
constructor(o) {
Object.assign(this, o);
this.model = this.file.model;
this.name = basename(this.tab.path);
this.env = prefs.get('envEnv', 'dev');
this.filter = '';
this.revealed = new Set();
this.dsnOpen = null;
this.info = null;
this.merged = null;
this.git = { repository: false, tracked: [], ignored: [] };
this.onParsed = () => { this.refreshMerge(); this.render(); };
this.watcher.listeners.add(this.onParsed);
this.refreshMerge = debounce(() => this.loadMerge().then(() => this.render()), 400);
put(this.view, el('div.dotenv-empty', {}, t('Reading the .env files…')));
this.view.addEventListener('dotenv-idle', () => { if (this.pending) this.render(); });
this.load();
}
destroy() {
this.watcher.listeners.delete(this.onParsed);
this.dead = true;
}
path(name) { return (this.folder ? this.folder + '/' : '') + name; }
async load() {
try {
const files = [...(this.area.app.tree?.files || [])];
if (!files.includes(this.tab.path)) files.push(this.tab.path);
this.info = await backend.invoke('dotenv.files', { folder: this.folder, files });
if (!this.info.files.some((f) => f.path === this.tab.path)) this.info.files.push({ path: this.tab.path, name: this.name, role: 'other', env: null });
if (!this.info.envs.includes(this.env)) this.env = this.info.envs[0];
this.compose = [];
for (const c of this.info.compose) {
const text = await this.area.readProjectText(c);
if (text) for (const f of (await backend.invoke('dotenv.compose', { text })).files) this.compose.push({ ...f, path: this.path(f.path), from: c });
}
await this.loadMerge();
await this.loadGit();
if (this.mode === 'vault') await this.loadVault();
} catch (e) {
clear(this.view).append(el('div.dotenv-empty', {}, e.message));
return;
}
this.render();
}
async loadMerge() {
const texts = {};
for (const f of this.info.files) {
if (f.role === 'example' || f.role === 'other') continue;
const text = f.path === this.tab.path ? this.model.getValue() : await this.area.readProjectText(f.path);
if (text !== null && text !== undefined) texts[f.name] = text;
}
this.merged = (await backend.invoke('dotenv.merge', { texts, kind: this.info.kind, envs: this.info.envs })).envs;
}
async loadGit() {
const paths = [...new Set([...this.info.files.map((f) => f.path), this.path('.env.local')])];
this.git = await backend.invoke('dotenv.git', { paths }).catch(() => ({ repository: false, tracked: [], ignored: [] }));
this.watcher.tracked = this.git.tracked.includes(this.tab.path);
this.watcher.mark();
}
async loadVault() {
this.vault = await backend.invoke('dotenv.vault', { folder: this.folder }).catch((e) => ({ error: e.message, envs: [] }));
this.vaultEnv ||= prefs.get('envVaultEnv', 'dev');
}
get readOnly() { return !!this.file.readOnly; }
get entries() { return this.watcher.parsed?.entries || []; }
/** edits of the open file, rewritten by the PHP side (only the lines of the variables touched change) */
async apply(ops) {
try {
const { text } = await backend.invoke('dotenv.edit', { text: this.model.getValue(), ops });
applyText(this.model, text);
} catch (e) { notify(e.message, 'error', { title: this.name }); }
}
/** another file of the folder changed: its open model (saved), else the disk (created when missing) */
async writeOther(path, change) {
const open = this.area.files.get(path);
if (open?.model) {
applyText(open.model, await change(open.model.getValue()));
await this.area.save(path);
return;
}
const current = await backend.invoke('file.read', { path }).catch(() => null);
const text = await change(current?.text ? current.content : '');
if (current?.text) await backend.invoke('file.write', { path, content: text });
else {
await backend.invoke('file.create', { path, content: text });
this.area.app.tree?.refresh?.();
}
}
async moveTo(entries, target) {
const targetPath = this.path(target);
const blocks = [];
for (const e of entries) blocks.push((await backend.invoke('dotenv.block', { text: this.model.getValue(), key: e.key, line: e.line })).block || '');
await this.writeOther(targetPath, async (text) => {
for (const b of blocks) text = (await backend.invoke('dotenv.append', { text, block: b })).text;
return text;
});
// the later lines first: the line numbers of the others stay right
const ops = [...entries].sort((a, b) => b.line - a.line).map((e) => ({ op: 'delete', key: e.key, line: e.line, withComments: true }));
await this.apply(ops);
await this.area.save(this.tab.path);
if (/\.local$/.test(target)) await this.ensureIgnored(true);
notify(t('{n} variables moved to {file}.', { n: entries.length, file: target }), 'success', { title: '.env' });
this.info.files.some((f) => f.name === target) || await this.load();
}
async copyTo(entry, targets) {
for (const target of targets) {
await this.writeOther(this.path(target), async (text) => {
const parsed = await backend.invoke('dotenv.parse', { text });
if (parsed.entries.some((x) => x.key === entry.key)) return (await backend.invoke('dotenv.edit', { text, ops: [{ op: 'set', key: entry.key, value: entry.value }] })).text;
const block = (await backend.invoke('dotenv.block', { text: this.model.getValue(), key: entry.key, line: entry.line, withComments: false })).block || '';
return (await backend.invoke('dotenv.append', { text, block })).text;
});
}
notify(t('{name} copied to {files}.', { name: entry.key, files: targets.join(', ') }), 'success', { title: '.env' });
await this.load();
}
/** .env.local & co. ignored by git (the lines Symfony's recipe writes, added when missing) */
async ensureIgnored(quiet = false) {
if (!this.git.repository) return;
const r = await backend.invoke('dotenv.ignore', { folder: this.folder }).catch((e) => { notify(e.message, 'error'); return null; });
if (r?.added?.length) notify(t('Added to {file}: {lines}', { file: r.path, lines: r.added.join(' ') }), 'success', { title: '.gitignore' });
else if (r && !quiet) notify(t('{file} already ignores the local files.', { file: r.path }), 'info', { title: '.gitignore' });
await this.loadGit();
this.render();
}
reveal(line) {
if (this.tab.mode !== 'split') { this.tab.mode = 'split'; this.area.renderView(this.group, this.tab); }
const editor = this.group.editor;
editor.revealLineInCenter(line);
editor.setPosition({ lineNumber: line, column: 1 });
editor.focus();
}
render() {
if (this.dead || !this.info || !this.watcher.parsed) return;
// a field being typed in keeps its focus: the table is drawn again after it
const active = document.activeElement;
if (active && this.view.contains(active) && active.matches('input, textarea, select') && !this.forceRender) { this.pending = true; return; }
this.pending = false;
const top = this.view.scrollTop;
clear(this.view);
if (this.mode === 'variables') this.renderVariables();
else if (this.mode === 'vault') this.renderVault();
else this.renderTable();
this.view.scrollTop = top;
}
// the table of the file ---------------------------------------------------------------------------------
fileBar() {
const bar = el('div.dotenv-files');
for (const f of this.info.files) {
const tracked = this.git.tracked.includes(f.path);
bar.append(el(`button.dotenv-file${f.path === this.tab.path ? '.on' : ''}`, {
title: tracked ? t('Tracked by git') : this.git.ignored.includes(f.path) ? t('Ignored by git') : '',
onclick: () => f.path !== this.tab.path && this.area.open(f.path),
}, f.name, tracked ? el('span.dotenv-badge.git', {}, 'git') : this.git.ignored.includes(f.path) ? el('span.dotenv-badge.local', {}, t('local')) : null));
}
const missing = targetFiles(this.info.files, this.info.kind, this.info.envs, '').filter((f) => !f.exists && f.name !== '.env');
if (missing.length && !this.readOnly) {
bar.append(el('button.icon-btn', { title: t('New .env file…'), onclick: (e) => menu(missing.map((f) => ({ label: f.name, action: async () => {
await backend.invoke('file.create', { path: this.path(f.name), content: '' }).catch((err) => notify(err.message, 'error'));
this.area.app.tree?.refresh?.();
if (/\.local$/.test(f.name)) await this.ensureIgnored(true);
this.area.open(this.path(f.name));
} })), e.currentTarget) }, icon('plus')));
}
return bar;
}
envPicker(onChange) {
return el('div.dotenv-envs', {}, this.info.envs.map((env) => el(`button${env === this.env ? '.on' : ''}`, {
onclick: () => { this.env = env; prefs.set('envEnv', env); onChange?.(); this.forceRender = true; this.render(); this.forceRender = false; },
}, env)));
}
banners() {
const out = [];
const tracked = this.git.tracked.includes(this.tab.path);
const committed = tracked ? this.entries.filter((e) => e.secret && !e.placeholder) : [];
const local = this.path('.env.local');
if (committed.length && !/\.local$/.test(this.name)) {
out.push(el('div.dotenv-banner.danger', {}, icon('warning'),
el('span', {}, t('{n} secrets in {file}, which git tracks: everyone who clones the project can read them.', { n: committed.length, file: this.name }), ' ',
el('b', {}, committed.map((e) => e.key).join(', '))),
this.readOnly ? null : el('button.btn.primary', { onclick: () => this.moveTo(committed, '.env.local') }, t('Move them to .env.local'))));
}
if (this.git.repository && this.git.tracked.includes(local)) {
out.push(el('div.dotenv-banner.warning', {}, icon('warning'), el('span', {}, t('.env.local is tracked by git: its values are in the repository. Remove it from the index (git rm --cached .env.local) and commit.'))));
} else if (this.git.repository && !this.git.ignored.includes(local)) {
out.push(el('div.dotenv-banner', {}, icon('warning'), el('span', {}, t('.env.local is not ignored by git: a commit could take it.')),
el('button.btn', { onclick: () => this.ensureIgnored() }, t('Ignore the local files in git'))));
}
if (this.info.dumped) out.push(el('div.dotenv-banner', {}, icon('warning'), el('span', {}, t('A .env.local.php exists (composer dump-env): Symfony reads it instead of the .env files.'))));
const problems = this.watcher.parsed.problems;
if (problems.length) {
out.push(el('div.dotenv-banner.problems', {}, icon('problems'), el('div', {}, problems.slice(0, 6).map((p) => el('div.dotenv-problem', { onclick: () => this.reveal(p.line) },
el('span.dotenv-line', {}, t('line {n}', { n: p.line })), ' ', p.message)), problems.length > 6 ? el('div', {}, t('{n} more…', { n: problems.length - 6 })) : null)));
}
return out;
}
/** the variable that wins for this name in the chosen environment */
winner(key) { return this.merged?.[this.env]?.variables.find((v) => v.key === key) || null; }
loaded() { return this.merged?.[this.env]?.order.includes(this.name); }
renderTable() {
const head = el('div.dotenv-head', {}, this.fileBar(), el('div.dotenv-tools', {},
el('span.dotenv-label', {}, t('Effective value for')), this.envPicker(),
el('input.input.dotenv-search', { type: 'search', placeholder: t('Filter'), value: this.filter, oninput: (e) => { this.filter = e.target.value; this.drawRows(); } }),
this.readOnly ? null : el('button.btn.primary', { onclick: () => this.addVariable() }, icon('plus'), t('Variable'))));
this.rows = el('tbody');
const notLoaded = this.merged && this.info.kind !== 'plain' && !this.loaded() && ['base', 'dist', 'local', 'env', 'envLocal'].includes(this.info.files.find((f) => f.path === this.tab.path)?.role);
put(this.view, head, ...this.banners(),
notLoaded ? el('div.dotenv-banner', {}, t('{file} is not loaded for {env}.', { file: this.name, env: this.env })) : null,
el('table.dotenv-table.entries', { 'data-tour': 'dotenv-table' }, el('thead', {}, el('tr', {}, el('th', {}, t('Name')), el('th', {}, t('Value')), el('th', {}, t('Effective value ({env})', { env: this.env })),
el('th', {}, t('Comment')), el('th', {}))), this.rows));
this.drawRows();
}
drawRows() {
clear(this.rows);
const q = this.filter.toLowerCase();
const list = this.entries.filter((e) => !q || e.key.toLowerCase().includes(q) || (!e.secret && e.value.toLowerCase().includes(q)));
if (!list.length) this.rows.append(el('tr', {}, el('td.dotenv-none', { colSpan: 5 }, this.entries.length ? t('No variable matches.') : t('No variable in this file yet.'))));
const last = new Map();
for (const e of this.entries) last.set(e.key, e.line);
for (const e of list) {
this.rows.append(this.row(e, last.get(e.key) !== e.line));
if (this.dsnOpen === `${e.key}:${e.line}`) this.rows.append(el('tr.dotenv-dsn-row', {}, el('td', { colSpan: 5 }, this.dsnBuilder(e))));
}
}
row(e, shadowed) {
const win = this.winner(e.key);
const overriddenBy = shadowed ? { file: this.name, line: [...this.entries].reverse().find((x) => x.key === e.key).line }
: win && this.loaded() && (win.file !== this.name || win.line !== e.line) ? win : null;
const secret = e.secret;
const shown = !secret || this.revealed.has(e.key);
const ro = this.readOnly;
const set = (value) => value !== e.value && this.apply([{ op: 'set', key: e.key, value, line: e.line }]);
const kind = valueKind(e.key, e.value);
const eye = secret ? el(`button.icon-btn.dotenv-eye${shown ? '.on' : ''}`, { title: shown ? t('Hide the value') : t('Show the value'),
onclick: () => { if (shown) this.revealed.delete(e.key); else this.revealed.add(e.key); this.drawRows(); } }, icon('eye')) : null;
let editor;
if (!shown) editor = el('span.dotenv-masked', { title: t('Secret: click the eye to show it') }, maskValue(e.value) || el('i', {}, t('empty')));
else if (kind === 'bool') {
editor = el('label.dotenv-bool', {}, el('input', { type: 'checkbox', checked: isTrue(e.value), disabled: ro, onchange: () => set(toggleBool(e.value)) }), el('code', {}, e.value));
} else if (kind === 'multiline') {
editor = el('textarea.input.dotenv-value', { rows: Math.min(6, e.value.split('\n').length), value: e.value, disabled: ro, onchange: (ev) => set(ev.target.value) });
} else {
editor = el('input.input.dotenv-value', { value: e.value, disabled: ro, spellcheck: false, inputMode: kind === 'number' ? 'decimal' : undefined, placeholder: t('empty'),
onchange: (ev) => set(ev.target.value), onkeydown: (ev) => { if (ev.key === 'Enter') ev.target.blur(); } });
}
const dsnBtn = kind === 'dsn' && !ro ? el(`button.btn.small${this.dsnOpen === `${e.key}:${e.line}` ? '.on' : ''}`, { title: t('Build the URL field by field'),
onclick: () => { this.dsnOpen = this.dsnOpen === `${e.key}:${e.line}` ? null : `${e.key}:${e.line}`; this.drawRows(); } }, 'DSN') : null;
const effective = win ? (win.secret && !this.revealed.has(e.key) ? maskValue(win.effective) : win.effective) : '';
return el(`tr${overriddenBy ? '.overridden' : ''}`, {},
el('td.dotenv-name', {}, el('input.input', { value: e.key, disabled: ro, spellcheck: false,
onchange: (ev) => { const to = ev.target.value.trim(); if (to && to !== e.key) this.apply([{ op: 'rename', key: e.key, to, line: e.line }]); },
onkeydown: (ev) => { if (ev.key === 'Enter') ev.target.blur(); } }),
e.export ? el('span.dotenv-badge', {}, 'export') : null, secret ? el('span.dotenv-badge.secret', {}, t('Secret')) : null),
el('td.dotenv-val', {}, el('div.dotenv-valbox', {}, editor, eye, dsnBtn)),
el('td.dotenv-eff', {}, overriddenBy
? el('span.dotenv-over', { title: t('Overridden') }, t('overridden by {file}:{line}', { file: overriddenBy.file, line: overriddenBy.line }))
: el('span', { title: e.refs?.length ? t('References resolved: {names}', { names: e.refs.join(', ') }) : '' }, effective)),
el('td.dotenv-comment', {}, el('input.input', { value: e.comment ?? '', disabled: ro, placeholder: '#',
onchange: (ev) => this.apply([{ op: 'comment', key: e.key, comment: ev.target.value || null, line: e.line }]), onkeydown: (ev) => { if (ev.key === 'Enter') ev.target.blur(); } })),
el('td.dotenv-actions', {}, el('button.icon-btn', { title: t('More'), onclick: (ev) => this.rowMenu(e, ev.currentTarget) }, icon('more'))));
}
rowMenu(e, at) {
const targets = targetFiles(this.info.files, this.info.kind, this.info.envs, this.name);
const envFiles = this.info.envs.map((env) => `.env.${env}`).filter((n) => n !== this.name);
menu([
{ label: t('Show in the code'), icon: 'code', action: () => this.reveal(e.line) },
this.readOnly ? null : { label: t('Move to'), items: targets.map((f) => ({ label: f.exists ? f.name : t('{file} (new)', { file: f.name }), action: () => this.moveTo([e], f.name) })) },
this.readOnly || !envFiles.length || this.info.kind !== 'symfony' ? null : { label: t('Copy to'), icon: 'copy', items: [
{ label: t('Every environment'), action: () => this.copyTo(e, envFiles) }, '-',
...targets.map((f) => ({ label: f.exists ? f.name : t('{file} (new)', { file: f.name }), action: () => this.copyTo(e, [f.name]) }))] },
'-',
this.readOnly ? null : { label: t('Delete'), icon: 'trash', action: async () => {
if (await confirm(t('Delete {name}?', { name: e.key }), t('Its line (and the comment lines just above it) leave {file}.', { file: this.name }), { ok: t('Delete'), danger: true })) {
this.apply([{ op: 'delete', key: e.key, line: e.line, withComments: true }]);
}
} },
].filter(Boolean), at);
}
async addVariable() {
const name = await prompt(t('New variable'), { label: t('Its name (letters, digits and _): it is added at the end of {file}.', { file: this.name }), placeholder: 'MY_VARIABLE' });
if (!name) return;
await this.apply([{ op: 'add', key: name.trim(), value: '' }]);
this.filter = '';
}
/** the URL of a DSN variable field by field (driver, user, password, host, port, database, options) */
dsnBuilder(e) {
const preset = dsnPreset(e.key) || { schemes: [], ports: {}, query: [] };
const parts = parseDsn(e.value) || { scheme: preset.schemes[0] || '', user: '', password: '', host: '', port: preset.ports[preset.schemes[0]] || '', path: '', query: [], fragment: null };
const query = [...parts.query];
for (const k of preset.query || []) if (!query.some(([q]) => q === k) && e.key === 'DATABASE_URL') query.push([k, '']);
const box = el('div.dotenv-dsn');
const preview = el('code.dotenv-dsn-preview');
let showPassword = false;
const current = () => buildDsn({ ...parts, query: query.filter(([k, v]) => k && v !== '') });
const update = () => { preview.textContent = showPassword ? current() : maskValue(current()) || current(); };
const field = (label, key, attrs = {}) => el('label.dotenv-field', {}, el('span', {}, label),
el('input.input', { value: parts[key] ?? '', spellcheck: false, ...attrs, oninput: (ev) => { parts[key] = ev.target.value; update(); } }));
const schemes = [...new Set([...preset.schemes, parts.scheme].filter(Boolean))];
const scheme = schemes.length ? el('select.input', { onchange: (ev) => {
const before = parts.scheme;
parts.scheme = ev.target.value;
if (!parts.port || parts.port === preset.ports[before]) parts.port = preset.ports[parts.scheme] || '';
draw();
} }, schemes.map((s) => el('option', { value: s, selected: s === parts.scheme }, s))) : null;
const pwd = el('input.input', { type: 'password', value: parts.password ?? '', oninput: (ev) => { parts.password = ev.target.value; update(); }, autocomplete: 'off' });
const draw = () => {
clear(box);
const file = parts.scheme === 'sqlite';
box.append(
el('div.dotenv-dsn-grid', {},
el('label.dotenv-field', {}, el('span', {}, t('Driver')), scheme || el('input.input', { value: parts.scheme, oninput: (ev) => { parts.scheme = ev.target.value; update(); } })),
file ? null : field(t('User'), 'user'),
file ? null : el('label.dotenv-field', {}, el('span', {}, t('Password')), el('div.dotenv-valbox', {}, pwd,
el('button.icon-btn', { title: t('Show the value'), onclick: () => { showPassword = !showPassword; pwd.type = showPassword ? 'text' : 'password'; update(); } }, icon('eye')))),
file ? null : field(t('Host'), 'host'),
file ? null : field(t('Port'), 'port', { inputMode: 'numeric', placeholder: preset.ports[parts.scheme] || '' }),
field(file ? t('File') : t('Database / path'), 'path', { placeholder: file ? '/%kernel.project_dir%/var/data.db' : '/app' })),
el('div.dotenv-query', {}, el('span.dotenv-label', {}, t('Options')), query.map((q, i) => el('span.dotenv-q', {},
el('input.input', { value: q[0], placeholder: t('name'), oninput: (ev) => { q[0] = ev.target.value; update(); } }), '=',
el('input.input', { value: q[1], placeholder: q[0] === 'serverVersion' ? '16' : q[0] === 'charset' ? 'utf8' : '', oninput: (ev) => { q[1] = ev.target.value; update(); } }),
el('button.icon-btn', { title: t('Delete'), onclick: () => { query.splice(i, 1); draw(); } }, icon('close')))),
el('button.icon-btn', { title: t('Add an option'), onclick: () => { query.push(['', '']); draw(); } }, icon('plus'))),
el('div.dotenv-dsn-foot', {}, preview, el('span', { style: { flex: 1 } }),
el('button.btn', { onclick: () => { this.dsnOpen = null; this.drawRows(); } }, t('Cancel')),
el('button.btn.primary', { onclick: () => { this.dsnOpen = null; this.apply([{ op: 'set', key: e.key, value: current(), line: e.line }]); } }, t('Apply'))));
update();
};
draw();
return box;
}
// the merged view --------------------------------------------------------------------------------------
renderVariables() {
const m = this.merged?.[this.env];
const head = el('div.dotenv-head', {}, this.fileBar(), el('div.dotenv-tools', {}, el('span.dotenv-label', {}, t('Environment')), this.envPicker(),
el('input.input.dotenv-search', { type: 'search', placeholder: t('Filter'), value: this.filter, oninput: (e) => { this.filter = e.target.value; this.forceRender = true; this.render(); this.forceRender = false; } })));
const order = el('div.dotenv-order', {}, el('span.dotenv-label', {}, t('Loaded in this order (the later wins):')),
...(m?.order.length ? m.order.flatMap((n, i) => [i ? el('span.dotenv-arrow', {}, '→') : null, el('button.dotenv-file', { onclick: () => this.area.open(this.path(n)) }, n)]) : [el('i', {}, t('no file'))]));
const q = this.filter.toLowerCase();
const rows = (m?.variables || []).filter((v) => !q || v.key.toLowerCase().includes(q)).sort((a, b) => a.key.localeCompare(b.key)).map((v) => {
const shown = !v.secret || this.revealed.has(v.key);
const lost = v.definitions.filter((d) => !d.wins);
return el('tr', {},
el('td.dotenv-name', {}, el('code', {}, v.key), v.secret ? el('span.dotenv-badge.secret', {}, t('Secret')) : null),
el('td', {}, el('div.dotenv-valbox', {}, el(`span${shown ? '' : '.dotenv-masked'}`, {}, shown ? v.effective : maskValue(v.effective)),
v.secret ? el(`button.icon-btn.dotenv-eye${shown ? '.on' : ''}`, { title: shown ? t('Hide the value') : t('Show the value'),
onclick: () => { if (shown) this.revealed.delete(v.key); else this.revealed.add(v.key); this.forceRender = true; this.render(); this.forceRender = false; } }, icon('eye')) : null)),
el('td', {}, el('button.dotenv-link', { onclick: () => this.area.open(this.path(v.file), { line: v.line }) }, `${v.file}:${v.line}`)),
el('td.dotenv-lost', {}, lost.map((d) => el('div', {}, el('s', {}, shown ? d.value : maskValue(d.value)), ' ',
el('button.dotenv-link', { onclick: () => this.area.open(this.path(d.file), { line: d.line }) }, `${d.file}:${d.line}`)))));
});
put(this.view, head, order,
this.info.dumped ? el('div.dotenv-banner', {}, icon('warning'), el('span', {}, t('A .env.local.php exists (composer dump-env): Symfony reads it instead of the .env files.'))) : null,
el('table.dotenv-table.merged', {}, el('thead', {}, el('tr', {}, el('th', {}, t('Name')), el('th', {}, t('Effective value ({env})', { env: this.env })), el('th', {}, t('From')), el('th', {}, t('Overridden values')))),
el('tbody', {}, rows.length ? rows : el('tr', {}, el('td.dotenv-none', { colSpan: 4 }, t('No variable.'))))),
this.compose.length ? el('div.dotenv-compose', {}, el('h4', {}, t('Docker Compose env files')), this.compose.map((c) => el('div', {},
el('button.dotenv-link', { onclick: () => this.area.open(c.path) }, c.path), ' ', el('span.dotenv-label', {}, t('services {names} ({file})', { names: c.services.join(', '), file: c.from }))))) : null,
el('p.dotenv-note', {}, t('Real environment variables (the shell, Docker) win over every file.')));
}
// Symfony's vault ------------------------------------------------------------------------------------------
renderVault() {
if (!this.vault) { this.loadVault().then(() => this.render()); return; }
const v = this.vault;
const envs = [...new Set([...v.envs.map((e) => e.env), ...this.info.envs.filter((e) => e === 'dev' || e === 'prod')])];
if (!envs.includes(this.vaultEnv)) this.vaultEnv = envs[0] || 'dev';
const cur = v.envs.find((e) => e.env === this.vaultEnv) || { env: this.vaultEnv, names: [], encryptKey: false, decryptKey: false, decryptPath: `config/secrets/${this.vaultEnv}/${this.vaultEnv}.decrypt.private.php` };
const keyPath = this.path(cur.decryptPath);
const head = el('div.dotenv-head', {}, el('div.dotenv-tools', {}, el('span.dotenv-label', {}, t('Symfony secrets vault')), el('div.dotenv-envs', {}, envs.map((env) => el(`button${env === this.vaultEnv ? '.on' : ''}`, {
onclick: () => { this.vaultEnv = env; prefs.set('envVaultEnv', env); this.revealedVault = null; this.render(); } }, env))),
el('span', { style: { flex: 1 } }),
cur.encryptKey ? el('button.btn', { onclick: () => this.vaultSet() }, icon('plus'), t('Secret')) : null,
cur.decryptKey ? el('button.btn', { onclick: () => this.vaultReveal() }, icon('eye'), t('Reveal the values')) : null,
el('button.btn', { onclick: () => this.vaultKeys(cur.encryptKey) }, cur.encryptKey ? t('Rotate the keys') : t('Generate the keys'))));
const banners = [];
if (!v.console) banners.push(el('div.dotenv-banner.warning', {}, icon('warning'), t('No bin/console: the vault needs a Symfony project.')));
if (v.trackedKeys?.includes(keyPath)) {
banners.push(el('div.dotenv-banner.danger', {}, icon('warning'), el('span', {}, t('The decrypt key {path} is committed: whoever has the repository can read every secret of {env}. Remove it from git (git rm --cached) and keep it out.', { path: cur.decryptPath, env: cur.env })),
el('button.btn', { onclick: () => this.ignoreKey(cur) }, t('Ignore it in git'))));
} else if (cur.decryptKey && !v.ignoredKeys?.includes(keyPath)) {
banners.push(el('div.dotenv-banner.warning', {}, icon('warning'), el('span', {}, t('The decrypt key {path} is not ignored by git: never commit it (for prod, give it to the server another way, or SYMFONY_DECRYPTION_SECRET).', { path: cur.decryptPath })),
el('button.btn', { onclick: () => this.ignoreKey(cur) }, t('Ignore it in git'))));
}
if (!cur.encryptKey) banners.push(el('div.dotenv-banner', {}, t('No keys for {env} yet: generate them, then add secrets. The decrypt key must never be committed.', { env: cur.env })));
else if (!cur.decryptKey) banners.push(el('div.dotenv-banner', {}, t('Only the encrypt key is here: secrets can be added, not read (the decrypt key lives on the server).')));
const revealed = this.revealedVault?.env === cur.env ? this.revealedVault.values : null;
const rows = cur.names.map((name) => {
const r = revealed?.find((x) => x.name === name);
const shown = this.revealed.has('vault:' + name);
return el('tr', {}, el('td.dotenv-name', {}, el('code', {}, name)),
el('td', {}, revealed ? el('div.dotenv-valbox', {}, el(`span${shown ? '' : '.dotenv-masked'}`, {}, r?.value == null ? el('i', {}, t('hidden')) : shown ? r.value : maskValue(r.value)),
r?.value != null ? el(`button.icon-btn.dotenv-eye${shown ? '.on' : ''}`, { onclick: () => { if (shown) this.revealed.delete('vault:' + name); else this.revealed.add('vault:' + name); this.render(); } }, icon('eye')) : null)
: el('span.dotenv-masked', {}, '••••••••')),
el('td', {}, r?.local != null ? el('span.dotenv-label', {}, t('overridden by a .env variable')) : ''),
el('td.dotenv-actions', {}, el('button.icon-btn', { title: t('Change the value'), onclick: () => this.vaultSet(name) }, icon('edit')),
el('button.icon-btn', { title: t('Delete'), onclick: () => this.vaultRemove(name) }, icon('trash'))));
});
put(this.view, head, ...banners,
v.error ? el('div.dotenv-banner.danger', {}, v.error) : null,
el('table.dotenv-table.vault', {}, el('thead', {}, el('tr', {}, el('th', {}, t('Secret')), el('th', {}, t('Value')), el('th', {}), el('th', {}))),
el('tbody', {}, rows.length ? rows : el('tr', {}, el('td.dotenv-none', { colSpan: 4 }, t('No secret in the {env} vault.', { env: cur.env }))))),
el('p.dotenv-note', {}, t('In the configuration: %env(NAME)%. A variable of the same name in .env.local overrides the vault (handy in dev).')));
}
async vaultRun(promise, busy) {
const n = notify(busy, 'info', { title: t('Vault'), timeout: 0 });
try { return await promise; } finally { n?.remove?.(); }
}
async vaultReveal() {
try {
const r = await this.vaultRun(backend.invoke('dotenv.vault.reveal', { env: this.vaultEnv }), t('Reading the secrets of {env}…', { env: this.vaultEnv }));
this.revealedVault = { env: this.vaultEnv, values: r.secrets };
this.render();
} catch (e) { notify(e.message, 'error', { title: t('Vault') }); }
}
vaultSet(name = '') {
const nameInput = el('input.input', { value: name, placeholder: 'API_KEY', disabled: !!name, spellcheck: false });
const value = el('textarea.input.dotenv-secret-input', { rows: 3, placeholder: t('The value (never shown in a log)'), spellcheck: false, autocomplete: 'off' });
value.classList.add('masked');
const env = this.vaultEnv;
dialog({
title: name ? t('Change {name} ({env})', { name, env }) : t('New secret ({env})', { env }),
body: el('div.dotenv-form', {}, el('label.dotenv-field', {}, el('span', {}, t('Name')), nameInput),
el('label.dotenv-field', {}, el('span', {}, t('Value')), el('div.dotenv-valbox', {}, value,
el('button.icon-btn', { title: t('Show the value'), onclick: () => value.classList.toggle('masked') }, icon('eye')))),
el('p.dotenv-note', {}, t('Encrypted by secrets:set with the value on its standard input: it appears on no command line.'))),
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
const n = nameInput.value.trim();
await this.vaultRun(backend.invoke('dotenv.vault.set', { env, name: n, value: value.value }), t('Encrypting {name}…', { name: n }));
notify(t('{name} is saved in the {env} vault.', { name: n, env }), 'success', { title: t('Vault') });
this.revealedVault = null;
await this.loadVault();
this.render();
} }],
});
}
async vaultRemove(name) {
if (!await confirm(t('Delete {name}?', { name }), t('The secret leaves the {env} vault.', { env: this.vaultEnv }), { ok: t('Delete'), danger: true })) return;
try {
await this.vaultRun(backend.invoke('dotenv.vault.remove', { env: this.vaultEnv, name }), t('Deleting {name}…', { name }));
await this.loadVault();
this.render();
} catch (e) { notify(e.message, 'error', { title: t('Vault') }); }
}
async vaultKeys(rotate) {
const env = this.vaultEnv;
if (!await confirm(rotate ? t('Rotate the keys of {env}?', { env }) : t('Generate the keys of {env}?', { env }),
t('secrets:generate-keys writes config/secrets/{env}/: the encrypt key (commit it) and the decrypt key (NEVER commit it: it is added to .gitignore).', { env }), { ok: 'OK' })) return;
try {
await this.vaultRun(backend.invoke('dotenv.vault.generateKeys', { env, rotate }), t('Generating the keys of {env}…', { env }));
if (this.git.repository) await backend.invoke('dotenv.ignore', { folder: this.folder, patterns: [`/config/secrets/${env}/${env}.decrypt.private.php`] });
this.area.app.tree?.refresh?.();
await this.loadVault();
this.render();
} catch (e) { notify(e.message, 'error', { title: t('Vault') }); }
}
async ignoreKey(cur) {
const r = await backend.invoke('dotenv.ignore', { folder: this.folder, patterns: ['/' + cur.decryptPath] }).catch((e) => { notify(e.message, 'error'); return null; });
if (r?.added?.length) notify(t('Added to {file}: {lines}', { file: r.path, lines: r.added.join(' ') }), 'success', { title: '.gitignore' });
await this.loadVault();
this.render();
}
}
// a field left (blur) after a change made while the table waited: drawn now
document.addEventListener('focusout', () => setTimeout(() => {
for (const node of document.querySelectorAll('.dotenv-view')) node.dispatchEvent(new Event('dotenv-idle'));
}, 0), true);