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

152 lines
9.8 KiB
JavaScript

// The .env editor's pure helpers (no DOM, no Monaco): which files are dotenv files, the kind of a value (boolean,
// number, DSN, multi-line), DSNs taken apart and built (the same rules as ide/src/Dotenv/Dsn.php), secrets recognised
// and masked (ide/src/Dotenv/Secrets.php), the variables Symfony and Laravel know, the smallest edit between two texts.
// Tested by dotenv-model.test.mjs (node --test).
/** .env, .env.local, .env.<env>, .env.<env>.local, .env.dist, .env.example, *.env (Docker Compose env_file); not .env.local.php */
export function isDotenvPath(path) {
const name = String(path).split('/').pop();
if (name === '.env.local.php') return false;
return /^\.env(\.[A-Za-z0-9_-]+){0,2}$/.test(name) || /^[A-Za-z0-9_.-]+\.env$/.test(name);
}
export const SECRET_NAME = /PASS(WORD|WD|PHRASE)?($|_)|SECRET|TOKEN|(^|_)KEY($|_)|APIKEY|PRIVATE|CREDENTIAL|(^|_)AUTH($|_)|SALT|(^|_)PWD($|_)/i;
export const isSecretName = (name) => SECRET_NAME.test(name) && !/PUBLIC/i.test(name);
const DSN = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@?#]*))?@)?(\[[^\]]*\]|[^:/?#]*)(?::([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/s;
const decode = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
const encodePart = (s) => String(s).replace(/[:@/?#\s"'\\]|%(?![0-9A-Fa-f]{2})/g, (c) => encodeURIComponent(c));
const encodeQuery = (s) => String(s).replace(/[&=#\s"'\\]|%(?![0-9A-Fa-f]{2})/g, (c) => encodeURIComponent(c));
/** scheme://user:password@host:port/path?query#fragment -> its parts (null: not a URL) */
export function parseDsn(value) {
const m = DSN.exec(String(value));
if (!m) return null;
const query = (m[7] || '').split('&').filter((p) => p !== '').map((p) => { const i = p.indexOf('='); return i < 0 ? [decode(p), ''] : [decode(p.slice(0, i)), decode(p.slice(i + 1))]; });
return { scheme: m[1], user: m[2] === undefined ? null : decode(m[2]), password: m[3] === undefined ? null : decode(m[3]), host: m[4] || '', port: m[5] || '',
path: m[6] || '', query, fragment: m[8] === undefined ? null : m[8] };
}
export function buildDsn(p) {
let out = `${p.scheme || ''}://`;
if (p.user || p.password) out += encodePart(p.user || '') + (p.password ? ':' + encodePart(p.password) : '') + '@';
out += p.host || '';
if (p.port !== undefined && p.port !== null && p.port !== '') out += ':' + p.port;
const path = p.path || '';
out += path === '' || path[0] === '/' ? path : '/' + path;
const query = (p.query || []).filter(([k]) => k !== '').map(([k, v]) => `${encodeQuery(k)}=${encodeQuery(v ?? '')}`);
if (query.length) out += '?' + query.join('&');
if (p.fragment !== null && p.fragment !== undefined) out += '#' + p.fragment;
return out;
}
const REF_ONLY = /^(\$\{[^}]*\}|\$[A-Za-z_]\w*|%env\([^)]*\)%)$/;
export const hasDsnPassword = (value) => { const d = parseDsn(value); return !!d?.password && !REF_ONLY.test(d.password); };
export const isSecret = (name, value) => isSecretName(name) || hasDsnPassword(value);
/** what is shown while a secret is masked: a DSN keeps everything but its password */
export function maskValue(value) {
if (value === '' || value === null || value === undefined) return '';
if (hasDsnPassword(value)) return String(value).replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/[^:@/?#]*:)([^@?#]+)@/, '$1••••@');
return '••••••••';
}
/** The DSN builders: schemes, their default ports and the query keys worth a field, per variable. */
export const DSN_PRESETS = {
DATABASE_URL: { schemes: ['postgresql', 'mysql', 'sqlite', 'sqlsrv', 'oci8'], ports: { postgresql: '5432', mysql: '3306', sqlsrv: '1433', oci8: '1521' }, query: ['serverVersion', 'charset'], path: 'database' },
MAILER_DSN: { schemes: ['smtp', 'smtps', 'sendmail', 'native', 'null', 'gmail+smtp', 'ses+smtp', 'mailgun+smtp', 'sendgrid+smtp', 'brevo+smtp', 'postmark+smtp', 'mailjet+smtp'], ports: { smtp: '587', smtps: '465' }, query: ['verify_peer', 'local_domain'] },
MESSENGER_TRANSPORT_DSN: { schemes: ['doctrine', 'amqp', 'redis', 'sync', 'in-memory', 'sqs'], ports: { amqp: '5672', redis: '6379' }, query: ['auto_setup', 'queue_name'] },
REDIS_URL: { schemes: ['redis', 'rediss'], ports: { redis: '6379', rediss: '6380' }, query: ['timeout', 'persistent'] },
LOCK_DSN: { schemes: ['flock', 'semaphore', 'redis', 'postgresql', 'mysql'], ports: { redis: '6379' }, query: [] },
};
export function dsnPreset(name) {
if (DSN_PRESETS[name]) return DSN_PRESETS[name];
if (/_DSN$/.test(name)) return { schemes: [], ports: {}, query: [] };
if (/(^|_)(DATABASE|REDIS|AMQP|MONGODB|ELASTICSEARCH|MERCURE)_URL$/.test(name)) return { schemes: [], ports: {}, query: [] };
return null;
}
const BOOL = /^(true|false|yes|no|on|off)$/i;
/** how the table edits a value: 'bool' | 'number' | 'dsn' | 'multiline' | 'text' */
export function valueKind(name, value) {
const v = String(value ?? '');
if (v.includes('\n')) return 'multiline';
if (dsnPreset(name) && (v === '' || parseDsn(v))) return 'dsn';
if (parseDsn(v) && /:\/\/[^/]*@/.test(v)) return 'dsn';
if (BOOL.test(v) || (/^[01]$/.test(v) && /DEBUG|ENABLE|DISABLE|(^|_)USE_|(^|_)IS_|VERBOSE|SECURE/i.test(name))) return 'bool';
if (/^-?\d+(\.\d+)?$/.test(v)) return 'number';
return 'text';
}
/** the other value of a boolean, in the same style (true/false, 1/0, yes/no, on/off; case kept) */
export function toggleBool(v) {
const pairs = { true: 'false', false: 'true', yes: 'no', no: 'yes', on: 'off', off: 'on', 1: '0', 0: '1' };
const lower = String(v).toLowerCase();
const other = pairs[lower] ?? 'true';
return v === v.toUpperCase() && /[a-z]/i.test(v) ? other.toUpperCase() : other;
}
export const isTrue = (v) => /^(true|yes|on|1)$/i.test(String(v));
/** The smallest change from a text to another: {start, end (in the old text), text} (null: the same). */
export function diffRange(before, after) {
if (before === after) return null;
let start = 0;
const max = Math.min(before.length, after.length);
while (start < max && before[start] === after[start]) start++;
let endB = before.length;
let endA = after.length;
while (endB > start && endA > start && before[endB - 1] === after[endA - 1]) { endB--; endA--; }
return { start, end: endB, text: after.slice(start, endA) };
}
/** What the cursor is in on a line of a .env file: {kind: 'name', prefix} | {kind: 'ref', prefix, braced} | {kind: 'value', name, prefix} | null */
export function contextAt(line, column) {
const before = line.slice(0, column - 1);
if (/^\s*#/.test(before)) return null;
const name = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)?$/.exec(before);
if (name) return { kind: 'name', prefix: name[1] || '' };
const ref = /\$(\{)?([A-Za-z_][A-Za-z0-9_]*)?$/.exec(before);
if (ref && !/'/.test(before.slice(before.indexOf('=') + 1))) return { kind: 'ref', prefix: ref[2] || '', braced: !!ref[1] };
const value = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(before);
if (value) return { kind: 'value', name: value[1], prefix: value[2] };
return null;
}
/** Variables Symfony and Laravel know, with an example value (completion, the "add variable" menu). */
export const KNOWN = {
symfony: {
APP_ENV: 'dev', APP_SECRET: '', APP_DEBUG: '1', APP_SHARE_DIR: 'var/share', DEFAULT_URI: 'http://localhost',
DATABASE_URL: '"postgresql://app:[email protected]:5432/app?serverVersion=16&charset=utf8"',
MAILER_DSN: 'null://null', MESSENGER_TRANSPORT_DSN: 'doctrine://default?auto_setup=0', REDIS_URL: 'redis://localhost:6379',
LOCK_DSN: 'flock', CORS_ALLOW_ORIGIN: "'^https?://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?$'", TRUSTED_PROXIES: '127.0.0.1,REMOTE_ADDR', TRUSTED_HOSTS: "'^localhost$'",
JWT_SECRET_KEY: '%kernel.project_dir%/config/jwt/private.pem', JWT_PUBLIC_KEY: '%kernel.project_dir%/config/jwt/public.pem', JWT_PASSPHRASE: '',
MERCURE_URL: 'https://example.com/.well-known/mercure', MERCURE_PUBLIC_URL: 'https://example.com/.well-known/mercure', MERCURE_JWT_SECRET: '"!ChangeThisMercureHubJWTSecretKey!"',
SENTRY_DSN: '', SYMFONY_DEPRECATIONS_HELPER: '999999', KERNEL_CLASS: "'App\\Kernel'",
},
laravel: {
APP_NAME: 'Laravel', APP_ENV: 'local', APP_KEY: '', APP_DEBUG: 'true', APP_URL: 'http://localhost', APP_LOCALE: 'en', APP_FALLBACK_LOCALE: 'en',
APP_MAINTENANCE_DRIVER: 'file', BCRYPT_ROUNDS: '12', LOG_CHANNEL: 'stack', LOG_STACK: 'single', LOG_LEVEL: 'debug',
DB_CONNECTION: 'sqlite', DB_HOST: '127.0.0.1', DB_PORT: '3306', DB_DATABASE: 'laravel', DB_USERNAME: 'root', DB_PASSWORD: '',
SESSION_DRIVER: 'database', SESSION_LIFETIME: '120', SESSION_ENCRYPT: 'false', BROADCAST_CONNECTION: 'log', FILESYSTEM_DISK: 'local',
QUEUE_CONNECTION: 'database', CACHE_STORE: 'database', REDIS_CLIENT: 'phpredis', REDIS_HOST: '127.0.0.1', REDIS_PASSWORD: 'null', REDIS_PORT: '6379',
MAIL_MAILER: 'log', MAIL_HOST: '127.0.0.1', MAIL_PORT: '2525', MAIL_USERNAME: 'null', MAIL_PASSWORD: 'null', MAIL_FROM_ADDRESS: '"[email protected]"', MAIL_FROM_NAME: '"${APP_NAME}"',
AWS_ACCESS_KEY_ID: '', AWS_SECRET_ACCESS_KEY: '', AWS_DEFAULT_REGION: 'us-east-1', AWS_BUCKET: '', VITE_APP_NAME: '"${APP_NAME}"',
},
};
/** the names a ${REF} can take in a text (its own variables first) */
export function namesIn(text) {
const out = [];
for (const m of String(text).matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)) if (!out.includes(m[1])) out.push(m[1]);
return out;
}
/** the files a variable can move / be copied to, from the folder's files (the missing usual ones are offered too) */
export function targetFiles(files, kind, envs, current) {
const names = new Set(files.map((f) => f.name));
const wanted = ['.env', '.env.local', ...(kind === 'symfony' ? envs.flatMap((e) => [`.env.${e}`, `.env.${e}.local`]) : [])];
for (const n of names) if (!wanted.includes(n)) wanted.push(n);
return wanted.filter((n) => n !== current && !/\.(example|sample|template|dist)$/.test(n)).map((n) => ({ name: n, exists: names.has(n) }));
}