@rebasepro/studio 0.30.0 → 0.31.0-canary.g59cd6fd
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/dist/{ApiKeysView-Bqf6XYR1.js → ApiKeysView-9ZvwMPyh.js} +16 -6
- package/dist/ApiKeysView-9ZvwMPyh.js.map +1 -0
- package/dist/{JSEditor-DCnPXsx6.js → JSEditor-ojAVSkaU.js} +158 -100
- package/dist/JSEditor-ojAVSkaU.js.map +1 -0
- package/dist/{RLSEditor-zAat58U0.js → RLSEditor-BAwkENpj.js} +394 -206
- package/dist/RLSEditor-BAwkENpj.js.map +1 -0
- package/dist/{SQLEditor-DV_VEEpL.js → SQLEditor-DX9LfbU7.js} +10 -8
- package/dist/SQLEditor-DX9LfbU7.js.map +1 -0
- package/dist/{SchemaVisualizer-pCYQ_Ds6.js → SchemaVisualizer-C75TENPm.js} +196 -189
- package/dist/SchemaVisualizer-C75TENPm.js.map +1 -0
- package/dist/components/JSEditor/JSEditorSidebar.d.ts +3 -6
- package/dist/components/JSEditor/JSMonacoEditor.d.ts +10 -10
- package/dist/components/JSEditor/table_access.d.ts +39 -0
- package/dist/components/RLSEditor/policy-presets.d.ts +1 -1
- package/dist/components/RLSEditor/policyListing.d.ts +32 -12
- package/dist/components/RLSEditor/policyRules.d.ts +32 -14
- package/dist/components/RLSEditor/saveRules.d.ts +48 -18
- package/dist/components/RLSEditor/saveSecurityRules.d.ts +5 -4
- package/dist/components/SchemaVisualizer/useSchemaGraph.d.ts +13 -8
- package/dist/components/schema-source.d.ts +37 -0
- package/dist/index.es.js +9 -9
- package/dist/index.es.js.map +1 -1
- package/dist/schema-source-C4ekB7WU.js +93 -0
- package/dist/schema-source-C4ekB7WU.js.map +1 -0
- package/dist/{sql_utils-DXvmxiCq.js → sql_utils-CYcgpgam.js} +14 -12
- package/dist/sql_utils-CYcgpgam.js.map +1 -0
- package/dist/utils/sql_utils.d.ts +14 -10
- package/package.json +9 -9
- package/dist/ApiKeysView-Bqf6XYR1.js.map +0 -1
- package/dist/JSEditor-DCnPXsx6.js.map +0 -1
- package/dist/RLSEditor-zAat58U0.js.map +0 -1
- package/dist/SQLEditor-DV_VEEpL.js.map +0 -1
- package/dist/SchemaVisualizer-pCYQ_Ds6.js.map +0 -1
- package/dist/sql_utils-DXvmxiCq.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"SchemaVisualizer-pCYQ_Ds6.js","names":[],"sources":["../src/components/SchemaVisualizer/dagre-layout.ts","../src/components/SchemaVisualizer/layout-runner.ts","../src/components/SchemaVisualizer/schema-visualizer.utils.ts","../src/components/SchemaVisualizer/useSchemaGraph.ts","../src/components/SchemaVisualizer/useLiveRls.ts","../src/components/SchemaVisualizer/TableNode.tsx","../src/components/SchemaVisualizer/RelationEdge.tsx","../src/components/SchemaVisualizer/SchemaVisualizer.tsx"],"sourcesContent":["import dagre from \"dagre\";\n\n/**\n * What the layout reads, as plain data: each table's id and box, each\n * relation's ends. Plain so it can cross into the layout worker unchanged.\n */\nexport interface LayoutInput {\n nodes: { id: string; width: number; height: number }[];\n edges: { source: string; target: string }[];\n}\n\n/** Each table's top-left corner, by node id. */\nexport type LayoutPositions = Record<string, { x: number; y: number }>;\n\n/**\n * Place the graph with dagre, top to bottom.\n *\n * An ERD read as a column of tables fits the tall, narrow canvas the\n * visualizer is given, and it is the only layout the visualizer offers.\n * Deterministic: the same input always gives the same positions.\n *\n * The cost is in dagre's ordering phase and grows fast with cross-linked\n * graphs — 5 s at 200 tables with two relations each, 90 s at 500 — which is\n * why the visualizer runs this in a worker (`dagre-layout.worker.ts`).\n */\nexport function runDagre(input: LayoutInput): LayoutPositions {\n const g = new dagre.graphlib.Graph();\n g.setGraph({\n rankdir: \"TB\",\n nodesep: 100,\n ranksep: 180,\n edgesep: 60,\n marginx: 60,\n marginy: 60\n });\n g.setDefaultEdgeLabel(() => ({}));\n\n for (const node of input.nodes) {\n g.setNode(node.id, {\n width: node.width,\n height: node.height\n });\n }\n for (const edge of input.edges) {\n g.setEdge(edge.source, edge.target);\n }\n\n dagre.layout(g);\n\n const positions: LayoutPositions = {};\n for (const node of input.nodes) {\n const placed = g.node(node.id);\n positions[node.id] = {\n x: placed.x - node.width / 2,\n y: placed.y - node.height / 2\n };\n }\n return positions;\n}\n","/// <reference types=\"vite/client\" />\nimport { runDagre, type LayoutInput, type LayoutPositions } from \"./dagre-layout\";\nimport type { LayoutWorkerReply } from \"./dagre-layout.worker\";\n\n/**\n * Whether this environment can start the layout worker.\n *\n * No in tests (jsdom has no `Worker`) and on a server render; there the\n * layout runs where it is asked for, as it always did.\n */\nexport const canLayOutOffThread = (): boolean =>\n typeof Worker !== \"undefined\" &&\n typeof Blob !== \"undefined\" &&\n typeof URL !== \"undefined\" &&\n typeof URL.createObjectURL === \"function\";\n\n/**\n * Lay a graph out in a worker of its own, which ends with the layout.\n *\n * The worker is inlined into the bundle (`?worker&inline`) rather than emitted\n * as a file beside it: `@rebasepro/studio` is a library, and a worker file\n * would be found only by an app bundler that rewrites\n * `new URL(…, import.meta.url)` inside dependencies, which Vite's dependency\n * pre-bundling does not. Imported on first use, so a page that never lays a\n * graph out never decodes it.\n *\n * A worker that cannot be started or loaded — a Content-Security-Policy\n * without `blob:` in `worker-src`, say — is not a broken diagram: the layout\n * runs on the main thread instead, as it did before there was a worker.\n */\nexport async function layOutOffThread(input: LayoutInput): Promise<LayoutPositions> {\n const { default: LayoutWorker } = await import(\"./dagre-layout.worker?worker&inline\");\n let worker: Worker;\n try {\n worker = new LayoutWorker({ name: \"rebase-schema-layout\" });\n } catch {\n return runDagre(input);\n }\n return new Promise<LayoutPositions>((resolve, reject) => {\n worker.addEventListener(\"message\", (event: MessageEvent<LayoutWorkerReply>) => {\n worker.terminate();\n const reply = event.data;\n if (\"positions\" in reply) resolve(reply.positions);\n else reject(new Error(reply.error));\n });\n // Only a worker that never ran gets here: the layout's own errors come\n // back as a reply.\n worker.addEventListener(\"error\", (event) => {\n event.preventDefault();\n worker.terminate();\n try {\n resolve(runDagre(input));\n } catch (error) {\n reject(error);\n }\n });\n worker.postMessage(input);\n });\n}\n","import type { Node, Edge } from \"@xyflow/react\";\nimport { runDagre, type LayoutInput, type LayoutPositions } from \"./dagre-layout\";\nimport { layOutOffThread } from \"./layout-runner\";\n\n// ─── Layout Constants ─────────────────────────────────────────────────\nexport const NODE_WIDTH = 280;\n/** Header with a single line of text (junction tables or tableName === collectionName). */\nconst HEADER_HEIGHT_SINGLE = 33;\n/** Header with two lines (name + subtitle when collectionName !== tableName). */\nconst HEADER_HEIGHT_DOUBLE = 47;\nconst ROW_HEIGHT = 28; // height per column row\n\n/**\n * Compute the correct header height for a table node.\n */\nexport const getHeaderHeight = (opts: {\n isJunction: boolean;\n collectionName: string;\n tableName: string;\n}): number => {\n if (opts.isJunction) return HEADER_HEIGHT_SINGLE;\n return opts.collectionName !== opts.tableName\n ? HEADER_HEIGHT_DOUBLE\n : HEADER_HEIGHT_SINGLE;\n};\n\n/**\n * Estimate the pixel height of a table node based on column count.\n */\nconst estimateNodeHeight = (columnCount: number, headerHeight: number = HEADER_HEIGHT_DOUBLE): number =>\n headerHeight + Math.max(columnCount, 1) * ROW_HEIGHT + 4; // +4 for bottom padding\n\n/**\n * Get the vertical center Y of a specific column row (0-indexed)\n * relative to the top of the node.\n */\nexport const getColumnRowY = (rowIndex: number, headerHeight: number = HEADER_HEIGHT_DOUBLE): number =>\n headerHeight + rowIndex * ROW_HEIGHT + ROW_HEIGHT / 2;\n\n// ─── Auto-Layout via Dagre ────────────────────────────────────────────\n\n/** A graph's layout input, and the key its positions are kept under. */\nexport interface LayoutPlan {\n input: LayoutInput;\n signature: string;\n}\n\n/**\n * What dagre will be given for these nodes and edges: each node's id and\n * box, each edge's ends, in order. The signature is all of it, so a changed\n * schema — a table, a column count, a relation — is a different key.\n */\nexport const planLayout = (nodes: Node[], edges: Edge[]): LayoutPlan => {\n const input: LayoutInput = {\n nodes: nodes.map((node) => {\n const data = node.data as { columns?: unknown[]; isJunction?: boolean; collectionName?: string; tableName?: string };\n const headerH = getHeaderHeight({\n isJunction: Boolean(data.isJunction),\n collectionName: data.collectionName ?? \"\",\n tableName: data.tableName ?? \"\"\n });\n return {\n id: node.id,\n width: NODE_WIDTH,\n height: estimateNodeHeight(data.columns?.length ?? 3, headerH)\n };\n }),\n edges: edges.map((edge) => ({\n source: edge.source,\n target: edge.target\n }))\n };\n const signature = `${input.nodes.map(node => `${node.id}:${node.height}`).join(\"|\")}#${input.edges.map(edge => `${edge.source}>${edge.target}`).join(\"|\")}`;\n return {\n input,\n signature\n };\n};\n\n/**\n * Positions of the graphs laid out in this page's life, by\n * {@link LayoutPlan.signature}: the most recent few.\n *\n * Dagre takes 4.5–5 s at 200 cross-linked tables and 90 s at 500, so a graph\n * is laid out once: not again when the live RLS answer arrives (a badge, not\n * the graph), nor when the view is reopened. The layout is deterministic, so\n * an entry never goes stale. Holds geometry only, nothing read from the\n * database.\n */\nconst layoutCache = new Map<string, LayoutPositions>();\nconst LAYOUT_CACHE_SIZE = 16;\n\nconst rememberLayout = (signature: string, positions: LayoutPositions): LayoutPositions => {\n layoutCache.set(signature, positions);\n if (layoutCache.size > LAYOUT_CACHE_SIZE) {\n const oldest = layoutCache.keys().next().value;\n if (oldest !== undefined) layoutCache.delete(oldest);\n }\n return positions;\n};\n\n/** The positions for this plan, if it has been laid out before. */\nexport const cachedLayout = (plan: LayoutPlan): LayoutPositions | undefined =>\n layoutCache.get(plan.signature);\n\n/** Lay the plan out here, on the calling thread. */\nexport const layOutNow = (plan: LayoutPlan): LayoutPositions =>\n cachedLayout(plan) ?? rememberLayout(plan.signature, runDagre(plan.input));\n\n/** Layouts running in a worker, by signature, so a second ask waits for the first. */\nconst layoutsInFlight = new Map<string, Promise<LayoutPositions>>();\n\n/**\n * Lay the plan out in a worker; the main thread stays free while it runs.\n * See {@link layOutOffThread}.\n */\nexport const layOutInBackground = (plan: LayoutPlan): Promise<LayoutPositions> => {\n const cached = cachedLayout(plan);\n if (cached) return Promise.resolve(cached);\n const running = layoutsInFlight.get(plan.signature);\n if (running) return running;\n const job = layOutOffThread(plan.input)\n .then((positions) => rememberLayout(plan.signature, positions))\n .finally(() => layoutsInFlight.delete(plan.signature));\n layoutsInFlight.set(plan.signature, job);\n return job;\n};\n\n/** The nodes at their laid-out positions, as new objects. */\nexport const placeNodes = (nodes: Node[], positions: LayoutPositions): Node[] =>\n nodes.map((node) => ({\n ...node,\n position: { ...(positions[node.id] ?? {\n x: 0,\n y: 0\n }) }\n }));\n\n// ─── Edge styling by relation type ────────────────────────────────────\n\nexport interface RelationEdgeData {\n cardinality: \"one\" | \"many\";\n direction: \"owning\" | \"inverse\";\n relationName: string;\n hasJunction: boolean;\n hasJoinPath: boolean;\n label: string;\n}\n\nexport const getCardinalityLabel = (\n cardinality: \"one\" | \"many\",\n direction: \"owning\" | \"inverse\"\n): string => {\n if (cardinality === \"many\") return \"M:N\";\n if (direction === \"inverse\") return \"1:1 ←\";\n return \"N:1\";\n};\n","import { useMemo, useState, useCallback, useEffect } from \"react\";\nimport type { Node, Edge } from \"@xyflow/react\";\nimport { MarkerType } from \"@xyflow/react\";\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport type { Relation, ResolvedRelation } from \"@rebasepro/types\";\nimport { getTableName, resolveCollectionRelations } from \"@rebasepro/common\";\nimport {\n cachedLayout,\n getCardinalityLabel,\n layOutInBackground,\n layOutNow,\n NODE_WIDTH,\n placeNodes,\n planLayout\n} from \"./schema-visualizer.utils\";\nimport type { RelationEdgeData } from \"./schema-visualizer.utils\";\nimport type { LayoutPositions } from \"./dagre-layout\";\nimport { canLayOutOffThread } from \"./layout-runner\";\nimport type { AdminCollection, AdminPostgresCollection } from \"@rebasepro/cms-types\";\n\n// ─── Column info extracted from a collection ──────────────────────────\n\nexport interface ColumnInfo {\n name: string;\n type: string;\n /**\n * The type the collection declares — `string`, `number`, `date`… — or\n * `FK` for a relation's key. Not the database's column type: the diagram\n * is drawn from the collections, and a property's column type depends on\n * more than its `type` (`columnType`, `isId`, integer validation).\n */\n typeLabel: string;\n isPrimaryKey: boolean;\n isForeignKey: boolean;\n isRequired: boolean;\n isEnum: boolean;\n enumValues?: string[];\n relationName?: string;\n}\n\n// ─── Node data shape ──────────────────────────────────────────────────\n\nexport interface TableNodeData {\n tableName: string;\n collectionName: string;\n slug: string;\n columns: ColumnInfo[];\n isJunction: boolean;\n isUnmanaged: boolean;\n rlsEnabled: boolean;\n historyEnabled: boolean;\n icon?: string;\n [key: string]: unknown;\n}\n\n// ─── Extract columns from a AdminCollection ─────────────────────────\n\nconst extractColumns = (collection: AdminCollection): ColumnInfo[] => {\n const columns: ColumnInfo[] = [];\n const properties = collection.properties ?? {};\n\n for (const [propName, prop] of Object.entries(properties)) {\n if (prop.type === \"relation\") continue; // Relations are shown as edges, not columns\n\n const isPk =\n (\"isId\" in prop && Boolean(prop.isId)) ||\n (!Object.values(properties).some(\n (p) => \"isId\" in p && Boolean(p.isId)\n ) &&\n propName === \"id\");\n\n const isEnum = prop.type === \"string\" && \"enum\" in prop && Boolean(prop.enum);\n\n let enumValues: string[] | undefined;\n if (isEnum && \"enum\" in prop && prop.enum) {\n const enumProp = prop.enum;\n if (Array.isArray(enumProp)) {\n enumValues = enumProp.map((v: unknown) =>\n typeof v === \"string\" ? v : String((v as Record<string, unknown>)?.id ?? v)\n );\n } else if (typeof enumProp === \"object\" && enumProp !== null) {\n enumValues = Object.keys(enumProp);\n }\n }\n\n columns.push({\n name: propName,\n type: prop.type,\n typeLabel: prop.type,\n isPrimaryKey: isPk,\n isForeignKey: false,\n isRequired: Boolean(prop.validation?.required),\n isEnum,\n enumValues\n });\n }\n\n // Add FK columns from owning relations\n if (isPostgresCollectionConfig(collection)) {\n try {\n const resolvedRelations = resolveCollectionRelations(collection);\n for (const rel of Object.values(resolvedRelations)) {\n if (rel.kind === \"belongsTo\" && rel.localKey) {\n // Only add if not already present as a regular column\n if (!columns.some((c) => c.name === rel.localKey)) {\n columns.push({\n name: rel.localKey,\n type: \"number\",\n typeLabel: \"FK\",\n isPrimaryKey: false,\n isForeignKey: true,\n isRequired: false,\n isEnum: false,\n relationName: rel.relationName\n });\n } else {\n // Mark existing column as FK\n const existing = columns.find((c) => c.name === rel.localKey);\n if (existing) {\n existing.isForeignKey = true;\n existing.relationName = rel.relationName;\n }\n }\n }\n }\n } catch {\n // Ignore resolution errors\n }\n }\n\n return columns;\n};\n\n// ─── Build graph from collections ─────────────────────────────────────\n\n/**\n * Every table and relation the collections declare, not yet placed. Edges\n * carry their column handles without a side; {@link placeGraph} picks the\n * side once it knows where the tables are.\n */\ninterface SchemaGraph {\n nodes: Node[];\n edges: Edge[];\n}\n\nconst buildGraph = (\n collections: AdminCollection[],\n liveRls: Set<string> | null\n): SchemaGraph => {\n /**\n * Is RLS on for this table?\n *\n * The database is the authority whenever we could reach it. Declaring rules\n * in code is not the same as having them applied, and the hosted console\n * never sees the declarations at all — see `useLiveRlsTables`. Only when\n * there is no SQL capability do we fall back to what the config says.\n */\n const isRlsEnabled = (schema: string, tableName: string, declaresRules: boolean): boolean =>\n liveRls ? liveRls.has(`${schema}.${tableName}`) : declaresRules;\n\n const nodes: Node[] = [];\n const edges: Edge[] = [];\n const tableToNodeId = new Map<string, string>();\n // Track columns per node so we can resolve handle IDs for edges\n const nodeColumns = new Map<string, ColumnInfo[]>();\n\n // Helper: find the PK column name for a node (falls back to \"id\")\n const getPkHandle = (nodeId: string): string => {\n const cols = nodeColumns.get(nodeId);\n const pk = cols?.find((c) => c.isPrimaryKey);\n return pk ? `target-${pk.name}` : \"target-default\";\n };\n\n // Helper: find the FK column name for a node pointing to a relation\n const getFkHandle = (nodeId: string, localKey: string | undefined): string => {\n if (!localKey) return \"source-default\";\n const cols = nodeColumns.get(nodeId);\n const fk = cols?.find((c) => c.name === localKey);\n return fk ? `source-${fk.name}` : \"source-default\";\n };\n\n // 1. Create nodes for each collection\n //\n // Named by `getTableName`, the table `db push` creates: `table`, or the\n // slug in snake case. The slug as it stands (`blog-posts`) names a table\n // the database does not have, and the live RLS answer is keyed by the real\n // one.\n for (const collection of collections) {\n if (!isPostgresCollectionConfig(collection)) continue;\n\n const tableName = getTableName(collection);\n const nodeId = `table-${tableName}`;\n tableToNodeId.set(tableName, nodeId);\n\n const columns = extractColumns(collection);\n nodeColumns.set(nodeId, columns);\n\n const nodeData: TableNodeData = {\n tableName,\n collectionName: collection.name,\n slug: collection.slug,\n columns,\n isJunction: false,\n isUnmanaged: false,\n rlsEnabled: isRlsEnabled(\n collection.schema ?? \"public\",\n tableName,\n Boolean(collection.securityRules && collection.securityRules.length > 0)\n ),\n historyEnabled: Boolean(collection.history),\n icon: typeof collection.icon === \"string\" ? collection.icon : undefined\n };\n\n nodes.push({\n id: nodeId,\n type: \"tableNode\",\n position: { x: 0,\ny: 0 },\n data: nodeData\n });\n }\n\n // 2. Create junction table nodes and edges\n const processedJunctions = new Set<string>();\n\n for (const collection of collections) {\n if (!isPostgresCollectionConfig(collection)) continue;\n\n const tableName = getTableName(collection);\n const sourceNodeId = tableToNodeId.get(tableName);\n if (!sourceNodeId) continue;\n\n let resolvedRelations: Record<string, ResolvedRelation>;\n try {\n resolvedRelations = resolveCollectionRelations(collection);\n } catch {\n continue;\n }\n\n for (const [relationKey, rel] of Object.entries(resolvedRelations)) {\n let targetCollection: AdminCollection;\n try {\n targetCollection = rel.target();\n } catch {\n continue;\n }\n\n if (!isPostgresCollectionConfig(targetCollection)) continue;\n\n const targetTable = getTableName(targetCollection);\n const targetNodeId = tableToNodeId.get(targetTable);\n if (!targetNodeId) continue;\n\n // Draw the side that owns the storage: a foreign key on this table,\n // or the junction. `hasOne`/`hasMany` are the mirror image of a\n // `belongsTo` that is drawn from the other end, and `via` has no\n // single edge to draw.\n if (rel.kind !== \"belongsTo\" && rel.kind !== \"manyToMany\") continue;\n\n const direction = \"owning\" as const;\n const edgeData: RelationEdgeData = {\n cardinality: rel.cardinality,\n direction,\n relationName: rel.relationName ?? relationKey,\n hasJunction: rel.kind === \"manyToMany\",\n hasJoinPath: false,\n label: getCardinalityLabel(rel.cardinality, direction)\n };\n\n if (rel.kind === \"manyToMany\" && !processedJunctions.has(rel.through.table)) {\n // Many-to-many: create junction node + two edges\n processedJunctions.add(rel.through.table);\n const junctionNodeId = `junction-${rel.through.table}`;\n\n const junctionColumns: ColumnInfo[] = [\n {\n name: rel.through.sourceColumn,\n type: \"number\",\n typeLabel: \"FK\",\n isPrimaryKey: true,\n isForeignKey: true,\n isRequired: true,\n isEnum: false\n },\n {\n name: rel.through.targetColumn,\n type: \"number\",\n typeLabel: \"FK\",\n isPrimaryKey: true,\n isForeignKey: true,\n isRequired: true,\n isEnum: false\n }\n ];\n nodeColumns.set(junctionNodeId, junctionColumns);\n\n nodes.push({\n id: junctionNodeId,\n type: \"tableNode\",\n position: { x: 0,\ny: 0 },\n data: {\n tableName: rel.through.table,\n collectionName: rel.through.table,\n slug: rel.through.table,\n columns: junctionColumns,\n isJunction: true,\n isUnmanaged: false,\n // Junction tables get derived policies rather than\n // declared ones, so the config can never say — but the\n // database can, and usually says yes.\n rlsEnabled: isRlsEnabled(\"public\", rel.through.table, false),\n historyEnabled: false\n } satisfies TableNodeData\n });\n\n // Source table → junction (junction references source PK)\n const sourcePk = nodeColumns.get(sourceNodeId)?.find((c) => c.isPrimaryKey);\n edges.push({\n id: `edge-${sourceNodeId}-${junctionNodeId}`,\n source: sourceNodeId,\n target: junctionNodeId,\n sourceHandle: sourcePk ? `source-${sourcePk.name}` : \"source-default\",\n targetHandle: `target-${rel.through.sourceColumn}`,\n type: \"relationEdge\",\n data: { ...edgeData,\nlabel: \"1:N\" } as Record<string, unknown>,\n markerEnd: { type: MarkerType.ArrowClosed,\nwidth: 16,\nheight: 16 }\n });\n\n // Junction → target table\n edges.push({\n id: `edge-${junctionNodeId}-${targetNodeId}`,\n source: junctionNodeId,\n target: targetNodeId,\n sourceHandle: `source-${rel.through.targetColumn}`,\n targetHandle: getPkHandle(targetNodeId),\n type: \"relationEdge\",\n data: { ...edgeData,\nlabel: \"N:1\" } as Record<string, unknown>,\n markerEnd: { type: MarkerType.ArrowClosed,\nwidth: 16,\nheight: 16 }\n });\n } else if (rel.kind === \"belongsTo\") {\n // A foreign key on this table.\n edges.push({\n id: `edge-${sourceNodeId}-${targetNodeId}-${relationKey}`,\n source: sourceNodeId,\n target: targetNodeId,\n sourceHandle: getFkHandle(sourceNodeId, rel.localKey),\n targetHandle: getPkHandle(targetNodeId),\n type: \"relationEdge\",\n data: { ...edgeData } as Record<string, unknown>,\n markerEnd: { type: MarkerType.ArrowClosed,\nwidth: 16,\nheight: 16 }\n });\n }\n }\n }\n return {\n nodes,\n edges\n };\n};\n\n/**\n * The graph at its laid-out positions, with each edge's handles on the sides\n * that face each other: a source left of its target exits right and enters\n * the target from the left, and the other way round.\n */\nconst placeGraph = (graph: SchemaGraph, positions: LayoutPositions): SchemaGraph => {\n const nodes = placeNodes(graph.nodes, positions);\n const edges = graph.edges.map((edge) => {\n const srcPos = positions[edge.source];\n const tgtPos = positions[edge.target];\n const srcBaseHandle = edge.sourceHandle ?? \"source-default\";\n const tgtBaseHandle = edge.targetHandle ?? \"target-default\";\n if (!srcPos || !tgtPos) {\n return {\n ...edge,\n sourceHandle: `${srcBaseHandle}-right`,\n targetHandle: `${tgtBaseHandle}-left`\n };\n }\n const sourceIsLeft = srcPos.x + NODE_WIDTH / 2 <= tgtPos.x + NODE_WIDTH / 2;\n return {\n ...edge,\n sourceHandle: `${srcBaseHandle}-${sourceIsLeft ? \"right\" : \"left\"}`,\n targetHandle: `${tgtBaseHandle}-${sourceIsLeft ? \"left\" : \"right\"}`\n };\n });\n return {\n nodes,\n edges\n };\n};\n\n// ─── Large schemas: one table's neighbourhood ─────────────────────────\n\n/**\n * Above this many tables the diagram draws one table's neighbourhood, not\n * the whole schema. Laying out 300 cross-linked tables takes dagre several\n * seconds even in a worker, and a canvas of that many tables is no longer\n * something anyone reads.\n */\nexport const LARGE_SCHEMA_TABLES = 300;\n\n/** How far from the focused table the drawn neighbourhood reaches. */\nexport type NeighbourhoodDepth = 1 | 2;\n\nconst isJunctionNode = (node: Node): boolean => Boolean((node.data as TableNodeData).isJunction);\n\n/**\n * The tables within `depth` relations of `focus`, and every relation between\n * them.\n *\n * A junction table is not a step of its own: a many-to-many is one relation,\n * drawn through its junction. So distances are counted in half steps — an edge\n * that touches a junction is one, a foreign key between two tables is two.\n */\nconst neighbourhoodOf = (graph: SchemaGraph, focus: string, depth: NeighbourhoodDepth): SchemaGraph => {\n const junctions = new Set(graph.nodes.filter(isJunctionNode).map((node) => node.id));\n const adjacent = new Map<string, string[]>();\n for (const edge of graph.edges) {\n adjacent.set(edge.source, [...(adjacent.get(edge.source) ?? []), edge.target]);\n adjacent.set(edge.target, [...(adjacent.get(edge.target) ?? []), edge.source]);\n }\n const limit = depth * 2;\n const distance = new Map<string, number>([[focus, 0]]);\n const byDistance: string[][] = Array.from({ length: limit + 1 }, () => []);\n byDistance[0].push(focus);\n for (let reached = 0; reached <= limit; reached++) {\n for (const id of byDistance[reached]) {\n if (distance.get(id) !== reached) continue;\n for (const next of adjacent.get(id) ?? []) {\n const step = junctions.has(id) || junctions.has(next) ? 1 : 2;\n const nextDistance = reached + step;\n if (nextDistance > limit || (distance.get(next) ?? Infinity) <= nextDistance) continue;\n distance.set(next, nextDistance);\n byDistance[nextDistance].push(next);\n }\n }\n }\n return {\n nodes: graph.nodes.filter((node) => distance.has(node.id)),\n edges: graph.edges.filter((edge) => distance.has(edge.source) && distance.has(edge.target))\n };\n};\n\n/** The table with the most relations: where a large schema opens. */\nconst mostConnectedTable = (graph: SchemaGraph): string | undefined => {\n const degree = new Map<string, number>();\n for (const edge of graph.edges) {\n degree.set(edge.source, (degree.get(edge.source) ?? 0) + 1);\n degree.set(edge.target, (degree.get(edge.target) ?? 0) + 1);\n }\n let best: Node | undefined;\n for (const node of graph.nodes) {\n if (isJunctionNode(node)) continue;\n if (!best || (degree.get(node.id) ?? 0) > (degree.get(best.id) ?? 0)) best = node;\n }\n return best?.id;\n};\n\n// ─── Hook ─────────────────────────────────────────────────────────────\n\nexport interface UseSchemaGraphResult {\n /**\n * The tables and relations on the canvas, placed. Empty while\n * {@link layingOut} — the layout of a graph not seen before runs in a\n * worker, never in render.\n */\n nodes: Node[];\n edges: Edge[];\n /** Every table and junction table in the schema, drawn or not. */\n allNodes: Node[];\n relayout: () => void;\n /** Tables and relations in the whole schema. */\n tableCount: number;\n relationCount: number;\n /** The layout is running off the main thread. */\n layingOut: boolean;\n /**\n * Set when the schema has more than {@link LARGE_SCHEMA_TABLES} tables:\n * which table's neighbourhood is drawn, how far it reaches, how many\n * tables that is, and how many there are in all.\n */\n neighbourhood: { focus: string; depth: NeighbourhoodDepth; shown: number; total: number } | null;\n}\n\nconst EMPTY_GRAPH: SchemaGraph = {\n nodes: [],\n edges: []\n};\nconst NO_POSITIONS: LayoutPositions = {};\n\nexport const useSchemaGraph = (\n collections: AdminCollection[] | undefined,\n /**\n * `schema.table` for every table the database reports RLS on, or `null`\n * when there is no SQL capability to ask. See {@link useLiveRlsTables}.\n */\n liveRls: Set<string> | null = null,\n /**\n * The table whose neighbourhood a large schema draws, by node id. When it\n * is absent, or not a table of this schema, the most connected one. Not\n * read for a schema of {@link LARGE_SCHEMA_TABLES} tables or fewer, which\n * is drawn whole.\n */\n focus: string | null = null,\n depth: NeighbourhoodDepth = 1\n): UseSchemaGraphResult => {\n const [version, setVersion] = useState(0);\n\n const relayout = useCallback(() => setVersion((v) => v + 1), []);\n\n const graph = useMemo(\n () => (collections && collections.length > 0 ? buildGraph(collections, liveRls) : EMPTY_GRAPH),\n [collections, liveRls]\n );\n\n const tables = graph.nodes.filter((node) => !isJunctionNode(node)).length;\n const large = tables > LARGE_SCHEMA_TABLES;\n const focused = large\n ? (focus && graph.nodes.some((node) => node.id === focus) ? focus : mostConnectedTable(graph)) ?? null\n : null;\n\n const drawn = useMemo(\n () => (focused ? neighbourhoodOf(graph, focused, depth) : graph),\n [graph, focused, depth]\n );\n const plan = useMemo(() => planLayout(drawn.nodes, drawn.edges), [drawn]);\n\n /**\n * Where the layout runs. Off the main thread wherever a worker can start;\n * in tests and on a server, here, as the visualizer always did.\n */\n const offThread = canLayOutOffThread();\n const [laidOut, setLaidOut] = useState<{ signature: string; positions: LayoutPositions } | null>(null);\n const [layoutError, setLayoutError] = useState<unknown>(null);\n\n const positions = drawn.nodes.length === 0\n ? NO_POSITIONS\n : cachedLayout(plan)\n ?? (laidOut?.signature === plan.signature ? laidOut.positions : undefined)\n ?? (offThread ? undefined : layOutNow(plan));\n\n useEffect(() => {\n if (!offThread || drawn.nodes.length === 0 || cachedLayout(plan)) return;\n let current = true;\n layOutInBackground(plan).then(\n (result) => {\n if (current) {\n setLaidOut({\n signature: plan.signature,\n positions: result\n });\n }\n },\n (error: unknown) => {\n if (current) setLayoutError(error);\n }\n );\n return () => {\n current = false;\n };\n }, [plan, offThread, drawn]);\n\n const placed = useMemo(\n () => (positions ? placeGraph(drawn, positions) : EMPTY_GRAPH),\n // `version` is the relayout button: new node objects put back every\n // table a person dragged.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [drawn, positions, version]\n );\n\n // The layout failing is the diagram failing, as it was when the layout\n // ran in render: the view's error boundary says so.\n if (layoutError) throw layoutError;\n\n return {\n nodes: placed.nodes,\n edges: placed.edges,\n allNodes: graph.nodes,\n relayout,\n tableCount: graph.nodes.length,\n relationCount: graph.edges.length,\n layingOut: positions === undefined,\n neighbourhood: focused\n ? {\n focus: focused,\n depth,\n shown: drawn.nodes.length,\n total: tables\n }\n : null\n };\n};\n","/**\n * Which tables actually have row-level security switched on, according to the\n * database.\n *\n * ## Why this is not read from the collection config\n *\n * The graph used to derive \"RLS protected\" from `collection.securityRules` —\n * i.e. from what the *codebase* declares. Two problems with that:\n *\n * - **It is not the truth.** Rules in code are only live once a migration has\n * applied them, and `ALTER TABLE … DISABLE ROW LEVEL SECURITY` in a psql\n * session is invisible to it. A security indicator that reports intent\n * rather than state is worse than none: it is green precisely when you most\n * need it to be red.\n * - **The hosted console has no codebase.** There, collections arrive from the\n * tenant's `/api/meta/contract`, which deliberately strips `securityRules`\n * (they carry the raw SQL of every policy guarding the project). So the\n * console showed \"RLS protected: 0\" and no badge on any table, for every\n * project, however well secured.\n *\n * `pg_tables.rowsecurity` answers the question directly and is available\n * wherever `databaseAdmin` is — which is both hosts.\n *\n * When there is no SQL capability at all the hook reports `null`, and callers\n * fall back to the config-derived flag rather than claiming everything is\n * unprotected.\n */\nimport { useEffect, useState } from \"react\";\nimport { useRebaseContext } from \"@rebasepro/app\";\n\n/** `schema.table` for every table with RLS enabled, or `null` if unknown. */\nexport type LiveRlsTables = Set<string> | null;\n\nconst RLS_TABLES_SQL = `\n SELECT schemaname, tablename, rowsecurity\n FROM pg_tables\n WHERE schemaname NOT IN ('information_schema', 'pg_catalog');\n`;\n\n/** Postgres column names arrive lower-cased over the wire, but not on every driver. */\nfunction pick<T>(row: Record<string, unknown>, name: string): T | undefined {\n return (row[name] ?? row[name.toUpperCase()]) as T | undefined;\n}\n\nfunction extractRows(result: unknown): Record<string, unknown>[] {\n if (result && typeof result === \"object\" && \"rows\" in result) {\n const rows = (result as { rows: unknown }).rows;\n if (Array.isArray(rows)) return rows as Record<string, unknown>[];\n }\n if (Array.isArray(result)) return result as Record<string, unknown>[];\n return [];\n}\n\nexport function useLiveRlsTables(): LiveRlsTables {\n const { databaseAdmin } = useRebaseContext();\n const executeSql = databaseAdmin?.executeSql;\n const [tables, setTables] = useState<LiveRlsTables>(null);\n\n useEffect(() => {\n if (!executeSql) {\n setTables(null);\n return;\n }\n let cancelled = false;\n executeSql(RLS_TABLES_SQL)\n .then((result: unknown) => {\n if (cancelled) return;\n const enabled = new Set<string>();\n for (const row of extractRows(result)) {\n if (!pick<boolean>(row, \"rowsecurity\")) continue;\n const schema = pick<string>(row, \"schemaname\") ?? \"public\";\n const table = pick<string>(row, \"tablename\");\n if (table) enabled.add(`${schema}.${table}`);\n }\n setTables(enabled);\n })\n .catch(() => {\n // No answer is not the same as \"nothing is protected\" — leave it\n // unknown so the caller keeps its config-derived fallback.\n if (!cancelled) setTables(null);\n });\n return () => { cancelled = true; };\n }, [executeSql]);\n\n return tables;\n}\n","import React, { memo, useMemo } from \"react\";\nimport { Handle, Position } from \"@xyflow/react\";\nimport type { NodeProps } from \"@xyflow/react\";\nimport { Typography, Chip, Tooltip, cls } from \"@rebasepro/ui\";\nimport { IconForView } from \"@rebasepro/app\";\nimport type { TableNodeData, ColumnInfo } from \"./useSchemaGraph\";\nimport { getColumnRowY, getHeaderHeight } from \"./schema-visualizer.utils\";\n\n/**\n * Custom React Flow node that renders a database table as a card.\n *\n * Every PK and FK column renders handles on BOTH Left and Right sides.\n * The edge builder picks which side to use based on relative node position.\n */\nconst TableNodeInner = ({ data, selected }: NodeProps) => {\n const {\n tableName,\n collectionName,\n columns,\n isJunction,\n rlsEnabled,\n historyEnabled,\n icon\n } = data as TableNodeData;\n\n // Build handles: every PK/FK column gets Left + Right handles\n const handles = useMemo(() => {\n const result: { id: string; type: \"source\" | \"target\"; position: Position; top: number }[] = [];\n const cols = columns as ColumnInfo[];\n const headerH = getHeaderHeight({\n isJunction: Boolean(isJunction),\n collectionName: collectionName as string,\n tableName: tableName as string\n });\n const midY = cols.length > 0 ? getColumnRowY(Math.floor(cols.length / 2), headerH) : 30;\n\n cols.forEach((col, idx) => {\n const y = getColumnRowY(idx, headerH);\n\n if (col.isForeignKey && !col.isPrimaryKey) {\n // FK: source handles on both sides\n result.push({ id: `source-${col.name}-right`,\ntype: \"source\",\nposition: Position.Right,\ntop: y });\n result.push({ id: `source-${col.name}-left`,\ntype: \"source\",\nposition: Position.Left,\ntop: y });\n }\n if (col.isPrimaryKey) {\n // PK: target + source handles on both sides\n result.push({ id: `target-${col.name}-right`,\ntype: \"target\",\nposition: Position.Right,\ntop: y });\n result.push({ id: `target-${col.name}-left`,\ntype: \"target\",\nposition: Position.Left,\ntop: y });\n result.push({ id: `source-${col.name}-right`,\ntype: \"source\",\nposition: Position.Right,\ntop: y });\n result.push({ id: `source-${col.name}-left`,\ntype: \"source\",\nposition: Position.Left,\ntop: y });\n }\n });\n\n // Default handles on both sides\n result.push({ id: \"target-default-right\",\ntype: \"target\",\nposition: Position.Right,\ntop: midY });\n result.push({ id: \"target-default-left\",\ntype: \"target\",\nposition: Position.Left,\ntop: midY });\n result.push({ id: \"source-default-right\",\ntype: \"source\",\nposition: Position.Right,\ntop: midY });\n result.push({ id: \"source-default-left\",\ntype: \"source\",\nposition: Position.Left,\ntop: midY });\n\n return result;\n }, [columns, isJunction, collectionName, tableName]);\n\n return (\n <div\n className={cls(\n \"relative rounded-lg border bg-surface-card shadow-sm transition-all duration-200 min-w-[240px] max-w-[320px]\",\n selected\n ? \"border-primary ring-2 ring-primary/20 shadow-md\"\n : \"border-hairline hover:shadow-md hover:border-hairline-strong\",\n isJunction && \"border-dashed\"\n )}\n >\n {/* ── Header ── */}\n <div\n className={cls(\n \"flex items-center gap-2 px-3 py-2 border-b rounded-t-lg\",\n isJunction\n ? \"bg-surface-sheet border-hairline\"\n : \"bg-surface-card border-hairline\"\n )}\n >\n {icon && !isJunction && (\n <div className=\"text-primary shrink-0\">\n <IconForView\n collectionOrView={{ slug: tableName,\nname: collectionName,\nicon }}\n size=\"smallest\"\n />\n </div>\n )}\n {isJunction && (\n <svg\n className=\"w-3.5 h-3.5 text-text-disabled dark:text-text-disabled-dark shrink-0\"\n fill=\"none\"\n stroke=\"currentColor\"\n viewBox=\"0 0 24 24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4\"\n />\n </svg>\n )}\n <div className=\"flex flex-col min-w-0\">\n <Typography\n variant=\"caption\"\n className={cls(\n \"font-semibold truncate text-[12px]\",\n isJunction\n ? \"text-text-secondary dark:text-text-secondary-dark\"\n : \"text-text-primary dark:text-text-primary-dark\"\n )}\n >\n {tableName}\n </Typography>\n {collectionName !== tableName && !isJunction && (\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark truncate\"\n >\n {collectionName}\n </Typography>\n )}\n </div>\n\n {/* Badges */}\n <div className=\"ml-auto flex items-center gap-1 shrink-0\">\n {rlsEnabled && (\n <Tooltip title=\"RLS enabled\">\n <div className=\"w-1.5 h-1.5 rounded-full bg-green-500\"/>\n </Tooltip>\n )}\n {historyEnabled && (\n <Tooltip title=\"History enabled\">\n <div className=\"w-1.5 h-1.5 rounded-full bg-blue-400\"/>\n </Tooltip>\n )}\n </div>\n </div>\n\n {/* ── Columns ── */}\n <div className=\"divide-y divide-surface-100 dark:divide-surface-950/60\">\n {(columns as ColumnInfo[]).map((col: ColumnInfo) => (\n <div\n key={col.name}\n className={cls(\n \"flex items-center gap-2 px-3 py-1.5 text-xs transition-colors\",\n col.isPrimaryKey && \"bg-amber-50/50 dark:bg-amber-950/10\",\n col.isForeignKey &&\n !col.isPrimaryKey &&\n \"bg-blue-50/40 dark:bg-blue-950/10\"\n )}\n >\n <span className=\"w-3 shrink-0 text-center\">\n {col.isPrimaryKey && (\n <Tooltip title=\"Primary Key\">\n <span className=\"text-amber-500 text-[10px] font-semibold\">🔑</span>\n </Tooltip>\n )}\n {col.isForeignKey && !col.isPrimaryKey && (\n <Tooltip title={`FK → ${col.relationName ?? \"?\"}`}>\n <span className=\"text-blue-400 text-[10px] font-semibold\">🔗</span>\n </Tooltip>\n )}\n </span>\n\n <Typography\n variant=\"caption\"\n className={cls(\n \"font-mono text-[11px] truncate flex-1 min-w-0\",\n col.isPrimaryKey\n ? \"font-semibold text-amber-700 dark:text-amber-400\"\n : col.isForeignKey\n ? \"text-blue-600 dark:text-blue-400\"\n : \"text-text-primary dark:text-text-primary-dark\"\n )}\n >\n {col.name}\n </Typography>\n\n {col.isEnum ? (\n <Chip\n size=\"smallest\"\n className=\"bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-400 border-violet-200 dark:border-violet-800 text-[9px] py-0\"\n >\n enum\n </Chip>\n ) : (\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark font-mono shrink-0\"\n >\n {col.typeLabel}\n </Typography>\n )}\n\n {col.isRequired && !col.isPrimaryKey && (\n <Tooltip title=\"Required\">\n <span className=\"text-red-400 text-[9px]\">•</span>\n </Tooltip>\n )}\n </div>\n ))}\n </div>\n\n {/* ── Handles at node root ── */}\n {handles.map((h) => (\n <Handle\n key={h.id}\n id={h.id}\n type={h.type}\n position={h.position}\n style={{ top: h.top }}\n className={cls(\n \"!w-2 !h-2 !border-2 !border-surface-card\",\n h.type === \"source\" ? \"!bg-blue-400\" : \"!bg-amber-400\"\n )}\n />\n ))}\n </div>\n );\n};\n\nexport const TableNode = memo(TableNodeInner);\n","import React, { memo } from \"react\";\nimport { BaseEdge, getSmoothStepPath, EdgeLabelRenderer } from \"@xyflow/react\";\nimport type { EdgeProps } from \"@xyflow/react\";\nimport { cls } from \"@rebasepro/ui\";\nimport type { RelationEdgeData } from \"./schema-visualizer.utils\";\n\n/**\n * Custom React Flow edge that renders relations with style variations\n * based on cardinality and direction.\n *\n * - Owning one-to-one: solid, primary color\n * - Many-to-many (junction): solid, violet\n * - Inverse: dashed, muted\n * - Join path: dotted, muted\n */\nconst RelationEdgeInner = ({\n id,\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n data,\n selected\n}: EdgeProps) => {\n const edgeData = data as RelationEdgeData | undefined;\n\n const [edgePath, labelX, labelY] = getSmoothStepPath({\n sourceX,\n sourceY,\n sourcePosition,\n targetX,\n targetY,\n targetPosition,\n borderRadius: 8\n });\n\n const isInverse = edgeData?.direction === \"inverse\";\n const isJoinPath = edgeData?.hasJoinPath;\n const isJunction = edgeData?.hasJunction;\n\n // Determine stroke style\n let strokeColor = \"var(--rf-edge-stroke, #9da2aa)\";\n let strokeDasharray: string | undefined;\n let strokeWidth = 1.5;\n\n if (selected) {\n strokeColor = \"var(--rf-edge-stroke-selected, #6366f1)\";\n strokeWidth = 2.5;\n } else if (isJunction) {\n strokeColor = \"#8b5cf6\"; // violet\n } else if (isInverse) {\n strokeDasharray = \"6 3\";\n strokeColor = \"#9da2aa\";\n } else if (isJoinPath) {\n strokeDasharray = \"3 3\";\n strokeColor = \"#9da2aa\";\n } else {\n strokeColor = \"#6366f1\"; // primary/indigo\n }\n\n return (\n <>\n <BaseEdge\n id={id}\n path={edgePath}\n style={{\n stroke: strokeColor,\n strokeWidth,\n strokeDasharray\n }}\n />\n {edgeData?.label && (\n <EdgeLabelRenderer>\n <div\n style={{\n position: \"absolute\",\n transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,\n pointerEvents: \"all\"\n }}\n className={cls(\n \"px-1.5 py-0.5 rounded text-[9px] font-mono font-semibold leading-none\",\n \"bg-surface-card border\",\n selected\n ? \"border-primary text-primary\"\n : isJunction\n ? \"border-violet-200 dark:border-violet-800 text-violet-600 dark:text-violet-400\"\n : isInverse || isJoinPath\n ? \"border-hairline-strong text-text-disabled dark:text-text-disabled-dark\"\n : \"border-primary/30 dark:border-primary/30 text-primary\"\n )}\n >\n {edgeData.label}\n </div>\n </EdgeLabelRenderer>\n )}\n </>\n );\n};\n\nexport const RelationEdge = memo(RelationEdgeInner);\n","import React, { useState, useCallback, useMemo, useEffect, useRef } from \"react\";\nimport {\n ReactFlow,\n Controls,\n MiniMap,\n Background,\n BackgroundVariant,\n useReactFlow,\n ReactFlowProvider,\n applyNodeChanges,\n applyEdgeChanges\n} from \"@xyflow/react\";\nimport type { Node, Edge, NodeChange, EdgeChange } from \"@xyflow/react\";\nimport \"@xyflow/react/dist/style.css\";\nimport {\n SearchBar,\n TextField,\n Tooltip,\n Alert,\n Typography,\n cls,\n defaultBorderMixin,\n CircularProgress,\n ResizablePanels,\n IconButton,\n ToggleButtonGroup,\n useIsDarkMode\n} from \"@rebasepro/ui\";\nimport {\n useStudioCollectionRegistry,\n IconForView,\n useTranslation\n} from \"@rebasepro/app\";\n\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName } from \"@rebasepro/common\";\nimport { useSchemaGraph } from \"./useSchemaGraph\";\nimport { useLiveRlsTables } from \"./useLiveRls\";\nimport type { NeighbourhoodDepth, TableNodeData } from \"./useSchemaGraph\";\nimport { TableNode } from \"./TableNode\";\nimport { RelationEdge } from \"./RelationEdge\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\n// ─── Custom node / edge type registrations ────────────────────────────\n\nconst nodeTypes = {\n tableNode: TableNode\n};\n\nconst edgeTypes = {\n relationEdge: RelationEdge\n};\n\n// ─── Inner component (needs ReactFlowProvider) ─────────────────────────\n\nfunction SchemaVisualizerCanvas({\n collections\n}: {\n collections: AdminCollection[];\n}) {\n const { t } = useTranslation();\n const reactFlowInstance = useReactFlow();\n const liveRls = useLiveRlsTables();\n // React Flow stamps its own `light` / `dark` class on the canvas. Left at\n // the default it stamps `light` under a dark app, which is a class our\n // theme used to answer to, and the whole canvas re-lit itself. Follow the\n // app instead so its controls, minimap and our tokens all agree.\n const isDark = useIsDarkMode();\n // A large schema is drawn one table's neighbourhood at a time; these say\n // which table, and how far out. See `LARGE_SCHEMA_TABLES`.\n const [focus, setFocus] = useState<string | null>(null);\n const [depth, setDepth] = useState<NeighbourhoodDepth>(1);\n const {\n nodes: layoutedNodes,\n edges: layoutedEdges,\n allNodes,\n relayout,\n tableCount,\n relationCount,\n layingOut,\n neighbourhood\n } = useSchemaGraph(collections, liveRls, focus, depth);\n\n const [nodes, setNodes] = useState<Node[]>([]);\n const [edges, setEdges] = useState<Edge[]>([]);\n const [selectedTable, setSelectedTable] = useState<string | null>(null);\n const [searchQuery, setSearchQuery] = useState(\"\");\n\n // Sync layouted data into state. While a new layout runs, what is drawn\n // stays drawn: a neighbourhood being replaced is not an empty canvas.\n useEffect(() => {\n if (layingOut) return;\n setNodes(layoutedNodes);\n setEdges(layoutedEdges);\n }, [layoutedNodes, layoutedEdges, layingOut]);\n\n const onNodesChange = useCallback(\n (changes: NodeChange[]) => setNodes((nds) => applyNodeChanges(changes, nds)),\n []\n );\n const onEdgesChange = useCallback(\n (changes: EdgeChange[]) => setEdges((eds) => applyEdgeChanges(changes, eds)),\n []\n );\n\n /**\n * Fit the graph into view when it is first drawn, and again whenever a\n * different neighbourhood replaces it.\n *\n * `fitView` needs every node's real width and height, which React Flow\n * only knows once it has rendered and measured them; a fit made before\n * that leaves the ERD a scatter of specks in a corner. React Flow's own\n * `fitView` waits for the measurement, so it is asked for in the commit\n * that hands it the new nodes — after its store has them, which a\n * child's effect does before this one runs.\n */\n const fitPending = useRef(true);\n useEffect(() => {\n if (!fitPending.current || nodes.length === 0) return;\n fitPending.current = false;\n void reactFlowInstance.fitView({\n padding: 0.15,\n duration: 400\n });\n }, [nodes, reactFlowInstance]);\n\n const handleFitView = useCallback(() => {\n reactFlowInstance.fitView({ padding: 0.15,\nduration: 400 });\n }, [reactFlowInstance]);\n\n const handleNodeClick = useCallback((_: React.MouseEvent, node: Node) => {\n setSelectedTable(node.id);\n }, []);\n\n const handlePaneClick = useCallback(() => {\n setSelectedTable(null);\n }, []);\n\n // Focus on a table from the sidebar. A large schema draws the picked\n // table's neighbourhood instead, and fits that once it is laid out.\n const handleTableSelect = useCallback(\n (nodeId: string) => {\n setSelectedTable(nodeId);\n if (neighbourhood) {\n if (neighbourhood.focus !== nodeId) {\n fitPending.current = true;\n setFocus(nodeId);\n }\n return;\n }\n const node = nodes.find((n) => n.id === nodeId);\n if (node) {\n reactFlowInstance.setCenter(\n node.position.x + 140,\n node.position.y + 60,\n { zoom: 1.2,\nduration: 400 }\n );\n }\n },\n [nodes, reactFlowInstance, neighbourhood]\n );\n\n const handleDepthChange = useCallback((value: string) => {\n fitPending.current = true;\n setDepth(value === \"2\" ? 2 : 1);\n }, []);\n\n // Sidebar panel size\n const [sidebarSize, setSidebarSize] = useState(() => {\n try {\n const saved = localStorage.getItem(\"rebase_schema_viz_sidebar_size\");\n return saved !== null ? parseFloat(saved) : 20;\n } catch {\n return 20;\n }\n });\n\n useEffect(() => {\n try {\n localStorage.setItem(\n \"rebase_schema_viz_sidebar_size\",\n sidebarSize.toString()\n );\n } catch {\n // Ignore\n }\n }, [sidebarSize]);\n\n // Group collections for sidebar\n const postgresCollections = useMemo(\n () => collections.filter(isPostgresCollectionConfig),\n [collections]\n );\n\n const filteredCollections = useMemo(() => {\n if (!searchQuery.trim()) return postgresCollections;\n const q = searchQuery.toLowerCase();\n return postgresCollections.filter(\n (c) =>\n c.name.toLowerCase().includes(q) ||\n getTableName(c).toLowerCase().includes(q) ||\n c.slug?.toLowerCase().includes(q)\n );\n }, [postgresCollections, searchQuery]);\n\n // Junction table nodes — every one in the schema, drawn or not.\n const junctionNodes = useMemo(\n () =>\n allNodes.filter(\n (n) => (n.data as TableNodeData).isJunction\n ),\n [allNodes]\n );\n\n /**\n * The RLS answer for one collection, from the same place the graph used.\n *\n * The graph's nodes already carry it, so look it up there rather than\n * re-deriving — that is what kept the sidebar dots, the node badges and the\n * total from agreeing. Every node, not only the drawn ones: a large schema\n * draws a neighbourhood, and the list shows every table.\n */\n const rlsByNodeId = useMemo(\n () => new Map(allNodes.map((n) => [n.id, Boolean((n.data as TableNodeData).rlsEnabled)])),\n [allNodes]\n );\n const rlsEnabledFor = useCallback(\n (collection: AdminCollection): boolean => rlsByNodeId.get(`table-${getTableName(collection)}`) ?? false,\n [rlsByNodeId]\n );\n\n const focusName = useMemo(() => {\n const node = neighbourhood ? allNodes.find((n) => n.id === neighbourhood.focus) : undefined;\n return node ? (node.data as TableNodeData).collectionName : \"\";\n }, [allNodes, neighbourhood]);\n\n // Stats\n const stats = useMemo(\n () => ({\n tables: tableCount,\n relations: relationCount,\n junctions: junctionNodes.length,\n // Counted off the nodes, which already carry the database's answer\n // where there was one — the same number the per-table badges show.\n // Counting `securityRules` here instead made the total disagree\n // with the badges, and read 0 in the hosted console, where the\n // contract endpoint strips those rules.\n withRls: allNodes.filter((n) => (n.data as TableNodeData | undefined)?.rlsEnabled).length\n }),\n [\n tableCount,\n relationCount,\n junctionNodes.length,\n allNodes\n ]\n );\n\n return (\n <ResizablePanels\n dividerAriaLabel={t(\"resize_sidebar\")}\n orientation=\"horizontal\"\n panelSizePercent={sidebarSize}\n onPanelSizeChange={setSidebarSize}\n minPanelSizePx={220}\n firstPanel={\n <div\n className={cls(\n \"flex flex-col h-full w-full bg-surface-card border-r\",\n defaultBorderMixin\n )}\n >\n {/* Sidebar header */}\n <div\n className={cls(\n \"flex items-center justify-between px-3 py-2 border-b bg-surface-sheet min-h-[48px]\",\n defaultBorderMixin\n )}\n >\n <Typography\n variant=\"caption\"\n className=\"font-semibold uppercase tracking-wider text-text-disabled dark:text-text-disabled-dark\"\n >\n Tables\n </Typography>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark font-mono\"\n >\n {stats.tables}\n </Typography>\n </div>\n\n {/* Search */}\n <div className=\"px-2 py-1.5 border-b border-hairline\">\n <SearchBar\n size=\"smallest\"\n placeholder=\"Filter tables…\"\n onTextSearch={(val) => setSearchQuery(val ?? \"\")}\n innerClassName=\"text-xs\"\n />\n </div>\n\n {/* Table list */}\n <div className=\"flex-grow overflow-y-auto no-scrollbar p-1\">\n {/* Regular collections */}\n <div className=\"space-y-0.5\">\n {filteredCollections.map((collection) => {\n const table = getTableName(collection);\n const nodeId = `table-${table}`;\n const isSelected = selectedTable === nodeId;\n return (\n <div\n key={nodeId}\n onClick={() =>\n handleTableSelect(nodeId)\n }\n className={cls(\n \"flex items-center p-1.5 cursor-pointer rounded transition-colors group\",\n isSelected\n ? \"bg-primary/10 text-primary dark:bg-primary/20 dark:text-primary-light\"\n : \"hover:bg-surface-hover text-text-secondary dark:text-text-secondary-dark\"\n )}\n >\n <div className=\"shrink-0 mr-1.5 text-text-disabled dark:text-text-disabled-dark\">\n <IconForView\n collectionOrView={{\n slug: collection.slug,\n name: collection.name,\n icon:\n typeof collection.icon ===\n \"string\"\n ? collection.icon\n : undefined\n }}\n size=\"smallest\"\n />\n </div>\n <div className=\"flex flex-col min-w-0 flex-1\">\n <Typography\n variant=\"caption\"\n className=\"text-xs truncate font-medium\"\n >\n {collection.name}\n </Typography>\n {table !== collection.name && (\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark font-mono truncate\"\n >\n {table}\n </Typography>\n )}\n </div>\n <div className=\"flex items-center gap-1 shrink-0 ml-1\">\n {/* Same source as the node badge and the\n \"RLS protected\" total: the database when\n it could be asked, the config otherwise.\n Reading `securityRules` directly here made\n the three disagree. */}\n {rlsEnabledFor(collection) && (\n <Tooltip title=\"RLS enabled\">\n <div className=\"w-1.5 h-1.5 rounded-full bg-green-500\"/>\n </Tooltip>\n )}\n {collection.history && (\n <Tooltip title=\"History enabled\">\n <div className=\"w-1.5 h-1.5 rounded-full bg-blue-400\"/>\n </Tooltip>\n )}\n </div>\n </div>\n );\n })}\n </div>\n\n {/* Junction tables */}\n {junctionNodes.length > 0 && (\n <div className=\"mt-3\">\n <Typography\n variant=\"caption\"\n className=\"px-1.5 text-[10px] uppercase tracking-wider text-text-disabled dark:text-text-disabled-dark font-medium\"\n >\n Junction Tables\n </Typography>\n <div className=\"mt-1 space-y-0.5\">\n {junctionNodes.map((node) => {\n const d =\n node.data as TableNodeData;\n const isSelected =\n selectedTable === node.id;\n return (\n <div\n key={node.id}\n onClick={() =>\n handleTableSelect(\n node.id\n )\n }\n className={cls(\n \"flex items-center p-1.5 cursor-pointer rounded transition-colors\",\n isSelected\n ? \"bg-primary/10 text-primary dark:bg-primary/20\"\n : \"hover:bg-surface-hover text-text-disabled dark:text-text-disabled-dark\"\n )}\n >\n <svg\n className=\"w-3.5 h-3.5 mr-1.5 shrink-0\"\n fill=\"none\"\n stroke=\"currentColor\"\n viewBox=\"0 0 24 24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4\"\n />\n </svg>\n <Typography\n variant=\"caption\"\n className=\"text-xs font-mono truncate\"\n >\n {d.tableName}\n </Typography>\n </div>\n );\n })}\n </div>\n </div>\n )}\n </div>\n\n {/* Stats footer */}\n <div\n className={cls(\n \"px-3 py-2 border-t bg-surface-sheet space-y-1\",\n defaultBorderMixin\n )}\n >\n <div className=\"flex items-center justify-between\">\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n Tables\n </Typography>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] font-mono font-medium\"\n >\n {stats.tables}\n </Typography>\n </div>\n <div className=\"flex items-center justify-between\">\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n Relations\n </Typography>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] font-mono font-medium\"\n >\n {stats.relations}\n </Typography>\n </div>\n <div className=\"flex items-center justify-between\">\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n RLS protected\n </Typography>\n <div className=\"flex items-center gap-1\">\n <div className=\"w-1.5 h-1.5 rounded-full bg-green-500\"/>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] font-mono font-medium\"\n >\n {stats.withRls}\n </Typography>\n </div>\n </div>\n </div>\n </div>\n }\n secondPanel={\n <div className=\"flex-grow flex flex-col min-w-0 h-full w-full bg-surface-card\">\n {/* Toolbar */}\n <div\n className={cls(\n \"flex items-center justify-between pr-2 border-b bg-surface-card min-h-[46px]\",\n defaultBorderMixin\n )}\n >\n <div className=\"flex flex-col min-w-0 px-4\">\n <Typography\n variant=\"subtitle2\"\n className=\"font-medium text-text-primary dark:text-text-primary-dark\"\n >\n Schema Visualizer\n </Typography>\n {/* What this diagram is drawn from. Everything on it\n but the RLS markers comes from the collection\n configs, not from the database's catalog. */}\n <Typography\n variant=\"caption\"\n className=\"text-text-secondary dark:text-text-secondary-dark truncate\"\n >\n {t(\"studio_schema_visualizer_source\")}\n </Typography>\n </div>\n <div className=\"flex shrink-0 items-center gap-1.5\">\n {/* Fit view */}\n <Tooltip title=\"Fit to view\">\n <IconButton aria-label=\"Fit to view\"\n size=\"small\"\n onClick={handleFitView}\n >\n <svg\n className=\"w-4 h-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n viewBox=\"0 0 24 24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4\"\n />\n </svg>\n </IconButton>\n </Tooltip>\n\n {/* Re-layout */}\n <Tooltip title=\"Re-layout\">\n <IconButton aria-label=\"Re-layout\"\n size=\"small\"\n onClick={relayout}\n >\n <svg\n className=\"w-4 h-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n viewBox=\"0 0 24 24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15\"\n />\n </svg>\n </IconButton>\n </Tooltip>\n </div>\n </div>\n\n {/* Canvas */}\n <div className=\"flex-grow relative\">\n <ReactFlow\n nodes={nodes}\n edges={edges}\n onNodesChange={onNodesChange}\n onEdgesChange={onEdgesChange}\n onNodeClick={handleNodeClick}\n onPaneClick={handlePaneClick}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n fitView\n fitViewOptions={{ padding: 0.15 }}\n minZoom={0.1}\n maxZoom={2}\n proOptions={{ hideAttribution: true }}\n colorMode={isDark ? \"dark\" : \"light\"}\n className=\"bg-surface-well\"\n >\n <Background\n variant={BackgroundVariant.Dots}\n gap={20}\n size={1}\n className=\"!bg-surface-well\"\n color={isDark ? \"#272a2f\" : \"#d9d9dc\"}\n />\n <Controls\n showInteractive={false}\n // mb clears the legend overlay pinned at bottom-left\n className=\"!mb-16 !bg-surface-card !border !border-hairline !shadow-sm !rounded-lg [--xy-controls-button-background-color:var(--color-surface-card)] [--xy-controls-button-background-color-hover:var(--color-surface-card-hover)] [--xy-controls-button-color:var(--color-text-secondary)] dark:[--xy-controls-button-color:var(--color-text-secondary-dark)] [--xy-controls-button-color-hover:var(--color-text-primary)] dark:[--xy-controls-button-color-hover:var(--color-text-primary-dark)] [--xy-controls-button-border-color:var(--color-hairline)]\"\n />\n <MiniMap\n nodeStrokeColor={(n) => {\n const d = n.data as TableNodeData;\n if (d.isJunction) return \"#a78bfa\";\n if (d.rlsEnabled) return \"#22c55e\";\n return \"#6366f1\";\n }}\n nodeColor={(n) => {\n const d = n.data as TableNodeData;\n // Tinted, not white: the minimap is a card, and its nodes\n // read as tiles on it in either theme.\n if (d.isJunction) return isDark ? \"#3b2f6b\" : \"#ede9fe\";\n return isDark ? \"#2b2d4a\" : \"#eef2ff\";\n }}\n maskColor={isDark ? \"rgba(0,0,0,0.35)\" : \"rgba(0,0,0,0.08)\"}\n className=\"!bg-surface-card !border !border-hairline !shadow-sm !rounded-lg\"\n />\n </ReactFlow>\n\n {/* A large schema: which part is drawn, and how far out */}\n {neighbourhood && (\n <div className=\"absolute top-4 left-4 right-4 flex justify-start pointer-events-none\">\n <div className=\"flex flex-wrap items-center gap-2 max-w-full px-3 py-2 bg-surface-card/90 backdrop-blur-sm rounded-lg border border-hairline shadow-sm pointer-events-auto\">\n <Typography\n variant=\"caption\"\n className=\"text-text-secondary dark:text-text-secondary-dark\"\n >\n {t(\"studio_schema_neighbourhood\", {\n shown: neighbourhood.shown,\n total: neighbourhood.total,\n table: focusName\n })}\n </Typography>\n <ToggleButtonGroup\n value={String(neighbourhood.depth)}\n onValueChange={handleDepthChange}\n options={[\n {\n value: \"1\",\n label: t(\"studio_schema_neighbourhood_depth_1\")\n },\n {\n value: \"2\",\n label: t(\"studio_schema_neighbourhood_depth_2\")\n }\n ]}\n />\n </div>\n </div>\n )}\n\n {/* The layout runs in a worker; say so while it does */}\n {layingOut && (\n <div\n role=\"status\"\n className=\"absolute inset-0 flex items-center justify-center pointer-events-none\"\n >\n <div className=\"flex items-center gap-2 px-3 py-2 bg-surface-card/90 backdrop-blur-sm rounded-lg border border-hairline shadow-sm\">\n <CircularProgress size=\"smallest\"/>\n <Typography\n variant=\"caption\"\n className=\"text-text-secondary dark:text-text-secondary-dark\"\n >\n {t(\"studio_schema_laying_out\")}\n </Typography>\n </div>\n </div>\n )}\n\n {/* Legend overlay */}\n <div className=\"absolute bottom-4 left-4 flex items-center gap-3 px-3 py-2 bg-surface-card/90 backdrop-blur-sm rounded-lg border border-hairline shadow-sm\">\n <div className=\"flex items-center gap-1.5\">\n <div className=\"w-6 h-0.5 bg-indigo-500 rounded\"/>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n Owning\n </Typography>\n </div>\n <div className=\"flex items-center gap-1.5\">\n <div className=\"w-6 h-0.5 bg-violet-500 rounded\"/>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n M:N\n </Typography>\n </div>\n <div className=\"flex items-center gap-1.5\">\n <div\n className=\"w-6 h-0.5 rounded\"\n style={{\n backgroundImage:\n \"repeating-linear-gradient(90deg, #9da2aa, #9da2aa 4px, transparent 4px, transparent 7px)\"\n }}\n />\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n Inverse\n </Typography>\n </div>\n <div className=\"h-3 w-px bg-surface-raised\"/>\n <div className=\"flex items-center gap-1\">\n <span className=\"text-[9px]\">🔑</span>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n PK\n </Typography>\n </div>\n <div className=\"flex items-center gap-1\">\n <span className=\"text-[9px]\">🔗</span>\n <Typography\n variant=\"caption\"\n className=\"text-[10px] text-text-disabled dark:text-text-disabled-dark\"\n >\n FK\n </Typography>\n </div>\n </div>\n </div>\n </div>\n }\n />\n );\n}\n\n// ─── Outer wrapper (provides ReactFlowProvider) ────────────────────────\n\nexport const SchemaVisualizer = () => {\n const { t } = useTranslation();\n const { collections: registryCollections } =\n useStudioCollectionRegistry() as {\n collections?: AdminCollection[];\n };\n\n /**\n * `undefined` and `[]` are different answers, and this view used to render\n * the same spinner for both. A project that declares no collections — a\n * fresh scaffold, a backend-only project someone opened the console\n * against — sat on \"Loading schema…\" forever, because there was nothing\n * coming.\n *\n * `undefined` is the Studio bridge before the admin's collection registry\n * has registered itself: genuinely still loading. `[]` is that registry\n * saying there is nothing to draw.\n */\n if (registryCollections === undefined) {\n return (\n <div className=\"flex items-center justify-center h-full w-full\">\n <div className=\"text-center space-y-3\">\n <CircularProgress size=\"small\"/>\n <Typography\n variant=\"body2\"\n color=\"secondary\"\n >\n Loading schema…\n </Typography>\n </div>\n </div>\n );\n }\n\n if (registryCollections.length === 0) {\n return (\n <div className=\"flex items-center justify-center h-full w-full p-6\">\n <div className=\"max-w-md text-center space-y-2\">\n <Typography variant=\"subtitle2\" className=\"block\">\n {t(\"studio_schema_no_collections\")}\n </Typography>\n <Typography variant=\"body2\" color=\"secondary\" className=\"block\">\n {t(\"studio_schema_no_collections_body\")}\n </Typography>\n <Typography variant=\"body2\" color=\"secondary\" className=\"block\">\n {t(\"studio_schema_introspect_hint\")}\n </Typography>\n </div>\n </div>\n );\n }\n\n const collections = registryCollections;\n\n return (\n <div className=\"flex h-full w-full bg-surface-card overflow-hidden text-text-primary dark:text-text-primary-dark\">\n <ReactFlowProvider>\n <SchemaVisualizerCanvas collections={collections}/>\n </ReactFlowProvider>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,SAAS,OAAqC;CAC1D,MAAM,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;EAAK,WAAU;YACX,qBAAC,OAAD;GAAK,WAAU;aAAf,CACI,oBAAC,kBAAD,EAAkB,MAAK,QAAQ,CAAA,GAC/B,oBAAC,YAAD;IACI,SAAQ;IACR,OAAM;cACT;GAEW,CAAA,CACX;;CACJ,CAAA;CAIb,IAAI,oBAAoB,WAAW,GAC/B,OACI,oBAAC,OAAD;EAAK,WAAU;YACX,qBAAC,OAAD;GAAK,WAAU;aAAf;IACI,oBAAC,YAAD;KAAY,SAAQ;KAAY,WAAU;eACrC,EAAE,8BAA8B;IACzB,CAAA;IACZ,oBAAC,YAAD;KAAY,SAAQ;KAAQ,OAAM;KAAY,WAAU;eACnD,EAAE,mCAAmC;IAC9B,CAAA;IACZ,oBAAC,YAAD;KAAY,SAAQ;KAAQ,OAAM;KAAY,WAAU;eACnD,EAAE,+BAA+B;IAC1B,CAAA;GACX;;CACJ,CAAA;CAMb,OACI,oBAAC,OAAD;EAAK,WAAU;YACX,oBAAC,mBAAD,EAAA,UACI,oBAAC,wBAAD,EAAqC,aAAA,oBAAa,CAAA,EACnC,CAAA;CAClB,CAAA;AAEb"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sql_utils-DXvmxiCq.js","names":[],"sources":["../src/utils/sql_utils.ts"],"sourcesContent":["import { astVisitor, parse, type Statement } from \"pgsql-ast-parser\";\nimport { csvRecord, toSnakeCase } from \"@rebasepro/utils\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport type { SqlScriptResult } from \"@rebasepro/types\";\nimport type { TableInfo } from \"../components/SQLEditor/sql_editor_types\";\n\n/** The statements in `sqlText`, or `null` when the parser cannot read it. */\nfunction parseStatements(sqlText: string): Statement[] | null {\n try {\n return parse(sqlText);\n } catch {\n return null;\n }\n}\n\n/**\n * The `EXPLAIN` for one statement, or `null` when `sqlText` is not exactly one.\n *\n * Never `ANALYZE`: that executes the statement to time it, so explaining a\n * `DELETE` deleted the rows — without the confirmation \"Run\" asks for.\n *\n * And never more than one statement. Sent as one simple query, `EXPLAIN (…)\n * SELECT 1; DELETE …` explains the SELECT and *runs* the DELETE. Text the\n * parser cannot read is still explained, as long as no `;` could be hiding a\n * second statement in it.\n */\nexport function buildExplainSql(sqlText: string): string | null {\n const statement = sqlText.trim().replace(/;+$/, \"\").trim();\n if (!statement) return null;\n const statements = parseStatements(statement);\n const single = statements ? statements.length === 1 : !statement.includes(\";\");\n return single ? `EXPLAIN (FORMAT JSON) ${statement}` : null;\n}\n\n/**\n * Whether the console's automatic `LIMIT` may be appended to `sqlText`: one\n * top-level SELECT that has no limit of its own.\n *\n * Decided on the parsed statement, not the text. A search for the word SELECT\n * also found it inside `INSERT INTO … SELECT` and `CREATE TABLE … AS SELECT`,\n * which then copied a thousand rows and reported success, and at the start of\n * a script whose last statement the appended `LIMIT` turned into a syntax\n * error. Text the parser cannot read is left as written.\n */\nexport function acceptsAutoLimit(sqlText: string): boolean {\n const statements = parseStatements(sqlText);\n if (!statements || statements.length !== 1) return false;\n const [statement] = statements;\n return statement.type === \"select\" && !statement.limit;\n}\n\n/** A destructive command named anywhere in a text, comments included. */\nconst DESTRUCTIVE_COMMAND = /\\b(DELETE|UPDATE|DROP|TRUNCATE)\\b/i;\n\nfunction isDestructiveStatement(statement: Statement): boolean {\n switch (statement.type) {\n case \"delete\":\n case \"update\":\n return !statement.where;\n case \"truncate table\":\n case \"drop table\":\n case \"drop sequence\":\n case \"drop index\":\n case \"drop type\":\n case \"drop trigger\":\n case \"drop function\":\n return true;\n case \"alter table\":\n return statement.changes.some(change => change.type === \"drop column\" || change.type === \"drop constraint\");\n case \"with\":\n return statement.bind.some(binding => isDestructiveStatement(binding.statement)) ||\n isDestructiveStatement(statement.in);\n case \"with recursive\":\n return isDestructiveStatement(statement.in);\n case \"do\":\n return DESTRUCTIVE_COMMAND.test(statement.code);\n default:\n return false;\n }\n}\n\n/**\n * Whether \"Run\" asks before running `sqlText`: a statement in it deletes or\n * updates without a WHERE of its own, drops or truncates.\n *\n * Decided per parsed statement, not on the text. A search of the text for the\n * word WHERE found it in another statement or in a comment, so `DELETE FROM\n * posts; SELECT * FROM posts WHERE id = 1` deleted every post without asking.\n * Text the parser cannot read is confirmed whenever it names a destructive\n * command.\n */\nexport function needsDestructiveConfirmation(sqlText: string): boolean {\n const statements = parseStatements(sqlText);\n if (!statements) return DESTRUCTIVE_COMMAND.test(sqlText);\n return statements.some(isDestructiveStatement);\n}\n\n/**\n * A table as SQL: `\"schema\".\"table\"` when a schema is given, a bare `\"table\"`\n * otherwise.\n */\nexport function quoteTableName(tableName: string, schemaName?: string): string {\n return schemaName ? `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);\n}\n\n/** An identifier as SQL, whatever it holds: double-quoted, with `\"` doubled. */\nexport function quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/**\n * The schema browser's statements for `table`, every name in them quoted. A\n * name is folded to lower case unless it is quoted, so `Posts` reads a table\n * `posts` that is not there and a column `createdAt` one called `createdat`;\n * and a reserved word is not a name at all — `SELECT * FROM user` answers\n * with the current role instead of reading the table. A table in `public` is\n * named without its schema.\n */\nexport function tableStatementTemplates(schemaName: string, table: Pick<TableInfo, \"tableName\" | \"columns\">): {\n selectTop: string;\n selectAll: string;\n insert: string;\n update: string;\n} {\n const from = schemaName === \"public\" ? quoteIdentifier(table.tableName) : quoteTableName(table.tableName, schemaName);\n const columns = table.columns.map(column => quoteIdentifier(column.name));\n return {\n selectTop: `SELECT * FROM ${from} LIMIT 100;`,\n selectAll: `SELECT \\n ${columns.join(\",\\n \")}\\nFROM ${from};`,\n insert: `INSERT INTO ${from} (\\n ${columns.join(\",\\n \")}\\n) VALUES (\\n ${columns.map(() => \"?\").join(\",\\n \")}\\n);`,\n update: `UPDATE ${from} \\nSET \\n ${columns.map(column => `${column} = ?`).join(\",\\n \")}\\nWHERE id = ?;`\n };\n}\n\n/** What the console knows about a result: its columns, and the tables they came from. */\nexport type ResultProvenance = Pick<SqlScriptResult, \"columns\" | \"tables\">;\n\n/**\n * The stored cell a result cell is, and the key that finds its row.\n */\nexport interface CellEditTarget {\n schema: string;\n table: string;\n /** The table column the edited value is written to. */\n column: string;\n /** Each primary key column of the table, and the result column holding its value for the row. */\n key: { column: string; resultColumn: string }[];\n}\n\n/**\n * Why a cell cannot be edited: a translation key of the console's, and its\n * parameters.\n */\nexport interface CellEditRefusal {\n key:\n | \"studio_sql_edit_unreadable_query\"\n | \"studio_sql_edit_not_a_select\"\n | \"studio_sql_edit_duplicate_column\"\n | \"studio_sql_edit_computed_column\"\n | \"studio_sql_edit_not_a_table\"\n | \"studio_sql_edit_inherited_table\"\n | \"studio_sql_edit_no_primary_key\"\n | \"studio_sql_edit_key_missing\"\n | \"studio_sql_edit_table_read_twice\";\n params: Record<string, string>;\n}\n\nexport type CellEditResolution =\n | { target: CellEditTarget; refusal?: undefined }\n | { target?: undefined; refusal: CellEditRefusal };\n\nconst refuse = (key: CellEditRefusal[\"key\"], params: Record<string, string> = {}): CellEditResolution =>\n ({ refusal: { key, params } });\n\n/**\n * Which stored cell an edit of the result column `resultColumn` writes, and\n * how its row is found again — or why no edit is safe.\n *\n * Decided on what the database reported, not on the query's text. Each\n * column of the result says which table column it was read from, or that it\n * was computed; a cell is editable only when it was read from a column of a\n * table, every column of that table's primary key was read too, and each of\n * them is the only column of the result with its name — a row holds one value\n * per name.\n *\n * The text was the only evidence before, and it was wrong twice over. For\n * `SELECT p.id, a.name FROM posts p JOIN authors a …` it took the post's `id`\n * for the author's key and updated whichever author shared the post's id.\n * For `SELECT id, lower(email) AS name FROM users` it wrote the edited text\n * to `users.name`.\n *\n * The database reports a table, not which mention of it: in a self-join both\n * sides are `authors`, and a key from one with a value from the other finds\n * the wrong row. So the query is still read, for one thing — the table must\n * be read once, and nothing it is read through may be read twice.\n */\nexport function resolveCellEdit(sqlText: string, provenance: ResultProvenance, resultColumn: string): CellEditResolution {\n const sameName = provenance.columns.filter(column => column.name === resultColumn);\n if (sameName.length !== 1) return refuse(\"studio_sql_edit_duplicate_column\", { column: resultColumn });\n const source = sameName[0].source;\n if (!source) return refuse(\"studio_sql_edit_computed_column\", { column: resultColumn });\n\n const tableLabel = `${source.schema}.${source.table}`;\n const table = provenance.tables.find(t => t.schema === source.schema && t.table === source.table);\n if (!table || (table.kind !== \"table\" && table.kind !== \"partitioned table\")) {\n return refuse(\"studio_sql_edit_not_a_table\", { column: resultColumn, table: tableLabel });\n }\n if (table.hasInheritors) return refuse(\"studio_sql_edit_inherited_table\", { table: tableLabel });\n if (table.primaryKey.length === 0) return refuse(\"studio_sql_edit_no_primary_key\", { table: tableLabel });\n\n const key: CellEditTarget[\"key\"] = [];\n for (const keyColumn of table.primaryKey) {\n const holders = provenance.columns.filter(column =>\n column.source?.schema === source.schema &&\n column.source.table === source.table &&\n column.source.column === keyColumn);\n const holder = holders.length === 1 && provenance.columns.filter(column => column.name === holders[0].name).length === 1\n ? holders[0]\n : undefined;\n if (!holder) return refuse(\"studio_sql_edit_key_missing\", { table: tableLabel, columns: table.primaryKey.join(\", \") });\n key.push({ column: keyColumn, resultColumn: holder.name });\n }\n\n const readOnce = tableReadOnce(sqlText, source.table);\n if (readOnce !== true) return readOnce;\n\n return { target: { schema: source.schema, table: source.table, column: source.column, key } };\n}\n\n/**\n * Whether `sqlText` is one SELECT that reads `table` once — counting every\n * mention of a table of that name, in any schema and at any depth, and every\n * mention of a `WITH` query, since one read twice reads its tables twice.\n */\nfunction tableReadOnce(sqlText: string, table: string): true | CellEditResolution {\n const statements = parseStatements(sqlText);\n if (!statements) return refuse(\"studio_sql_edit_unreadable_query\");\n if (statements.length !== 1) return refuse(\"studio_sql_edit_not_a_select\");\n const [statement] = statements;\n const isRead = statement.type === \"select\" ||\n (statement.type === \"with\" &&\n statement.in.type === \"select\" &&\n statement.bind.every(binding => binding.statement.type === \"select\"));\n if (!isRead) return refuse(\"studio_sql_edit_not_a_select\");\n\n const mentions = new Map<string, number>();\n const withNames: string[] = [];\n astVisitor(visitor => ({\n fromTable: from => {\n const name = from.name.name.toLowerCase();\n mentions.set(name, (mentions.get(name) ?? 0) + 1);\n visitor.super().fromTable(from);\n },\n with: withStatement => {\n withNames.push(...withStatement.bind.map(binding => binding.alias.name.toLowerCase()));\n visitor.super().with(withStatement);\n }\n })).statement(statement);\n\n const readTwice = (mentions.get(table.toLowerCase()) ?? 0) !== 1 ||\n withNames.some(name => (mentions.get(name) ?? 0) > 1);\n return readTwice ? refuse(\"studio_sql_edit_table_read_twice\", { table }) : true;\n}\n\n/**\n * A collection whose records a query's rows can be opened as.\n */\nexport interface ResolvedQueryCollection {\n /** The table, as the database named it. */\n tableName: string;\n schemaName: string;\n /** The matched collection */\n collection: AdminCollection;\n /** The result column that holds the table's primary key. */\n pkColumn: string;\n}\n\n/**\n * The collections a result's rows can be opened as: those whose table one of\n * the result's columns was read from, with the table's (single-column) primary\n * key read too, under a name no other column of the result has.\n *\n * Matched on the provenance the database reported. A text match took the\n * result's `id` for every table of a join: `SELECT p.id, a.name FROM posts p\n * JOIN authors a …` offered to open the author whose id was the post's.\n */\nexport function resolveQueryCollections(provenance: ResultProvenance, collections: AdminCollection[]): ResolvedQueryCollection[] {\n const results: ResolvedQueryCollection[] = [];\n for (const table of provenance.tables) {\n const collection = collections.find(c => {\n const tableName = (\"table\" in c ? c.table : undefined) || toSnakeCase(c.slug);\n const schemaName = (\"schema\" in c ? c.schema : undefined) || \"public\";\n return tableName === table.table && schemaName === table.schema;\n });\n if (!collection || table.primaryKey.length !== 1) continue;\n const [keyColumn] = table.primaryKey;\n const holders = provenance.columns.filter(column =>\n column.source?.schema === table.schema &&\n column.source.table === table.table &&\n column.source.column === keyColumn);\n if (holders.length !== 1) continue;\n const pkColumn = holders[0].name;\n if (provenance.columns.filter(column => column.name === pkColumn).length !== 1) continue;\n results.push({ tableName: table.table, schemaName: table.schema, collection, pkColumn });\n }\n return results;\n}\n\n/**\n * A stretch of SQL text, by what it is to the database: code, or text that is\n * data and must not be rewritten — a string literal (quoted, `E'…'` or\n * dollar-quoted), a quoted identifier, or a comment.\n */\ninterface SqlSegment {\n text: string;\n kind: \"code\" | \"literal\" | \"identifier\" | \"line comment\" | \"block comment\";\n}\n\n/** A character an unquoted identifier or keyword can hold, `$` included. */\nconst IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\n\n/**\n * Cut `sqlText` into code and the things in it whose text is data.\n *\n * A lexer, not a parser: it reads text the parser refuses as well, which is\n * most of what a person types while writing a query.\n */\nfunction splitSql(sqlText: string): SqlSegment[] {\n const segments: SqlSegment[] = [];\n let code = \"\";\n const push = (text: string, kind: SqlSegment[\"kind\"]) => {\n if (code) segments.push({ text: code, kind: \"code\" });\n code = \"\";\n segments.push({ text, kind });\n };\n let i = 0;\n while (i < sqlText.length) {\n const ch = sqlText[i];\n const next = sqlText[i + 1];\n if (ch === \"-\" && next === \"-\") {\n const newline = sqlText.indexOf(\"\\n\", i);\n const end = newline === -1 ? sqlText.length : newline + 1;\n push(sqlText.slice(i, end), \"line comment\");\n i = end;\n continue;\n }\n if (ch === \"/\" && next === \"*\") {\n // Block comments nest in Postgres.\n let depth = 1;\n let j = i + 2;\n while (j < sqlText.length && depth > 0) {\n if (sqlText[j] === \"/\" && sqlText[j + 1] === \"*\") {\n depth++;\n j += 2;\n } else if (sqlText[j] === \"*\" && sqlText[j + 1] === \"/\") {\n depth--;\n j += 2;\n } else {\n j++;\n }\n }\n push(sqlText.slice(i, j), \"block comment\");\n i = j;\n continue;\n }\n if (ch === \"'\" || ch === \"\\\"\") {\n // `E'…'` takes backslash escapes; every quoted text takes its\n // quote doubled.\n const backslashEscapes = ch === \"'\" && /(^|[^A-Za-z0-9_$])[eE]$/.test(code);\n let j = i + 1;\n while (j < sqlText.length) {\n if (backslashEscapes && sqlText[j] === \"\\\\\") {\n j += 2;\n } else if (sqlText[j] === ch && sqlText[j + 1] === ch) {\n j += 2;\n } else if (sqlText[j] === ch) {\n j++;\n break;\n } else {\n j++;\n }\n }\n push(sqlText.slice(i, j), ch === \"'\" ? \"literal\" : \"identifier\");\n i = j;\n continue;\n }\n if (ch === \"$\" && !IDENTIFIER_CHARACTER.test(code.slice(-1))) {\n // `$tag$…$tag$` — not `$1`, a parameter, whose tag would start\n // with a digit.\n const tag = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sqlText.slice(i));\n if (tag) {\n const close = sqlText.indexOf(tag[0], i + tag[0].length);\n const end = close === -1 ? sqlText.length : close + tag[0].length;\n push(sqlText.slice(i, end), \"literal\");\n i = end;\n continue;\n }\n }\n code += ch;\n i++;\n }\n if (code) segments.push({ text: code, kind: \"code\" });\n return segments;\n}\n\n/**\n * The console's \"Format SQL\": runs of whitespace become one space, a comma is\n * followed by one, and an `=` standing alone gets one on each side — in the\n * code only.\n *\n * A literal, a quoted identifier and a comment are copied as they are: their\n * text is data, and rewriting `'a,b'` to `'a, b'` changes the value the next\n * Run writes. A line comment keeps the line break that ends it, or it would\n * swallow the code after it. `>=`, `<=`, `!=`, `:=` and `=>` are operators of\n * their own and are left whole.\n */\nexport function formatSql(sqlText: string): string {\n const segments = splitSql(sqlText);\n return segments.map((segment, index) => {\n if (segment.kind !== \"code\") return segment.text;\n const tidied = segment.text\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \", \")\n .replace(/(?<![<>!:=~*+\\-/%^&|#@?])\\s*=\\s*(?![=>~*<])/g, \" = \");\n return segments[index - 1]?.kind === \"line comment\" ? tidied.trimStart() : tidied;\n }).join(\"\").trim();\n}\n\n/**\n * `sqlText` with the console's automatic `LIMIT` on it, or `null` when it\n * takes none (see {@link acceptsAutoLimit}).\n *\n * The limit goes straight after the statement's last token — before a\n * trailing comment, which would otherwise swallow it, and in place of a\n * trailing `;`. A query that computes an aggregate is limited like any other:\n * the limit applies to the rows it returns, so a `count(*)` still counts every\n * row, and a window `count(*) OVER ()` is no longer a way past the cap.\n */\nexport function withAutoLimit(sqlText: string, limit: number): string | null {\n if (!acceptsAutoLimit(sqlText)) return null;\n const segments = splitSql(sqlText);\n const isComment = (segment: SqlSegment) => segment.kind === \"line comment\" || segment.kind === \"block comment\";\n const isFiller = (segment: SqlSegment) => isComment(segment) || (segment.kind === \"code\" && /^[\\s;]*$/.test(segment.text));\n let last = segments.length - 1;\n while (last >= 0 && isFiller(segments[last])) last--;\n if (last < 0) return null;\n\n const lastSegment = segments[last];\n const head = lastSegment.kind === \"code\" ? lastSegment.text.replace(/[\\s;]+$/, \"\") : lastSegment.text;\n const after = lastSegment.kind === \"code\" ? lastSegment.text.slice(head.length) : \"\";\n // What follows the statement is comments and the space between them; its\n // `;` are dropped, the limit brings its own.\n const tail = after.replace(/;/g, \"\") + segments.slice(last + 1)\n .map(segment => segment.kind === \"code\" ? segment.text.replace(/;/g, \"\") : segment.text)\n .join(\"\");\n const before = segments.slice(0, last).map(segment => segment.text).join(\"\");\n return `${before}${head} LIMIT ${limit};${tail.trimEnd()}`;\n}\n\n/**\n * Rows as CSV text: a header record of column names, then one record per\n * row, each value under its own column.\n *\n * RFC 4180 with every record ended by CRLF — byte for byte what\n * `POST /api/admin/sql/csv` streams for the same result, so \"Export CSV\" and\n * \"Download full result as CSV\" write one format. They used to differ in\n * the line break (LF here), which a diff, a checksum or a strict reader\n * notices.\n */\nexport function toCsv(columns: readonly string[], rows: readonly Record<string, unknown>[]): string {\n const records = [csvRecord(columns), ...rows.map(row => csvRecord(columns.map(column => row[column])))];\n return records.map(record => record + \"\\r\\n\").join(\"\");\n}\n\n/**\n * The rows on screen as CSV text — {@link toCsv} over the first row's\n * columns.\n *\n * A value was quoted only when it held a comma, and a quote in it was never\n * doubled nor a line break quoted, so `say \"hi\"` or a two-line note broke the\n * row it was in.\n */\nexport function resultsToCsv(rows: Record<string, unknown>[]): string {\n if (rows.length === 0) return \"\";\n return toCsv(Object.keys(rows[0]), rows);\n}\n\n/** Column widths per query, as the console keeps them: SQL text → column → width. */\nexport type ColumnWidthsByQuery = Record<string, Record<string, number>>;\n\n/** How many queries' column widths the console remembers. */\nexport const COLUMN_WIDTHS_REMEMBERED = 50;\n\n/**\n * The widths kept, at most `limit` queries' worth, the most recently resized\n * last.\n *\n * They are kept per query text, in `localStorage`, and used to be kept\n * forever: every query anybody ever resized a column of stayed, whole SQL\n * text and all, in an origin's storage — which the console's tabs, snippets\n * and history share, and which a full store refuses to write at all. The\n * oldest go first; resizing a query's column again makes it the newest.\n */\nexport function rememberColumnWidth(\n widths: ColumnWidthsByQuery,\n sql: string,\n column: string,\n width: number,\n limit: number = COLUMN_WIDTHS_REMEMBERED\n): ColumnWidthsByQuery {\n const { [sql]: current, ...others } = widths;\n return keepLatestColumnWidths({ ...others, [sql]: { ...current, [column]: width } }, limit);\n}\n\n/**\n * The `limit` most recent queries' widths — the last ones in insertion\n * order — and only entries that are a column → width record.\n */\nexport function keepLatestColumnWidths(widths: Record<string, unknown>, limit: number = COLUMN_WIDTHS_REMEMBERED): ColumnWidthsByQuery {\n const kept: ColumnWidthsByQuery = {};\n for (const [sql, value] of Object.entries(widths).slice(-limit)) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) continue;\n const columns: Record<string, number> = {};\n for (const [column, width] of Object.entries(value)) {\n if (typeof width === \"number\" && Number.isFinite(width)) columns[column] = width;\n }\n kept[sql] = columns;\n }\n return kept;\n}\n\n/**\n * The schema browser's tables, by schema, from `information_schema.columns`\n * rows: each table in the order it first appears, its columns in row order.\n *\n * A table is found by its key, not looked up among the schema's tables: that\n * lookup ran once per row over every table so far — 142 ms at 2,000 tables,\n * 923 ms at 5,000, on every open of the console.\n */\nexport function groupSchemaRows(data: Record<string, unknown>[]): Record<string, TableInfo[]> {\n const grouped: Record<string, TableInfo[]> = {};\n const tables = new Map<string, TableInfo>();\n for (const curr of data) {\n const schema = (curr.schema || curr.SCHEMA || curr.table_schema || \"public\") as string;\n const table = (curr.table || curr.TABLE || curr.table_name) as string;\n const column = (curr.column || curr.COLUMN || curr.column_name) as string;\n const dataType = (curr.data_type || curr.DATA_TYPE || \"\") as string;\n const isPrimaryKey = curr.is_pk === true || curr.is_pk === \"true\";\n\n const key = `${schema}\\u0000${table}`;\n let tableInfo = tables.get(key);\n if (!tableInfo) {\n tableInfo = { schemaName: schema, tableName: table, columns: [] };\n tables.set(key, tableInfo);\n (grouped[schema] ??= []).push(tableInfo);\n }\n tableInfo.columns.push({ name: column, dataType, isPrimaryKey });\n }\n return grouped;\n}\n\nconst INTEGER_TYPES = new Set([\"smallint\", \"integer\", \"bigint\"]);\nconst FLOAT_TYPES = new Set([\"real\", \"double precision\"]);\n\n/** How many significant digits a plain decimal (`-0012.3400`) has. */\nfunction significantDigits(decimal: string): number {\n const digits = decimal.replace(/^-/, \"\").replace(\".\", \"\").replace(/^0+/, \"\");\n return digits.replace(/0+$/, \"\").length;\n}\n\n/**\n * One value of the console's result, read by its column's type: an integer a\n * double holds exactly, a float, a numeric of at most 15 significant digits,\n * a boolean (`t`/`f`), json. Anything else — and any value that would change\n * on the way (a bigint past 2^53, a 20-digit numeric, `NaN`) — stays the\n * database's text. A value that is not text (a backend that returned typed\n * rows) or a column with no type is left as it came.\n */\nfunction typedValue(value: unknown, type: string | undefined): unknown {\n if (typeof value !== \"string\" || !type) return value;\n const base = type.replace(/\\(.*\\)$/, \"\").trim();\n if (INTEGER_TYPES.has(base)) {\n const number = Number(value);\n return /^-?\\d+$/.test(value) && Number.isSafeInteger(number) ? number : value;\n }\n if (FLOAT_TYPES.has(base)) {\n const number = Number(value);\n return value.trim() !== \"\" && Number.isFinite(number) ? number : value;\n }\n if (base === \"numeric\") {\n return /^-?\\d+(\\.\\d+)?$/.test(value) && significantDigits(value) <= 15 ? Number(value) : value;\n }\n if (base === \"boolean\") {\n return value === \"t\" ? true : value === \"f\" ? false : value;\n }\n if (base === \"json\" || base === \"jsonb\") {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n return value;\n}\n\n/**\n * The console's rows for a typed JSON export: each value read by the type of\n * the column it is in (see `typedValue`), where \"Export JSON\" writes the\n * database's text as the console holds it. A row holds the last of two\n * columns that share a name, so that column's type is the one read.\n */\nexport function typedJsonRows(\n rows: Record<string, unknown>[],\n columns: readonly { name: string; type?: string }[]\n): Record<string, unknown>[] {\n const typeByName = new Map<string, string | undefined>();\n for (const column of columns) typeByName.set(column.name, column.type);\n return rows.map(row => Object.fromEntries(\n Object.entries(row).map(([key, value]) => [key, typedValue(value, typeByName.get(key))])\n ));\n}\n"],"mappings":";;;;AAOA,SAAS,gBAAgB,SAAqC;CAC1D,IAAI;EACA,OAAO,MAAM,OAAO;CACxB,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,SAAgC;CAC5D,MAAM,YAAY,QAAQ,KAAK,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC,CAAC,KAAK;CACzD,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,aAAa,gBAAgB,SAAS;CAE5C,QADe,aAAa,WAAW,WAAW,IAAI,CAAC,UAAU,SAAS,GAAG,KAC7D,yBAAyB,cAAc;AAC3D;;;;;;;;;;;AAYA,SAAgB,iBAAiB,SAA0B;CACvD,MAAM,aAAa,gBAAgB,OAAO;CAC1C,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG,OAAO;CACnD,MAAM,CAAC,aAAa;CACpB,OAAO,UAAU,SAAS,YAAY,CAAC,UAAU;AACrD;;AAGA,IAAM,sBAAsB;AAE5B,SAAS,uBAAuB,WAA+B;CAC3D,QAAQ,UAAU,MAAlB;EACI,KAAK;EACL,KAAK,UACD,OAAO,CAAC,UAAU;EACtB,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,iBACD,OAAO;EACX,KAAK,eACD,OAAO,UAAU,QAAQ,MAAK,WAAU,OAAO,SAAS,iBAAiB,OAAO,SAAS,iBAAiB;EAC9G,KAAK,QACD,OAAO,UAAU,KAAK,MAAK,YAAW,uBAAuB,QAAQ,SAA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