Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions apps/web/src/components/docs/SidebarList.astro
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,12 @@ const { items } = Astro.props;

<style>
/*
These rules live here (not in DocsSidebar.astro) on purpose: Astro
scopes styles per-file, so a <style> block in the parent never
reaches elements rendered by this child component. That mismatch
was why the sidebar rendered with raw browser defaults.
These rules live here, not in DocsSidebar.astro: Astro scopes styles per
file, so a parent's <style> never reaches elements rendered by this child.

--docs-link-padding / --docs-link-nested-indent let an ancestor
(e.g. the mobile dropdown wrapper in DocsSidebar.astro) override
spacing for its variant, since CSS custom properties inherit
through the real DOM regardless of Astro's scoping.
--docs-link-padding / --docs-link-nested-indent let an ancestor (the mobile
dropdown wrapper in DocsSidebar.astro) override spacing, since custom
properties inherit through the DOM regardless of Astro's scoping.
*/
ul {
margin: 0;
Expand Down
5 changes: 1 addition & 4 deletions apps/web/src/components/landing/CommandsSection.astro
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ function parse(line: string): { kind: Kind; text: string } {
</script>

<style>
/* ---------- Layout ----------
Phones and no-JS: a plain list. Each row is followed by its terminal.
/* Phones and no-JS: a plain list, each row followed by its terminal.
Wide screens with JS: rows on the left, one sticky terminal on the right. */
.cmdx {
display: grid;
Expand Down Expand Up @@ -174,7 +173,6 @@ function parse(line: string): { kind: Kind; text: string } {
display: none;
}

/* ---------- Rows ---------- */
.cmdx__group {
margin: 1.75rem 0 0.4rem;
padding-inline: 1rem;
Expand Down Expand Up @@ -287,7 +285,6 @@ function parse(line: string): { kind: Kind; text: string } {
margin: 0.25rem 0 0.75rem;
}

/* ---------- Terminal ---------- */
.cx {
display: flex;
flex-direction: column;
Expand Down
1 change: 0 additions & 1 deletion apps/web/src/components/landing/HeroSection.astro
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ const log: Array<{ text: string; tone?: "ok" | "dim" | "hot" }> = [
}
}

/* Terminal card */
.hero__stage {
min-width: 0;
}
Expand Down
13 changes: 4 additions & 9 deletions apps/web/src/scripts/copy-command.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
const FEEDBACK_MS = 2000;

/**
* Copy text to the clipboard with a legacy fallback for non-secure contexts
* (clipboard API requires HTTPS or localhost).
*/
/** Falls back to `execCommand` where the clipboard API is unavailable (it needs HTTPS or localhost). */
export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
Expand All @@ -22,11 +19,9 @@ export async function copyText(text: string): Promise<boolean> {
}

/**
* Wire a copy-to-clipboard CTA. On success the button flips to a "copied"
* state (styled via `[data-copied]`, e.g. icon copy → check, accent color)
* and announces "Copied!" through aria-label, then reverts. The command text
* is read from the element itself, so it works regardless of any
* typewriter/typing animation on the same node.
* On success the button gets `[data-copied]` (styles swap the copy icon for a
* check) and announces "Copied!" through aria-label, then reverts. The command
* is read from the element's text, so a typing animation on the node does not matter.
*/
export function initCopyCommand(button: HTMLElement, commandEl: HTMLElement): void {
const command = commandEl.textContent?.trim() ?? "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,7 @@ function parseRelationDeclarations(text: string): RelationDeclaration[] {
return declarations;
}

// ---------------------------------------------------------------------------
// Source scanning: just enough JS lexing to find balanced brackets and split on
// commas without being fooled by strings or comments.
// ---------------------------------------------------------------------------
// Minimal JS lexing below: balanced brackets and top-level commas, ignoring strings and comments.

function stripComments(source: string): string {
let out = "";
Expand Down
64 changes: 15 additions & 49 deletions packages/cli/src/analyzers/analysis/extractors/fallbackExtractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,7 @@ import { isDynamicSegment, isOperationalSegment, LARGE_API_ROUTE_COUNT } from ".
import type { RouteInfo } from "../../detectors/index.js";
import type { EntityInfo, IRouteFallbackExtractor } from "./types.js";

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/**
* Segments yang sering muncul di URL tapi bukan entity name.
* Difilter biar gak muncul sebagai entity hint.
*/
/** URL segments that are common but never entity names. */
const ROUTE_NON_ENTITY_SEGMENTS = new Set([
"api", "v1", "v2", "v3",
"public", "internal", "private",
Expand All @@ -19,10 +12,7 @@ const ROUTE_NON_ENTITY_SEGMENTS = new Set([
"me", "self",
]);

/**
* Kata irregular yang singularization-nya tidak bisa di-derive dari suffix rules.
* Key = lowercase plural, value = singular yang benar.
*/
/** Words whose singular cannot be derived from suffix rules. Key is the lowercase plural form. */
const IRREGULAR_SINGULAR = new Map([
["media", "media"],
["data", "data"],
Expand All @@ -48,21 +38,10 @@ const IRREGULAR_SINGULAR = new Map([

const SINGULAR_ENDS_IN_S_PLURAL = /(?:status|bus|alias|campus|bonus|virus|canvas|bias|atlas)es$/;

// ---------------------------------------------------------------------------
// Extractor
// ---------------------------------------------------------------------------

/**
* RouteFallbackExtractor — derive entity names dari URL segments sebagai
* best-effort fallback kalau tidak ada schema source yang ditemukan.
*
* Confidence: low — hanya dapat names, zero field/relation data.
* Tapi tetap berguna buat capabilityDetector dan domain inference.
*
* Contoh:
* /api/snippets → "Snippet"
* /api/workspaces/[id] → "Workspace"
* /api/collections → "Collection"
* Derives entity names from API route segments when no schema source exists
* (`/api/snippets` gives "Snippet"). Low confidence: names only, no fields or relations, but
* capabilityDetector and domain inference still use them.
*/
export class RouteFallbackExtractor implements IRouteFallbackExtractor {
readonly name = "route-fallback";
Expand All @@ -77,20 +56,19 @@ export class RouteFallbackExtractor implements IRouteFallbackExtractor {
const writes = (route.methods ?? []).some((method) => method !== "GET" && method !== "HEAD" && method !== "QUERY");

for (const segment of segments) {
// Skip dynamic segments: [id], [slug], [...catchall], :id
// Dynamic segments: [id], [slug], [...catchall], :id
if (isDynamicSegment(segment)) {
prevWasDynamic = true;
continue;
}
// Segments immediately after a dynamic parameter are sub-resources
// (e.g. /api/workspaces/[id]/members → "members" is a sub-resource of "workspaces")
// A segment right after a dynamic parameter is a sub-resource (`/api/workspaces/[id]/members`),
// which is skipped so it does not become its own entity.
if (prevWasDynamic) {
prevWasDynamic = false;
continue;
}
// Skip short segments: "v1", "id", dll
// Short segments such as "v1" and "id".
if (segment.length <= 2) continue;
// Skip common non-entity prefixes
if (ROUTE_NON_ENTITY_SEGMENTS.has(segment.toLowerCase())) continue;
if (isOperationalSegment(segment)) continue;

Expand Down Expand Up @@ -124,24 +102,14 @@ export function resourceEntityName(segment: string): string {
return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
}

// ---------------------------------------------------------------------------
// Singularization
// ---------------------------------------------------------------------------

/**
* singularize — simple English singularization untuk route segments.
* Cukup buat common REST conventions, bukan full NLP.
*
* "snippets" → "Snippet"
* "categories" → "Category"
* "replies" → "Reply"
* "workspaces" → "Workspace"
* "media" → "Media" (irregular, tidak diubah)
* Singularizes a route segment and capitalizes it ("categories" gives "Category", "media" stays
* "Media"). Covers common REST naming only, not English in general.
*/
export function singularize(word: string): string {
const lower = word.toLowerCase();

// Irregular — cek duluan sebelum suffix rules
// Irregulars first: suffix rules would mangle them.
if (IRREGULAR_SINGULAR.has(lower)) {
return capitalize(IRREGULAR_SINGULAR.get(lower) ?? lower);
}
Expand All @@ -158,17 +126,15 @@ export function singularize(word: string): string {
if (lower.endsWith("ies")) {
return capitalize(lower.slice(0, -3) + "y");
}
// "addresses" → "address", "churches" → "church", "boxes" → "box"
// (stem itself ends in a hard consonant cluster that takes "-es")
// "addresses", "churches", "boxes": the stem ends in a sound that takes "-es".
if (lower.endsWith("sses") || lower.endsWith("xes") || lower.endsWith("ches") || lower.endsWith("shes")) {
return capitalize(lower.slice(0, -2));
}
// "verses" → "verse", "houses" → "house", "cases" → "case", "responses" → "response"
// (singular already ends in a silent "e" before the "s" — plural just adds "s", not "es")
// "verses", "houses", "responses": the singular ends in a silent "e" and the plural adds only "s".
if (lower.endsWith("ses")) {
return capitalize(lower.slice(0, -1));
}
// "workspaces", "snippets", "collections" — trailing -s yang umum
// Plain trailing "s"; "ss" words ("class") are left alone.
if (lower.endsWith("s") && !lower.endsWith("ss")) {
return capitalize(lower.slice(0, -1));
}
Expand Down
66 changes: 12 additions & 54 deletions packages/cli/src/analyzers/analysis/extractors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,11 @@ import { DrizzleExtractor } from "./drizzleExtractor.js";
import { SQLExtractor } from "./sqlExtractor.js";
import { RouteFallbackExtractor } from "./fallbackExtractor.js";

// ---------------------------------------------------------------------------
// Extractor registry
// ---------------------------------------------------------------------------

/**
* EXTRACTORS — ordered fallback chain, diiterasi dari atas ke bawah.
*
* Tambah source baru = append extractor baru ke sini, tanpa ubah logic apapun.
* Orchestrator stop di extractor pertama yang canHandle() = true DAN extract() non-empty.
*
* Order penting: lebih reliable = lebih atas.
* 1. Prisma — high confidence, full field + relation data
* 2. Drizzle — fields + foreign-key relations from `pgTable`/`mysqlTable`/`sqliteTable`
* 3. [future] TypeORM → import { TypeORMExtractor } from "./typeormExtractor.js"
* 4. [future] Mongoose → import { MongooseExtractor } from "./mongooseExtractor.js"
* 5. SQL — raw pg/mysql2/better-sqlite3, table names as pseudo-entities
* (no field/relation data — lowest confidence of the schema sources,
* stays last so any ORM extractor above gets first refusal)
* Fallback chain, tried top to bottom; the first extractor with `canHandle()` true and a
* non-empty `extract()` wins. Order is by reliability, most reliable first:
* Prisma (fields and relations), Drizzle (fields and foreign keys), then SQL (table names only),
* which stays last so any ORM extractor gets first refusal. New sources slot in above SQL.
*/
const EXTRACTORS: IEntityExtractor[] = [
new PrismaExtractor(),
Expand All @@ -35,26 +22,15 @@ const EXTRACTORS: IEntityExtractor[] = [

const ROUTE_FALLBACK = new RouteFallbackExtractor();

// ---------------------------------------------------------------------------
// Main entry
// ---------------------------------------------------------------------------

/**
* extractEntities — scan files dan build entity graph.
*
* Fallback chain:
* 1. Iterate EXTRACTORS — stop di hasil pertama yang non-empty
* 2. Kalau semua kosong dan ada routes → route-hint fallback
* 3. Kalau routes juga kosong → return empty graph
*
* Relation graph di-build dari entity fields setelah semua entities terkumpul.
* Dedup entity dilakukan di sini (bukan di extractor) untuk handle Prisma multi-file schema.
* Runs the EXTRACTORS chain, then falls back to route-derived entity names, then to an empty graph.
* Entities are deduplicated here rather than in the extractors because a Prisma multi-file
* schema can define a model twice.
*/
export function extractEntities(
files: ScannedFile[],
routes: RouteInfo[] = []
): EntityGraph {
// --- Schema-based sources ---
for (const extractor of EXTRACTORS) {
if (!extractor.canHandle(files)) continue;

Expand All @@ -72,7 +48,7 @@ export function extractEntities(
};
}

// --- Route fallback: aktif kalau semua schema source kosong ---
// Only reached when every schema source came back empty.
if (routes.length > 0) {
const entities = ROUTE_FALLBACK.extract(routes);
if (entities.length > 0) {
Expand All @@ -88,19 +64,9 @@ export function extractEntities(
return { entities: [], relations: [], entityNames: [], source: "empty" };
}

// ---------------------------------------------------------------------------
// Relation graph builder
// ---------------------------------------------------------------------------

/**
* buildRelationGraph — derive semua relasi dari field isRelation = true.
*
* Rules:
* A.b B[] = one-to-many (A has many B)
* A.b B = one-to-one
* A.b B[] + B.a A[] = many-to-many
*
* Duplicate guard: many-to-many A↔B hanya disimpan sekali.
* Derives relations from relation fields: `B[]` is one-to-many, `B` is one-to-one, and `B[]`
* on both sides is many-to-many (stored once per pair).
*/
function buildRelationGraph(entities: EntityInfo[]): RelationInfo[] {
const relations: RelationInfo[] = [];
Expand All @@ -123,7 +89,7 @@ function buildRelationGraph(entities: EntityInfo[]): RelationInfo[] {
kind = "one-to-one";
}

// Skip duplicate many-to-many (B→A sudah masuk waktu proses A→B)
// The B→A side of a many-to-many was already added while processing A→B.
const isDuplicate = relations.some(
(r) =>
r.kind === "many-to-many" &&
Expand All @@ -140,15 +106,7 @@ function buildRelationGraph(entities: EntityInfo[]): RelationInfo[] {
return relations;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/**
* deduplicateEntities — filter duplicate entity names.
* Penting buat Prisma multi-file schema dimana model bisa didefinisi di file terpisah.
* First-seen wins.
*/
/** First definition of a name wins. */
function deduplicateEntities(entities: EntityInfo[]): EntityInfo[] {
const seen = new Set<string>();
return entities.filter((e) => {
Expand Down
Loading
Loading