@rebasepro/studio 0.30.1 → 0.31.0-canary.g902a0ce

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.
Files changed (34) hide show
  1. package/dist/{ApiKeysView-Bqf6XYR1.js → ApiKeysView-9ZvwMPyh.js} +16 -6
  2. package/dist/ApiKeysView-9ZvwMPyh.js.map +1 -0
  3. package/dist/{JSEditor-DCnPXsx6.js → JSEditor-ojAVSkaU.js} +158 -100
  4. package/dist/JSEditor-ojAVSkaU.js.map +1 -0
  5. package/dist/{RLSEditor-zAat58U0.js → RLSEditor-BAwkENpj.js} +394 -206
  6. package/dist/RLSEditor-BAwkENpj.js.map +1 -0
  7. package/dist/{SQLEditor-DV_VEEpL.js → SQLEditor-DX9LfbU7.js} +10 -8
  8. package/dist/SQLEditor-DX9LfbU7.js.map +1 -0
  9. package/dist/{SchemaVisualizer-pCYQ_Ds6.js → SchemaVisualizer-C75TENPm.js} +196 -189
  10. package/dist/SchemaVisualizer-C75TENPm.js.map +1 -0
  11. package/dist/components/JSEditor/JSEditorSidebar.d.ts +3 -6
  12. package/dist/components/JSEditor/JSMonacoEditor.d.ts +10 -10
  13. package/dist/components/JSEditor/table_access.d.ts +39 -0
  14. package/dist/components/RLSEditor/policy-presets.d.ts +1 -1
  15. package/dist/components/RLSEditor/policyListing.d.ts +32 -12
  16. package/dist/components/RLSEditor/policyRules.d.ts +32 -14
  17. package/dist/components/RLSEditor/saveRules.d.ts +48 -18
  18. package/dist/components/RLSEditor/saveSecurityRules.d.ts +5 -4
  19. package/dist/components/SchemaVisualizer/useSchemaGraph.d.ts +13 -8
  20. package/dist/components/schema-source.d.ts +37 -0
  21. package/dist/index.es.js +9 -9
  22. package/dist/index.es.js.map +1 -1
  23. package/dist/schema-source-C4ekB7WU.js +93 -0
  24. package/dist/schema-source-C4ekB7WU.js.map +1 -0
  25. package/dist/{sql_utils-DXvmxiCq.js → sql_utils-CYcgpgam.js} +14 -12
  26. package/dist/sql_utils-CYcgpgam.js.map +1 -0
  27. package/dist/utils/sql_utils.d.ts +14 -10
  28. package/package.json +9 -9
  29. package/dist/ApiKeysView-Bqf6XYR1.js.map +0 -1
  30. package/dist/JSEditor-DCnPXsx6.js.map +0 -1
  31. package/dist/RLSEditor-zAat58U0.js.map +0 -1
  32. package/dist/SQLEditor-DV_VEEpL.js.map +0 -1
  33. package/dist/SchemaVisualizer-pCYQ_Ds6.js.map +0 -1
  34. package/dist/sql_utils-DXvmxiCq.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaVisualizer-C75TENPm.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 { columnTypeLabel } from \"@rebasepro/types\";\nimport type { ColumnDescriptor, ColumnType, RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\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\";\n\n// ─── Column info extracted from a table descriptor ────────────────────\n\nexport interface ColumnInfo {\n /** The SQL column name: what the diagram shows, and what a foreign key's handle is named by. */\n name: string;\n /** The key on a JSON row, in the SDK and in filters. */\n key: string;\n /** The Postgres type's kind (`uuid`, `text`, `enum`…). */\n type: string;\n /** The Postgres type as SQL spells it: `varchar(255)`, `integer[]`, `numeric(10, 2)`. */\n typeLabel: string;\n isPrimaryKey: boolean;\n isForeignKey: boolean;\n /** `NOT NULL`. */\n isRequired: boolean;\n /** A single-column `UNIQUE` constraint. */\n isUnique: boolean;\n /** A Postgres enum, or a closed value set (`.oneOf`). */\n isEnum: boolean;\n enumValues?: string[];\n /** The `belongsTo` relation this column is the foreign key of. */\n relationName?: string;\n}\n\n// ─── Node data shape ──────────────────────────────────────────────────\n\nexport interface TableNodeData {\n tableName: string;\n /** The name the table was defined under. */\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// ─── Columns of a table descriptor ────────────────────────────────────\n\nfunction enumValuesOf(column: ColumnDescriptor): string[] | undefined {\n if (column.type.kind === \"enum\") return [...column.type.values];\n if (column.oneOf) return column.oneOf.map(String);\n return undefined;\n}\n\nconst columnInfo = (column: ColumnDescriptor): ColumnInfo => {\n const enumValues = enumValuesOf(column);\n return {\n name: column.column,\n key: column.key,\n type: column.type.kind,\n typeLabel: columnTypeLabel(column.type),\n isPrimaryKey: column.primaryKey === true,\n isForeignKey: column.foreignKeyOf !== undefined,\n isRequired: !column.nullable,\n isUnique: column.unique === true,\n isEnum: enumValues !== undefined,\n ...(enumValues ? { enumValues } : {}),\n ...(column.foreignKeyOf !== undefined ? { relationName: column.foreignKeyOf } : {})\n };\n};\n\n/**\n * Every column the server serves, in physical order. A `belongsTo` whose key\n * column was withheld from this caller still names its column, so the edge\n * has a handle to leave from.\n */\nconst extractColumns = (table: TableDescriptor): ColumnInfo[] => {\n const columns = table.columns.map(columnInfo);\n for (const relation of table.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n const existing = columns.find((c) => c.name === relation.localKey);\n if (existing) {\n existing.isForeignKey = true;\n existing.relationName = relation.name;\n continue;\n }\n columns.push({\n name: relation.localKey,\n key: relation.localField,\n type: \"foreignKey\",\n typeLabel: \"FK\",\n isPrimaryKey: false,\n isForeignKey: true,\n isRequired: false,\n isUnique: false,\n isEnum: false,\n relationName: relation.name\n });\n }\n return columns;\n};\n\n/** The integer type a column that points at a serial key holds. */\nconst SERIAL_REFERENCE: Partial<Record<ColumnType[\"kind\"], ColumnType>> = {\n smallserial: { kind: \"smallint\" },\n serial: { kind: \"integer\" },\n bigserial: { kind: \"bigint\" }\n};\n\n/** The type label of a junction column: the type of the key it points at (a serial's integer). */\nfunction keyTypeLabel(table: TableDescriptor | undefined): string {\n const key = table?.columns.find((column) => column.primaryKey === true);\n if (!key) return \"FK\";\n return columnTypeLabel(SERIAL_REFERENCE[key.type.kind] ?? key.type);\n}\n\n// ─── Build graph from the tables ──────────────────────────────────────\n\n/**\n * Every table and relation the server declares, not yet placed. Edges carry\n * their column handles without a side; {@link placeGraph} picks the side once\n * it knows where the tables are.\n */\ninterface SchemaGraph {\n nodes: Node[];\n edges: Edge[];\n}\n\nconst buildGraph = (\n tables: readonly TableDescriptor[],\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 * is not the same as having them applied — see `useLiveRlsTables`. Only\n * when there is no SQL capability do we fall back to the declaration:\n * every declared table's posture enables RLS.\n */\n const isRlsEnabled = (schema: string, tableName: string, declared: boolean): boolean =>\n liveRls ? liveRls.has(`${schema}.${tableName}`) : declared;\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 const bySlug = new Map(tables.map((table) => [table.slug, table]));\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 const drawn = tables.filter((table) => table.kind === \"table\");\n\n // 1. A node for each table, named by its SQL table — the live RLS answer\n // is keyed by it.\n for (const table of drawn) {\n const nodeId = `table-${table.table}`;\n tableToNodeId.set(table.slug, nodeId);\n\n const columns = extractColumns(table);\n nodeColumns.set(nodeId, columns);\n\n const nodeData: TableNodeData = {\n tableName: table.table,\n collectionName: table.name,\n slug: table.slug,\n columns,\n isJunction: false,\n isUnmanaged: false,\n rlsEnabled: isRlsEnabled(table.schema, table.table, true),\n historyEnabled: table.history === true\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. Junction table nodes and edges\n const processedJunctions = new Set<string>();\n\n for (const table of drawn) {\n const sourceNodeId = tableToNodeId.get(table.slug);\n if (!sourceNodeId) continue;\n\n for (const rel of table.relations) {\n const targetNodeId = tableToNodeId.get(rel.target);\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.name,\n hasJunction: rel.kind === \"manyToMany\",\n hasJoinPath: false,\n label: getCardinalityLabel(rel.cardinality, direction)\n };\n\n if (rel.kind === \"manyToMany\") {\n if (processedJunctions.has(rel.through.table)) continue;\n processedJunctions.add(rel.through.table);\n drawJunction(table, rel, sourceNodeId, targetNodeId, edgeData);\n } else {\n // A foreign key on this table.\n edges.push({\n id: `edge-${sourceNodeId}-${targetNodeId}-${rel.name}`,\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\n // Many-to-many: a junction node, and two edges.\n function drawJunction(\n table: TableDescriptor,\n rel: Extract<RelationDescriptor, { kind: \"manyToMany\" }>,\n sourceNodeId: string,\n targetNodeId: string,\n edgeData: RelationEdgeData\n ): void {\n const junctionNodeId = `junction-${rel.through.table}`;\n const junctionColumns: ColumnInfo[] = [\n {\n name: rel.through.sourceKey,\n key: rel.through.sourceKey,\n type: \"foreignKey\",\n typeLabel: keyTypeLabel(table),\n isPrimaryKey: true,\n isForeignKey: true,\n isRequired: true,\n isUnique: false,\n isEnum: false\n },\n {\n name: rel.through.targetKey,\n key: rel.through.targetKey,\n type: \"foreignKey\",\n typeLabel: keyTypeLabel(bySlug.get(rel.target)),\n isPrimaryKey: true,\n isForeignKey: true,\n isRequired: true,\n isUnique: false,\n isEnum: false\n },\n ...rel.through.pivot.map(columnInfo)\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 // A junction gets derived policies, and the server switches\n // RLS on for it like any table it declares.\n rlsEnabled: isRlsEnabled(table.schema, rel.through.table, true),\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.sourceKey}`,\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.targetKey}`,\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 }\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 descriptors: readonly TableDescriptor[] | 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 () => (descriptors && descriptors.length > 0 ? buildGraph(descriptors, liveRls) : EMPTY_GRAPH),\n [descriptors, 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 IconForView,\n useTableDescriptors,\n useTranslation\n} from \"@rebasepro/app\";\n\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { useSchemaGraph } from \"./useSchemaGraph\";\nimport { useLiveRlsTables } from \"./useLiveRls\";\nimport type { NeighbourhoodDepth, TableNodeData } from \"./useSchemaGraph\";\nimport { TableNode } from \"./TableNode\";\nimport { RelationEdge } from \"./RelationEdge\";\nimport { schemaSourceProblem, SchemaSourceProblemView } from \"../schema-source\";\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 tables\n}: {\n tables: readonly TableDescriptor[];\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(tables, 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 // The tables, for the sidebar (a view has no node of its own).\n const drawnTables = useMemo(\n () => tables.filter((table) => table.kind === \"table\"),\n [tables]\n );\n\n const filteredTables = useMemo(() => {\n if (!searchQuery.trim()) return drawnTables;\n const q = searchQuery.toLowerCase();\n return drawnTables.filter(\n (table) =>\n table.name.toLowerCase().includes(q) ||\n table.table.toLowerCase().includes(q) ||\n table.slug.toLowerCase().includes(q)\n );\n }, [drawnTables, 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 table, 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 (table: TableDescriptor): boolean => rlsByNodeId.get(`table-${table.table}`) ?? 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 {/* Declared tables */}\n <div className=\"space-y-0.5\">\n {filteredTables.map((descriptor) => {\n const table = descriptor.table;\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: descriptor.slug,\n name: descriptor.name\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 {descriptor.name}\n </Typography>\n {table !== descriptor.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 declaration otherwise.\n Reading the rules directly here made the\n three disagree. */}\n {rlsEnabledFor(descriptor) && (\n <Tooltip title=\"RLS enabled\">\n <div className=\"w-1.5 h-1.5 rounded-full bg-green-500\"/>\n </Tooltip>\n )}\n {descriptor.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 tables the\n server serves, 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 // The tables the server serves — with or without a CMS on the page.\n const descriptors = useTableDescriptors();\n const problem = schemaSourceProblem(descriptors);\n\n if (problem && descriptors.tables.length === 0) {\n return <SchemaSourceProblemView problem={problem}/>;\n }\n\n /**\n * Still loading and nothing to draw are different answers, and this view\n * once rendered the same spinner for both. A project that declares no\n * tables — a fresh scaffold, a backend someone opened the console against\n * — sat on \"Loading schema…\" forever, because there was nothing coming.\n */\n if (descriptors.status === \"loading\") {\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 {t(\"studio_schema_loading\")}\n </Typography>\n </div>\n </div>\n );\n }\n\n if (!descriptors.tables.some((table) => table.kind === \"table\")) {\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_tables_declared\")}\n </Typography>\n <Typography variant=\"body2\" color=\"secondary\" className=\"block\">\n {t(\"studio_schema_no_tables_declared_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 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 tables={descriptors.tables}/>\n </ReactFlowProvider>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,SAA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ACI,oBAAC,kBAAD,EAAkB,MAAK,QAAQ,CAAA,GAC/B,oBAAC,YAAD;IACI,SAAQ;IACR,OAAM;cAEL,EAAE,uBAAuB;GAClB,CAAA,CACX;;CACJ,CAAA;CAIb,IAAI,CAAC,YAAY,OAAO,MAAM,UAAU,MAAM,SAAS,OAAO,GAC1D,OACI,oBAAC,OAAD;EAAK,WAAU;YACX,qBAAC,OAAD;GAAK,WAAU;aAAf;IACI,oBAAC,YAAD;KAAY,SAAQ;KAAY,WAAU;eACrC,EAAE,kCAAkC;IAC7B,CAAA;IACZ,oBAAC,YAAD;KAAY,SAAQ;KAAQ,OAAM;KAAY,WAAU;eACnD,EAAE,uCAAuC;IAClC,CAAA;IACZ,oBAAC,YAAD;KAAY,SAAQ;KAAQ,OAAM;KAAY,WAAU;eACnD,EAAE,+BAA+B;IAC1B,CAAA;GACX;;CACJ,CAAA;CAIb,OACI,oBAAC,OAAD;EAAK,WAAU;YACX,oBAAC,mBAAD,EAAA,UACI,oBAAC,wBAAD,EAAwB,QAAQ,YAAY,OAAQ,CAAA,EACrC,CAAA;CAClB,CAAA;AAEb"}
