@lines-db/studio 0.16.3 → 0.16.5
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.
- package/CHANGELOG.md +18 -0
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/index.d.mts +0 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +79 -14
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -6
- package/ui/assets/{index-a4TvKq00.js → index-Bwwhvci0.js} +24 -24
- package/ui/index.html +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["resolvePath"],"sources":["../src/declared-columns.ts","../src/file-rows.ts","../src/server.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve, win32 } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type * as TS from 'typescript';\n\n/** A column as the schema file declares it, read from the types of its Standard Schema */\nexport interface DeclaredColumn {\n name: string;\n /** The type of the values, without the null and undefined that the two flags below stand for */\n type: string;\n /** The field may be left out of a row: optional, or filled in by a default */\n optional: boolean;\n nullable: boolean;\n}\n\n// The flags of the Corsa API of typescript@7.1, which are not the ones of every compiler API: typescript 5 has\n// others, so that one is read from the `ts` it is given\nconst CORSA_NULL = 8;\nconst CORSA_UNION = 134217728;\nconst CORSA_OPTIONAL = 16777216;\n\n/** The type checker of either API, as far as reading the columns needs it */\ninterface TypeReader<Type, Property> {\n /** The type of what the file exports as `schema`, or else as its default */\n entryType(): Type | undefined;\n property(type: Type, name: string): Property | undefined;\n typeOf(property: Property): Type;\n nonNullable(type: Type): Type;\n /** The types a union is of, or the type itself: the properties of a union are only those its members share */\n members(type: Type): readonly Type[];\n properties(type: Type): readonly Property[];\n nameOf(property: Property): string;\n isOptional(property: Property): boolean;\n isNullable(type: Type): boolean;\n text(type: Type): string;\n}\n\n/** What a reading found, and the files of the project it was read from, which a change to any of them makes stale */\ninterface Reading {\n columns: DeclaredColumn[] | undefined;\n files: string[];\n}\n\n/**\n * Standard Schema holds the types of what it validates in `~standard.types`, which every library that\n * implements it fills in, so the columns are read from the types and not from any one library\n */\nfunction columnsOf<Type, Property>(reader: TypeReader<Type, Property>): DeclaredColumn[] | undefined {\n let type = reader.entryType();\n for (const name of ['~standard', 'types', 'input']) {\n const property = type && reader.property(type, name);\n if (!property) return undefined;\n type = reader.nonNullable(reader.typeOf(property));\n }\n const members = type ? reader.members(type) : [];\n const merged = new Map<string, { types: string[]; seen: number; optional: boolean; nullable: boolean }>();\n for (const member of members) {\n for (const property of reader.properties(member)) {\n const declared = reader.typeOf(property);\n const name = reader.nameOf(property);\n const column = merged.get(name) ?? { types: [], seen: 0, optional: false, nullable: false };\n const text = reader.text(reader.nonNullable(declared));\n if (!column.types.includes(text)) column.types.push(text);\n column.seen += 1;\n column.optional ||= reader.isOptional(property);\n column.nullable ||= reader.isNullable(declared);\n merged.set(name, column);\n }\n }\n if (merged.size === 0) return undefined;\n // A field a member of the union lacks may be left out of a row\n return [...merged].map(([name, column]) => ({\n name,\n type: column.types.join(' | '),\n optional: column.optional || column.seen < members.length,\n nullable: column.nullable,\n }));\n}\n\nfunction readWithCompilerApi(ts: typeof TS, schemaPath: string): Reading {\n const configPath = ts.findConfigFile(dirname(schemaPath), ts.sys.fileExists);\n const configured = configPath\n ? ts.parseJsonConfigFileContent(ts.readConfigFile(configPath, ts.sys.readFile).config, ts.sys, dirname(configPath))\n .options\n : {};\n const program = ts.createProgram([schemaPath], {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n ...configured,\n noEmit: true,\n skipLibCheck: true,\n strictNullChecks: true,\n allowImportingTsExtensions: true,\n types: [],\n });\n const checker = program.getTypeChecker();\n const file = program.getSourceFile(schemaPath);\n const module = file && checker.getSymbolAtLocation(file);\n const files = program\n .getSourceFiles()\n .filter((source) => !program.isSourceFileFromExternalLibrary(source) && !program.isSourceFileDefaultLibrary(source))\n .map((source) => source.fileName);\n if (configPath) files.push(configPath);\n if (!file || !module) return { columns: undefined, files };\n return {\n files,\n columns: columnsOf<TS.Type, TS.Symbol>({\n entryType() {\n const exports = checker.getExportsOfModule(module);\n let entry =\n exports.find((symbol) => symbol.name === 'schema') ?? exports.find((symbol) => symbol.name === 'default');\n if (entry && entry.flags & ts.SymbolFlags.Alias) entry = checker.getAliasedSymbol(entry);\n return entry && checker.getTypeOfSymbolAtLocation(entry, file);\n },\n property: (type, name) => type.getProperty(name),\n typeOf: (property) => checker.getTypeOfSymbol(property),\n nonNullable: (type) => checker.getNonNullableType(type),\n members: (type) => (type.flags & ts.TypeFlags.Union ? (type as TS.UnionType).types : [type]),\n properties: (type) => checker.getPropertiesOfType(type),\n nameOf: (property) => property.name,\n isOptional: (property) => Boolean(property.flags & ts.SymbolFlags.Optional),\n isNullable: (type) =>\n type.flags & ts.TypeFlags.Union\n ? (type as TS.UnionType).types.some((member) => member.flags & ts.TypeFlags.Null)\n : Boolean(type.flags & ts.TypeFlags.Null),\n text: (type) => checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation),\n }),\n };\n}\n\n// What of the Corsa API this reads: the unstable API of typescript@7.1, which the compiler API's types do not describe\ninterface CorsaSymbol {\n name: string;\n flags: number;\n}\ninterface CorsaType {\n flags: number;\n getProperty(name: string): CorsaSymbol | undefined;\n getTypes(): readonly CorsaType[] | undefined;\n}\ninterface CorsaChecker {\n getSymbolOfSourceFile(file: string): CorsaSymbol | undefined;\n getExportsOfModule(symbol: CorsaSymbol): readonly CorsaSymbol[];\n getTypeOfSymbol(symbol: CorsaSymbol): CorsaType;\n getNonNullableType(type: CorsaType): CorsaType;\n getPropertiesOfType(type: CorsaType): readonly CorsaSymbol[];\n typeToString(type: CorsaType): string;\n}\ninterface CorsaApi {\n createProgram(\n files: string[],\n options: Record<string, unknown>,\n ): { getProject(): { checker: CorsaChecker }; getSourceFileNames(): readonly string[] };\n close(): void;\n}\n\n/**\n * Whether a file of a program is one of the project's own, and not a library: those are in node_modules, or\n * have names that are not paths of the disk at all. Either kind of separator, as on Windows.\n */\nexport function isProjectSource(name: string): boolean {\n return win32.isAbsolute(name) && !/[\\\\/]node_modules[\\\\/]/.test(name);\n}\n\nfunction readWithCorsa(api: CorsaApi, schemaPath: string): Reading {\n try {\n // ESNext, Bundler and ESNext, as in the compiler API above\n const program = api.createProgram([schemaPath], {\n target: 99,\n module: 99,\n moduleResolution: 100,\n strict: true,\n skipLibCheck: true,\n noEmit: true,\n allowImportingTsExtensions: true,\n types: [],\n });\n const checker = program.getProject().checker;\n const files = program.getSourceFileNames().filter(isProjectSource);\n const module = checker.getSymbolOfSourceFile(schemaPath);\n if (!module) return { columns: undefined, files };\n return {\n files,\n columns: columnsOf<CorsaType, CorsaSymbol>({\n entryType() {\n const exports = checker.getExportsOfModule(module);\n const entry =\n exports.find((symbol) => symbol.name === 'schema') ?? exports.find((symbol) => symbol.name === 'default');\n return entry && checker.getTypeOfSymbol(entry);\n },\n property: (type, name) => type.getProperty(name),\n typeOf: (property) => checker.getTypeOfSymbol(property),\n nonNullable: (type) => checker.getNonNullableType(type),\n members: (type) => (type.flags & CORSA_UNION ? (type.getTypes() ?? [type]) : [type]),\n properties: (type) => checker.getPropertiesOfType(type),\n nameOf: (property) => property.name,\n isOptional: (property) => Boolean(property.flags & CORSA_OPTIONAL),\n isNullable: (type) =>\n type.flags & CORSA_UNION\n ? (type.getTypes() ?? []).some((member) => member.flags & CORSA_NULL)\n : Boolean(type.flags & CORSA_NULL),\n text: (type) => checker.typeToString(type),\n }),\n };\n } finally {\n api.close();\n }\n}\n\n/** The modification time of each file that can be read, which a reading is as fresh as */\nasync function stampsOf(files: string[]): Promise<Map<string, number>> {\n const stamps = new Map<string, number>();\n for (const file of new Set(files)) {\n try {\n stamps.set(file, (await stat(file)).mtimeMs);\n } catch {\n // Not on the disk: not something that can change it\n }\n }\n return stamps;\n}\n\nasync function isFresh(stamps: Map<string, number>): Promise<boolean> {\n for (const [file, mtimeMs] of stamps) {\n try {\n if ((await stat(file)).mtimeMs !== mtimeMs) return false;\n } catch {\n return false;\n }\n }\n return true;\n}\n\nconst cache = new Map<string, { columns: DeclaredColumn[] | undefined; stamps: Map<string, number> }>();\n\n/**\n * The columns a schema file declares, read from its types with the TypeScript installed from `searchFrom`:\n * the compiler API of typescript 5 and 6, or the Corsa API of typescript 7.1 and later. Undefined when there\n * is none, the schema declares no types or the file cannot be read, so the caller can fall back on the rows.\n */\nexport async function readDeclaredColumns(\n schemaPath: string,\n searchFrom: string,\n): Promise<DeclaredColumn[] | undefined> {\n try {\n // Not as given: the CLI passes the directory as it was typed, and createRequire takes only an absolute path\n const schemaFile = resolve(schemaPath);\n const from = resolve(searchFrom);\n const key = `${from}\\0${schemaFile}`;\n const cached = cache.get(key);\n if (cached && (await isFresh(cached.stamps))) return cached.columns;\n\n const require = createRequire(join(from, 'noop.js'));\n const { version } = require('typescript/package.json') as { version: string };\n let reading: Reading;\n if (Number.parseInt(version, 10) >= 7) {\n const { API } = (await import(pathToFileURL(require.resolve('typescript/sync')).href)) as {\n API: new (options: { cwd: string }) => CorsaApi;\n };\n reading = readWithCorsa(new API({ cwd: dirname(schemaFile) }), schemaFile);\n } else {\n reading = readWithCompilerApi(require('typescript') as typeof TS, schemaFile);\n }\n cache.set(key, { columns: reading.columns, stamps: await stampsOf([schemaFile, ...reading.files]) });\n return reading.columns;\n } catch {\n return undefined;\n }\n}\n","import type { JsonObject } from 'lines-db';\n\n/**\n * The content with the rows at the given indexes - counting the lines that hold a row, as reading\n * the file does - written over their lines, and every other line left as it was\n */\nexport function replaceRows(content: string, replaced: ReadonlyMap<number, JsonObject>): string {\n const bom = content.startsWith('\\u{feff}') ? '\\u{feff}' : '';\n let index = -1;\n const lines = content\n .slice(bom.length)\n .split('\\n')\n .map((raw) => {\n const carriage = raw.endsWith('\\r') ? '\\r' : '';\n if (raw.trim() === '') return raw;\n index += 1;\n const row = replaced.get(index);\n return row ? `${JSON.stringify(row)}${carriage}` : raw;\n });\n return bom + lines.join('\\n');\n}\n","import { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { watch } from 'node:fs';\nimport { readFile, realpath, writeFile } from 'node:fs/promises';\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { basename, extname, relative, resolve as resolvePath } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n LinesDB,\n DirectoryScanner,\n ErrorFormatter,\n unwrap,\n JsonlReader,\n findSchemaFile,\n type ColumnDefinition,\n type ForeignKeyDefinition,\n type JsonlConflictError,\n type JsonlParseError,\n type JsonObject,\n type JsonValue,\n type StandardSchemaIssue,\n type TableDefs,\n type ValidationError,\n type ValidationErrorDetail,\n type WriteFilledValues,\n} from 'lines-db';\nimport { hashJsonlContent, replaceFile } from 'lines-db/internal';\nimport { readDeclaredColumns } from './declared-columns.js';\nimport { replaceRows } from './file-rows.js';\n\nexport interface StudioServerOptions {\n dataDir: string | string[];\n schemaDir?: string;\n /** Directory holding the built page. Defaults to the one shipped with the package */\n uiDir?: string;\n /** Which values the schema fills in a save writes into the file. Defaults to 'primaryKey' */\n writeFilledValues?: WriteFilledValues;\n host?: string;\n port?: number;\n}\n\nexport interface StudioServer {\n url: string;\n /** The token every API request presents, generated at start-up and handed to the page */\n token: string;\n close(): Promise<void>;\n}\n\ninterface Snapshot {\n db: LinesDB<TableDefs>;\n /** Rows that failed validation on load, whose table is therefore left out */\n problems: string[];\n /**\n * The tables left out because rows failed validation, edited in their file instead: the database\n * holds only rows that passed, so a failing row cannot be fixed through it\n */\n invalid: Map<string, InvalidTable>;\n}\n\ninterface InvalidTable {\n file: string;\n rows?: JsonObject[];\n sources?: Array<{ file: string; rowIndex: number }>;\n files?: Array<{ file: string; content: string }>;\n revision?: string;\n /** The issues of each failing row, by its index among the rows of the file */\n issues: Map<number, StandardSchemaIssue[]>;\n}\n\nexport async function startStudioServer(options: StudioServerOptions): Promise<StudioServer> {\n const dataDirs: string[] = [];\n const seen = new Set<string>();\n for (const dir of [options.dataDir].flat()) {\n const resolved = resolvePath(dir);\n const actual = await realpath(resolved);\n if (seen.has(actual)) continue;\n seen.add(actual);\n dataDirs.push(resolved);\n }\n if (dataDirs.length === 0) throw new Error('Studio requires at least one data directory');\n const dataDir = dataDirs[0];\n const schemaDir = options.schemaDir ?? dataDir;\n const host = options.host ?? '127.0.0.1';\n const uiDir = options.uiDir ?? shippedUiDir();\n const token = randomBytes(24).toString('base64url');\n const writeFilledValues = options.writeFilledValues ?? 'primaryKey';\n const load = () => loadSnapshot(dataDirs, options.schemaDir, writeFilledValues);\n let snapshot = await load();\n\n let queue: Promise<unknown> = Promise.resolve();\n const serialize = <T>(fn: () => Promise<T>): Promise<T> => {\n const result = queue.then(fn);\n queue = result.catch(() => {});\n return result;\n };\n\n /** Reload the tables when a JSONL file no longer holds what they were read from; true if it did */\n const reloadUnlocked = async (): Promise<void> => {\n const previous = snapshot;\n snapshot = await load();\n await previous.db.close();\n };\n const reloadIfChangedUnlocked = async (): Promise<boolean> => {\n if (!unwrap(await snapshot.db.hasExternalChanges())) return false;\n await reloadUnlocked();\n notifyChanged();\n return true;\n };\n\n // Not found again on each listing: what the schema takes is the same until the files are read again,\n // and finding it reads the table's file for a sample row\n type Columns = ReturnType<typeof withLeeway<ColumnDefinition>>;\n const leeway = new WeakMap<Snapshot, Map<string, Columns>>();\n const loadedColumnsOf = async (current: Snapshot, name: string): Promise<Columns> => {\n const byTable = leeway.get(current) ?? new Map<string, Columns>();\n leeway.set(current, byTable);\n if (!byTable.has(name)) {\n const [sample] = unwrap(await current.db.findWithDefaults(name));\n const columns = current.db.getSchema(name)?.columns ?? [];\n byTable.set(name, withLeeway(current.db, name, sample?.row as JsonObject | undefined, columns));\n }\n return byTable.get(name)!;\n };\n // Not read on each listing: a table with no foreign keys in the database has them read from its schema\n // file, imported anew each time, and they stay the same until the files are read again\n type References = Awaited<ReturnType<typeof referencesOf>>;\n const references = new WeakMap<Snapshot, Map<string, References>>();\n const referencesFor = async (current: Snapshot, name: string): Promise<References> => {\n const byTable = references.get(current) ?? new Map<string, References>();\n references.set(current, byTable);\n if (!byTable.has(name)) byTable.set(name, await referencesOf(current.db, schemaDir, name));\n return byTable.get(name)!;\n };\n // Not found on each listing either for a table whose rows fail validation: finding it validates rows\n const invalidColumns = new WeakMap<Snapshot, Map<string, { columns: Columns; rowCount: number }>>();\n const invalidColumnsOf = async (current: Snapshot, name: string): Promise<{ columns: Columns; rowCount: number }> => {\n const byTable = invalidColumns.get(current) ?? new Map<string, { columns: Columns; rowCount: number }>();\n invalidColumns.set(current, byTable);\n if (!byTable.has(name)) {\n const invalid = current.invalid.get(name)!;\n const { issues } = invalid;\n const rows = invalid.rows ?? unwrap(await JsonlReader.read(invalid.file));\n const unknown = unknownFields(current.db, name, rows, issues);\n const inferred = unwrap(JsonlReader.inferSchema(name, rows)).columns;\n // A field no row holds - a required one every row lacks - has no column to fill it in otherwise;\n // its type is unknown, so it is edited as JSON, which takes any value\n const missing = [...new Set([...issues.values()].flat().map(fieldOf))].filter(\n (field): field is string => field !== undefined && !inferred.some((column) => column.name === field),\n );\n const columns = withLeeway(current.db, name, rows.find((_, index) => !issues.has(index)) ?? rows[0], [\n ...inferred,\n ...missing.map((field) => ({ name: field, type: 'JSON' as const, notNull: false, primaryKey: false })),\n ]).map((column) => ({ ...column, primaryKey: false, ...(unknown.has(column.name) ? { unknown: true } : {}) }));\n byTable.set(name, { columns, rowCount: rows.length });\n }\n return byTable.get(name)!;\n };\n\n const eventClients = new Set<ServerResponse>();\n const notifyChanged = (): void => {\n for (const client of eventClients) client.write('event: changed\\ndata: {}\\n\\n');\n };\n\n let watchTimer: NodeJS.Timeout | undefined;\n // Not checking on each event: an editor saving a file fires several (a temporary file, then a rename)\n const watchers = [...new Set([...dataDirs, resolvePath(schemaDir)])].flatMap((dir) => {\n try {\n const watcher = watch(dir, () => {\n clearTimeout(watchTimer);\n watchTimer = setTimeout(() => {\n // Not reporting the error here: the page asks again on 'changed' and shows the error it gets\n reloadIfChanged().catch(notifyChanged);\n }, 100);\n });\n // Not letting the error end the process: Reload still loads the current files without the watcher\n watcher.on('error', (error) => {\n console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);\n watcher.close();\n });\n return [watcher];\n } catch (error) {\n console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);\n return [];\n }\n });\n const reloadIfChanged = (): Promise<boolean> => serialize(reloadIfChangedUnlocked);\n\n const server = createServer((req, res) => {\n handle(req, res).catch((error) =>\n sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }),\n );\n });\n\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const { port } = server.address() as AddressInfo;\n const allowedHosts = new Set([`${host}:${port}`, `127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);\n if (!allowedHosts.has(req.headers.host ?? '')) {\n sendJson(res, 403, { message: 'Requests must be addressed to the local studio server' });\n return;\n }\n\n const url = new URL(req.url ?? '/', 'http://localhost');\n\n // Not behind the token: the page has to load before it holds one. Another site cannot read the page,\n // so the token it carries keeps that site's requests out\n if (req.method === 'GET' && !url.pathname.startsWith('/api/')) {\n await servePage(res, uiDir, url.pathname, token);\n return;\n }\n // Not taken from the query elsewhere: an event source cannot send headers, but a fetch can\n const presented = bearerToken(req) ?? (url.pathname === '/api/events' ? url.searchParams.get('token') : null) ?? '';\n if (!sameToken(presented, token)) {\n sendJson(res, 401, {\n message: 'This page holds no token of this run of lines-db studio. Reload it to get one.',\n });\n return;\n }\n const segments = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);\n\n if (req.method === 'GET' && url.pathname === '/api/events') {\n res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' });\n res.write(': connected\\n\\n');\n eventClients.add(res);\n req.on('close', () => eventClients.delete(res));\n return;\n }\n\n if (req.method === 'GET' && url.pathname === '/api/tables') {\n // Not left open to a reload between its awaits: one would close the database the listing reads\n const listing = await serialize(async () => {\n await reloadIfChangedUnlocked();\n const current = snapshot;\n // Not listed as loaded when rows failed a constraint on load: its passing rows are in the database,\n // but its rows are fixed in the file, by index\n const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));\n const tables = [];\n for (const name of loadedTables) {\n const columns = await loadedColumnsOf(current, name);\n const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;\n const rowCount =\n unwrap(current.db.queryOne<{ n: number }>(`SELECT COUNT(*) AS n FROM \"${name.replaceAll('\"', '\"\"')}\"`))\n ?.n ?? 0;\n tables.push({\n name,\n columns,\n primaryKey,\n rowCount,\n invalidRows: 0,\n readOnlyReason: whyReadOnly(current.db, name),\n schemaFile: null as string | null,\n references: await referencesFor(current, name),\n });\n }\n for (const [name, { issues }] of current.invalid) {\n const { columns, rowCount } = await invalidColumnsOf(current, name);\n tables.push({\n name,\n columns,\n primaryKey: null,\n rowCount,\n invalidRows: issues.size,\n readOnlyReason: null,\n schemaFile: null,\n references: await referencesFor(current, name),\n });\n }\n for (const table of tables) {\n const schemaPath = await findSchemaFile(schemaDir, table.name);\n table.schemaFile = schemaPath ? basename(schemaPath) : null;\n }\n tables.sort((a, b) => a.name.localeCompare(b.name));\n return {\n dataDir,\n dataDirs,\n schemaDir: resolvePath(schemaDir),\n tables,\n problems: current.problems,\n };\n });\n sendJson(res, 200, listing);\n return;\n }\n\n const [, , tableName, resource, encodedKey] = segments;\n if (segments[0] === 'api' && segments[1] === 'tables' && resource === 'schema' && segments.length === 4) {\n if (req.method !== 'GET') {\n sendJson(res, 405, { message: 'Method not allowed' });\n return;\n }\n await reloadIfChanged();\n // Not looked up for a name that is not a table: the name would otherwise reach the file system as is\n const known = Boolean(snapshot.db.getSchema(tableName)) || snapshot.invalid.has(tableName);\n const schemaPath = known ? await findSchemaFile(schemaDir, tableName) : undefined;\n if (!schemaPath) {\n sendJson(res, 404, { message: `Table '${tableName}' has no schema file` });\n return;\n }\n const loaded = snapshot.invalid.has(tableName) ? undefined : snapshot.db.getSchema(tableName);\n const declared = loaded && (await readDeclaredColumns(schemaPath, schemaDir));\n const flagsOf = (name: string) => {\n const column = loaded?.columns.find((candidate) => candidate.name === name);\n return { ...(column?.primaryKey ? { primaryKey: true } : {}), ...(column?.unique ? { unique: true } : {}) };\n };\n sendJson(res, 200, {\n file: basename(schemaPath),\n source: await readFile(schemaPath, 'utf-8'),\n definition: loaded\n ? {\n // Declared when the types of the schema can be read, as the columns the database holds are inferred\n // from the values of the rows: a field left out of every row is missing, and one in every row is not null\n columnsFrom: declared ? 'schema' : 'rows',\n columns: declared\n ? declared.map((column) => ({ ...column, ...flagsOf(column.name) }))\n : loaded.columns.map((column) => ({\n name: column.name,\n type: column.valueType ?? column.type,\n ...(column.notNull ? { notNull: true } : {}),\n ...flagsOf(column.name),\n })),\n foreignKeys: loaded.declaredForeignKeys ?? [],\n indexes: loaded.indexes ?? [],\n }\n : null,\n });\n return;\n }\n const isRows = segments[0] === 'api' && segments[1] === 'tables' && resource === 'rows' && segments.length <= 5;\n const isChanges =\n segments[0] === 'api' &&\n segments[1] === 'tables' &&\n (resource === 'changes' || resource === 'check') &&\n segments.length === 4;\n if (!isRows && !isChanges) {\n sendJson(res, 404, { message: 'Not found' });\n return;\n }\n\n if (isRows && req.method === 'GET' && encodedKey === undefined) {\n await reloadIfChanged();\n const invalid = snapshot.invalid.get(tableName);\n if (invalid) {\n if (invalid.rows) {\n sendJson(res, 200, {\n rows: invalid.rows,\n defaulted: invalid.rows.map(() => []),\n issues: Object.fromEntries(invalid.issues),\n revision: invalid.revision,\n });\n return;\n }\n const { rows, contentHash } = unwrap(await JsonlReader.readSnapshot(invalid.file));\n const read = unwrap(rows);\n sendJson(res, 200, {\n rows: read,\n defaulted: read.map(() => []),\n issues: Object.fromEntries(invalid.issues),\n revision: contentHash,\n });\n return;\n }\n if (!snapshot.db.getSchema(tableName)) {\n sendJson(res, 404, { message: `Table '${tableName}' does not exist` });\n return;\n }\n const rows = unwrap(await snapshot.db.findWithDefaults(tableName));\n sendJson(res, 200, { rows: rows.map(({ row }) => row), defaulted: rows.map(({ defaulted }) => defaulted) });\n return;\n }\n\n const write = isChanges\n ? req.method === 'POST'\n ? resource === 'check'\n ? ({ kind: 'check' } as const)\n : ({ kind: 'batch' } as const)\n : undefined\n : writeOperation(req.method, encodedKey);\n if (!write) {\n sendJson(res, 405, { message: 'Method not allowed' });\n return;\n }\n const origin = req.headers.origin;\n if (origin !== undefined && !allowedHosts.has(origin.replace(/^http:\\/\\//, ''))) {\n sendJson(res, 403, { message: 'Writes are accepted from the studio page only' });\n return;\n }\n if (write.kind !== 'delete' && !isJsonMediaType(req.headers['content-type'])) {\n sendJson(res, 415, { message: 'Writes must be sent as application/json' });\n return;\n }\n let batch: ChangeBatch;\n if (write.kind === 'batch' || write.kind === 'check') {\n batch = changeBatch(await readJson(req));\n } else if (write.kind === 'delete') {\n batch = { inserts: [], updates: [], deletes: [write.key] };\n } else {\n const body = writeBody(await readJson(req));\n batch =\n write.kind === 'insert'\n ? {\n inserts: [body.row ?? {}],\n insertDataDirs: body.dataDir ? [body.dataDir] : undefined,\n updates: [],\n deletes: [],\n }\n : {\n inserts: [],\n updates: [{ key: write.key, changes: body.changes ?? {}, resetToDefault: body.resetToDefault }],\n deletes: [],\n };\n }\n\n if (\n dataDirs.length > 1 &&\n batch.inserts.some((_, index) => {\n const dir = batch.insertDataDirs?.[index];\n return !dir || !dataDirs.includes(resolvePath(dir));\n })\n )\n throw new BadRequestError('Choose a data directory for each inserted row');\n\n type Outcome = { status: number; body: unknown; changed?: boolean };\n /** Apply the updates to the rows of the file, and write them only once every edited row passes */\n const writeInvalidTable = async (invalid: InvalidTable): Promise<Outcome> => {\n const { file } = invalid;\n if (batch.inserts.length > 0 || batch.deletes.length > 0) {\n const message = 'Fix the rows that fail validation before adding or deleting rows of this table';\n return { status: 409, body: { message } };\n }\n const files = await Promise.all(\n (invalid.files ?? [{ file }]).map(async ({ file }) => ({\n file,\n content: await readFile(file, 'utf8'),\n })),\n );\n const content = files[0].content;\n const revision =\n files.length > 1 || invalid.files ? hashJsonlContent(JSON.stringify(files)) : hashJsonlContent(content);\n // Not left to the watcher: once it reloads, the file it compares against is the changed one, while\n // the page still addresses rows by where they stood when it read them\n if (batch.revision !== revision) {\n const message =\n files.length > 1\n ? 'Source files changed since their rows were read; reload the table to see them'\n : `${relative(dataDir, file)} changed since its rows were read; reload the table to see them`;\n return { status: 409, body: { message } };\n }\n const rows = invalid.rows ?? unwrap(await JsonlReader.read(file));\n const replaced = new Map<number, JsonObject>();\n for (const [index, { key, changes, resetToDefault }] of batch.updates.entries()) {\n // An earlier update of the same row in the batch is built on, as a transaction would apply it\n const base = typeof key === 'number' ? (replaced.get(key) ?? rows[key]) : undefined;\n if (!base)\n return { status: 400, body: { message: `No row ${JSON.stringify(key)} in ${relative(dataDir, file)}` } };\n const next: JsonObject = { ...base, ...changes };\n for (const field of resetToDefault ?? []) delete next[field];\n const validated = snapshot.db.validateRow(tableName, next);\n if (!validated.ok) {\n const change: FailedChange = { kind: 'update', index, key };\n const failure = { message: validated.error.message, issues: perKey(validated.error.issues), change };\n return write.kind === 'check'\n ? { status: 200, body: { ok: false, ...failure } }\n : { status: 400, body: failure };\n }\n replaced.set(key as number, next);\n }\n if (write.kind === 'check') return { status: 200, body: { ok: true } };\n const plans = files\n .map(({ file, content }) => {\n const changes = new Map<number, JsonObject>();\n for (const [index, row] of replaced) {\n const source = invalid.sources?.[index] ?? { file: invalid.file, rowIndex: index };\n if (source.file === file) changes.set(source.rowIndex, row);\n }\n return { file, content, next: replaceRows(content, changes), changed: changes.size > 0 };\n })\n .filter((plan) => plan.changed);\n const written: typeof plans = [];\n try {\n for (const plan of plans) {\n await replaceUnchangedFile(plan.file, plan.next, plan.content);\n written.push(plan);\n }\n } catch (error) {\n const unrestored: string[] = [];\n for (const plan of written) {\n await replaceUnchangedFile(plan.file, plan.content, plan.next).catch(() => unrestored.push(plan.file));\n }\n if (unrestored.length)\n throw new Error(`${errorMessage(error)}; could not restore ${unrestored.join(', ')}`, { cause: error });\n if (error instanceof Error && error.name === 'JsonlConflictError') {\n await reloadUnlocked();\n return { status: 409, body: { message: error.message }, changed: true };\n }\n throw error;\n }\n await reloadUnlocked();\n // Not refused before writing: a foreign key is checked on load only, so the edited rows that still\n // fail are reported once the tables are loaded again\n const stillFailing = [...replaced.keys()]\n .map((index) => ({ index, issues: snapshot.invalid.get(tableName)?.issues.get(index) ?? [] }))\n .filter(({ issues }) => issues.length > 0);\n return { status: 200, body: { ok: true, ...(stillFailing.length > 0 ? { stillFailing } : {}) }, changed: true };\n };\n\n let reloaded = false;\n const outcome = await serialize(async (): Promise<Outcome> => {\n // Not left to the watcher: its event may not have fired yet, and a changed schema file is no\n // conflict a write-back detects, so the rows would be validated against the old schema\n const changedFiles = unwrap(await snapshot.db.findExternalChanges());\n if (changedFiles.length > 0) {\n await reloadUnlocked();\n reloaded = true;\n if (write.kind === 'check') changedFiles.length = 0;\n // Not saved over an outside edit of the edited table's own file: the change was made on rows\n // the page showed before that edit\n // A changed schema file of the edited table counts too: its primary key may name another column\n const ownFile = changedFiles.find(\n (file) =>\n dataDirs.some((dir) => resolvePath(file) === resolvePath(dir, `${tableName}.jsonl`)) ||\n basename(file).startsWith(`${tableName}.schema.`),\n );\n if (ownFile) {\n const message = `${relative(dataDir, ownFile) || ownFile} changed on disk, so the tables were reloaded. Check the rows and try again.`;\n return { status: 409, body: { message }, changed: true };\n }\n }\n const { db } = snapshot;\n const invalid = snapshot.invalid.get(tableName);\n if (invalid) return writeInvalidTable(invalid);\n const schema = db.getSchema(tableName);\n if (!schema) return { status: 404, body: { message: `Table '${tableName}' does not exist` } };\n const primaryKey = schema.columns.find((column) => column.primaryKey)?.name;\n const reason = whyReadOnly(db, tableName);\n if (!primaryKey || reason) return { status: 409, body: { message: reason } };\n\n const result = await db.transaction((tx) => {\n const check = (written: { ok: boolean; error?: Error }, change: FailedChange) => {\n if (!written.ok) throw Object.assign(written.error!, { change });\n };\n batch.deletes.forEach((key, index) =>\n check(tx.delete(tableName, { [primaryKey]: key }), { kind: 'delete', index, key }),\n );\n batch.updates.forEach(({ key, changes, resetToDefault }, index) =>\n check(tx.update(tableName, changes, { [primaryKey]: key }, { resetToDefault }), {\n kind: 'update',\n index,\n key,\n }),\n );\n batch.inserts.forEach((row, index) =>\n check(tx.insert(tableName, row, { dataDir: batch.insertDataDirs?.[index] }), { kind: 'insert', index }),\n );\n // Not committed when only checking: throwing rolls the transaction back before anything is written\n if (write.kind === 'check') throw DRY_RUN;\n });\n if (write.kind === 'check') {\n if (!result.ok && result.error === DRY_RUN) return { status: 200, body: { ok: true } };\n const failure = (result.ok ? {} : result.error) as Partial<ValidationError> & { change?: FailedChange };\n return {\n status: 200,\n body: {\n ok: false,\n message: failure.message,\n issues: perKey(failure.issues ?? []),\n ...(failure.change ? { change: failure.change } : {}),\n },\n };\n }\n if (!result.ok) {\n if (result.error.name === 'JsonlConflictError') {\n await reloadUnlocked();\n const { file } = result.error as JsonlConflictError;\n const message = `${relative(dataDir, file) || file} changed on disk, so the tables were reloaded. Check the rows and try again.`;\n return { status: 409, body: { message }, changed: true };\n }\n const { issues, change } = result.error as Partial<ValidationError> & { change?: FailedChange };\n return {\n status: 400,\n body: {\n message: result.error.message,\n ...(issues ? { issues: perKey(issues) } : {}),\n ...(change ? { change } : {}),\n },\n };\n }\n return { status: write.kind === 'insert' ? 201 : 200, body: { ok: true }, changed: true };\n });\n sendJson(res, outcome.status, outcome.body);\n // Not before the response: the page that saved would still be in its editor when the event arrives\n // Not only when the outcome says so: the watcher finds nothing left to reload once this did\n if (outcome.changed || reloaded) notifyChanged();\n }\n\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(options.port ?? 4848, host, () => {\n server.off('error', reject);\n resolve();\n });\n });\n } catch (error) {\n watchers.forEach((watcher) => watcher.close());\n await snapshot.db.close();\n throw error;\n }\n const { port } = server.address() as AddressInfo;\n\n const url = `http://${host.includes(':') ? `[${host}]` : host}:${port}`;\n return {\n url,\n token,\n close: async () => {\n watchers.forEach((watcher) => watcher.close());\n clearTimeout(watchTimer);\n server.closeAllConnections();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n await serialize(() => snapshot.db.close());\n },\n };\n}\n\nasync function replaceUnchangedFile(file: string, next: string, expected: string): Promise<void> {\n await replaceFile(file, (temporary) => writeFile(temporary, next, 'utf8'), expected);\n}\n\nasync function loadSnapshot(\n dataDir: string | string[],\n schemaDir: string | undefined,\n writeFilledValues: WriteFilledValues,\n): Promise<Snapshot> {\n const db = LinesDB.create<TableDefs>({ dataDir, schemaDir, writeFilledValues, writeDataSets: true });\n const baseDir = [dataDir].flat()[0];\n // Not the bulk insert: a foreign key or NOT NULL violation would fail the whole load instead of\n // marking the row, which the studio then cannot show to be fixed\n const loaded = await db.initialize({ detailedValidate: true });\n if (!loaded.ok) {\n await db.close();\n if (loaded.error.name === 'JsonlParseError') {\n const { file, line, message } = loaded.error as JsonlParseError;\n throw new Error(`${relative(baseDir, file) || file}:${line}: ${message}`, { cause: loaded.error });\n }\n throw loaded.error;\n }\n return {\n db,\n problems: describeProblems(baseDir, loaded.value.errors),\n invalid:\n typeof dataDir !== 'string' && dataDir.length > 1\n ? await composedInvalidTables(dataDir, loaded.value.errors)\n : invalidTables(loaded.value.errors),\n };\n}\n\n/**\n * Each column with whether the schema lets it be null and lets the key be left out. A schema does not\n * list what it takes, so a row is validated with the field set to null and with the key removed, and\n * the column counts as taking it when no issue is about that field; an issue about another field is\n * the row's own and says nothing of this one\n */\nfunction withLeeway<Column extends { name: string; type?: string; notNull?: boolean }>(\n db: LinesDB<TableDefs>,\n tableName: string,\n sample: JsonObject | undefined,\n columns: Column[],\n): Array<Column & { nullable: boolean; optional: boolean; nested?: Record<string, NestedLeeway> }> {\n const probe = prober(db, tableName, sample ?? {});\n return columns.map((column) => {\n const { [column.name]: _removed, ...without } = sample ?? {};\n const value = sample?.[column.name];\n // Not taken on the schema's word alone for a NOT NULL column: the row is written as the schema leaves it\n // Not taken while the field still fails: a sample failing for it already, as with no row that passes,\n // has its issue among the sample's, so the change brings no new one\n const takes = (row: JsonObject) => {\n const { taken, value: validated, failsAt } = probe(row);\n return taken && !failsAt([column.name]) && (!column.notNull || (validated?.[column.name] ?? null) !== null);\n };\n return {\n ...column,\n nullable: takes({ ...without, [column.name]: null }),\n optional: takes(without),\n ...(sample && value !== null && typeof value === 'object'\n ? { nested: nestedLeeway(db, tableName, sample, column.name) }\n : {}),\n };\n });\n}\n\n/**\n * Whether the schema takes a change of the sample row: it does when the change brings no issue the\n * sample did not have. Not only an issue about the field changed counts, as a check across fields\n * reports on another field, or on the row as a whole\n */\nfunction prober(db: LinesDB<TableDefs>, tableName: string, sample: JsonObject) {\n const issuesOf = (result: ReturnType<typeof tryValidate>) =>\n !result ? undefined : result.ok ? [] : perKey(result.error.issues).map((issue) => JSON.stringify(issue));\n const before = new Set(issuesOf(tryValidate(db, tableName, sample)));\n return (\n row: JsonObject,\n ): { taken: boolean; value?: JsonObject; failsAt: (path: Array<string | number>) => boolean } => {\n const result = tryValidate(db, tableName, row);\n const taken = issuesOf(result)?.every((issue) => before.has(issue)) ?? false;\n const paths = result && !result.ok ? perKey(result.error.issues).map((issue) => (issue.path ?? []).map(keyOf)) : [];\n // Whether an issue is about the value at the path or one inside it\n const failsAt = (path: Array<string | number>) =>\n paths.some((at) => path.every((segment, index) => at[index] === String(segment)));\n return { taken, value: result?.ok ? result.value : undefined, failsAt };\n };\n}\n\n/**\n * The foreign keys of a table, as the row form opens the row a key refers to by them. Read from its\n * schema file first: the database leaves out a key to a table whose rows failed on load, and has no\n * schema at all for a table whose own rows failed, though the studio lists those tables and their rows\n */\nasync function referencesOf(db: LinesDB<TableDefs>, dataDir: string, tableName: string) {\n const declared = await foreignKeysInFile(dataDir, tableName);\n const foreignKeys = declared.length > 0 ? declared : (db.getSchema(tableName)?.foreignKeys ?? []);\n return foreignKeys.map((fk) => ({\n column: fk.column,\n table: fk.references.table,\n referencedColumn: fk.references.column,\n }));\n}\n\n/** The foreign keys a table's schema file exports, as the database reads them on load */\nasync function foreignKeysInFile(dataDir: string, tableName: string): Promise<ForeignKeyDefinition[]> {\n const schemaPath = await findSchemaFile(dataDir, tableName);\n if (!schemaPath) return [];\n try {\n const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);\n const exported = module.schema ?? module.default;\n return exported?.foreignKeys ?? module.foreignKeys ?? [];\n } catch {\n // Not failing the listing: the file failed to load on start too, and its problem is listed there\n return [];\n }\n}\n\n/**\n * The row validated, or undefined when the schema threw: a schema can assume a value the change took\n * away, such as reading the keys of an object removed, and that says it does not take the change\n */\nfunction tryValidate(db: LinesDB<TableDefs>, tableName: string, row: JsonObject) {\n try {\n return db.validateRow(tableName, row);\n } catch {\n return undefined;\n }\n}\n\n/** What the schema takes of an object inside a JSON value: keys it does not name, and leaving a key out */\ninterface NestedLeeway {\n open?: boolean;\n optional?: boolean;\n}\n\n/** A key no schema names, added to an object to see whether the schema takes keys it does not name */\nconst PROBE_KEY = '__lines_db_studio_probe__';\n\n/**\n * What the schema takes of each object inside the sample's value of a JSON column, by its path there\n * with list indexes as `*` (`''` for the value itself, `items.*.name` for a key of each item, and\n * `%`, `.` and `*` in a key as `%25`, `%2E` and `%2A`). Found as\n * for a column, from the issues a change brings that the sample did not have: a key added to an object\n * tells whether it takes keys it does not name, and a key removed whether it can be left out. The\n * items of a list are changed together in one check, so what one of them refuses counts as refused for all\n */\nfunction nestedLeeway(\n db: LinesDB<TableDefs>,\n tableName: string,\n sample: JsonObject,\n column: string,\n): Record<string, NestedLeeway> {\n const probe = prober(db, tableName, sample);\n // Not one object at a time: the items of a list share a pattern, so all of them are changed in one check,\n // and one an item refuses is refused for all\n const atAll = (paths: Array<Array<string | number>>, change: (object: JsonObject) => JsonObject) =>\n ({\n ...sample,\n [column]: paths.reduce((value, path) => changeAt(value, path, change), sample[column]),\n }) as JsonObject;\n\n const objects = new Map<string, Array<{ path: Array<string | number>; object: JsonObject }>>();\n const walk = (value: JsonValue | undefined, path: Array<string | number>, pattern: string[]) => {\n if (Array.isArray(value)) {\n value.forEach((item, index) => walk(item, [...path, index], [...pattern, '*']));\n return;\n }\n if (value === null || typeof value !== 'object') return;\n const key = pattern.join('.');\n objects.set(key, [...(objects.get(key) ?? []), { path, object: value }]);\n for (const [name, item] of Object.entries(value)) walk(item, [...path, name], [...pattern, segmentOf(name)]);\n };\n walk(sample[column], [], []);\n\n const leeway: Record<string, NestedLeeway> = {};\n for (const [pattern, found] of objects) {\n const prefix = pattern === '' ? '' : `${pattern}.`;\n // Not tried on an empty object: with no value of its own to give a new key, any value tried may be refused\n const filled = found.filter(({ object }) => Object.keys(object).length > 0);\n if (filled.length > 0) {\n // Not the probe key alone: an object may hold it already, and then it is changed rather than added\n let added = PROBE_KEY;\n while (filled.some(({ object }) => Object.hasOwn(object, added))) added += '_';\n const open = probe(\n atAll(\n filled.map(({ path }) => path),\n (object) => ({ ...object, [added]: Object.values(object)[0] }),\n ),\n ).taken;\n leeway[pattern] = { open };\n }\n const keys = new Set(found.flatMap(({ object }) => Object.keys(object)));\n for (const name of keys) {\n const holding = found.filter(({ object }) => Object.hasOwn(object, name)).map(({ path }) => path);\n const { taken, failsAt } = probe(\n atAll(holding, (object) => {\n const { [name]: _removed, ...rest } = object;\n return rest;\n }),\n );\n // Not taken while the key still fails: a sample failing for it already has its issue among the sample's\n const optional = taken && !holding.some((path) => failsAt([column, ...path, name]));\n leeway[`${prefix}${segmentOf(name)}`] = { ...leeway[`${prefix}${segmentOf(name)}`], optional };\n }\n }\n return leeway;\n}\n\n/** A key as a segment of a pattern, apart from the dots between segments and the `*` of a list index */\nconst segmentOf = (key: string) => key.replace(/[%.*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n\n/** The value with the object at the path inside it changed */\nfunction changeAt(\n value: JsonValue | undefined,\n path: Array<string | number>,\n change: (object: JsonObject) => JsonObject,\n): JsonValue {\n if (path.length === 0) return change(value as JsonObject);\n const [head, ...rest] = path;\n if (Array.isArray(value)) return value.map((item, index) => (index === head ? changeAt(item, rest, change) : item));\n const object = value as JsonObject;\n return { ...object, [head]: changeAt(object[head], rest, change) };\n}\n\n/**\n * The issues with one about several refused keys split per key. Zod reports the keys a strict object\n * refuses in one issue at the path of the object and the keys beside it, which no field would be found\n * by, nor a key inside a JSON value\n */\nfunction perKey(issues: readonly StandardSchemaIssue[]): StandardSchemaIssue[] {\n return issues.flatMap((issue) => {\n const { code, keys } = issue as { code?: unknown; keys?: unknown };\n if (code !== 'unrecognized_keys' || !Array.isArray(keys)) return [issue];\n if (keys.length === 0 || !keys.every((key) => typeof key === 'string')) return [issue];\n return keys.map((key) => ({ ...issue, keys: [key], path: [...(issue.path ?? []), { key }] }));\n });\n}\n\n/** A segment of an issue's path as the key it names */\nconst keyOf = (segment: PropertyKey | { key: PropertyKey }) =>\n typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n\n/** The field of the row an issue is about, if it is about one */\nfunction fieldOf(issue: StandardSchemaIssue): string | undefined {\n const segment = issue.path?.[0];\n if (segment === undefined) return undefined;\n return typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n}\n\n/**\n * The fields of a table's rows its schema refuses as keys, which a fix can only remove. A schema does\n * not list its keys, so a field counts when removing it from each row it fails on clears its issues,\n * and no row that passes keeps it: removing a known optional field holding a wrong value clears its\n * issue too, but a passing row then has it\n */\nfunction unknownFields(\n db: LinesDB<TableDefs>,\n tableName: string,\n rows: JsonObject[],\n issues: Map<number, StandardSchemaIssue[]>,\n): Set<string> {\n const failingOn = new Map<string, number[]>();\n for (const [index, rowIssues] of issues) {\n for (const issue of rowIssues) {\n const key = fieldOf(issue);\n if (key !== undefined && Object.hasOwn(rows[index] ?? {}, key))\n failingOn.set(key, [...(failingOn.get(key) ?? []), index]);\n }\n }\n const kept = new Set<string>();\n rows.forEach((row, index) => {\n if (issues.has(index)) return;\n const validated = tryValidate(db, tableName, row);\n if (validated?.ok) for (const key of Object.keys(validated.value)) kept.add(key);\n });\n const unknown = new Set<string>();\n for (const [key, indexes] of failingOn) {\n if (kept.has(key)) continue;\n const clears = indexes.every((index) => {\n const { [key]: _removed, ...rest } = rows[index];\n // Not counted as clearing it when the schema throws without the key: it relies on the key being there\n const result = tryValidate(db, tableName, rest);\n return (\n result !== undefined && (result.ok || !perKey(result.error.issues).some((issue) => fieldOf(issue) === key))\n );\n });\n if (clears) unknown.add(key);\n }\n return unknown;\n}\n\n/** The tables whose failing rows all come from one file, which can then be edited line by line */\nfunction invalidTables(errors: ValidationErrorDetail[]): Map<string, InvalidTable> {\n const tables = new Map<string, InvalidTable | null>();\n for (const error of errors) {\n const known = tables.get(error.tableName);\n if (known === null) continue;\n if (known && known.file !== error.file) {\n tables.set(error.tableName, null);\n continue;\n }\n const table = known ?? { file: error.file, issues: new Map() };\n const foreignKey = error.foreignKeyError;\n const issues: StandardSchemaIssue[] = foreignKey\n ? [\n {\n message: `No ${foreignKey.referencedTable} row has ${foreignKey.referencedColumn} ${JSON.stringify(foreignKey.value)}`,\n path: [{ key: foreignKey.column }],\n },\n ]\n : perKey(error.issues);\n table.issues.set(error.rowIndex, [...(table.issues.get(error.rowIndex) ?? []), ...issues]);\n tables.set(error.tableName, table);\n }\n return new Map([...tables].filter((entry): entry is [string, InvalidTable] => entry[1] !== null));\n}\n\nasync function composedInvalidTables(\n dataDirs: string[],\n errors: ValidationErrorDetail[],\n): Promise<Map<string, InvalidTable>> {\n const tables = await DirectoryScanner.scanDirectory(dataDirs);\n const invalid = new Map<string, InvalidTable>();\n for (const name of new Set(errors.map((error) => error.tableName))) {\n const config = tables.get(name)!;\n const rows: JsonObject[] = [];\n const adjusted: ValidationErrorDetail[] = [];\n const files: Array<{ file: string; content: string }> = [];\n const sources: Array<{ file: string; rowIndex: number }> = [];\n for (const file of config.jsonlPaths ?? [config.jsonlPath]) {\n const offset = rows.length;\n const read = unwrap(await JsonlReader.read(file));\n files.push({ file, content: await readFile(file, 'utf8') });\n sources.push(...read.map((_, rowIndex) => ({ file, rowIndex })));\n rows.push(...read);\n adjusted.push(\n ...errors\n .filter((error) => error.tableName === name && error.file === file)\n .map((error) => ({ ...error, file: config.jsonlPath, rowIndex: offset + error.rowIndex })),\n );\n }\n const table = invalidTables(adjusted).get(name)!;\n invalid.set(name, { ...table, rows, files, sources, revision: hashJsonlContent(JSON.stringify(files)) });\n }\n return invalid;\n}\n\nfunction describeProblems(dataDir: string, errors: ValidationErrorDetail[]): string[] {\n const formatter = new ErrorFormatter();\n return errors.map((error) => {\n const file = relative(dataDir, error.file) || error.file;\n const foreignKey = error.foreignKeyError;\n return foreignKey\n ? formatter.formatForeignKeyError({ file, rowIndex: error.rowIndex, ...foreignKey })\n : formatter.formatValidationErrors([{ file, rowIndex: error.rowIndex, issues: error.issues }]);\n });\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.json': 'application/json; charset=utf-8',\n};\n\nfunction shippedUiDir(): string {\n return fileURLToPath(new URL('../ui', import.meta.url));\n}\n\n/** Serve a file of the built page, the page itself carrying the token */\nasync function servePage(res: ServerResponse, uiDir: string, pathname: string, token: string): Promise<void> {\n // Not only `/`: the same page is reachable as /index.html, and must carry the token and stay uncached there too\n const isPage = pathname === '/' || pathname === '/index.html';\n const file = resolvePath(uiDir, `.${isPage ? '/index.html' : pathname}`);\n if (relative(uiDir, file).startsWith('..')) {\n sendJson(res, 404, { message: 'Not found' });\n return;\n }\n const content = await readFile(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT' || error.code === 'EISDIR') return undefined;\n throw error;\n });\n if (!content) {\n if (isPage) {\n res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('The studio page has not been built. Run `pnpm build` in the lines-db repository.');\n return;\n }\n sendJson(res, 404, { message: 'Not found' });\n return;\n }\n // Not 'unsafe-inline' for styles: the editor injects its styles, and a nonce allows only those\n const nonce = randomBytes(18).toString('base64');\n const body = isPage\n ? Buffer.from(\n content\n .toString('utf8')\n .replace(\n '</head>',\n `<meta name=\"csp-nonce\" content=\"${nonce}\"><meta name=\"studio-token\" content=\"${token}\"></head>`,\n ),\n )\n : content;\n res.writeHead(200, {\n 'Content-Type': CONTENT_TYPES[extname(file)] ?? 'application/octet-stream',\n 'Content-Security-Policy': `default-src 'none'; script-src 'self'; style-src 'self' 'nonce-${nonce}'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,\n 'Cache-Control': isPage ? 'no-store' : 'public, max-age=31536000, immutable',\n 'X-Content-Type-Options': 'nosniff',\n });\n res.end(body);\n}\n\nfunction bearerToken(req: IncomingMessage): string | undefined {\n return /^Bearer (.+)$/.exec(req.headers.authorization ?? '')?.[1];\n}\n\nfunction sameToken(presented: string, token: string): boolean {\n const a = Buffer.from(presented);\n const b = Buffer.from(token);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nconst NO_PRIMARY_KEY =\n 'This table has no primary key, so a row cannot be told apart from the others. Add an \"id\" column or declare primaryKey in its schema file to edit it here.';\n\n/** Why a table cannot be edited here: a row is found by its primary key, which must tell every row apart */\nfunction whyReadOnly(db: LinesDB<TableDefs>, tableName: string): string | null {\n const primaryKey = db.getSchema(tableName)?.columns.find((column) => column.primaryKey)?.name;\n if (!primaryKey) return NO_PRIMARY_KEY;\n const quote = (name: string) => `\"${name.replaceAll('\"', '\"\"')}\"`;\n const missing =\n unwrap(\n db.queryOne<{ n: number }>(`SELECT COUNT(*) AS n FROM ${quote(tableName)} WHERE ${quote(primaryKey)} IS NULL`),\n )?.n ?? 0;\n return missing > 0\n ? `${missing} row(s) have no value for the primary key ${primaryKey}, so they cannot be told apart. Give them one in the JSONL file to edit this table here.`\n : null;\n}\n\ntype WriteOperation = { kind: 'insert' } | { kind: 'update' | 'delete'; key: JsonValue };\n\nfunction writeOperation(method: string | undefined, encodedKey: string | undefined): WriteOperation | undefined {\n if (method === 'POST' && encodedKey === undefined) return { kind: 'insert' };\n if (encodedKey === undefined) return undefined;\n const key = parseJson(encodedKey, 'The row key in the address is not JSON') as JsonValue;\n if (method === 'PATCH') return { kind: 'update', key };\n if (method === 'DELETE') return { kind: 'delete', key };\n return undefined;\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });\n res.end(JSON.stringify(body));\n}\n\nasync function readJson(req: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return parseJson(Buffer.concat(chunks).toString('utf8'), 'The request body is not JSON');\n}\n\n/** The rows a save inserts, the changes it makes by primary key, and the keys it deletes */\ninterface ChangeBatch {\n inserts: JsonObject[];\n insertDataDirs?: string[];\n updates: Array<{ key: JsonValue; changes: JsonObject; resetToDefault?: string[] }>;\n deletes: JsonValue[];\n /** For a table with failing rows, whose rows are addressed by index: the file the page read them from */\n revision?: string;\n}\n\n/** The change of a batch the database refused */\ntype FailedChange = { kind: 'insert'; index: number } | { kind: 'update' | 'delete'; index: number; key: JsonValue };\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isFieldList(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((field) => typeof field === 'string');\n}\n\n/** `application/json`, with or without parameters such as a charset */\nfunction isJsonMediaType(contentType: string | undefined): boolean {\n return contentType?.split(';')[0].trim().toLowerCase() === 'application/json';\n}\n\nfunction changeBatch(body: unknown): ChangeBatch {\n if (!isJsonObject(body)) throw new BadRequestError('The request body must be a JSON object');\n const { inserts = [], updates = [], deletes = [], insertDataDirs } = body;\n if (\n insertDataDirs !== undefined &&\n (!Array.isArray(insertDataDirs) ||\n !insertDataDirs.every((dir) => typeof dir === 'string') ||\n insertDataDirs.length !== (Array.isArray(inserts) ? inserts.length : 0))\n )\n throw new BadRequestError('`insertDataDirs` must name a directory for each insert');\n if (!Array.isArray(inserts) || !inserts.every(isJsonObject))\n throw new BadRequestError('`inserts` must be a list of rows');\n if (!Array.isArray(deletes)) throw new BadRequestError('`deletes` must be a list of primary keys');\n if (\n !Array.isArray(updates) ||\n !updates.every(\n (update) =>\n isJsonObject(update) &&\n 'key' in update &&\n isJsonObject(update.changes) &&\n (update.resetToDefault === undefined || isFieldList(update.resetToDefault)),\n )\n ) {\n throw new BadRequestError('`updates` must be a list of { key, changes, resetToDefault? }');\n }\n if (body.revision !== undefined && typeof body.revision !== 'string')\n throw new BadRequestError('`revision` must be a string');\n return {\n inserts,\n insertDataDirs: insertDataDirs as string[] | undefined,\n updates: updates as unknown as ChangeBatch['updates'],\n deletes,\n revision: body.revision,\n };\n}\n\ninterface WriteBody {\n dataDir?: string;\n row?: JsonObject;\n changes?: JsonObject;\n resetToDefault?: string[];\n}\n\nfunction writeBody(body: unknown): WriteBody {\n if (!isJsonObject(body)) throw new BadRequestError('The request body must be a JSON object');\n const { row, changes, resetToDefault, dataDir } = body;\n if (dataDir !== undefined && typeof dataDir !== 'string') throw new BadRequestError('`dataDir` must be a string');\n if (row !== undefined && !isJsonObject(row)) throw new BadRequestError('`row` must be an object');\n if (changes !== undefined && !isJsonObject(changes)) throw new BadRequestError('`changes` must be an object');\n if (resetToDefault !== undefined && !isFieldList(resetToDefault)) {\n throw new BadRequestError('`resetToDefault` must be a list of field names');\n }\n return { row, changes, resetToDefault, dataDir };\n}\n\n/** Thrown at the end of a checked batch, so its transaction rolls back */\nconst DRY_RUN = new Error('dry run');\n\n/** An error in the request itself, answered with 400 */\nclass BadRequestError extends Error {}\n\nfunction parseJson(text: string, message: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new BadRequestError(message);\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,iBAAiB;;;;;AA4BvB,SAAS,UAA0B,QAAkE;CACnG,IAAI,OAAO,OAAO,UAAU;CAC5B,KAAK,MAAM,QAAQ;EAAC;EAAa;EAAS;CAAO,GAAG;EAClD,MAAM,WAAW,QAAQ,OAAO,SAAS,MAAM,IAAI;EACnD,IAAI,CAAC,UAAU,OAAO,KAAA;EACtB,OAAO,OAAO,YAAY,OAAO,OAAO,QAAQ,CAAC;CACnD;CACA,MAAM,UAAU,OAAO,OAAO,QAAQ,IAAI,IAAI,CAAC;CAC/C,MAAM,yBAAS,IAAI,IAAqF;CACxG,KAAK,MAAM,UAAU,SACnB,KAAK,MAAM,YAAY,OAAO,WAAW,MAAM,GAAG;EAChD,MAAM,WAAW,OAAO,OAAO,QAAQ;EACvC,MAAM,OAAO,OAAO,OAAO,QAAQ;EACnC,MAAM,SAAS,OAAO,IAAI,IAAI,KAAK;GAAE,OAAO,CAAC;GAAG,MAAM;GAAG,UAAU;GAAO,UAAU;EAAM;EAC1F,MAAM,OAAO,OAAO,KAAK,OAAO,YAAY,QAAQ,CAAC;EACrD,IAAI,CAAC,OAAO,MAAM,SAAS,IAAI,GAAG,OAAO,MAAM,KAAK,IAAI;EACxD,OAAO,QAAQ;EACf,OAAO,aAAa,OAAO,WAAW,QAAQ;EAC9C,OAAO,aAAa,OAAO,WAAW,QAAQ;EAC9C,OAAO,IAAI,MAAM,MAAM;CACzB;CAEF,IAAI,OAAO,SAAS,GAAG,OAAO,KAAA;CAE9B,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,aAAa;EAC1C;EACA,MAAM,OAAO,MAAM,KAAK,KAAK;EAC7B,UAAU,OAAO,YAAY,OAAO,OAAO,QAAQ;EACnD,UAAU,OAAO;CACn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,QAAQ;EACN,MAAM,IAAI,gBAAgB,OAAO;CACnC;AACF;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["resolvePath"],"sources":["../src/declared-columns.ts","../src/file-rows.ts","../src/server.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve, win32 } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { TableSchema } from 'lines-db';\nimport type * as TS from 'typescript';\n\n/** A column as the schema file declares it, read from the types of its Standard Schema */\nexport interface DeclaredColumn {\n name: string;\n /** The type of the values, without the null and undefined that the two flags below stand for */\n type: string;\n /** The field may be left out of a row: optional, or filled in by a default */\n optional: boolean;\n nullable: boolean;\n}\n\n// The flags of the Corsa API of typescript@7.1, which are not the ones of every compiler API: typescript 5 has\n// others, so that one is read from the `ts` it is given\nconst CORSA_NULL = 8;\nconst CORSA_UNION = 134217728;\nconst CORSA_OPTIONAL = 16777216;\n\n/** The type checker of either API, as far as reading the columns needs it */\ninterface TypeReader<Type, Property> {\n /** The type of what the file exports as `schema`, or else as its default */\n entryType(): Type | undefined;\n property(type: Type, name: string): Property | undefined;\n typeOf(property: Property): Type;\n nonNullable(type: Type): Type;\n /** The types a union is of, or the type itself: the properties of a union are only those its members share */\n members(type: Type): readonly Type[];\n properties(type: Type): readonly Property[];\n nameOf(property: Property): string;\n isOptional(property: Property): boolean;\n isNullable(type: Type): boolean;\n text(type: Type): string;\n}\n\n/** What a reading found, and the files of the project it was read from, which a change to any of them makes stale */\ninterface Reading {\n columns: DeclaredColumn[] | undefined;\n files: string[];\n}\n\n/**\n * Standard Schema holds the types of what it validates in `~standard.types`, which every library that\n * implements it fills in, so the columns are read from the types and not from any one library\n */\nfunction columnsOf<Type, Property>(reader: TypeReader<Type, Property>): DeclaredColumn[] | undefined {\n let type = reader.entryType();\n for (const name of ['~standard', 'types', 'input']) {\n const property = type && reader.property(type, name);\n if (!property) return undefined;\n type = reader.nonNullable(reader.typeOf(property));\n }\n const members = type ? reader.members(type) : [];\n const merged = new Map<string, { types: string[]; seen: number; optional: boolean; nullable: boolean }>();\n for (const member of members) {\n for (const property of reader.properties(member)) {\n const declared = reader.typeOf(property);\n const name = reader.nameOf(property);\n const column = merged.get(name) ?? { types: [], seen: 0, optional: false, nullable: false };\n const text = reader.text(reader.nonNullable(declared));\n if (!column.types.includes(text)) column.types.push(text);\n column.seen += 1;\n column.optional ||= reader.isOptional(property);\n column.nullable ||= reader.isNullable(declared);\n merged.set(name, column);\n }\n }\n if (merged.size === 0) return undefined;\n // A field a member of the union lacks may be left out of a row\n return [...merged].map(([name, column]) => ({\n name,\n type: column.types.join(' | '),\n optional: column.optional || column.seen < members.length,\n nullable: column.nullable,\n }));\n}\n\nfunction readWithCompilerApi(ts: typeof TS, schemaPath: string): Reading {\n const configPath = ts.findConfigFile(dirname(schemaPath), ts.sys.fileExists);\n const configured = configPath\n ? ts.parseJsonConfigFileContent(ts.readConfigFile(configPath, ts.sys.readFile).config, ts.sys, dirname(configPath))\n .options\n : {};\n const program = ts.createProgram([schemaPath], {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n ...configured,\n noEmit: true,\n skipLibCheck: true,\n strictNullChecks: true,\n allowImportingTsExtensions: true,\n types: [],\n });\n const checker = program.getTypeChecker();\n const file = program.getSourceFile(schemaPath);\n const module = file && checker.getSymbolAtLocation(file);\n const files = program\n .getSourceFiles()\n .filter((source) => !program.isSourceFileFromExternalLibrary(source) && !program.isSourceFileDefaultLibrary(source))\n .map((source) => source.fileName);\n if (configPath) files.push(configPath);\n if (!file || !module) return { columns: undefined, files };\n return {\n files,\n columns: columnsOf<TS.Type, TS.Symbol>({\n entryType() {\n const exports = checker.getExportsOfModule(module);\n let entry =\n exports.find((symbol) => symbol.name === 'schema') ?? exports.find((symbol) => symbol.name === 'default');\n if (entry && entry.flags & ts.SymbolFlags.Alias) entry = checker.getAliasedSymbol(entry);\n return entry && checker.getTypeOfSymbolAtLocation(entry, file);\n },\n property: (type, name) => type.getProperty(name),\n typeOf: (property) => checker.getTypeOfSymbol(property),\n nonNullable: (type) => checker.getNonNullableType(type),\n members: (type) => (type.flags & ts.TypeFlags.Union ? (type as TS.UnionType).types : [type]),\n properties: (type) => checker.getPropertiesOfType(type),\n nameOf: (property) => property.name,\n isOptional: (property) => Boolean(property.flags & ts.SymbolFlags.Optional),\n isNullable: (type) =>\n type.flags & ts.TypeFlags.Union\n ? (type as TS.UnionType).types.some((member) => member.flags & ts.TypeFlags.Null)\n : Boolean(type.flags & ts.TypeFlags.Null),\n text: (type) => checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation),\n }),\n };\n}\n\n// What of the Corsa API this reads: the unstable API of typescript@7.1, which the compiler API's types do not describe\ninterface CorsaSymbol {\n name: string;\n flags: number;\n}\ninterface CorsaType {\n flags: number;\n getProperty(name: string): CorsaSymbol | undefined;\n getTypes(): readonly CorsaType[] | undefined;\n}\ninterface CorsaChecker {\n getSymbolOfSourceFile(file: string): CorsaSymbol | undefined;\n getExportsOfModule(symbol: CorsaSymbol): readonly CorsaSymbol[];\n getTypeOfSymbol(symbol: CorsaSymbol): CorsaType;\n getNonNullableType(type: CorsaType): CorsaType;\n getPropertiesOfType(type: CorsaType): readonly CorsaSymbol[];\n typeToString(type: CorsaType): string;\n}\ninterface CorsaApi {\n createProgram(\n files: string[],\n options: Record<string, unknown>,\n ): { getProject(): { checker: CorsaChecker }; getSourceFileNames(): readonly string[] };\n close(): void;\n}\n\n/**\n * Whether a file of a program is one of the project's own, and not a library: those are in node_modules, or\n * have names that are not paths of the disk at all. Either kind of separator, as on Windows.\n */\nexport function isProjectSource(name: string): boolean {\n return win32.isAbsolute(name) && !/[\\\\/]node_modules[\\\\/]/.test(name);\n}\n\nfunction readWithCorsa(api: CorsaApi, schemaPath: string): Reading {\n try {\n // ESNext, Bundler and ESNext, as in the compiler API above\n const program = api.createProgram([schemaPath], {\n target: 99,\n module: 99,\n moduleResolution: 100,\n strict: true,\n skipLibCheck: true,\n noEmit: true,\n allowImportingTsExtensions: true,\n types: [],\n });\n const checker = program.getProject().checker;\n const files = program.getSourceFileNames().filter(isProjectSource);\n const module = checker.getSymbolOfSourceFile(schemaPath);\n if (!module) return { columns: undefined, files };\n return {\n files,\n columns: columnsOf<CorsaType, CorsaSymbol>({\n entryType() {\n const exports = checker.getExportsOfModule(module);\n const entry =\n exports.find((symbol) => symbol.name === 'schema') ?? exports.find((symbol) => symbol.name === 'default');\n return entry && checker.getTypeOfSymbol(entry);\n },\n property: (type, name) => type.getProperty(name),\n typeOf: (property) => checker.getTypeOfSymbol(property),\n nonNullable: (type) => checker.getNonNullableType(type),\n members: (type) => (type.flags & CORSA_UNION ? (type.getTypes() ?? [type]) : [type]),\n properties: (type) => checker.getPropertiesOfType(type),\n nameOf: (property) => property.name,\n isOptional: (property) => Boolean(property.flags & CORSA_OPTIONAL),\n isNullable: (type) =>\n type.flags & CORSA_UNION\n ? (type.getTypes() ?? []).some((member) => member.flags & CORSA_NULL)\n : Boolean(type.flags & CORSA_NULL),\n text: (type) => checker.typeToString(type),\n }),\n };\n } finally {\n api.close();\n }\n}\n\n/** The modification time of each file that can be read, which a reading is as fresh as */\nasync function stampsOf(files: string[]): Promise<Map<string, number>> {\n const stamps = new Map<string, number>();\n for (const file of new Set(files)) {\n try {\n stamps.set(file, (await stat(file)).mtimeMs);\n } catch {\n // Not on the disk: not something that can change it\n }\n }\n return stamps;\n}\n\nasync function isFresh(stamps: Map<string, number>): Promise<boolean> {\n for (const [file, mtimeMs] of stamps) {\n try {\n if ((await stat(file)).mtimeMs !== mtimeMs) return false;\n } catch {\n return false;\n }\n }\n return true;\n}\n\nconst cache = new Map<string, { columns: DeclaredColumn[] | undefined; stamps: Map<string, number> }>();\n\n/**\n * The columns a schema file declares, read from its types with the TypeScript installed from `searchFrom`:\n * the compiler API of typescript 5 and 6, or the Corsa API of typescript 7.1 and later. Undefined when there\n * is none, the schema declares no types or the file cannot be read, so the caller can fall back on the rows.\n */\nexport async function readDeclaredColumns(\n schemaPath: string,\n searchFrom: string,\n): Promise<DeclaredColumn[] | undefined> {\n try {\n // Not as given: the CLI passes the directory as it was typed, and createRequire takes only an absolute path\n const schemaFile = resolve(schemaPath);\n const from = resolve(searchFrom);\n const key = `${from}\\0${schemaFile}`;\n const cached = cache.get(key);\n if (cached && (await isFresh(cached.stamps))) return cached.columns;\n\n const require = createRequire(join(from, 'noop.js'));\n const { version } = require('typescript/package.json') as { version: string };\n let reading: Reading;\n if (Number.parseInt(version, 10) >= 7) {\n const { API } = (await import(pathToFileURL(require.resolve('typescript/sync')).href)) as {\n API: new (options: { cwd: string }) => CorsaApi;\n };\n reading = readWithCorsa(new API({ cwd: dirname(schemaFile) }), schemaFile);\n } else {\n reading = readWithCompilerApi(require('typescript') as typeof TS, schemaFile);\n }\n cache.set(key, { columns: reading.columns, stamps: await stampsOf([schemaFile, ...reading.files]) });\n return reading.columns;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The table the columns a schema file declares make, for a table with no rows to infer them from. The types\n * are written as the compiler prints them, so a number cannot be told an integer from a real one and is stored\n * as REAL, which gives an integer back as one.\n */\nexport function tableSchemaOf(tableName: string, columns: readonly DeclaredColumn[]): TableSchema {\n return {\n name: tableName,\n columns: columns.map((column) => ({\n name: column.name,\n type: sqlTypeOf(column.type),\n notNull: !column.optional && !column.nullable,\n ...(isBoolean(column.type) ? { valueType: 'boolean' as const } : {}),\n })),\n };\n}\n\ntype TypeKind = 'text' | 'number' | 'boolean' | 'other';\n\nfunction kindOf(member: string): TypeKind {\n if (member === 'string' || /^(\".*\"|'.*')$/.test(member)) return 'text';\n if (member === 'number' || /^-?\\d+(\\.\\d+)?$/.test(member)) return 'number';\n if (member === 'boolean' || member === 'true' || member === 'false') return 'boolean';\n return 'other';\n}\n\n// Not TEXT for a type it is not sure of: a TEXT column stores an object or a number as its text, which the file then holds\nfunction sqlTypeOf(type: string): TableSchema['columns'][number]['type'] {\n const kinds = new Set(unionMembers(type).map(kindOf));\n if (kinds.size !== 1) return 'JSON';\n const [kind] = kinds;\n return kind === 'text' ? 'TEXT' : kind === 'number' ? 'REAL' : kind === 'boolean' ? 'INTEGER' : 'JSON';\n}\n\nfunction isBoolean(type: string): boolean {\n return unionMembers(type).every((member) => kindOf(member) === 'boolean');\n}\n\n/** The members of a union as the compiler prints it, split only where ` | ` is outside quotes and brackets */\nfunction unionMembers(type: string): string[] {\n const members: string[] = [];\n let depth = 0;\n let quote: string | undefined;\n let start = 0;\n for (let index = 0; index < type.length; index++) {\n const char = type[index];\n if (quote) {\n if (char === '\\\\') index++;\n else if (char === quote) quote = undefined;\n } else if (char === '\"' || char === \"'\") quote = char;\n else if ('{[(<'.includes(char)) depth++;\n else if ('}])>'.includes(char)) depth--;\n else if (depth === 0 && type.startsWith(' | ', index)) {\n members.push(type.slice(start, index));\n start = index + 3;\n }\n }\n members.push(type.slice(start));\n return members;\n}\n","import type { JsonObject } from 'lines-db';\n\n/**\n * The content with the rows at the given indexes - counting the lines that hold a row, as reading\n * the file does - written over their lines, and every other line left as it was\n */\nexport function replaceRows(content: string, replaced: ReadonlyMap<number, JsonObject>): string {\n const bom = content.startsWith('\\u{feff}') ? '\\u{feff}' : '';\n let index = -1;\n const lines = content\n .slice(bom.length)\n .split('\\n')\n .map((raw) => {\n const carriage = raw.endsWith('\\r') ? '\\r' : '';\n if (raw.trim() === '') return raw;\n index += 1;\n const row = replaced.get(index);\n return row ? `${JSON.stringify(row)}${carriage}` : raw;\n });\n return bom + lines.join('\\n');\n}\n","import { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { readFile, realpath, writeFile } from 'node:fs/promises';\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { basename, dirname, extname, relative, resolve as resolvePath } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { watch, type FSWatcher } from 'zygiella';\nimport {\n LinesDB,\n DirectoryScanner,\n ErrorFormatter,\n unwrap,\n JsonlReader,\n findSchemaFile,\n type ColumnDefinition,\n type ForeignKeyDefinition,\n type JsonlConflictError,\n type JsonlParseError,\n type JsonObject,\n type JsonValue,\n type StandardSchemaIssue,\n type TableDefs,\n type ValidationError,\n type ValidationErrorDetail,\n type WriteFilledValues,\n} from 'lines-db';\nimport { hashJsonlContent, replaceFile } from 'lines-db/internal';\nimport { readDeclaredColumns, tableSchemaOf } from './declared-columns.js';\nimport { replaceRows } from './file-rows.js';\n\nexport interface StudioServerOptions {\n dataDir: string | string[];\n schemaDir?: string;\n /** Directory holding the built page. Defaults to the one shipped with the package */\n uiDir?: string;\n /** Which values the schema fills in a save writes into the file. Defaults to 'primaryKey' */\n writeFilledValues?: WriteFilledValues;\n host?: string;\n port?: number;\n}\n\nexport interface StudioServer {\n url: string;\n /** The token every API request presents, generated at start-up and handed to the page */\n token: string;\n close(): Promise<void>;\n}\n\ninterface Snapshot {\n db: LinesDB<TableDefs>;\n /** Rows that failed validation on load, whose table is therefore left out */\n problems: string[];\n /**\n * The tables left out because rows failed validation, edited in their file instead: the database\n * holds only rows that passed, so a failing row cannot be fixed through it\n */\n invalid: Map<string, InvalidTable>;\n}\n\ninterface InvalidTable {\n file: string;\n rows?: JsonObject[];\n sources?: Array<{ file: string; rowIndex: number }>;\n files?: Array<{ file: string; content: string }>;\n revision?: string;\n /** The issues of each failing row, by its index among the rows of the file */\n issues: Map<number, StandardSchemaIssue[]>;\n}\n\nexport async function startStudioServer(options: StudioServerOptions): Promise<StudioServer> {\n const dataDirs: string[] = [];\n const seen = new Set<string>();\n for (const dir of [options.dataDir].flat()) {\n const resolved = resolvePath(dir);\n const actual = await realpath(resolved);\n if (seen.has(actual)) continue;\n seen.add(actual);\n dataDirs.push(resolved);\n }\n if (dataDirs.length === 0) throw new Error('Studio requires at least one data directory');\n const dataDir = dataDirs[0];\n const schemaDir = options.schemaDir ?? dataDir;\n const host = options.host ?? '127.0.0.1';\n const uiDir = options.uiDir ?? shippedUiDir();\n const token = randomBytes(24).toString('base64url');\n const writeFilledValues = options.writeFilledValues ?? 'primaryKey';\n const load = () => loadSnapshot(dataDirs, options.schemaDir, writeFilledValues);\n let snapshot = await load();\n\n let queue: Promise<unknown> = Promise.resolve();\n const serialize = <T>(fn: () => Promise<T>): Promise<T> => {\n const result = queue.then(fn);\n queue = result.catch(() => {});\n return result;\n };\n\n /** Reload the tables when a JSONL file no longer holds what they were read from; true if it did */\n const reloadUnlocked = async (): Promise<void> => {\n const previous = snapshot;\n snapshot = await load();\n await previous.db.close();\n };\n const reloadIfChangedUnlocked = async (): Promise<boolean> => {\n if (!unwrap(await snapshot.db.hasExternalChanges())) return false;\n await reloadUnlocked();\n notifyChanged();\n return true;\n };\n\n // Not found again on each listing: what the schema takes is the same until the files are read again,\n // and finding it reads the table's file for a sample row\n type Columns = ReturnType<typeof withLeeway<ColumnDefinition>>;\n const leeway = new WeakMap<Snapshot, Map<string, Columns>>();\n const loadedColumnsOf = async (current: Snapshot, name: string): Promise<Columns> => {\n const byTable = leeway.get(current) ?? new Map<string, Columns>();\n leeway.set(current, byTable);\n if (!byTable.has(name)) {\n const [sample] = unwrap(await current.db.findWithDefaults(name));\n const columns = current.db.getSchema(name)?.columns ?? [];\n byTable.set(name, withLeeway(current.db, name, sample?.row as JsonObject | undefined, columns));\n }\n return byTable.get(name)!;\n };\n // Not read on each listing: a table with no foreign keys in the database has them read from its schema\n // file, imported anew each time, and they stay the same until the files are read again\n type References = Awaited<ReturnType<typeof referencesOf>>;\n const references = new WeakMap<Snapshot, Map<string, References>>();\n const referencesFor = async (current: Snapshot, name: string): Promise<References> => {\n const byTable = references.get(current) ?? new Map<string, References>();\n references.set(current, byTable);\n if (!byTable.has(name)) byTable.set(name, await referencesOf(current.db, schemaDir, name));\n return byTable.get(name)!;\n };\n // Not found on each listing either for a table whose rows fail validation: finding it validates rows\n const invalidColumns = new WeakMap<Snapshot, Map<string, { columns: Columns; rowCount: number }>>();\n const invalidColumnsOf = async (current: Snapshot, name: string): Promise<{ columns: Columns; rowCount: number }> => {\n const byTable = invalidColumns.get(current) ?? new Map<string, { columns: Columns; rowCount: number }>();\n invalidColumns.set(current, byTable);\n if (!byTable.has(name)) {\n const invalid = current.invalid.get(name)!;\n const { issues } = invalid;\n const rows = invalid.rows ?? unwrap(await JsonlReader.read(invalid.file));\n const unknown = unknownFields(current.db, name, rows, issues);\n const inferred = unwrap(JsonlReader.inferSchema(name, rows)).columns;\n // A field no row holds - a required one every row lacks - has no column to fill it in otherwise;\n // its type is unknown, so it is edited as JSON, which takes any value\n const missing = [...new Set([...issues.values()].flat().map(fieldOf))].filter(\n (field): field is string => field !== undefined && !inferred.some((column) => column.name === field),\n );\n const columns = withLeeway(current.db, name, rows.find((_, index) => !issues.has(index)) ?? rows[0], [\n ...inferred,\n ...missing.map((field) => ({ name: field, type: 'JSON' as const, notNull: false, primaryKey: false })),\n ]).map((column) => ({ ...column, primaryKey: false, ...(unknown.has(column.name) ? { unknown: true } : {}) }));\n byTable.set(name, { columns, rowCount: rows.length });\n }\n return byTable.get(name)!;\n };\n\n const eventClients = new Set<ServerResponse>();\n const notifyChanged = (): void => {\n for (const client of eventClients) client.write('event: changed\\ndata: {}\\n\\n');\n };\n\n const reloadIfChanged = (): Promise<boolean> => serialize(reloadIfChangedUnlocked);\n\n let watchTimer: NodeJS.Timeout | undefined;\n // Not checking on each event: an editor saving a file fires several (a temporary file, then a rename)\n const watchers = (\n await Promise.all(\n [...new Set([...dataDirs, resolvePath(schemaDir)])].map(async (dir): Promise<FSWatcher[]> => {\n try {\n const watcher = watch(dir, { ignoreInitial: true, depth: 0 });\n watcher.on('all', () => {\n clearTimeout(watchTimer);\n watchTimer = setTimeout(() => {\n // Not reporting the error here: the page asks again on 'changed' and shows the error it gets\n reloadIfChanged().catch(notifyChanged);\n }, 100);\n });\n // Not letting the error end the process: Reload still loads the current files without the watcher\n watcher.on('error', (error) => {\n console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);\n void watcher.close();\n });\n // Not left watching: the watcher would wait for the directory to appear, and Reload is the way to pick it up\n const { missing } = await watcher.ready;\n if (missing.length > 0) {\n console.warn(`Live reload is off for '${dir}': the directory does not exist`);\n await watcher.close();\n return [];\n }\n return [watcher];\n } catch (error) {\n console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);\n return [];\n }\n }),\n )\n ).flat();\n\n const server = createServer((req, res) => {\n handle(req, res).catch((error) =>\n sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }),\n );\n });\n\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const { port } = server.address() as AddressInfo;\n const allowedHosts = new Set([`${host}:${port}`, `127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);\n if (!allowedHosts.has(req.headers.host ?? '')) {\n sendJson(res, 403, { message: 'Requests must be addressed to the local studio server' });\n return;\n }\n\n const url = new URL(req.url ?? '/', 'http://localhost');\n\n // Not behind the token: the page has to load before it holds one. Another site cannot read the page,\n // so the token it carries keeps that site's requests out\n if (req.method === 'GET' && !url.pathname.startsWith('/api/')) {\n await servePage(res, uiDir, url.pathname, token);\n return;\n }\n // Not taken from the query elsewhere: an event source cannot send headers, but a fetch can\n const presented = bearerToken(req) ?? (url.pathname === '/api/events' ? url.searchParams.get('token') : null) ?? '';\n if (!sameToken(presented, token)) {\n sendJson(res, 401, {\n message: 'This page holds no token of this run of lines-db studio. Reload it to get one.',\n });\n return;\n }\n const segments = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);\n\n if (req.method === 'GET' && url.pathname === '/api/events') {\n res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' });\n res.write(': connected\\n\\n');\n eventClients.add(res);\n req.on('close', () => eventClients.delete(res));\n return;\n }\n\n if (req.method === 'GET' && url.pathname === '/api/tables') {\n // Not left open to a reload between its awaits: one would close the database the listing reads\n const listing = await serialize(async () => {\n await reloadIfChangedUnlocked();\n const current = snapshot;\n // Not listed as loaded when rows failed a constraint on load: its passing rows are in the database,\n // but its rows are fixed in the file, by index\n const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));\n const tables = [];\n for (const name of loadedTables) {\n const columns = await loadedColumnsOf(current, name);\n const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;\n const rowCount =\n unwrap(current.db.queryOne<{ n: number }>(`SELECT COUNT(*) AS n FROM \"${name.replaceAll('\"', '\"\"')}\"`))\n ?.n ?? 0;\n tables.push({\n name,\n columns,\n primaryKey,\n rowCount,\n invalidRows: 0,\n readOnlyReason: whyReadOnly(current.db, name),\n schemaFile: null as string | null,\n references: await referencesFor(current, name),\n });\n }\n for (const [name, { issues }] of current.invalid) {\n const { columns, rowCount } = await invalidColumnsOf(current, name);\n tables.push({\n name,\n columns,\n primaryKey: null,\n rowCount,\n invalidRows: issues.size,\n readOnlyReason: null,\n schemaFile: null,\n references: await referencesFor(current, name),\n });\n }\n for (const table of tables) {\n const schemaPath = await findSchemaFile(schemaDir, table.name);\n table.schemaFile = schemaPath ? basename(schemaPath) : null;\n }\n tables.sort((a, b) => a.name.localeCompare(b.name));\n return {\n dataDir,\n dataDirs,\n schemaDir: resolvePath(schemaDir),\n tables,\n problems: current.problems,\n };\n });\n sendJson(res, 200, listing);\n return;\n }\n\n const [, , tableName, resource, encodedKey] = segments;\n if (segments[0] === 'api' && segments[1] === 'tables' && resource === 'schema' && segments.length === 4) {\n if (req.method !== 'GET') {\n sendJson(res, 405, { message: 'Method not allowed' });\n return;\n }\n await reloadIfChanged();\n // Not looked up for a name that is not a table: the name would otherwise reach the file system as is\n const known = Boolean(snapshot.db.getSchema(tableName)) || snapshot.invalid.has(tableName);\n const schemaPath = known ? await findSchemaFile(schemaDir, tableName) : undefined;\n if (!schemaPath) {\n sendJson(res, 404, { message: `Table '${tableName}' has no schema file` });\n return;\n }\n const loaded = snapshot.invalid.has(tableName) ? undefined : snapshot.db.getSchema(tableName);\n const declared = loaded && (await readDeclaredColumns(schemaPath, schemaDir));\n const flagsOf = (name: string) => {\n const column = loaded?.columns.find((candidate) => candidate.name === name);\n return { ...(column?.primaryKey ? { primaryKey: true } : {}), ...(column?.unique ? { unique: true } : {}) };\n };\n sendJson(res, 200, {\n file: basename(schemaPath),\n source: await readFile(schemaPath, 'utf-8'),\n definition: loaded\n ? {\n // Declared when the types of the schema can be read, as the columns the database holds are inferred\n // from the values of the rows: a field left out of every row is missing, and one in every row is not null\n columnsFrom: declared ? 'schema' : 'rows',\n columns: declared\n ? declared.map((column) => ({ ...column, ...flagsOf(column.name) }))\n : loaded.columns.map((column) => ({\n name: column.name,\n type: column.valueType ?? column.type,\n ...(column.notNull ? { notNull: true } : {}),\n ...flagsOf(column.name),\n })),\n foreignKeys: loaded.declaredForeignKeys ?? [],\n indexes: loaded.indexes ?? [],\n }\n : null,\n });\n return;\n }\n const isRows = segments[0] === 'api' && segments[1] === 'tables' && resource === 'rows' && segments.length <= 5;\n const isChanges =\n segments[0] === 'api' &&\n segments[1] === 'tables' &&\n (resource === 'changes' || resource === 'check') &&\n segments.length === 4;\n if (!isRows && !isChanges) {\n sendJson(res, 404, { message: 'Not found' });\n return;\n }\n\n if (isRows && req.method === 'GET' && encodedKey === undefined) {\n await reloadIfChanged();\n const invalid = snapshot.invalid.get(tableName);\n if (invalid) {\n if (invalid.rows) {\n sendJson(res, 200, {\n rows: invalid.rows,\n defaulted: invalid.rows.map(() => []),\n issues: Object.fromEntries(invalid.issues),\n revision: invalid.revision,\n });\n return;\n }\n const { rows, contentHash } = unwrap(await JsonlReader.readSnapshot(invalid.file));\n const read = unwrap(rows);\n sendJson(res, 200, {\n rows: read,\n defaulted: read.map(() => []),\n issues: Object.fromEntries(invalid.issues),\n revision: contentHash,\n });\n return;\n }\n if (!snapshot.db.getSchema(tableName)) {\n sendJson(res, 404, { message: `Table '${tableName}' does not exist` });\n return;\n }\n const rows = unwrap(await snapshot.db.findWithDefaults(tableName));\n sendJson(res, 200, { rows: rows.map(({ row }) => row), defaulted: rows.map(({ defaulted }) => defaulted) });\n return;\n }\n\n const write = isChanges\n ? req.method === 'POST'\n ? resource === 'check'\n ? ({ kind: 'check' } as const)\n : ({ kind: 'batch' } as const)\n : undefined\n : writeOperation(req.method, encodedKey);\n if (!write) {\n sendJson(res, 405, { message: 'Method not allowed' });\n return;\n }\n const origin = req.headers.origin;\n if (origin !== undefined && !allowedHosts.has(origin.replace(/^http:\\/\\//, ''))) {\n sendJson(res, 403, { message: 'Writes are accepted from the studio page only' });\n return;\n }\n if (write.kind !== 'delete' && !isJsonMediaType(req.headers['content-type'])) {\n sendJson(res, 415, { message: 'Writes must be sent as application/json' });\n return;\n }\n let batch: ChangeBatch;\n if (write.kind === 'batch' || write.kind === 'check') {\n batch = changeBatch(await readJson(req));\n } else if (write.kind === 'delete') {\n batch = { inserts: [], updates: [], deletes: [write.key] };\n } else {\n const body = writeBody(await readJson(req));\n batch =\n write.kind === 'insert'\n ? {\n inserts: [body.row ?? {}],\n insertDataDirs: body.dataDir ? [body.dataDir] : undefined,\n updates: [],\n deletes: [],\n }\n : {\n inserts: [],\n updates: [{ key: write.key, changes: body.changes ?? {}, resetToDefault: body.resetToDefault }],\n deletes: [],\n };\n }\n\n if (\n dataDirs.length > 1 &&\n batch.inserts.some((_, index) => {\n const dir = batch.insertDataDirs?.[index];\n return !dir || !dataDirs.includes(resolvePath(dir));\n })\n )\n throw new BadRequestError('Choose a data directory for each inserted row');\n\n type Outcome = { status: number; body: unknown; changed?: boolean };\n /** Apply the updates to the rows of the file, and write them only once every edited row passes */\n const writeInvalidTable = async (invalid: InvalidTable): Promise<Outcome> => {\n const { file } = invalid;\n if (batch.inserts.length > 0 || batch.deletes.length > 0) {\n const message = 'Fix the rows that fail validation before adding or deleting rows of this table';\n return { status: 409, body: { message } };\n }\n const files = await Promise.all(\n (invalid.files ?? [{ file }]).map(async ({ file }) => ({\n file,\n content: await readFile(file, 'utf8'),\n })),\n );\n const content = files[0].content;\n const revision =\n files.length > 1 || invalid.files ? hashJsonlContent(JSON.stringify(files)) : hashJsonlContent(content);\n // Not left to the watcher: once it reloads, the file it compares against is the changed one, while\n // the page still addresses rows by where they stood when it read them\n if (batch.revision !== revision) {\n const message =\n files.length > 1\n ? 'Source files changed since their rows were read; reload the table to see them'\n : `${relative(dataDir, file)} changed since its rows were read; reload the table to see them`;\n return { status: 409, body: { message } };\n }\n const rows = invalid.rows ?? unwrap(await JsonlReader.read(file));\n const replaced = new Map<number, JsonObject>();\n for (const [index, { key, changes, resetToDefault }] of batch.updates.entries()) {\n // An earlier update of the same row in the batch is built on, as a transaction would apply it\n const base = typeof key === 'number' ? (replaced.get(key) ?? rows[key]) : undefined;\n if (!base)\n return { status: 400, body: { message: `No row ${JSON.stringify(key)} in ${relative(dataDir, file)}` } };\n const next: JsonObject = { ...base, ...changes };\n for (const field of resetToDefault ?? []) delete next[field];\n const validated = snapshot.db.validateRow(tableName, next);\n if (!validated.ok) {\n const change: FailedChange = { kind: 'update', index, key };\n const failure = { message: validated.error.message, issues: perKey(validated.error.issues), change };\n return write.kind === 'check'\n ? { status: 200, body: { ok: false, ...failure } }\n : { status: 400, body: failure };\n }\n replaced.set(key as number, next);\n }\n if (write.kind === 'check') return { status: 200, body: { ok: true } };\n const plans = files\n .map(({ file, content }) => {\n const changes = new Map<number, JsonObject>();\n for (const [index, row] of replaced) {\n const source = invalid.sources?.[index] ?? { file: invalid.file, rowIndex: index };\n if (source.file === file) changes.set(source.rowIndex, row);\n }\n return { file, content, next: replaceRows(content, changes), changed: changes.size > 0 };\n })\n .filter((plan) => plan.changed);\n const written: typeof plans = [];\n try {\n for (const plan of plans) {\n await replaceUnchangedFile(plan.file, plan.next, plan.content);\n written.push(plan);\n }\n } catch (error) {\n const unrestored: string[] = [];\n for (const plan of written) {\n await replaceUnchangedFile(plan.file, plan.content, plan.next).catch(() => unrestored.push(plan.file));\n }\n if (unrestored.length)\n throw new Error(`${errorMessage(error)}; could not restore ${unrestored.join(', ')}`, { cause: error });\n if (error instanceof Error && error.name === 'JsonlConflictError') {\n await reloadUnlocked();\n return { status: 409, body: { message: error.message }, changed: true };\n }\n throw error;\n }\n await reloadUnlocked();\n // Not refused before writing: a foreign key is checked on load only, so the edited rows that still\n // fail are reported once the tables are loaded again\n const stillFailing = [...replaced.keys()]\n .map((index) => ({ index, issues: snapshot.invalid.get(tableName)?.issues.get(index) ?? [] }))\n .filter(({ issues }) => issues.length > 0);\n return { status: 200, body: { ok: true, ...(stillFailing.length > 0 ? { stillFailing } : {}) }, changed: true };\n };\n\n let reloaded = false;\n const outcome = await serialize(async (): Promise<Outcome> => {\n // Not left to the watcher: its event may not have fired yet, and a changed schema file is no\n // conflict a write-back detects, so the rows would be validated against the old schema\n const changedFiles = unwrap(await snapshot.db.findExternalChanges());\n if (changedFiles.length > 0) {\n await reloadUnlocked();\n reloaded = true;\n if (write.kind === 'check') changedFiles.length = 0;\n // Not saved over an outside edit of the edited table's own file: the change was made on rows\n // the page showed before that edit\n // A changed schema file of the edited table counts too: its primary key may name another column\n const ownFile = changedFiles.find(\n (file) =>\n dataDirs.some((dir) => resolvePath(file) === resolvePath(dir, `${tableName}.jsonl`)) ||\n basename(file).startsWith(`${tableName}.schema.`),\n );\n if (ownFile) {\n const message = `${relative(dataDir, ownFile) || ownFile} changed on disk, so the tables were reloaded. Check the rows and try again.`;\n return { status: 409, body: { message }, changed: true };\n }\n }\n const { db } = snapshot;\n const invalid = snapshot.invalid.get(tableName);\n if (invalid) return writeInvalidTable(invalid);\n const schema = db.getSchema(tableName);\n if (!schema) return { status: 404, body: { message: `Table '${tableName}' does not exist` } };\n const primaryKey = schema.columns.find((column) => column.primaryKey)?.name;\n const reason = whyReadOnly(db, tableName);\n if (!primaryKey || reason) return { status: 409, body: { message: reason } };\n\n const result = await db.transaction((tx) => {\n const check = (written: { ok: boolean; error?: Error }, change: FailedChange) => {\n if (!written.ok) throw Object.assign(written.error!, { change });\n };\n batch.deletes.forEach((key, index) =>\n check(tx.delete(tableName, { [primaryKey]: key }), { kind: 'delete', index, key }),\n );\n batch.updates.forEach(({ key, changes, resetToDefault }, index) =>\n check(tx.update(tableName, changes, { [primaryKey]: key }, { resetToDefault }), {\n kind: 'update',\n index,\n key,\n }),\n );\n batch.inserts.forEach((row, index) =>\n check(tx.insert(tableName, row, { dataDir: batch.insertDataDirs?.[index] }), { kind: 'insert', index }),\n );\n // Not committed when only checking: throwing rolls the transaction back before anything is written\n if (write.kind === 'check') throw DRY_RUN;\n });\n if (write.kind === 'check') {\n if (!result.ok && result.error === DRY_RUN) return { status: 200, body: { ok: true } };\n const failure = (result.ok ? {} : result.error) as Partial<ValidationError> & { change?: FailedChange };\n return {\n status: 200,\n body: {\n ok: false,\n message: failure.message,\n issues: perKey(failure.issues ?? []),\n ...(failure.change ? { change: failure.change } : {}),\n },\n };\n }\n if (!result.ok) {\n if (result.error.name === 'JsonlConflictError') {\n await reloadUnlocked();\n const { file } = result.error as JsonlConflictError;\n const message = `${relative(dataDir, file) || file} changed on disk, so the tables were reloaded. Check the rows and try again.`;\n return { status: 409, body: { message }, changed: true };\n }\n const { issues, change } = result.error as Partial<ValidationError> & { change?: FailedChange };\n return {\n status: 400,\n body: {\n message: result.error.message,\n ...(issues ? { issues: perKey(issues) } : {}),\n ...(change ? { change } : {}),\n },\n };\n }\n // Not kept: the listing would answer with the column types cached before this write\n leeway.get(snapshot)?.delete(tableName);\n return { status: write.kind === 'insert' ? 201 : 200, body: { ok: true }, changed: true };\n });\n sendJson(res, outcome.status, outcome.body);\n // Not before the response: the page that saved would still be in its editor when the event arrives\n // Not only when the outcome says so: the watcher finds nothing left to reload once this did\n if (outcome.changed || reloaded) notifyChanged();\n }\n\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(options.port ?? 4848, host, () => {\n server.off('error', reject);\n resolve();\n });\n });\n } catch (error) {\n await Promise.all(watchers.map((watcher) => watcher.close()));\n await snapshot.db.close();\n throw error;\n }\n const { port } = server.address() as AddressInfo;\n\n const url = `http://${host.includes(':') ? `[${host}]` : host}:${port}`;\n return {\n url,\n token,\n close: async () => {\n await Promise.all(watchers.map((watcher) => watcher.close()));\n clearTimeout(watchTimer);\n server.closeAllConnections();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n await serialize(() => snapshot.db.close());\n },\n };\n}\n\nasync function replaceUnchangedFile(file: string, next: string, expected: string): Promise<void> {\n await replaceFile(file, (temporary) => writeFile(temporary, next, 'utf8'), expected);\n}\n\nasync function loadSnapshot(\n dataDir: string | string[],\n schemaDir: string | undefined,\n writeFilledValues: WriteFilledValues,\n): Promise<Snapshot> {\n const db = LinesDB.create<TableDefs>({\n dataDir,\n schemaDir,\n writeFilledValues,\n writeDataSets: true,\n schemaOfEmptyTable: async ({ tableName, schemaPath }) => {\n const declared = schemaPath && (await readDeclaredColumns(schemaPath, schemaDir ?? dirname(schemaPath)));\n return declared ? tableSchemaOf(tableName, declared) : undefined;\n },\n });\n const baseDir = [dataDir].flat()[0];\n // Not the bulk insert: a foreign key or NOT NULL violation would fail the whole load instead of\n // marking the row, which the studio then cannot show to be fixed\n const loaded = await db.initialize({ detailedValidate: true });\n if (!loaded.ok) {\n await db.close();\n if (loaded.error.name === 'JsonlParseError') {\n const { file, line, message } = loaded.error as JsonlParseError;\n throw new Error(`${relative(baseDir, file) || file}:${line}: ${message}`, { cause: loaded.error });\n }\n throw loaded.error;\n }\n return {\n db,\n problems: describeProblems(baseDir, loaded.value.errors),\n invalid:\n typeof dataDir !== 'string' && dataDir.length > 1\n ? await composedInvalidTables(dataDir, loaded.value.errors)\n : invalidTables(loaded.value.errors),\n };\n}\n\n/**\n * Each column with whether the schema lets it be null and lets the key be left out. A schema does not\n * list what it takes, so a row is validated with the field set to null and with the key removed, and\n * the column counts as taking it when no issue is about that field; an issue about another field is\n * the row's own and says nothing of this one\n */\nfunction withLeeway<Column extends { name: string; type?: string; notNull?: boolean }>(\n db: LinesDB<TableDefs>,\n tableName: string,\n sample: JsonObject | undefined,\n columns: Column[],\n): Array<Column & { nullable: boolean; optional: boolean; nested?: Record<string, NestedLeeway> }> {\n const probe = prober(db, tableName, sample ?? {});\n return columns.map((column) => {\n const { [column.name]: _removed, ...without } = sample ?? {};\n const value = sample?.[column.name];\n // Not taken on the schema's word alone for a NOT NULL column: the row is written as the schema leaves it\n // Not taken while the field still fails: a sample failing for it already, as with no row that passes,\n // has its issue among the sample's, so the change brings no new one\n const takes = (row: JsonObject) => {\n const { taken, value: validated, failsAt } = probe(row);\n return taken && !failsAt([column.name]) && (!column.notNull || (validated?.[column.name] ?? null) !== null);\n };\n return {\n ...column,\n nullable: takes({ ...without, [column.name]: null }),\n optional: takes(without),\n ...(sample && value !== null && typeof value === 'object'\n ? { nested: nestedLeeway(db, tableName, sample, column.name) }\n : {}),\n };\n });\n}\n\n/**\n * Whether the schema takes a change of the sample row: it does when the change brings no issue the\n * sample did not have. Not only an issue about the field changed counts, as a check across fields\n * reports on another field, or on the row as a whole\n */\nfunction prober(db: LinesDB<TableDefs>, tableName: string, sample: JsonObject) {\n const issuesOf = (result: ReturnType<typeof tryValidate>) =>\n !result ? undefined : result.ok ? [] : perKey(result.error.issues).map((issue) => JSON.stringify(issue));\n const before = new Set(issuesOf(tryValidate(db, tableName, sample)));\n return (\n row: JsonObject,\n ): { taken: boolean; value?: JsonObject; failsAt: (path: Array<string | number>) => boolean } => {\n const result = tryValidate(db, tableName, row);\n const taken = issuesOf(result)?.every((issue) => before.has(issue)) ?? false;\n const paths = result && !result.ok ? perKey(result.error.issues).map((issue) => (issue.path ?? []).map(keyOf)) : [];\n // Whether an issue is about the value at the path or one inside it\n const failsAt = (path: Array<string | number>) =>\n paths.some((at) => path.every((segment, index) => at[index] === String(segment)));\n return { taken, value: result?.ok ? result.value : undefined, failsAt };\n };\n}\n\n/**\n * The foreign keys of a table, as the row form opens the row a key refers to by them. Read from its\n * schema file first: the database leaves out a key to a table whose rows failed on load, and has no\n * schema at all for a table whose own rows failed, though the studio lists those tables and their rows\n */\nasync function referencesOf(db: LinesDB<TableDefs>, dataDir: string, tableName: string) {\n const declared = await foreignKeysInFile(dataDir, tableName);\n const foreignKeys = declared.length > 0 ? declared : (db.getSchema(tableName)?.foreignKeys ?? []);\n return foreignKeys.map((fk) => ({\n column: fk.column,\n table: fk.references.table,\n referencedColumn: fk.references.column,\n }));\n}\n\n/** The foreign keys a table's schema file exports, as the database reads them on load */\nasync function foreignKeysInFile(dataDir: string, tableName: string): Promise<ForeignKeyDefinition[]> {\n const schemaPath = await findSchemaFile(dataDir, tableName);\n if (!schemaPath) return [];\n try {\n const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);\n const exported = module.schema ?? module.default;\n return exported?.foreignKeys ?? module.foreignKeys ?? [];\n } catch {\n // Not failing the listing: the file failed to load on start too, and its problem is listed there\n return [];\n }\n}\n\n/**\n * The row validated, or undefined when the schema threw: a schema can assume a value the change took\n * away, such as reading the keys of an object removed, and that says it does not take the change\n */\nfunction tryValidate(db: LinesDB<TableDefs>, tableName: string, row: JsonObject) {\n try {\n return db.validateRow(tableName, row);\n } catch {\n return undefined;\n }\n}\n\n/** What the schema takes of an object inside a JSON value: keys it does not name, and leaving a key out */\ninterface NestedLeeway {\n open?: boolean;\n optional?: boolean;\n}\n\n/** A key no schema names, added to an object to see whether the schema takes keys it does not name */\nconst PROBE_KEY = '__lines_db_studio_probe__';\n\n/**\n * What the schema takes of each object inside the sample's value of a JSON column, by its path there\n * with list indexes as `*` (`''` for the value itself, `items.*.name` for a key of each item, and\n * `%`, `.` and `*` in a key as `%25`, `%2E` and `%2A`). Found as\n * for a column, from the issues a change brings that the sample did not have: a key added to an object\n * tells whether it takes keys it does not name, and a key removed whether it can be left out. The\n * items of a list are changed together in one check, so what one of them refuses counts as refused for all\n */\nfunction nestedLeeway(\n db: LinesDB<TableDefs>,\n tableName: string,\n sample: JsonObject,\n column: string,\n): Record<string, NestedLeeway> {\n const probe = prober(db, tableName, sample);\n // Not one object at a time: the items of a list share a pattern, so all of them are changed in one check,\n // and one an item refuses is refused for all\n const atAll = (paths: Array<Array<string | number>>, change: (object: JsonObject) => JsonObject) =>\n ({\n ...sample,\n [column]: paths.reduce((value, path) => changeAt(value, path, change), sample[column]),\n }) as JsonObject;\n\n const objects = new Map<string, Array<{ path: Array<string | number>; object: JsonObject }>>();\n const walk = (value: JsonValue | undefined, path: Array<string | number>, pattern: string[]) => {\n if (Array.isArray(value)) {\n value.forEach((item, index) => walk(item, [...path, index], [...pattern, '*']));\n return;\n }\n if (value === null || typeof value !== 'object') return;\n const key = pattern.join('.');\n objects.set(key, [...(objects.get(key) ?? []), { path, object: value }]);\n for (const [name, item] of Object.entries(value)) walk(item, [...path, name], [...pattern, segmentOf(name)]);\n };\n walk(sample[column], [], []);\n\n const leeway: Record<string, NestedLeeway> = {};\n for (const [pattern, found] of objects) {\n const prefix = pattern === '' ? '' : `${pattern}.`;\n // Not tried on an empty object: with no value of its own to give a new key, any value tried may be refused\n const filled = found.filter(({ object }) => Object.keys(object).length > 0);\n if (filled.length > 0) {\n // Not the probe key alone: an object may hold it already, and then it is changed rather than added\n let added = PROBE_KEY;\n while (filled.some(({ object }) => Object.hasOwn(object, added))) added += '_';\n const open = probe(\n atAll(\n filled.map(({ path }) => path),\n (object) => ({ ...object, [added]: Object.values(object)[0] }),\n ),\n ).taken;\n leeway[pattern] = { open };\n }\n const keys = new Set(found.flatMap(({ object }) => Object.keys(object)));\n for (const name of keys) {\n const holding = found.filter(({ object }) => Object.hasOwn(object, name)).map(({ path }) => path);\n const { taken, failsAt } = probe(\n atAll(holding, (object) => {\n const { [name]: _removed, ...rest } = object;\n return rest;\n }),\n );\n // Not taken while the key still fails: a sample failing for it already has its issue among the sample's\n const optional = taken && !holding.some((path) => failsAt([column, ...path, name]));\n leeway[`${prefix}${segmentOf(name)}`] = { ...leeway[`${prefix}${segmentOf(name)}`], optional };\n }\n }\n return leeway;\n}\n\n/** A key as a segment of a pattern, apart from the dots between segments and the `*` of a list index */\nconst segmentOf = (key: string) => key.replace(/[%.*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n\n/** The value with the object at the path inside it changed */\nfunction changeAt(\n value: JsonValue | undefined,\n path: Array<string | number>,\n change: (object: JsonObject) => JsonObject,\n): JsonValue {\n if (path.length === 0) return change(value as JsonObject);\n const [head, ...rest] = path;\n if (Array.isArray(value)) return value.map((item, index) => (index === head ? changeAt(item, rest, change) : item));\n const object = value as JsonObject;\n return { ...object, [head]: changeAt(object[head], rest, change) };\n}\n\n/**\n * The issues with one about several refused keys split per key. Zod reports the keys a strict object\n * refuses in one issue at the path of the object and the keys beside it, which no field would be found\n * by, nor a key inside a JSON value\n */\nfunction perKey(issues: readonly StandardSchemaIssue[]): StandardSchemaIssue[] {\n return issues.flatMap((issue) => {\n const { code, keys } = issue as { code?: unknown; keys?: unknown };\n if (code !== 'unrecognized_keys' || !Array.isArray(keys)) return [issue];\n if (keys.length === 0 || !keys.every((key) => typeof key === 'string')) return [issue];\n return keys.map((key) => ({ ...issue, keys: [key], path: [...(issue.path ?? []), { key }] }));\n });\n}\n\n/** A segment of an issue's path as the key it names */\nconst keyOf = (segment: PropertyKey | { key: PropertyKey }) =>\n typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n\n/** The field of the row an issue is about, if it is about one */\nfunction fieldOf(issue: StandardSchemaIssue): string | undefined {\n const segment = issue.path?.[0];\n if (segment === undefined) return undefined;\n return typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n}\n\n/**\n * The fields of a table's rows its schema refuses as keys, which a fix can only remove. A schema does\n * not list its keys, so a field counts when removing it from each row it fails on clears its issues,\n * and no row that passes keeps it: removing a known optional field holding a wrong value clears its\n * issue too, but a passing row then has it\n */\nfunction unknownFields(\n db: LinesDB<TableDefs>,\n tableName: string,\n rows: JsonObject[],\n issues: Map<number, StandardSchemaIssue[]>,\n): Set<string> {\n const failingOn = new Map<string, number[]>();\n for (const [index, rowIssues] of issues) {\n for (const issue of rowIssues) {\n const key = fieldOf(issue);\n if (key !== undefined && Object.hasOwn(rows[index] ?? {}, key))\n failingOn.set(key, [...(failingOn.get(key) ?? []), index]);\n }\n }\n const kept = new Set<string>();\n rows.forEach((row, index) => {\n if (issues.has(index)) return;\n const validated = tryValidate(db, tableName, row);\n if (validated?.ok) for (const key of Object.keys(validated.value)) kept.add(key);\n });\n const unknown = new Set<string>();\n for (const [key, indexes] of failingOn) {\n if (kept.has(key)) continue;\n const clears = indexes.every((index) => {\n const { [key]: _removed, ...rest } = rows[index];\n // Not counted as clearing it when the schema throws without the key: it relies on the key being there\n const result = tryValidate(db, tableName, rest);\n return (\n result !== undefined && (result.ok || !perKey(result.error.issues).some((issue) => fieldOf(issue) === key))\n );\n });\n if (clears) unknown.add(key);\n }\n return unknown;\n}\n\n/** The tables whose failing rows all come from one file, which can then be edited line by line */\nfunction invalidTables(errors: ValidationErrorDetail[]): Map<string, InvalidTable> {\n const tables = new Map<string, InvalidTable | null>();\n for (const error of errors) {\n const known = tables.get(error.tableName);\n if (known === null) continue;\n if (known && known.file !== error.file) {\n tables.set(error.tableName, null);\n continue;\n }\n const table = known ?? { file: error.file, issues: new Map() };\n const foreignKey = error.foreignKeyError;\n const issues: StandardSchemaIssue[] = foreignKey\n ? [\n {\n message: `No ${foreignKey.referencedTable} row has ${foreignKey.referencedColumn} ${JSON.stringify(foreignKey.value)}`,\n path: [{ key: foreignKey.column }],\n },\n ]\n : perKey(error.issues);\n table.issues.set(error.rowIndex, [...(table.issues.get(error.rowIndex) ?? []), ...issues]);\n tables.set(error.tableName, table);\n }\n return new Map([...tables].filter((entry): entry is [string, InvalidTable] => entry[1] !== null));\n}\n\nasync function composedInvalidTables(\n dataDirs: string[],\n errors: ValidationErrorDetail[],\n): Promise<Map<string, InvalidTable>> {\n const tables = await DirectoryScanner.scanDirectory(dataDirs);\n const invalid = new Map<string, InvalidTable>();\n for (const name of new Set(errors.map((error) => error.tableName))) {\n const config = tables.get(name)!;\n const rows: JsonObject[] = [];\n const adjusted: ValidationErrorDetail[] = [];\n const files: Array<{ file: string; content: string }> = [];\n const sources: Array<{ file: string; rowIndex: number }> = [];\n for (const file of config.jsonlPaths ?? [config.jsonlPath]) {\n const offset = rows.length;\n const read = unwrap(await JsonlReader.read(file));\n files.push({ file, content: await readFile(file, 'utf8') });\n sources.push(...read.map((_, rowIndex) => ({ file, rowIndex })));\n rows.push(...read);\n adjusted.push(\n ...errors\n .filter((error) => error.tableName === name && error.file === file)\n .map((error) => ({ ...error, file: config.jsonlPath, rowIndex: offset + error.rowIndex })),\n );\n }\n const table = invalidTables(adjusted).get(name)!;\n invalid.set(name, { ...table, rows, files, sources, revision: hashJsonlContent(JSON.stringify(files)) });\n }\n return invalid;\n}\n\nfunction describeProblems(dataDir: string, errors: ValidationErrorDetail[]): string[] {\n const formatter = new ErrorFormatter();\n return errors.map((error) => {\n const file = relative(dataDir, error.file) || error.file;\n const foreignKey = error.foreignKeyError;\n return foreignKey\n ? formatter.formatForeignKeyError({ file, rowIndex: error.rowIndex, ...foreignKey })\n : formatter.formatValidationErrors([{ file, rowIndex: error.rowIndex, issues: error.issues }]);\n });\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.json': 'application/json; charset=utf-8',\n};\n\nfunction shippedUiDir(): string {\n return fileURLToPath(new URL('../ui', import.meta.url));\n}\n\n/** Serve a file of the built page, the page itself carrying the token */\nasync function servePage(res: ServerResponse, uiDir: string, pathname: string, token: string): Promise<void> {\n // Not only `/`: the same page is reachable as /index.html, and must carry the token and stay uncached there too\n const isPage = pathname === '/' || pathname === '/index.html';\n const file = resolvePath(uiDir, `.${isPage ? '/index.html' : pathname}`);\n if (relative(uiDir, file).startsWith('..')) {\n sendJson(res, 404, { message: 'Not found' });\n return;\n }\n const content = await readFile(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT' || error.code === 'EISDIR') return undefined;\n throw error;\n });\n if (!content) {\n if (isPage) {\n res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('The studio page has not been built. Run `pnpm build` in the lines-db repository.');\n return;\n }\n sendJson(res, 404, { message: 'Not found' });\n return;\n }\n // Not 'unsafe-inline' for styles: the editor injects its styles, and a nonce allows only those\n const nonce = randomBytes(18).toString('base64');\n const body = isPage\n ? Buffer.from(\n content\n .toString('utf8')\n .replace(\n '</head>',\n `<meta name=\"csp-nonce\" content=\"${nonce}\"><meta name=\"studio-token\" content=\"${token}\"></head>`,\n ),\n )\n : content;\n res.writeHead(200, {\n 'Content-Type': CONTENT_TYPES[extname(file)] ?? 'application/octet-stream',\n 'Content-Security-Policy': `default-src 'none'; script-src 'self'; style-src 'self' 'nonce-${nonce}'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,\n 'Cache-Control': isPage ? 'no-store' : 'public, max-age=31536000, immutable',\n 'X-Content-Type-Options': 'nosniff',\n });\n res.end(body);\n}\n\nfunction bearerToken(req: IncomingMessage): string | undefined {\n return /^Bearer (.+)$/.exec(req.headers.authorization ?? '')?.[1];\n}\n\nfunction sameToken(presented: string, token: string): boolean {\n const a = Buffer.from(presented);\n const b = Buffer.from(token);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nconst NO_PRIMARY_KEY =\n 'This table has no primary key, so a row cannot be told apart from the others. Add an \"id\" column or declare primaryKey in its schema file to edit it here.';\n\n/** Why a table cannot be edited here: a row is found by its primary key, which must tell every row apart */\nfunction whyReadOnly(db: LinesDB<TableDefs>, tableName: string): string | null {\n const primaryKey = db.getSchema(tableName)?.columns.find((column) => column.primaryKey)?.name;\n if (!primaryKey) return NO_PRIMARY_KEY;\n const quote = (name: string) => `\"${name.replaceAll('\"', '\"\"')}\"`;\n const missing =\n unwrap(\n db.queryOne<{ n: number }>(`SELECT COUNT(*) AS n FROM ${quote(tableName)} WHERE ${quote(primaryKey)} IS NULL`),\n )?.n ?? 0;\n return missing > 0\n ? `${missing} row(s) have no value for the primary key ${primaryKey}, so they cannot be told apart. Give them one in the JSONL file to edit this table here.`\n : null;\n}\n\ntype WriteOperation = { kind: 'insert' } | { kind: 'update' | 'delete'; key: JsonValue };\n\nfunction writeOperation(method: string | undefined, encodedKey: string | undefined): WriteOperation | undefined {\n if (method === 'POST' && encodedKey === undefined) return { kind: 'insert' };\n if (encodedKey === undefined) return undefined;\n const key = parseJson(encodedKey, 'The row key in the address is not JSON') as JsonValue;\n if (method === 'PATCH') return { kind: 'update', key };\n if (method === 'DELETE') return { kind: 'delete', key };\n return undefined;\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });\n res.end(JSON.stringify(body));\n}\n\nasync function readJson(req: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return parseJson(Buffer.concat(chunks).toString('utf8'), 'The request body is not JSON');\n}\n\n/** The rows a save inserts, the changes it makes by primary key, and the keys it deletes */\ninterface ChangeBatch {\n inserts: JsonObject[];\n insertDataDirs?: string[];\n updates: Array<{ key: JsonValue; changes: JsonObject; resetToDefault?: string[] }>;\n deletes: JsonValue[];\n /** For a table with failing rows, whose rows are addressed by index: the file the page read them from */\n revision?: string;\n}\n\n/** The change of a batch the database refused */\ntype FailedChange = { kind: 'insert'; index: number } | { kind: 'update' | 'delete'; index: number; key: JsonValue };\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isFieldList(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((field) => typeof field === 'string');\n}\n\n/** `application/json`, with or without parameters such as a charset */\nfunction isJsonMediaType(contentType: string | undefined): boolean {\n return contentType?.split(';')[0].trim().toLowerCase() === 'application/json';\n}\n\nfunction changeBatch(body: unknown): ChangeBatch {\n if (!isJsonObject(body)) throw new BadRequestError('The request body must be a JSON object');\n const { inserts = [], updates = [], deletes = [], insertDataDirs } = body;\n if (\n insertDataDirs !== undefined &&\n (!Array.isArray(insertDataDirs) ||\n !insertDataDirs.every((dir) => typeof dir === 'string') ||\n insertDataDirs.length !== (Array.isArray(inserts) ? inserts.length : 0))\n )\n throw new BadRequestError('`insertDataDirs` must name a directory for each insert');\n if (!Array.isArray(inserts) || !inserts.every(isJsonObject))\n throw new BadRequestError('`inserts` must be a list of rows');\n if (!Array.isArray(deletes)) throw new BadRequestError('`deletes` must be a list of primary keys');\n if (\n !Array.isArray(updates) ||\n !updates.every(\n (update) =>\n isJsonObject(update) &&\n 'key' in update &&\n isJsonObject(update.changes) &&\n (update.resetToDefault === undefined || isFieldList(update.resetToDefault)),\n )\n ) {\n throw new BadRequestError('`updates` must be a list of { key, changes, resetToDefault? }');\n }\n if (body.revision !== undefined && typeof body.revision !== 'string')\n throw new BadRequestError('`revision` must be a string');\n return {\n inserts,\n insertDataDirs: insertDataDirs as string[] | undefined,\n updates: updates as unknown as ChangeBatch['updates'],\n deletes,\n revision: body.revision,\n };\n}\n\ninterface WriteBody {\n dataDir?: string;\n row?: JsonObject;\n changes?: JsonObject;\n resetToDefault?: string[];\n}\n\nfunction writeBody(body: unknown): WriteBody {\n if (!isJsonObject(body)) throw new BadRequestError('The request body must be a JSON object');\n const { row, changes, resetToDefault, dataDir } = body;\n if (dataDir !== undefined && typeof dataDir !== 'string') throw new BadRequestError('`dataDir` must be a string');\n if (row !== undefined && !isJsonObject(row)) throw new BadRequestError('`row` must be an object');\n if (changes !== undefined && !isJsonObject(changes)) throw new BadRequestError('`changes` must be an object');\n if (resetToDefault !== undefined && !isFieldList(resetToDefault)) {\n throw new BadRequestError('`resetToDefault` must be a list of field names');\n }\n return { row, changes, resetToDefault, dataDir };\n}\n\n/** Thrown at the end of a checked batch, so its transaction rolls back */\nconst DRY_RUN = new Error('dry run');\n\n/** An error in the request itself, answered with 400 */\nclass BadRequestError extends Error {}\n\nfunction parseJson(text: string, message: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new BadRequestError(message);\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,iBAAiB;;;;;AA4BvB,SAAS,UAA0B,QAAkE;CACnG,IAAI,OAAO,OAAO,UAAU;CAC5B,KAAK,MAAM,QAAQ;EAAC;EAAa;EAAS;CAAO,GAAG;EAClD,MAAM,WAAW,QAAQ,OAAO,SAAS,MAAM,IAAI;EACnD,IAAI,CAAC,UAAU,OAAO,KAAA;EACtB,OAAO,OAAO,YAAY,OAAO,OAAO,QAAQ,CAAC;CACnD;CACA,MAAM,UAAU,OAAO,OAAO,QAAQ,IAAI,IAAI,CAAC;CAC/C,MAAM,yBAAS,IAAI,IAAqF;CACxG,KAAK,MAAM,UAAU,SACnB,KAAK,MAAM,YAAY,OAAO,WAAW,MAAM,GAAG;EAChD,MAAM,WAAW,OAAO,OAAO,QAAQ;EACvC,MAAM,OAAO,OAAO,OAAO,QAAQ;EACnC,MAAM,SAAS,OAAO,IAAI,IAAI,KAAK;GAAE,OAAO,CAAC;GAAG,MAAM;GAAG,UAAU;GAAO,UAAU;EAAM;EAC1F,MAAM,OAAO,OAAO,KAAK,OAAO,YAAY,QAAQ,CAAC;EACrD,IAAI,CAAC,OAAO,MAAM,SAAS,IAAI,GAAG,OAAO,MAAM,KAAK,IAAI;EACxD,OAAO,QAAQ;EACf,OAAO,aAAa,OAAO,WAAW,QAAQ;EAC9C,OAAO,aAAa,OAAO,WAAW,QAAQ;EAC9C,OAAO,IAAI,MAAM,MAAM;CACzB;CAEF,IAAI,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B,KAAA,KAAa,YAAY,OAAO,cAAc,EAC7E,GAEA,MAAM,IAAI,gBAAgB,+DAA+D;CAE3F,IAAI,KAAK,aAAa,KAAA,KAAa,OAAO,KAAK,aAAa,UAC1D,MAAM,IAAI,gBAAgB,6BAA6B;CACzD,OAAO;EACL;EACgB;EACP;EACT;EACA,UAAU,KAAK;CACjB;AACF;AASA,SAAS,UAAU,MAA0B;CAC3C,IAAI,CAAC,aAAa,IAAI,GAAG,MAAM,IAAI,gBAAgB,wCAAwC;CAC3F,MAAM,EAAE,KAAK,SAAS,gBAAgB,YAAY;CAClD,IAAI,YAAY,KAAA,KAAa,OAAO,YAAY,UAAU,MAAM,IAAI,gBAAgB,4BAA4B;CAChH,IAAI,QAAQ,KAAA,KAAa,CAAC,aAAa,GAAG,GAAG,MAAM,IAAI,gBAAgB,yBAAyB;CAChG,IAAI,YAAY,KAAA,KAAa,CAAC,aAAa,OAAO,GAAG,MAAM,IAAI,gBAAgB,6BAA6B;CAC5G,IAAI,mBAAmB,KAAA,KAAa,CAAC,YAAY,cAAc,GAC7D,MAAM,IAAI,gBAAgB,gDAAgD;CAE5E,OAAO;EAAE;EAAK;EAAS;EAAgB;CAAQ;AACjD;;AAGA,MAAM,0BAAU,IAAI,MAAM,SAAS;;AAGnC,IAAM,kBAAN,cAA8B,MAAM,CAAC;AAErC,SAAS,UAAU,MAAc,SAA0B;CACzD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,MAAM,IAAI,gBAAgB,OAAO;CACnC;AACF;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lines-db/studio",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.5",
|
|
4
4
|
"description": "Browser UI and local server for lines-db",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./dist/index.d.mts",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"CHANGELOG.md"
|
|
17
17
|
],
|
|
18
18
|
"engines": {
|
|
19
|
-
"node": ">=22.
|
|
19
|
+
"node": ">=22.18.0"
|
|
20
20
|
},
|
|
21
21
|
"license": "MIT",
|
|
22
22
|
"author": "toiroakr",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"directory": "studio"
|
|
27
27
|
},
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"lines-db": "^0.
|
|
29
|
+
"lines-db": "^0.19.0",
|
|
30
30
|
"typescript": ">=5 <7 || >=7.1.0-0"
|
|
31
31
|
},
|
|
32
32
|
"peerDependenciesMeta": {
|
|
@@ -35,15 +35,18 @@
|
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@types/node": "^
|
|
38
|
+
"@types/node": "^26.6.6",
|
|
39
39
|
"publint": "^0.3.25",
|
|
40
|
-
"tsdown": "^0.23.
|
|
40
|
+
"tsdown": "^0.23.4",
|
|
41
41
|
"typescript": "^6.0.3",
|
|
42
42
|
"valibot": "^1.5.0",
|
|
43
43
|
"vitest": "^5.0.5",
|
|
44
|
-
"lines-db": "0.
|
|
44
|
+
"lines-db": "0.19.0",
|
|
45
45
|
"zod": "^4.6.7"
|
|
46
46
|
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"zygiella": "0.1.3"
|
|
49
|
+
},
|
|
47
50
|
"scripts": {
|
|
48
51
|
"build": "tsdown && pnpm --filter @toiroakr/lines-db-studio-ui build",
|
|
49
52
|
"publint": "publint",
|