feat(docs): database documentation viewer and DBML export

* feat(docs): add SchemaSnapshot model

* feat(docs): infer relationship cardinality from foreign keys

* fix(docs): resolve foreign keys within the source schema

* feat(docs): convert group hue to sRGB hex for DBML

* feat(docs): add DBML lexical primitives

* feat(docs): render DBML table blocks

* feat(docs): render DBML refs, enums and table groups

* feat(docs): assemble complete DBML documents

* feat(docs): collect schema snapshots with bounded fan-out

* fix(docs): gate FK warning on engine capability and reference synthesized enums

* fix(docs): qualify synthesized enum references in multi-schema output

* test(docs): anchor the multi-schema enum reference assertion

* feat(docs): add snapshot collection route

* feat(docs): add collect_docs_snapshot to DbxBackend

* feat(docs): add dbx dbml command

* test(docs): add live snapshot and DBML verification

Runs collect_snapshot + to_dbml against a real PostgreSQL database
(organon, 47 tables) and asserts structural DBML validity: Project
header, every table present, balanced braces, trailing newline.

* refactor(docs): use sort_by_key for snapshot table ordering

* docs(docs): add database documentation design and implementation plan

Records the Part 1 design (SchemaSnapshot + DBML export) and the plan that
produced it. The plan carries an appendix listing the thirteen assumptions
that proved wrong during execution, so the corrected facts are not re-derived
from the surrounding prose.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* fix(docs): use native enum names, canonical engine labels, and surface metadata failures

Final review fix wave covering four findings:

- PostgreSQL named enums (e.g. `ConversationStatus`) now keep their own
  type name and synthesized: false, instead of being renamed to
  `{table}_{column}` and losing identity. A type shared by several
  columns now dedupes to a single Enum block instead of colliding or
  duplicating. `synthesize_enum` and `render_type` route through one
  shared `enum_type_name` helper so the two can't drift apart again.
- `database_type` (and the CommentsUnsupported/NoForeignKeyMetadata
  warnings) now use the same canonical engine label already used
  throughout table_structure_sql's own warning prose, instead of a raw
  Rust Debug string (`Postgres`, `SqlServer`, `MongoDb`).
- An index-fetch failure during collection now surfaces as a
  TableSkipped warning instead of silently degrading to an empty index
  list, which relations.rs uses to infer relationship cardinality.
- A schema-enumeration failure now surfaces as a warning instead of
  silently proceeding against schema "".
- Removed the redundant Arc<Semaphore>; buffer_unordered already caps
  concurrency at MAX_CONCURRENT_TABLES.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* feat(docs): add annotation file model

* test(docs): assert full round-trip fidelity for the annotation model

* feat(docs): add per-engine annotation key folding

* fix(docs): do not fold identifiers on case-sensitive engines

* feat(docs): load and validate the notes file

* fix(docs): report a version mismatch before unknown-field errors

* feat(docs): merge annotations into the schema snapshot

* feat(docs): detect orphaned annotations without deleting them

* feat(docs): add --notes to dbx dbml

* feat(docs): remember a notes file path per connection

Adds docs_notes_path to ConnectionConfig so the desktop app (Part 3)
can persist where a connection's documentation notes file lives. The
CLI is unaffected — it takes an explicit --notes path.

ConnectionConfig has a hand-written Deserialize impl that delegates to
a mirror struct, ConnectionConfigData, and converts via From. Adding
the field only to ConnectionConfig would compile but never populate
from stored JSON, since ConnectionConfigData's fields are what serde
actually reads. The field is threaded through all three places:
ConnectionConfig, ConnectionConfigData, and the From impl, mirroring
the existing `color` field.

* test(docs): verify annotations against a live database

* test(docs): assert exactly one orphaned annotation

* feat(docs): add snapshot types for the docs viewer

* fix(docs): correct snapshot type nullability and add missing column fields

* feat(docs): add a real-output fixture and drift conformance test

The fixture is generated by dump_docs_fixture.rs from a live collect_snapshot
run against the keycloak database in the shared local-infra stack, with
annotations applied so a LOCAL note, column note, group and orphanedNotes
warning are all present. fixtureConformance.spec.ts asserts against that real
JSON rather than a hand-written literal, so a change to the Rust snapshot
shape breaks the test instead of silently drifting from the hand-maintained
types.ts.

Keycloak is used because its schema is public open-source knowledge, so the
committed fixture carries no private schema. The kept tables are an explicit
allowlist rather than an alphabetical slice, because the conformance test
needs a connected foreign-key subgraph: protocol_mapper has two foreign keys
to different tables and composite_role has two to the same one.

* feat(docs): add index grouping for the docs viewer

* feat(docs): describe snapshot warnings for the viewer

* feat(docs): add client-side search for the docs viewer

* test(docs): make the search fixture able to fail

* feat(docs): expose group hue as a CSS custom property

* docs(plan): add annotations and viewer plans, correct Task 7

Parts 2 and 3a were planned after the first plan was committed and were never
tracked. docs/superpowers/ is gitignored, so both needed -f, matching how the
existing specs and plans in that directory were added.

The viewer plan's Task 7 is corrected against the installed marked@18.0.4. Its
original text carried four defects, found by probing the library rather than by
review: an assertion that fails against a correct implementation, a pre-escaping
approach that double-escapes entities, a javascript: blocklist with live
bypasses (entity-encoded, vbscript:, data:text/html, and <img src>, which was
never covered at all), and a link renderer whose text property is raw markdown
source rather than parsed HTML — an XSS hole found while verifying the fix for
the previous defect.

The viewer plan also gains a corrections appendix grouping defects by failure
mode. The annotations plan is committed as written; its defects are recorded in
a follow-up.

* feat(docs): render note markdown with raw HTML escaped

* fix(docs): drop protocol-relative URLs in note markdown

The URL allowlist permitted anything starting with / so relative paths work,
and //evil.com qualifies. Over https that grants nothing a note author could
not do with an ordinary https link, but the Part 3b standalone export is
opened via file://, where //host/path is a UNC path. On Windows that opens an
SMB connection and leaks an NTLM hash, with no click required since images
auto-load, and it is plantable from a COMMENT ON value.

Found by an adversarial probe of the committed module rather than by review;
the backslash form was already dropped, only the slash form slipped through.

* docs(plan): add corrections appendix to the annotations plan

Groups the defects found executing Part 2 by failure mode, matching the form
of the viewer plan's appendix. The notable one is Mode A: docs_notes_path had
to be added in three places because ConnectionConfig has a serde mirror
struct, and adding it in one place compiles, passes a round-trip test written
against the same struct, and then reads None forever after every load.

Also records a controller hypothesis that turned out to be wrong, since
checking it cost one read.

* fix(docs): reject backslash protocol-relative URLs in notes

The // guard from the previous commit was itself a blocklist: /\evil.com
starts with a single slash, so it passed, and the WHATWG URL spec treats /\ identically to // for special schemes. Browsers normalise the backslash, so
it reaches the same file:// UNC path and the same no-click NTLM leak.

Rejecting both separator characters in both positions closes it. Found by
probing what String(raw).trim() leaves unnormalised before the prefix checks;
the third defect on this file found by probing rather than by reading.

* feat(docs): add docs viewer components

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* test(docs): pin each theme's legacy colour base independently

The ordering check indexOf(hsl) < indexOf(@supports) quantified over any
occurrence, so deleting the light .docs-group block left the dark block's hsl
satisfying it. The test passed while every table group rendered colourless on
light-theme WebViews without oklch.

Asserting each selector's own base block catches deleting either one. Found by
the task implementer, which deleted one block and then both to show the guard
pinned 'some base exists' rather than 'each selector has a base'.

* fix(docs): escape single quotes in note attribute values

escapeHtml covered & < > and double quotes but not single quotes. Not
exploitable today because every attribute in this file is double-quoted, but
that is a formatting convention enforced nowhere and living in a different
part of the file from the escaper. A future edit writing title='...' would
turn a formatting choice into an attribute breakout.

Raised by review as latent fragility rather than a defect; fixed because the
escaper should be correct on its own rather than correct-given-an-invariant.

* test(docs): match single-quoted v-html bindings in the contract guard

The guard matched /v-html\s*=\s*"([^"]*)"/ — double quotes only. A binding
written `v-html='table.note'` produced zero matches and passed, handing a
database COMMENT ON value straight to the DOM with the renderNote sanitiser
bypassed. Both quote styles are valid Vue and nothing in the repo enforces
one, so the guard had a hole exactly where it mattered most.

Verified by temporarily rewriting a real WikiIndex binding as
`v-html='table.note'`: the test now fails with "WikiIndex.vue: v-html must
render renderNote output: expected 'table.note' to contain 'renderNote'".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* fix(docs): cap search results per kind instead of overall

DocsSearch sliced searchDocs output to 40 AFTER concatenation, and the
concatenation order is tables -> columns -> groups -> enums. Columns always
flooded the list, so the cap deleted the tail — every group and enum hit.
Against the real fixture, "e" produced 155 hits (9 table, 133 column, 1 group,
12 enum) and rendered 9 tables, 31 columns and nothing else; groups and enums
were structurally unreachable through search.

Cap each kind against its own limit inside docsSearch.ts, where the logic is
tested, and drop the slice from the template so exactly one place limits
results. Ranking is unchanged: tables still precede columns.

Verified by reverting to a single .slice(0, 40) over the concatenation: the
new tests fail with "enums must survive a column flood: expected false to be
true" and "expected 30 to be 20".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* fix(docs): move the index card note out of its button