@@ -1,4 +1,5 @@
1
1
  import React from "react";
2
+ import { type TableInfo } from "./table_access.js";
2
3
  export interface JSSnippet {
3
4
  id: string;
4
5
  name: string;
@@ -6,17 +7,13 @@ export interface JSSnippet {
6
7
  createdAt: number;
7
8
  isFavorite?: boolean;
8
9
  }
9
- interface CollectionInfo {
10
- slug: string;
11
- properties: string[];
12
- }
13
10
  interface JSEditorSidebarProps {
14
- collections: CollectionInfo[];
11
+ tables: TableInfo[];
15
12
  snippets: JSSnippet[];
16
13
  history: string[];
17
14
  onSelectSnippet: (code: string) => void;
18
15
  onDeleteSnippet: (id: string) => void;
19
16
  onInsertCode: (code: string) => void;
20
17
  }
21
- export declare const JSEditorSidebar: ({ collections, snippets, history, onSelectSnippet, onDeleteSnippet, onInsertCode }: JSEditorSidebarProps) => React.JSX.Element;
18
+ export declare const JSEditorSidebar: ({ tables, snippets, history, onSelectSnippet, onDeleteSnippet, onInsertCode }: JSEditorSidebarProps) => React.JSX.Element;
22
19
  export {};
@@ -1,10 +1,12 @@
1
1
  import React from "react";
2
2
  import type { MonacoEditorHandle } from "../SQLEditor/MonacoEditor.js";
3
- export type CollectionInfo = {
4
- slug: string;
5
- name: string;
6
- properties: string[];
7
- };
3
+ import type { TableInfo } from "./table_access.js";
4
+ /**
5
+ * Ambient typings for the served tables: a row type per table from its column
6
+ * keys, and `client.data.<accessor>` for each table one property reaches
7
+ * (the rest are reached with `client.data.table("<slug>")`).
8
+ */
9
+ export declare function tableTypings(tables: readonly TableInfo[]): string;
8
10
  export type JSMonacoEditorProps = {
9
11
  /** The script and its selection, read when Run acts on them. */
10
12
  ref?: React.Ref<MonacoEditorHandle>;
@@ -14,9 +16,7 @@ export type JSMonacoEditorProps = {
14
16
  className?: string;
15
17
  readOnly?: boolean;
16
18
  autoFocus?: boolean;
17
- /** Collection slugs for basic autocomplete */
18
- collectionSlugs?: string[];
19
- /** Full collection info with property names for richer type generation */
20
- collections?: CollectionInfo[];
19
+ /** The tables the server serves: typed accessors on `client.data`. */
20
+ tables?: readonly TableInfo[];
21
21
  };
22
- export declare const JSMonacoEditor: ({ ref, value, onChange, onRun, className, readOnly, autoFocus, collectionSlugs, collections }: JSMonacoEditorProps) => React.JSX.Element;
22
+ export declare const JSMonacoEditor: ({ ref, value, onChange, onRun, className, readOnly, autoFocus, tables }: JSMonacoEditorProps) => React.JSX.Element;
@@ -0,0 +1,39 @@
1
+ import type { TableDescriptor } from "@rebasepro/types";
2
+ /**
3
+ * A table as the JS editor offers it: in the sidebar, in the script's
4
+ * `context.tables`, and as Monaco typings.
5
+ */
6
+ export interface TableInfo {
7
+ slug: string;
8
+ /** The name the table was defined under. */
9
+ name: string;
10
+ /**
11
+ * The property that reaches it on the editor's `client.data`, when there
12
+ * is one — see {@link dotAccessorOf}. Without one, `data.table("<slug>")`.
13
+ */
14
+ accessor?: string;
15
+ /** The column keys the server serves, in physical order. */
16
+ columns: string[];
17
+ /** The keys of the primary-key columns. */
18
+ primaryKey: string[];
19
+ }
20
+ /**
21
+ * The property that reaches `slug` on the editor's `client.data`, or
22
+ * `undefined` when no property does.
23
+ *
24
+ * The editor's clients carry no generated table dictionary, so a property is
25
+ * read the untyped way: its snake_case is the slug (`companyMembers` →
26
+ * `company_members`). A slug that is its own snake_case identifier (`posts`,
27
+ * `order_items`) is reached as itself; any other slug (`blog-posts`,
28
+ * `blogPosts`) by no property at all.
29
+ */
30
+ export declare function dotAccessorOf(slug: string): string | undefined;
31
+ /** How a script reaches `table`: `client.data.posts`, or `client.data.table("blog-posts")`. */
32
+ export declare function tableAccessExpression(table: Pick<TableInfo, "slug" | "accessor">): string;
33
+ /** The {@link TableInfo} of every table the server serves (views included: they are read the same way). */
34
+ export declare function tableInfosOf(tables: readonly TableDescriptor[]): TableInfo[];
35
+ /**
36
+ * The slug a `client.data.<property>` names, as the client resolves it: a
37
+ * table's own accessor, or else the property's snake_case.
38
+ */
39
+ export declare function slugOfProperty(property: string, tables: readonly TableInfo[]): string;
@@ -45,7 +45,7 @@ export declare function roleOptionsFor(fetched: readonly string[] | undefined, p
45
45
  * Preset conditions, compiled by the framework's own policy compiler rather
46
46
  * than written out here.
47
47
  *
48
- * `policyToPostgres` is the function `db push` generates policies with, so a
48
+ * `compilePolicyExpression` is the function `db push` generates policies with, so a
49
49
  * preset cannot drift from what the framework emits — and the one that matters
50
50
  * has drifted before: `authenticated()` used to compile to a bare
51
51
  * `IS NOT NULL`, which is true for anonymous visitors, and any copy of that
@@ -1,10 +1,10 @@
1
- import type { CollectionConfig, PostgresPolicy } from "@rebasepro/types";
1
+ import type { PolicyDescriptor, PostgresPolicy, RlsDescriptor, SecurityRule } from "@rebasepro/types";
2
2
  /** A part of a policy the database can hold differently from its declaration. */
3
3
  export type PolicyDriftField = "roles" | "command" | "mode" | "USING" | "WITH CHECK";
4
4
  /** A row of the RLS editor's policy list. */
5
5
  export interface ListedPolicy extends PostgresPolicy {
6
6
  /**
7
- * What the project's code compiles this policy to, when it declares one by
7
+ * What the server compiles this policy to, when the table declares one by
8
8
  * this name. For a policy the database also has, the row's own fields are
9
9
  * the database's and this is what they are compared against.
10
10
  */
@@ -13,10 +13,13 @@ export interface ListedPolicy extends PostgresPolicy {
13
13
  drift?: PolicyDriftField[];
14
14
  /**
15
15
  * Rebase adds this policy itself — the admin baseline, a tenancy or
16
- * auth-write gate, a junction's derived policies — so no rule of the
17
- * author's holds it, and the next server start re-creates it.
16
+ * auth-write gate, a junction's derived policies, an admin-request
17
+ * companion — so no rule of the author's holds it, and the next server
18
+ * start re-creates it.
18
19
  */
19
20
  generated?: boolean;
21
+ /** The index in the table's declared `rls.rules` of the rule this policy compiles from. */
22
+ rule?: number;
20
23
  }
21
24
  /**
22
25
  * The roles of a `pg_policies` row, from its `roles` column.
@@ -29,6 +32,8 @@ export interface ListedPolicy extends PostgresPolicy {
29
32
  * is not there, and an edit of it names a role that does not exist.
30
33
  */
31
34
  export declare function readPolicyRoles(value: unknown): string[];
35
+ /** A policy the server compiled, in the shape `pg_policies` describes one. */
36
+ export declare function servedAsPostgresPolicy(served: PolicyDescriptor, tableName: string): PostgresPolicy;
32
37
  /**
33
38
  * Where a live policy differs from the one the code compiles to.
34
39
  *
@@ -40,16 +45,31 @@ export declare function readPolicyRoles(value: unknown): string[];
40
45
  * changes who the policy admits.
41
46
  */
42
47
  export declare function policyDrift(declared: PostgresPolicy, live: PostgresPolicy): PolicyDriftField[];
48
+ /**
49
+ * What the server says a table's policies are: its declared rules and the
50
+ * policies it compiled from them, or — for a junction — the derived policies
51
+ * alone. `undefined` when the table is not one the server declares, or when it
52
+ * withheld the compiled policies from this caller (no `schema:read`).
53
+ */
54
+ export interface DeclaredPolicies {
55
+ /** The declared rules, as written; empty for a junction. */
56
+ rules: readonly SecurityRule[];
57
+ /** Every policy the server compiles for the table. */
58
+ policies: readonly PolicyDescriptor[];
59
+ }
60
+ /** The {@link DeclaredPolicies} of a served table, when the server included its compiled policies. */
61
+ export declare function declaredPoliciesOf(rls: RlsDescriptor): DeclaredPolicies | undefined;
43
62
  /**
44
63
  * The policies of one table: every policy the database has, as the database
45
- * has it, and every policy the code declares for the table that it does not.
64
+ * has it, and every policy the server compiles for the table that it does not.
46
65
  *
47
- * A policy in both keeps the database's fields — this list is what Postgres
48
- * enforces — and carries the declaration beside them, with where the two
49
- * differ.
66
+ * The server is the one compiler: what it serves in `rls.policies` (and
67
+ * `rls.junctions`) is exactly what `db push` and every server start write.
68
+ * This only compares it with `pg_policies`. A policy in both keeps the
69
+ * database's fields — this list is what Postgres enforces — and carries the
70
+ * declaration beside them, with where the two differ.
50
71
  *
51
- * @param live The table's `pg_policies` rows.
52
- * @param collection The collection the table belongs to, if any.
53
- * @param collections Every collection, to resolve the ones a rule refers to.
72
+ * @param live The table's `pg_policies` rows.
73
+ * @param declared What the server serves for the table, if anything.
54
74
  */
55
- export declare function listPolicies(live: readonly PostgresPolicy[], collection: CollectionConfig | null, tableName: string, collections: readonly CollectionConfig[]): ListedPolicy[];
75
+ export declare function listPolicies(live: readonly PostgresPolicy[], declared: DeclaredPolicies | undefined, tableName: string): ListedPolicy[];
@@ -1,4 +1,5 @@
1
- import type { PolicyExpression, PostgresPolicy, SecurityRule, SecurityRuleBase } from "@rebasepro/types";
1
+ import type { PolicyCondition, PostgresPolicy, SecurityRule, SecurityRuleAccess, SecurityRuleBase } from "@rebasepro/types";
2
+ import type { ListedPolicy } from "./policyListing.js";
2
3
  /**
3
4
  * The security-rule fields a {@link PostgresPolicy} describes, and the ones an
4
5
  * edit carries over from the rule it changes.
@@ -11,10 +12,26 @@ export type PolicyRule = SecurityRuleBase & {
11
12
  using?: string;
12
13
  withCheck?: string;
13
14
  ownerField?: string;
14
- access?: "public";
15
- condition?: PolicyExpression;
16
- check?: PolicyExpression;
15
+ access?: SecurityRuleAccess;
16
+ condition?: PolicyCondition;
17
+ check?: PolicyCondition;
18
+ /** Carried through untouched; a redacted rule is never edited ({@link ruleForm}). */
19
+ redacted?: true;
17
20
  };
21
+ /**
22
+ * Which form a declared rule is written in — what the editor can do with it.
23
+ *
24
+ * Every rule form but one is editable as SQL: the editor shows the policy the
25
+ * rule compiles to, and a field is only rewritten when the form changed it
26
+ * ({@link applyPolicyEdit}), so an untouched rule — a `PolicyShorthand`
27
+ * condition, `access` with a condition — is saved exactly as written, and
28
+ * its policy keeps its name. The exception is `redacted`: the server withheld
29
+ * the rule's clauses from this caller, so there is nothing to show or edit;
30
+ * it is defined on the server.
31
+ */
32
+ export type PolicyRuleForm = "owner" | "access" | "conditional_access" | "structured" | "raw" | "roles_only" | "redacted";
33
+ /** The {@link PolicyRuleForm} of a declared rule. */
34
+ export declare function ruleForm(rule: SecurityRule): PolicyRuleForm;
18
35
  /** Why an edited policy could not be written back to a rule. */
19
36
  export type PolicyEditRefusal =
20
37
  /** Rebase adds it (the admin baseline, tenancy); no declared rule holds it. */
@@ -22,7 +39,9 @@ export type PolicyEditRefusal =
22
39
  /** It exists only in the database. */
23
40
  | "not_declared"
24
41
  /** Its rule covers several operations, and the policy is one of them. */
25
- | "several_operations";
42
+ | "several_operations"
43
+ /** Its rule was served redacted: the clauses are defined on the server. */
44
+ | "redacted";
26
45
  export type PolicyEdit = {
27
46
  ok: true;
28
47
  rules: PolicyRule[];
@@ -33,17 +52,16 @@ export type PolicyEdit = {
33
52
  /**
34
53
  * Write an edit of one policy back to the declared rule it compiles from.
35
54
  *
36
- * The rule is found by the policy names it compiles to, not by `rule.name`:
37
- * an unnamed rule's policy is `<table>_<op>_<hash>`, and a rule over several
38
- * operations names each `<name>_<op>`. Matching on `name` missed both, saved
39
- * the rules unchanged and reported success.
55
+ * The rule is the one the server says the policy was compiled from (the
56
+ * served policy's `rule` index, carried on the listed row) — the server is the
57
+ * one compiler, so the editor never guesses it from names. A policy with no
58
+ * rule is Rebase's own (`generated`: the admin baseline, tenancy, a junction's
59
+ * derived policies) or exists only in the database.
40
60
  *
41
61
  * A rule over several operations is refused rather than split: taking one
42
62
  * operation out renames every policy the rule compiles to.
43
63
  *
44
- * @param declared The collection's `securityRules`, as written.
45
- * @param effective Every rule the generator compiles for the table — the
46
- * declared ones plus what Rebase adds — to tell a generated
47
- * policy from one that exists only in the database.
64
+ * @param declared The table's declared rules (`rls.rules`), as written.
65
+ * @param original The listed policy the editor was opened with.
48
66
  */
49
- export declare function applyPolicyEdit(declared: readonly SecurityRule[], effective: readonly SecurityRule[], tableName: string, original: PostgresPolicy, edited: Partial<PostgresPolicy>): PolicyEdit;
67
+ export declare function applyPolicyEdit(declared: readonly SecurityRule[], original: ListedPolicy, edited: Partial<PostgresPolicy>): PolicyEdit;