UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

1 lines • 11.7 kB
{"version":3,"file":"legacy-databases.cjs","names":["Data","Effect","join","existsSync","readFileSync","loadDotenv","PGLITE_TEST_DATABASE_URL","pgliteDefaultUrlForSlug","normalizeDatabaseSlug","resolve","PGLITE_DEFAULT_URL"],"sources":["../../src/env/legacy-databases.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { config as loadDotenv } from \"dotenv\";\nimport { Data, Effect } from \"effect\";\nimport { PGLITE_DEFAULT_URL, pgliteDefaultUrlForSlug } from \"../db/binding\";\nimport { normalizeDatabaseSlug, PGLITE_TEST_DATABASE_URL } from \"../services/infra\";\n\nexport class LegacyMigrationError extends Data.TaggedError(\"LegacyMigrationError\")<{\n cause: unknown;\n}> {}\n\nexport interface LegacyMigrationReport {\n databaseUrlDrift: Array<{ key: string; from: string; to: string }>;\n composeRelocated: boolean;\n}\n\n/**\n * The compose-era local database convention (`bos dev` provisioned Postgres\n * via the committed docker-compose.yml): every `*_DATABASE_URL` pointed at\n * `postgres://everythingdev:everythingdev@localhost:<port>/<db>` on the\n * hardcoded 5432–5435 block. Those are exactly the opt-ins that made two\n * concurrent local projects fight over host ports.\n *\n * The compose-era convention is retired — local persistence is a\n * file-backed PGlite data dir per workspace (`.bos/db/<slug>`), tests run on\n * in-memory pglite. `bos dev` repairs leftover state once, idempotently:\n * 1. `.env` lines whose URL matches the conventional shape (user, host,\n * and database name — port too, but drift ports like 5532 from the old\n * +100 allocator also match by name) are rewritten to the per-identity\n * defaults. Any other `postgres://` URL is operator-owned and left alone.\n * 2. `.env` lines where two or more `*_DATABASE_URL` secrets share the one\n * legacy pglite dir (`pglite:.bos/db`) are rewritten to per-identity\n * subdirs — multiple live PGlite instances on one data dir silently\n * corrupt committed data (ADR 0044). Only the exact legacy literal is\n * rewritten; operator-authored pglite URLs are left to the preflight\n * tripwire, which fails loudly on any remaining same-dir set.\n * 3. A leftover scaffold-shaped `docker-compose.yml` is moved to\n * `.bos/compose-retired/` rather than deleted; operator-authored\n * compose files (different service names/images) are untouched.\n */\nexport const migrateLegacyComposeState = (\n configDir: string,\n): Effect.Effect<LegacyMigrationReport, never> =>\n Effect.try({\n try: () => {\n const envPath = join(configDir, \".env\");\n const databaseUrlDrift: LegacyMigrationReport[\"databaseUrlDrift\"] = [];\n\n if (existsSync(envPath)) {\n const raw = readFileSync(envPath, \"utf-8\");\n const parsed = loadDotenv({ path: envPath, quiet: true }).parsed ?? {};\n const rewritten = rewrittenLegacyDatabaseValues({ file: parsed, raw });\n for (const [key, to] of rewrittenSharedPgliteValues(parsed)) {\n if (!rewritten.has(key)) rewritten.set(key, to);\n }\n if (rewritten.size > 0) {\n const lines = raw.split(\"\\n\");\n const updated = lines.map((line) => {\n const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);\n if (!match) return line;\n const replacement = rewritten.get(match[1]);\n return replacement === undefined ? line : `${match[1]}=${replacement}`;\n });\n writeFileSync(envPath, updated.join(\"\\n\"));\n for (const [key, to] of rewritten) {\n databaseUrlDrift.push({ key, from: parsed[key] ?? \"\", to });\n }\n }\n }\n\n const composeRelocated = relocateLegacyComposeFile(configDir);\n return { databaseUrlDrift, composeRelocated };\n },\n catch: (cause) => new LegacyMigrationError({ cause }),\n }).pipe(Effect.orElseSucceed(() => ({ databaseUrlDrift: [], composeRelocated: false })));\n\n/** Matches the compose-era URL shapes: the scaffolded user + localhost + the convention's database names. */\nconst LEGACY_DATABASE_NAME = /^(api_db|auth_db|api_test_db|auth_test_db)$/;\n\nfunction legacyMappingForUrl(secret: string, rawUrl: string): string | undefined {\n try {\n const url = new URL(rawUrl);\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return undefined;\n if (url.hostname !== \"localhost\" && url.hostname !== \"127.0.0.1\") return undefined;\n if (url.username !== \"everythingdev\" || url.password !== \"everythingdev\") return undefined;\n const databaseName = decodeURIComponent(url.pathname.replace(/^\\//, \"\"));\n if (!LEGACY_DATABASE_NAME.test(databaseName)) return undefined;\n return databaseName.endsWith(\"_test_db\")\n ? PGLITE_TEST_DATABASE_URL\n : pgliteDefaultUrlForSlug(normalizeDatabaseSlug(secret));\n } catch {\n return undefined;\n }\n}\n\nexport function rewrittenLegacyDatabaseValues(input: {\n file: Record<string, string>;\n raw: string;\n}): Map<string, string> {\n const rewritten = new Map<string, string>();\n for (const [key, value] of Object.entries(input.file)) {\n const match = value ? legacyMappingForUrl(key, value) : undefined;\n if (match !== undefined) {\n const rawLine = new RegExp(`^${key}=.+$`, \"m\").test(input.raw);\n if (rawLine) rewritten.set(key, match);\n }\n }\n return rewritten;\n}\n\n/**\n * The pre-ADR-0044 scaffold pinned every workspace to one shared PGlite data\n * dir (`pglite:.bos/db`). Multiple live PGlite instances on one data dir\n * silently corrupt committed data (heap/index divergence — ADR 0044), so when\n * two or more `*_DATABASE_URL` secrets share the legacy dir, each pin is\n * rewritten to its per-identity subdir. Only the exact legacy literal is\n * rewritten; anything operator-authored is left alone for the preflight\n * tripwire. A rewrite is also skipped when its target dir is occupied by a\n * pin that stays — a safe partial repair beats a new collision.\n */\nexport function rewrittenSharedPgliteValues(file: Record<string, string>): Map<string, string> {\n const byDir = new Map<string, string[]>();\n for (const [key, value] of Object.entries(file)) {\n if (!key.endsWith(\"_DATABASE_URL\") || !value?.startsWith(\"pglite:\")) continue;\n const rawDir = value.slice(\"pglite:\".length);\n if (rawDir === \":memory:\" || rawDir.endsWith(\"/:memory:\")) continue;\n const dir = resolve(rawDir);\n const secrets = byDir.get(dir);\n if (secrets) secrets.push(key);\n else byDir.set(dir, [key]);\n }\n\n const rewritten = new Map<string, string>();\n for (const secrets of byDir.values()) {\n if (secrets.length < 2) continue;\n for (const secret of secrets) {\n if (file[secret] !== PGLITE_DEFAULT_URL) continue;\n const target = pgliteDefaultUrlForSlug(normalizeDatabaseSlug(secret));\n const targetDir = resolve(target.slice(\"pglite:\".length));\n const occupant = byDir.get(targetDir);\n if (occupant?.some((other) => other !== secret && !rewritten.has(other))) continue;\n rewritten.set(secret, target);\n }\n }\n return rewritten;\n}\n\nconst SCAFFOLD_SERVICE_NAMES = new Set([\n \"postgres-api\",\n \"postgres-auth\",\n \"postgres-api-test\",\n \"postgres-auth-test\",\n]);\nconst SCAFFOLD_IMAGE_HINTS = [\n \"public.ecr.aws/docker/library/postgres\",\n \"docker.io/library/postgres\",\n \"postgres:17-alpine\",\n \"ghcr.io/nearbuilders/mirror-postgres\",\n];\n\nfunction isScaffoldComposeFile(raw: string): boolean {\n const services = [...raw.matchAll(/^\\s+-?\\s*([a-z-]+):\\s*$/gm)].map((match) => match[1] ?? \"\");\n if (!services.some((name) => SCAFFOLD_SERVICE_NAMES.has(name))) return false;\n return SCAFFOLD_IMAGE_HINTS.some((hint) => raw.includes(hint));\n}\n\nfunction relocateLegacyComposeFile(configDir: string): boolean {\n const composePath = join(configDir, \"docker-compose.yml\");\n if (!existsSync(composePath)) return false;\n let raw: string;\n try {\n raw = readFileSync(composePath, \"utf-8\");\n } catch {\n return false;\n }\n if (!isScaffoldComposeFile(raw)) return false;\n const retiredDir = join(configDir, \".bos\", \"compose-retired\");\n mkdirSync(retiredDir, { recursive: true });\n renameSync(composePath, join(retiredDir, \"docker-compose.yml\"));\n return true;\n}\n"],"mappings":";;;;;;;;AAOA,IAAa,uBAAb,cAA0CA,YAAK,YAAY,sBAAsB,CAAC,CAE/E,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;AA+BJ,MAAa,6BACX,cAEAC,cAAO,IAAI;CACT,WAAW;EACT,MAAM,cAAUC,gBAAK,WAAW,MAAM;EACtC,MAAM,mBAA8D,CAAC;EAErE,QAAIC,oBAAW,OAAO,GAAG;GACvB,MAAM,UAAMC,sBAAa,SAAS,OAAO;GACzC,MAAM,aAASC,eAAW;IAAE,MAAM;IAAS,OAAO;GAAK,CAAC,CAAC,CAAC,UAAU,CAAC;GACrE,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