The card rendered renderNote output with v-html inside the <button>. A note
containing a markdown link — [spec](https://example.com) — put an <a> inside a
<button>: invalid nesting, and the anchor was not keyboard reachable because
the button swallows it in the tab order.

The <li> now carries the card's border, background and hover, the button holds
only the table name and kind, and the note is its sibling. Visually identical —
same padding, same 0.5 gap, previously mt-0.5 — and the name row still spans
the full width as the click target.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* test(docs): pin every fixture struct's key set in both directions

The guard pinned ColumnInfo and IndexInfo plus three DocTable keys, and only
in the "no missing key" direction. Relationship, FieldRef, DocEnum,
ProjectMeta, ColumnNote, ForeignKeyInfo, TableGroup and 10 of 13 DocTable keys
were unchecked. Renaming Relationship::to to `target` in Rust kept the suite at
67/67 and vue-tsc at exit 0 while RelationshipList read `field.table` on
undefined and every table page rendered blank.

Every struct in the fixture is now pinned both ways — no missing key, no
unexpected key — over every instance rather than element [0]. Each direction
catches a different half of a rename. Object.hasOwn throughout, so a key that
is present and null stays distinguishable from one skip_serializing_if omitted.

ForeignKeyInfo, TableGroup and the SchemaSnapshot root are included beyond the
list the review gave: they are equally present in the fixture and equally
unpinned.

Verified against a modified copy of the fixture outside the repo with
Relationship::to renamed: "Relationship[0] must always carry to: expected
false to be true".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKcC15gEuQBHMidPCFFYwn

* fix(cli): error when an explicit --notes path does not exist

load_annotations returns Ok(None) for a missing file, which is right for the
implicit per-connection notes path — it may legitimately not exist yet. It is
wrong for --notes, where the user named a specific file: a mistyped path
produced DBML with every note silently absent and no diagnostic at all,
indistinguishable from a database that has no documentation.

Both final reviewers independently ruled this must-fix-before-merge.

* fix(docs): treat an explicit FK ref_schema as authoritative

find_target tried the explicit ref_schema, then fell through to the source
table's own schema on failure. When the referenced schema was not collected —
routine, since users select schemas — an FK from sales.orders to
archive.customers resolved to sales.customers instead: a different table, and
a diagram that is confidently wrong rather than visibly incomplete.

The function's own doc comment already promised that keys pointing outside the
collected set are dropped. Now it does that.

This is a regression of the defect found in Part 1: the three-tier lookup was
added then, but tier one was written to fall through rather than to decide.

* fix(docs): corroborate engine capability warnings against what was collected

supports_comments and supports_foreign_keys delegate to the structure
editor's DDL-generation capabilities, not to introspection support. IRIS is
the proven divergence: it reports %DESCRIPTION on introspection but DBX
cannot ALTER an existing one, so the flag is false while the collector reads
and includes those comments — producing a snapshot that warned comments were
unsupported alongside the comments themselves.

Each warning now fires only when the flag says the engine cannot AND
collection found nothing of the kind to contradict it. ClickHouse and Doris,
which genuinely report no foreign keys, still warn. The doc comments now say
what the functions actually measure.

Found by final review, which traced every other caller to establish the
flag's real semantics.

* docs(fixture): finish repointing the fixture source to keycloak

Follows the rebase that replaced the fixture at its origin commit. Repoints
the live annotation test's project identity and both plans, and records the
one capability keycloak costs us.

Keycloak declares no PostgreSQL enum types, so the fixture cannot exercise
DocEnum — a Rust-side rename of a DocEnum field would pass every test here
and break the viewer's enum rendering silently. Rather than delete the test,
it now asserts the gap, so it fails the day the fixture source gains an enum
and prompts restoring the pin.

* docs(spec): design for in-app database documentation (Part 3b)

Mounts the Part 3a viewer in DBX and makes it editable: table/column notes,
table groups, and per-group colour, autosaved to a notes file that can live
in the user's repository.

Two findings shaped the scope. DBX already ships SchemaDiagramDialog, so the
viewer links to it rather than building a second ER diagram — only the Part 3c
export needs its own minimal renderer, because that dialog reaches into stores
and cannot be inlined. And nothing currently reads docs_notes_path or writes
annotations at all, so 'in-app editing' needs new Rust rather than frontend
wiring alone.

The standalone export, dbx docs verb and hash routing are deferred to 3c.

* docs(plan): implementation plan for in-app database documentation

Ten tasks: atomic annotation save and path resolution, Tauri commands, web
route parity, the frontend facade, pure edit transforms, the i18n namespace
with a parity guard, editing components, the enum page, edit plumbing through
the viewer, and the dialog with debounced autosave.

Self-review caught three defects before dispatch, all the same class that cost
Part 3a ten fix rounds: a return type named DescribedWarning that does not
exist (it is WarningNotice), a test calling emptySnapshot() which does not
exist, and a table() helper invoked with columns when its real signature takes
a groupId. Every identifier the plan names is a claim about the codebase.

* docs(plan): resolve the data directory without a dbx-mcp dependency

Tasks 2 and 3 called dbx_mcp::paths::app_data_dir(), but neither src-tauri nor
dbx-web depends on dbx-mcp, so neither would have compiled. Both already have
a better source: AppState.storage.data_dir() honours a custom data dir, and
WebState already carries data_dir.

Found by the pre-flight scan before any implementer saw it.

* docs(plan): fix Task 1 against the real crate (no Default, no tempfile)

ConnectionConfig has no Default derive and ~60 fields, so resolve_notes_path
now takes the connection id and the optional override directly — the two
fields it actually reads. The test pain was pointing at the signature.

dbx-core has no dev-dependencies, so the tests use the temp_dir + uuid idiom
already present in annotations.rs rather than tempfile.

* feat(docs): add atomic annotation save and notes path resolution

* docs(plan): guard the autosave against concurrent writes

flush() cleared the debounce timer but not an in-flight write, so closing the
dialog while a debounced save was awaiting the backend started a second one.
Two concurrent saves of the same file waste a round trip, race to land stale,
and are the exact concurrency that corrupts the notes file when the temp path
is not unique per writer.

Found while adjudicating the Task 1 review, which demonstrated the Rust half
of the same problem.

* fix(docs): make temp paths unique to prevent concurrent save corruption

* fix(docs): replace vacuous atomicity test with inode-based verification

* docs(plan): correct the apply_annotations import path

dbx_core::docs re-exports collector, color, dbml, keys, relations and snapshot
but NOT annotations, so apply_annotations and friends are only reachable at
dbx_core::docs::annotations. Tasks 2 and 3 both used the shorter path and
would not have compiled.

Verified against crates/dbx-core/src/docs/mod.rs before either was dispatched.

* fix(docs): truncate temp filename to stay within 255-byte filesystem limit

* feat(docs): add Tauri commands for docs snapshot and annotations

* docs(plan): propagate the resolve_notes_path signature to its callers

Pre-flight changed resolve_notes_path to take (connection_id, docs_notes_path,
data_dir) instead of a ConnectionConfig, but only Task 1 was updated. Tasks 2
and 3 still called it with the old signature and would not have compiled.

The Task 2 implementer caught it and used the correct form from its dispatch
note. Task 3 had the identical stale call and had not been dispatched yet.

The plan's self-review checks signature consistency across tasks; this changed
AFTER that review, during pre-flight, and nothing re-ran the check.

* docs(plan): pin Task 4's http.ts idiom and the Tauri argument names

http.ts uses a post<T>(url, body) helper at line 222; the plan said only
'match the existing idiom', which is delegating verification to someone with
less context. Written out concretely now.

Also records what Task 2's review flagged as unverifiable from its own diff:
Tauri serialises command arguments by name, so the invoke object keys must
match the Rust parameter names. That mismatch compiles cleanly on both sides
and fails only when a user clicks — and it falls in the gap between two
task-scoped reviews, since neither diff contains both halves.

* feat(docs): add web routes for annotation load, apply and save

Mirrors the Tauri commands (docs_load_annotations, docs_apply_annotations,
docs_save_annotations) added in the previous task: collect returns the raw
snapshot, apply is separate so the shadowedNote rule stays in one place.

* docs(plan): make the i18n parity guard actually observable

Every non-English locale is export default withEnglishFallback({...}) — the
fallback is applied at module level, inside the locale file. Only en.ts is a
bare object. So importing a locale's default export yields the ALREADY-MERGED
object, and the parity test would have found every key present in every locale
and passed while translations were missing.

The test written to catch silent English fallback would have been silently
defeated by that fallback.

Task 6 now puts the new namespace in per-locale modules under locales/docs/,
which the test imports directly and unwrapped. Scoped entirely to the new
namespace; the existing 315 KB of keys are untouched. Step 6 also asks the
implementer to demonstrate the trap: point the imports back at the merged
modules and watch a missing key pass.

* feat(docs): expose docs snapshot and annotations to the frontend

* docs(plan): locate the duplicated table-key rule correctly in Task 8

The plan said docsIndex.ts builds the qualified table key inline. It does not
— it groups by table.schema, a section key. The table key rule lives in a
private qualified() in docsSearch.ts and in a hand-rolled tableKey() in
DocsApp.vue, DocsSidebar.vue and WikiIndex.vue.

Part 3a's final review flagged that duplication as a Minor and it was
deferred. Task 8 was about to add a fifth copy, so it now extracts
docsKeys.ts first and replaces the existing ones. This is the key annotations
are stored under, so two call sites disagreeing attaches a note to the wrong
table.

* feat(docs): add pure annotation edit transforms

* docs(plan): ground the group hue picker in DBX's existing swatch idiom

ConnectionDialog.vue already has a swatch row — h-6 w-6 rounded-full buttons,
ring-2 selected state, i18n titles. Task 7 now points at it so the new picker
looks native.

With an explicit warning not to copy the fill mechanism: connection colours
are hex painted via Tailwind classes, group colours are hues rendered through
docs.css. A naive copy introduces hex literals and fails the contract test —
correctly, since a hardcoded hex cannot stay legible on both grounds, which is
why groups store a hue at all.

* docs(plan): make Task 10's dialog wiring concrete

Five exact locations, all verified: the store ref and its export, the
useDialogSources watcher, the AppDialogs import and render, and the
ObjectBrowser trigger plus its context-menu entry.

Records the non-obvious part: the watcher clears the source back to null
after firing, and that clearing is what makes the dialog re-openable —
without it, setting the same value twice does not re-trigger the watch.

ObjectBrowser is the entry point rather than the connection tree, because the
tree has no diagram entry either and ObjectBrowser already supplies exactly
the prefills the docs dialog needs.

* feat(docs): add the docs i18n namespace with a parity guard

* fix(docs): ban vue-i18n from standalone-exportable docs components

WarningBanner.vue used useI18n() directly, which throws with no Vue app
instance -- exactly the standalone HTML export case describeWarning's
translator parameter exists to avoid. Thread translate as a prop from
DocsApp instead, and add vue-i18n/useI18n( to the component contract's
forbidden list so the constraint is enforced, not just documented.

* docs(plan): note that DocsApp already has snapshot and translate

Task 6's fix added translate to DocsApp when describeWarning started taking a
translator. Task 9 said to add it, which would have been a duplicate prop.
It now says to add only annotations and readonly to the existing defineProps.

* feat(docs): add note editor, group editor and group picker

* docs(plan): give Task 10 the dialog shell from SchemaDiagramDialog

Exact Dialog primitives, the get/set computed every dialog here uses to bridge
the open prop, and the sizing class copied verbatim from
SchemaDiagramDialog.vue:827 — the docs viewer is the same kind of full-window
workspace, not a form, so it should not invent dimensions.

Also states explicitly that this component lives outside src/docs/ and so may
and must use useI18n(): it is what supplies the translate prop the viewer
components need, since they are banned from importing vue-i18n themselves.

* test(docs): guard the light-ground group tokens too

* feat(docs): add the enum page and a shared table-key helper

EnumPage renders an enum's values and every column declared with that type.
It is read-only on purpose: AnnotationFile has no `enums` key, so an edited
note would have nowhere to be saved.

qualifiedTableKey moves the `schema.name` rule — bare name on schema-less
engines like SQLite and MySQL — into docsKeys, where the call sites that had
each copied it can share one definition. It is the key annotations are stored
under, so two call sites disagreeing would attach a note to the wrong table.

columnsUsingEnum matches data_type exactly rather than by substring: an enum
named `state` would otherwise claim every `estado` and `statement` column.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VTBWnT4goXLA9iqDrfTPqk

* refactor(docs): share one qualified table key across the viewer

Six call sites had each copied the `schema.name` rule; they now import
qualifiedTableKey from docsKeys instead. Two were not in the plan's list:
TablePage.vue and RelationshipList.vue. RelationshipList passes a remapped
FieldRef rather than a DocTable, which is why the helper takes
Pick<DocTable, "schema" | "name"> — that widening is what let every call site
be adapted directly instead of keeping a thin delegating wrapper.

Also strengthens the columnsUsingEnum substring guard, which was not guarding
anything. Its only column had type `integer`, and "integer".includes("state")
is false, so replacing the exact match with includes() left all 8 tests
green. Adds a `statement` column — the only type here that really contains
`state` — and drops `estado` from the doc comment, since it does not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VTBWnT4goXLA9iqDrfTPqk

* feat(docs): thread editing through the viewer as emitted events

DocsApp gains `annotations` and `readonly` and re-emits a DocsEdit for every
change its children request. Nothing under src/docs/ persists anything, which
is what keeps the directory bundleable into the standalone HTML export; a new
contract guard now pins that by rejecting any component that names
save/load/applyDocsAnnotations.

NoteEditor is fed the MERGED snapshot note, not the local annotation layer. It
renders and edits one value, so seeding it locally would show nothing for a
note that came from a database comment. Writing over one shadows it, which is
what noteSource and shadowedNote already exist to disclose.

`annotations` is threaded for what the merge erases: `groups` carries the
editable GroupAnnotation records, while snapshot.groups carries resolved
TableGroups that GroupPicker and GroupEditor cannot write back to.

Also makes enums reachable. EnumPage rendered nowhere and search returned enum
hits that DocsSearch deliberately disabled, since enums carry no table key;
they now navigate by bare name, which is how columnsUsingEnum resolves them
too. Groups remain unclickable — they still have no page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VTBWnT4goXLA9iqDrfTPqk

* feat(docs): mount the documentation viewer in DBX with autosaved editing

DatabaseDocsDialog hosts DocsApp outside src/docs/, which is what lets it use
useI18n() and supply the `translate` prop the viewer components are banned from
importing for themselves. It collects the snapshot, loads the notes file
(falling back to emptyAnnotations), and holds the raw snapshot so every edit can
re-derive the merged view through applyDocsAnnotations.

createAutosave debounces writes and, above all, makes a failure visible: a
silently swallowed write is the worst outcome here, because the user keeps
typing and believes their notes are saved. It also refuses to run two writes at
once — flush() clearing the timer does not stop a write already awaiting save,
and two concurrent writes of the same file is the exact race that corrupted the
notes file before the Rust side used a unique temp path. Both properties are
pinned by tests I confirmed fail when the guard is removed.

Loads and re-derivations carry a generation number so a slow response cannot
overwrite a newer one, and closing flushes the debounce rather than dropping a
note typed a moment earlier.

Trigger mirrors the schema diagram's wiring: docsSource on connectionStore, a
watch in useDialogSources that clears the source so the dialog is re-openable,
an async component in AppDialogs, and openDocs in ObjectBrowser. The context
entry is added at BOTH object menus — the plan named only the table one, but
views offer diagram.open too and documentation is no less relevant there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VTBWnT4goXLA9iqDrfTPqk

* docs(plan): record Tasks 1-10 as done

The plan carried 58 unticked boxes after ten completed tasks, so progress had
to be reconstructed from the commit trail instead of read off the document.

Tasks 1-7 are ticked from that commit evidence rather than from step-by-step
observation — they landed in earlier sessions. Tasks 8-10 were executed and
verified directly.

Task 8 Step 2 stays open on purpose. `columnsUsingEnum` was already implemented
and committed before that step was reached, so its failure was never observed;
the exact-match guard was verified by Step 5 instead, which is what exposed
that the test could not detect a substring match at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VTBWnT4goXLA9iqDrfTPqk

* feat(docs): print snapshot warnings as prose from the CLI

`dbx dbml` printed `{warning:?}`, so a skipped table surfaced as
`TableSkipped { table: "public.orders", reason: "permission denied" }` —
the struct shape, reading like a panic rather than like advice.

The prose lives in Rust rather than in the `docs.warnings` i18n namespace
because the CLI has no i18n runtime. That is the same constraint that made
`describeWarning` take a translator instead of importing vue-i18n: the
viewer translates, the CLI cannot, so each needs its own source for the
same text.

A second test asserts the rendering is not the Debug form, because
reverting the CLI to `{warning:?}` is a one-character edit that still
compiles and still prints something.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH

* feat(docs): let a connection point its notes file at a repository

`docs_notes_path` has existed on `ConnectionConfig` since Part 2 and has
been read by `resolve_notes_path` since Part 3b, but nothing ever set it —
so every connection silently used the app data directory default and the
override was unreachable.

The field is what makes schema documentation reviewable: pointing it at a
file inside a repository puts notes in the same diff as the migration that
changed the schema.

Gated on `isSchemaAware`, matching the row above it, since documentation is
a relational-only feature. A cleared field is normalised to absent rather
than "" — `resolve_notes_path` treats blank as unset, but an empty string
would still be persisted as though a path had been chosen.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH

* docs: document database documentation and DBML export

Covers opening the viewer, notes and groups, the LOCAL/database-comment
rule, the notes file format and where it lives, every warning the viewer
can raise, and the `dbx dbml` verb including the CI drift check.

States the boundaries explicitly — relational engines only, no triggers or
procedures, and DBML export is one-way — because each of those is a
question the feature invites and would otherwise be answered by trying it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ro4mfGEmsbbH32WYsvxsfH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: t8y2 <t8y2@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-08-07 03:35:19 +08:00
1 parent 352403d79e
commit f30d59b989
117 files changed
+18546 -3

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import DocsSearch from "./components/DocsSearch.vue";
import DocsSidebar from "./components/DocsSidebar.vue";
import EnumPage from "./components/EnumPage.vue";
import GroupEditor from "./components/GroupEditor.vue";
import NoteEditor from "./components/NoteEditor.vue";
import TablePage from "./components/TablePage.vue";
import WarningBanner from "./components/WarningBanner.vue";
import WikiIndex from "./components/WikiIndex.vue";
import "./docs.css";
import type { Translate } from "./docsWarnings";
import { qualifiedTableKey } from "./docsKeys";
import { groupBySchema, groupByTableGroup } from "./docsIndex";
import type { AnnotationFile, DocsEdit, GroupAnnotation, SchemaSnapshot } from "./types";
const props = defineProps<{
snapshot: SchemaSnapshot;
/**
* The local notes layer. `snapshot` already carries notes merged for display,
* so this is here for what the merge erases: `groups` holds the editable
* `GroupAnnotation` records, while `snapshot.groups` holds resolved
* `TableGroup`s that GroupEditor and GroupPicker cannot write back to.
*/
annotations: AnnotationFile;
readonly?: boolean;
translate: Translate;
}>();
const emit = defineEmits<{
edit: [edit: DocsEdit];
}>();
/** `readonly` is the one optional prop; absent means editing is allowed. */
const isReadonly = computed(() => props.readonly ?? false);
const annotationGroups = computed<GroupAnnotation[]>(() => props.annotations.groups ?? []);
// Grouping is computed once here and handed to both the sidebar and the index,
// so the two can never disagree about what the sections are.
const mode = ref<"schema" | "group">(props.snapshot.groups.length > 0 ? "group" : "schema");
const activeKey = ref<string | null>(null);
const activeEnumName = ref<string | null>(null);
const sections = computed(() => (mode.value === "schema" ? groupBySchema(props.snapshot) : groupByTableGroup(props.snapshot)));
const activeTable = computed(() => props.snapshot.tables.find((table) => qualifiedTableKey(table) === activeKey.value) ?? null);
/**
* Matched on the bare name because that is the only thing a column's
* `data_type` can be compared against — `columnsUsingEnum` resolves enums the
* same way, so both agree when one name appears in two schemas.
*/
const activeEnum = computed(() => (activeEnumName.value === null ? null : (props.snapshot.enums.find((value) => value.name === activeEnumName.value) ?? null)));
const view = computed<"index" | "table" | "enum">(() => {
if (activeEnum.value !== null) {
return "enum";
}
return activeTable.value === null ? "index" : "table";
});
const activeGroup = computed(() => {
const groupId = activeTable.value?.groupId;
if (!groupId) {
return null;
}
return props.snapshot.groups.find((group) => group.id === groupId) ?? null;
});
function open(key: string): void {
// A key naming no table leaves the reader where they are rather than
// dropping them on a blank page.
if (props.snapshot.tables.some((table) => qualifiedTableKey(table) === key)) {
activeEnumName.value = null;
activeKey.value = key;
}
}
function openEnum(name: string): void {
if (props.snapshot.enums.some((value) => value.name === name)) {
activeKey.value = null;
activeEnumName.value = name;
}
}
function home(): void {
activeKey.value = null;
activeEnumName.value = null;
}
/**
* GroupPicker asks for a new group without naming it, so the id and hue are
* minted here. The hue rotates rather than repeating so two fresh groups are
* visually distinct before anyone opens GroupEditor to choose a colour.
*/
function createGroupFor(tableKey: string): void {
const group: GroupAnnotation = {
id: crypto.randomUUID(),
// Reuses the picker's own "New group" string rather than adding a locale
// key for a placeholder the user renames immediately in GroupEditor.
name: props.translate("docs.newGroup"),
hue: (annotationGroups.value.length * 47) % 360,
};
emit("edit", { kind: "upsertGroup", group });
emit("edit", { kind: "tableGroup", tableKey, groupId: group.id });
}
</script>
<template>
<div class="flex h-full min-h-0 bg-background text-foreground">
<DocsSidebar :sections="sections" :mode="mode" :active-key="activeKey" @update:mode="mode = $event" @select="open" @home="home()" />
<main class="flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
<header class="flex flex-wrap items-start justify-between gap-3">
<div class="flex flex-col gap-1">
<h1 class="text-base font-semibold">{{ snapshot.project.name }}</h1>
<p class="text-xs text-muted-foreground">
{{ snapshot.project.databaseType }}<template v-if="snapshot.project.database"> · {{ snapshot.project.database }}</template> · {{ snapshot.tables.length }} tables · generated {{ snapshot.project.generatedAt }}
</p>
</div>
<DocsSearch :snapshot="snapshot" @select="open" @select-enum="openEnum" />
</header>
<WarningBanner :warnings="snapshot.warnings" :translate="translate" />
<div v-if="view === 'index'" class="flex flex-col gap-4">
<NoteEditor :model-value="snapshot.project.note ?? ''" :readonly="isReadonly" :translate="translate" @update:model-value="emit('edit', { kind: 'projectNote', note: $event })" />
<WikiIndex :sections="sections" @select="open" />
<section v-if="!isReadonly && annotationGroups.length > 0" class="flex flex-col gap-2">
<h2 class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Groups</h2>
<GroupEditor v-for="group in annotationGroups" :key="group.id" :group="group" :translate="translate" @update:group="emit('edit', { kind: 'upsertGroup', group: $event })" @delete="emit('edit', { kind: 'removeGroup', groupId: $event })" />
</section>
</div>
<TablePage
v-else-if="view === 'table' && activeTable"
:table="activeTable"
:relationships="snapshot.relationships"
:group="activeGroup"
:annotation-groups="annotationGroups"
:readonly="isReadonly"
:translate="translate"
@select="open"
@edit="emit('edit', $event)"
@create-group="createGroupFor"
/>
<EnumPage v-else-if="activeEnum" :enum-type="activeEnum" :snapshot="snapshot" :translate="translate" @select="open" />
</main>
</div>
</template>
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { emptyAnnotations, removeGroup, setColumnNote, setProjectNote, setTableGroup, setTableNote, upsertGroup } from "../annotationEdits";
const base = emptyAnnotations();
describe("annotationEdits", () => {
it("starts from a valid empty file", () => {
expect(emptyAnnotations()).toEqual({ formatVersion: 1 });
});
it("never mutates its input", () => {
// Every function returns a new file. Mutating in place would make Vue's
// reactivity miss the change and make undo impossible to add later.
const before = JSON.stringify(base);
setTableNote(base, "public.orders", "hello");
expect(JSON.stringify(base)).toBe(before);
});
it("sets and clears a table note", () => {
const withNote = setTableNote(base, "public.orders", "One row per checkout.");
expect(withNote.tables?.["public.orders"].note).toBe("One row per checkout.");
const cleared = setTableNote(withNote, "public.orders", " ");
expect(cleared.tables?.["public.orders"]).toBeUndefined();
});
it("keeps a table entry when it still carries a group after the note clears", () => {
// Dropping the whole entry here would silently unassign the group.
const grouped = setTableGroup(setTableNote(base, "public.orders", "n"), "public.orders", "g1");
const cleared = setTableNote(grouped, "public.orders", "");
expect(cleared.tables?.["public.orders"].group).toBe("g1");
expect(cleared.tables?.["public.orders"].note).toBeUndefined();
});
it("sets and clears a column note", () => {
const withNote = setColumnNote(base, "public.orders", "status", "Lifecycle state.");
expect(withNote.tables?.["public.orders"].columns?.status.note).toBe("Lifecycle state.");
const cleared = setColumnNote(withNote, "public.orders", "status", "");
expect(cleared.tables?.["public.orders"]).toBeUndefined();
});
it("upserts a group by id", () => {
const created = upsertGroup(base, { id: "g1", name: "Core", hue: 28 });
expect(created.groups).toEqual([{ id: "g1", name: "Core", hue: 28 }]);
const renamed = upsertGroup(created, { id: "g1", name: "Core Accounts", hue: 200 });
expect(renamed.groups).toHaveLength(1);
expect(renamed.groups?.[0]).toEqual({ id: "g1", name: "Core Accounts", hue: 200 });
});
it("removing a group also clears every table that referenced it", () => {
// A dangling groupId renders as no group at all, so the file would look
// correct while carrying a reference to something that does not exist.
const withGroup = setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1");
const removed = removeGroup(withGroup, "g1");
expect(removed.groups ?? []).toEqual([]);
expect(removed.tables?.["public.orders"]).toBeUndefined();
});
it("removing a group keeps a table that still has a note", () => {
const seeded = setTableNote(setTableGroup(upsertGroup(base, { id: "g1", name: "Core", hue: 28 }), "public.orders", "g1"), "public.orders", "keep me");
const removed = removeGroup(seeded, "g1");
expect(removed.tables?.["public.orders"].note).toBe("keep me");
expect(removed.tables?.["public.orders"].group).toBeUndefined();
});
it("sets and clears the project note", () => {
const withNote = setProjectNote(base, "# Sales\n\nThe billing schema.");
expect(withNote.project?.note).toBe("# Sales\n\nThe billing schema.");
expect(setProjectNote(withNote, "").project).toBeUndefined();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { ANNOTATION_FILE_KEYS, COLUMN_ANNOTATION_KEYS, GROUP_ANNOTATION_KEYS, PROJECT_ANNOTATION_KEYS, TABLE_ANNOTATION_KEYS } from "../types";
// The Rust structs carry deny_unknown_fields, so any property TypeScript adds
// that Rust does not declare turns every save into a deserialization error at
// runtime. vue-tsc cannot see across the language boundary, so this reads the
// Rust source and compares the field sets directly.
const rustSource = readFileSync(path.resolve(__dirname, "../../../../../crates/dbx-core/src/docs/annotations.rs"), "utf8");
function rustFields(structName: string): string[] {
const start = rustSource.indexOf(`pub struct ${structName} {`);
expect(start, `struct ${structName} not found in annotations.rs`).toBeGreaterThan(-1);
const body = rustSource.slice(start, rustSource.indexOf("\n}", start));
return [...body.matchAll(/^\s{4}pub ([a-z_]+):/gm)].map((match) => toCamel(match[1])).sort();
}
function toCamel(value: string): string {
return value.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());
}
describe("annotation types match the Rust structs", () => {
it.each([
["AnnotationFile", ANNOTATION_FILE_KEYS],
["ProjectAnnotation", PROJECT_ANNOTATION_KEYS],
["GroupAnnotation", GROUP_ANNOTATION_KEYS],
["TableAnnotation", TABLE_ANNOTATION_KEYS],
["ColumnAnnotation", COLUMN_ANNOTATION_KEYS],
])("%s", (structName, witness) => {
// Rust source on one side, the TS interface's own keys on the other —
// so this fails whichever side drifts. Comparing Rust against a hardcoded
// list would only ever catch the Rust side.
expect(rustFields(structName as string)).toEqual(Object.keys(witness).sort());
});
});
@@ -0,0 +1,157 @@
import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { parse } from "vue/compiler-sfc";
const docsRoot = path.resolve(__dirname, "..");
function vueFiles(): string[] {
const found: string[] = [];
const walk = (dir: string) => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory() && entry.name !== "__tests__" && entry.name !== "fixtures") {
walk(full);
} else if (entry.isFile() && entry.name.endsWith(".vue")) {
found.push(full);
}
}
};
walk(docsRoot);
return found;
}
function scriptOf(file: string): string {
const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });
return `${descriptor.script?.content ?? ""}\n${descriptor.scriptSetup?.content ?? ""}`;
}
const EXPECTED = ["ColumnTable.vue", "DocsApp.vue", "DocsSearch.vue", "DocsSidebar.vue", "EnumPage.vue", "GroupEditor.vue", "GroupPicker.vue", "NoteEditor.vue", "RelationshipList.vue", "TablePage.vue", "WarningBanner.vue", "WikiIndex.vue"];
describe("docs viewer component contract", () => {
it("finds every expected component", () => {
expect(
vueFiles()
.map((file) => path.basename(file))
.sort(),
).toEqual(EXPECTED);
});
// Every test below loops over vueFiles(). On an empty set those loops run zero
// assertions and pass while proving nothing, so each one asserts the set is
// populated first. Without this, deleting every component turns the whole
// contract green.
it("makes no backend calls", () => {
const files = vueFiles();
expect(files.length).toBe(EXPECTED.length);
// vue-i18n belongs here for the same reason as the backend imports: these
// components are bundled into a standalone HTML file with no Vue app
// around them, and useI18n() throws without a provided instance. Strings
// arrive as a `translate` prop from the host instead.
const forbidden = ["@/lib/backend", "@tauri-apps", "invoke(", "useConnectionStore", "useQueryStore", "useSettingsStore", "fetch(", "axios", "vue-i18n", "useI18n("];
for (const file of files) {
const script = scriptOf(file);
for (const needle of forbidden) {
expect(script.includes(needle), `${path.basename(file)} must not reference ${needle}`).toBe(false);
}
}
});
it("keeps colour decisions out of templates", () => {
const files = vueFiles();
expect(files.length).toBe(EXPECTED.length);
for (const file of files) {
const source = readFileSync(file, "utf8");
expect(source.includes("oklch("), `${path.basename(file)} must not compute colour`).toBe(false);
expect(/#[0-9a-fA-F]{6}\b/.test(source), `${path.basename(file)} must not hardcode a hex colour`).toBe(false);
}
});
it("only ever feeds renderNote output to v-html", () => {
// The single most dangerous thing a template here can do. Task 7 escapes
// author HTML, but `v-html="table.note"` bypasses it entirely and hands a
// COMMENT ON value straight to the DOM. Every v-html binding must name
// renderNote, and no component may build HTML any other way.
const files = vueFiles();
expect(files.length).toBe(EXPECTED.length);
for (const file of files) {
const source = readFileSync(file, "utf8");
// Either quote style. A double-quote-only pattern finds zero matches in
// `v-html='table.note'` and passes it, which is the exact binding this
// test exists to catch.
for (const match of source.matchAll(/v-html\s*=\s*(["'])(.*?)\1/g)) {
expect(match[2], `${path.basename(file)}: v-html must render renderNote output`).toContain("renderNote");
}
expect(source.includes("innerHTML"), `${path.basename(file)} must not touch innerHTML`).toBe(false);
}
});
it("the viewer emits edits rather than persisting them", () => {
// src/docs/ must stay free of I/O so Part 3c can bundle it. Editing works
// by emitting upward; the dialog outside this directory does the saving.
const files = vueFiles();
expect(files.length).toBe(EXPECTED.length);
for (const file of files) {
const source = readFileSync(file, "utf8");
for (const needle of ["saveDocsAnnotations", "loadDocsAnnotations", "applyDocsAnnotations"]) {
expect(source.includes(needle), `${path.basename(file)} must not call ${needle}`).toBe(false);
}
}
});
it("editing components accept a readonly mode", () => {
// Part 3c renders these same components with editing off inside an
// exported HTML file. A component that cannot be made read-only would
// have to be forked for the export.
const files = vueFiles();
expect(files.length).toBe(EXPECTED.length);
const editors = files.filter((file) => path.basename(file) === "NoteEditor.vue");
expect(editors.length).toBe(1);
expect(readFileSync(editors[0], "utf8")).toContain("readonly");
});
it('uses <script setup lang="ts">', () => {
const files = vueFiles();
expect(files.length).toBe(EXPECTED.length);
for (const file of files) {
const { descriptor } = parse(readFileSync(file, "utf8"), { filename: file });
expect(descriptor.scriptSetup, `${path.basename(file)} must use <script setup>`).toBeTruthy();
expect(descriptor.scriptSetup?.lang, `${path.basename(file)} must be TypeScript`).toBe("ts");
}
});
it("defines the group colour tokens for WebViews without oklch", () => {
// DBX supports legacy WebViews with no oklch (globals.css carries an
// `@supports not (color: oklch(...))` block). The repo's convention is
// progressive enhancement: a legacy-safe base value first, then the same
// token redefined inside `@supports (color: oklch(1 0 0))`. Without the
// base, every table group renders colourless on those WebViews.
//
// Assert each selector's base block separately. An ordering check like
// `indexOf(hsl) < indexOf(@supports)` quantifies over ANY occurrence, so
// deleting the light block leaves the dark block's hsl satisfying it — the
// test passes while light-theme legacy WebViews render every group
// colourless.
//
// `.docs-ground-light` is here for the same reason as the other two, not as
// a third theme: GroupEditor previews a hue on a light ground whatever the
// app's theme, so that ground needs its own legacy-safe base. Without this
// entry the whole block could be deleted with the suite still green, and
// the preview would quietly show dark-theme colours on white in dark mode.
const css = readFileSync(path.join(docsRoot, "docs.css"), "utf8");
const enhanced = css.indexOf("@supports (color: oklch(1 0 0))");
expect(enhanced).toBeGreaterThan(-1);
const legacyBase = css.slice(0, enhanced);
for (const selector of [".docs-group", ".dark .docs-group", ".docs-ground-light .docs-group"]) {
// `^` with the m flag anchors to a line start, so `.docs-group` cannot
// match inside `.dark .docs-group`, and neither matches the indented
// copies inside the @supports block.
const pattern = new RegExp(`^${selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*\\{([^}]*)\\}`, "m");
const block = pattern.exec(legacyBase)?.[1];
expect(block, `${selector} needs a legacy-safe base block before @supports`).toBeTruthy();
expect(block, `${selector} must define --group-c without oklch`).toContain("--group-c: hsl(");
expect(block, `${selector} must define --group-tint without oklch`).toContain("--group-tint: hsl(");
}
});
});
+152
View File
@@ -0,0 +1,152 @@
import { describe, expect, it } from "vitest";
import { columnsUsingEnum, groupBySchema, groupByTableGroup } from "../docsIndex";
import type { DocTable, SchemaSnapshot, TableGroup } from "../types";
function table(schema: string | null, name: string, groupId: string | null = null): DocTable {
return {
schema,
name,
kind: "TABLE",
columns: [],
indexes: [],
foreignKeys: [],
groupId,
note: null,
noteSource: "NONE",
shadowedNote: null,
columnNotes: {},
estimatedRows: null,
viewDefinition: null,
};
}
function snapshot(tables: DocTable[], groups: TableGroup[] = []): SchemaSnapshot {
return {
formatVersion: 1,
project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
tables,
relationships: [],
groups,
enums: [],
warnings: [],
};
}
describe("groupBySchema", () => {
it("groups tables under their schema, sorted by schema then name", () => {
const sections = groupBySchema(snapshot([table("public", "orders"), table("analytics", "daily_sales"), table("public", "customers")]));
expect(sections.map((section) => section.key)).toEqual(["analytics", "public"]);
expect(sections[1].tables.map((t) => t.name)).toEqual(["customers", "orders"]);
});
it("puts schema-less tables in a single bare section", () => {
const sections = groupBySchema(snapshot([table(null, "orders")]));
expect(sections).toHaveLength(1);
expect(sections[0].tables[0].name).toBe("orders");
});
});
describe("groupByTableGroup", () => {
const groups: TableGroup[] = [
{ id: "order-mgmt", name: "Order Management", hue: 28, note: "Checkout." },
{ id: "product-mgmt", name: "Product Management", hue: 148, note: null },
];
it("groups tables by their group, preserving the snapshot's group order", () => {
const sections = groupByTableGroup(snapshot([table("product", "products", "product-mgmt"), table("core", "orders", "order-mgmt")], groups));
expect(sections.map((section) => section.key)).toEqual(["order-mgmt", "product-mgmt"]);
expect(sections[0].label).toBe("Order Management");
expect(sections[0].hue).toBe(28);
expect(sections[0].note).toBe("Checkout.");
});
it("collects ungrouped tables into a trailing (no group) section", () => {
const sections = groupByTableGroup(snapshot([table("core", "orders", "order-mgmt"), table("core", "users", null)], groups));
const last = sections[sections.length - 1];
expect(last.key).toBe("");
expect(last.hue).toBeNull();
expect(last.tables.map((t) => t.name)).toEqual(["users"]);
});
it("omits a group that has no members", () => {
// render_group in the serializer skips empty groups; the viewer must not
// show an empty header where the DBML shows nothing.
const sections = groupByTableGroup(snapshot([table("core", "orders", "order-mgmt")], groups));
expect(sections.map((section) => section.key)).not.toContain("product-mgmt");
});
it("treats a table whose groupId names no group as ungrouped", () => {
const sections = groupByTableGroup(snapshot([table("core", "orders", "ghost")], groups));
expect(sections).toHaveLength(1);
expect(sections[0].key).toBe("");
});
});
describe("columnsUsingEnum", () => {
// The file's existing helper is `table(schema, name, groupId)` and builds a
// table with NO columns, so these tests need columns attached. Add this
// helper beside it rather than changing the existing signature — the other
// tests in this file call it positionally.
function withColumns(base: DocTable, columns: Array<{ name: string; type: string }>): DocTable {
return {
...base,
columns: columns.map((column) => ({
name: column.name,
data_type: column.type,
is_nullable: false,
column_default: null,
is_primary_key: false,
extra: "",
comment: null,
numeric_precision: null,
numeric_scale: null,
character_maximum_length: null,
})),
};
}
function snapshotOf(tables: DocTable[], enums: SchemaSnapshot["enums"]): SchemaSnapshot {
return {
formatVersion: 1,
project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
tables,
relationships: [],
groups: [],
enums,
warnings: [],
};
}
it("finds every column using an enum, across tables", () => {
const snapshot = snapshotOf(
[withColumns(table("public", "orders"), [{ name: "status", type: "order_status" }]), withColumns(table("public", "returns"), [{ name: "state", type: "order_status" }]), withColumns(table("public", "users"), [{ name: "id", type: "integer" }])],
[{ schema: "public", name: "order_status", values: ["new"], note: null, synthesized: false }],
);
expect(columnsUsingEnum(snapshot, "order_status")).toEqual([
{ tableKey: "public.orders", table: "orders", column: "status" },
{ tableKey: "public.returns", table: "returns", column: "state" },
]);
});
it("returns nothing for an enum no column references", () => {
// Must not fall back to "every column". The `statement` column is the one
// that matters: it is the only type here that *contains* `state`, so a
// substring match would claim it while an unrelated type like `integer`
// would not. Drop it and this test passes against `includes()` too, which
// makes it stop guarding anything.
const snapshot = snapshotOf(
[
withColumns(table("public", "users"), [
{ name: "id", type: "integer" },
{ name: "body", type: "statement" },
]),
],
[{ schema: "public", name: "state", values: ["a"], note: null, synthesized: false }],
);
expect(columnsUsingEnum(snapshot, "state")).toEqual([]);
});
});
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from "vitest";
import { searchDocs, type SearchHit } from "../docsSearch";
import type { DocTable, SchemaSnapshot } from "../types";
function column(name: string) {
return {
name,
data_type: "text",
is_nullable: true,
column_default: null,
is_primary_key: false,
extra: null,
};
}
function table(schema: string, name: string, columns: string[] = []): DocTable {
return {
schema,
name,
kind: "TABLE",
columns: columns.map(column),
indexes: [],
foreignKeys: [],
groupId: null,
note: null,
noteSource: "NONE",
shadowedNote: null,
columnNotes: {},
estimatedRows: null,
viewDefinition: null,
};
}
const snapshot: SchemaSnapshot = {
formatVersion: 1,
project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
tables: [
table("public", "orders", ["status", "total"]),
// `orders_count` contains "orders", so a query for "orders" matches BOTH
// a table and a column — which is what makes the ranking test able to fail.
table("public", "customers", ["status", "orders_count"]),
// Mixed case, so a mutant that lowercases only the needle and not the
// candidate would fail the case-insensitivity test.
table("public", "Invoices", ["Amount"]),
],
relationships: [],
groups: [{ id: "g1", name: "Order Management", hue: 28, note: null }],
enums: [{ schema: "public", name: "order_status", values: ["pending"], note: null, synthesized: false }],
warnings: [],
};
// Columns outnumber every other kind by two orders of magnitude in a real
// database — the fixture answers "e" with 133 columns against 1 group and 12
// enums. This snapshot reproduces that shape: one term matching more of each
// kind than its cap allows.
const flooded: SchemaSnapshot = {
formatVersion: 1,
project: { name: "p", databaseType: "postgres", database: null, schemas: [], generatedAt: "", note: null },
tables: [
table(
"public",
"notes",
Array.from({ length: 30 }, (_, index) => `note_${index}`),
),
],
relationships: [],
groups: Array.from({ length: 12 }, (_, index) => ({ id: `g${index}`, name: `note group ${index}`, hue: 28, note: null })),
enums: Array.from({ length: 12 }, (_, index) => ({ schema: "public", name: `note_enum_${index}`, values: ["pending"], note: null, synthesized: false })),
warnings: [],
};
describe("searchDocs", () => {
it("returns nothing for an empty query", () => {
expect(searchDocs(snapshot, "")).toEqual([]);
expect(searchDocs(snapshot, " ")).toEqual([]);
});
it("matches table names case-insensitively", () => {
const hits = searchDocs(snapshot, "ORD");
expect(hits.some((hit) => hit.kind === "table" && hit.label === "orders")).toBe(true);
});
it("matches columns and reports which table they belong to", () => {
const hits = searchDocs(snapshot, "total");
const hit = hits.find((candidate) => candidate.kind === "column");
expect(hit).toBeDefined();
expect(hit!.label).toBe("total");
expect(hit!.context).toContain("orders");
});
it("returns one hit per table for a column name shared by several tables", () => {
const hits = searchDocs(snapshot, "status").filter((hit) => hit.kind === "column");
expect(hits).toHaveLength(2);
expect(hits.map((hit) => hit.context).sort()).toEqual(["public.customers", "public.orders"]);
});
it("matches groups and enums", () => {
expect(searchDocs(snapshot, "Order Man").some((hit) => hit.kind === "group")).toBe(true);
expect(searchDocs(snapshot, "order_status").some((hit) => hit.kind === "enum")).toBe(true);
});
it("ranks table matches above column matches for the same term", () => {
// "orders" now matches the `orders` table AND the `orders_count` column
// on `customers`. Reversing the concatenation order must fail this.
const hits = searchDocs(snapshot, "orders");
const firstTable = hits.findIndex((hit) => hit.kind === "table");
const firstColumn = hits.findIndex((hit) => hit.kind === "column");
expect(firstTable).toBeGreaterThanOrEqual(0);
expect(firstColumn).toBeGreaterThanOrEqual(0);
expect(firstTable).toBeLessThan(firstColumn);
});
it("carries a tableKey so a hit can navigate", () => {
const hit = searchDocs(snapshot, "total").find((candidate) => candidate.kind === "column");
expect(hit!.tableKey).toBe("public.orders");
});
it("still returns group and enum hits when columns flood the results", () => {
// A single cap applied after concatenation deletes the tail of the list,
// and groups and enums are the tail — making them unreachable through
// search no matter what the user types.
const hits = searchDocs(flooded, "note");
expect(
hits.some((hit) => hit.kind === "group"),
"groups must survive a column flood",
).toBe(true);
expect(
hits.some((hit) => hit.kind === "enum"),
"enums must survive a column flood",
).toBe(true);
});
it("caps each kind independently", () => {
const hits = searchDocs(flooded, "note");
const count = (kind: SearchHit["kind"]) => hits.filter((hit) => hit.kind === kind).length;
expect(count("table")).toBe(1);
expect(count("column")).toBe(20);
expect(count("group")).toBe(10);
expect(count("enum")).toBe(10);
});
it("matches a mixed-case identifier from a lowercase query", () => {
// The candidate, not just the needle, must be lowercased — otherwise
// search silently becomes case-sensitive for databases with quoted or
// uppercase identifiers.
expect(searchDocs(snapshot, "invoice").some((hit) => hit.label === "Invoices")).toBe(true);
expect(searchDocs(snapshot, "amount").some((hit) => hit.label === "Amount")).toBe(true);
});
});
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { describeWarning, type Translate } from "../docsWarnings";
import type { SnapshotWarning } from "../types";
// A fake translator that echoes the key and params back rather than English
// prose. This is what actually matters now: that describeWarning calls
// translate with the right key and the right params, not what the English
// copy says — the copy itself lives in the i18n namespace and is covered by
// the parity test.
const translate: Translate = (key, params) => `${key}|${JSON.stringify(params ?? {})}`;
describe("describeWarning", () => {
it("explains a skipped table as a warning naming the table and reason", () => {
const notice = describeWarning({ kind: "tableSkipped", table: "public.secret", reason: "permission denied" }, translate);
expect(notice.severity).toBe("warning");
expect(notice.title).toBe("docs.warnings.tableSkipped.title|{}");
expect(notice.detail).toBe('docs.warnings.tableSkipped.detail|{"table":"public.secret","reason":"permission denied"}');
});
it("explains missing foreign-key metadata as an engine limitation, not a fault", () => {
const notice = describeWarning({ kind: "noForeignKeyMetadata", engine: "ClickHouse" }, translate);
expect(notice.severity).toBe("info");
expect(notice.title).toBe("docs.warnings.noForeignKeyMetadata.title|{}");
expect(notice.detail).toBe('docs.warnings.noForeignKeyMetadata.detail|{"engine":"ClickHouse"}');
});
it("explains unsupported comments", () => {
const notice = describeWarning({ kind: "commentsUnsupported", engine: "SQLite" }, translate);
expect(notice.severity).toBe("info");
expect(notice.title).toBe("docs.warnings.commentsUnsupported.title|{}");
expect(notice.detail).toBe('docs.warnings.commentsUnsupported.detail|{"engine":"SQLite"}');
});
it("reports orphaned notes with the count", () => {
const notice = describeWarning({ kind: "orphanedNotes", count: 3 }, translate);
expect(notice.severity).toBe("warning");
expect(notice.title).toBe("docs.warnings.orphanedNotes.title|{}");
expect(notice.detail).toBe('docs.warnings.orphanedNotes.detail|{"count":3}');
});
it("explains a DBML omission naming the item", () => {
const notice = describeWarning(
{
kind: "dbmlOmitted",
table: "public.orders",
item: "idx_orders_open",
reason: "partial index filter has no DBML equivalent",
},
translate,
);
expect(notice.severity).toBe("info");
expect(notice.title).toBe("docs.warnings.dbmlOmitted.title|{}");
expect(notice.detail).toBe('docs.warnings.dbmlOmitted.detail|{"item":"idx_orders_open","table":"public.orders","reason":"partial index filter has no DBML equivalent"}');
});
it("never returns an empty title or detail for any known kind", () => {
const samples: SnapshotWarning[] = [
{ kind: "tableSkipped", table: "t", reason: "r" },
{ kind: "noForeignKeyMetadata", engine: "e" },
{ kind: "commentsUnsupported", engine: "e" },
{ kind: "orphanedNotes", count: 1 },
{ kind: "dbmlOmitted", table: "t", item: "i", reason: "r" },
];
for (const sample of samples) {
const notice = describeWarning(sample, translate);
expect(notice.title.length, `empty title for ${sample.kind}`).toBeGreaterThan(0);
expect(notice.detail.length, `empty detail for ${sample.kind}`).toBeGreaterThan(0);
}
});
});
@@ -0,0 +1,158 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import type { SchemaSnapshot } from "../types";
const fixturePath = path.resolve(__dirname, "../fixtures/keycloak.snapshot.json");
function loadFixture(): SchemaSnapshot {
return JSON.parse(readFileSync(fixturePath, "utf8")) as SchemaSnapshot;
}
describe("fixture conformance", () => {
// This fixture is generated by the REAL Rust serializer. Its job is to fail
// when the Rust model changes shape, so the hand-maintained types.ts cannot
// drift silently.
it("has the shape types.ts declares", () => {
const snapshot = loadFixture();
expect(snapshot.formatVersion).toBe(1);
expect(Array.isArray(snapshot.tables)).toBe(true);
expect(snapshot.tables.length).toBeGreaterThan(0);
expect(typeof snapshot.project.databaseType).toBe("string");
expect(Array.isArray(snapshot.project.schemas)).toBe(true);
});
it("uses camelCase for snapshot-owned fields", () => {
const raw = JSON.parse(readFileSync(fixturePath, "utf8")) as Record<string, unknown>;
expect(raw).toHaveProperty("formatVersion");
expect(raw).not.toHaveProperty("format_version");
const table = (raw.tables as Record<string, unknown>[])[0];
expect(table).toHaveProperty("noteSource");
expect(table).toHaveProperty("columnNotes");
expect(table).toHaveProperty("foreignKeys");
expect(table).not.toHaveProperty("note_source");
});
it("keeps snake_case on columns, which come from crate::types", () => {
const snapshot = loadFixture();
const withColumns = snapshot.tables.find((table) => table.columns.length > 0);
expect(withColumns, "fixture must contain at least one table with columns").toBeDefined();
const column = withColumns!.columns[0] as unknown as Record<string, unknown>;
expect(column).toHaveProperty("data_type");
expect(column).toHaveProperty("is_nullable");
expect(column).not.toHaveProperty("dataType");
});
it("carries an annotated note, a group and an orphan warning", () => {
const snapshot = loadFixture();
const annotated = snapshot.tables.find((table) => table.noteSource === "LOCAL");
expect(annotated, "fixture must include a LOCAL-sourced note").toBeDefined();
expect(annotated!.note).toBeTruthy();
expect(snapshot.groups.length).toBeGreaterThan(0);
expect(typeof snapshot.groups[0].hue).toBe("number");
const orphan = snapshot.warnings.find((warning) => warning.kind === "orphanedNotes");
expect(orphan, "fixture must include an orphanedNotes warning").toBeDefined();
});
it("every warning discriminant is one types.ts knows", () => {
const known = new Set(["tableSkipped", "noForeignKeyMetadata", "commentsUnsupported", "orphanedNotes", "dbmlOmitted"]);
for (const warning of loadFixture().warnings) {
expect(known.has(warning.kind), `unknown warning kind: ${warning.kind}`).toBe(true);
}
});
// Every struct below is pinned in BOTH directions — no missing key, no
// unexpected key — because each direction catches a different drift. A
// missing key is a removal or a rename's old name; an unexpected key is the
// rename's new name. Pinning only "required keys present" lets a rename of
// Relationship::to slip through the whole suite AND vue-tsc while
// RelationshipList reads `field.table` on undefined and every table page
// renders blank.
//
// `Object.hasOwn`, never truthiness: most of these keys are legitimately
// null, and "present and null" must stay distinguishable from "absent",
// which is what skip_serializing_if produces.
function pinShape(label: string, instances: unknown[], required: string[], optional: string[] = []): void {
// An empty instance list runs zero assertions and passes while proving
// nothing, so every struct has to actually appear in the fixture.
expect(instances.length, `fixture must contain at least one ${label}`).toBeGreaterThan(0);
const allowed = new Set([...required, ...optional]);
for (const [position, instance] of instances.entries()) {
const record = instance as Record<string, unknown>;
for (const key of required) {
expect(Object.hasOwn(record, key), `${label}[${position}] must always carry ${key}`).toBe(true);
}
for (const key of Object.keys(record)) {
expect(allowed.has(key), `${label}[${position}] carries unexpected key ${key}`).toBe(true);
}
}
}
it("the snapshot root has exactly the keys types.ts declares", () => {
pinShape("SchemaSnapshot", [loadFixture()], ["formatVersion", "project", "tables", "relationships", "groups", "enums", "warnings"]);
});
it("ProjectMeta has exactly the keys types.ts declares", () => {
pinShape("ProjectMeta", [loadFixture().project], ["name", "databaseType", "database", "schemas", "generatedAt", "note"]);
});
it("DocTable has exactly the keys types.ts declares", () => {
pinShape("DocTable", loadFixture().tables, ["schema", "name", "kind", "columns", "indexes", "foreignKeys", "groupId", "note", "noteSource", "shadowedNote", "columnNotes", "estimatedRows", "viewDefinition"]);
});
it("ColumnInfo has exactly the keys types.ts declares", () => {
// The required ten are required because Rust has no skip_serializing_if on
// them. The optional three DO carry one, so the key is absent rather than
// null when there is no value.
const columns = loadFixture().tables.flatMap((table) => table.columns);
pinShape("ColumnInfo", columns, ["name", "data_type", "is_nullable", "column_default", "is_primary_key", "extra", "comment", "numeric_precision", "numeric_scale", "character_maximum_length"], ["enum_values", "character_set", "collation"]);
});
it("IndexInfo has exactly the keys types.ts declares", () => {
const indexes = loadFixture().tables.flatMap((table) => table.indexes);
pinShape("IndexInfo", indexes, ["name", "columns", "is_unique", "is_primary", "filter", "index_type", "included_columns", "comment"]);
});
it("ForeignKeyInfo has exactly the keys types.ts declares", () => {
const foreignKeys = loadFixture().tables.flatMap((table) => table.foreignKeys);
pinShape("ForeignKeyInfo", foreignKeys, ["name", "column", "ref_table", "ref_column"], ["ref_schema", "on_update", "on_delete"]);
});
it("ColumnNote has exactly the keys types.ts declares", () => {
const notes = loadFixture().tables.flatMap((table) => Object.values(table.columnNotes));
pinShape("ColumnNote", notes, ["note", "source", "shadowed"]);
});
it("Relationship and FieldRef have exactly the keys types.ts declares", () => {
const relationships = loadFixture().relationships;
pinShape("Relationship", relationships, ["id", "name", "from", "to", "cardinality", "onUpdate", "onDelete"]);
pinShape(
"FieldRef",
relationships.flatMap((relationship) => [relationship.from, relationship.to]),
["schema", "table", "column"],
);
});
it("TableGroup has exactly the keys types.ts declares", () => {
pinShape("TableGroup", loadFixture().groups, ["id", "name", "hue", "note"]);
});
it("records that the fixture source declares no enum types, leaving DocEnum unpinned", () => {
// Keycloak's schema has no PostgreSQL enum types, so this fixture cannot
// exercise DocEnum. That is a real gap: a Rust-side rename of a DocEnum
// field would pass every test in this file and break the viewer's enum
// rendering silently.
//
// Asserting the gap rather than deleting the test keeps it visible and
// makes it self-correcting — the day the fixture source gains an enum this
// fails, and the pin below should replace it:
//
// pinShape("DocEnum", loadFixture().enums, ["schema", "name", "values", "note", "synthesized"]);
expect(loadFixture().enums, "fixture gained enums — restore the DocEnum pinShape here").toEqual([]);
});
});
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { groupStyle } from "../groupColor";
describe("groupStyle", () => {
it("exposes the hue as a CSS custom property", () => {
expect(groupStyle(28)).toEqual({ "--h": "28" });
});
it("returns no custom property for an ungrouped section", () => {
expect(groupStyle(null)).toEqual({});
});
it("wraps hues into 0-359 rather than emitting an out-of-range value", () => {
expect(groupStyle(360)).toEqual({ "--h": "0" });
expect(groupStyle(388)).toEqual({ "--h": "28" });
expect(groupStyle(-1)).toEqual({ "--h": "359" });
});
it("never emits a colour value", () => {
// Lightness and chroma belong to the theme. If this function ever returns
// a hex or oklch string, the dark-mode contrast guarantee is gone.
const style = groupStyle(200);
const serialized = JSON.stringify(style);
expect(serialized).not.toContain("#");
expect(serialized).not.toContain("oklch");
expect(serialized).not.toContain("rgb");
});
it("coerces a non-integer hue to an integer", () => {
expect(groupStyle(28.7)).toEqual({ "--h": "28" });
});
});
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, it } from "vitest";
import { renderNote } from "../renderNote";
describe("renderNote", () => {
it("renders ordinary markdown", () => {
expect(renderNote("One row per **checkout**.")).toContain("<strong>checkout</strong>");
});
it("renders inline code and fenced blocks", () => {
expect(renderNote("see `order_status`")).toContain("<code>order_status</code>");
expect(renderNote("```sql\nSELECT 1;\n```")).toContain("<pre>");
});
it("returns an empty string for null or blank input", () => {
expect(renderNote(null)).toBe("");
expect(renderNote(" ")).toBe("");
});
it("escapes a script tag rather than rendering it", () => {
const html = renderNote("<script>alert(1)</script>");
expect(html).not.toContain("<script>");
expect(html).toContain("&lt;script&gt;");
});
it("escapes an img onerror payload", () => {
// NB: asserting !contains("onerror=") would FAIL against a correct
// implementation — the escaped text legitimately still contains that
// substring. What matters is that no <img> ELEMENT is produced.
const html = renderNote('<img src=x onerror="alert(1)">');
expect(html.toLowerCase()).not.toContain("<img");
expect(html).toContain("&lt;img");
});
it("escapes raw HTML even when it looks harmless", () => {
// Blanket rule: no author-supplied HTML is rendered, ever. A rule with
// exceptions is a rule someone will find a way around.
const html = renderNote("<b>bold</b>");
expect(html).not.toContain("<b>bold</b>");
expect(html).toContain("&lt;b&gt;");
});
it("does not preserve HTML entities twice", () => {
// Guards the pre-escaping approach, which turns "a &amp; b" into
// "a &amp;amp; b" and renders the entity visibly to the reader.
expect(renderNote("a &amp; b")).toContain("a &amp; b");
expect(renderNote("a &amp; b")).not.toContain("&amp;amp;");
});
it.each([
["javascript:alert(1)", "javascript"],
["JaVaScRiPt:alert(1)", "javascript"],
["&#106;avascript:alert(1)", "avascript"],
["vbscript:alert(1)", "vbscript"],
["data:text/html;base64,PHNjcmlwdD4=", "data:"],
])("drops the unsafe link scheme %s", (href, forbidden) => {
const html = renderNote(`[click](${href})`).toLowerCase();
expect(html).not.toContain(forbidden);
expect(html).toContain("click"); // the text survives; only the href is dropped
});
it("drops an unsafe image scheme", () => {
const html = renderNote("![img](javascript:alert(1))").toLowerCase();
expect(html).not.toContain("javascript");
expect(html).not.toContain("<img");
});
it.each(["//evil.example.com", "//evil.example.com/a.png", "/\\evil.example.com", "/\\evil.example.com/a.png", "\\\\evil.example.com"])("drops the protocol-relative URL %s", (href) => {
// The URL spec treats /\ like //, so both separators must be rejected.
expect(renderNote(`[x](${href})`)).not.toContain("evil.example.com");
expect(renderNote(`![x](${href})`)).not.toContain("evil.example.com");
});
it("escapes single quotes so the escaper does not rely on double-quoted attributes", () => {
// Not exploitable while every attribute here is double-quoted, but that is
// a formatting convention enforced nowhere. Escaping ' keeps escapeHtml
// correct on its own rather than correct-given-a-distant-invariant.
const html = renderNote(`[x](https://example.com "it's here")`);
expect(html).toContain("&#39;");
expect(html).not.toContain("it's here");
});
it("still allows an ordinary root-relative path", () => {
// The // guard must not break the single-slash relative case it sits in
// front of.
expect(renderNote("[x](/docs/page.html)")).toContain('href="/docs/page.html"');
});
it.each(["https://example.com", "http://example.com", "mailto:a@b.com", "#anchor", "./rel.html"])("keeps the safe link target %s", (href) => {
expect(renderNote(`[ok](${href})`)).toContain(`href="${href}"`);
});
it("parses markdown inside link text instead of emitting it raw", () => {
// marked hands the renderer the RAW source text. Emitting it directly
// both breaks formatting and injects unescaped HTML.
expect(renderNote("[**keep**](https://example.com)")).toContain("<strong>keep</strong>");
const dropped = renderNote('[<img src=x onerror="alert(1)">](javascript:alert(1))');
expect(dropped.toLowerCase()).not.toContain("<img");
expect(dropped).toContain("&lt;img");
});
});
+95
View File
@@ -0,0 +1,95 @@
import { describe, expect, it } from "vitest";
import type { ColumnInfo, IndexInfo, SchemaSnapshot, SnapshotWarning } from "../types";
describe("snapshot types", () => {
it("accepts a minimal snapshot shaped like the Rust output", () => {
const snapshot: SchemaSnapshot = {
formatVersion: 1,
project: {
name: "Ecommerce",
databaseType: "postgres",
database: "shop",
schemas: ["public"],
generatedAt: "2026-08-03T00:00:00Z",
note: null,
},
tables: [
{
schema: "public",
name: "orders",
kind: "TABLE",
columns: [],
indexes: [],
foreignKeys: [],
groupId: null,
note: "Checkout rows.",
noteSource: "DATABASE",
shadowedNote: null,
columnNotes: {},
estimatedRows: null,
viewDefinition: null,
},
],
relationships: [],
groups: [],
enums: [],
warnings: [],
};
expect(snapshot.tables[0].noteSource).toBe("DATABASE");
expect(snapshot.tables[0].kind).toBe("TABLE");
});
it("discriminates warnings on a camelCase kind", () => {
// Rust: #[serde(rename_all = "camelCase", tag = "kind")] — so the
// discriminant is camelCase even though sibling enums are SCREAMING_SNAKE.
const warning: SnapshotWarning = {
kind: "tableSkipped",
table: "public.secret",
reason: "permission denied",
};
expect(warning.kind).toBe("tableSkipped");
const orphans: SnapshotWarning = { kind: "orphanedNotes", count: 3 };
if (orphans.kind === "orphanedNotes") {
expect(orphans.count).toBe(3);
} else {
throw new Error("discriminated union must narrow on kind");
}
});
it("requires the always-serialized column and index fields", () => {
// These keys have no skip_serializing_if in Rust, so they are always
// present in the JSON. Typing them optional would let `undefined` reach
// code that checks `=== null`.
const column: ColumnInfo = {
name: "status",
data_type: "text",
is_nullable: false,
column_default: null,
is_primary_key: false,
extra: null,
comment: null,
numeric_precision: null,
numeric_scale: null,
character_maximum_length: null,
};
expect(column.comment).toBeNull();
const index: IndexInfo = {
name: "idx",
columns: ["status"],
is_unique: false,
is_primary: false,
filter: null,
index_type: null,
included_columns: null,
comment: null,
};
expect(index.filter).toBeNull();
// The skip_serializing_if fields may simply be absent.
const minimal: ColumnInfo = { ...column, enum_values: undefined };
expect(minimal.character_set).toBeUndefined();
});
});
+100
View File
@@ -0,0 +1,100 @@
import type { AnnotationFile, GroupAnnotation, TableAnnotation } from "./types";
/**
* Every function here returns a NEW file rather than mutating.
*
* Empty or whitespace-only prose removes the entry instead of storing "" —
* the notes file is meant to be committed and reviewed, so it must not
* accumulate keys holding nothing.
*/
export function emptyAnnotations(): AnnotationFile {
return { formatVersion: 1 };
}
function blank(value: string): boolean {
return value.trim() === "";
}
/** Drop a table entry once it carries neither a note nor a group. */
function pruneTable(tables: Record<string, TableAnnotation>, key: string): Record<string, TableAnnotation> {
const entry = tables[key];
const empty = entry !== undefined && entry.note === undefined && entry.group === undefined && Object.keys(entry.columns ?? {}).length === 0;
if (!empty) {
return tables;
}
const { [key]: _dropped, ...rest } = tables;
return rest;
}
function withTable(file: AnnotationFile, key: string, change: (entry: TableAnnotation) => TableAnnotation): AnnotationFile {
const tables = { ...file.tables };
tables[key] = change(tables[key] ?? {});
const pruned = pruneTable(tables, key);
return { ...file, tables: Object.keys(pruned).length > 0 ? pruned : undefined };
}
export function setTableNote(file: AnnotationFile, tableKey: string, note: string): AnnotationFile {
return withTable(file, tableKey, (entry) => {
const { note: _old, ...rest } = entry;
return blank(note) ? rest : { ...rest, note };
});
}
export function setColumnNote(file: AnnotationFile, tableKey: string, column: string, note: string): AnnotationFile {
return withTable(file, tableKey, (entry) => {
const columns = { ...entry.columns };
if (blank(note)) {
delete columns[column];
} else {
columns[column] = { note };
}
const { columns: _old, ...rest } = entry;
return Object.keys(columns).length > 0 ? { ...rest, columns } : rest;
});
}
export function setTableGroup(file: AnnotationFile, tableKey: string, groupId: string | null): AnnotationFile {
return withTable(file, tableKey, (entry) => {
const { group: _old, ...rest } = entry;
return groupId === null ? rest : { ...rest, group: groupId };
});
}
export function upsertGroup(file: AnnotationFile, group: GroupAnnotation): AnnotationFile {
const groups = [...(file.groups ?? [])];
const index = groups.findIndex((candidate) => candidate.id === group.id);
if (index >= 0) {
groups[index] = group;
} else {
groups.push(group);
}
return { ...file, groups };
}
/**
* Remove a group and every reference to it.
*
* `docsIndex` already drops a dangling groupId when rendering, so the viewer
* degrades correctly either way — but the committed file should not carry a
* reference to a group that no longer exists.
*/
export function removeGroup(file: AnnotationFile, groupId: string): AnnotationFile {
const groups = (file.groups ?? []).filter((group) => group.id !== groupId);
let next: AnnotationFile = { ...file, groups };
for (const [key, entry] of Object.entries(file.tables ?? {})) {
if (entry.group === groupId) {
next = setTableGroup(next, key, null);
}
}
return next;
}
export function setProjectNote(file: AnnotationFile, note: string): AnnotationFile {
const project = { ...file.project };
if (blank(note)) {
delete project.note;
} else {
project.note = note;
}
return { ...file, project: Object.keys(project).length > 0 ? project : undefined };
}
@@ -0,0 +1,101 @@
<script setup lang="ts">
import type { Translate } from "../docsWarnings";
import type { ColumnInfo, ColumnNote, DocsEdit } from "../types";
import NoteEditor from "./NoteEditor.vue";
const props = defineProps<{
columns: ColumnInfo[];
/** Keyed by the column's real name, exactly as the snapshot emits it. */
columnNotes: Record<string, ColumnNote>;
/** Qualified key of the table these columns belong to, for emitted edits. */
tableKey: string;
readonly: boolean;
translate: Translate;
}>();
const emit = defineEmits<{
edit: [edit: DocsEdit];
}>();
/** Rebuild the declared type from the parts the snapshot reports separately. */
function typeLabel(column: ColumnInfo): string {
if (column.character_maximum_length !== null) {
return `${column.data_type}(${column.character_maximum_length})`;
}
if (column.numeric_precision !== null) {
const scale = column.numeric_scale === null ? "" : `,${column.numeric_scale}`;
return `${column.data_type}(${column.numeric_precision}${scale})`;
}
return column.data_type;
}
function settings(column: ColumnInfo): string[] {
const parts: string[] = [];
if (column.is_primary_key) {
parts.push("pk");
}
if (!column.is_nullable) {
parts.push("not null");
}
if (column.column_default !== null) {
parts.push(`default: ${column.column_default}`);
}
if (column.extra !== null && column.extra !== "") {
parts.push(column.extra);
}
if (column.enum_values !== undefined && column.enum_values.length > 0) {
parts.push(`enum: ${column.enum_values.join(", ")}`);
}
return parts;
}
function noteOf(column: ColumnInfo): ColumnNote | null {
return props.columnNotes[column.name] ?? null;
}
/**
* The database's own comment, when a local note replaced it. Bound with
* `:title` so Vue escapes it — this is author text like any other note.
*/
function shadowedTitle(column: ColumnInfo): string | undefined {
const shadowed = noteOf(column)?.shadowed;
return shadowed ? `Database comment: ${shadowed}` : undefined;
}
</script>
<template>
<div class="overflow-hidden rounded-md border border-border">
<table class="w-full text-xs">
<thead>
<tr class="bg-muted/30">
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Column</th>
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Type</th>
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Settings</th>
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Note</th>
</tr>
</thead>
<tbody>
<tr v-for="column in columns" :key="column.name" class="border-t border-border align-top">
<td class="px-2 py-1.5 font-mono font-medium text-foreground">{{ column.name }}</td>
<td class="px-2 py-1.5 font-mono text-muted-foreground">{{ typeLabel(column) }}</td>
<td class="px-2 py-1.5">
<div class="flex flex-wrap gap-1">
<span v-for="setting in settings(column)" :key="setting" class="rounded bg-muted/50 px-1.5 py-0.5 text-[10px] text-muted-foreground">
{{ setting }}
</span>
</div>
</td>
<td class="px-2 py-1.5 text-muted-foreground">
<div class="flex items-start gap-1">
<span v-if="noteOf(column)?.source === 'LOCAL'" class="mt-0.5 shrink-0 text-[10px] font-medium" :title="shadowedTitle(column)">⬤ LOCAL</span>
<!-- Merged note, for the same reason as TablePage: NoteEditor
renders and edits one value, and the local layer alone would
hide notes that came from the database. -->
<NoteEditor class="min-w-0 flex-1" :model-value="noteOf(column)?.note ?? ''" :readonly="readonly" :translate="translate" @update:model-value="emit('edit', { kind: 'columnNote', tableKey, column: column.name, note: $event })" />
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
@@ -0,0 +1,94 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { searchDocs, type SearchHit } from "../docsSearch";
import type { SchemaSnapshot } from "../types";
const props = defineProps<{
snapshot: SchemaSnapshot;
}>();
const emit = defineEmits<{
select: [tableKey: string];
selectEnum: [enumName: string];
}>();
const open = ref(false);
const query = ref("");
const input = ref<HTMLInputElement | null>(null);
// searchDocs caps its own results, per kind. Slicing again here would just
// re-create the bug where columns crowd out every other kind.
const hits = computed(() => searchDocs(props.snapshot, query.value));
async function show(): Promise<void> {
open.value = true;
query.value = "";
await nextTick();
input.value?.focus();
}
function onKeydown(event: KeyboardEvent): void {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
if (open.value) {
open.value = false;
} else {
void show();
}
return;
}
if (event.key === "Escape" && open.value) {
open.value = false;
}
}
/** Enums navigate by name, everything else by table key; groups have neither. */
function isNavigable(hit: SearchHit): boolean {
return hit.kind === "enum" || hit.tableKey !== null;
}
function choose(hit: SearchHit): void {
// Enums navigate by name — they have no table key, and EnumPage resolves them
// by bare name for the same reason columnsUsingEnum does.
if (hit.kind === "enum") {
emit("selectEnum", hit.label);
open.value = false;
return;
}
// Groups still have no page of their own, so they stay unclickable rather
// than navigating somewhere arbitrary.
if (hit.tableKey === null) {
return;
}
emit("select", hit.tableKey);
open.value = false;
}
onMounted(() => window.addEventListener("keydown", onKeydown));
onBeforeUnmount(() => window.removeEventListener("keydown", onKeydown));
</script>
<template>
<div>
<button type="button" class="flex items-center gap-2 rounded border border-border bg-background px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40" @click="show()">
<span>Search</span>
<span class="rounded bg-muted/50 px-1 py-0.5 text-[10px]">⌘K</span>
</button>
<div v-if="open" class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-24" @click.self="open = false">
<div class="w-full max-w-lg overflow-hidden rounded-md border border-border bg-background shadow-lg">
<input ref="input" v-model="query" type="text" placeholder="Search tables, columns, groups, enums…" class="w-full border-b border-border bg-transparent px-3 py-2 text-sm text-foreground outline-none" />
<ul class="max-h-80 overflow-y-auto">
<li v-if="query.trim() !== '' && hits.length === 0" class="px-3 py-4 text-center text-xs text-muted-foreground">Nothing matches “{{ query }}”.</li>
<li v-for="(hit, position) in hits" :key="`${hit.kind}-${hit.context}-${hit.label}-${position}`">
<button type="button" class="flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-xs transition-colors" :class="isNavigable(hit) ? 'hover:bg-muted/40' : 'cursor-default text-muted-foreground'" :disabled="!isNavigable(hit)" @click="choose(hit)">
<span class="w-14 shrink-0 text-[10px] uppercase text-muted-foreground">{{ hit.kind }}</span>
<span class="font-mono text-foreground">{{ hit.label }}</span>
<span class="truncate text-[11px] text-muted-foreground">{{ hit.context }}</span>
</button>
</li>
</ul>
</div>
</div>
</div>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import type { IndexSection } from "../docsIndex";
import { qualifiedTableKey } from "../docsKeys";
import { groupStyle } from "../groupColor";
defineProps<{
sections: IndexSection[];
mode: "schema" | "group";
/** Qualified name of the table currently open, or null on the index. */
activeKey: string | null;
}>();
const emit = defineEmits<{
"update:mode": ["schema" | "group"];
select: [tableKey: string];
home: [];
}>();
</script>
<template>
<nav class="flex w-64 shrink-0 flex-col gap-3 overflow-y-auto border-r border-border bg-background p-3">
<button type="button" class="rounded px-2 py-1 text-left text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/40" @click="emit('home')">Overview</button>
<div class="flex flex-col gap-1">
<span class="px-2 text-[10px] uppercase tracking-wide text-muted-foreground">Group by</span>
<div class="flex rounded border border-border p-0.5">
<button type="button" class="flex-1 rounded px-2 py-1 text-xs transition-colors" :class="mode === 'schema' ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/40'" @click="emit('update:mode', 'schema')">Schemas</button>
<button type="button" class="flex-1 rounded px-2 py-1 text-xs transition-colors" :class="mode === 'group' ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/40'" @click="emit('update:mode', 'group')">Table Groups</button>
</div>
</div>
<div v-for="section in sections" :key="section.key" class="flex flex-col gap-0.5">
<div class="flex items-center gap-1.5 px-2 py-1" :class="{ 'docs-group': section.hue !== null }" :style="groupStyle(section.hue)">
<span v-if="section.hue !== null" class="h-2 w-2 shrink-0 rounded-full" style="background-color: var(--group-c)"></span>
<span class="truncate text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
{{ section.label || "(no schema)" }}
</span>
</div>
<button
v-for="table in section.tables"
:key="qualifiedTableKey(table)"
type="button"
class="truncate rounded px-2 py-1 text-left font-mono text-xs transition-colors"
:class="activeKey === qualifiedTableKey(table) ? 'bg-muted text-foreground' : 'text-muted-foreground hover:bg-muted/40'"
@click="emit('select', qualifiedTableKey(table))"
>
{{ table.name }}
</button>
</div>
</nav>
</template>
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { computed } from "vue";
import { columnsUsingEnum } from "../docsIndex";
import type { Translate } from "../docsWarnings";
import type { DocEnum, SchemaSnapshot } from "../types";
import NoteEditor from "./NoteEditor.vue";
const props = defineProps<{
enumType: DocEnum;
/** Every table in the snapshot; usedBy filters them down to enum columns. */
snapshot: SchemaSnapshot;
translate: Translate;
}>();
const emit = defineEmits<{
select: [tableKey: string];
}>();
const qualifiedName = computed(() => (props.enumType.schema ? `${props.enumType.schema}.${props.enumType.name}` : props.enumType.name));
// No annotation storage exists for enum notes yet (AnnotationFile has no
// `enums` key), so this is always read-only — there is nowhere to save an
// edit to.
const usedBy = computed(() => columnsUsingEnum(props.snapshot, props.enumType.name));
</script>
<template>
<article class="flex flex-col gap-5">
<header class="flex flex-col gap-2">
<div class="flex flex-wrap items-center gap-2">
<h2 class="font-mono text-lg font-semibold text-foreground">{{ qualifiedName }}</h2>
<span v-if="enumType.synthesized" class="rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground">synthesized</span>
</div>
<NoteEditor :model-value="enumType.note ?? ''" readonly :translate="translate" />
</header>
<section>
<h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{{ translate("docs.enumValues") }}</h3>
<ul class="flex flex-wrap gap-1">
<li v-for="value in enumType.values" :key="value" class="rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground">{{ value }}</li>
</ul>
</section>
<section>
<h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{{ translate("docs.usedBy") }}</h3>
<p v-if="usedBy.length === 0" class="text-xs text-muted-foreground">No column uses this enum.</p>
<ul v-else class="flex flex-col gap-1">
<li v-for="hit in usedBy" :key="`${hit.tableKey}.${hit.column}`" class="text-xs">
<button type="button" class="w-full rounded border border-border bg-background px-2 py-1.5 text-left font-mono transition-colors hover:bg-muted/40" @click="emit('select', hit.tableKey)">{{ hit.tableKey }}.{{ hit.column }}</button>
</li>
</ul>
</section>
</article>
</template>
@@ -0,0 +1,96 @@
<script setup lang="ts">
import type { Translate } from "../docsWarnings";
import { groupStyle } from "../groupColor";
import type { GroupAnnotation } from "../types";
const props = defineProps<{
group: GroupAnnotation;
translate: Translate;
}>();
const emit = defineEmits<{
"update:group": [group: GroupAnnotation];
delete: [groupId: string];
}>();
/**
* Twelve evenly spaced hues.
*
* Presets are hues, not colours: docs.css fixes lightness and chroma per
* theme, so any point on the wheel is legible on both grounds and an even
* split cannot produce a bad preset.
*/
const PRESET_HUES = Array.from({ length: 12 }, (_, step) => step * 30);
function rename(event: Event): void {
emit("update:group", { ...props.group, name: (event.target as HTMLInputElement).value });
}
function recolour(hue: number): void {
emit("update:group", { ...props.group, hue });
}
function slide(event: Event): void {
recolour(Number((event.target as HTMLInputElement).value));
}
/**
* No per-hue i18n key exists and adding one means eight locale files, so the
* tooltip pairs the "Colour" label with the raw hue.
*/
function swatchTitle(hue: number): string {
return `${props.translate("docs.groupColour")} ${hue}°`;
}
</script>
<template>
<div class="flex flex-col gap-3">
<label class="flex flex-col gap-1">
<span class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ translate("docs.groupName") }}</span>
<input type="text" :value="group.name" :placeholder="translate('docs.groupName')" class="rounded border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus:border-ring" @input="rename($event)" />
</label>
<div class="flex flex-col gap-2">
<span class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ translate("docs.groupColour") }}</span>
<!-- `docs-group` and the hue go on the SAME element: the class brings in
the theme's lightness and chroma, groupStyle only supplies --h. A
hex fill here could not stay legible on both grounds. -->
<div class="flex items-center gap-1.5">
<button
v-for="hue in PRESET_HUES"
:key="hue"
type="button"
class="docs-group h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105"
:class="group.hue === hue ? 'ring-2 ring-ring ring-offset-2' : 'border-border'"
style="background-color: var(--group-c)"
:style="groupStyle(hue)"
:title="swatchTitle(hue)"
@click="recolour(hue)"
></button>
</div>
<input type="range" min="0" max="359" :value="group.hue" class="w-full" :title="swatchTitle(group.hue)" @input="slide($event)" />
<!-- Both grounds at once: the reader picks one hue and it has to work in
either theme, so neither can be left to imagination. `docs-ground-light`
and `dark` pin each half to a theme regardless of the app's own. -->
<div class="grid grid-cols-2 gap-2">
<div class="docs-ground-light flex items-center gap-2 overflow-hidden rounded border border-border bg-white p-2">
<span class="docs-group h-4 w-4 shrink-0 rounded-full" style="background-color: var(--group-c)" :style="groupStyle(group.hue)"></span>
<span class="docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium" style="background-color: var(--group-tint); color: var(--group-c)" :style="groupStyle(group.hue)">{{ group.name }}</span>
</div>
<div class="dark flex items-center gap-2 overflow-hidden rounded border border-border bg-neutral-900 p-2">
<span class="docs-group h-4 w-4 shrink-0 rounded-full" style="background-color: var(--group-c)" :style="groupStyle(group.hue)"></span>
<span class="docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium" style="background-color: var(--group-tint); color: var(--group-c)" :style="groupStyle(group.hue)">{{ group.name }}</span>
</div>
</div>
</div>
<div class="flex justify-end">
<button type="button" class="rounded border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40" @click="emit('delete', group.id)">
{{ translate("docs.deleteGroup") }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { computed } from "vue";
import type { Translate } from "../docsWarnings";
import { groupStyle } from "../groupColor";
import type { GroupAnnotation } from "../types";
const props = defineProps<{
groups: GroupAnnotation[];
/** Id of the selected group, or null when the table belongs to none. */
modelValue: string | null;
translate: Translate;
}>();
const emit = defineEmits<{
"update:modelValue": [groupId: string | null];
create: [];
}>();
/**
* Value of the "New group…" option. Group ids come from a hand-editable notes
* file, so this is treated as the sentinel only when no real group claims it —
* otherwise picking that group would silently open a create flow instead.
*/
const CREATE = "__dbx_new_group__";
const selected = computed(() => props.groups.find((group) => group.id === props.modelValue) ?? null);
function choose(event: Event): void {
const select = event.target as HTMLSelectElement;
if (select.value === CREATE && !props.groups.some((group) => group.id === CREATE)) {
// "New group…" is an action, not a selection: park the select back on the
// current group so it does not display a group that does not exist.
select.value = props.modelValue ?? "";
emit("create");
return;
}
emit("update:modelValue", select.value === "" ? null : select.value);
}
</script>
<template>
<div class="flex items-center gap-1.5">
<span v-if="selected" class="docs-group h-3 w-3 shrink-0 rounded-full" style="background-color: var(--group-c)" :style="groupStyle(selected.hue)"></span>
<select :value="modelValue ?? ''" class="rounded border border-border bg-background px-2 py-1 text-xs text-foreground outline-none focus:border-ring" @change="choose($event)">
<option value="">{{ translate("docs.noGroup") }}</option>
<option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }}</option>
<option :value="CREATE">{{ translate("docs.newGroup") }}</option>
</select>
</div>
</template>
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { nextTick, ref } from "vue";
import type { Translate } from "../docsWarnings";
import { renderNote } from "../renderNote";
const props = defineProps<{
/** Raw markdown. Displayed through renderNote, edited as its source. */
modelValue: string;
/**
* Part 3c renders this same component inside the standalone HTML export,
* where nothing can be saved. Read-only means the note never turns into a
* textarea — not a disabled one, none at all.
*/
readonly: boolean;
translate: Translate;
}>();
const emit = defineEmits<{
"update:modelValue": [note: string];
}>();
const editing = ref(false);
const draft = ref("");
const input = ref<HTMLTextAreaElement | null>(null);
async function begin(): Promise<void> {
if (props.readonly) {
return;
}
draft.value = props.modelValue;
editing.value = true;
await nextTick();
input.value?.focus();
}
function commit(): void {
editing.value = false;
// The parent owns the value. Emitting an unchanged note would dirty the
// annotation file for a click that edited nothing.
if (draft.value !== props.modelValue) {
emit("update:modelValue", draft.value);
}
}
/** Escape abandons the draft; the stored note stays the source of truth. */
function cancel(): void {
draft.value = props.modelValue;
editing.value = false;
}
</script>
<template>
<div class="text-sm text-muted-foreground">
<textarea v-if="editing" ref="input" v-model="draft" rows="4" class="w-full resize-y rounded border border-border bg-background p-2 font-mono text-xs text-foreground outline-none focus:border-ring" @blur="commit()" @keydown.escape="cancel()"></textarea>
<!-- renderNote is the sanitiser: a note can be a database COMMENT ON value
the reader never wrote, so its markdown is rendered here and its HTML
is escaped there. Binding the raw note would hand that comment to the
DOM verbatim. -->
<div v-else-if="modelValue.trim() !== ''" class="leading-relaxed" :class="readonly ? '' : 'cursor-text rounded transition-colors hover:bg-muted/30'" :title="readonly ? undefined : translate('docs.editNote')" @click="begin()" v-html="renderNote(modelValue)"></div>
<button v-else-if="!readonly" type="button" class="rounded border border-dashed border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40" @click="begin()">
{{ translate("docs.addNote") }}
</button>
</div>
</template>
@@ -0,0 +1,86 @@
<script setup lang="ts">
import { computed } from "vue";
import { qualifiedTableKey } from "../docsKeys";
import type { FieldRef, Relationship } from "../types";
const props = defineProps<{
/** Every relationship in the snapshot; filtered here on the current table. */
relationships: Relationship[];
schema: string | null;
table: string;
}>();
const emit = defineEmits<{
select: [tableKey: string];
}>();
function isCurrent(field: FieldRef): boolean {
return field.table === props.table && (field.schema ?? null) === props.schema;
}
// FieldRef names its table property `table`, not `name`, so it is remapped
// rather than passed to qualifiedTableKey directly.
function keyOf(field: FieldRef): string {
return qualifiedTableKey({ schema: field.schema, name: field.table });
}
function label(field: FieldRef): string {
return `${keyOf(field)}.${field.column}`;
}
function notation(relationship: Relationship): string {
return relationship.cardinality === "ONE_TO_ONE" ? "1 – 1" : "* – 1";
}
function actions(relationship: Relationship): string[] {
const parts: string[] = [];
if (relationship.onUpdate) {
parts.push(`on update ${relationship.onUpdate}`);
}
if (relationship.onDelete) {
parts.push(`on delete ${relationship.onDelete}`);
}
return parts;
}
const outgoing = computed(() => props.relationships.filter((relationship) => isCurrent(relationship.from)));
const incoming = computed(() => props.relationships.filter((relationship) => isCurrent(relationship.to)));
</script>
<template>
<div class="grid gap-4 sm:grid-cols-2">
<section>
<h4 class="mb-1.5 text-xs font-medium text-muted-foreground">References ({{ outgoing.length }})</h4>
<p v-if="outgoing.length === 0" class="text-xs text-muted-foreground">This table references no other table.</p>
<ul v-else class="flex flex-col gap-1">
<li v-for="relationship in outgoing" :key="relationship.id" class="text-xs">
<button type="button" class="w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40" @click="emit('select', keyOf(relationship.to))">
<span class="font-mono">{{ relationship.from.column }}</span>
<span class="mx-1.5 text-muted-foreground">{{ notation(relationship) }}</span>
<span class="font-mono">{{ label(relationship.to) }}</span>
<span v-if="actions(relationship).length > 0" class="ml-1.5 text-[10px] text-muted-foreground">
{{ actions(relationship).join(", ") }}
</span>
</button>
</li>
</ul>
</section>
<section>
<h4 class="mb-1.5 text-xs font-medium text-muted-foreground">Referenced by ({{ incoming.length }})</h4>
<p v-if="incoming.length === 0" class="text-xs text-muted-foreground">No table references this one.</p>
<ul v-else class="flex flex-col gap-1">
<li v-for="relationship in incoming" :key="relationship.id" class="text-xs">
<button type="button" class="w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40" @click="emit('select', keyOf(relationship.from))">
<span class="font-mono">{{ label(relationship.from) }}</span>
<span class="mx-1.5 text-muted-foreground">{{ notation(relationship) }}</span>
<span class="font-mono">{{ relationship.to.column }}</span>
<span v-if="actions(relationship).length > 0" class="ml-1.5 text-[10px] text-muted-foreground">
{{ actions(relationship).join(", ") }}
</span>
</button>
</li>
</ul>
</section>
</div>
</template>
@@ -0,0 +1,112 @@
<script setup lang="ts">
import { computed } from "vue";
import type { Translate } from "../docsWarnings";
import { qualifiedTableKey } from "../docsKeys";
import { groupStyle } from "../groupColor";
import type { DocsEdit, DocTable, GroupAnnotation, Relationship, TableGroup } from "../types";
import ColumnTable from "./ColumnTable.vue";
import GroupPicker from "./GroupPicker.vue";
import NoteEditor from "./NoteEditor.vue";
import RelationshipList from "./RelationshipList.vue";
const props = defineProps<{
table: DocTable;
/** Every relationship in the snapshot; RelationshipList filters them. */
relationships: Relationship[];
/** The table's group, or null when it belongs to none. */
group: TableGroup | null;
/** The editable group records, which `group` above cannot be written back to. */
annotationGroups: GroupAnnotation[];
readonly: boolean;
translate: Translate;
}>();
const emit = defineEmits<{
select: [tableKey: string];
edit: [edit: DocsEdit];
createGroup: [tableKey: string];
}>();
const qualified = computed(() => qualifiedTableKey(props.table));
const kindLabel = computed(() => props.table.kind.toLowerCase().replace(/_/g, " "));
/**
* The database comment a local note replaced. Bound with `:title` so Vue
* escapes it — it is author text, exactly like the note itself.
*/
const shadowedTitle = computed(() => (props.table.shadowedNote ? `Database comment: ${props.table.shadowedNote}` : undefined));
</script>
<template>
<article class="flex flex-col gap-5">
<header class="flex flex-col gap-2">
<div class="flex flex-wrap items-center gap-2">
<h2 class="font-mono text-lg font-semibold text-foreground">{{ qualified }}</h2>
<span class="rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground">{{ kindLabel }}</span>
<span v-if="group" class="docs-group rounded px-1.5 py-0.5 text-[10px] font-medium" style="background-color: var(--group-tint); color: var(--group-c)" :style="groupStyle(group.hue)">
{{ group.name }}
</span>
<span v-if="table.estimatedRows !== null" class="text-[10px] text-muted-foreground"> ~{{ table.estimatedRows }} rows </span>
</div>
<!-- NoteEditor is fed the MERGED note, not the local one. It renders and
edits a single value, so seeding it from the annotation file would
show nothing for a note that came from a database comment. Writing
one shadows that comment, which is what noteSource and shadowedNote
below exist to disclose. -->
<div class="flex items-start gap-2">
<span v-if="table.noteSource === 'LOCAL'" class="mt-0.5 shrink-0 text-[10px] font-medium text-muted-foreground" :title="shadowedTitle">⬤ LOCAL</span>
<NoteEditor class="min-w-0 flex-1" :model-value="table.note ?? ''" :readonly="readonly" :translate="translate" @update:model-value="emit('edit', { kind: 'tableNote', tableKey: qualified, note: $event })" />
</div>
<GroupPicker v-if="!readonly" :groups="annotationGroups" :model-value="table.groupId" :translate="translate" @update:model-value="emit('edit', { kind: 'tableGroup', tableKey: qualified, groupId: $event })" @create="emit('createGroup', qualified)" />
</header>
<section>
<h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Columns</h3>
<ColumnTable :columns="table.columns" :column-notes="table.columnNotes" :table-key="qualified" :readonly="readonly" :translate="translate" @edit="emit('edit', $event)" />
</section>
<section v-if="table.indexes.length > 0">
<h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Indexes</h3>
<div class="overflow-hidden rounded-md border border-border">
<table class="w-full text-xs">
<thead>
<tr class="bg-muted/30">
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Name</th>
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Columns</th>
<th class="px-2 py-1.5 text-left font-medium text-muted-foreground">Settings</th>
</tr>
</thead>
<tbody>
<tr v-for="index in table.indexes" :key="index.name" class="border-t border-border align-top">
<td class="px-2 py-1.5 font-mono">{{ index.name }}</td>
<td class="px-2 py-1.5 font-mono text-muted-foreground">
{{ index.columns.join(", ") }}<template v-if="index.included_columns && index.included_columns.length > 0"> (include {{ index.included_columns.join(", ") }}) </template>
</td>
<td class="px-2 py-1.5">
<div class="flex flex-wrap gap-1 text-[10px] text-muted-foreground">
<span v-if="index.is_primary" class="rounded bg-muted/50 px-1.5 py-0.5">pk</span>
<span v-if="index.is_unique" class="rounded bg-muted/50 px-1.5 py-0.5">unique</span>
<span v-if="index.index_type" class="rounded bg-muted/50 px-1.5 py-0.5">{{ index.index_type }}</span>
<span v-if="index.filter" class="rounded bg-muted/50 px-1.5 py-0.5">where {{ index.filter }}</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<section>
<h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Relationships</h3>
<RelationshipList :relationships="relationships" :schema="table.schema" :table="table.name" @select="emit('select', $event)" />
</section>
<section v-if="table.viewDefinition">
<h3 class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Definition</h3>
<pre class="overflow-x-auto rounded-md border border-border bg-muted/20 p-2 font-mono text-xs">{{ table.viewDefinition }}</pre>
</section>
</article>
</template>
@@ -0,0 +1,27 @@
<script setup lang="ts">
import { computed } from "vue";
import { describeWarning, type Translate } from "../docsWarnings";
import type { SnapshotWarning } from "../types";
const props = defineProps<{
warnings: SnapshotWarning[];
translate: Translate;
}>();
// Keyed by index: two warnings of the same kind can carry identical text.
const notices = computed(() => props.warnings.map((warning, index) => ({ key: `${warning.kind}-${index}`, ...describeWarning(warning, props.translate) })));
</script>
<template>
<div v-if="notices.length > 0" class="flex flex-col gap-2">
<div
v-for="notice in notices"
:key="notice.key"
class="rounded-md border px-3 py-2 text-xs"
:class="notice.severity === 'warning' ? 'border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200' : 'border-border bg-muted/30 text-muted-foreground'"
>
<div class="font-medium">{{ notice.title }}</div>
<div class="mt-0.5 leading-relaxed">{{ notice.detail }}</div>
</div>
</div>
</template>
@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { IndexSection } from "../docsIndex";
import { qualifiedTableKey } from "../docsKeys";
import { groupStyle } from "../groupColor";
import { renderNote } from "../renderNote";
defineProps<{
sections: IndexSection[];
}>();
const emit = defineEmits<{
select: [tableKey: string];
}>();
</script>
<template>
<div class="flex flex-col gap-6">
<section v-for="section in sections" :key="section.key" class="flex flex-col gap-2">
<div class="flex flex-col gap-1 border-l-2 pl-3" :class="{ 'docs-group': section.hue !== null }" style="border-color: var(--group-c, var(--border))" :style="groupStyle(section.hue)">
<div class="flex items-baseline gap-2">
<h2 class="text-sm font-semibold text-foreground">{{ section.label || "(no schema)" }}</h2>
<span class="text-xs text-muted-foreground">{{ section.tables.length }} tables</span>
</div>
<div v-if="section.note" class="text-xs text-muted-foreground" v-html="renderNote(section.note)"></div>
</div>
<ul class="grid gap-1 sm:grid-cols-2 lg:grid-cols-3">
<!-- The note renders author markdown, so it can contain an <a>. Inside
the <button> that would be invalid nesting and the link would not
be keyboard reachable, so the note is a sibling of the button and
the <li> carries the card. -->
<li v-for="table in section.tables" :key="qualifiedTableKey(table)" class="flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 transition-colors hover:bg-muted/40">
<button type="button" class="flex w-full items-baseline gap-1.5 text-left" @click="emit('select', qualifiedTableKey(table))">
<span class="font-mono text-xs font-medium text-foreground">{{ table.name }}</span>
<span v-if="table.kind !== 'TABLE'" class="text-[10px] uppercase text-muted-foreground">
{{ table.kind.toLowerCase().replace(/_/g, " ") }}
</span>
</button>
<div v-if="table.note" class="line-clamp-2 text-[11px] text-muted-foreground" v-html="renderNote(table.note)"></div>
</li>
</ul>
</section>
</div>
</template>
+42
View File
@@ -0,0 +1,42 @@
/* Group colour. A group stores one number (the hue); lightness and chroma are
* fixed here per theme, so no hue can produce an illegible swatch.
*
* Base values use hsl() because DBX supports WebViews without oklch — the same
* bare `--h` number works in both functions. The oklch values below are the
* enhancement, matching how globals.css defines its own tokens. */
.docs-group {
--group-c: hsl(var(--h, 220), 55%, 38%);
--group-tint: hsl(var(--h, 220), 55%, 94%);
}
.dark .docs-group {
--group-c: hsl(var(--h, 220), 50%, 72%);
--group-tint: hsl(var(--h, 220), 30%, 18%);
}
/* GroupEditor previews a hue on a light and a dark ground side by side. The
* dark half just carries `.dark`, which works in either theme; the light half
* needs this, because in dark mode `.dark .docs-group` would otherwise paint
* dark-theme values onto a white ground and the preview would lie. Same
* specificity as the rule above and declared after it, so it wins. */
.docs-ground-light .docs-group {
--group-c: hsl(var(--h, 220), 55%, 38%);
--group-tint: hsl(var(--h, 220), 55%, 94%);
}
@supports (color: oklch(1 0 0)) {
.docs-group {
--group-c: oklch(0.55 0.15 var(--h, 220));
--group-tint: oklch(0.96 0.03 var(--h, 220));
}
.dark .docs-group {
--group-c: oklch(0.76 0.13 var(--h, 220));
--group-tint: oklch(0.28 0.05 var(--h, 220));
}
.docs-ground-light .docs-group {
--group-c: oklch(0.55 0.15 var(--h, 220));
--group-tint: oklch(0.96 0.03 var(--h, 220));
}
}
+88
View File
@@ -0,0 +1,88 @@
import { qualifiedTableKey } from "./docsKeys";
import type { DocTable, SchemaSnapshot } from "./types";
export interface IndexSection {
/** Schema name, group id, or "" for the ungrouped bucket. */
key: string;
label: string;
/** Group hue, or null for schema sections and the ungrouped bucket. */
hue: number | null;
note: string | null;
tables: DocTable[];
}
function byName(a: DocTable, b: DocTable): number {
return a.name.localeCompare(b.name);
}
export function groupBySchema(snapshot: SchemaSnapshot): IndexSection[] {
const sections = new Map<string, DocTable[]>();
for (const table of snapshot.tables) {
const key = table.schema ?? "";
const bucket = sections.get(key);
if (bucket) {
bucket.push(table);
} else {
sections.set(key, [table]);
}
}
return [...sections.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, tables]) => ({
key,
label: key,
hue: null,
note: null,
tables: [...tables].sort(byName),
}));
}
export function groupByTableGroup(snapshot: SchemaSnapshot): IndexSection[] {
const known = new Map(snapshot.groups.map((group) => [group.id, group]));
const sections: IndexSection[] = [];
// Snapshot order is the notes file's order — the user's own arrangement.
for (const group of snapshot.groups) {
const tables = snapshot.tables.filter((table) => table.groupId === group.id).sort(byName);
// An empty group renders nothing, matching render_group in the serializer.
if (tables.length === 0) {
continue;
}
sections.push({
key: group.id,
label: group.name,
hue: group.hue,
note: group.note,
tables,
});
}
// A groupId naming no known group is treated as ungrouped rather than
// creating a phantom section.
const ungrouped = snapshot.tables.filter((table) => table.groupId === null || !known.has(table.groupId)).sort(byName);
if (ungrouped.length > 0) {
sections.push({ key: "", label: "(no group)", hue: null, note: null, tables: ungrouped });
}
return sections;
}
/**
* Every column whose declared type is this enum.
*
* Exact match on `data_type`, never a substring: an enum named `state` would
* otherwise claim every column of type `statement`.
*/
export function columnsUsingEnum(snapshot: SchemaSnapshot, enumName: string): Array<{ tableKey: string; table: string; column: string }> {
const hits: Array<{ tableKey: string; table: string; column: string }> = [];
for (const table of snapshot.tables) {
for (const column of table.columns) {
if (column.data_type === enumName) {
hits.push({ tableKey: qualifiedTableKey(table), table: table.name, column: column.name });
}
}
}
return hits;
}
+17
View File
@@ -0,0 +1,17 @@
import type { DocTable } from "./types";
/**
* The key that identifies a table across the viewer — `schema.name`, or the
* bare name on schema-less engines like SQLite and MySQL.
*
* This rule was copied into four places before it lived here. It is the key
* that annotations are stored under, so two call sites disagreeing would
* attach a note to the wrong table.
*
* Typed as `Pick<DocTable, "schema" | "name">` rather than the full `DocTable`
* so callers that only have a schema/name pair on hand — a relationship's
* `FieldRef`, remapped — can use it too without an unsafe cast.
*/
export function qualifiedTableKey(table: Pick<DocTable, "schema" | "name">): string {
return table.schema ? `${table.schema}.${table.name}` : table.name;
}
+66
View File
@@ -0,0 +1,66 @@
import { qualifiedTableKey } from "./docsKeys";
import type { SchemaSnapshot } from "./types";
export interface SearchHit {
kind: "table" | "column" | "group" | "enum";
label: string;
/** Where the hit lives — a qualified table name, or a count for groups. */
context: string;
/** Qualified table name for navigation, or null for groups and enums. */
tableKey: string | null;
}
/** Per-kind result caps. A single overall cap lets columns — by far the most
* numerous kind — crowd groups and enums out of the list entirely. */
const LIMITS = { table: 20, column: 20, group: 10, enum: 10 } as const;
/**
* Case-insensitive substring search over the whole snapshot.
*
* Tables rank first: someone typing a table's name almost always wants the
* table, not a column that happens to share the word.
*
* Results are capped per kind — see LIMITS. This is the only place results are
* limited; callers render everything they are handed.
*/
export function searchDocs(snapshot: SchemaSnapshot, query: string): SearchHit[] {
const needle = query.trim().toLowerCase();
if (needle.length === 0) {
return [];
}
const tables: SearchHit[] = [];
const columns: SearchHit[] = [];
for (const table of snapshot.tables) {
const key = qualifiedTableKey(table);
if (table.name.toLowerCase().includes(needle)) {
tables.push({ kind: "table", label: table.name, context: key, tableKey: key });
}
for (const column of table.columns) {
if (column.name.toLowerCase().includes(needle)) {
columns.push({ kind: "column", label: column.name, context: key, tableKey: key });
}
}
}
const groups: SearchHit[] = snapshot.groups
.filter((group) => group.name.toLowerCase().includes(needle))
.map((group) => ({
kind: "group",
label: group.name,
context: `${snapshot.tables.filter((table) => table.groupId === group.id).length} tables`,
tableKey: null,
}));
const enums: SearchHit[] = snapshot.enums
.filter((value) => value.name.toLowerCase().includes(needle))
.map((value) => ({
kind: "enum",
label: value.name,
context: `${value.values.length} values`,
tableKey: null,
}));
return [...tables.slice(0, LIMITS.table), ...columns.slice(0, LIMITS.column), ...groups.slice(0, LIMITS.group), ...enums.slice(0, LIMITS.enum)];
}
+60
View File
@@ -0,0 +1,60 @@
import type { SnapshotWarning } from "./types";
export interface WarningNotice {
severity: "info" | "warning";
title: string;
detail: string;
}
/**
* A `useI18n().t`-shaped function, passed in rather than imported directly.
*
* `useI18n()` throws without a provided Vue instance — exactly the standalone
* HTML export case (Part 3c), which bootstraps no Vue app around this module.
* Taking the translator as a parameter keeps this file a pure module the
* export can call with an English identity function, and is why `src/docs/`
* must never import vue-i18n directly.
*/
export type Translate = (key: string, params?: Record<string, string | number>) => string;
/**
* Turn a snapshot warning into something a reader can act on.
*
* This is where "degrade visibly, never silently" becomes literal: if a table
* could not be read, or an engine cannot report relationships, the reader has
* to learn that from the page rather than infer it from an absence.
*/
export function describeWarning(warning: SnapshotWarning, translate: Translate): WarningNotice {
switch (warning.kind) {
case "tableSkipped":
return {
severity: "warning",
title: translate("docs.warnings.tableSkipped.title"),
detail: translate("docs.warnings.tableSkipped.detail", { table: warning.table, reason: warning.reason }),
};
case "noForeignKeyMetadata":
return {
severity: "info",
title: translate("docs.warnings.noForeignKeyMetadata.title"),
detail: translate("docs.warnings.noForeignKeyMetadata.detail", { engine: warning.engine }),
};
case "commentsUnsupported":
return {
severity: "info",
title: translate("docs.warnings.commentsUnsupported.title"),
detail: translate("docs.warnings.commentsUnsupported.detail", { engine: warning.engine }),
};
case "orphanedNotes":
return {
severity: "warning",
title: translate("docs.warnings.orphanedNotes.title"),
detail: translate("docs.warnings.orphanedNotes.detail", { count: warning.count }),
};
case "dbmlOmitted":
return {
severity: "info",
title: translate("docs.warnings.dbmlOmitted.title"),
detail: translate("docs.warnings.dbmlOmitted.detail", { item: warning.item, table: warning.table, reason: warning.reason }),
};
}
}
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
/**
* Inline style exposing a table group's hue to CSS.
*
* A group stores ONE number. Lightness and chroma are fixed per theme in the
* stylesheet — `--group-c: oklch(0.55 0.15 var(--h))` in light,
* `oklch(0.76 0.13 var(--h))` in dark — so every hue is legible on both
* grounds by construction. Computing a colour here would throw that away.
*/
export function groupStyle(hue: number | null): Record<string, string> {
if (hue === null) {
return {};
}
const wrapped = ((Math.trunc(hue) % 360) + 360) % 360;
return { "--h": String(wrapped) };
}
+78
View File
@@ -0,0 +1,78 @@
import { Marked } from "marked";
/** Escape the five characters that can break out of text or an attribute value. */
function escapeHtml(value: unknown): string {
return (
String(value ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
// Single quotes too, so the escaper is self-sufficient. Every attribute
// here is double-quoted today, which makes this redundant — but that is a
// formatting convention enforced nowhere, and the day someone writes
// title='...' it becomes the difference between escaping and a breakout.
.replace(/'/g, "&#39;")
);
}
/**
* URL allowlist. Blocklists lose: `javascript:` alone misses `JaVaScRiPt:`,
* the entity-encoded `&#106;avascript:`, `vbscript:` and `data:text/html`.
* Permitting only what we understand is both shorter and complete.
*/
const SAFE_SCHEME = /^(https?:|mailto:)/i;
function safeUrl(raw: unknown): string | null {
const url = String(raw ?? "").trim();
if (url === "") {
return null;
}
// Protocol-relative. Harmless over https, but the Part 3b standalone export
// is opened via file://, where //host/path is a UNC path — on Windows that
// opens an SMB connection and leaks an NTLM hash, and images need no click.
// Both separators must be rejected: the URL spec treats /\ exactly like //.
if (/^[/\\]{2}/.test(url)) {
return null;
}
if (url.startsWith("#") || url.startsWith("/") || url.startsWith("./") || url.startsWith("../")) {
return url;
}
return SAFE_SCHEME.test(url) ? url : null;
}
const renderer = new Marked({
renderer: {
// Raw HTML in the source is shown as text, never rendered.
html({ text }) {
return escapeHtml(text);
},
link({ href, title, tokens }) {
// `tokens`, not `text` — `text` is the raw markdown source, so returning
// it would emit author HTML unescaped and swallow inline formatting.
const inner = this.parser.parseInline(tokens);
const safe = safeUrl(href);
if (safe === null) {
return inner;
}
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
return `<a href="${escapeHtml(safe)}"${titleAttr}>${inner}</a>`;
},
image({ href, title, text }) {
const safe = safeUrl(href);
if (safe === null) {
return escapeHtml(text);
}
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
return `<img src="${escapeHtml(safe)}" alt="${escapeHtml(text)}"${titleAttr}>`;
},
},
});
/** Render a note's markdown to HTML with all author-supplied HTML escaped. */
export function renderNote(markdown: string | null): string {
if (markdown === null || markdown.trim() === "") {
return "";
}
return renderer.parse(markdown) as string;
}
+210
View File
@@ -0,0 +1,210 @@
// Mirrors crates/dbx-core/src/docs/snapshot.rs. There is no Rust->TS codegen
// in this repo, so this file is maintained by hand — see
// __tests__/fixtureConformance.spec.ts, which validates it against a snapshot
// generated by the real Rust code and fails if the two drift apart.
export type TableKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW";
export type NoteSource = "DATABASE" | "LOCAL" | "NONE";
export type Cardinality = "ONE_TO_ONE" | "MANY_TO_ONE";
export interface ColumnInfo {
name: string;
data_type: string;
is_nullable: boolean;
column_default: string | null;
is_primary_key: boolean;
extra: string | null;
// No skip_serializing_if in Rust — these keys are ALWAYS present, so they
// are required and may be null. Marking them optional would let `undefined`
// reach code that checks `=== null`.
comment: string | null;
numeric_precision: number | null;
numeric_scale: number | null;
character_maximum_length: number | null;
// These three DO carry skip_serializing_if, so the key is absent rather
// than null when there is no value.
enum_values?: string[];
character_set?: string;
collation?: string;
}
export interface IndexInfo {
name: string;
columns: string[];
is_unique: boolean;
is_primary: boolean;
// No skip_serializing_if on any of these in Rust — required, may be null.
filter: string | null;
index_type: string | null;
included_columns: string[] | null;
comment: string | null;
}
export interface ForeignKeyInfo {
name: string;
column: string;
ref_schema?: string | null;
ref_table: string;
ref_column: string;
on_update?: string | null;
on_delete?: string | null;
}
export interface ProjectMeta {
name: string;
databaseType: string;
database: string | null;
schemas: string[];
generatedAt: string;
note: string | null;
}
export interface ColumnNote {
note: string;
source: NoteSource;
shadowed: string | null;
}
export interface DocTable {
schema: string | null;
name: string;
kind: TableKind;
columns: ColumnInfo[];
indexes: IndexInfo[];
foreignKeys: ForeignKeyInfo[];
groupId: string | null;
note: string | null;
noteSource: NoteSource;
shadowedNote: string | null;
columnNotes: Record<string, ColumnNote>;
estimatedRows: number | null;
viewDefinition: string | null;
}
export interface TableGroup {
id: string;
name: string;
/** 0-359. Lightness and chroma are theme-controlled in CSS. */
hue: number;
note: string | null;
}
export interface FieldRef {
schema: string | null;
table: string;
column: string;
}
export interface Relationship {
id: string;
name: string | null;
from: FieldRef;
to: FieldRef;
cardinality: Cardinality;
onUpdate: string | null;
onDelete: string | null;
}
export interface DocEnum {
schema: string | null;
name: string;
values: string[];
note: string | null;
synthesized: boolean;
}
/**
* Internally tagged on a camelCase `kind`. Note this differs from
* TableKind/NoteSource/Cardinality, which are SCREAMING_SNAKE — the Rust enum
* carries both `tag = "kind"` and `rename_all = "camelCase"`.
*/
export type SnapshotWarning =
| { kind: "tableSkipped"; table: string; reason: string }
| { kind: "noForeignKeyMetadata"; engine: string }
| { kind: "commentsUnsupported"; engine: string }
| { kind: "orphanedNotes"; count: number }
| { kind: "dbmlOmitted"; table: string; item: string; reason: string };
export interface SchemaSnapshot {
formatVersion: number;
project: ProjectMeta;
tables: DocTable[];
relationships: Relationship[];
groups: TableGroup[];
enums: DocEnum[];
warnings: SnapshotWarning[];
}
/** Mirrors `dbx_core::docs::annotations::ColumnAnnotation`. */
export interface ColumnAnnotation {
note: string;
}
/** Mirrors `TableAnnotation`. Absent keys are omitted, never sent as null. */
export interface TableAnnotation {
group?: string;
note?: string;
columns?: Record<string, ColumnAnnotation>;
}
/** Mirrors `GroupAnnotation`. `hue` is 0–359; lightness and chroma are the theme's. */
export interface GroupAnnotation {
id: string;
name: string;
hue: number;
note?: string;
}
/** Mirrors `ProjectAnnotation`. */
export interface ProjectAnnotation {
name?: string;
note?: string;
}
/**
* The on-disk notes file. Rust declares `deny_unknown_fields`, so adding a
* property here without adding it in Rust makes every save fail.
*/
export interface AnnotationFile {
formatVersion: number;
project?: ProjectAnnotation;
groups?: GroupAnnotation[];
tables?: Record<string, TableAnnotation>;
}
/**
* What the viewer asks its host to do. The viewer never persists anything —
* that is what keeps `src/docs/` free of backend calls and bundleable into a
* standalone HTML file.
*/
export type DocsEdit =
| { kind: "projectNote"; note: string }
| { kind: "tableNote"; tableKey: string; note: string }
| { kind: "columnNote"; tableKey: string; column: string; note: string }
| { kind: "tableGroup"; tableKey: string; groupId: string | null }
| { kind: "upsertGroup"; group: GroupAnnotation }
| { kind: "removeGroup"; groupId: string };
/**
* Runtime witnesses for the interfaces above.
*
* TypeScript types are erased at runtime, so a test cannot enumerate an
* interface's keys. `Record<keyof T, true>` gives a value that IS enumerable
* and that `vue-tsc` checks against the interface: add a field and this object
* is missing a key; remove one and it carries an excess property. Either way
* the build fails here rather than at a user's save.
*
* These live in this file, not in the spec, because `tsconfig.json` excludes
* `src/**\/__tests__/**` from `vue-tsc` — witnesses in a spec file would be
* checked by nothing.
*/
export const COLUMN_ANNOTATION_KEYS: Record<keyof ColumnAnnotation, true> = { note: true };
export const TABLE_ANNOTATION_KEYS: Record<keyof TableAnnotation, true> = { group: true, note: true, columns: true };
export const GROUP_ANNOTATION_KEYS: Record<keyof GroupAnnotation, true> = { id: true, name: true, hue: true, note: true };
export const PROJECT_ANNOTATION_KEYS: Record<keyof ProjectAnnotation, true> = { name: true, note: true };
export const ANNOTATION_FILE_KEYS: Record<keyof AnnotationFile, true> = {
formatVersion: true,
project: true,
groups: true,
tables: true,
};