@marktiderman/genesis-cli 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from 'module';
2
+ import { studioSetupSql } from '@marktiderman/genesis-studio-server';
3
+
1
4
  // src/scaffolder.ts
2
5
  var VALID_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
3
6
  var NOOP_LOGGER = {
@@ -342,6 +345,640 @@ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}
342
345
  `;
343
346
  }
344
347
 
345
- export { planScaffold, runScaffold, validateConsumerName };
348
+ // src/introspect/comments.ts
349
+ var MARKER = "@genesis";
350
+ var TABLE_KEYS = ["label", "labelField", "description"];
351
+ var FIELD_KEYS = ["label", "description", "widget"];
352
+ var CommentSettingsError = class extends Error {
353
+ };
354
+ function parse(comment, keys, where) {
355
+ if (!comment) return {};
356
+ const at = comment.indexOf(MARKER);
357
+ if (at < 0) return { description: comment.trim() || void 0 };
358
+ const description = comment.slice(0, at).trim() || void 0;
359
+ const raw = comment.slice(at + MARKER.length).trim();
360
+ let value;
361
+ try {
362
+ value = JSON.parse(raw);
363
+ } catch {
364
+ throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
365
+ }
366
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
367
+ throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
368
+ }
369
+ const settings = {};
370
+ for (const [key, v] of Object.entries(value)) {
371
+ if (!keys.includes(key)) {
372
+ throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key}". Allowed: ${keys.join(", ")}.`);
373
+ }
374
+ if (typeof v !== "string") throw new CommentSettingsError(`${where}: ${MARKER} "${key}" must be a string.`);
375
+ settings[key] = v;
376
+ }
377
+ return { ...description ? { description } : {}, ...Object.keys(settings).length ? { settings } : {} };
378
+ }
379
+ function parseTableComment(comment, table) {
380
+ return parse(comment, TABLE_KEYS, table);
381
+ }
382
+ function parseColumnComment(comment, column) {
383
+ return parse(comment, FIELD_KEYS, column);
384
+ }
385
+
386
+ // src/introspect/model.ts
387
+ function storageTypeOf(dbType) {
388
+ const t = dbType.toLowerCase().replace(/\[\]$/, "");
389
+ if (/^(smallint|integer|bigint|int2|int4|int8|real|double precision|float4|float8|numeric|decimal|money)\b/.test(t)) {
390
+ return "number";
391
+ }
392
+ if (t === "boolean" || t === "bool") return "boolean";
393
+ if (/^(date|timestamp|timestamptz|time|timetz|interval)\b/.test(t)) return "datetime";
394
+ if (t === "json" || t === "jsonb") return "json";
395
+ return "string";
396
+ }
397
+
398
+ // src/introspect/postgres.ts
399
+ async function introspectPostgres(sql, schemas) {
400
+ const columns = await sql`
401
+ select n.nspname as schema, c.relname as table,
402
+ obj_description(c.oid, 'pg_class') as table_comment,
403
+ a.attname as column,
404
+ format_type(a.atttypid, a.atttypmod) as db_type,
405
+ t.typcategory = 'A' as is_array,
406
+ a.attnotnull as not_null,
407
+ (a.atthasdef or a.attidentity <> '') as has_default,
408
+ (a.attgenerated <> '' or a.attidentity <> '') as generated,
409
+ (select array_agg(e.enumlabel::text order by e.enumsortorder)
410
+ from pg_enum e
411
+ where e.enumtypid = case when t.typcategory = 'A' then t.typelem else t.oid end) as enum_values,
412
+ col_description(c.oid, a.attnum) as column_comment
413
+ from pg_class c
414
+ join pg_namespace n on n.oid = c.relnamespace
415
+ join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
416
+ join pg_type t on t.oid = a.atttypid
417
+ where c.relkind in ('r', 'p', 'v', 'm', 'f')
418
+ and n.nspname = any(${schemas})
419
+ order by n.nspname, c.relname, a.attnum`;
420
+ const keys = await sql`
421
+ select n.nspname as schema, c.relname as table,
422
+ array_agg(a.attname::text order by k.ord) as columns
423
+ from pg_constraint con
424
+ join pg_class c on c.oid = con.conrelid
425
+ join pg_namespace n on n.oid = c.relnamespace
426
+ cross join lateral unnest(con.conkey) with ordinality as k(attnum, ord)
427
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = k.attnum
428
+ where con.contype = 'p' and n.nspname = any(${schemas})
429
+ group by n.nspname, c.relname`;
430
+ const links = await sql`
431
+ select n.nspname as schema, c.relname as table, a.attname as column,
432
+ rn.nspname as ref_schema, rc.relname as ref_table, ra.attname as ref_column
433
+ from pg_constraint con
434
+ join pg_class c on c.oid = con.conrelid
435
+ join pg_namespace n on n.oid = c.relnamespace
436
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
437
+ join pg_class rc on rc.oid = con.confrelid
438
+ join pg_namespace rn on rn.oid = rc.relnamespace
439
+ join pg_attribute ra on ra.attrelid = rc.oid and ra.attnum = con.confkey[1]
440
+ where con.contype = 'f' and array_length(con.conkey, 1) = 1
441
+ and n.nspname = any(${schemas})`;
442
+ const keyOf = new Map(keys.map((k) => [`${k.schema}.${k.table}`, k.columns]));
443
+ const linkOf = new Map(links.map((l) => [`${l.schema}.${l.table}.${l.column}`, l]));
444
+ const tables = /* @__PURE__ */ new Map();
445
+ for (const row of columns) {
446
+ const name = `${row.schema}.${row.table}`;
447
+ let table = tables.get(name);
448
+ if (!table) {
449
+ const comment2 = parseTableComment(row.table_comment, name);
450
+ table = {
451
+ name,
452
+ schema: row.schema,
453
+ table: row.table,
454
+ key: keyOf.get(name) ?? [],
455
+ columns: [],
456
+ ...comment2.description ? { description: comment2.description } : {},
457
+ ...comment2.settings ? { settings: comment2.settings } : {}
458
+ };
459
+ tables.set(name, table);
460
+ }
461
+ const comment = parseColumnComment(row.column_comment, `${name}.${row.column}`);
462
+ const link = linkOf.get(`${name}.${row.column}`);
463
+ table.columns.push({
464
+ name: row.column,
465
+ dbType: row.db_type,
466
+ type: storageTypeOf(row.db_type),
467
+ array: row.is_array,
468
+ nullable: !row.not_null,
469
+ hasDefault: row.has_default,
470
+ generated: row.generated,
471
+ ...row.enum_values ? { enumValues: row.enum_values } : {},
472
+ ...link ? { references: { resource: `${link.ref_schema}.${link.ref_table}`, field: link.ref_column } } : {},
473
+ ...comment.description ? { description: comment.description } : {},
474
+ ...comment.settings ? { settings: comment.settings } : {}
475
+ });
476
+ }
477
+ return [...tables.values()];
478
+ }
479
+
480
+ // src/introspect/openapi.ts
481
+ var PK = /<pk\/>/;
482
+ var FK = /<fk table='([^']+)' column='([^']+)'\/>/;
483
+ var NOTES = /\s*Note:\s*This is a (?:Primary|Foreign) Key[^<]*<(?:pk|fk)[^>]*\/>/g;
484
+ function clean(description) {
485
+ if (!description) return void 0;
486
+ return description.replace(NOTES, "").trim() || void 0;
487
+ }
488
+ function introspectOpenApi(doc, schema = "public") {
489
+ const definitions = doc.definitions ?? doc.components?.schemas;
490
+ if (!definitions) throw new Error("This OpenAPI document has no definitions. Is it a PostgREST (Supabase /rest/v1/) spec?");
491
+ return Object.keys(definitions).sort().map((tableName) => {
492
+ const def = definitions[tableName];
493
+ const name = `${schema}.${tableName}`;
494
+ const required = new Set(def.required ?? []);
495
+ const key = [];
496
+ const columns = Object.entries(def.properties ?? {}).map(([column, prop]) => {
497
+ if (PK.test(prop.description ?? "")) key.push(column);
498
+ const fk = FK.exec(prop.description ?? "");
499
+ const isArray = prop.type === "array";
500
+ const format = (isArray ? prop.items?.format : prop.format) ?? prop.type ?? "text";
501
+ const dbType = isArray ? `${format}[]` : format;
502
+ const comment2 = parseColumnComment(clean(prop.description), `${name}.${column}`);
503
+ return {
504
+ name: column,
505
+ dbType,
506
+ type: storageTypeOf(format),
507
+ array: isArray,
508
+ // PostgREST lists NOT NULL columns without a default as required;
509
+ // the rest may be null or are filled by the database.
510
+ nullable: !required.has(column),
511
+ hasDefault: prop.default !== void 0,
512
+ generated: false,
513
+ ...prop.enum ? { enumValues: prop.enum.map(String) } : {},
514
+ ...fk ? { references: { resource: `${schema}.${fk[1]}`, field: fk[2] } } : {},
515
+ ...comment2.description ? { description: comment2.description } : {},
516
+ ...comment2.settings ? { settings: comment2.settings } : {}
517
+ };
518
+ });
519
+ const comment = parseTableComment(def.description, name);
520
+ return {
521
+ name,
522
+ schema,
523
+ table: tableName,
524
+ key,
525
+ columns,
526
+ ...comment.description ? { description: comment.description } : {},
527
+ ...comment.settings ? { settings: comment.settings } : {}
528
+ };
529
+ });
530
+ }
531
+
532
+ // src/introspect/emit.ts
533
+ var TS_TYPE = {
534
+ string: "string",
535
+ number: "number",
536
+ boolean: "boolean",
537
+ // The studio handler sends dates and timestamps as Postgres text, exactly.
538
+ datetime: "string",
539
+ json: "unknown"
540
+ };
541
+ function quote(value) {
542
+ return JSON.stringify(value);
543
+ }
544
+ function propKey(name) {
545
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quote(name);
546
+ }
547
+ function typeName(table) {
548
+ const pascal = `${table.schema}_${table.table}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("");
549
+ return `${/^[0-9]/.test(pascal) ? "T" : ""}${pascal}Row`;
550
+ }
551
+ function tsType(column) {
552
+ const base = column.enumValues?.length ? column.enumValues.map(quote).join(" | ") : TS_TYPE[column.type];
553
+ const element = column.array ? base.includes("|") ? `(${base})[]` : `${base}[]` : base;
554
+ return column.nullable ? `${element} | null` : element;
555
+ }
556
+ function field(column) {
557
+ const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
558
+ if (column.array) parts.push("array: true");
559
+ if (column.nullable) parts.push("nullable: true");
560
+ if (column.nullable || column.hasDefault || column.generated) parts.push("optional: true");
561
+ if (column.hasDefault) parts.push("hasDefault: true");
562
+ if (column.generated) parts.push("generated: true");
563
+ if (column.enumValues) parts.push(`enumValues: [${column.enumValues.map(quote).join(", ")}]`);
564
+ if (column.references) {
565
+ parts.push(`references: { resource: ${quote(column.references.resource)}, field: ${quote(column.references.field)} }`);
566
+ }
567
+ const label = column.settings?.label;
568
+ const description = column.settings?.description ?? column.description;
569
+ if (label) parts.push(`label: ${quote(label)}`);
570
+ if (description) parts.push(`description: ${quote(description)}`);
571
+ if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
572
+ return ` { ${parts.join(", ")} },`;
573
+ }
574
+ function emitContracts(tables, options) {
575
+ const sorted = [...tables].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
576
+ const out = [
577
+ "// Generated by `genesis introspect` \u2014 do not edit by hand.",
578
+ `// Source: ${options.source}`,
579
+ "//",
580
+ "// Re-run `genesis introspect` after a schema change and review the diff.",
581
+ "// Labels, widgets and descriptions come from `@genesis {...}` settings in",
582
+ "// table and column comments. Pass `contracts` to createStudioHandler: it",
583
+ "// wins over discovery for presentation, while types, keys and every",
584
+ "// permission still come from the live database.",
585
+ "",
586
+ "export const contracts = {"
587
+ ];
588
+ for (const table of sorted) {
589
+ out.push(` ${quote(table.name)}: {`);
590
+ out.push(` name: ${quote(table.name)},`);
591
+ out.push(` key: ${table.key.length === 1 ? quote(table.key[0]) : `[${table.key.map(quote).join(", ")}]`},`);
592
+ if (table.settings?.label) out.push(` label: ${quote(table.settings.label)},`);
593
+ if (table.settings?.labelField) out.push(` labelField: ${quote(table.settings.labelField)},`);
594
+ const description = table.settings?.description ?? table.description;
595
+ if (description) out.push(` description: ${quote(description)},`);
596
+ out.push(" fields: [");
597
+ for (const column of table.columns) out.push(field(column));
598
+ out.push(" ],");
599
+ out.push(" },");
600
+ }
601
+ out.push("} as const;", "");
602
+ out.push("/** Every resource in this contract, `schema.table`. */");
603
+ out.push("export type GenesisResource = keyof typeof contracts;", "");
604
+ for (const table of sorted) {
605
+ out.push(`/** A row of \`${table.name}\`, as the studio handler returns it. */`);
606
+ out.push(`export interface ${typeName(table)} {`);
607
+ for (const column of table.columns) out.push(` ${propKey(column.name)}: ${tsType(column)};`);
608
+ out.push("}", "");
609
+ }
610
+ out.push("/** Row types by resource. */");
611
+ out.push("export interface GenesisRows {");
612
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${typeName(table)};`);
613
+ out.push("}", "");
614
+ return out.join("\n");
615
+ }
616
+
617
+ // src/studio/wire-route.ts
618
+ function routeTags(source) {
619
+ const tags = [];
620
+ const stack = [];
621
+ const re = /<Route\b|<\/Route>/g;
622
+ let m;
623
+ while (m = re.exec(source)) {
624
+ if (m[0] === "</Route>") {
625
+ const open = stack.pop();
626
+ if (open) open.close = m.index;
627
+ continue;
628
+ }
629
+ let i = m.index + "<Route".length;
630
+ let depth = 0;
631
+ let quote2 = null;
632
+ for (; i < source.length; i++) {
633
+ const ch = source[i];
634
+ if (quote2) {
635
+ if (ch === quote2 && source[i - 1] !== "\\") quote2 = null;
636
+ continue;
637
+ }
638
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
639
+ else if (ch === "{") depth++;
640
+ else if (ch === "}") depth--;
641
+ else if (depth === 0 && ch === ">") break;
642
+ }
643
+ const selfClosing = source[i - 1] === "/";
644
+ const tag = { start: m.index, openEnd: i + 1, selfClosing, text: source.slice(m.index, i + 1) };
645
+ tags.push(tag);
646
+ if (!selfClosing) stack.push(tag);
647
+ re.lastIndex = i + 1;
648
+ }
649
+ return tags;
650
+ }
651
+ var GUARD = /<((?:[A-Z]\w*)?(?:Admin|Staff)\w*(?:Guard|Route|Only)|RequireAdmin|RequireStaff)>/;
652
+ function wireStudioRoute(source, route, pageImportPath) {
653
+ const tags = routeTags(source);
654
+ const relative = route.replace(/^\//, "");
655
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
656
+ if (existing) {
657
+ return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
658
+ }
659
+ const layouts = tags.filter((t) => !t.selfClosing && t.close !== void 0 && /Layout|Shell/.test(t.text));
660
+ const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
661
+ if (roots.length !== 1) {
662
+ return {
663
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
664
+ };
665
+ }
666
+ const layout = roots[0];
667
+ const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
668
+ if (base && !relative.startsWith(`${base}/`)) {
669
+ return {
670
+ skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
671
+ };
672
+ }
673
+ const childPath = base ? relative.slice(base.length + 1) : relative;
674
+ const guard = GUARD.exec(source)?.[1];
675
+ const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
676
+ const before = source.slice(0, layout.close);
677
+ const lastLine = before.slice(before.lastIndexOf("\n", before.lastIndexOf("<Route")) + 1);
678
+ const indent = /^\s*/.exec(lastLine)?.[0] ?? " ";
679
+ const closeLineStart = source.lastIndexOf("\n", layout.close) + 1;
680
+ const routeLine = `${indent}<Route path="${childPath}" element={${element}} />
681
+ `;
682
+ let next = source.slice(0, closeLineStart) + routeLine + source.slice(closeLineStart);
683
+ const lazy = /const \w+ = lazy\(\(\) => import\(["'][^"']+["']\)\);?\n/g;
684
+ let lastLazy = null;
685
+ let mm;
686
+ while (mm = lazy.exec(next)) lastLazy = mm;
687
+ if (lastLazy) {
688
+ const at = lastLazy.index + lastLazy[0].length;
689
+ next = `${next.slice(0, at)}const DataStudioPage = lazy(() => import("${pageImportPath}"));
690
+ ${next.slice(at)}`;
691
+ } else {
692
+ const imports = /^import .*;\s*$/gm;
693
+ let lastImport = null;
694
+ while (mm = imports.exec(next)) lastImport = mm;
695
+ const at = lastImport ? lastImport.index + lastImport[0].length + 1 : 0;
696
+ next = `${next.slice(0, at)}import DataStudioPage from "${pageImportPath}";
697
+ ${next.slice(at)}`;
698
+ }
699
+ return { content: next, ...guard ? { guard } : {} };
700
+ }
701
+
702
+ // src/studio/init.ts
703
+ var SERVER_VERSION = createRequire(import.meta.url)("@marktiderman/genesis-studio-server/package.json").version;
704
+ var PACKAGES = [
705
+ "@marktiderman/genesis-studio",
706
+ `@marktiderman/genesis-studio-server@${SERVER_VERSION}`,
707
+ "@marktiderman/genesis-ui",
708
+ "@marktiderman/genesis-core",
709
+ // Pinned to the ranges the studio supports: an unpinned "latest" can move
710
+ // past them (@hookform/resolvers 6 is a different major).
711
+ "@tanstack/react-query@^5",
712
+ "@tanstack/react-virtual@^3.14",
713
+ "react-hook-form@^7",
714
+ "zod@^4",
715
+ "@hookform/resolvers@^5.1.0"
716
+ ];
717
+ var ROLE = /^[a-z_][a-z0-9_]{0,62}$/;
718
+ function has(facts, name) {
719
+ return Boolean(facts.packageJson.dependencies?.[name] ?? facts.packageJson.devDependencies?.[name]);
720
+ }
721
+ function detectHost(facts) {
722
+ if (has(facts, "next") && (facts.exists("app") || facts.exists("src/app"))) return "next";
723
+ if (has(facts, "@tanstack/react-start") && facts.exists("src/routes")) return "tanstack-start";
724
+ return "supabase-function";
725
+ }
726
+ var LOVABLE_CLIENT = "src/integrations/supabase/client.ts";
727
+ function planStudioInit(facts, options = {}) {
728
+ const host = options.host ?? detectHost(facts);
729
+ const route = (options.route ?? "/admin/data").replace(/\/+$/, "") || "/admin/data";
730
+ const role = options.loginRole ?? "genesis_studio_login";
731
+ if (!ROLE.test(role)) throw new Error(`"${role}" isn't a plain Postgres role name.`);
732
+ if (!/^\/[A-Za-z0-9/_-]*$/.test(route)) throw new Error(`"${route}" isn't a simple path like /admin/data.`);
733
+ const files = [];
734
+ const steps = [];
735
+ const supabaseDir = facts.exists("supabase");
736
+ const migrationPath = supabaseDir ? `supabase/migrations/${facts.timestamp}_genesis_studio.sql` : "genesis-studio.sql";
737
+ files.push({
738
+ path: migrationPath,
739
+ content: [
740
+ "-- Genesis Data Studio: its own database login, and the audit trail every edit is written to.",
741
+ "-- Generated by `genesis studio init`. Review it, then apply it like any migration. Safe to run again.",
742
+ "--",
743
+ `-- ${role} can do nothing on its own (NOINHERIT): the studio switches it to the signed-in user's`,
744
+ "-- role for each request, so row-level security applies to everything it shows or saves.",
745
+ "-- Its password is set outside this file (see the steps `genesis studio init` printed).",
746
+ "",
747
+ "do $$",
748
+ "begin",
749
+ ` if not exists (select 1 from pg_roles where rolname = '${role}') then`,
750
+ ` create role ${role} login noinherit;`,
751
+ " end if;",
752
+ "end $$;",
753
+ `grant authenticated to ${role};`,
754
+ "",
755
+ studioSetupSql({ loginRole: role })
756
+ ].join("\n")
757
+ });
758
+ const install = [...PACKAGES];
759
+ const pagePath = route.replace(/^\//, "");
760
+ if (host === "next") {
761
+ const base = facts.exists("src/app") ? "src/app" : "app";
762
+ const group = (facts.list?.(base) ?? []).filter((d) => /^\(.+\)$/.test(d) && facts.exists(`${base}/${d}/layout.tsx`));
763
+ const appDir = group.length === 1 ? `${base}/${group[0]}` : base;
764
+ const ssr = has(facts, "@supabase/ssr");
765
+ if (!ssr && !has(facts, "@supabase/supabase-js")) install.push("@supabase/supabase-js");
766
+ files.push({
767
+ path: `${appDir}/api/studio/route.ts`,
768
+ content: `// The Data Studio's server: every table, as the signed-in user. Generated by \`genesis studio init\`.
769
+ import { supabaseStudio } from "@marktiderman/genesis-studio-server";
770
+
771
+ export const runtime = "nodejs";
772
+
773
+ export const POST = supabaseStudio({
774
+ url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
775
+ database: process.env.STUDIO_DATABASE_URL!,
776
+ // Server-side details of anything that goes wrong; users only see a plain message.
777
+ onError: (error) => console.error("[genesis-studio]", error),
778
+ // Who may open the studio. The default is any signed-in user, who sees exactly what row-level
779
+ // security already lets them see. Narrow it to staff with, e.g.:
780
+ // who: (claims) => (claims.app_metadata as { role?: string } | undefined)?.role === "admin",
781
+ });
782
+ `
783
+ });
784
+ files.push({
785
+ path: `${appDir}/${pagePath}/page.tsx`,
786
+ content: `"use client";
787
+ // The Data Studio page. Generated by \`genesis studio init\`.
788
+ import { useMemo } from "react";
789
+ import { ${ssr ? "createBrowserClient" : "createClient"} } from "${ssr ? "@supabase/ssr" : "@supabase/supabase-js"}";
790
+ import { DataStudio } from "@marktiderman/genesis-studio";
791
+ import { createSupabaseStudioProvider } from "@marktiderman/genesis-studio-server/client";
792
+ import "@marktiderman/genesis-studio/standalone.css";
793
+
794
+ export default function DataStudioPage() {
795
+ const provider = useMemo(() => {
796
+ const supabase = ${ssr ? "createBrowserClient" : "createClient"}(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!);
797
+ return createSupabaseStudioProvider(supabase, { url: "/api/studio" });
798
+ }, []);
799
+ // "plain": no frame of its own, so it sits under the app's header and nav like its other pages.
800
+ return <DataStudio provider={provider} title="Data" variant="plain" />;
801
+ }
802
+ `
803
+ });
804
+ steps.push(
805
+ `Set the login's password once, in the Supabase SQL editor (never in a migration): alter role ${role} with password '<a long random password>';`,
806
+ `Add STUDIO_DATABASE_URL to .env.local and your host's settings: the session pooler string from Supabase \u2192 Connect, with the user changed to ${role}.<project-ref> and that password.`,
807
+ `Apply ${migrationPath}, then open ${route}.`
808
+ );
809
+ } else if (host === "tanstack-start") {
810
+ planTanstackStart(facts, route, files, steps, role);
811
+ } else {
812
+ const lovable = facts.read(LOVABLE_CLIENT);
813
+ files.push({
814
+ path: "supabase/functions/genesis-studio/index.ts",
815
+ content: `// The Data Studio's server, as a Supabase Edge Function: every table, as the signed-in user.
816
+ // Generated by \`genesis studio init\`. It checks each user's token itself (verify_jwt is off, so the
817
+ // browser's CORS preflight can reach it).
818
+ import { supabaseStudio } from "npm:@marktiderman/genesis-studio-server@${SERVER_VERSION}";
819
+
820
+ const handler = supabaseStudio({
821
+ url: Deno.env.get("SUPABASE_URL")!,
822
+ database: Deno.env.get("STUDIO_DATABASE_URL")!,
823
+ // The app's origins, comma-separated, e.g. "https://app.example.com,http://localhost:8080".
824
+ allowedOrigins: (Deno.env.get("STUDIO_ALLOWED_ORIGINS") ?? "").split(",").map((o) => o.trim()).filter(Boolean),
825
+ // Server-side details of anything that goes wrong (the function's logs); users only see a plain message.
826
+ onError: (error) => console.error("[genesis-studio]", error),
827
+ // Who may open the studio. The default is any signed-in user, who sees exactly what row-level
828
+ // security already lets them see. Narrow it to staff with, e.g.:
829
+ // who: (claims) => (claims.app_metadata as { role?: string } | undefined)?.role === "admin",
830
+ });
831
+
832
+ Deno.serve((request) => handler(request));
833
+ `
834
+ });
835
+ if (facts.exists("supabase/config.toml")) {
836
+ const config = facts.read("supabase/config.toml") ?? "";
837
+ if (!/\[functions\.genesis-studio\]/.test(config)) {
838
+ files.push({ path: "supabase/config.toml", append: true, content: `
839
+ [functions.genesis-studio]
840
+ verify_jwt = false
841
+ ` });
842
+ }
843
+ } else {
844
+ steps.push("Deploy the function with JWT verification off (the studio verifies tokens itself): supabase functions deploy genesis-studio --no-verify-jwt");
845
+ }
846
+ const clientImport = lovable ? `import { supabase } from "@/integrations/supabase/client";` : `import { createClient } from "@supabase/supabase-js";`;
847
+ const clientSetup = lovable ? "" : `const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY);
848
+ `;
849
+ if (!lovable && !has(facts, "@supabase/supabase-js")) install.push("@supabase/supabase-js");
850
+ const componentDir = facts.exists("src/pages") ? "src/pages" : "src";
851
+ const routerPath = ["src/App.tsx", "src/app.tsx", "src/router.tsx", "src/routes.tsx", "src/main.tsx"].find(
852
+ (p) => /<Routes\b|<Route\b/.test(facts.read(p) ?? "")
853
+ );
854
+ const wired = routerPath ? wireStudioRoute(facts.read(routerPath), route, `./${componentDir.replace(/^src\/?/, "") ? `${componentDir.replace(/^src\//, "")}/` : ""}DataStudioPage`) : { skipped: `Add <Route path="${route}" element={<DataStudioPage />} /> to your router, inside the layout your other pages use.` };
855
+ const inShell = Boolean(wired.content);
856
+ files.push({
857
+ path: `${componentDir}/DataStudioPage.tsx`,
858
+ content: `// The Data Studio page. Generated by \`genesis studio init\`: add it to your router at ${route}.
859
+ import { useMemo } from "react";
860
+ import { DataStudio } from "@marktiderman/genesis-studio";
861
+ import { createSupabaseStudioProvider } from "@marktiderman/genesis-studio-server/client";
862
+ import "@marktiderman/genesis-studio/standalone.css";
863
+ ${clientImport}
864
+
865
+ ${clientSetup}const STUDIO_URL = \`\${import.meta.env.VITE_SUPABASE_URL}/functions/v1/genesis-studio\`;
866
+
867
+ export default function DataStudioPage() {
868
+ const provider = useMemo(() => createSupabaseStudioProvider(supabase, { url: STUDIO_URL }), []);
869
+ return <DataStudio provider={provider} title="Data"${inShell ? ` variant="plain"` : ""} />;
870
+ }
871
+ `
872
+ });
873
+ if (wired.content) {
874
+ files.push({
875
+ path: routerPath,
876
+ content: wired.content,
877
+ edit: `added ${route} inside your app's layout${wired.guard ? `, behind <${wired.guard}>` : ""}`
878
+ });
879
+ } else {
880
+ steps.push(wired.skipped);
881
+ }
882
+ steps.push(
883
+ `Set the login's password once, in the Supabase SQL editor (never in a migration): alter role ${role} with password '<a long random password>';`,
884
+ `Set the function's secrets: supabase secrets set STUDIO_DATABASE_URL='<session pooler string from Supabase \u2192 Connect, user ${role}.<project-ref>>' STUDIO_ALLOWED_ORIGINS='<your app's origins>'`,
885
+ `Apply ${migrationPath}, deploy the function (supabase functions deploy genesis-studio), then open ${route}.`
886
+ );
887
+ }
888
+ return { host, files, install, steps };
889
+ }
890
+ function planTanstackStart(facts, route, files, steps, role) {
891
+ files.push({
892
+ path: "src/routes/api/studio.ts",
893
+ content: `// The Data Studio's server: every table, as the signed-in user. Generated by \`genesis studio init\`.
894
+ import { createFileRoute } from "@tanstack/react-router";
895
+
896
+ let studio: ((request: Request) => Promise<Response>) | undefined;
897
+
898
+ export const Route = createFileRoute("/api/studio")({
899
+ server: {
900
+ handlers: {
901
+ POST: async ({ request }) => {
902
+ // Loaded here, on the server only, so database code never reaches the browser bundle.
903
+ const { supabaseStudio } = await import("@marktiderman/genesis-studio-server");
904
+ studio ??= supabaseStudio({
905
+ url: process.env.SUPABASE_URL ?? process.env.VITE_SUPABASE_URL!,
906
+ database: process.env.STUDIO_DATABASE_URL!,
907
+ // Server-side details of anything that goes wrong; users only see a plain message.
908
+ onError: (error) => console.error("[genesis-studio]", error),
909
+ // Who may open the studio. The default is any signed-in user, who sees exactly what
910
+ // row-level security already lets them see. Narrow it to staff with, e.g.:
911
+ // who: (claims) => (claims.app_metadata as { role?: string } | undefined)?.role === "admin",
912
+ });
913
+ return studio(request);
914
+ },
915
+ },
916
+ },
917
+ });
918
+ `
919
+ });
920
+ const layouts = (facts.listDeep?.("src/routes") ?? []).filter((p) => p.endsWith("/route.tsx")).map((p) => ({ dir: p.slice(0, -"/route.tsx".length), text: facts.read(p) ?? "" })).filter((r) => /AppShell|Layout|Sidebar/.test(r.text) && !/\$/.test(r.dir));
921
+ const rank = (r) => (/AppShell/.test(r.text) ? 0 : 1) * 1e3 + r.dir.split("/").length;
922
+ const shellDirs = layouts.sort((a, b) => rank(a) - rank(b)).map((r) => r.dir);
923
+ const dir = shellDirs[0] ?? "src/routes";
924
+ const segments = route.replace(/^\//, "").split("/");
925
+ const named = segments.map((segment, i) => {
926
+ const prefix = segments.slice(0, i + 1).join(".");
927
+ const parent = i < segments.length - 1 && (facts.exists(`${dir}/${prefix}.tsx`) || facts.exists(`${dir}/${prefix}/route.tsx`));
928
+ return parent ? `${segment}_` : segment;
929
+ });
930
+ const id = `${dir.replace(/^src\/routes/, "")}/${named.join("/")}`.replace(/\/+/g, "/");
931
+ const file = `${dir}/${named.join(".")}.tsx`;
932
+ const lovable = facts.exists(LOVABLE_CLIENT);
933
+ const tailwind4 = /@import\s+["']tailwindcss/.test(facts.read("src/styles.css") ?? "");
934
+ files.push({
935
+ path: file,
936
+ content: `// The Data Studio page. Generated by \`genesis studio init\`. It sits inside the app's shell, so it
937
+ // gets the app's nav, header and theme.
938
+ import { useMemo } from "react";
939
+ import { createFileRoute } from "@tanstack/react-router";
940
+ import { DataStudio } from "@marktiderman/genesis-studio";
941
+ import { createSupabaseStudioProvider } from "@marktiderman/genesis-studio-server/client";
942
+ ${tailwind4 ? "" : 'import "@marktiderman/genesis-studio/standalone.css";\n'}${lovable ? 'import { supabase } from "@/integrations/supabase/client";' : 'import { createClient } from "@supabase/supabase-js";\n\nconst supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY);'}
943
+
944
+ export const Route = createFileRoute("${id}")({
945
+ ssr: false,
946
+ component: DataStudioPage,
947
+ });
948
+
949
+ function DataStudioPage() {
950
+ const provider = useMemo(() => createSupabaseStudioProvider(supabase, { url: "/api/studio" }), []);
951
+ return <DataStudio provider={provider} title="Data" variant="plain" />;
952
+ }
953
+ `
954
+ });
955
+ if (tailwind4) {
956
+ const css = facts.read("src/styles.css");
957
+ if (!css.includes("genesis-studio/dist")) {
958
+ const line = '@source "../node_modules/@marktiderman/genesis-studio/dist";';
959
+ const ui = '@source "../node_modules/@marktiderman/genesis-ui/dist";';
960
+ const at = css.search(/@source[^\n]*genesis-ui[^\n]*\n/);
961
+ const next = at >= 0 ? css.replace(/(@source[^\n]*genesis-ui[^\n]*\n)/, `$1${line}
962
+ `) : css.replace(/(@import\s+["']tailwindcss[^\n]*\n)/, `$1${ui}
963
+ ${line}
964
+ `);
965
+ if (next !== css) {
966
+ files.push({ path: "src/styles.css", content: next, edit: "Tailwind now also scans the studio's classes" });
967
+ } else {
968
+ steps.push(`Add these to the stylesheet that imports Tailwind, so it builds the studio's classes:
969
+ ${ui}
970
+ ${line}`);
971
+ }
972
+ }
973
+ }
974
+ steps.push(
975
+ `Add a link to ${route} in your app's navigation (for staff only, if that's who should see it).`,
976
+ `Set the login's password once, in the Supabase SQL editor (never in a migration): alter role ${role} with password '<a long random password>';`,
977
+ `Add STUDIO_DATABASE_URL to the server's environment: the session pooler string from Supabase \u2192 Connect, with the user changed to ${role}.<project-ref> and that password.`,
978
+ `Apply the migration, then open ${route}.`
979
+ );
980
+ }
981
+
982
+ export { CommentSettingsError, detectHost, emitContracts, introspectOpenApi, introspectPostgres, parseColumnComment, parseTableComment, planScaffold, planStudioInit, runScaffold, validateConsumerName };
346
983
  //# sourceMappingURL=index.js.map
347
984
  //# sourceMappingURL=index.js.map