monorise 2.0.0-dev.4 → 2.0.0-dev.5

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/cli/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  // cli.ts
4
4
  import "tsx";
5
- import fs5 from "fs";
6
- import path5 from "path";
5
+ import fs7 from "fs";
6
+ import path7 from "path";
7
7
  import { execSync } from "child_process";
8
8
  import chokidar from "chokidar";
9
9
 
@@ -16,22 +16,22 @@ function normalizeSqlIdentifier(name) {
16
16
  const normalized = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
17
17
  return /^[a-z_]/.test(normalized) ? normalized : `_${normalized}`;
18
18
  }
19
- function athenaType(schema, path6) {
19
+ function athenaType(schema, path8) {
20
20
  let current = schema;
21
21
  for (; ; ) {
22
- const typeName = current._def?.typeName;
23
- if (typeName === "ZodEffects") {
22
+ const typeName2 = current._def?.typeName;
23
+ if (typeName2 === "ZodEffects") {
24
24
  if (current._def?.effect?.type !== "refinement") return "json";
25
25
  if (!current._def.schema) return "json";
26
26
  current = current._def.schema;
27
27
  continue;
28
28
  }
29
- if (typeName === "ZodOptional" || typeName === "ZodNullable" || typeName === "ZodDefault" || typeName === "ZodCatch" || typeName === "ZodReadonly") {
29
+ if (typeName2 === "ZodOptional" || typeName2 === "ZodNullable" || typeName2 === "ZodDefault" || typeName2 === "ZodCatch" || typeName2 === "ZodReadonly") {
30
30
  if (!current._def?.innerType) return "json";
31
31
  current = current._def.innerType;
32
32
  continue;
33
33
  }
34
- if (typeName === "ZodBranded") {
34
+ if (typeName2 === "ZodBranded") {
35
35
  if (!current._def?.type) return "json";
36
36
  current = current._def.type;
37
37
  continue;
@@ -65,12 +65,12 @@ function athenaType(schema, path6) {
65
65
  return "json";
66
66
  }
67
67
  }
68
- function columns(schema, path6) {
68
+ function columns(schema, path8) {
69
69
  let objectSchema = schema;
70
70
  while (!objectSchema.shape && objectSchema._def?.typeName === "ZodEffects") {
71
- const innerSchema = objectSchema._def.schema;
72
- if (!innerSchema) break;
73
- objectSchema = innerSchema;
71
+ const innerSchema2 = objectSchema._def.schema;
72
+ if (!innerSchema2) break;
73
+ objectSchema = innerSchema2;
74
74
  }
75
75
  if (!objectSchema.shape) return [];
76
76
  const names = /* @__PURE__ */ new Map();
@@ -79,14 +79,14 @@ function columns(schema, path6) {
79
79
  const existing = names.get(name);
80
80
  if (existing) {
81
81
  throw new Error(
82
- `Analytics column identifier collision in ${path6}: ${existing} and ${sourceName} both normalize to ${name}.`
82
+ `Analytics column identifier collision in ${path8}: ${existing} and ${sourceName} both normalize to ${name}.`
83
83
  );
84
84
  }
85
85
  names.set(name, sourceName);
86
86
  return {
87
87
  name,
88
88
  sourceName,
89
- type: athenaType(field, `${path6}.${sourceName}`)
89
+ type: athenaType(field, `${path8}.${sourceName}`)
90
90
  };
91
91
  });
92
92
  }
@@ -270,207 +270,3626 @@ function createAnalyticsManifest(configs) {
270
270
  `Analytics mutual ${mutual.name} conflicts with ${existing}: both use the ${pair} entity pair.`
271
271
  );
272
272
  }
273
- mutualPairs.set(pair, mutual.name);
274
- addDataset(
275
- "mutual",
276
- mutual.name,
277
- mutual.mutualDataSchema,
278
- entities
279
- );
273
+ mutualPairs.set(pair, mutual.name);
274
+ addDataset(
275
+ "mutual",
276
+ mutual.name,
277
+ mutual.mutualDataSchema,
278
+ entities
279
+ );
280
+ }
281
+ }
282
+ return {
283
+ version: 2,
284
+ datasets,
285
+ unnamedMutuals: [...unnamedMutuals].sort(),
286
+ schemaFingerprint: fingerprint(datasets)
287
+ };
288
+ }
289
+
290
+ // cli.ts
291
+ import { fileURLToPath } from "url";
292
+
293
+ // commands/utils/api-key-policies.ts
294
+ import fs2 from "fs";
295
+ import { createRequire } from "module";
296
+ import path2 from "path";
297
+ import { pathToFileURL } from "url";
298
+ var require2 = createRequire(import.meta.url);
299
+ var VALIDATE_API_KEY_POLICIES = /* @__PURE__ */ Symbol.for("monorise.validateApiKeyPolicies");
300
+ function resolveApiKeysPath(projectRoot, apiKeys, configDir) {
301
+ if (!apiKeys) return void 0;
302
+ const absolutePath = path2.resolve(projectRoot, apiKeys);
303
+ if (!fs2.existsSync(absolutePath) && !fs2.existsSync(`${absolutePath}.ts`) && !fs2.existsSync(`${absolutePath}.js`)) {
304
+ throw new Error(
305
+ `API key policies file not found: '${absolutePath}'. Please ensure 'apiKeys' in monorise.config.ts points to a valid file.`
306
+ );
307
+ }
308
+ const fromConfigDir = path2.relative(configDir, absolutePath);
309
+ if (!fromConfigDir.startsWith("..") && !path2.isAbsolute(fromConfigDir)) {
310
+ throw new Error(
311
+ `API key policies file '${absolutePath}' is inside configDir '${configDir}', where every file is loaded as an entity config. Move it outside, e.g. './monorise/api-keys.ts'.`
312
+ );
313
+ }
314
+ return absolutePath;
315
+ }
316
+ function apiKeysFile(apiKeysPath) {
317
+ return ["", ".ts", ".js"].map((extension) => `${apiKeysPath}${extension}`).find((file) => fs2.existsSync(file) && fs2.statSync(file).isFile()) ?? apiKeysPath;
318
+ }
319
+ var importFresh = (file) => {
320
+ delete require2.cache[file];
321
+ return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
322
+ };
323
+ async function validateApiKeyPoliciesFile(apiKeysPath, configOutputPath) {
324
+ const { default: generatedConfig } = await importFresh(configOutputPath);
325
+ const { default: policies } = await importFresh(apiKeysFile(apiKeysPath));
326
+ const validate = policies?.[VALIDATE_API_KEY_POLICIES];
327
+ if (typeof validate !== "function") {
328
+ throw new Error(
329
+ `API key policies file at '${apiKeysPath}' must default export the result of defineApiKeyPolicies(...).`
330
+ );
331
+ }
332
+ const errors = validate(generatedConfig.EntityConfig);
333
+ if (errors.length) {
334
+ throw new Error(
335
+ `Invalid API key policies in '${apiKeysPath}':
336
+ - ${errors.join("\n - ")}`
337
+ );
338
+ }
339
+ console.log("Validated API key policies.");
340
+ return policies;
341
+ }
342
+ function routePermissionDeclarations(policies, baseModuleNames) {
343
+ const permissions = /* @__PURE__ */ new Set();
344
+ for (const policy of Object.values(policies)) {
345
+ const routes = policy?.routes;
346
+ if (Array.isArray(routes)) {
347
+ for (const permission of routes) permissions.add(permission);
348
+ }
349
+ }
350
+ if (permissions.size === 0) return "";
351
+ const members = [...permissions].sort().map((permission) => ` ${JSON.stringify(permission)}: true;`).join("\n");
352
+ return baseModuleNames.map(
353
+ (moduleName) => `
354
+ declare module '${moduleName}' {
355
+ interface ApiKeyRoutePermissions {
356
+ ${members}
357
+ }
358
+ }
359
+ `
360
+ ).join("");
361
+ }
362
+ function apiKeyPoliciesHandleParts(monoriseOutputDir, apiKeysPath) {
363
+ if (!apiKeysPath) return { importLine: "", coreFactoryArg: "config" };
364
+ const relativePath = path2.relative(monoriseOutputDir, apiKeysPath).replace(/\.(ts|js|mjs|cjs)$/, "");
365
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
366
+ return {
367
+ importLine: `import apiKeyPolicies from '${importPath}';`,
368
+ coreFactoryArg: "{ ...config, ApiKeyPolicies: apiKeyPolicies }"
369
+ };
370
+ }
371
+
372
+ // commands/utils/api-key-types.ts
373
+ var literalUnion = (names) => names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never";
374
+ function apiKeyTypeDeclarations(entities) {
375
+ const enumKeys = new Map(
376
+ entities.map((entity) => [entity.name, entity.enumKey])
377
+ );
378
+ const tagEntries = entities.map(
379
+ ({ enumKey, config }) => `[Entity.${enumKey}]: ${literalUnion((config.tags ?? []).map((tag) => tag.name))};`
380
+ );
381
+ const mutualFields = /* @__PURE__ */ new Map();
382
+ const setDirection = (from, to, fields) => {
383
+ const targets = mutualFields.get(from) ?? /* @__PURE__ */ new Map();
384
+ if (!targets.has(to)) targets.set(to, fields);
385
+ mutualFields.set(from, targets);
386
+ };
387
+ for (const pass of ["own", "reverse"]) {
388
+ for (const { name, config } of entities) {
389
+ for (const field of Object.values(config.mutual?.mutualFields ?? {})) {
390
+ const shape = field.mutual?.mutualDataSchema?.shape;
391
+ if (!shape || !enumKeys.has(field.entityType)) continue;
392
+ const fields = Object.keys(shape);
393
+ if (pass === "own") setDirection(name, field.entityType, fields);
394
+ else setDirection(field.entityType, name, fields);
395
+ }
396
+ }
397
+ }
398
+ const mutualEntries = [...mutualFields].map(
399
+ ([from, targets]) => `[Entity.${enumKeys.get(from)}]: {
400
+ ${[...targets].map(
401
+ ([to, fields]) => ` [Entity.${enumKeys.get(to)}]: ${literalUnion(fields)};`
402
+ ).join("\n")}
403
+ };`
404
+ );
405
+ return `
406
+ export interface ApiKeyEntityTags {
407
+ ${tagEntries.join("\n ")}
408
+ }
409
+
410
+ export interface ApiKeyMutualDataFields {
411
+ ${mutualEntries.join("\n ")}
412
+ }`;
413
+ }
414
+
415
+ // commands/utils/detect-package.ts
416
+ import fs3 from "fs";
417
+ import path3 from "path";
418
+ function detectCombinedPackage(startDir) {
419
+ let dir = startDir;
420
+ while (true) {
421
+ if (fs3.existsSync(path3.join(dir, "node_modules", "monorise"))) {
422
+ return true;
423
+ }
424
+ const parent = path3.dirname(dir);
425
+ if (parent === dir) break;
426
+ dir = parent;
427
+ }
428
+ return false;
429
+ }
430
+
431
+ // commands/utils/search-manifest.ts
432
+ import fs4 from "fs";
433
+ import { createRequire as createRequire2 } from "module";
434
+ import path4 from "path";
435
+ import { pathToFileURL as pathToFileURL2 } from "url";
436
+ function searchDefaultsDeclaration(defaults) {
437
+ return `const SearchDefaults = ${JSON.stringify(defaults ?? {})};`;
438
+ }
439
+ async function loadProjectBase(projectRoot) {
440
+ const name = detectCombinedPackage(projectRoot) ? "monorise/base" : "../base/index.js";
441
+ const require3 = createRequire2(path4.join(projectRoot, "package.json"));
442
+ const base = await import(pathToFileURL2(require3.resolve(name)).href);
443
+ if (typeof base.searchConfigHash !== "function") {
444
+ throw new Error(
445
+ `'search' needs a newer ${name}: this version doesn't support the search index.`
446
+ );
447
+ }
448
+ return base;
449
+ }
450
+ async function writeSearchManifest(monoriseOutputDir, projectRoot, configs, defaults) {
451
+ const manifestPath = path4.join(monoriseOutputDir, "search-manifest.json");
452
+ const indexed = configs.filter((config) => config.search);
453
+ if (!indexed.length) {
454
+ fs4.rmSync(manifestPath, { force: true });
455
+ return;
456
+ }
457
+ const base = await loadProjectBase(projectRoot);
458
+ if (defaults !== void 0) {
459
+ base.validateSearchSettings(defaults, "monorise.config.ts");
460
+ }
461
+ const manifest = {
462
+ version: 1,
463
+ entities: Object.fromEntries(
464
+ indexed.map((config) => [
465
+ config.name,
466
+ base.searchConfigHash(
467
+ base.resolveSearchConfig(config.search, defaults)
468
+ )
469
+ ])
470
+ )
471
+ };
472
+ fs4.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}
473
+ `);
474
+ }
475
+
476
+ // commands/devtool.ts
477
+ import { spawn } from "child_process";
478
+ import fs6 from "fs";
479
+ import path6 from "path";
480
+ import { pathToFileURL as pathToFileURL3 } from "url";
481
+
482
+ // commands/devtool/metadata.ts
483
+ function definition(schema) {
484
+ return schema?._def ?? schema?.def ?? {};
485
+ }
486
+ function typeName(schema) {
487
+ const def = definition(schema);
488
+ const raw = def.typeName ?? def.type ?? schema?.constructor?.name ?? "";
489
+ if (typeof raw !== "string") return "";
490
+ return raw.replace(/^Zod/, "").toLowerCase();
491
+ }
492
+ function innerSchema(schema) {
493
+ const def = definition(schema);
494
+ return def.innerType ?? def.schema ?? def.type ?? def.out ?? def.output ?? def.getter?.();
495
+ }
496
+ function unwrap(schema) {
497
+ let current = schema;
498
+ const seen = /* @__PURE__ */ new Set();
499
+ const wrappers = /* @__PURE__ */ new Set([
500
+ "optional",
501
+ "nullable",
502
+ "default",
503
+ "catch",
504
+ "branded",
505
+ "readonly",
506
+ "effects",
507
+ "transform",
508
+ "pipeline",
509
+ "pipe",
510
+ "lazy"
511
+ ]);
512
+ while (wrappers.has(typeName(current)) && !seen.has(current)) {
513
+ seen.add(current);
514
+ const inner = innerSchema(current);
515
+ if (!inner || typeof inner !== "object") break;
516
+ current = inner;
517
+ }
518
+ return current;
519
+ }
520
+ function shapeOf(schema) {
521
+ if (!schema) return {};
522
+ const unwrapped = unwrap(schema);
523
+ const def = definition(unwrapped);
524
+ const shape = def.shape ?? unwrapped.shape;
525
+ if (typeof shape === "function") return shape();
526
+ return shape && typeof shape === "object" ? shape : {};
527
+ }
528
+ function isOptional(schema) {
529
+ try {
530
+ return schema.isOptional?.() ?? typeName(schema) === "optional";
531
+ } catch {
532
+ return typeName(schema) === "optional";
533
+ }
534
+ }
535
+ function enumValues(schema) {
536
+ const unwrapped = unwrap(schema);
537
+ const def = definition(unwrapped);
538
+ if (Array.isArray(def.values)) return def.values;
539
+ if (def.entries && typeof def.entries === "object") {
540
+ return [...new Set(Object.values(def.entries))];
541
+ }
542
+ if (typeName(unwrapped) === "literal") {
543
+ const value = def.value ?? def.values?.[0];
544
+ return value === void 0 ? void 0 : [value];
545
+ }
546
+ return void 0;
547
+ }
548
+ function describeType(schema) {
549
+ const unwrapped = unwrap(schema);
550
+ const name = typeName(unwrapped);
551
+ const def = definition(unwrapped);
552
+ if (name === "array") {
553
+ const item = def.type ?? def.element;
554
+ return `${item && typeof item === "object" ? describeType(item) : "unknown"}[]`;
555
+ }
556
+ if (name === "enum" || name === "nativeenum" || name === "literal") {
557
+ return enumValues(unwrapped)?.map((value) => JSON.stringify(value)).join(" | ") ?? "enum";
558
+ }
559
+ if (name === "union" || name === "discriminatedunion") {
560
+ const options = Array.isArray(def.options) ? def.options : def.options && typeof def.options.values === "function" ? [
561
+ ...def.options.values()
562
+ ] : [];
563
+ return options.length ? options.map((option) => describeType(option)).join(" | ") : "union";
564
+ }
565
+ if (name === "record" || name === "map") return "object";
566
+ if (name === "object") return "object";
567
+ if (name === "date") return "date";
568
+ if (name === "boolean" || name === "number" || name === "bigint") return name;
569
+ if (name === "null") return "null";
570
+ if (name === "any" || name === "unknown") return "unknown";
571
+ return name || "unknown";
572
+ }
573
+ function stringExample(fieldName, schema) {
574
+ const lowerName = fieldName.toLowerCase();
575
+ const checks = definition(unwrap(schema)).checks ?? [];
576
+ const checkKinds = checks.map((check) => {
577
+ const value = check;
578
+ return value.kind ?? value._zod?.def?.check ?? value.format;
579
+ });
580
+ if (checkKinds.some((kind) => String(kind).includes("email"))) {
581
+ return "example@example.com";
582
+ }
583
+ if (checkKinds.some((kind) => String(kind).includes("datetime")) || lowerName.endsWith("at") || lowerName.includes("date")) {
584
+ return (/* @__PURE__ */ new Date()).toISOString();
585
+ }
586
+ if (checkKinds.some((kind) => String(kind).includes("url"))) {
587
+ return "https://example.com";
588
+ }
589
+ if (lowerName.includes("email")) return "example@example.com";
590
+ if (lowerName.endsWith("id")) return "example-id";
591
+ if (lowerName.includes("name")) return "Example name";
592
+ return `Example ${fieldName}`;
593
+ }
594
+ function exampleValue(fieldName, schema) {
595
+ const originalDef = definition(schema);
596
+ if (typeName(schema) === "default") {
597
+ const defaultValue = originalDef.defaultValue;
598
+ return typeof defaultValue === "function" ? defaultValue() : defaultValue;
599
+ }
600
+ const unwrapped = unwrap(schema);
601
+ const def = definition(unwrapped);
602
+ const name = typeName(unwrapped);
603
+ const values = enumValues(unwrapped);
604
+ if (values?.length) return values[0];
605
+ if (name === "string") return stringExample(fieldName, unwrapped);
606
+ if (name === "number") return 0;
607
+ if (name === "bigint") return 0;
608
+ if (name === "boolean") return false;
609
+ if (name === "date") return (/* @__PURE__ */ new Date()).toISOString();
610
+ if (name === "array") return [];
611
+ if (name === "object") {
612
+ return Object.fromEntries(
613
+ Object.entries(shapeOf(unwrapped)).filter(([, child]) => !isOptional(child)).map(([childName, child]) => [
614
+ childName,
615
+ exampleValue(childName, child)
616
+ ])
617
+ );
618
+ }
619
+ if (name === "record" || name === "map") return {};
620
+ if (name === "tuple") return [];
621
+ if (name === "union") {
622
+ const option = Array.isArray(def.options) ? def.options[0] : void 0;
623
+ return option ? exampleValue(fieldName, option) : null;
624
+ }
625
+ return null;
626
+ }
627
+ function effectiveMutualShape(config) {
628
+ if (config.effectiveMutualSchema) {
629
+ return shapeOf(config.effectiveMutualSchema);
630
+ }
631
+ return {
632
+ ...shapeOf(config.mutual?.mutualSchema),
633
+ ...shapeOf(config.mutual?.createMutualSchema)
634
+ };
635
+ }
636
+ function fieldsMetadata(shape, relationshipFields = /* @__PURE__ */ new Set(), uniqueFields = /* @__PURE__ */ new Set()) {
637
+ return Object.entries(shape).map(([name, schema]) => ({
638
+ name,
639
+ type: describeType(schema),
640
+ required: !isOptional(schema),
641
+ relationship: relationshipFields.has(name),
642
+ unique: uniqueFields.has(name),
643
+ ...schema.description ? { description: schema.description } : {},
644
+ ...enumValues(schema) ? { values: enumValues(schema) } : {}
645
+ }));
646
+ }
647
+ function templateFor(shape) {
648
+ return Object.fromEntries(
649
+ Object.entries(shape).filter(([, schema]) => !isOptional(schema)).map(([name, schema]) => [name, exampleValue(name, schema)])
650
+ );
651
+ }
652
+ function entityMetadata(config) {
653
+ const baseShape = shapeOf(config.baseSchema);
654
+ const createShape = shapeOf(config.createSchema);
655
+ const mutualShape = effectiveMutualShape(config);
656
+ const shape = { ...baseShape, ...createShape, ...mutualShape };
657
+ const mutualFields = /* @__PURE__ */ new Set([
658
+ ...Object.keys(mutualShape),
659
+ ...Object.keys(config.mutual?.mutualFields ?? {})
660
+ ]);
661
+ const uniqueFields = (config.uniqueFields ?? []).map(String);
662
+ const fields = fieldsMetadata(shape, mutualFields, new Set(uniqueFields));
663
+ const createTemplate = templateFor(shape);
664
+ const searchFields = config.search?.fields?.length ? config.search.fields.map(({ field }) => String(field)) : (config.searchableFields ?? []).map(String);
665
+ const mutualsByEntity = /* @__PURE__ */ new Map();
666
+ for (const [field, relationship] of Object.entries(
667
+ config.mutual?.mutualFields ?? {}
668
+ )) {
669
+ if (relationship.entityType === void 0) continue;
670
+ const entityType = String(relationship.entityType);
671
+ const existing = mutualsByEntity.get(entityType);
672
+ const asEntity = relationship.mutual?.asEntity;
673
+ const dataSchema = asEntity ? asEntity.createSchema ?? asEntity.baseSchema : relationship.mutual?.mutualDataSchema;
674
+ const dataShape = shapeOf(dataSchema);
675
+ mutualsByEntity.set(entityType, {
676
+ entityType,
677
+ fields: [...existing?.fields ?? [], field],
678
+ dataFields: Object.keys(dataShape).length ? fieldsMetadata(dataShape) : existing?.dataFields ?? [],
679
+ createTemplate: Object.keys(dataShape).length ? templateFor(dataShape) : existing?.createTemplate ?? {},
680
+ ...asEntity?.name !== void 0 ? { asEntity: String(asEntity.name) } : existing?.asEntity ? { asEntity: existing.asEntity } : {}
681
+ });
682
+ }
683
+ return {
684
+ name: String(config.name),
685
+ displayName: config.displayName || String(config.name),
686
+ searchable: searchFields.length > 0,
687
+ searchFields,
688
+ uniqueFields,
689
+ tags: (config.tags ?? []).filter(({ name }) => name !== void 0).map(({ name }) => String(name)),
690
+ mutuals: [...mutualsByEntity.values()],
691
+ fields,
692
+ createTemplate
693
+ };
694
+ }
695
+
696
+ // commands/devtool/server.ts
697
+ import {
698
+ createServer
699
+ } from "http";
700
+
701
+ // commands/devtool/ui.ts
702
+ var INDEX_HTML = `<!doctype html>
703
+ <html lang="en">
704
+ <head>
705
+ <meta charset="UTF-8" />
706
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
707
+ <meta name="color-scheme" content="dark" />
708
+ <title>Monorise Devtool</title>
709
+ <link rel="stylesheet" href="/styles.css" />
710
+ </head>
711
+ <body>
712
+ <div class="app-shell">
713
+ <aside class="sidebar">
714
+ <div class="brand">
715
+ <div class="brand-mark" aria-hidden="true">M</div>
716
+ <div>
717
+ <strong>Monorise</strong>
718
+ <span>Devtool</span>
719
+ </div>
720
+ </div>
721
+ <div class="sidebar-label">Entities</div>
722
+ <nav id="entity-nav" aria-label="Entity types"></nav>
723
+ <div class="sidebar-footer">
724
+ <span class="status-dot"></span>
725
+ <span id="api-label">Loading configuration\u2026</span>
726
+ </div>
727
+ </aside>
728
+
729
+ <main>
730
+ <header class="page-header">
731
+ <div>
732
+ <div class="eyebrow">Entity browser</div>
733
+ <h1 id="page-title">Select an entity</h1>
734
+ <p id="page-description">Browse and manage your local development data.</p>
735
+ </div>
736
+ <div class="header-actions">
737
+ <div class="connection-controls">
738
+ <label>
739
+ <span>Stage</span>
740
+ <select id="stage-select" aria-label="SST stage"></select>
741
+ </label>
742
+ <label>
743
+ <span>API key</span>
744
+ <select id="key-select" aria-label="Scoped API key"></select>
745
+ </label>
746
+ </div>
747
+ <button id="refresh-button" class="button button-secondary" type="button">
748
+ <span aria-hidden="true">\u21BB</span> Refresh
749
+ </button>
750
+ <p id="connection-warning" class="connection-warning" hidden></p>
751
+ </div>
752
+ </header>
753
+
754
+ <section id="content" class="content" hidden>
755
+ <div class="metrics">
756
+ <div class="metric">
757
+ <span>Results</span>
758
+ <strong id="result-count">\u2014</strong>
759
+ </div>
760
+ <div class="metric">
761
+ <span>Search</span>
762
+ <strong id="search-status">Unavailable</strong>
763
+ </div>
764
+ <div class="metric">
765
+ <span>Unique fields</span>
766
+ <strong id="unique-count">0</strong>
767
+ </div>
768
+ </div>
769
+
770
+ <div class="panel">
771
+ <div class="toolbar">
772
+ <div class="listing-tools">
773
+ <label class="listing-mode">
774
+ <span>View</span>
775
+ <select id="listing-mode" aria-label="Entity listing mode"></select>
776
+ </label>
777
+ <form id="search-form" class="search">
778
+ <span aria-hidden="true">\u2315</span>
779
+ <input
780
+ id="search-input"
781
+ type="search"
782
+ autocomplete="off"
783
+ placeholder="Search entities"
784
+ aria-label="Search entities"
785
+ />
786
+ </form>
787
+ </div>
788
+ <div class="toolbar-actions">
789
+ <button id="clear-search" class="button button-ghost" type="button" hidden>
790
+ Clear search
791
+ </button>
792
+ <button id="create-button" class="button button-primary" type="button">
793
+ <span aria-hidden="true">\uFF0B</span> Create
794
+ </button>
795
+ </div>
796
+ </div>
797
+
798
+ <form id="tag-filter-form" class="tag-filters" hidden>
799
+ <label>
800
+ <span>Group</span>
801
+ <input id="tag-group" autocomplete="off" placeholder="Exact group" />
802
+ </label>
803
+ <label>
804
+ <span>Sort prefix</span>
805
+ <input id="tag-query" autocomplete="off" placeholder="Starts with" />
806
+ </label>
807
+ <label>
808
+ <span>Sort from</span>
809
+ <input id="tag-start" autocomplete="off" placeholder="Inclusive" />
810
+ </label>
811
+ <label>
812
+ <span>Sort to</span>
813
+ <input id="tag-end" autocomplete="off" placeholder="Inclusive" />
814
+ </label>
815
+ <div class="tag-filter-actions">
816
+ <button class="button button-primary" type="submit">Apply tag</button>
817
+ <button id="clear-tag" class="button button-ghost" type="button">Clear</button>
818
+ </div>
819
+ <p>Provide a group, a sort prefix, or a sort range. A prefix cannot be combined with a range.</p>
820
+ </form>
821
+
822
+ <div id="notice" class="notice" hidden></div>
823
+ <div id="loading" class="loading" hidden>
824
+ <div class="spinner"></div>
825
+ <span>Loading entities\u2026</span>
826
+ </div>
827
+ <div id="empty" class="empty" hidden>
828
+ <div class="empty-icon">{ }</div>
829
+ <h2>No entities found</h2>
830
+ <p id="empty-message">Create the first record for this entity type.</p>
831
+ </div>
832
+
833
+ <div id="table-wrap" class="table-wrap" hidden>
834
+ <table>
835
+ <thead id="table-head"></thead>
836
+ <tbody id="table-body"></tbody>
837
+ </table>
838
+ </div>
839
+
840
+ <div id="pagination" class="pagination" hidden>
841
+ <span id="page-label">Page 1</span>
842
+ <div>
843
+ <button id="previous-button" class="button button-secondary" type="button">
844
+ Previous
845
+ </button>
846
+ <button id="next-button" class="button button-secondary" type="button">
847
+ Next
848
+ </button>
849
+ </div>
850
+ </div>
851
+ </div>
852
+ </section>
853
+
854
+ <section id="welcome" class="welcome">
855
+ <div class="welcome-mark">M</div>
856
+ <h2>Your data, without the console hopping.</h2>
857
+ <p>Select an entity type to list, search, create, edit, or delete its records.</p>
858
+ </section>
859
+ </main>
860
+ </div>
861
+
862
+ <dialog id="editor-dialog">
863
+ <form id="editor-form" method="dialog">
864
+ <div class="dialog-header">
865
+ <div>
866
+ <div id="dialog-eyebrow" class="eyebrow">Create entity</div>
867
+ <h2 id="dialog-title">New entity</h2>
868
+ </div>
869
+ <button class="icon-button" value="cancel" aria-label="Close editor" type="submit">\xD7</button>
870
+ </div>
871
+ <div class="dialog-body">
872
+ <div class="editor-column">
873
+ <label for="json-editor">Entity data (JSON)</label>
874
+ <textarea id="json-editor" spellcheck="false" aria-describedby="editor-help"></textarea>
875
+ <p id="editor-help">Only send the fields you want to store or update.</p>
876
+ <div id="editor-error" class="editor-error" hidden></div>
877
+ </div>
878
+ <aside class="field-reference">
879
+ <div class="field-reference-title">Schema reference</div>
880
+ <div id="field-list"></div>
881
+ </aside>
882
+ </div>
883
+ <div class="dialog-footer">
884
+ <button class="button button-secondary" value="cancel" type="submit">Cancel</button>
885
+ <button id="save-button" class="button button-primary" type="button">Create entity</button>
886
+ </div>
887
+ </form>
888
+ </dialog>
889
+
890
+ <dialog id="mutual-dialog" class="mutual-dialog">
891
+ <div class="dialog-header">
892
+ <div>
893
+ <div class="eyebrow">Mutual relationships</div>
894
+ <h2 id="mutual-title">Entity mutuals</h2>
895
+ </div>
896
+ <button id="mutual-close" class="icon-button" aria-label="Close mutuals" type="button">\xD7</button>
897
+ </div>
898
+ <div class="mutual-toolbar">
899
+ <label>
900
+ <span>Related entity</span>
901
+ <select id="mutual-target" aria-label="Related entity type"></select>
902
+ </label>
903
+ <div class="mutual-toolbar-actions">
904
+ <button id="mutual-create" class="button button-primary" type="button">
905
+ <span aria-hidden="true">\uFF0B</span> Create mutual
906
+ </button>
907
+ <button id="mutual-refresh" class="button button-secondary" type="button">
908
+ <span aria-hidden="true">\u21BB</span> Refresh
909
+ </button>
910
+ </div>
911
+ </div>
912
+ <div id="mutual-notice" class="notice" hidden></div>
913
+ <div id="mutual-loading" class="loading" hidden>
914
+ <div class="spinner"></div>
915
+ <span>Loading mutuals\u2026</span>
916
+ </div>
917
+ <div id="mutual-empty" class="empty" hidden>
918
+ <div class="empty-icon">\u2194</div>
919
+ <h2>No mutuals found</h2>
920
+ <p>This entity has no relationships to the selected entity type.</p>
921
+ </div>
922
+ <div id="mutual-table-wrap" class="table-wrap" hidden>
923
+ <table>
924
+ <thead>
925
+ <tr>
926
+ <th>Entity ID</th>
927
+ <th>Entity data</th>
928
+ <th>Mutual data</th>
929
+ <th>Updated</th>
930
+ <th aria-label="Actions"></th>
931
+ </tr>
932
+ </thead>
933
+ <tbody id="mutual-table-body"></tbody>
934
+ </table>
935
+ </div>
936
+ <div id="mutual-pagination" class="pagination" hidden>
937
+ <span id="mutual-page-label">Page 1</span>
938
+ <div>
939
+ <button id="mutual-previous" class="button button-secondary" type="button">Previous</button>
940
+ <button id="mutual-next" class="button button-secondary" type="button">Next</button>
941
+ </div>
942
+ </div>
943
+ </dialog>
944
+
945
+ <dialog id="mutual-editor-dialog">
946
+ <form id="mutual-editor-form" method="dialog">
947
+ <div class="dialog-header">
948
+ <div>
949
+ <div id="mutual-editor-eyebrow" class="eyebrow">Create mutual</div>
950
+ <h2 id="mutual-editor-title">New mutual relationship</h2>
951
+ </div>
952
+ <button class="icon-button" value="cancel" aria-label="Close mutual editor" type="submit">\xD7</button>
953
+ </div>
954
+ <div class="dialog-body">
955
+ <div class="editor-column">
956
+ <label for="mutual-entity-id">Related entity ID</label>
957
+ <input id="mutual-entity-id" class="dialog-input" autocomplete="off" />
958
+ <label for="mutual-json-editor">Mutual data (JSON)</label>
959
+ <textarea id="mutual-json-editor" class="json-editor" spellcheck="false"></textarea>
960
+ <p class="editor-help">This data belongs to the relationship, not either entity.</p>
961
+ <div id="mutual-editor-error" class="editor-error" hidden></div>
962
+ </div>
963
+ <aside class="field-reference">
964
+ <div class="field-reference-title">Mutual data schema</div>
965
+ <div id="mutual-field-list" class="field-list"></div>
966
+ </aside>
967
+ </div>
968
+ <div class="dialog-footer">
969
+ <button class="button button-secondary" value="cancel" type="submit">Cancel</button>
970
+ <button id="mutual-save" class="button button-primary" type="button">Create mutual</button>
971
+ </div>
972
+ </form>
973
+ </dialog>
974
+
975
+ <div id="toast" class="toast" role="status" aria-live="polite"></div>
976
+ <script src="/app.js" type="module"></script>
977
+ </body>
978
+ </html>`;
979
+ var STYLES_CSS = `
980
+ :root {
981
+ --bg: #090b0d;
982
+ --panel: #111417;
983
+ --panel-soft: #15191d;
984
+ --line: #252a2f;
985
+ --line-bright: #353c43;
986
+ --text: #f2f5f7;
987
+ --muted: #8d969f;
988
+ --accent: #d5ff47;
989
+ --accent-strong: #bfe935;
990
+ --accent-ink: #151b00;
991
+ --danger: #ff6b6b;
992
+ --danger-soft: rgba(255, 107, 107, 0.1);
993
+ --radius: 14px;
994
+ --mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
995
+ --sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
996
+ }
997
+
998
+ * {
999
+ box-sizing: border-box;
1000
+ }
1001
+
1002
+ html,
1003
+ body {
1004
+ min-height: 100%;
1005
+ }
1006
+
1007
+ body {
1008
+ margin: 0;
1009
+ color: var(--text);
1010
+ background:
1011
+ radial-gradient(circle at 75% -15%, rgba(213, 255, 71, 0.08), transparent 30rem),
1012
+ var(--bg);
1013
+ font-family: var(--sans);
1014
+ font-size: 14px;
1015
+ }
1016
+
1017
+ button,
1018
+ input,
1019
+ select,
1020
+ textarea {
1021
+ font: inherit;
1022
+ }
1023
+
1024
+ button {
1025
+ color: inherit;
1026
+ }
1027
+
1028
+ .app-shell {
1029
+ display: grid;
1030
+ grid-template-columns: 248px minmax(0, 1fr);
1031
+ min-height: 100vh;
1032
+ }
1033
+
1034
+ .sidebar {
1035
+ position: sticky;
1036
+ top: 0;
1037
+ display: flex;
1038
+ flex-direction: column;
1039
+ height: 100vh;
1040
+ padding: 28px 18px 20px;
1041
+ border-right: 1px solid var(--line);
1042
+ background: rgba(12, 14, 16, 0.94);
1043
+ backdrop-filter: blur(16px);
1044
+ }
1045
+
1046
+ .brand {
1047
+ display: flex;
1048
+ align-items: center;
1049
+ gap: 11px;
1050
+ padding: 0 8px 32px;
1051
+ }
1052
+
1053
+ .brand-mark,
1054
+ .welcome-mark {
1055
+ display: grid;
1056
+ place-items: center;
1057
+ color: var(--accent-ink);
1058
+ background: var(--accent);
1059
+ font-weight: 900;
1060
+ transform: rotate(-4deg);
1061
+ }
1062
+
1063
+ .brand-mark {
1064
+ width: 34px;
1065
+ height: 34px;
1066
+ border-radius: 9px;
1067
+ }
1068
+
1069
+ .brand strong,
1070
+ .brand span {
1071
+ display: block;
1072
+ }
1073
+
1074
+ .brand strong {
1075
+ letter-spacing: -0.02em;
1076
+ }
1077
+
1078
+ .brand span {
1079
+ margin-top: 2px;
1080
+ color: var(--muted);
1081
+ font-size: 12px;
1082
+ }
1083
+
1084
+ .sidebar-label,
1085
+ .eyebrow {
1086
+ color: var(--muted);
1087
+ font-size: 10px;
1088
+ font-weight: 750;
1089
+ letter-spacing: 0.14em;
1090
+ text-transform: uppercase;
1091
+ }
1092
+
1093
+ .sidebar-label {
1094
+ padding: 0 10px 9px;
1095
+ }
1096
+
1097
+ #entity-nav {
1098
+ display: grid;
1099
+ gap: 4px;
1100
+ overflow-y: auto;
1101
+ }
1102
+
1103
+ .entity-link {
1104
+ display: flex;
1105
+ align-items: center;
1106
+ justify-content: space-between;
1107
+ width: 100%;
1108
+ padding: 10px 11px;
1109
+ border: 1px solid transparent;
1110
+ border-radius: 9px;
1111
+ color: #aeb6bd;
1112
+ background: transparent;
1113
+ cursor: pointer;
1114
+ text-align: left;
1115
+ transition: 140ms ease;
1116
+ }
1117
+
1118
+ .entity-link:hover {
1119
+ color: var(--text);
1120
+ background: var(--panel-soft);
1121
+ }
1122
+
1123
+ .entity-link.active {
1124
+ color: var(--text);
1125
+ border-color: #333a3f;
1126
+ background: #1b2024;
1127
+ box-shadow: inset 3px 0 var(--accent);
1128
+ }
1129
+
1130
+ .entity-link code {
1131
+ color: #687078;
1132
+ font-family: var(--mono);
1133
+ font-size: 10px;
1134
+ }
1135
+
1136
+ .sidebar-footer {
1137
+ display: flex;
1138
+ align-items: center;
1139
+ gap: 8px;
1140
+ min-width: 0;
1141
+ margin-top: auto;
1142
+ padding: 14px 9px 0;
1143
+ border-top: 1px solid var(--line);
1144
+ color: var(--muted);
1145
+ font-family: var(--mono);
1146
+ font-size: 10px;
1147
+ }
1148
+
1149
+ .sidebar-footer span:last-child {
1150
+ overflow: hidden;
1151
+ text-overflow: ellipsis;
1152
+ white-space: nowrap;
1153
+ }
1154
+
1155
+ .status-dot {
1156
+ flex: 0 0 auto;
1157
+ width: 7px;
1158
+ height: 7px;
1159
+ border-radius: 50%;
1160
+ background: var(--accent);
1161
+ box-shadow: 0 0 10px rgba(213, 255, 71, 0.5);
1162
+ }
1163
+
1164
+ main {
1165
+ min-width: 0;
1166
+ padding: 46px clamp(24px, 5vw, 76px) 70px;
1167
+ }
1168
+
1169
+ .page-header {
1170
+ display: flex;
1171
+ align-items: end;
1172
+ justify-content: space-between;
1173
+ gap: 24px;
1174
+ max-width: 1320px;
1175
+ margin: 0 auto 30px;
1176
+ }
1177
+
1178
+ h1,
1179
+ h2,
1180
+ p {
1181
+ margin-top: 0;
1182
+ }
1183
+
1184
+ h1 {
1185
+ margin: 7px 0 6px;
1186
+ font-size: clamp(30px, 4vw, 46px);
1187
+ line-height: 1;
1188
+ letter-spacing: -0.045em;
1189
+ }
1190
+
1191
+ .page-header p,
1192
+ .welcome p {
1193
+ margin-bottom: 0;
1194
+ color: var(--muted);
1195
+ }
1196
+
1197
+ .header-actions {
1198
+ display: grid;
1199
+ grid-template-columns: minmax(0, 1fr) auto;
1200
+ align-items: end;
1201
+ gap: 8px;
1202
+ width: min(620px, 58%);
1203
+ }
1204
+
1205
+ .connection-controls {
1206
+ display: grid;
1207
+ grid-template-columns: minmax(120px, 0.8fr) minmax(180px, 1.2fr);
1208
+ gap: 8px;
1209
+ }
1210
+
1211
+ .connection-controls label {
1212
+ display: grid;
1213
+ gap: 5px;
1214
+ min-width: 0;
1215
+ }
1216
+
1217
+ .connection-controls label > span {
1218
+ color: var(--muted);
1219
+ font-size: 9px;
1220
+ font-weight: 750;
1221
+ letter-spacing: 0.12em;
1222
+ text-transform: uppercase;
1223
+ }
1224
+
1225
+ .connection-controls select {
1226
+ width: 100%;
1227
+ min-height: 38px;
1228
+ padding: 0 32px 0 10px;
1229
+ overflow: hidden;
1230
+ border: 1px solid var(--line-bright);
1231
+ border-radius: 8px;
1232
+ outline: 0;
1233
+ color: #dce1e5;
1234
+ background: var(--panel-soft);
1235
+ text-overflow: ellipsis;
1236
+ }
1237
+
1238
+ .connection-controls select:focus {
1239
+ border-color: #69742f;
1240
+ box-shadow: 0 0 0 3px rgba(213, 255, 71, 0.07);
1241
+ }
1242
+
1243
+ .connection-controls select:disabled {
1244
+ opacity: 0.45;
1245
+ cursor: not-allowed;
1246
+ }
1247
+
1248
+ .connection-warning {
1249
+ grid-column: 1 / -1;
1250
+ margin: 2px 0 0;
1251
+ color: #e5c47a !important;
1252
+ font-size: 10px;
1253
+ text-align: right;
1254
+ }
1255
+
1256
+ .content {
1257
+ max-width: 1320px;
1258
+ margin: 0 auto;
1259
+ }
1260
+
1261
+ .metrics {
1262
+ display: grid;
1263
+ grid-template-columns: repeat(3, minmax(0, 1fr));
1264
+ gap: 10px;
1265
+ margin-bottom: 14px;
1266
+ }
1267
+
1268
+ .metric {
1269
+ padding: 18px 20px;
1270
+ border: 1px solid var(--line);
1271
+ border-radius: 12px;
1272
+ background: rgba(17, 20, 23, 0.72);
1273
+ }
1274
+
1275
+ .metric span,
1276
+ .metric strong {
1277
+ display: block;
1278
+ }
1279
+
1280
+ .metric span {
1281
+ margin-bottom: 7px;
1282
+ color: var(--muted);
1283
+ font-size: 11px;
1284
+ }
1285
+
1286
+ .metric strong {
1287
+ overflow: hidden;
1288
+ font-family: var(--mono);
1289
+ font-size: 16px;
1290
+ text-overflow: ellipsis;
1291
+ white-space: nowrap;
1292
+ }
1293
+
1294
+ .panel {
1295
+ overflow: hidden;
1296
+ border: 1px solid var(--line);
1297
+ border-radius: var(--radius);
1298
+ background: var(--panel);
1299
+ box-shadow: 0 22px 60px rgba(0, 0, 0, 0.22);
1300
+ }
1301
+
1302
+ .toolbar {
1303
+ display: flex;
1304
+ align-items: center;
1305
+ justify-content: space-between;
1306
+ gap: 12px;
1307
+ padding: 14px;
1308
+ border-bottom: 1px solid var(--line);
1309
+ }
1310
+
1311
+ .toolbar-actions {
1312
+ display: flex;
1313
+ gap: 8px;
1314
+ }
1315
+
1316
+ .listing-tools {
1317
+ display: flex;
1318
+ align-items: end;
1319
+ gap: 8px;
1320
+ width: min(720px, 68%);
1321
+ }
1322
+
1323
+ .listing-mode {
1324
+ display: grid;
1325
+ flex: 0 0 190px;
1326
+ gap: 5px;
1327
+ }
1328
+
1329
+ .listing-mode > span,
1330
+ .tag-filters label > span,
1331
+ .mutual-toolbar label > span {
1332
+ color: var(--muted);
1333
+ font-size: 9px;
1334
+ font-weight: 750;
1335
+ letter-spacing: 0.12em;
1336
+ text-transform: uppercase;
1337
+ }
1338
+
1339
+ .listing-mode select,
1340
+ .tag-filters input,
1341
+ .mutual-toolbar select {
1342
+ min-height: 38px;
1343
+ padding: 0 10px;
1344
+ border: 1px solid var(--line-bright);
1345
+ border-radius: 8px;
1346
+ outline: 0;
1347
+ color: #dce1e5;
1348
+ background: #0d1012;
1349
+ }
1350
+
1351
+ .listing-mode select:focus,
1352
+ .tag-filters input:focus,
1353
+ .mutual-toolbar select:focus {
1354
+ border-color: #69742f;
1355
+ box-shadow: 0 0 0 3px rgba(213, 255, 71, 0.07);
1356
+ }
1357
+
1358
+ .search {
1359
+ display: flex;
1360
+ flex: 1;
1361
+ align-items: center;
1362
+ min-width: 180px;
1363
+ border: 1px solid var(--line-bright);
1364
+ border-radius: 9px;
1365
+ background: #0d1012;
1366
+ }
1367
+
1368
+ .search:focus-within {
1369
+ border-color: #69742f;
1370
+ box-shadow: 0 0 0 3px rgba(213, 255, 71, 0.07);
1371
+ }
1372
+
1373
+ .search span {
1374
+ padding-left: 12px;
1375
+ color: var(--muted);
1376
+ font-size: 18px;
1377
+ }
1378
+
1379
+ .search input {
1380
+ width: 100%;
1381
+ padding: 10px;
1382
+ border: 0;
1383
+ outline: 0;
1384
+ color: var(--text);
1385
+ background: transparent;
1386
+ }
1387
+
1388
+ .search input::placeholder {
1389
+ color: #646c73;
1390
+ }
1391
+
1392
+ .search.disabled {
1393
+ opacity: 0.45;
1394
+ }
1395
+
1396
+ .tag-filters {
1397
+ display: grid;
1398
+ grid-template-columns: repeat(4, minmax(120px, 1fr)) auto;
1399
+ align-items: end;
1400
+ gap: 10px;
1401
+ padding: 14px;
1402
+ border-bottom: 1px solid var(--line);
1403
+ background: #0d1012;
1404
+ }
1405
+
1406
+ .tag-filters label {
1407
+ display: grid;
1408
+ gap: 5px;
1409
+ }
1410
+
1411
+ .tag-filters input {
1412
+ width: 100%;
1413
+ }
1414
+
1415
+ .tag-filter-actions {
1416
+ display: flex;
1417
+ gap: 4px;
1418
+ }
1419
+
1420
+ .tag-filters > p {
1421
+ grid-column: 1 / -1;
1422
+ margin: 0;
1423
+ color: #737d84;
1424
+ font-size: 10px;
1425
+ }
1426
+
1427
+ .button,
1428
+ .icon-button {
1429
+ border: 0;
1430
+ cursor: pointer;
1431
+ font-weight: 700;
1432
+ transition: 130ms ease;
1433
+ }
1434
+
1435
+ .button {
1436
+ min-height: 38px;
1437
+ padding: 0 14px;
1438
+ border-radius: 8px;
1439
+ font-size: 12px;
1440
+ }
1441
+
1442
+ .button:hover {
1443
+ transform: translateY(-1px);
1444
+ }
1445
+
1446
+ .button:disabled {
1447
+ opacity: 0.42;
1448
+ cursor: not-allowed;
1449
+ transform: none;
1450
+ }
1451
+
1452
+ .button-primary {
1453
+ color: var(--accent-ink);
1454
+ background: var(--accent);
1455
+ }
1456
+
1457
+ .button-primary:hover {
1458
+ background: var(--accent-strong);
1459
+ }
1460
+
1461
+ .button-secondary {
1462
+ border: 1px solid var(--line-bright);
1463
+ color: #c7cdd2;
1464
+ background: var(--panel-soft);
1465
+ }
1466
+
1467
+ .button-secondary:hover {
1468
+ border-color: #4a535b;
1469
+ color: var(--text);
1470
+ }
1471
+
1472
+ .button-ghost {
1473
+ color: var(--muted);
1474
+ background: transparent;
1475
+ }
1476
+
1477
+ .button-ghost:hover {
1478
+ color: var(--text);
1479
+ background: var(--panel-soft);
1480
+ }
1481
+
1482
+ .notice {
1483
+ margin: 14px;
1484
+ padding: 11px 13px;
1485
+ border: 1px solid rgba(255, 107, 107, 0.35);
1486
+ border-radius: 8px;
1487
+ color: #ffabab;
1488
+ background: var(--danger-soft);
1489
+ }
1490
+
1491
+ .loading,
1492
+ .empty,
1493
+ .welcome {
1494
+ display: grid;
1495
+ justify-items: center;
1496
+ text-align: center;
1497
+ }
1498
+
1499
+ .loading {
1500
+ grid-auto-flow: column;
1501
+ justify-content: center;
1502
+ gap: 10px;
1503
+ padding: 72px 20px;
1504
+ color: var(--muted);
1505
+ }
1506
+
1507
+ .spinner {
1508
+ width: 18px;
1509
+ height: 18px;
1510
+ border: 2px solid #394047;
1511
+ border-top-color: var(--accent);
1512
+ border-radius: 50%;
1513
+ animation: spin 0.7s linear infinite;
1514
+ }
1515
+
1516
+ @keyframes spin {
1517
+ to {
1518
+ transform: rotate(360deg);
1519
+ }
1520
+ }
1521
+
1522
+ .empty {
1523
+ padding: 76px 20px;
1524
+ }
1525
+
1526
+ .empty-icon {
1527
+ margin-bottom: 16px;
1528
+ color: #626b72;
1529
+ font-family: var(--mono);
1530
+ font-size: 28px;
1531
+ }
1532
+
1533
+ .empty h2 {
1534
+ margin-bottom: 7px;
1535
+ font-size: 17px;
1536
+ }
1537
+
1538
+ .empty p {
1539
+ margin-bottom: 0;
1540
+ color: var(--muted);
1541
+ font-size: 13px;
1542
+ }
1543
+
1544
+ .table-wrap {
1545
+ overflow-x: auto;
1546
+ }
1547
+
1548
+ table {
1549
+ width: 100%;
1550
+ border-collapse: collapse;
1551
+ }
1552
+
1553
+ th,
1554
+ td {
1555
+ padding: 13px 16px;
1556
+ border-bottom: 1px solid var(--line);
1557
+ text-align: left;
1558
+ white-space: nowrap;
1559
+ }
1560
+
1561
+ th {
1562
+ color: #717a82;
1563
+ background: #0e1113;
1564
+ font-size: 10px;
1565
+ font-weight: 750;
1566
+ letter-spacing: 0.08em;
1567
+ text-transform: uppercase;
1568
+ }
1569
+
1570
+ td {
1571
+ max-width: 280px;
1572
+ overflow: hidden;
1573
+ color: #c5cbd0;
1574
+ font-size: 12px;
1575
+ text-overflow: ellipsis;
1576
+ }
1577
+
1578
+ tbody tr {
1579
+ transition: 120ms ease;
1580
+ }
1581
+
1582
+ tbody tr:hover {
1583
+ background: #151a1e;
1584
+ }
1585
+
1586
+ tbody tr:last-child td {
1587
+ border-bottom: 0;
1588
+ }
1589
+
1590
+ .id-cell {
1591
+ color: #9ba3aa;
1592
+ font-family: var(--mono);
1593
+ font-size: 11px;
1594
+ }
1595
+
1596
+ .date-cell {
1597
+ color: #7d868e;
1598
+ font-family: var(--mono);
1599
+ font-size: 10px;
1600
+ }
1601
+
1602
+ .json-cell {
1603
+ min-width: 220px;
1604
+ max-width: 420px;
1605
+ color: #aeb8a1;
1606
+ font-family: var(--mono);
1607
+ font-size: 10px;
1608
+ line-height: 1.5;
1609
+ white-space: normal;
1610
+ word-break: break-word;
1611
+ }
1612
+
1613
+ .row-actions {
1614
+ display: flex;
1615
+ justify-content: end;
1616
+ gap: 5px;
1617
+ }
1618
+
1619
+ .row-action {
1620
+ padding: 6px 8px;
1621
+ border: 1px solid transparent;
1622
+ border-radius: 6px;
1623
+ color: var(--muted);
1624
+ background: transparent;
1625
+ cursor: pointer;
1626
+ font-size: 11px;
1627
+ }
1628
+
1629
+ .row-action:hover {
1630
+ border-color: var(--line-bright);
1631
+ color: var(--text);
1632
+ background: var(--panel-soft);
1633
+ }
1634
+
1635
+ .row-action.danger:hover {
1636
+ border-color: rgba(255, 107, 107, 0.35);
1637
+ color: #ff9696;
1638
+ background: var(--danger-soft);
1639
+ }
1640
+
1641
+ .pagination {
1642
+ display: flex;
1643
+ align-items: center;
1644
+ justify-content: space-between;
1645
+ padding: 13px 14px;
1646
+ border-top: 1px solid var(--line);
1647
+ color: var(--muted);
1648
+ font-family: var(--mono);
1649
+ font-size: 10px;
1650
+ }
1651
+
1652
+ .pagination div {
1653
+ display: flex;
1654
+ gap: 7px;
1655
+ }
1656
+
1657
+ .welcome {
1658
+ max-width: 560px;
1659
+ margin: 16vh auto 0;
1660
+ }
1661
+
1662
+ .welcome-mark {
1663
+ width: 62px;
1664
+ height: 62px;
1665
+ margin-bottom: 26px;
1666
+ border-radius: 16px;
1667
+ font-size: 25px;
1668
+ box-shadow: 0 18px 50px rgba(213, 255, 71, 0.12);
1669
+ }
1670
+
1671
+ .welcome h2 {
1672
+ margin-bottom: 10px;
1673
+ font-size: clamp(25px, 4vw, 38px);
1674
+ letter-spacing: -0.04em;
1675
+ }
1676
+
1677
+ dialog {
1678
+ width: min(940px, calc(100vw - 32px));
1679
+ max-height: calc(100vh - 42px);
1680
+ padding: 0;
1681
+ overflow: hidden;
1682
+ border: 1px solid var(--line-bright);
1683
+ border-radius: 16px;
1684
+ color: var(--text);
1685
+ background: #111518;
1686
+ box-shadow: 0 32px 100px rgba(0, 0, 0, 0.72);
1687
+ }
1688
+
1689
+ dialog::backdrop {
1690
+ background: rgba(0, 0, 0, 0.72);
1691
+ backdrop-filter: blur(4px);
1692
+ }
1693
+
1694
+ .dialog-header,
1695
+ .dialog-footer {
1696
+ display: flex;
1697
+ align-items: center;
1698
+ justify-content: space-between;
1699
+ padding: 17px 20px;
1700
+ }
1701
+
1702
+ .mutual-dialog {
1703
+ width: min(1120px, calc(100vw - 32px));
1704
+ }
1705
+
1706
+ .mutual-toolbar {
1707
+ display: flex;
1708
+ align-items: end;
1709
+ justify-content: space-between;
1710
+ gap: 12px;
1711
+ padding: 14px 20px;
1712
+ border-bottom: 1px solid var(--line);
1713
+ background: #0d1012;
1714
+ }
1715
+
1716
+ .mutual-toolbar label {
1717
+ display: grid;
1718
+ gap: 5px;
1719
+ width: min(360px, 70%);
1720
+ }
1721
+
1722
+ .mutual-toolbar-actions {
1723
+ display: flex;
1724
+ gap: 8px;
1725
+ }
1726
+
1727
+ .mutual-dialog .table-wrap {
1728
+ max-height: min(520px, calc(100vh - 260px));
1729
+ overflow: auto;
1730
+ }
1731
+
1732
+ .mutual-dialog .empty,
1733
+ .mutual-dialog .loading {
1734
+ min-height: 280px;
1735
+ }
1736
+
1737
+ .dialog-header {
1738
+ border-bottom: 1px solid var(--line);
1739
+ }
1740
+
1741
+ .dialog-header h2 {
1742
+ margin: 4px 0 0;
1743
+ font-size: 21px;
1744
+ letter-spacing: -0.025em;
1745
+ }
1746
+
1747
+ .icon-button {
1748
+ display: grid;
1749
+ place-items: center;
1750
+ width: 34px;
1751
+ height: 34px;
1752
+ border-radius: 8px;
1753
+ color: var(--muted);
1754
+ background: transparent;
1755
+ font-size: 22px;
1756
+ }
1757
+
1758
+ .icon-button:hover {
1759
+ color: var(--text);
1760
+ background: var(--panel-soft);
1761
+ }
1762
+
1763
+ .dialog-body {
1764
+ display: grid;
1765
+ grid-template-columns: minmax(0, 1.45fr) minmax(250px, 0.75fr);
1766
+ height: min(560px, calc(100vh - 190px));
1767
+ min-height: 0;
1768
+ max-height: calc(100vh - 190px);
1769
+ }
1770
+
1771
+ .editor-column,
1772
+ .field-reference {
1773
+ padding: 20px;
1774
+ overflow-y: auto;
1775
+ }
1776
+
1777
+ .editor-column {
1778
+ display: flex;
1779
+ flex-direction: column;
1780
+ }
1781
+
1782
+ .editor-column label,
1783
+ .field-reference-title {
1784
+ margin-bottom: 9px;
1785
+ font-size: 11px;
1786
+ font-weight: 750;
1787
+ }
1788
+
1789
+ #json-editor,
1790
+ .json-editor {
1791
+ flex: 1;
1792
+ width: 100%;
1793
+ min-height: 330px;
1794
+ resize: vertical;
1795
+ padding: 16px;
1796
+ border: 1px solid var(--line-bright);
1797
+ border-radius: 10px;
1798
+ outline: 0;
1799
+ color: #dce6c2;
1800
+ background: #090c0e;
1801
+ font-family: var(--mono);
1802
+ font-size: 12px;
1803
+ line-height: 1.65;
1804
+ tab-size: 2;
1805
+ }
1806
+
1807
+ #json-editor:focus,
1808
+ .json-editor:focus {
1809
+ border-color: #69742f;
1810
+ box-shadow: 0 0 0 3px rgba(213, 255, 71, 0.07);
1811
+ }
1812
+
1813
+ #editor-help,
1814
+ .editor-help {
1815
+ margin: 9px 0 0;
1816
+ color: var(--muted);
1817
+ font-size: 11px;
1818
+ }
1819
+
1820
+ .editor-error {
1821
+ margin-top: 10px;
1822
+ color: #ff9696;
1823
+ font-size: 12px;
1824
+ }
1825
+
1826
+ .field-reference {
1827
+ min-height: 0;
1828
+ border-left: 1px solid var(--line);
1829
+ background: #0d1012;
1830
+ overscroll-behavior: contain;
1831
+ }
1832
+
1833
+ #field-list,
1834
+ .field-list {
1835
+ display: grid;
1836
+ gap: 7px;
1837
+ }
1838
+
1839
+ .dialog-input {
1840
+ width: 100%;
1841
+ min-height: 40px;
1842
+ margin-bottom: 16px;
1843
+ padding: 0 12px;
1844
+ border: 1px solid var(--line-bright);
1845
+ border-radius: 8px;
1846
+ outline: 0;
1847
+ color: var(--text);
1848
+ background: #090c0e;
1849
+ font-family: var(--mono);
1850
+ }
1851
+
1852
+ .dialog-input:focus {
1853
+ border-color: #69742f;
1854
+ box-shadow: 0 0 0 3px rgba(213, 255, 71, 0.07);
1855
+ }
1856
+
1857
+ .dialog-input:disabled {
1858
+ opacity: 0.55;
1859
+ }
1860
+
1861
+ .field {
1862
+ padding: 10px;
1863
+ border: 1px solid #22282d;
1864
+ border-radius: 8px;
1865
+ background: #111518;
1866
+ }
1867
+
1868
+ .field-main {
1869
+ display: flex;
1870
+ align-items: center;
1871
+ justify-content: space-between;
1872
+ gap: 8px;
1873
+ }
1874
+
1875
+ .field code {
1876
+ overflow: hidden;
1877
+ color: #e1e6e9;
1878
+ font-family: var(--mono);
1879
+ font-size: 11px;
1880
+ text-overflow: ellipsis;
1881
+ }
1882
+
1883
+ .field-type {
1884
+ color: #7f8a92;
1885
+ font-family: var(--mono);
1886
+ font-size: 9px;
1887
+ text-align: right;
1888
+ }
1889
+
1890
+ .field-meta {
1891
+ display: flex;
1892
+ gap: 6px;
1893
+ margin-top: 7px;
1894
+ }
1895
+
1896
+ .badge {
1897
+ padding: 2px 5px;
1898
+ border-radius: 4px;
1899
+ color: #89929a;
1900
+ background: #20262b;
1901
+ font-size: 8px;
1902
+ font-weight: 800;
1903
+ letter-spacing: 0.05em;
1904
+ text-transform: uppercase;
1905
+ }
1906
+
1907
+ .badge.required {
1908
+ color: var(--accent-ink);
1909
+ background: var(--accent);
1910
+ }
1911
+
1912
+ .badge.relationship {
1913
+ color: #b8acf4;
1914
+ background: #292340;
1915
+ }
1916
+
1917
+ .badge.unique {
1918
+ color: #9fd8ff;
1919
+ background: #183044;
1920
+ }
1921
+
1922
+ .field-description {
1923
+ margin: 7px 0 0;
1924
+ color: var(--muted);
1925
+ font-size: 10px;
1926
+ line-height: 1.45;
1927
+ }
1928
+
1929
+ .dialog-footer {
1930
+ justify-content: end;
1931
+ gap: 8px;
1932
+ border-top: 1px solid var(--line);
1933
+ }
1934
+
1935
+ .toast {
1936
+ position: fixed;
1937
+ right: 22px;
1938
+ bottom: 22px;
1939
+ z-index: 10;
1940
+ max-width: min(380px, calc(100vw - 44px));
1941
+ padding: 12px 15px;
1942
+ border: 1px solid #3e4931;
1943
+ border-radius: 9px;
1944
+ color: #e9f6c9;
1945
+ background: #1c2415;
1946
+ box-shadow: 0 14px 40px rgba(0, 0, 0, 0.4);
1947
+ opacity: 0;
1948
+ pointer-events: none;
1949
+ transform: translateY(8px);
1950
+ transition: 180ms ease;
1951
+ }
1952
+
1953
+ .toast.visible {
1954
+ opacity: 1;
1955
+ transform: translateY(0);
1956
+ }
1957
+
1958
+ .toast.error {
1959
+ border-color: #5d3030;
1960
+ color: #ffc3c3;
1961
+ background: #2a1717;
1962
+ }
1963
+
1964
+ [hidden] {
1965
+ display: none !important;
1966
+ }
1967
+
1968
+ @media (max-width: 820px) {
1969
+ .app-shell {
1970
+ display: block;
1971
+ }
1972
+
1973
+ .sidebar {
1974
+ position: relative;
1975
+ height: auto;
1976
+ padding: 16px;
1977
+ border-right: 0;
1978
+ border-bottom: 1px solid var(--line);
1979
+ }
1980
+
1981
+ .brand {
1982
+ padding: 0 0 14px;
1983
+ }
1984
+
1985
+ .sidebar-label,
1986
+ .sidebar-footer {
1987
+ display: none;
1988
+ }
1989
+
1990
+ #entity-nav {
1991
+ display: flex;
1992
+ overflow-x: auto;
1993
+ }
1994
+
1995
+ .entity-link {
1996
+ flex: 0 0 auto;
1997
+ width: auto;
1998
+ }
1999
+
2000
+ .entity-link code {
2001
+ display: none;
2002
+ }
2003
+
2004
+ main {
2005
+ padding: 28px 16px 50px;
2006
+ }
2007
+
2008
+ .page-header {
2009
+ align-items: stretch;
2010
+ flex-direction: column;
2011
+ }
2012
+
2013
+ .header-actions {
2014
+ width: 100%;
2015
+ }
2016
+
2017
+ .connection-controls {
2018
+ grid-template-columns: 1fr;
2019
+ }
2020
+
2021
+ .connection-warning {
2022
+ text-align: left;
2023
+ }
2024
+
2025
+ .metrics {
2026
+ grid-template-columns: 1fr;
2027
+ }
2028
+
2029
+ .toolbar {
2030
+ align-items: stretch;
2031
+ flex-direction: column;
2032
+ }
2033
+
2034
+ .search {
2035
+ width: 100%;
2036
+ }
2037
+
2038
+ .listing-tools {
2039
+ align-items: stretch;
2040
+ flex-direction: column;
2041
+ width: 100%;
2042
+ }
2043
+
2044
+ .listing-mode {
2045
+ flex-basis: auto;
2046
+ }
2047
+
2048
+ .tag-filters {
2049
+ grid-template-columns: 1fr 1fr;
2050
+ }
2051
+
2052
+ .tag-filter-actions,
2053
+ .tag-filters > p {
2054
+ grid-column: 1 / -1;
2055
+ }
2056
+
2057
+ .toolbar-actions {
2058
+ justify-content: end;
2059
+ }
2060
+
2061
+ .dialog-body {
2062
+ display: block;
2063
+ overflow-y: auto;
2064
+ }
2065
+
2066
+ .editor-column,
2067
+ .field-reference {
2068
+ overflow: visible;
2069
+ }
2070
+
2071
+ .field-reference {
2072
+ border-top: 1px solid var(--line);
2073
+ border-left: 0;
2074
+ }
2075
+
2076
+ .mutual-toolbar {
2077
+ align-items: stretch;
2078
+ flex-direction: column;
2079
+ }
2080
+
2081
+ .mutual-toolbar label {
2082
+ width: 100%;
2083
+ }
2084
+
2085
+ .mutual-toolbar-actions {
2086
+ justify-content: end;
2087
+ }
2088
+ }
2089
+ `;
2090
+ var APP_JS = `
2091
+ const state = {
2092
+ meta: null,
2093
+ entity: null,
2094
+ items: [],
2095
+ currentCursor: null,
2096
+ nextCursor: null,
2097
+ cursorHistory: [],
2098
+ query: '',
2099
+ tagName: null,
2100
+ tagFilters: { group: '', query: '', start: '', end: '' },
2101
+ tagApplied: false,
2102
+ totalCount: 0,
2103
+ editorMode: 'create',
2104
+ editingId: null,
2105
+ connectionBusy: false,
2106
+ entityBusy: false,
2107
+ connectionVersion: 0,
2108
+ mutualSourceId: null,
2109
+ mutualTarget: null,
2110
+ mutualItems: [],
2111
+ mutualCurrentCursor: null,
2112
+ mutualNextCursor: null,
2113
+ mutualCursorHistory: [],
2114
+ mutualBusy: false,
2115
+ mutualEditorMode: 'create',
2116
+ mutualEditingId: null,
2117
+ };
2118
+
2119
+ const elements = {
2120
+ entityNav: document.querySelector('#entity-nav'),
2121
+ apiLabel: document.querySelector('#api-label'),
2122
+ content: document.querySelector('#content'),
2123
+ welcome: document.querySelector('#welcome'),
2124
+ pageTitle: document.querySelector('#page-title'),
2125
+ pageDescription: document.querySelector('#page-description'),
2126
+ stage: document.querySelector('#stage-select'),
2127
+ key: document.querySelector('#key-select'),
2128
+ connectionWarning: document.querySelector('#connection-warning'),
2129
+ refresh: document.querySelector('#refresh-button'),
2130
+ resultCount: document.querySelector('#result-count'),
2131
+ searchStatus: document.querySelector('#search-status'),
2132
+ uniqueCount: document.querySelector('#unique-count'),
2133
+ listingMode: document.querySelector('#listing-mode'),
2134
+ searchForm: document.querySelector('#search-form'),
2135
+ searchInput: document.querySelector('#search-input'),
2136
+ clearSearch: document.querySelector('#clear-search'),
2137
+ create: document.querySelector('#create-button'),
2138
+ tagFilterForm: document.querySelector('#tag-filter-form'),
2139
+ tagGroup: document.querySelector('#tag-group'),
2140
+ tagQuery: document.querySelector('#tag-query'),
2141
+ tagStart: document.querySelector('#tag-start'),
2142
+ tagEnd: document.querySelector('#tag-end'),
2143
+ clearTag: document.querySelector('#clear-tag'),
2144
+ notice: document.querySelector('#notice'),
2145
+ loading: document.querySelector('#loading'),
2146
+ empty: document.querySelector('#empty'),
2147
+ emptyMessage: document.querySelector('#empty-message'),
2148
+ tableWrap: document.querySelector('#table-wrap'),
2149
+ tableHead: document.querySelector('#table-head'),
2150
+ tableBody: document.querySelector('#table-body'),
2151
+ pagination: document.querySelector('#pagination'),
2152
+ pageLabel: document.querySelector('#page-label'),
2153
+ previous: document.querySelector('#previous-button'),
2154
+ next: document.querySelector('#next-button'),
2155
+ dialog: document.querySelector('#editor-dialog'),
2156
+ dialogEyebrow: document.querySelector('#dialog-eyebrow'),
2157
+ dialogTitle: document.querySelector('#dialog-title'),
2158
+ jsonEditor: document.querySelector('#json-editor'),
2159
+ editorError: document.querySelector('#editor-error'),
2160
+ fieldList: document.querySelector('#field-list'),
2161
+ save: document.querySelector('#save-button'),
2162
+ mutualDialog: document.querySelector('#mutual-dialog'),
2163
+ mutualTitle: document.querySelector('#mutual-title'),
2164
+ mutualClose: document.querySelector('#mutual-close'),
2165
+ mutualTarget: document.querySelector('#mutual-target'),
2166
+ mutualCreate: document.querySelector('#mutual-create'),
2167
+ mutualRefresh: document.querySelector('#mutual-refresh'),
2168
+ mutualNotice: document.querySelector('#mutual-notice'),
2169
+ mutualLoading: document.querySelector('#mutual-loading'),
2170
+ mutualEmpty: document.querySelector('#mutual-empty'),
2171
+ mutualTableWrap: document.querySelector('#mutual-table-wrap'),
2172
+ mutualTableBody: document.querySelector('#mutual-table-body'),
2173
+ mutualPagination: document.querySelector('#mutual-pagination'),
2174
+ mutualPageLabel: document.querySelector('#mutual-page-label'),
2175
+ mutualPrevious: document.querySelector('#mutual-previous'),
2176
+ mutualNext: document.querySelector('#mutual-next'),
2177
+ mutualEditorDialog: document.querySelector('#mutual-editor-dialog'),
2178
+ mutualEditorEyebrow: document.querySelector('#mutual-editor-eyebrow'),
2179
+ mutualEditorTitle: document.querySelector('#mutual-editor-title'),
2180
+ mutualEntityId: document.querySelector('#mutual-entity-id'),
2181
+ mutualJsonEditor: document.querySelector('#mutual-json-editor'),
2182
+ mutualEditorError: document.querySelector('#mutual-editor-error'),
2183
+ mutualFieldList: document.querySelector('#mutual-field-list'),
2184
+ mutualSave: document.querySelector('#mutual-save'),
2185
+ toast: document.querySelector('#toast'),
2186
+ };
2187
+
2188
+ function escapeHtml(value) {
2189
+ return String(value)
2190
+ .replaceAll('&', '&amp;')
2191
+ .replaceAll('<', '&lt;')
2192
+ .replaceAll('>', '&gt;')
2193
+ .replaceAll('"', '&quot;')
2194
+ .replaceAll("'", '&#039;');
2195
+ }
2196
+
2197
+ function plural(value, singular) {
2198
+ return value === 1 ? singular : singular + 's';
2199
+ }
2200
+
2201
+ function showToast(message, isError) {
2202
+ elements.toast.textContent = message;
2203
+ elements.toast.classList.toggle('error', Boolean(isError));
2204
+ elements.toast.classList.add('visible');
2205
+ window.clearTimeout(showToast.timer);
2206
+ showToast.timer = window.setTimeout(
2207
+ () => elements.toast.classList.remove('visible'),
2208
+ 3200,
2209
+ );
2210
+ }
2211
+
2212
+ function errorMessage(payload, response) {
2213
+ if (typeof payload === 'string' && payload.trim()) return payload;
2214
+ if (payload && typeof payload.message === 'string') return payload.message;
2215
+ if (payload && payload.details && payload.details.fieldErrors) {
2216
+ const fieldErrors = Object.entries(payload.details.fieldErrors)
2217
+ .filter((entry) => Array.isArray(entry[1]) && entry[1].length)
2218
+ .map((entry) => entry[0] + ': ' + entry[1].join(', '));
2219
+ if (fieldErrors.length) return fieldErrors.join('\\n');
2220
+ }
2221
+ return 'Request failed with status ' + response.status;
2222
+ }
2223
+
2224
+ async function api(path, options) {
2225
+ const response = await fetch(path, options);
2226
+ const contentType = response.headers.get('content-type') || '';
2227
+ const payload = contentType.includes('json')
2228
+ ? await response.json()
2229
+ : await response.text();
2230
+ if (!response.ok) throw new Error(errorMessage(payload, response));
2231
+ return payload;
2232
+ }
2233
+
2234
+ function renderNavigation() {
2235
+ elements.entityNav.innerHTML = state.meta.entities
2236
+ .map(
2237
+ (entity) =>
2238
+ '<button class="entity-link" type="button" data-entity="' +
2239
+ escapeHtml(entity.name) +
2240
+ '"><span>' +
2241
+ escapeHtml(entity.displayName) +
2242
+ '</span><code>' +
2243
+ escapeHtml(entity.name) +
2244
+ '</code></button>',
2245
+ )
2246
+ .join('');
2247
+ }
2248
+
2249
+ function renderConnection() {
2250
+ const connection = state.meta.connection;
2251
+ elements.stage.innerHTML = state.meta.stages
2252
+ .map(
2253
+ (stage) =>
2254
+ '<option value="' +
2255
+ escapeHtml(stage.id) +
2256
+ '">' +
2257
+ escapeHtml(stage.label) +
2258
+ '</option>',
2259
+ )
2260
+ .join('');
2261
+ elements.stage.value = connection.stageId;
2262
+ elements.key.innerHTML = connection.keys.length
2263
+ ? connection.keys
2264
+ .map(
2265
+ (key) =>
2266
+ '<option value="' +
2267
+ escapeHtml(key.id) +
2268
+ '">' +
2269
+ escapeHtml(key.label) +
2270
+ '</option>',
2271
+ )
2272
+ .join('')
2273
+ : '<option value="">No usable keys</option>';
2274
+ elements.key.value = connection.keyId || '';
2275
+ elements.stage.disabled = state.connectionBusy;
2276
+ elements.key.disabled = state.connectionBusy || connection.keys.length === 0;
2277
+ elements.apiLabel.textContent = connection.apiUrl;
2278
+ elements.connectionWarning.textContent = connection.warning || '';
2279
+ elements.connectionWarning.hidden = !connection.warning;
2280
+ }
2281
+
2282
+ function selectedEntity() {
2283
+ return state.meta.entities.find((entity) => entity.name === state.entity);
2284
+ }
2285
+
2286
+ function entityByName(name) {
2287
+ return state.meta.entities.find((entity) => entity.name === name);
2288
+ }
2289
+
2290
+ function mutualTargets(entity) {
2291
+ const targets = new Set((entity.mutuals || []).map((mutual) => mutual.entityType));
2292
+ state.meta.entities.forEach((candidate) => {
2293
+ if (
2294
+ (candidate.mutuals || []).some(
2295
+ (mutual) => mutual.entityType === entity.name,
2296
+ )
2297
+ ) {
2298
+ targets.add(candidate.name);
2299
+ }
2300
+ });
2301
+ return [...targets]
2302
+ .map(entityByName)
2303
+ .filter(Boolean)
2304
+ .sort((left, right) => left.displayName.localeCompare(right.displayName));
2305
+ }
2306
+
2307
+ function mutualDescriptor(entity, targetType) {
2308
+ const direct = (entity.mutuals || []).find(
2309
+ (mutual) => mutual.entityType === targetType,
2310
+ );
2311
+ const target = entityByName(targetType);
2312
+ const reverse = target
2313
+ ? (target.mutuals || []).find(
2314
+ (mutual) => mutual.entityType === entity.name,
2315
+ )
2316
+ : null;
2317
+ return (
2318
+ [direct, reverse].find(
2319
+ (mutual) =>
2320
+ mutual &&
2321
+ ((mutual.dataFields || []).length ||
2322
+ Object.keys(mutual.createTemplate || {}).length),
2323
+ ) ||
2324
+ direct ||
2325
+ reverse || {
2326
+ entityType: targetType,
2327
+ fields: [],
2328
+ dataFields: [],
2329
+ createTemplate: {},
2330
+ }
2331
+ );
2332
+ }
2333
+
2334
+ function renderListingControls() {
2335
+ const entity = selectedEntity();
2336
+ elements.listingMode.innerHTML =
2337
+ '<option value="">All entities</option>' +
2338
+ (entity.tags || [])
2339
+ .map(
2340
+ (tag) =>
2341
+ '<option value="' +
2342
+ escapeHtml(tag) +
2343
+ '">Tag \xB7 ' +
2344
+ escapeHtml(tag) +
2345
+ '</option>',
2346
+ )
2347
+ .join('');
2348
+ elements.listingMode.value = state.tagName || '';
2349
+ elements.tagFilterForm.hidden = !state.tagName;
2350
+ elements.searchForm.hidden = Boolean(state.tagName);
2351
+ elements.clearSearch.hidden = Boolean(state.tagName) || !state.query;
2352
+ elements.searchInput.disabled = !entity.searchable || Boolean(state.tagName);
2353
+ elements.searchForm.classList.toggle(
2354
+ 'disabled',
2355
+ !entity.searchable || Boolean(state.tagName),
2356
+ );
2357
+ elements.searchStatus.textContent = state.tagName
2358
+ ? 'Tag \xB7 ' + state.tagName
2359
+ : entity.searchable
2360
+ ? entity.searchFields.join(', ')
2361
+ : 'Unavailable';
2362
+ }
2363
+
2364
+ function setBusy(isBusy) {
2365
+ state.entityBusy = isBusy;
2366
+ elements.loading.hidden = !isBusy;
2367
+ elements.tableWrap.hidden = true;
2368
+ elements.empty.hidden = true;
2369
+ elements.pagination.hidden = true;
2370
+ elements.refresh.disabled = isBusy || state.connectionBusy;
2371
+ }
2372
+
2373
+ function setConnectionBusy(isBusy) {
2374
+ state.connectionBusy = isBusy;
2375
+ elements.stage.disabled = isBusy;
2376
+ elements.key.disabled =
2377
+ isBusy || !state.meta || state.meta.connection.keys.length === 0;
2378
+ elements.refresh.disabled = isBusy || state.entityBusy;
2379
+ }
2380
+
2381
+ function showNotice(message) {
2382
+ elements.notice.textContent = message || '';
2383
+ elements.notice.hidden = !message;
2384
+ }
2385
+
2386
+ function displayValue(value) {
2387
+ if (value === undefined || value === null) return '\u2014';
2388
+ if (typeof value === 'object') return JSON.stringify(value);
2389
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
2390
+ return String(value);
2391
+ }
2392
+
2393
+ function visibleFields(entity) {
2394
+ const configured = entity.fields
2395
+ .filter((field) => !field.relationship)
2396
+ .map((field) => field.name);
2397
+ if (configured.length) return configured.slice(0, 4);
2398
+ const firstData = state.items[0] && state.items[0].data;
2399
+ return firstData ? Object.keys(firstData).slice(0, 4) : [];
2400
+ }
2401
+
2402
+ function renderTable() {
2403
+ const entity = selectedEntity();
2404
+ const fields = visibleFields(entity);
2405
+ const hasMutuals = mutualTargets(entity).length > 0;
2406
+ elements.tableHead.innerHTML =
2407
+ '<tr><th>Entity ID</th>' +
2408
+ fields.map((field) => '<th>' + escapeHtml(field) + '</th>').join('') +
2409
+ '<th>Updated</th><th aria-label="Actions"></th></tr>';
2410
+
2411
+ elements.tableBody.innerHTML = state.items
2412
+ .map((item) => {
2413
+ const encodedId = encodeURIComponent(item.entityId);
2414
+ return (
2415
+ '<tr>' +
2416
+ '<td class="id-cell" title="' +
2417
+ escapeHtml(item.entityId) +
2418
+ '">' +
2419
+ escapeHtml(item.entityId) +
2420
+ '</td>' +
2421
+ fields
2422
+ .map((field) => {
2423
+ const value = displayValue(item.data && item.data[field]);
2424
+ return '<td title="' + escapeHtml(value) + '">' + escapeHtml(value) + '</td>';
2425
+ })
2426
+ .join('') +
2427
+ '<td class="date-cell">' +
2428
+ escapeHtml(item.updatedAt ? new Date(item.updatedAt).toLocaleString() : '\u2014') +
2429
+ '</td>' +
2430
+ '<td><div class="row-actions">' +
2431
+ (hasMutuals
2432
+ ? '<button class="row-action" type="button" data-action="mutuals" data-id="' +
2433
+ encodedId +
2434
+ '">Mutuals</button>'
2435
+ : '') +
2436
+ '<button class="row-action" type="button" data-action="edit" data-id="' +
2437
+ encodedId +
2438
+ '">Edit</button>' +
2439
+ '<button class="row-action danger" type="button" data-action="delete" data-id="' +
2440
+ encodedId +
2441
+ '">Delete</button>' +
2442
+ '</div></td></tr>'
2443
+ );
2444
+ })
2445
+ .join('');
2446
+ }
2447
+
2448
+ function renderResults() {
2449
+ const count = state.items.length;
2450
+ state.entityBusy = false;
2451
+ elements.refresh.disabled = state.connectionBusy;
2452
+ elements.resultCount.textContent =
2453
+ state.query && state.totalCount !== undefined
2454
+ ? String(state.totalCount)
2455
+ : String(state.totalCount || count);
2456
+ elements.loading.hidden = true;
2457
+ elements.empty.hidden = count > 0;
2458
+ elements.tableWrap.hidden = count === 0;
2459
+ elements.pagination.hidden =
2460
+ count === 0 ||
2461
+ (!state.tagName && Boolean(state.query)) ||
2462
+ (!state.nextCursor && !state.cursorHistory.length);
2463
+ elements.previous.disabled = state.cursorHistory.length === 0;
2464
+ elements.next.disabled = !state.nextCursor;
2465
+ elements.pageLabel.textContent = 'Page ' + (state.cursorHistory.length + 1);
2466
+ elements.emptyMessage.textContent =
2467
+ state.tagName && !state.tagApplied
2468
+ ? 'Set a tag group, sort prefix, or sort range to begin.'
2469
+ : state.tagName
2470
+ ? 'No records matched this tag query.'
2471
+ : state.query
2472
+ ? 'No records matched \u201C' + state.query + '\u201D.'
2473
+ : 'Create the first record for this entity type.';
2474
+ if (count) renderTable();
2475
+ }
2476
+
2477
+ async function loadEntities() {
2478
+ if (!state.entity) return;
2479
+ if (state.tagName && !state.tagApplied) {
2480
+ state.items = [];
2481
+ state.nextCursor = null;
2482
+ state.totalCount = 0;
2483
+ showNotice('');
2484
+ renderResults();
2485
+ return;
2486
+ }
2487
+ const connectionVersion = state.connectionVersion;
2488
+ setBusy(true);
2489
+ showNotice('');
2490
+ const params = new URLSearchParams({ limit: '25' });
2491
+ if (state.tagName) {
2492
+ Object.entries(state.tagFilters).forEach(([key, value]) => {
2493
+ if (value) params.set(key, value);
2494
+ });
2495
+ } else if (state.query) {
2496
+ params.set('query', state.query);
2497
+ }
2498
+ if (state.currentCursor) params.set('lastKey', state.currentCursor);
2499
+
2500
+ try {
2501
+ const path = state.tagName
2502
+ ? '/api/tags/' +
2503
+ encodeURIComponent(state.entity) +
2504
+ '/' +
2505
+ encodeURIComponent(state.tagName)
2506
+ : '/api/entities/' + encodeURIComponent(state.entity);
2507
+ const result = await api(
2508
+ path + '?' + params,
2509
+ );
2510
+ if (connectionVersion !== state.connectionVersion) return;
2511
+ state.items = Array.isArray(state.tagName ? result.entities : result.data)
2512
+ ? state.tagName
2513
+ ? result.entities
2514
+ : result.data
2515
+ : [];
2516
+ state.nextCursor = result.lastKey || null;
2517
+ state.totalCount =
2518
+ typeof result.filteredCount === 'number'
2519
+ ? result.filteredCount
2520
+ : typeof result.totalCount === 'number'
2521
+ ? result.totalCount
2522
+ : state.items.length;
2523
+ renderResults();
2524
+ } catch (error) {
2525
+ state.items = [];
2526
+ setBusy(false);
2527
+ showNotice(error.message);
2528
+ }
2529
+ }
2530
+
2531
+ function chooseEntity(name) {
2532
+ state.entity = name;
2533
+ state.query = '';
2534
+ state.tagName = null;
2535
+ state.tagFilters = { group: '', query: '', start: '', end: '' };
2536
+ state.tagApplied = false;
2537
+ state.currentCursor = null;
2538
+ state.nextCursor = null;
2539
+ state.cursorHistory = [];
2540
+ const entity = selectedEntity();
2541
+
2542
+ document.querySelectorAll('.entity-link').forEach((button) => {
2543
+ button.classList.toggle('active', button.dataset.entity === name);
2544
+ });
2545
+ elements.content.hidden = false;
2546
+ elements.welcome.hidden = true;
2547
+ elements.pageTitle.textContent = entity.displayName;
2548
+ elements.pageDescription.textContent =
2549
+ 'Browse and manage ' + entity.name + ' entities.';
2550
+ elements.searchInput.value = '';
2551
+ elements.searchInput.placeholder = entity.searchable
2552
+ ? 'Search ' + entity.searchFields.join(', ')
2553
+ : 'Search is not configured';
2554
+ elements.uniqueCount.textContent = String(entity.uniqueFields.length);
2555
+ elements.tagGroup.value = '';
2556
+ elements.tagQuery.value = '';
2557
+ elements.tagStart.value = '';
2558
+ elements.tagEnd.value = '';
2559
+ renderListingControls();
2560
+ loadEntities();
2561
+ }
2562
+
2563
+ function resetListing() {
2564
+ state.currentCursor = null;
2565
+ state.nextCursor = null;
2566
+ state.cursorHistory = [];
2567
+ state.totalCount = 0;
2568
+ }
2569
+
2570
+ function clearTagFilters(shouldLoad = true) {
2571
+ state.tagFilters = { group: '', query: '', start: '', end: '' };
2572
+ state.tagApplied = false;
2573
+ elements.tagGroup.value = '';
2574
+ elements.tagQuery.value = '';
2575
+ elements.tagStart.value = '';
2576
+ elements.tagEnd.value = '';
2577
+ resetListing();
2578
+ if (shouldLoad) loadEntities();
2579
+ }
2580
+
2581
+ function changeListingMode(tagName) {
2582
+ state.tagName = tagName || null;
2583
+ state.query = '';
2584
+ state.tagApplied = false;
2585
+ elements.searchInput.value = '';
2586
+ clearTagFilters(false);
2587
+ renderListingControls();
2588
+ loadEntities();
2589
+ }
2590
+
2591
+ function applyTagFilters() {
2592
+ const filters = {
2593
+ group: elements.tagGroup.value.trim(),
2594
+ query: elements.tagQuery.value.trim(),
2595
+ start: elements.tagStart.value.trim(),
2596
+ end: elements.tagEnd.value.trim(),
2597
+ };
2598
+ if (!filters.group && !filters.query && !filters.start && !filters.end) {
2599
+ showToast('Provide a tag group, sort prefix, or sort range.', true);
2600
+ return;
2601
+ }
2602
+ if (filters.query && (filters.start || filters.end)) {
2603
+ showToast('Use either a sort prefix or a sort range, not both.', true);
2604
+ return;
2605
+ }
2606
+ state.tagFilters = filters;
2607
+ state.tagApplied = true;
2608
+ resetListing();
2609
+ loadEntities();
2610
+ }
2611
+
2612
+ async function switchStage(stageId) {
2613
+ const previousStageId = state.meta.connection.stageId;
2614
+ setConnectionBusy(true);
2615
+ try {
2616
+ const connection = await api('/api/connection', {
2617
+ method: 'POST',
2618
+ headers: { 'Content-Type': 'application/json' },
2619
+ body: JSON.stringify({ stageId }),
2620
+ });
2621
+ state.meta.connection = connection;
2622
+ state.meta.apiUrl = connection.apiUrl;
2623
+ state.connectionVersion += 1;
2624
+ resetListing();
2625
+ if (elements.mutualDialog.open) elements.mutualDialog.close();
2626
+ renderConnection();
2627
+ await loadEntities();
2628
+ const stage = state.meta.stages.find((candidate) => candidate.id === stageId);
2629
+ showToast('Connected to ' + (stage ? stage.label : 'stage') + '.');
2630
+ } catch (error) {
2631
+ elements.stage.value = previousStageId;
2632
+ showToast(error.message, true);
2633
+ } finally {
2634
+ setConnectionBusy(false);
2635
+ renderConnection();
2636
+ }
2637
+ }
2638
+
2639
+ async function switchKey(keyId) {
2640
+ const previousKeyId = state.meta.connection.keyId;
2641
+ setConnectionBusy(true);
2642
+ try {
2643
+ const connection = await api('/api/connection/key', {
2644
+ method: 'POST',
2645
+ headers: { 'Content-Type': 'application/json' },
2646
+ body: JSON.stringify({ keyId }),
2647
+ });
2648
+ state.meta.connection = connection;
2649
+ state.connectionVersion += 1;
2650
+ resetListing();
2651
+ if (elements.mutualDialog.open) elements.mutualDialog.close();
2652
+ renderConnection();
2653
+ await loadEntities();
2654
+ showToast('API key changed.');
2655
+ } catch (error) {
2656
+ elements.key.value = previousKeyId || '';
2657
+ showToast(error.message, true);
2658
+ } finally {
2659
+ setConnectionBusy(false);
2660
+ renderConnection();
2661
+ }
2662
+ }
2663
+
2664
+ function fieldReferenceHtml(fields, emptyMessage) {
2665
+ return fields.length
2666
+ ? fields
2667
+ .map(
2668
+ (field) =>
2669
+ '<div class="field"><div class="field-main"><code>' +
2670
+ escapeHtml(field.name) +
2671
+ '</code><span class="field-type">' +
2672
+ escapeHtml(field.type) +
2673
+ '</span></div><div class="field-meta">' +
2674
+ (field.required
2675
+ ? '<span class="badge required">Required</span>'
2676
+ : '<span class="badge">Optional</span>') +
2677
+ (field.relationship
2678
+ ? '<span class="badge relationship">Relationship</span>'
2679
+ : '') +
2680
+ (field.unique ? '<span class="badge unique">Unique</span>' : '') +
2681
+ '</div>' +
2682
+ (field.description
2683
+ ? '<p class="field-description">' +
2684
+ escapeHtml(field.description) +
2685
+ '</p>'
2686
+ : '') +
2687
+ '</div>',
2688
+ )
2689
+ .join('')
2690
+ : '<p class="field-description">' + escapeHtml(emptyMessage) + '</p>';
2691
+ }
2692
+
2693
+ function fieldReference(entity) {
2694
+ elements.fieldList.innerHTML = fieldReferenceHtml(
2695
+ entity.fields,
2696
+ 'No schema fields were discovered.',
2697
+ );
2698
+ }
2699
+
2700
+ function openEditor(mode, item) {
2701
+ const entity = selectedEntity();
2702
+ state.editorMode = mode;
2703
+ state.editingId = item ? item.entityId : null;
2704
+ elements.dialogEyebrow.textContent =
2705
+ mode === 'create' ? 'Create entity' : 'Update entity';
2706
+ elements.dialogTitle.textContent =
2707
+ mode === 'create'
2708
+ ? 'New ' + entity.displayName
2709
+ : entity.displayName + ' \xB7 ' + item.entityId;
2710
+ elements.save.textContent = mode === 'create' ? 'Create entity' : 'Save changes';
2711
+ elements.jsonEditor.value = JSON.stringify(
2712
+ mode === 'create' ? entity.createTemplate : item.data || {},
2713
+ null,
2714
+ 2,
2715
+ );
2716
+ elements.editorError.hidden = true;
2717
+ elements.editorError.textContent = '';
2718
+ fieldReference(entity);
2719
+ elements.dialog.showModal();
2720
+ window.setTimeout(() => elements.jsonEditor.focus(), 0);
2721
+ }
2722
+
2723
+ async function saveEntity() {
2724
+ let payload;
2725
+ try {
2726
+ payload = JSON.parse(elements.jsonEditor.value);
2727
+ if (!payload || Array.isArray(payload) || typeof payload !== 'object') {
2728
+ throw new Error('Entity data must be a JSON object.');
2729
+ }
2730
+ } catch (error) {
2731
+ elements.editorError.textContent =
2732
+ error instanceof SyntaxError ? 'Enter valid JSON: ' + error.message : error.message;
2733
+ elements.editorError.hidden = false;
2734
+ return;
2735
+ }
2736
+
2737
+ elements.save.disabled = true;
2738
+ elements.save.textContent =
2739
+ state.editorMode === 'create' ? 'Creating\u2026' : 'Saving\u2026';
2740
+ elements.editorError.hidden = true;
2741
+ try {
2742
+ const path =
2743
+ '/api/entities/' +
2744
+ encodeURIComponent(state.entity) +
2745
+ (state.editingId ? '/' + encodeURIComponent(state.editingId) : '');
2746
+ await api(path, {
2747
+ method: state.editorMode === 'create' ? 'POST' : 'PATCH',
2748
+ headers: { 'Content-Type': 'application/json' },
2749
+ body: JSON.stringify(payload),
2750
+ });
2751
+ elements.dialog.close();
2752
+ showToast(
2753
+ selectedEntity().displayName +
2754
+ (state.editorMode === 'create' ? ' created.' : ' updated.'),
2755
+ );
2756
+ await loadEntities();
2757
+ } catch (error) {
2758
+ elements.editorError.textContent = error.message;
2759
+ elements.editorError.hidden = false;
2760
+ } finally {
2761
+ elements.save.disabled = false;
2762
+ elements.save.textContent =
2763
+ state.editorMode === 'create' ? 'Create entity' : 'Save changes';
2764
+ }
2765
+ }
2766
+
2767
+ async function deleteEntity(id) {
2768
+ const entity = selectedEntity();
2769
+ if (
2770
+ !window.confirm(
2771
+ 'Delete ' + entity.displayName + ' \u201C' + id + '\u201D?\\n\\nThis cannot be undone.',
2772
+ )
2773
+ ) {
2774
+ return;
2775
+ }
2776
+
2777
+ try {
2778
+ await api(
2779
+ '/api/entities/' +
2780
+ encodeURIComponent(state.entity) +
2781
+ '/' +
2782
+ encodeURIComponent(id),
2783
+ { method: 'DELETE' },
2784
+ );
2785
+ showToast(entity.displayName + ' deleted.');
2786
+ await loadEntities();
2787
+ } catch (error) {
2788
+ showToast(error.message, true);
2789
+ }
2790
+ }
2791
+
2792
+ function resetMutualPaging() {
2793
+ state.mutualCurrentCursor = null;
2794
+ state.mutualNextCursor = null;
2795
+ state.mutualCursorHistory = [];
2796
+ }
2797
+
2798
+ function showMutualNotice(message) {
2799
+ elements.mutualNotice.textContent = message || '';
2800
+ elements.mutualNotice.hidden = !message;
2801
+ }
2802
+
2803
+ function setMutualBusy(isBusy) {
2804
+ state.mutualBusy = isBusy;
2805
+ elements.mutualLoading.hidden = !isBusy;
2806
+ elements.mutualEmpty.hidden = true;
2807
+ elements.mutualTableWrap.hidden = true;
2808
+ elements.mutualPagination.hidden = true;
2809
+ elements.mutualTarget.disabled = isBusy;
2810
+ elements.mutualCreate.disabled = isBusy;
2811
+ elements.mutualRefresh.disabled = isBusy;
2812
+ }
2813
+
2814
+ function renderMutualResults() {
2815
+ const count = state.mutualItems.length;
2816
+ state.mutualBusy = false;
2817
+ elements.mutualTarget.disabled = false;
2818
+ elements.mutualCreate.disabled = false;
2819
+ elements.mutualRefresh.disabled = false;
2820
+ elements.mutualLoading.hidden = true;
2821
+ elements.mutualEmpty.hidden = count > 0;
2822
+ elements.mutualTableWrap.hidden = count === 0;
2823
+ elements.mutualPagination.hidden =
2824
+ count === 0 ||
2825
+ (!state.mutualNextCursor && !state.mutualCursorHistory.length);
2826
+ elements.mutualPrevious.disabled = state.mutualCursorHistory.length === 0;
2827
+ elements.mutualNext.disabled = !state.mutualNextCursor;
2828
+ elements.mutualPageLabel.textContent =
2829
+ 'Page ' + (state.mutualCursorHistory.length + 1);
2830
+ elements.mutualTableBody.innerHTML = state.mutualItems
2831
+ .map((mutual) => {
2832
+ const data = displayValue(mutual.data || {});
2833
+ const mutualData = displayValue(mutual.mutualData || {});
2834
+ const encodedId = encodeURIComponent(mutual.entityId);
2835
+ return (
2836
+ '<tr>' +
2837
+ '<td class="id-cell" title="' +
2838
+ escapeHtml(mutual.entityId) +
2839
+ '">' +
2840
+ escapeHtml(mutual.entityId) +
2841
+ '</td>' +
2842
+ '<td class="json-cell">' +
2843
+ escapeHtml(data) +
2844
+ '</td>' +
2845
+ '<td class="json-cell">' +
2846
+ escapeHtml(mutualData) +
2847
+ '</td>' +
2848
+ '<td class="date-cell">' +
2849
+ escapeHtml(
2850
+ mutual.mutualUpdatedAt
2851
+ ? new Date(mutual.mutualUpdatedAt).toLocaleString()
2852
+ : '\u2014',
2853
+ ) +
2854
+ '</td>' +
2855
+ '<td><div class="row-actions">' +
2856
+ '<button class="row-action" type="button" data-mutual-action="edit" data-id="' +
2857
+ encodedId +
2858
+ '">Edit</button>' +
2859
+ '<button class="row-action danger" type="button" data-mutual-action="delete" data-id="' +
2860
+ encodedId +
2861
+ '">Delete</button>' +
2862
+ '</div></td></tr>'
2863
+ );
2864
+ })
2865
+ .join('');
2866
+ }
2867
+
2868
+ async function loadMutuals() {
2869
+ if (!state.mutualSourceId || !state.mutualTarget) return;
2870
+ const connectionVersion = state.connectionVersion;
2871
+ setMutualBusy(true);
2872
+ showMutualNotice('');
2873
+ const params = new URLSearchParams({ limit: '25' });
2874
+ if (state.mutualCurrentCursor) {
2875
+ params.set('lastKey', state.mutualCurrentCursor);
2876
+ }
2877
+ try {
2878
+ const result = await api(
2879
+ '/api/mutuals/' +
2880
+ encodeURIComponent(state.entity) +
2881
+ '/' +
2882
+ encodeURIComponent(state.mutualSourceId) +
2883
+ '/' +
2884
+ encodeURIComponent(state.mutualTarget) +
2885
+ '?' +
2886
+ params,
2887
+ );
2888
+ if (connectionVersion !== state.connectionVersion) return;
2889
+ state.mutualItems = Array.isArray(result.entities) ? result.entities : [];
2890
+ state.mutualNextCursor = result.lastKey || null;
2891
+ renderMutualResults();
2892
+ } catch (error) {
2893
+ state.mutualItems = [];
2894
+ setMutualBusy(false);
2895
+ showMutualNotice(error.message);
2896
+ }
2897
+ }
2898
+
2899
+ function openMutuals(id) {
2900
+ const entity = selectedEntity();
2901
+ const targets = mutualTargets(entity);
2902
+ if (!targets.length) {
2903
+ showToast('No mutual relationships are configured for this entity.', true);
2904
+ return;
2905
+ }
2906
+ state.mutualSourceId = id;
2907
+ state.mutualTarget = targets[0].name;
2908
+ state.mutualItems = [];
2909
+ resetMutualPaging();
2910
+ elements.mutualTitle.textContent = entity.displayName + ' \xB7 ' + id;
2911
+ elements.mutualTarget.innerHTML = targets
2912
+ .map(
2913
+ (target) =>
2914
+ '<option value="' +
2915
+ escapeHtml(target.name) +
2916
+ '">' +
2917
+ escapeHtml(target.displayName) +
2918
+ ' (' +
2919
+ escapeHtml(target.name) +
2920
+ ')</option>',
2921
+ )
2922
+ .join('');
2923
+ elements.mutualTarget.value = state.mutualTarget;
2924
+ elements.mutualDialog.showModal();
2925
+ loadMutuals();
2926
+ }
2927
+
2928
+ function openMutualEditor(mode, mutual) {
2929
+ const source = selectedEntity();
2930
+ const target = entityByName(state.mutualTarget);
2931
+ const descriptor = mutualDescriptor(source, state.mutualTarget);
2932
+ state.mutualEditorMode = mode;
2933
+ state.mutualEditingId = mutual ? mutual.entityId : null;
2934
+ elements.mutualEditorEyebrow.textContent =
2935
+ mode === 'create' ? 'Create mutual' : 'Update mutual';
2936
+ elements.mutualEditorTitle.textContent =
2937
+ mode === 'create'
2938
+ ? 'Link ' + source.displayName + ' to ' + target.displayName
2939
+ : target.displayName + ' \xB7 ' + mutual.entityId;
2940
+ elements.mutualEntityId.value = mutual ? mutual.entityId : '';
2941
+ elements.mutualEntityId.disabled = mode === 'edit';
2942
+ elements.mutualJsonEditor.value = JSON.stringify(
2943
+ mode === 'create'
2944
+ ? descriptor.createTemplate || {}
2945
+ : mutual.mutualData || {},
2946
+ null,
2947
+ 2,
2948
+ );
2949
+ elements.mutualFieldList.innerHTML = fieldReferenceHtml(
2950
+ descriptor.dataFields || [],
2951
+ 'This relationship has no configured mutual data fields. Use an empty JSON object.',
2952
+ );
2953
+ elements.mutualEditorError.textContent = '';
2954
+ elements.mutualEditorError.hidden = true;
2955
+ elements.mutualSave.textContent =
2956
+ mode === 'create' ? 'Create mutual' : 'Save mutual';
2957
+ elements.mutualEditorDialog.showModal();
2958
+ window.setTimeout(
2959
+ () =>
2960
+ (mode === 'create'
2961
+ ? elements.mutualEntityId
2962
+ : elements.mutualJsonEditor
2963
+ ).focus(),
2964
+ 0,
2965
+ );
2966
+ }
2967
+
2968
+ async function saveMutual() {
2969
+ const entityId = (
2970
+ state.mutualEditingId || elements.mutualEntityId.value
2971
+ ).trim();
2972
+ if (!entityId) {
2973
+ elements.mutualEditorError.textContent =
2974
+ 'Enter the related entity ID.';
2975
+ elements.mutualEditorError.hidden = false;
2976
+ return;
2977
+ }
2978
+ let payload;
2979
+ try {
2980
+ payload = JSON.parse(elements.mutualJsonEditor.value);
2981
+ if (!payload || Array.isArray(payload) || typeof payload !== 'object') {
2982
+ throw new Error('Mutual data must be a JSON object.');
2983
+ }
2984
+ } catch (error) {
2985
+ elements.mutualEditorError.textContent =
2986
+ error instanceof SyntaxError
2987
+ ? 'Enter valid JSON: ' + error.message
2988
+ : error.message;
2989
+ elements.mutualEditorError.hidden = false;
2990
+ return;
2991
+ }
2992
+
2993
+ elements.mutualSave.disabled = true;
2994
+ elements.mutualSave.textContent =
2995
+ state.mutualEditorMode === 'create' ? 'Creating\u2026' : 'Saving\u2026';
2996
+ elements.mutualEditorError.hidden = true;
2997
+ try {
2998
+ await api(
2999
+ '/api/mutuals/' +
3000
+ encodeURIComponent(state.entity) +
3001
+ '/' +
3002
+ encodeURIComponent(state.mutualSourceId) +
3003
+ '/' +
3004
+ encodeURIComponent(state.mutualTarget) +
3005
+ '/' +
3006
+ encodeURIComponent(entityId),
3007
+ {
3008
+ method: state.mutualEditorMode === 'create' ? 'POST' : 'PATCH',
3009
+ headers: { 'Content-Type': 'application/json' },
3010
+ body: JSON.stringify(payload),
3011
+ },
3012
+ );
3013
+ elements.mutualEditorDialog.close();
3014
+ showToast(
3015
+ state.mutualEditorMode === 'create'
3016
+ ? 'Mutual relationship created.'
3017
+ : 'Mutual relationship updated.',
3018
+ );
3019
+ await loadMutuals();
3020
+ } catch (error) {
3021
+ elements.mutualEditorError.textContent = error.message;
3022
+ elements.mutualEditorError.hidden = false;
3023
+ } finally {
3024
+ elements.mutualSave.disabled = false;
3025
+ elements.mutualSave.textContent =
3026
+ state.mutualEditorMode === 'create' ? 'Create mutual' : 'Save mutual';
3027
+ }
3028
+ }
3029
+
3030
+ async function deleteMutual(mutual) {
3031
+ const target = entityByName(state.mutualTarget);
3032
+ if (
3033
+ !window.confirm(
3034
+ 'Delete the mutual relationship to ' +
3035
+ target.displayName +
3036
+ ' \u201C' +
3037
+ mutual.entityId +
3038
+ '\u201D?\\n\\nThis cannot be undone.',
3039
+ )
3040
+ ) {
3041
+ return;
3042
+ }
3043
+ try {
3044
+ await api(
3045
+ '/api/mutuals/' +
3046
+ encodeURIComponent(state.entity) +
3047
+ '/' +
3048
+ encodeURIComponent(state.mutualSourceId) +
3049
+ '/' +
3050
+ encodeURIComponent(state.mutualTarget) +
3051
+ '/' +
3052
+ encodeURIComponent(mutual.entityId),
3053
+ { method: 'DELETE' },
3054
+ );
3055
+ showToast('Mutual relationship deleted.');
3056
+ await loadMutuals();
3057
+ } catch (error) {
3058
+ showToast(error.message, true);
3059
+ }
3060
+ }
3061
+
3062
+ elements.entityNav.addEventListener('click', (event) => {
3063
+ const button = event.target.closest('[data-entity]');
3064
+ if (button) chooseEntity(button.dataset.entity);
3065
+ });
3066
+
3067
+ elements.refresh.addEventListener('click', () => loadEntities());
3068
+ elements.stage.addEventListener('change', () => switchStage(elements.stage.value));
3069
+ elements.key.addEventListener('change', () => switchKey(elements.key.value));
3070
+ elements.listingMode.addEventListener('change', () =>
3071
+ changeListingMode(elements.listingMode.value),
3072
+ );
3073
+ elements.create.addEventListener('click', () => openEditor('create'));
3074
+ elements.save.addEventListener('click', saveEntity);
3075
+
3076
+ elements.tagFilterForm.addEventListener('submit', (event) => {
3077
+ event.preventDefault();
3078
+ applyTagFilters();
3079
+ });
3080
+ elements.clearTag.addEventListener('click', () => clearTagFilters());
3081
+
3082
+ elements.searchForm.addEventListener('submit', (event) => {
3083
+ event.preventDefault();
3084
+ if (!selectedEntity().searchable) return;
3085
+ state.query = elements.searchInput.value.trim();
3086
+ state.currentCursor = null;
3087
+ state.cursorHistory = [];
3088
+ elements.clearSearch.hidden = !state.query;
3089
+ loadEntities();
3090
+ });
3091
+
3092
+ elements.clearSearch.addEventListener('click', () => {
3093
+ state.query = '';
3094
+ elements.searchInput.value = '';
3095
+ elements.clearSearch.hidden = true;
3096
+ loadEntities();
3097
+ });
3098
+
3099
+ elements.next.addEventListener('click', () => {
3100
+ if (!state.nextCursor) return;
3101
+ state.cursorHistory.push(state.currentCursor);
3102
+ state.currentCursor = state.nextCursor;
3103
+ loadEntities();
3104
+ });
3105
+
3106
+ elements.previous.addEventListener('click', () => {
3107
+ if (!state.cursorHistory.length) return;
3108
+ state.currentCursor = state.cursorHistory.pop() || null;
3109
+ loadEntities();
3110
+ });
3111
+
3112
+ elements.tableBody.addEventListener('click', (event) => {
3113
+ const button = event.target.closest('[data-action]');
3114
+ if (!button) return;
3115
+ const id = decodeURIComponent(button.dataset.id);
3116
+ const item = state.items.find((candidate) => candidate.entityId === id);
3117
+ if (button.dataset.action === 'mutuals') openMutuals(id);
3118
+ if (button.dataset.action === 'edit' && item) openEditor('edit', item);
3119
+ if (button.dataset.action === 'delete') deleteEntity(id);
3120
+ });
3121
+
3122
+ elements.mutualClose.addEventListener('click', () =>
3123
+ elements.mutualDialog.close(),
3124
+ );
3125
+ elements.mutualCreate.addEventListener('click', () =>
3126
+ openMutualEditor('create'),
3127
+ );
3128
+ elements.mutualRefresh.addEventListener('click', loadMutuals);
3129
+ elements.mutualTarget.addEventListener('change', () => {
3130
+ state.mutualTarget = elements.mutualTarget.value;
3131
+ state.mutualItems = [];
3132
+ resetMutualPaging();
3133
+ loadMutuals();
3134
+ });
3135
+ elements.mutualNext.addEventListener('click', () => {
3136
+ if (!state.mutualNextCursor) return;
3137
+ state.mutualCursorHistory.push(state.mutualCurrentCursor);
3138
+ state.mutualCurrentCursor = state.mutualNextCursor;
3139
+ loadMutuals();
3140
+ });
3141
+ elements.mutualPrevious.addEventListener('click', () => {
3142
+ if (!state.mutualCursorHistory.length) return;
3143
+ state.mutualCurrentCursor =
3144
+ state.mutualCursorHistory.pop() || null;
3145
+ loadMutuals();
3146
+ });
3147
+ elements.mutualTableBody.addEventListener('click', (event) => {
3148
+ const button = event.target.closest('[data-mutual-action]');
3149
+ if (!button) return;
3150
+ const id = decodeURIComponent(button.dataset.id);
3151
+ const mutual = state.mutualItems.find(
3152
+ (candidate) => candidate.entityId === id,
3153
+ );
3154
+ if (!mutual) return;
3155
+ if (button.dataset.mutualAction === 'edit') {
3156
+ openMutualEditor('edit', mutual);
3157
+ }
3158
+ if (button.dataset.mutualAction === 'delete') deleteMutual(mutual);
3159
+ });
3160
+ elements.mutualSave.addEventListener('click', saveMutual);
3161
+
3162
+ elements.jsonEditor.addEventListener('keydown', (event) => {
3163
+ if (event.key === 'Tab') {
3164
+ event.preventDefault();
3165
+ const start = elements.jsonEditor.selectionStart;
3166
+ const end = elements.jsonEditor.selectionEnd;
3167
+ elements.jsonEditor.setRangeText(' ', start, end, 'end');
3168
+ }
3169
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') saveEntity();
3170
+ });
3171
+ elements.mutualJsonEditor.addEventListener('keydown', (event) => {
3172
+ if (event.key === 'Tab') {
3173
+ event.preventDefault();
3174
+ const start = elements.mutualJsonEditor.selectionStart;
3175
+ const end = elements.mutualJsonEditor.selectionEnd;
3176
+ elements.mutualJsonEditor.setRangeText(' ', start, end, 'end');
3177
+ }
3178
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') saveMutual();
3179
+ });
3180
+
3181
+ async function start() {
3182
+ try {
3183
+ state.meta = await api('/api/meta');
3184
+ renderConnection();
3185
+ renderNavigation();
3186
+ if (state.meta.entities.length) chooseEntity(state.meta.entities[0].name);
3187
+ } catch (error) {
3188
+ elements.apiLabel.textContent = 'Configuration error';
3189
+ showToast(error.message, true);
3190
+ }
3191
+ }
3192
+
3193
+ start();
3194
+ `;
3195
+
3196
+ // commands/devtool/server.ts
3197
+ var DEFAULT_DEVTOOL_PORT = 6767;
3198
+ var MAX_BODY_BYTES = 1024 * 1024;
3199
+ function send(response, status, body, contentType) {
3200
+ response.writeHead(status, {
3201
+ "Content-Type": contentType,
3202
+ "Content-Length": Buffer.byteLength(body),
3203
+ "Cache-Control": "no-store",
3204
+ "X-Content-Type-Options": "nosniff"
3205
+ });
3206
+ response.end(body);
3207
+ }
3208
+ function sendJson(response, status, value) {
3209
+ send(
3210
+ response,
3211
+ status,
3212
+ JSON.stringify(value),
3213
+ "application/json; charset=utf-8"
3214
+ );
3215
+ }
3216
+ async function requestBody(request) {
3217
+ if (request.method === "GET" || request.method === "HEAD") return void 0;
3218
+ const chunks = [];
3219
+ let length = 0;
3220
+ for await (const chunk of request) {
3221
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
3222
+ length += buffer.length;
3223
+ if (length > MAX_BODY_BYTES) {
3224
+ throw new Error("REQUEST_TOO_LARGE");
3225
+ }
3226
+ chunks.push(buffer);
3227
+ }
3228
+ return Buffer.concat(chunks);
3229
+ }
3230
+ function entityRoute(pathname) {
3231
+ const match = pathname.match(/^\/api\/entities\/([^/]+)(?:\/([^/]+))?$/);
3232
+ if (!match) return void 0;
3233
+ try {
3234
+ return {
3235
+ entityType: decodeURIComponent(match[1]),
3236
+ entityId: match[2] ? decodeURIComponent(match[2]) : void 0
3237
+ };
3238
+ } catch {
3239
+ return void 0;
3240
+ }
3241
+ }
3242
+ function tagRoute(pathname) {
3243
+ const match = pathname.match(/^\/api\/tags\/([^/]+)\/([^/]+)$/);
3244
+ if (!match) return void 0;
3245
+ try {
3246
+ return {
3247
+ entityType: decodeURIComponent(match[1]),
3248
+ tagName: decodeURIComponent(match[2])
3249
+ };
3250
+ } catch {
3251
+ return void 0;
3252
+ }
3253
+ }
3254
+ function mutualRoute(pathname) {
3255
+ const match = pathname.match(
3256
+ /^\/api\/mutuals\/([^/]+)\/([^/]+)\/([^/]+)(?:\/([^/]+))?$/
3257
+ );
3258
+ if (!match) return void 0;
3259
+ try {
3260
+ return {
3261
+ byEntityType: decodeURIComponent(match[1]),
3262
+ byEntityId: decodeURIComponent(match[2]),
3263
+ entityType: decodeURIComponent(match[3]),
3264
+ entityId: match[4] ? decodeURIComponent(match[4]) : void 0
3265
+ };
3266
+ } catch {
3267
+ return void 0;
3268
+ }
3269
+ }
3270
+ function createDevtoolServer(options) {
3271
+ const host = options.host ?? "127.0.0.1";
3272
+ const configuredPort = options.port ?? DEFAULT_DEVTOOL_PORT;
3273
+ const allowedEntities = new Set(options.entities.map(({ name }) => name));
3274
+ const allowedTags = new Map(
3275
+ options.entities.map(({ name, tags }) => [name, new Set(tags ?? [])])
3276
+ );
3277
+ const staticStage = {
3278
+ id: "local",
3279
+ label: "Local",
3280
+ source: "local"
3281
+ };
3282
+ const staticKey = options.apiKey ? {
3283
+ id: "manual",
3284
+ label: "Manual key",
3285
+ value: options.apiKey
3286
+ } : void 0;
3287
+ const connections = options.connections ?? {
3288
+ stages: [staticStage],
3289
+ initialStage: staticStage,
3290
+ initialConnection: {
3291
+ apiUrl: options.apiUrl ?? "http://localhost:3000/api",
3292
+ keys: staticKey ? [staticKey] : []
3293
+ },
3294
+ resolve: async () => ({
3295
+ apiUrl: options.apiUrl ?? "http://localhost:3000/api",
3296
+ keys: staticKey ? [staticKey] : []
3297
+ })
3298
+ };
3299
+ let active = {
3300
+ stage: connections.initialStage,
3301
+ connection: connections.initialConnection,
3302
+ keyId: connections.initialConnection.keys[0]?.id
3303
+ };
3304
+ const publicConnection = () => ({
3305
+ stageId: active.stage.id,
3306
+ apiUrl: active.connection.apiUrl.replace(/\/+$/, ""),
3307
+ keyId: active.keyId,
3308
+ keys: active.connection.keys.map(({ id, label, policy }) => ({
3309
+ id,
3310
+ label,
3311
+ policy
3312
+ })),
3313
+ warning: active.connection.warning
3314
+ });
3315
+ const server = createServer(async (request, response) => {
3316
+ const requestUrl = new URL(request.url ?? "/", `http://${host}`);
3317
+ if (request.method === "GET" && requestUrl.pathname === "/") {
3318
+ response.setHeader(
3319
+ "Content-Security-Policy",
3320
+ "default-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; base-uri 'none'; frame-ancestors 'none'"
3321
+ );
3322
+ return send(response, 200, INDEX_HTML, "text/html; charset=utf-8");
3323
+ }
3324
+ if (request.method === "GET" && requestUrl.pathname === "/styles.css") {
3325
+ return send(response, 200, STYLES_CSS, "text/css; charset=utf-8");
3326
+ }
3327
+ if (request.method === "GET" && requestUrl.pathname === "/app.js") {
3328
+ return send(response, 200, APP_JS, "text/javascript; charset=utf-8");
3329
+ }
3330
+ if (request.method === "GET" && requestUrl.pathname === "/favicon.ico") {
3331
+ response.writeHead(204);
3332
+ return response.end();
3333
+ }
3334
+ if (request.method === "GET" && requestUrl.pathname === "/api/meta") {
3335
+ return sendJson(response, 200, {
3336
+ apiUrl: publicConnection().apiUrl,
3337
+ entities: options.entities,
3338
+ stages: connections.stages,
3339
+ connection: publicConnection()
3340
+ });
3341
+ }
3342
+ if (request.method === "POST" && requestUrl.pathname === "/api/connection") {
3343
+ try {
3344
+ const body = await requestBody(request);
3345
+ const payload = JSON.parse(body?.toString("utf8") || "{}");
3346
+ const stage = connections.stages.find(
3347
+ ({ id }) => id === payload.stageId
3348
+ );
3349
+ if (!stage) {
3350
+ return sendJson(response, 400, { message: "Unknown stage" });
3351
+ }
3352
+ const connection = await connections.resolve(stage.id);
3353
+ active = {
3354
+ stage,
3355
+ connection,
3356
+ keyId: connection.keys[0]?.id
3357
+ };
3358
+ return sendJson(response, 200, publicConnection());
3359
+ } catch (error) {
3360
+ if (error.message === "REQUEST_TOO_LARGE") {
3361
+ return sendJson(response, 413, {
3362
+ message: "Request body exceeds the 1 MB limit"
3363
+ });
3364
+ }
3365
+ return sendJson(response, 502, {
3366
+ message: error instanceof Error ? error.message : "Could not connect to this stage"
3367
+ });
3368
+ }
3369
+ }
3370
+ if (request.method === "POST" && requestUrl.pathname === "/api/connection/key") {
3371
+ try {
3372
+ const body = await requestBody(request);
3373
+ const payload = JSON.parse(body?.toString("utf8") || "{}");
3374
+ if (payload.keyId !== void 0 && !active.connection.keys.some(({ id }) => id === payload.keyId)) {
3375
+ return sendJson(response, 400, { message: "Unknown API key" });
3376
+ }
3377
+ active.keyId = payload.keyId;
3378
+ return sendJson(response, 200, publicConnection());
3379
+ } catch {
3380
+ return sendJson(response, 400, { message: "Invalid request body" });
3381
+ }
3382
+ }
3383
+ const entity = entityRoute(requestUrl.pathname);
3384
+ const tag = tagRoute(requestUrl.pathname);
3385
+ const mutual = mutualRoute(requestUrl.pathname);
3386
+ if (!entity && !tag && !mutual) {
3387
+ return sendJson(response, 404, { message: "Not found" });
3388
+ }
3389
+ let requestedTypes;
3390
+ if (entity) requestedTypes = [entity.entityType];
3391
+ else if (tag) requestedTypes = [tag.entityType];
3392
+ else if (mutual) {
3393
+ requestedTypes = [mutual.byEntityType, mutual.entityType];
3394
+ } else {
3395
+ return sendJson(response, 404, { message: "Not found" });
3396
+ }
3397
+ if (requestedTypes.some((entityType) => !allowedEntities.has(entityType))) {
3398
+ return sendJson(response, 404, { message: "Unknown entity type" });
3399
+ }
3400
+ if (tag && !allowedTags.get(tag.entityType)?.has(tag.tagName)) {
3401
+ return sendJson(response, 404, { message: "Unknown tag" });
3402
+ }
3403
+ const allowedMethods = entity || mutual ? ["GET", "POST", "PATCH", "DELETE"] : ["GET"];
3404
+ if (!allowedMethods.includes(request.method ?? "")) {
3405
+ response.setHeader("Allow", allowedMethods.join(", "));
3406
+ return sendJson(response, 405, { message: "Method not allowed" });
3407
+ }
3408
+ if (entity && (request.method === "PATCH" || request.method === "DELETE") && !entity.entityId) {
3409
+ return sendJson(response, 400, { message: "Entity ID is required" });
3410
+ }
3411
+ if (entity && request.method === "POST" && entity.entityId) {
3412
+ return sendJson(response, 405, { message: "Method not allowed" });
3413
+ }
3414
+ if (mutual && ["POST", "PATCH", "DELETE"].includes(request.method ?? "") && !mutual.entityId) {
3415
+ return sendJson(response, 400, {
3416
+ message: "Related entity ID is required"
3417
+ });
3418
+ }
3419
+ try {
3420
+ const body = await requestBody(request);
3421
+ const apiUrl = active.connection.apiUrl.replace(/\/+$/, "");
3422
+ let upstreamPath;
3423
+ if (entity) {
3424
+ upstreamPath = `/core/entity/${encodeURIComponent(entity.entityType)}${entity.entityId ? `/${encodeURIComponent(entity.entityId)}` : ""}`;
3425
+ } else if (tag) {
3426
+ upstreamPath = `/core/tag/${encodeURIComponent(tag.entityType)}/${encodeURIComponent(tag.tagName)}`;
3427
+ } else if (mutual) {
3428
+ upstreamPath = `/core/mutual/${encodeURIComponent(mutual.byEntityType)}/${encodeURIComponent(mutual.byEntityId)}/${encodeURIComponent(mutual.entityType)}${mutual.entityId ? `/${encodeURIComponent(mutual.entityId)}` : ""}`;
3429
+ } else {
3430
+ return sendJson(response, 404, { message: "Not found" });
3431
+ }
3432
+ const upstream = new URL(`${apiUrl}${upstreamPath}`);
3433
+ upstream.search = requestUrl.search;
3434
+ const headers = new Headers({ Accept: "application/json" });
3435
+ if (body?.length) headers.set("Content-Type", "application/json");
3436
+ const apiKey = active.connection.keys.find(
3437
+ ({ id }) => id === active.keyId
3438
+ )?.value;
3439
+ if (apiKey) headers.set("x-api-key", apiKey);
3440
+ const upstreamResponse = await fetch(upstream, {
3441
+ method: request.method,
3442
+ headers,
3443
+ body,
3444
+ redirect: "manual"
3445
+ });
3446
+ const responseBody = Buffer.from(await upstreamResponse.arrayBuffer());
3447
+ response.writeHead(upstreamResponse.status, {
3448
+ "Content-Type": upstreamResponse.headers.get("content-type") ?? "application/json; charset=utf-8",
3449
+ "Content-Length": responseBody.length,
3450
+ "Cache-Control": "no-store",
3451
+ "X-Content-Type-Options": "nosniff"
3452
+ });
3453
+ response.end(responseBody);
3454
+ } catch (error) {
3455
+ if (error.message === "REQUEST_TOO_LARGE") {
3456
+ return sendJson(response, 413, {
3457
+ message: "Request body exceeds the 1 MB limit"
3458
+ });
3459
+ }
3460
+ console.error("[monorise devtool] API proxy failed:", error);
3461
+ return sendJson(response, 502, {
3462
+ message: `Could not reach the Monorise API at ${active.connection.apiUrl.replace(/\/+$/, "")}`
3463
+ });
280
3464
  }
281
- }
3465
+ });
282
3466
  return {
283
- version: 2,
284
- datasets,
285
- unnamedMutuals: [...unnamedMutuals].sort(),
286
- schemaFingerprint: fingerprint(datasets)
3467
+ server,
3468
+ listen: () => new Promise(
3469
+ (resolve, reject) => {
3470
+ server.once("error", reject);
3471
+ server.listen(configuredPort, host, () => {
3472
+ server.off("error", reject);
3473
+ const address = server.address();
3474
+ resolve({
3475
+ host,
3476
+ port: address.port,
3477
+ url: `http://${host}:${address.port}`
3478
+ });
3479
+ });
3480
+ }
3481
+ ),
3482
+ close: () => new Promise((resolve, reject) => {
3483
+ server.close((error) => error ? reject(error) : resolve());
3484
+ })
287
3485
  };
288
3486
  }
289
3487
 
290
- // cli.ts
291
- import { fileURLToPath } from "url";
292
-
293
- // commands/utils/api-key-policies.ts
294
- import fs2 from "fs";
295
- import { createRequire } from "module";
296
- import path2 from "path";
297
- import { pathToFileURL } from "url";
298
- var require2 = createRequire(import.meta.url);
299
- var VALIDATE_API_KEY_POLICIES = /* @__PURE__ */ Symbol.for("monorise.validateApiKeyPolicies");
300
- function resolveApiKeysPath(projectRoot, apiKeys, configDir) {
301
- if (!apiKeys) return void 0;
302
- const absolutePath = path2.resolve(projectRoot, apiKeys);
303
- if (!fs2.existsSync(absolutePath) && !fs2.existsSync(`${absolutePath}.ts`) && !fs2.existsSync(`${absolutePath}.js`)) {
304
- throw new Error(
305
- `API key policies file not found: '${absolutePath}'. Please ensure 'apiKeys' in monorise.config.ts points to a valid file.`
306
- );
3488
+ // commands/devtool/sst.ts
3489
+ import { execFile } from "child_process";
3490
+ import { createHash as createHash2 } from "crypto";
3491
+ import fs5 from "fs";
3492
+ import path5 from "path";
3493
+ var SHELL_MARKER = "__MONORISE_DEVTOOL__";
3494
+ var ANSI_ESCAPE = new RegExp(
3495
+ `${String.fromCharCode(27)}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])`,
3496
+ "g"
3497
+ );
3498
+ var SHELL_DISCOVERY_SCRIPT = `
3499
+ const resources = [];
3500
+ try {
3501
+ const consolidated = JSON.parse(process.env.SST_RESOURCES_JSON || '{}');
3502
+ resources.push(...Object.entries(consolidated));
3503
+ } catch {}
3504
+ for (const [name, raw] of Object.entries(process.env)) {
3505
+ if (!name.startsWith('SST_RESOURCE_') || !raw) continue;
3506
+ try {
3507
+ resources.push([name.slice('SST_RESOURCE_'.length), JSON.parse(raw)]);
3508
+ } catch {}
3509
+ }
3510
+ const markedApis = resources
3511
+ .filter(([, value]) =>
3512
+ value?.kind === 'monorise-devtool' &&
3513
+ typeof value?.apiUrl === 'string'
3514
+ )
3515
+ .map(([name, value]) => ({
3516
+ name: value.coreId || name,
3517
+ url: value.apiUrl,
3518
+ }));
3519
+ const legacyApis = resources
3520
+ .filter(([name, value]) =>
3521
+ /monorise.*api/i.test(name) &&
3522
+ typeof value?.url === 'string'
3523
+ )
3524
+ .map(([name, value]) => ({
3525
+ name: name.replace(/-monorise-api$/i, ''),
3526
+ url: value.url,
3527
+ }));
3528
+ const apiKeys = resources.find(([name]) => name === 'API_KEYS')?.[1]?.value;
3529
+ const result = {
3530
+ apis: markedApis.length ? markedApis : legacyApis,
3531
+ apiKeys,
3532
+ };
3533
+ process.stdout.write(
3534
+ '\\n${SHELL_MARKER}' +
3535
+ Buffer.from(JSON.stringify(result)).toString('base64') +
3536
+ '\\n',
3537
+ );
3538
+ `;
3539
+ function findSstExecutable(root) {
3540
+ const binary = process.platform === "win32" ? "sst.cmd" : "sst";
3541
+ let current = root;
3542
+ while (true) {
3543
+ const candidate = path5.join(current, "node_modules", ".bin", binary);
3544
+ if (fs5.existsSync(candidate)) return candidate;
3545
+ const parent = path5.dirname(current);
3546
+ if (parent === current) return void 0;
3547
+ current = parent;
307
3548
  }
308
- const fromConfigDir = path2.relative(configDir, absolutePath);
309
- if (!fromConfigDir.startsWith("..") && !path2.isAbsolute(fromConfigDir)) {
310
- throw new Error(
311
- `API key policies file '${absolutePath}' is inside configDir '${configDir}', where every file is loaded as an entity config. Move it outside, e.g. './monorise/api-keys.ts'.`
312
- );
3549
+ }
3550
+ var runSst = (args, { cwd }) => new Promise((resolve, reject) => {
3551
+ const executable = findSstExecutable(cwd);
3552
+ if (!executable) {
3553
+ reject(new Error("SST is not installed in this project."));
3554
+ return;
313
3555
  }
314
- return absolutePath;
3556
+ execFile(
3557
+ executable,
3558
+ args,
3559
+ {
3560
+ cwd,
3561
+ env: {
3562
+ ...process.env,
3563
+ CI: "1",
3564
+ NO_COLOR: "1",
3565
+ SST_STAGE: process.env.SST_STAGE ?? "devtool"
3566
+ },
3567
+ maxBuffer: 10 * 1024 * 1024,
3568
+ timeout: 6e4
3569
+ },
3570
+ (error, stdout, stderr) => {
3571
+ if (error) {
3572
+ const message = stderr.trim().split("\n").filter(Boolean).at(-1);
3573
+ reject(
3574
+ new Error(
3575
+ message ? `SST command failed: ${message}` : `SST command failed: ${error.message}`
3576
+ )
3577
+ );
3578
+ return;
3579
+ }
3580
+ resolve(stdout);
3581
+ }
3582
+ );
3583
+ });
3584
+ function parseStageList(output) {
3585
+ const lines = output.replace(ANSI_ESCAPE, "").split(/\r?\n/);
3586
+ const stages = [];
3587
+ let readingStages = false;
3588
+ for (const line of lines) {
3589
+ const heading = line.match(/^\s*Stages:\s*(.*)$/);
3590
+ if (heading) {
3591
+ readingStages = true;
3592
+ const first = heading[1].replace(/\s+\(not deployed\)\s*$/, "").trim();
3593
+ if (first && !heading[1].includes("(not deployed)")) stages.push(first);
3594
+ continue;
3595
+ }
3596
+ if (!readingStages || !line.trim()) continue;
3597
+ if (/^\S[^:]*:/.test(line)) break;
3598
+ const stage = line.replace(/\s+\(not deployed\)\s*$/, "").trim();
3599
+ if (stage && !line.includes("(not deployed)")) stages.push(stage);
3600
+ }
3601
+ return [...new Set(stages)];
315
3602
  }
316
- function apiKeysFile(apiKeysPath) {
317
- return ["", ".ts", ".js"].map((extension) => `${apiKeysPath}${extension}`).find((file) => fs2.existsSync(file) && fs2.statSync(file).isFile()) ?? apiKeysPath;
3603
+ async function discoverSstStages(root, runner = runSst) {
3604
+ if (!fs5.existsSync(path5.join(root, "sst.config.ts")) && !fs5.existsSync(path5.join(root, "sst.config.js"))) {
3605
+ return [];
3606
+ }
3607
+ return parseStageList(await runner(["state", "list"], { cwd: root }));
318
3608
  }
319
- var importFresh = (file) => {
320
- delete require2.cache[file];
321
- return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
322
- };
323
- async function validateApiKeyPoliciesFile(apiKeysPath, configOutputPath) {
324
- const { default: generatedConfig } = await importFresh(configOutputPath);
325
- const { default: policies } = await importFresh(apiKeysFile(apiKeysPath));
326
- const validate = policies?.[VALIDATE_API_KEY_POLICIES];
327
- if (typeof validate !== "function") {
3609
+ function keyId(value) {
3610
+ return createHash2("sha256").update(value).digest("hex");
3611
+ }
3612
+ function parseApiKeys(raw) {
3613
+ if (typeof raw !== "string" || !raw.trim()) {
3614
+ return { keys: [], hashedCount: 0 };
3615
+ }
3616
+ const parsed = JSON.parse(raw);
3617
+ const entries = Array.isArray(parsed) ? [["full", parsed]] : parsed && typeof parsed === "object" ? Object.entries(parsed) : [];
3618
+ const keys = [];
3619
+ let hashedCount = 0;
3620
+ for (const [policy, policyKeys] of entries) {
3621
+ if (!Array.isArray(policyKeys)) continue;
3622
+ for (const value of policyKeys) {
3623
+ if (typeof value !== "string" || !value) continue;
3624
+ if (value.startsWith("sha256:")) {
3625
+ hashedCount += 1;
3626
+ continue;
3627
+ }
3628
+ const id = keyId(value);
3629
+ keys.push({
3630
+ id,
3631
+ label: `${policy} \xB7 ${id.slice(0, 8)}`,
3632
+ policy,
3633
+ value
3634
+ });
3635
+ }
3636
+ }
3637
+ return { keys, hashedCount };
3638
+ }
3639
+ function parseSecretList(output, secretName = "API_KEYS") {
3640
+ const lines = output.replace(ANSI_ESCAPE, "").split(/\r?\n/);
3641
+ let currentName;
3642
+ let currentValue = [];
3643
+ let found;
3644
+ const commit = () => {
3645
+ if (currentName === secretName) {
3646
+ found = currentValue.join("\n").trim();
3647
+ }
3648
+ currentName = void 0;
3649
+ currentValue = [];
3650
+ };
3651
+ for (const line of lines) {
3652
+ if (/^\s*#/.test(line)) {
3653
+ commit();
3654
+ continue;
3655
+ }
3656
+ const assignment = line.match(/^([A-Z][a-zA-Z0-9_]*)=(.*)$/);
3657
+ if (assignment) {
3658
+ commit();
3659
+ currentName = assignment[1];
3660
+ currentValue = [assignment[2]];
3661
+ continue;
3662
+ }
3663
+ if (currentName) currentValue.push(line);
3664
+ }
3665
+ commit();
3666
+ return found;
3667
+ }
3668
+ function parseShellDiscovery(output) {
3669
+ const markerIndex = output.lastIndexOf(SHELL_MARKER);
3670
+ if (markerIndex < 0) {
328
3671
  throw new Error(
329
- `API key policies file at '${apiKeysPath}' must default export the result of defineApiKeyPolicies(...).`
3672
+ "SST did not return Monorise resource metadata. Redeploy this stage with the current Monorise version."
330
3673
  );
331
3674
  }
332
- const errors = validate(generatedConfig.EntityConfig);
333
- if (errors.length) {
3675
+ const encoded = output.slice(markerIndex + SHELL_MARKER.length).split(/\r?\n/, 1)[0].trim();
3676
+ const decoded = JSON.parse(
3677
+ Buffer.from(encoded, "base64").toString("utf8")
3678
+ );
3679
+ const parsed = decoded && typeof decoded === "object" ? decoded : {};
3680
+ const apis = Array.isArray(parsed.apis) ? parsed.apis.filter(
3681
+ (api) => typeof api?.name === "string" && typeof api?.url === "string"
3682
+ ) : [];
3683
+ if (apis.length === 0) {
334
3684
  throw new Error(
335
- `Invalid API key policies in '${apiKeysPath}':
336
- - ${errors.join("\n - ")}`
3685
+ "No Monorise Core API was found in this SST stage. Redeploy it with the current Monorise version."
337
3686
  );
338
3687
  }
339
- console.log("Validated API key policies.");
340
- return policies;
341
- }
342
- function routePermissionDeclarations(policies, baseModuleNames) {
343
- const permissions = /* @__PURE__ */ new Set();
344
- for (const policy of Object.values(policies)) {
345
- const routes = policy?.routes;
346
- if (Array.isArray(routes)) {
347
- for (const permission of routes) permissions.add(permission);
348
- }
3688
+ if (apis.length > 1) {
3689
+ throw new Error(
3690
+ `This stage has multiple Monorise Core APIs (${apis.map(({ name }) => name).join(", ")}). Start the devtool with --api-url to choose one.`
3691
+ );
349
3692
  }
350
- if (permissions.size === 0) return "";
351
- const members = [...permissions].sort().map((permission) => ` ${JSON.stringify(permission)}: true;`).join("\n");
352
- return baseModuleNames.map(
353
- (moduleName) => `
354
- declare module '${moduleName}' {
355
- interface ApiKeyRoutePermissions {
356
- ${members}
3693
+ let apiUrl;
3694
+ try {
3695
+ apiUrl = new URL(apis[0].url);
3696
+ } catch {
3697
+ throw new Error("The discovered Monorise API URL is invalid.");
3698
+ }
3699
+ if (!["http:", "https:"].includes(apiUrl.protocol)) {
3700
+ throw new Error("The discovered Monorise API URL must use http or https.");
357
3701
  }
358
- }
359
- `
360
- ).join("");
361
- }
362
- function apiKeyPoliciesHandleParts(monoriseOutputDir, apiKeysPath) {
363
- if (!apiKeysPath) return { importLine: "", coreFactoryArg: "config" };
364
- const relativePath = path2.relative(monoriseOutputDir, apiKeysPath).replace(/\.(ts|js|mjs|cjs)$/, "");
365
- const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
366
3702
  return {
367
- importLine: `import apiKeyPolicies from '${importPath}';`,
368
- coreFactoryArg: "{ ...config, ApiKeyPolicies: apiKeyPolicies }"
3703
+ apiUrl: apiUrl.toString(),
3704
+ apiKeys: typeof parsed.apiKeys === "string" ? parsed.apiKeys : void 0
369
3705
  };
370
3706
  }
371
-
372
- // commands/utils/api-key-types.ts
373
- var literalUnion = (names) => names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never";
374
- function apiKeyTypeDeclarations(entities) {
375
- const enumKeys = new Map(
376
- entities.map((entity) => [entity.name, entity.enumKey])
377
- );
378
- const tagEntries = entities.map(
379
- ({ enumKey, config }) => `[Entity.${enumKey}]: ${literalUnion((config.tags ?? []).map((tag) => tag.name))};`
3707
+ async function resolveSstStage(root, stage, runner = runSst) {
3708
+ const output = await runner(
3709
+ ["shell", "--stage", stage, "--", "node", "-e", SHELL_DISCOVERY_SCRIPT],
3710
+ { cwd: root }
380
3711
  );
381
- const mutualFields = /* @__PURE__ */ new Map();
382
- const setDirection = (from, to, fields) => {
383
- const targets = mutualFields.get(from) ?? /* @__PURE__ */ new Map();
384
- if (!targets.has(to)) targets.set(to, fields);
385
- mutualFields.set(from, targets);
386
- };
387
- for (const pass of ["own", "reverse"]) {
388
- for (const { name, config } of entities) {
389
- for (const field of Object.values(config.mutual?.mutualFields ?? {})) {
390
- const shape = field.mutual?.mutualDataSchema?.shape;
391
- if (!shape || !enumKeys.has(field.entityType)) continue;
392
- const fields = Object.keys(shape);
393
- if (pass === "own") setDirection(name, field.entityType, fields);
394
- else setDirection(field.entityType, name, fields);
395
- }
3712
+ const discovered = parseShellDiscovery(output);
3713
+ try {
3714
+ const secrets = await runner(["secret", "list", "--stage", stage], {
3715
+ cwd: root
3716
+ });
3717
+ discovered.apiKeys = parseSecretList(secrets) ?? discovered.apiKeys;
3718
+ } catch (error) {
3719
+ if (!(error instanceof Error) || !/no secrets found/i.test(error.message)) {
3720
+ throw error;
396
3721
  }
397
3722
  }
398
- const mutualEntries = [...mutualFields].map(
399
- ([from, targets]) => `[Entity.${enumKeys.get(from)}]: {
400
- ${[...targets].map(
401
- ([to, fields]) => ` [Entity.${enumKeys.get(to)}]: ${literalUnion(fields)};`
402
- ).join("\n")}
403
- };`
404
- );
405
- return `
406
- export interface ApiKeyEntityTags {
407
- ${tagEntries.join("\n ")}
3723
+ let parsedKeys;
3724
+ try {
3725
+ parsedKeys = parseApiKeys(discovered.apiKeys);
3726
+ } catch {
3727
+ throw new Error(
3728
+ `The API_KEYS secret in stage '${stage}' is not valid JSON.`
3729
+ );
408
3730
  }
409
-
410
- export interface ApiKeyMutualDataFields {
411
- ${mutualEntries.join("\n ")}
412
- }`;
3731
+ const warning = parsedKeys.hashedCount > 0 ? `${parsedKeys.hashedCount} pre-hashed API ${parsedKeys.hashedCount === 1 ? "key is" : "keys are"} unavailable because original values cannot be recovered.` : parsedKeys.keys.length === 0 ? "No usable API keys were found for this stage." : void 0;
3732
+ return {
3733
+ apiUrl: discovered.apiUrl,
3734
+ keys: parsedKeys.keys,
3735
+ warning
3736
+ };
413
3737
  }
414
3738
 
415
- // commands/utils/detect-package.ts
416
- import fs3 from "fs";
417
- import path3 from "path";
418
- function detectCombinedPackage(startDir) {
419
- let dir = startDir;
420
- while (true) {
421
- if (fs3.existsSync(path3.join(dir, "node_modules", "monorise"))) {
422
- return true;
3739
+ // commands/devtool.ts
3740
+ async function importModule(filePath) {
3741
+ return import(pathToFileURL3(filePath).href);
3742
+ }
3743
+ async function loadProject(rootPath) {
3744
+ const root = path6.resolve(rootPath ?? process.cwd());
3745
+ const configPath = ["monorise.config.ts", "monorise.config.js"].map((name) => path6.join(root, name)).find((candidate) => fs6.existsSync(candidate));
3746
+ if (!configPath) {
3747
+ throw new Error(
3748
+ "Run this command from a Monorise project root (monorise.config.ts or monorise.config.js was not found)."
3749
+ );
3750
+ }
3751
+ const configModule = await importModule(configPath);
3752
+ const config = configModule.default;
3753
+ if (!config?.configDir) {
3754
+ throw new Error(`${path6.basename(configPath)} must define configDir.`);
3755
+ }
3756
+ const configDir = path6.resolve(root, config.configDir);
3757
+ if (!fs6.existsSync(configDir) || !fs6.statSync(configDir).isDirectory()) {
3758
+ throw new Error(`Entity config directory was not found: ${configDir}`);
3759
+ }
3760
+ const configFiles = fs6.readdirSync(configDir).filter(
3761
+ (file) => /\.(?:[cm]?[jt]s)$/.test(file) && !file.endsWith(".d.ts") && !/^index\./.test(file)
3762
+ ).sort();
3763
+ const entities = [];
3764
+ for (const file of configFiles) {
3765
+ const module = await importModule(path6.join(configDir, file));
3766
+ if (!module.default?.name) {
3767
+ throw new Error(
3768
+ `${path6.relative(root, path6.join(configDir, file))} must default export an entity config.`
3769
+ );
423
3770
  }
424
- const parent = path3.dirname(dir);
425
- if (parent === dir) break;
426
- dir = parent;
3771
+ entities.push(entityMetadata(module.default));
427
3772
  }
428
- return false;
3773
+ entities.sort(
3774
+ (left, right) => left.displayName.localeCompare(right.displayName)
3775
+ );
3776
+ return { root, config, entities };
429
3777
  }
430
-
431
- // commands/utils/search-manifest.ts
432
- import fs4 from "fs";
433
- import { createRequire as createRequire2 } from "module";
434
- import path4 from "path";
435
- import { pathToFileURL as pathToFileURL2 } from "url";
436
- function searchDefaultsDeclaration(defaults) {
437
- return `const SearchDefaults = ${JSON.stringify(defaults ?? {})};`;
3778
+ function openBrowser(url) {
3779
+ const command = process.platform === "darwin" ? { executable: "open", args: [url] } : process.platform === "win32" ? { executable: "cmd", args: ["/c", "start", "", url] } : { executable: "xdg-open", args: [url] };
3780
+ const child = spawn(command.executable, command.args, {
3781
+ detached: true,
3782
+ stdio: "ignore"
3783
+ });
3784
+ child.on("error", () => {
3785
+ console.warn(
3786
+ `Could not open a browser automatically. Open ${url} instead.`
3787
+ );
3788
+ });
3789
+ child.unref();
438
3790
  }
439
- async function loadProjectBase(projectRoot) {
440
- const name = detectCombinedPackage(projectRoot) ? "monorise/base" : "../base/index.js";
441
- const require3 = createRequire2(path4.join(projectRoot, "package.json"));
442
- const base = await import(pathToFileURL2(require3.resolve(name)).href);
443
- if (typeof base.searchConfigHash !== "function") {
444
- throw new Error(
445
- `'search' needs a newer ${name}: this version doesn't support the search index.`
3791
+ async function runDevtoolCommand(options = {}) {
3792
+ const { root, config, entities } = await loadProject(options.rootPath);
3793
+ if (entities.length === 0) {
3794
+ throw new Error("No entity config files were found.");
3795
+ }
3796
+ const configuredApiUrl = options.apiUrl ?? process.env.MONORISE_API_URL ?? process.env.API_BASE_URL ?? config.devtool?.apiUrl;
3797
+ const apiUrl = configuredApiUrl ?? "http://localhost:3000/api";
3798
+ const apiKey = options.apiKey ?? process.env.MONORISE_API_KEY ?? process.env.X_API_KEY;
3799
+ const port = options.port ?? config.devtool?.port ?? DEFAULT_DEVTOOL_PORT;
3800
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
3801
+ throw new Error(`Invalid devtool port: ${port}`);
3802
+ }
3803
+ let parsedApiUrl;
3804
+ try {
3805
+ parsedApiUrl = new URL(apiUrl);
3806
+ } catch {
3807
+ throw new Error(`Invalid Monorise API URL: ${apiUrl}`);
3808
+ }
3809
+ if (!["http:", "https:"].includes(parsedApiUrl.protocol)) {
3810
+ throw new Error("The Monorise API URL must use http or https.");
3811
+ }
3812
+ const manualKey = apiKey ? {
3813
+ id: "manual",
3814
+ label: "Manual key",
3815
+ value: apiKey
3816
+ } : void 0;
3817
+ const localStage = {
3818
+ id: "local",
3819
+ label: configuredApiUrl ? "Configured URL" : "Local app proxy",
3820
+ source: "local"
3821
+ };
3822
+ const localConnection = {
3823
+ apiUrl: parsedApiUrl.toString(),
3824
+ keys: manualKey ? [manualKey] : []
3825
+ };
3826
+ let deployedStages = [];
3827
+ try {
3828
+ deployedStages = await discoverSstStages(root);
3829
+ } catch (error) {
3830
+ console.warn(
3831
+ `Could not discover deployed SST stages: ${error instanceof Error ? error.message : String(error)}`
446
3832
  );
447
3833
  }
448
- return base;
449
- }
450
- async function writeSearchManifest(monoriseOutputDir, projectRoot, configs, defaults) {
451
- const manifestPath = path4.join(monoriseOutputDir, "search-manifest.json");
452
- const indexed = configs.filter((config) => config.search);
453
- if (!indexed.length) {
454
- fs4.rmSync(manifestPath, { force: true });
455
- return;
3834
+ const stageSummaries = [
3835
+ localStage,
3836
+ ...deployedStages.map((stage) => ({
3837
+ id: `sst:${stage}`,
3838
+ label: stage,
3839
+ source: "sst"
3840
+ }))
3841
+ ];
3842
+ const resolveStage = async (stageId) => {
3843
+ if (stageId === localStage.id) return localConnection;
3844
+ const stage = stageSummaries.find(({ id }) => id === stageId);
3845
+ if (!stage || stage.source !== "sst") {
3846
+ throw new Error(`Unknown SST stage: ${stageId}`);
3847
+ }
3848
+ const resolved = await resolveSstStage(root, stage.label);
3849
+ if (manualKey && !resolved.keys.some(({ value }) => value === manualKey.value)) {
3850
+ resolved.keys.unshift(manualKey);
3851
+ }
3852
+ return resolved;
3853
+ };
3854
+ const requestedStageId = options.stage ? `sst:${options.stage}` : "local";
3855
+ const initialStage = stageSummaries.find(({ id }) => id === requestedStageId) ?? localStage;
3856
+ if (options.stage && initialStage === localStage) {
3857
+ throw new Error(
3858
+ `SST stage '${options.stage}' was not found for the current credentials.`
3859
+ );
456
3860
  }
457
- const base = await loadProjectBase(projectRoot);
458
- if (defaults !== void 0) {
459
- base.validateSearchSettings(defaults, "monorise.config.ts");
3861
+ const initialConnection = initialStage.id === "local" ? localConnection : await resolveStage(initialStage.id);
3862
+ const connections = {
3863
+ stages: stageSummaries,
3864
+ initialStage,
3865
+ initialConnection,
3866
+ resolve: resolveStage
3867
+ };
3868
+ const devtool = createDevtoolServer({
3869
+ entities,
3870
+ connections,
3871
+ port
3872
+ });
3873
+ const address = await devtool.listen();
3874
+ console.log("");
3875
+ console.log(`Monorise Devtool is ready at ${address.url}`);
3876
+ console.log(
3877
+ `Connection: ${initialStage.label} (${initialConnection.apiUrl.replace(/\/$/, "")})`
3878
+ );
3879
+ if (deployedStages.length) {
3880
+ console.log(`SST stages: ${deployedStages.join(", ")}`);
460
3881
  }
461
- const manifest = {
462
- version: 1,
463
- entities: Object.fromEntries(
464
- indexed.map((config) => [
465
- config.name,
466
- base.searchConfigHash(
467
- base.resolveSearchConfig(config.search, defaults)
468
- )
469
- ])
470
- )
3882
+ console.log(`Entities: ${entities.map(({ name }) => name).join(", ")}`);
3883
+ console.log("Press Ctrl+C to stop.");
3884
+ console.log("");
3885
+ if (options.open !== false) openBrowser(address.url);
3886
+ const close = async () => {
3887
+ await devtool.close();
3888
+ process.exit(0);
471
3889
  };
472
- fs4.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}
473
- `);
3890
+ process.once("SIGINT", close);
3891
+ process.once("SIGTERM", close);
3892
+ return { ...address, close: devtool.close };
474
3893
  }
475
3894
 
476
3895
  // templates/root-tsconfig.ts
@@ -495,10 +3914,10 @@ var ROOT_TSCONFIG_TEMPLATE = {
495
3914
 
496
3915
  // cli.ts
497
3916
  var __filename = fileURLToPath(import.meta.url);
498
- var __dirname = path5.dirname(__filename);
499
- var TEMPLATES_DIR = path5.join(__dirname, "templates", "files");
3917
+ var __dirname = path7.dirname(__filename);
3918
+ var TEMPLATES_DIR = path7.join(__dirname, "templates", "files");
500
3919
  function readTemplate(filename) {
501
- return fs5.readFileSync(path5.join(TEMPLATES_DIR, filename), "utf-8");
3920
+ return fs7.readFileSync(path7.join(TEMPLATES_DIR, filename), "utf-8");
502
3921
  }
503
3922
  function kebabToCamel(str) {
504
3923
  return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
@@ -511,19 +3930,19 @@ function execCommand(command, cwd, stdio = "inherit") {
511
3930
  execSync(command, { cwd, stdio });
512
3931
  }
513
3932
  async function generateConfigFile(configDir, monoriseOutputDir, projectRoot, searchDefaults) {
514
- const configOutputPath = path5.join(monoriseOutputDir, "config.ts");
3933
+ const configOutputPath = path7.join(monoriseOutputDir, "config.ts");
515
3934
  const initialConfigContent = `
516
3935
  export enum Entity {}
517
3936
  export default {};
518
3937
  `;
519
- fs5.writeFileSync(configOutputPath, initialConfigContent);
520
- fs5.writeFileSync(
521
- path5.join(monoriseOutputDir, "index.ts"),
3938
+ fs7.writeFileSync(configOutputPath, initialConfigContent);
3939
+ fs7.writeFileSync(
3940
+ path7.join(monoriseOutputDir, "index.ts"),
522
3941
  `export * from './config';
523
3942
  export { default } from './config';
524
3943
  `
525
3944
  );
526
- const files = fs5.readdirSync(configDir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
3945
+ const files = fs7.readdirSync(configDir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
527
3946
  const names = /* @__PURE__ */ new Set();
528
3947
  const nameRegex = /^[a-z]+(-[a-z]+)*$/;
529
3948
  const imports = [];
@@ -537,10 +3956,10 @@ export { default } from './config';
537
3956
  const analyticsConfigs = [];
538
3957
  const apiKeyTypeEntities = [];
539
3958
  const searchConfigs = [];
540
- const relativePathToConfigDir = path5.relative(monoriseOutputDir, configDir);
3959
+ const relativePathToConfigDir = path7.relative(monoriseOutputDir, configDir);
541
3960
  const importPathPrefix = relativePathToConfigDir ? `${relativePathToConfigDir}/` : "./";
542
3961
  for (const file of files) {
543
- const fullPath = path5.join(configDir, file);
3962
+ const fullPath = path7.join(configDir, file);
544
3963
  const module = await import(fullPath);
545
3964
  const config = module.default;
546
3965
  if (!nameRegex.test(config.name)) {
@@ -641,7 +4060,7 @@ const config = {
641
4060
  export default config;
642
4061
  ${moduleAugmentations}
643
4062
  `;
644
- fs5.writeFileSync(configOutputPath, configOutputContent);
4063
+ fs7.writeFileSync(configOutputPath, configOutputContent);
645
4064
  writeAnalyticsManifest(monoriseOutputDir, analyticsConfigs);
646
4065
  await writeSearchManifest(
647
4066
  monoriseOutputDir,
@@ -650,8 +4069,8 @@ ${moduleAugmentations}
650
4069
  searchDefaults
651
4070
  );
652
4071
  console.log("Successfully generated config.ts!");
653
- const indexOutputPath = path5.join(monoriseOutputDir, "index.ts");
654
- fs5.writeFileSync(
4072
+ const indexOutputPath = path7.join(monoriseOutputDir, "index.ts");
4073
+ fs7.writeFileSync(
655
4074
  indexOutputPath,
656
4075
  `export * from './config';
657
4076
  export { default } from './config';
@@ -661,21 +4080,21 @@ export { default } from './config';
661
4080
  return configOutputPath;
662
4081
  }
663
4082
  async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir, apiKeysPath) {
664
- const handleOutputPath = path5.join(monoriseOutputDir, "handle.ts");
4083
+ const handleOutputPath = path7.join(monoriseOutputDir, "handle.ts");
665
4084
  const customRoutesPath = monoriseConfig.customRoutes;
666
4085
  let routesImportLine = "";
667
4086
  let appHandlerPayload = "{}";
668
4087
  if (customRoutesPath) {
669
- const absoluteCustomRoutesPath = path5.resolve(
4088
+ const absoluteCustomRoutesPath = path7.resolve(
670
4089
  projectRoot,
671
4090
  customRoutesPath
672
4091
  );
673
- if (!fs5.existsSync(absoluteCustomRoutesPath) && !fs5.existsSync(`${absoluteCustomRoutesPath}.ts`) && !fs5.existsSync(`${absoluteCustomRoutesPath}.js`)) {
4092
+ if (!fs7.existsSync(absoluteCustomRoutesPath) && !fs7.existsSync(`${absoluteCustomRoutesPath}.ts`) && !fs7.existsSync(`${absoluteCustomRoutesPath}.js`)) {
674
4093
  throw new Error(
675
4094
  `Custom routes file not found: '${absoluteCustomRoutesPath}'. Please ensure 'customRoutes' in monorise.config.ts points to a valid file.`
676
4095
  );
677
4096
  }
678
- let relativePathToRoutes = path5.relative(
4097
+ let relativePathToRoutes = path7.relative(
679
4098
  monoriseOutputDir,
680
4099
  absoluteCustomRoutesPath
681
4100
  );
@@ -719,30 +4138,30 @@ export const wsDisconnect = coreFactory.wsDisconnect;
719
4138
  export const wsDefault = coreFactory.wsDefault;
720
4139
  export const wsBroadcast = coreFactory.wsBroadcast;
721
4140
  `;
722
- fs5.writeFileSync(handleOutputPath, combinedContent);
4141
+ fs7.writeFileSync(handleOutputPath, combinedContent);
723
4142
  console.log("Successfully generated handle.ts!");
724
4143
  return handleOutputPath;
725
4144
  }
726
4145
  async function generateFiles(rootPath) {
727
- const baseDir = rootPath ? path5.resolve(rootPath) : process.cwd();
728
- const configFilePathTS = path5.join(baseDir, "monorise.config.ts");
729
- const configFilePathJS = path5.join(baseDir, "monorise.config.js");
4146
+ const baseDir = rootPath ? path7.resolve(rootPath) : process.cwd();
4147
+ const configFilePathTS = path7.join(baseDir, "monorise.config.ts");
4148
+ const configFilePathJS = path7.join(baseDir, "monorise.config.js");
730
4149
  let configFilePath;
731
- if (fs5.existsSync(configFilePathTS)) {
4150
+ if (fs7.existsSync(configFilePathTS)) {
732
4151
  configFilePath = configFilePathTS;
733
- } else if (fs5.existsSync(configFilePathJS)) {
4152
+ } else if (fs7.existsSync(configFilePathJS)) {
734
4153
  configFilePath = configFilePathJS;
735
4154
  } else {
736
4155
  throw new Error(
737
4156
  "Neither monorise.config.ts nor monorise.config.js found in the root of the project."
738
4157
  );
739
4158
  }
740
- const projectRoot = path5.dirname(configFilePath);
4159
+ const projectRoot = path7.dirname(configFilePath);
741
4160
  const monoriseConfigModule = await import(configFilePath);
742
4161
  const monoriseConfig = monoriseConfigModule.default;
743
- const configDir = path5.resolve(projectRoot, monoriseConfig.configDir);
744
- const monoriseOutputDir = path5.join(projectRoot, ".monorise");
745
- fs5.mkdirSync(monoriseOutputDir, { recursive: true });
4162
+ const configDir = path7.resolve(projectRoot, monoriseConfig.configDir);
4163
+ const monoriseOutputDir = path7.join(projectRoot, ".monorise");
4164
+ fs7.mkdirSync(monoriseOutputDir, { recursive: true });
746
4165
  const apiKeysPath = resolveApiKeysPath(
747
4166
  projectRoot,
748
4167
  monoriseConfig.apiKeys,
@@ -759,7 +4178,7 @@ async function generateFiles(rootPath) {
759
4178
  apiKeysPath,
760
4179
  configOutputPath
761
4180
  );
762
- fs5.appendFileSync(
4181
+ fs7.appendFileSync(
763
4182
  configOutputPath,
764
4183
  routePermissionDeclarations(policies, [
765
4184
  detectCombinedPackage(projectRoot) ? "monorise/base" : "../base/index.js"
@@ -830,29 +4249,29 @@ async function runInitCommand(rootPath) {
830
4249
  let projectName = "my-app";
831
4250
  let projectRoot;
832
4251
  if (rootPath) {
833
- projectRoot = path5.resolve(rootPath);
834
- projectName = path5.basename(projectRoot);
4252
+ projectRoot = path7.resolve(rootPath);
4253
+ projectName = path7.basename(projectRoot);
835
4254
  } else {
836
4255
  const args = process.argv.slice(2);
837
4256
  const nameIndex = args.indexOf("--name");
838
4257
  if (nameIndex > -1 && args[nameIndex + 1]) {
839
4258
  projectName = args[nameIndex + 1];
840
4259
  }
841
- projectRoot = path5.resolve(projectName);
4260
+ projectRoot = path7.resolve(projectName);
842
4261
  }
843
4262
  console.log(`
844
4263
  \u{1F680} Creating Monorise project: ${projectName}
845
4264
  `);
846
- if (fs5.existsSync(projectRoot)) {
4265
+ if (fs7.existsSync(projectRoot)) {
847
4266
  console.error(`Error: Directory ${projectName} already exists.`);
848
4267
  process.exit(1);
849
4268
  }
850
4269
  console.log("\u{1F4C1} Creating project structure...");
851
- fs5.mkdirSync(projectRoot, { recursive: true });
852
- fs5.mkdirSync(path5.join(projectRoot, "apps"), { recursive: true });
853
- fs5.mkdirSync(path5.join(projectRoot, "services", "core"), { recursive: true });
854
- fs5.mkdirSync(path5.join(projectRoot, "monorise", "configs"), { recursive: true });
855
- fs5.mkdirSync(path5.join(projectRoot, "monorise", "mutuals"), { recursive: true });
4270
+ fs7.mkdirSync(projectRoot, { recursive: true });
4271
+ fs7.mkdirSync(path7.join(projectRoot, "apps"), { recursive: true });
4272
+ fs7.mkdirSync(path7.join(projectRoot, "services", "core"), { recursive: true });
4273
+ fs7.mkdirSync(path7.join(projectRoot, "monorise", "configs"), { recursive: true });
4274
+ fs7.mkdirSync(path7.join(projectRoot, "monorise", "mutuals"), { recursive: true });
856
4275
  console.log("\u{1F4E6} Initializing root package.json...");
857
4276
  const rootPackageJson = {
858
4277
  name: projectName,
@@ -861,21 +4280,21 @@ async function runInitCommand(rootPath) {
861
4280
  private: true,
862
4281
  workspaces: ["apps/*", "services/*"]
863
4282
  };
864
- fs5.writeFileSync(
865
- path5.join(projectRoot, "package.json"),
4283
+ fs7.writeFileSync(
4284
+ path7.join(projectRoot, "package.json"),
866
4285
  JSON.stringify(rootPackageJson, null, 2)
867
4286
  );
868
4287
  console.log("\u2699\uFE0F Creating root tsconfig.json...");
869
- fs5.writeFileSync(
870
- path5.join(projectRoot, "tsconfig.json"),
4288
+ fs7.writeFileSync(
4289
+ path7.join(projectRoot, "tsconfig.json"),
871
4290
  JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2)
872
4291
  );
873
4292
  console.log("\n\u{1F4F1} Creating Next.js app in apps/web...");
874
- const nextAppDir = path5.join(projectRoot, "apps", "web");
4293
+ const nextAppDir = path7.join(projectRoot, "apps", "web");
875
4294
  try {
876
4295
  execCommand(
877
4296
  `npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias "#/*" --no-turbopack --yes`,
878
- path5.join(projectRoot, "apps")
4297
+ path7.join(projectRoot, "apps")
879
4298
  );
880
4299
  } catch (error) {
881
4300
  console.error("Failed to create Next.js app:", error);
@@ -896,32 +4315,32 @@ async function runInitCommand(rootPath) {
896
4315
  process.exit(1);
897
4316
  }
898
4317
  console.log("\u2699\uFE0F Creating monorise.config.ts...");
899
- fs5.writeFileSync(
900
- path5.join(projectRoot, "monorise.config.ts"),
4318
+ fs7.writeFileSync(
4319
+ path7.join(projectRoot, "monorise.config.ts"),
901
4320
  readTemplate("monorise.config.ts")
902
4321
  );
903
- fs5.writeFileSync(
904
- path5.join(projectRoot, "monorise", "api-keys.ts"),
4322
+ fs7.writeFileSync(
4323
+ path7.join(projectRoot, "monorise", "api-keys.ts"),
905
4324
  readTemplate("api-keys.ts")
906
4325
  );
907
4326
  console.log("\u{1F517} Creating team-membership mutual config...");
908
- fs5.writeFileSync(
909
- path5.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
4327
+ fs7.writeFileSync(
4328
+ path7.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
910
4329
  readTemplate("team-membership.mutual.ts")
911
4330
  );
912
4331
  console.log("\u{1F464} Creating starter User entity...");
913
- fs5.writeFileSync(
914
- path5.join(projectRoot, "monorise", "configs", "user.ts"),
4332
+ fs7.writeFileSync(
4333
+ path7.join(projectRoot, "monorise", "configs", "user.ts"),
915
4334
  readTemplate("user-entity.ts")
916
4335
  );
917
4336
  console.log("\u{1F465} Creating starter Team entity...");
918
- fs5.writeFileSync(
919
- path5.join(projectRoot, "monorise", "configs", "team.ts"),
4337
+ fs7.writeFileSync(
4338
+ path7.join(projectRoot, "monorise", "configs", "team.ts"),
920
4339
  readTemplate("team-entity.ts")
921
4340
  );
922
4341
  console.log("\u{1F527} Creating services/core/routes.ts...");
923
- fs5.writeFileSync(
924
- path5.join(projectRoot, "services", "core", "routes.ts"),
4342
+ fs7.writeFileSync(
4343
+ path7.join(projectRoot, "services", "core", "routes.ts"),
925
4344
  readTemplate("core-routes.ts")
926
4345
  );
927
4346
  const servicesPackageJson = {
@@ -929,13 +4348,13 @@ async function runInitCommand(rootPath) {
929
4348
  version: "0.0.0",
930
4349
  type: "module"
931
4350
  };
932
- fs5.writeFileSync(
933
- path5.join(projectRoot, "services", "core", "package.json"),
4351
+ fs7.writeFileSync(
4352
+ path7.join(projectRoot, "services", "core", "package.json"),
934
4353
  JSON.stringify(servicesPackageJson, null, 2)
935
4354
  );
936
4355
  console.log("\u2699\uFE0F Creating sst.config.ts with Monorise...");
937
- const sstConfigPath = path5.join(projectRoot, "sst.config.ts");
938
- fs5.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
4356
+ const sstConfigPath = path7.join(projectRoot, "sst.config.ts");
4357
+ fs7.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
939
4358
  console.log("\n\u2601\uFE0F Installing SST providers...");
940
4359
  try {
941
4360
  execCommand("npx sst install", projectRoot);
@@ -943,63 +4362,63 @@ async function runInitCommand(rootPath) {
943
4362
  console.warn("Warning: SST install failed, continuing anyway...");
944
4363
  }
945
4364
  console.log("\u{1F4C4} Creating example page in apps/web...");
946
- const webSrcAppDir = path5.join(projectRoot, "apps", "web", "src", "app");
947
- const webAppDir = path5.join(projectRoot, "apps", "web", "app");
948
- const pagePath = fs5.existsSync(webSrcAppDir) ? path5.join(webSrcAppDir, "page.tsx") : fs5.existsSync(webAppDir) ? path5.join(webAppDir, "page.tsx") : null;
4365
+ const webSrcAppDir = path7.join(projectRoot, "apps", "web", "src", "app");
4366
+ const webAppDir = path7.join(projectRoot, "apps", "web", "app");
4367
+ const pagePath = fs7.existsSync(webSrcAppDir) ? path7.join(webSrcAppDir, "page.tsx") : fs7.existsSync(webAppDir) ? path7.join(webAppDir, "page.tsx") : null;
949
4368
  if (pagePath) {
950
4369
  try {
951
- fs5.writeFileSync(pagePath, readTemplate("example-page.tsx"));
952
- console.log(`Created example page at ${path5.relative(projectRoot, pagePath)}`);
4370
+ fs7.writeFileSync(pagePath, readTemplate("example-page.tsx"));
4371
+ console.log(`Created example page at ${path7.relative(projectRoot, pagePath)}`);
953
4372
  } catch (error) {
954
4373
  console.warn("Warning: Could not create example page:", error);
955
4374
  }
956
4375
  } else {
957
4376
  console.warn("Warning: Could not find apps/web/src/app or apps/web/app directory");
958
4377
  }
959
- const webRoot = fs5.existsSync(webSrcAppDir) ? path5.join(projectRoot, "apps", "web", "src") : fs5.existsSync(webAppDir) ? path5.join(projectRoot, "apps", "web") : null;
4378
+ const webRoot = fs7.existsSync(webSrcAppDir) ? path7.join(projectRoot, "apps", "web", "src") : fs7.existsSync(webAppDir) ? path7.join(projectRoot, "apps", "web") : null;
960
4379
  if (webRoot) {
961
- const appDir = fs5.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
962
- fs5.mkdirSync(path5.join(webRoot, "components", "ui"), { recursive: true });
963
- fs5.mkdirSync(path5.join(webRoot, "lib"), { recursive: true });
4380
+ const appDir = fs7.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
4381
+ fs7.mkdirSync(path7.join(webRoot, "components", "ui"), { recursive: true });
4382
+ fs7.mkdirSync(path7.join(webRoot, "lib"), { recursive: true });
964
4383
  console.log("\u{1F310} Creating global components...");
965
- fs5.writeFileSync(
966
- path5.join(webRoot, "components", "global-initializer.tsx"),
4384
+ fs7.writeFileSync(
4385
+ path7.join(webRoot, "components", "global-initializer.tsx"),
967
4386
  readTemplate("global-initializer.tsx")
968
4387
  );
969
- fs5.writeFileSync(
970
- path5.join(webRoot, "components", "global-loader.tsx"),
4388
+ fs7.writeFileSync(
4389
+ path7.join(webRoot, "components", "global-loader.tsx"),
971
4390
  readTemplate("global-loader.tsx")
972
4391
  );
973
4392
  console.log("\u{1F527} Creating lib/utils.ts...");
974
- fs5.writeFileSync(
975
- path5.join(webRoot, "lib", "utils.ts"),
4393
+ fs7.writeFileSync(
4394
+ path7.join(webRoot, "lib", "utils.ts"),
976
4395
  readTemplate("lib-utils.ts")
977
4396
  );
978
4397
  console.log("\u{1F3A8} Creating shadcn UI components...");
979
- fs5.writeFileSync(
980
- path5.join(webRoot, "components", "ui", "button.tsx"),
4398
+ fs7.writeFileSync(
4399
+ path7.join(webRoot, "components", "ui", "button.tsx"),
981
4400
  readTemplate("ui-button.tsx")
982
4401
  );
983
- fs5.writeFileSync(
984
- path5.join(webRoot, "components", "ui", "card.tsx"),
4402
+ fs7.writeFileSync(
4403
+ path7.join(webRoot, "components", "ui", "card.tsx"),
985
4404
  readTemplate("ui-card.tsx")
986
4405
  );
987
- fs5.writeFileSync(
988
- path5.join(webRoot, "components", "ui", "input.tsx"),
4406
+ fs7.writeFileSync(
4407
+ path7.join(webRoot, "components", "ui", "input.tsx"),
989
4408
  readTemplate("ui-input.tsx")
990
4409
  );
991
- fs5.writeFileSync(
992
- path5.join(webRoot, "components", "ui", "label.tsx"),
4410
+ fs7.writeFileSync(
4411
+ path7.join(webRoot, "components", "ui", "label.tsx"),
993
4412
  readTemplate("ui-label.tsx")
994
4413
  );
995
4414
  console.log("\u{1F3A8} Setting up shadcn globals.css...");
996
- const globalsCssPath = path5.join(appDir, "globals.css");
997
- fs5.writeFileSync(globalsCssPath, readTemplate("globals.css"));
4415
+ const globalsCssPath = path7.join(appDir, "globals.css");
4416
+ fs7.writeFileSync(globalsCssPath, readTemplate("globals.css"));
998
4417
  console.log("\u{1F4D0} Updating layout.tsx with global components...");
999
- const layoutPath = path5.join(appDir, "layout.tsx");
1000
- if (fs5.existsSync(layoutPath)) {
4418
+ const layoutPath = path7.join(appDir, "layout.tsx");
4419
+ if (fs7.existsSync(layoutPath)) {
1001
4420
  try {
1002
- let layoutContent = fs5.readFileSync(layoutPath, "utf8");
4421
+ let layoutContent = fs7.readFileSync(layoutPath, "utf8");
1003
4422
  const globalImports = `import GlobalInitializer from '#/components/global-initializer';
1004
4423
  import GlobalLoader from '#/components/global-loader';`;
1005
4424
  const lastImportIndex = layoutContent.lastIndexOf("import ");
@@ -1012,14 +4431,14 @@ import GlobalLoader from '#/components/global-loader';`;
1012
4431
  <GlobalInitializer />
1013
4432
  <GlobalLoader />`
1014
4433
  );
1015
- fs5.writeFileSync(layoutPath, layoutContent);
4434
+ fs7.writeFileSync(layoutPath, layoutContent);
1016
4435
  } catch (error) {
1017
4436
  console.warn("Warning: Could not update layout.tsx:", error);
1018
4437
  }
1019
4438
  }
1020
- const postcssPath = path5.join(projectRoot, "apps", "web", "postcss.config.mjs");
1021
- if (fs5.existsSync(postcssPath)) {
1022
- fs5.writeFileSync(
4439
+ const postcssPath = path7.join(projectRoot, "apps", "web", "postcss.config.mjs");
4440
+ if (fs7.existsSync(postcssPath)) {
4441
+ fs7.writeFileSync(
1023
4442
  postcssPath,
1024
4443
  `const config = {
1025
4444
  plugins: {
@@ -1032,31 +4451,31 @@ export default config;
1032
4451
  );
1033
4452
  }
1034
4453
  console.log("\u{1F500} Creating API proxy routes...");
1035
- const coreApiDir = path5.join(appDir, "api", "core");
1036
- const proxyDir = path5.join(coreApiDir, "[...path]");
1037
- const ticketDir = path5.join(
4454
+ const coreApiDir = path7.join(appDir, "api", "core");
4455
+ const proxyDir = path7.join(coreApiDir, "[...path]");
4456
+ const ticketDir = path7.join(
1038
4457
  coreApiDir,
1039
4458
  "ws",
1040
4459
  "ticket",
1041
4460
  "[entityType]",
1042
4461
  "[entityId]"
1043
4462
  );
1044
- fs5.mkdirSync(proxyDir, { recursive: true });
1045
- fs5.mkdirSync(ticketDir, { recursive: true });
1046
- fs5.writeFileSync(
1047
- path5.join(proxyDir, "route.ts"),
4463
+ fs7.mkdirSync(proxyDir, { recursive: true });
4464
+ fs7.mkdirSync(ticketDir, { recursive: true });
4465
+ fs7.writeFileSync(
4466
+ path7.join(proxyDir, "route.ts"),
1048
4467
  readTemplate("proxy-route.ts")
1049
4468
  );
1050
- fs5.writeFileSync(
1051
- path5.join(ticketDir, "route.ts"),
4469
+ fs7.writeFileSync(
4470
+ path7.join(ticketDir, "route.ts"),
1052
4471
  readTemplate("ws-ticket-route.ts")
1053
4472
  );
1054
4473
  }
1055
4474
  console.log("\u2699\uFE0F Updating apps/web tsconfig.json...");
1056
- const webTsconfigPath = path5.join(projectRoot, "apps", "web", "tsconfig.json");
1057
- if (fs5.existsSync(webTsconfigPath)) {
4475
+ const webTsconfigPath = path7.join(projectRoot, "apps", "web", "tsconfig.json");
4476
+ if (fs7.existsSync(webTsconfigPath)) {
1058
4477
  try {
1059
- const webTsconfigContent = fs5.readFileSync(webTsconfigPath, "utf8");
4478
+ const webTsconfigContent = fs7.readFileSync(webTsconfigPath, "utf8");
1060
4479
  const webTsconfig = JSON.parse(webTsconfigContent);
1061
4480
  if (!webTsconfig.compilerOptions) {
1062
4481
  webTsconfig.compilerOptions = {};
@@ -1067,9 +4486,9 @@ export default config;
1067
4486
  webTsconfig.compilerOptions.paths["#/shared/*"] = ["../../shared/*"];
1068
4487
  webTsconfig.compilerOptions.paths["#/monorise/*"] = ["../../.monorise/*"];
1069
4488
  webTsconfig.compilerOptions.paths["#/monorise"] = ["../../.monorise/config"];
1070
- const hasSrcDir = fs5.existsSync(path5.join(projectRoot, "apps", "web", "src"));
4489
+ const hasSrcDir = fs7.existsSync(path7.join(projectRoot, "apps", "web", "src"));
1071
4490
  webTsconfig.compilerOptions.paths["#/*"] = [hasSrcDir ? "./src/*" : "./*"];
1072
- fs5.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
4491
+ fs7.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
1073
4492
  } catch (error) {
1074
4493
  console.warn("Warning: Could not update apps/web tsconfig.json:", error);
1075
4494
  }
@@ -1096,7 +4515,7 @@ export default config;
1096
4515
  console.log(` \u2022 Edit your data model \u2192 monorise/configs/user.ts`);
1097
4516
  console.log(` (Add fields like phone, role, status to the User entity)`);
1098
4517
  console.log(
1099
- ` \u2022 Build your UI \u2192 ${pagePath ? path5.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
4518
+ ` \u2022 Build your UI \u2192 ${pagePath ? path7.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
1100
4519
  );
1101
4520
  console.log(` (React components using useEntities and createEntity)`);
1102
4521
  console.log(` \u2022 Add backend logic \u2192 services/core/routes.ts`);
@@ -1118,7 +4537,7 @@ async function runDevCommand({ configDir, apiKeysFile: apiKeysFile2 }, rootPath)
1118
4537
  const watched = apiKeysFile2 ? [configDir, apiKeysFile2] : configDir;
1119
4538
  const watcher = chokidar.watch(watched, {
1120
4539
  ignored: (watchedPath) => {
1121
- const fileName = path5.basename(watchedPath);
4540
+ const fileName = path7.basename(watchedPath);
1122
4541
  return fileName === "index.ts" || // Old name, still ignore in case it exists
1123
4542
  fileName === "config.ts" || // Generated config file
1124
4543
  fileName === "processors.ts" || // Generated processors file
@@ -1175,16 +4594,35 @@ async function main() {
1175
4594
  if (rootFlagIndex > -1 && args[rootFlagIndex + 1]) {
1176
4595
  rootPath = args[rootFlagIndex + 1];
1177
4596
  }
4597
+ const option = (name) => {
4598
+ const index = args.indexOf(name);
4599
+ if (index < 0) return void 0;
4600
+ const value = args[index + 1];
4601
+ if (!value || value.startsWith("--")) {
4602
+ throw new Error(`${name} requires a value.`);
4603
+ }
4604
+ return value;
4605
+ };
1178
4606
  try {
1179
4607
  if (command === "dev") {
1180
4608
  await runDevCommand(await generateFiles(rootPath), rootPath);
1181
4609
  } else if (command === "build") {
1182
4610
  await runBuildCommand(rootPath);
4611
+ } else if (command === "devtool") {
4612
+ const portValue = option("--port");
4613
+ await runDevtoolCommand({
4614
+ rootPath,
4615
+ apiUrl: option("--api-url"),
4616
+ apiKey: option("--api-key"),
4617
+ stage: option("--stage"),
4618
+ port: portValue === void 0 ? void 0 : Number(portValue),
4619
+ open: !args.includes("--no-open")
4620
+ });
1183
4621
  } else if (command === "init") {
1184
4622
  await runInitCommand();
1185
4623
  } else {
1186
4624
  console.error(
1187
- "Unknown command. Usage:\n monorise dev [--config-root <path>]\n monorise build [--config-root <path>]\n monorise init [--name <project-name>]"
4625
+ "Unknown command. Usage:\n monorise dev [--config-root <path>]\n monorise build [--config-root <path>]\n monorise devtool [--stage <stage>] [--api-url <url>] [--api-key <key>] [--port <port>] [--no-open] [--config-root <path>]\n monorise init [--name <project-name>]"
1188
4626
  );
1189
4627
  process.exit(1);
1190
4628
  }