@quixomatic/rpf 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/assets/dev-host/boot.js +7 -223
  3. package/assets/dev-host/boot.js.LEGAL.txt +0 -22
  4. package/assets/dev-host/chunks/{accordion-O6VUPQ32.js → accordion-7MNNAFNO.js} +2 -2
  5. package/assets/dev-host/chunks/{alert-PRAGKG5L.js → alert-GIZIVENB.js} +2 -2
  6. package/assets/dev-host/chunks/{alert-dialog-SCBXM23J.js → alert-dialog-7NG5WNXK.js} +2 -2
  7. package/assets/dev-host/chunks/{avatar-WXPKQ3Z5.js → avatar-BCPZUJGX.js} +2 -2
  8. package/assets/dev-host/chunks/{breadcrumb-IJQJQ5JV.js → breadcrumb-T2XOHRDG.js} +2 -2
  9. package/assets/dev-host/chunks/button-TGT2523L.js +2 -0
  10. package/assets/dev-host/chunks/calendar-TOTKKMY2.js +2 -0
  11. package/assets/dev-host/chunks/{card-EY3LK2GB.js → card-LOSZVZYW.js} +2 -2
  12. package/assets/dev-host/chunks/{chart-2PHC6UIE.js → chart-43TBOZGK.js} +2 -2
  13. package/assets/dev-host/chunks/{chart-blocks-PZPCWCNT.js → chart-blocks-HLNNWNB5.js} +2 -2
  14. package/assets/dev-host/chunks/{chart-frame-MNUFXAPU.js → chart-frame-FNM5OPZU.js} +2 -2
  15. package/assets/dev-host/chunks/{chat-TTESCYES.js → chat-QVZ4BUWR.js} +2 -2
  16. package/assets/dev-host/chunks/{checkbox-Y2UGSRR4.js → checkbox-AFUTB4DV.js} +2 -2
  17. package/assets/dev-host/chunks/{chunk-UWANBOC6.js → chunk-2FVHAZMZ.js} +2 -2
  18. package/assets/dev-host/chunks/{chunk-CWDPAB6V.js → chunk-34RXMJIM.js} +2 -2
  19. package/assets/dev-host/chunks/chunk-354OFHNU.js +219 -0
  20. package/assets/dev-host/chunks/chunk-354OFHNU.js.LEGAL.txt +23 -0
  21. package/assets/dev-host/chunks/{chunk-CCXMDKVL.js → chunk-3LMPMW3Q.js} +2 -2
  22. package/assets/dev-host/chunks/{chunk-3H6F4X7R.js → chunk-4XESWRTW.js} +2 -2
  23. package/assets/dev-host/chunks/{chunk-PYWKHILP.js → chunk-7FCGD4LS.js} +2 -2
  24. package/assets/dev-host/chunks/{chunk-AVSRGCSF.js → chunk-7JQIKRBV.js} +2 -2
  25. package/assets/dev-host/chunks/{chunk-PHK25MY7.js → chunk-DU3VFETH.js} +2 -2
  26. package/assets/dev-host/chunks/{chunk-2IZ44WWI.js → chunk-E5JYU6CR.js} +2 -2
  27. package/assets/dev-host/chunks/{chunk-BB4IX5QA.js → chunk-FBZMZ5S2.js} +2 -2
  28. package/assets/dev-host/chunks/{chunk-GWDGPUGM.js → chunk-GSJT5YWB.js} +2 -2
  29. package/assets/dev-host/chunks/{chunk-OXJ6LWKI.js → chunk-HCQR5YME.js} +3 -3
  30. package/assets/dev-host/chunks/{chunk-APP2HKWR.js → chunk-HGBRF6KW.js} +2 -2
  31. package/assets/dev-host/chunks/{chunk-6ARM5VDH.js → chunk-HVTUE7NV.js} +2 -2
  32. package/assets/dev-host/chunks/{chunk-M7A47ZSM.js → chunk-IY3GAGI7.js} +2 -2
  33. package/assets/dev-host/chunks/{chunk-MGLBTOXD.js → chunk-KY2HARU6.js} +2 -2
  34. package/assets/dev-host/chunks/{chunk-EDEL6XSO.js → chunk-ND526XXU.js} +2 -2
  35. package/assets/dev-host/chunks/{chunk-UXUS6DNI.js → chunk-NMFZMT4R.js} +2 -2
  36. package/assets/dev-host/chunks/{chunk-XE5RQ73V.js → chunk-NPJXSRRT.js} +2 -2
  37. package/assets/dev-host/chunks/{chunk-FJRWQRLM.js → chunk-OUCK2LIZ.js} +2 -2
  38. package/assets/dev-host/chunks/{chunk-Z76KXEPD.js → chunk-OXLXEX2R.js} +2 -2
  39. package/assets/dev-host/chunks/{chunk-BH6FGVDP.js → chunk-PB5RYDO5.js} +2 -2
  40. package/assets/dev-host/chunks/{chunk-TQPXDAVH.js → chunk-QJVIEN5R.js} +2 -2
  41. package/assets/dev-host/chunks/{chunk-57M36GYM.js → chunk-QZ3NJHFR.js} +2 -2
  42. package/assets/dev-host/chunks/{chunk-FZPMZMFU.js → chunk-SC7J7HFI.js} +2 -2
  43. package/assets/dev-host/chunks/{chunk-X34AFUS2.js → chunk-SKBWMIS5.js} +2 -2
  44. package/assets/dev-host/chunks/{chunk-LTVKSGLG.js → chunk-UCEBXCOI.js} +2 -2
  45. package/assets/dev-host/chunks/{chunk-T7JFBQSG.js → chunk-UNKI7HPL.js} +2 -2
  46. package/assets/dev-host/chunks/{chunk-F5MKIWPQ.js → chunk-UPZXXDXM.js} +2 -2
  47. package/assets/dev-host/chunks/{chunk-ML6HCGK5.js → chunk-XBWE3IIB.js} +2 -2
  48. package/assets/dev-host/chunks/{chunk-NJX7QY3Z.js → chunk-YFI7GTF6.js} +2 -2
  49. package/assets/dev-host/chunks/{chunk-NI6ZJ6DH.js → chunk-YJM2Y722.js} +2 -2
  50. package/assets/dev-host/chunks/{chunk-WLBNJ4K3.js → chunk-ZNWVTDCV.js} +2 -2
  51. package/assets/dev-host/chunks/{chunk-UUJ5X322.js → chunk-ZTMZ7LJW.js} +2 -2
  52. package/assets/dev-host/chunks/{chunk-OW6AVFQA.js → chunk-ZZ2RYU7S.js} +2 -2
  53. package/assets/dev-host/chunks/{code-block-H2ETQV3M.js → code-block-IKYEIWY2.js} +2 -2
  54. package/assets/dev-host/chunks/code-editor-KDRLM33B.js +2 -0
  55. package/assets/dev-host/chunks/{collapsible-4ZOFMWLB.js → collapsible-WK7PDWEV.js} +2 -2
  56. package/assets/dev-host/chunks/{color-picker-RRCCLR54.js → color-picker-VPSOGTDM.js} +2 -2
  57. package/assets/dev-host/chunks/{combobox-U4455OMJ.js → combobox-GYLAHYVX.js} +2 -2
  58. package/assets/dev-host/chunks/{contrast-badge-KDF65X7J.js → contrast-badge-QZW62DMF.js} +2 -2
  59. package/assets/dev-host/chunks/{date-range-picker-WJYHAHRM.js → date-range-picker-6Q2JGR43.js} +2 -2
  60. package/assets/dev-host/chunks/{dialog-I6AGHWB3.js → dialog-HDQAIAFZ.js} +2 -2
  61. package/assets/dev-host/chunks/{dropdown-menu-LSOMXDWG.js → dropdown-menu-E7K3YNXS.js} +2 -2
  62. package/assets/dev-host/chunks/{empty-NLQODUSK.js → empty-JCVCSM3V.js} +2 -2
  63. package/assets/dev-host/chunks/{font-picker-3TLYYZJH.js → font-picker-7FBJCSTQ.js} +2 -2
  64. package/assets/dev-host/chunks/{frame-HA7UIYZF.js → frame-LZ2IUISE.js} +2 -2
  65. package/assets/dev-host/chunks/{heading-7M24WKK6.js → heading-GX36VR3U.js} +2 -2
  66. package/assets/dev-host/chunks/{hover-card-HSHOQPOI.js → hover-card-ONEUZ7TU.js} +2 -2
  67. package/assets/dev-host/chunks/{image-R7XGYKVH.js → image-E3BYZ2HA.js} +2 -2
  68. package/assets/dev-host/chunks/{input-YECXNM53.js → input-G7S4OLSN.js} +2 -2
  69. package/assets/dev-host/chunks/{input-group-GFKXSZM7.js → input-group-54JRMLWQ.js} +2 -2
  70. package/assets/dev-host/chunks/{kbd-V25ZMVCM.js → kbd-TKMXF542.js} +2 -2
  71. package/assets/dev-host/chunks/label-YIVRPKQJ.js +2 -0
  72. package/assets/dev-host/chunks/{label-value-6Z6ATP55.js → label-value-V7QDIDAP.js} +2 -2
  73. package/assets/dev-host/chunks/{logo-AAMBHX2W.js → logo-DBA4NHQE.js} +2 -2
  74. package/assets/dev-host/chunks/{number-field-6TCQAVTR.js → number-field-FPC3YXDC.js} +2 -2
  75. package/assets/dev-host/chunks/{pill-7L57ZNRJ.js → pill-4WVEOBR4.js} +2 -2
  76. package/assets/dev-host/chunks/{popover-3P6YNKH3.js → popover-GQD2U5SP.js} +2 -2
  77. package/assets/dev-host/chunks/{progress-RBCJRVM7.js → progress-TITSWD2A.js} +2 -2
  78. package/assets/dev-host/chunks/{radio-group-NJWXZCX3.js → radio-group-YA3OUIPB.js} +2 -2
  79. package/assets/dev-host/chunks/{resizable-XF4P6OKR.js → resizable-XQKUCHIS.js} +2 -2
  80. package/assets/dev-host/chunks/rich-text-2RYBPVRF.js +2 -0
  81. package/assets/dev-host/chunks/{rich-text-editor-T6KWD4P3.js → rich-text-editor-IX7RIMLI.js} +2 -2
  82. package/assets/dev-host/chunks/{scroll-row-LMI7JCFR.js → scroll-row-MZZQZYLM.js} +2 -2
  83. package/assets/dev-host/chunks/{select-F3MZWTTS.js → select-5U37ZHLQ.js} +2 -2
  84. package/assets/dev-host/chunks/separator-JATMMEKS.js +2 -0
  85. package/assets/dev-host/chunks/{sheet-EXRT4MFB.js → sheet-KTVNRYAO.js} +2 -2
  86. package/assets/dev-host/chunks/{side-panel-IBHLEANN.js → side-panel-2UVNFRIF.js} +2 -2
  87. package/assets/dev-host/chunks/{sidebar-VKQMQMF2.js → sidebar-GR4A2LDD.js} +2 -2
  88. package/assets/dev-host/chunks/{skeleton-KIRVQ4EO.js → skeleton-XE2TGBGQ.js} +2 -2
  89. package/assets/dev-host/chunks/{slider-XKYDL5MR.js → slider-BGGGQLSH.js} +2 -2
  90. package/assets/dev-host/chunks/{split-button-WP6LALDS.js → split-button-KLVGWHNN.js} +2 -2
  91. package/assets/dev-host/chunks/{stepper-KR6PXZHW.js → stepper-AY3NGEDC.js} +2 -2
  92. package/assets/dev-host/chunks/{switch-P6NJELJJ.js → switch-A2VSCLHA.js} +2 -2
  93. package/assets/dev-host/chunks/{tabs-PFPRJNVZ.js → tabs-2IO6EIED.js} +2 -2
  94. package/assets/dev-host/chunks/textarea-YQH2OPGH.js +2 -0
  95. package/assets/dev-host/chunks/{toggle-group-PS7JN2JM.js → toggle-group-3SDBWJ2G.js} +2 -2
  96. package/assets/dev-host/chunks/{tooltip-S4RBC3O4.js → tooltip-4QJ2SWCS.js} +2 -2
  97. package/assets/dev-host/chunks/{tree-NQF6ZJLH.js → tree-CFIKTPFC.js} +2 -2
  98. package/assets/dev-host/kit-candidates.json +1 -1
  99. package/assets/dev-host/kit-manifest.json +1 -1
  100. package/assets/dev-host/stage.js +54 -0
  101. package/assets/forge-app/app/assets/{_forge-shiki-langs-DaJjT17w.js → _forge-shiki-langs-nxHsAEiY.js} +1 -1
  102. package/assets/forge-app/app/assets/{appendItems-CWJJlOE7.js → appendItems-CLsiMCGq.js} +1 -1
  103. package/assets/forge-app/app/assets/{core-Dl2d1S-D.js → core-DEkUYqk0.js} +1 -1
  104. package/assets/forge-app/app/assets/{diff-view-Chujmqzi.js → diff-view-ctlXj2p5.js} +1 -1
  105. package/assets/forge-app/app/assets/{file-panel-le_M5nHe.js → file-panel-BnUdO2N6.js} +1 -1
  106. package/assets/forge-app/app/assets/{highlights-BxaWC1ve.js → highlights-CEbVTJAm.js} +1 -1
  107. package/assets/forge-app/app/assets/index-DYFQser1.js +291 -0
  108. package/assets/forge-app/app/assets/index-Ddi87x2p.css +1 -0
  109. package/assets/forge-app/app/assets/{loader-BMv9OYvr.js → loader-V5V4Ad0d.js} +1 -1
  110. package/assets/forge-app/app/assets/{shiki-CoRI3zWj.js → shiki-B5GY8Ub_.js} +2 -2
  111. package/assets/forge-app/app/assets/{stream-tokenizer-BMtK_3oz.js → stream-tokenizer-CZZoarTM.js} +1 -1
  112. package/assets/forge-app/app/assets/{terminal-view-D3CiLjfu.js → terminal-view-BR9EXBM5.js} +1 -1
  113. package/assets/forge-app/app/assets/{themes-CLX9vH7e.js → themes-BMbfM7BC.js} +2 -2
  114. package/assets/forge-app/app/assets/{useNextRenderData-dgMkjxGZ.js → useNextRenderData-ICppXFTX.js} +1 -1
  115. package/assets/forge-app/app/index.html +2 -2
  116. package/assets/forge-app/server.mjs +283 -34
  117. package/dist/cli.mjs +1906 -718
  118. package/package.json +1 -1
  119. package/assets/dev-host/chunks/button-4JMBKYN4.js +0 -2
  120. package/assets/dev-host/chunks/calendar-XXLCAUPG.js +0 -2
  121. package/assets/dev-host/chunks/code-editor-2JYERJLS.js +0 -2
  122. package/assets/dev-host/chunks/label-LJT4V2CT.js +0 -2
  123. package/assets/dev-host/chunks/rich-text-7OMYZ564.js +0 -2
  124. package/assets/dev-host/chunks/separator-JRJYKM4Z.js +0 -2
  125. package/assets/dev-host/chunks/textarea-2JXA5XWS.js +0 -2
  126. package/assets/forge-app/app/assets/index-BwYJlfwT.css +0 -1
  127. package/assets/forge-app/app/assets/index-UP3KtgHV.js +0 -291
  128. /package/assets/dev-host/chunks/{chunk-OXJ6LWKI.js.LEGAL.txt → chunk-HCQR5YME.js.LEGAL.txt} +0 -0
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // rpforge 0.3.1 (MIT). Built from packages/rpforge, packages/forge-core and packages/forge-mcp.
2
+ // rpforge 0.3.2 (MIT). Built from packages/rpforge, packages/forge-core and packages/forge-mcp.
3
3
  var __defProp = Object.defineProperty;
4
4
  var __returnValue = (v) => v;
5
5
  function __exportSetter(name, newValue) {
@@ -233,7 +233,7 @@ async function importPortalSource(source) {
233
233
  throw new Error("portal.mjs has no `export default`");
234
234
  return new Function(body)();
235
235
  }
236
- var roots, MANIFEST = "forge.workspace.json", FORGE_DIR = ".forge", LOCAL_ONLY, REACT_PORTAL_STYLE, prettierMod = null, prettierConfig = null;
236
+ var roots, MANIFEST = "forge.workspace.json", FORGE_DIR = ".forge", BASE_MARK = ".base", LOCAL_ONLY, REACT_PORTAL_STYLE, prettierMod = null, prettierConfig = null;
237
237
  var init_layout = __esm(() => {
238
238
  roots = {
239
239
  repo: "",
@@ -243,7 +243,7 @@ var init_layout = __esm(() => {
243
243
  hostTypes: "",
244
244
  typesFrom: ""
245
245
  };
246
- LOCAL_ONLY = new Set(["README.md", MANIFEST, ".gitignore", ".prettierrc.json"]);
246
+ LOCAL_ONLY = new Set(["README.md", MANIFEST, ".gitignore", ".prettierrc.json", "stage.json", BASE_MARK]);
247
247
  REACT_PORTAL_STYLE = {
248
248
  semi: true,
249
249
  singleQuote: true,
@@ -270,6 +270,9 @@ function instanceKey(url) {
270
270
  return url;
271
271
  }
272
272
  }
273
+ function isComponentManifest(m) {
274
+ return !!m && m.kind === "component";
275
+ }
273
276
  function readManifest(dir) {
274
277
  const f = join3(dir, MANIFEST);
275
278
  if (!existsSync3(f))
@@ -277,7 +280,15 @@ function readManifest(dir) {
277
280
  const m = JSON.parse(readFileSync3(f, "utf8"));
278
281
  if (m.format !== 1)
279
282
  throw new Error(`${MANIFEST}: unsupported format ${m.format}`);
280
- return { format: 1, ignore: m.ignore || [], images: m.images || [], instances: m.instances || {} };
283
+ if (m.kind !== undefined && m.kind !== "portal" && m.kind !== "component")
284
+ throw new Error(`${MANIFEST}: unknown kind "${m.kind}" (update rpf)`);
285
+ return {
286
+ format: 1,
287
+ ...m.kind === "component" ? { kind: "component" } : {},
288
+ ignore: m.ignore || [],
289
+ images: m.images || [],
290
+ instances: m.instances || {}
291
+ };
281
292
  }
282
293
  function sorted(v) {
283
294
  if (Array.isArray(v))
@@ -293,6 +304,7 @@ function sorted(v) {
293
304
  async function writeManifest(dir, m) {
294
305
  const body = {
295
306
  format: m.format,
307
+ ...m.kind === "component" ? { kind: "component" } : {},
296
308
  ignore: m.ignore.slice().sort(),
297
309
  images: m.images.slice().sort(),
298
310
  instances: sorted(m.instances)
@@ -1122,7 +1134,7 @@ var package_default;
1122
1134
  var init_package = __esm(() => {
1123
1135
  package_default = {
1124
1136
  name: "@quixomatic/rpf",
1125
- version: "0.3.1",
1137
+ version: "0.3.2",
1126
1138
  description: "React Portal from the terminal: instance profiles, sign-in, new draft portals, local workspaces, live lookups, built-in Claude Code skills, health checks and the Forge MCP server for ServiceNow instances running React Portal.",
1127
1139
  type: "module",
1128
1140
  license: "MIT",
@@ -2123,7 +2135,7 @@ function renderPull(out, r) {
2123
2135
  if (r.status)
2124
2136
  out.line(r.status.clean ? c.green("clean") : `status: ${countsText(r.status.counts)}`);
2125
2137
  } else {
2126
- out.line(`${c.bold(r.mode === "adopt" ? "Adopted" : "Pulled")} ${r.portal ? r.portal.slug : ""} into ${rel(r.dir)}`);
2138
+ out.line(`${c.bold(r.mode === "adopt" ? "Adopted" : "Pulled")} ${r.portal ? r.portal.slug : r.app ? r.app.scope + " components" : ""} into ${rel(r.dir)}`);
2127
2139
  if (r.updateSet)
2128
2140
  out.line(c.dim(`pushes write into update set "${r.updateSet.name}"`));
2129
2141
  if (r.counts)
@@ -2623,9 +2635,178 @@ var init_skills = __esm(() => {
2623
2635
  init_version();
2624
2636
  });
2625
2637
 
2638
+ // ../forge-core/src/dev/stage-protocol.ts
2639
+ function emptyStageState() {
2640
+ return { options: {}, params: {}, mode: "system", width: "full" };
2641
+ }
2642
+ function stageWidthPx(w) {
2643
+ if (typeof w === "number" && w > 0)
2644
+ return Math.max(240, Math.min(3840, Math.round(w)));
2645
+ if (typeof w === "string" && w in STAGE_WIDTHS)
2646
+ return STAGE_WIDTHS[w];
2647
+ return 0;
2648
+ }
2649
+ function cleanStageState(v) {
2650
+ const s = v && typeof v === "object" ? v : {};
2651
+ const str = (x) => typeof x === "string" && x.trim() ? x.trim().slice(0, 500) : undefined;
2652
+ const params = {};
2653
+ const p = s.params && typeof s.params === "object" ? s.params : {};
2654
+ for (const k of ["table", "sysId", "view", "query"]) {
2655
+ const val = str(p[k]);
2656
+ if (val)
2657
+ params[k] = val;
2658
+ }
2659
+ if (Array.isArray(p.q))
2660
+ params.q = p.q.filter((e) => Array.isArray(e) && typeof e[0] === "string").slice(0, 50).map((e) => [String(e[0]).slice(0, 100), String(e[1] ?? "").slice(0, 1000)]);
2661
+ const out = {
2662
+ options: s.options && typeof s.options === "object" && !Array.isArray(s.options) ? s.options : {},
2663
+ params,
2664
+ mode: s.mode === "light" || s.mode === "dark" ? s.mode : "system",
2665
+ width: typeof s.width === "number" ? stageWidthPx(s.width) : (s.width in STAGE_WIDTHS) ? s.width : "full"
2666
+ };
2667
+ const tp = str(s.themePortal);
2668
+ if (tp)
2669
+ out.themePortal = tp;
2670
+ const th = str(s.theme);
2671
+ if (th)
2672
+ out.theme = th;
2673
+ return out;
2674
+ }
2675
+ var STAGE_WIDTHS;
2676
+ var init_stage_protocol = __esm(() => {
2677
+ STAGE_WIDTHS = { phone: 390, tablet: 820, laptop: 1280, full: 0 };
2678
+ });
2679
+
2680
+ // ../forge-core/src/dev/stage.ts
2681
+ import { existsSync as existsSync9, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "node:fs";
2682
+ import { join as join8 } from "node:path";
2683
+ function isComponentWorkspace(dir) {
2684
+ let m = null;
2685
+ try {
2686
+ m = readManifest(dir);
2687
+ } catch {
2688
+ m = null;
2689
+ }
2690
+ if (m && m.kind === "component")
2691
+ return true;
2692
+ if (m && m.kind === "portal")
2693
+ return false;
2694
+ return !existsSync9(join8(dir, "portal.mjs")) && existsSync9(join8(dir, "components"));
2695
+ }
2696
+ function readStageFile(dir) {
2697
+ const f = join8(dir, STAGE_FILE);
2698
+ let raw = null;
2699
+ try {
2700
+ raw = existsSync9(f) ? JSON.parse(readFileSync11(f, "utf8")) : null;
2701
+ } catch {
2702
+ raw = null;
2703
+ }
2704
+ const out = { components: {} };
2705
+ if (raw && typeof raw.current === "string")
2706
+ out.current = raw.current;
2707
+ const comps = raw && raw.components && typeof raw.components === "object" ? raw.components : {};
2708
+ for (const uid of Object.keys(comps))
2709
+ out.components[uid] = cleanStageState(comps[uid]);
2710
+ return out;
2711
+ }
2712
+ async function writeStageFile(dir, file) {
2713
+ const comps = {};
2714
+ for (const uid of Object.keys(file.components).sort())
2715
+ comps[uid] = file.components[uid];
2716
+ const body = { current: file.current, components: comps };
2717
+ const text = await formatFile(STAGE_FILE, JSON.stringify(body, null, 4) + `
2718
+ `);
2719
+ const f = join8(dir, STAGE_FILE);
2720
+ if (existsSync9(f) && readFileSync11(f, "utf8") === text)
2721
+ return false;
2722
+ writeFileSync6(f, text, "utf8");
2723
+ return true;
2724
+ }
2725
+ function currentComponent(components, file, asked) {
2726
+ if (asked && components.has(asked))
2727
+ return asked;
2728
+ if (file.current && components.has(file.current))
2729
+ return file.current;
2730
+ return Array.from(components.keys()).sort()[0] || "";
2731
+ }
2732
+ function stateOf(file, uid) {
2733
+ return file.components[uid] ? cleanStageState(file.components[uid]) : emptyStageState();
2734
+ }
2735
+ function stageStructure(components, uid, state, themeKey) {
2736
+ const comp = uid ? components.get(uid) : undefined;
2737
+ const kind = comp ? comp.kind : "";
2738
+ const used = new Set;
2739
+ const regions = {};
2740
+ let layout = null;
2741
+ let note = "";
2742
+ if (!comp)
2743
+ note = "This workspace has no components yet: rpf new component <namespace>/<key>";
2744
+ else if (kind === "layout") {
2745
+ layout = uid;
2746
+ used.add(uid);
2747
+ } else if (kind === "utility")
2748
+ note = `${uid} is a utility: it exports code, so there is nothing to render`;
2749
+ else {
2750
+ used.add(uid);
2751
+ regions.main = [
2752
+ {
2753
+ id: `local:placement:page:${STAGE_ROUTE}/stage`,
2754
+ unit: `placement:page:${STAGE_ROUTE}/stage`,
2755
+ key: "stage",
2756
+ region: "main",
2757
+ order: 0,
2758
+ component: uid,
2759
+ options: { ...state.options },
2760
+ classes: "",
2761
+ layout: {},
2762
+ style: {},
2763
+ roles: []
2764
+ }
2765
+ ];
2766
+ }
2767
+ const page = {
2768
+ id: `local:page:${STAGE_ROUTE}`,
2769
+ route: STAGE_ROUTE,
2770
+ title: comp ? comp.name : "Stage",
2771
+ order: 0,
2772
+ roles: [],
2773
+ layout,
2774
+ layoutOptions: {},
2775
+ contentWidth: "full",
2776
+ defaultPanel: null,
2777
+ regions,
2778
+ variants: []
2779
+ };
2780
+ const slug = state.themePortal || STAGE_SLUG;
2781
+ return {
2782
+ def: null,
2783
+ slug,
2784
+ name: comp ? `${comp.name} (stage)` : "rpf stage",
2785
+ home: STAGE_ROUTE,
2786
+ settings: { contentWidth: "full" },
2787
+ roles: [],
2788
+ theme: themeKey,
2789
+ layout: null,
2790
+ layoutOptions: {},
2791
+ regions: {},
2792
+ pages: [page],
2793
+ panels: [],
2794
+ menus: {},
2795
+ cellRenderers: [],
2796
+ components: used,
2797
+ stage: { component: uid, kind, note }
2798
+ };
2799
+ }
2800
+ var STAGE_FILE = "stage.json", STAGE_SLUG = "rpf-stage", STAGE_DEFAULT_THEME = "shadcn-neutral", STAGE_ROUTE = "stage";
2801
+ var init_stage = __esm(() => {
2802
+ init_manifest();
2803
+ init_layout();
2804
+ init_stage_protocol();
2805
+ });
2806
+
2626
2807
  // ../forge-core/src/dev/compile.ts
2627
- import { existsSync as existsSync9, readFileSync as readFileSync11 } from "node:fs";
2628
- import { isAbsolute, join as join8, relative as relative5, resolve as resolve4 } from "node:path";
2808
+ import { existsSync as existsSync10, readFileSync as readFileSync12 } from "node:fs";
2809
+ import { isAbsolute, join as join9, relative as relative5, resolve as resolve4 } from "node:path";
2629
2810
  import { createHash as createHash3 } from "node:crypto";
2630
2811
  async function esbuild() {
2631
2812
  if (!esbuildMod)
@@ -2674,7 +2855,7 @@ function keep(tok, out) {
2674
2855
  }
2675
2856
  function entryOf(dir) {
2676
2857
  for (const e of ENTRIES)
2677
- if (existsSync9(join8(dir, e)))
2858
+ if (existsSync10(join9(dir, e)))
2678
2859
  return e;
2679
2860
  return null;
2680
2861
  }
@@ -2711,9 +2892,9 @@ async function compileComponent(input) {
2711
2892
  }
2712
2893
  const deps = new Set;
2713
2894
  const cssParts = [];
2714
- const styles = join8(dir, "styles.css");
2715
- if (existsSync9(styles))
2716
- cssParts.push({ file: "styles.css", text: readFileSync11(styles, "utf8") });
2895
+ const styles = join9(dir, "styles.css");
2896
+ if (existsSync10(styles))
2897
+ cssParts.push({ file: "styles.css", text: readFileSync12(styles, "utf8") });
2717
2898
  const es = await esbuild();
2718
2899
  let result;
2719
2900
  try {
@@ -2770,7 +2951,7 @@ async function compileComponent(input) {
2770
2951
  b.onLoad({ filter: /\.css$/ }, (a) => {
2771
2952
  const rel = relative5(dir, a.path).split("\\").join("/");
2772
2953
  if (rel !== "styles.css" && !cssParts.some((c) => c.file === rel))
2773
- cssParts.push({ file: rel, text: readFileSync11(a.path, "utf8") });
2954
+ cssParts.push({ file: rel, text: readFileSync12(a.path, "utf8") });
2774
2955
  return { contents: "module.exports = {};", loader: "js" };
2775
2956
  });
2776
2957
  }
@@ -2789,9 +2970,9 @@ async function compileComponent(input) {
2789
2970
  if (file.startsWith("rpf:"))
2790
2971
  continue;
2791
2972
  const abs = resolve4(dir, file);
2792
- if (!existsSync9(abs) || abs.endsWith(".json"))
2973
+ if (!existsSync10(abs) || abs.endsWith(".json"))
2793
2974
  continue;
2794
- for (const c of extractCandidates(readFileSync11(abs, "utf8")))
2975
+ for (const c of extractCandidates(readFileSync12(abs, "utf8")))
2795
2976
  candidates.add(c);
2796
2977
  }
2797
2978
  const css = cssParts.map((c) => `/* ${input.uniqueId}/${c.file} */
@@ -2832,8 +3013,8 @@ var init_compile = __esm(() => {
2832
3013
  });
2833
3014
 
2834
3015
  // ../forge-core/src/dev/library.ts
2835
- import { existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "node:fs";
2836
- import { dirname as dirname7, join as join9, normalize, relative as relative6 } from "node:path";
3016
+ import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "node:fs";
3017
+ import { dirname as dirname7, join as join10, normalize, relative as relative6 } from "node:path";
2837
3018
 
2838
3019
  class Library {
2839
3020
  client;
@@ -2845,7 +3026,7 @@ class Library {
2845
3026
  }
2846
3027
  dirOf(uid, revision) {
2847
3028
  const [ns, key] = uid.split("/");
2848
- return join9(this.root, ns, key, String(revision));
3029
+ return join10(this.root, ns, key, String(revision));
2849
3030
  }
2850
3031
  ensure(uid) {
2851
3032
  let p = this.pending.get(uid);
@@ -2873,25 +3054,25 @@ class Library {
2873
3054
  optionsSchema: m.optionsSchema && typeof m.optionsSchema === "object" ? m.optionsSchema : null
2874
3055
  };
2875
3056
  const dir = this.dirOf(uid, meta.revision);
2876
- const marker = join9(dir, ".rpf-meta.json");
2877
- if (existsSync10(marker))
3057
+ const marker = join10(dir, ".rpf-meta.json");
3058
+ if (existsSync11(marker))
2878
3059
  return { meta, dir, from: "cache" };
2879
3060
  const src = await this.client.get("/component/source", { ref: uid });
2880
3061
  for (const f of src.files || []) {
2881
3062
  const rel = normalize(String(f.path || ""));
2882
- if (!rel || rel.startsWith("..") || relative6(dir, join9(dir, rel)).startsWith(".."))
3063
+ if (!rel || rel.startsWith("..") || relative6(dir, join10(dir, rel)).startsWith(".."))
2883
3064
  continue;
2884
- const abs = join9(dir, rel);
3065
+ const abs = join10(dir, rel);
2885
3066
  mkdirSync6(dirname7(abs), { recursive: true });
2886
- writeFileSync6(abs, f.content == null ? "" : String(f.content));
3067
+ writeFileSync7(abs, f.content == null ? "" : String(f.content));
2887
3068
  }
2888
3069
  mkdirSync6(dir, { recursive: true });
2889
- writeFileSync6(marker, JSON.stringify({ meta, fetchedAt: new Date().toISOString() }, null, 2));
3070
+ writeFileSync7(marker, JSON.stringify({ meta, fetchedAt: new Date().toISOString() }, null, 2));
2890
3071
  return { meta, dir, from: "instance" };
2891
3072
  }
2892
3073
  static cachedMeta(dir) {
2893
3074
  try {
2894
- return JSON.parse(readFileSync12(join9(dir, ".rpf-meta.json"), "utf8")).meta;
3075
+ return JSON.parse(readFileSync13(join10(dir, ".rpf-meta.json"), "utf8")).meta;
2895
3076
  } catch {
2896
3077
  return null;
2897
3078
  }
@@ -3075,9 +3256,9 @@ var init_shadows = __esm(() => {
3075
3256
  });
3076
3257
 
3077
3258
  // ../forge-core/src/dev/tailwind.ts
3078
- import { readFileSync as readFileSync13 } from "node:fs";
3259
+ import { readFileSync as readFileSync14 } from "node:fs";
3079
3260
  import { createRequire as createRequire2 } from "node:module";
3080
- import { dirname as dirname8, join as join10 } from "node:path";
3261
+ import { dirname as dirname8, join as join11 } from "node:path";
3081
3262
  function portalInput() {
3082
3263
  const colors = COLOR_TOKENS.map((t) => ` --color-${t}: var(--${t});`).join(`
3083
3264
  `);
@@ -3129,17 +3310,17 @@ function stylesheetLoader(src) {
3129
3310
  const req = createRequire2(import.meta.url);
3130
3311
  const twDir = dirname8(req.resolve("tailwindcss/package.json"));
3131
3312
  const files = {
3132
- "tailwindcss/theme": join10(twDir, "theme.css"),
3133
- "tailwindcss/utilities": join10(twDir, "utilities.css"),
3134
- "tailwindcss/preflight": join10(twDir, "preflight.css"),
3135
- "tw-animate-css": join10(src.cssDir, "tw-animate.css"),
3136
- "shadcn/tailwind.css": join10(src.cssDir, "shadcn-tailwind.css")
3313
+ "tailwindcss/theme": join11(twDir, "theme.css"),
3314
+ "tailwindcss/utilities": join11(twDir, "utilities.css"),
3315
+ "tailwindcss/preflight": join11(twDir, "preflight.css"),
3316
+ "tw-animate-css": join11(src.cssDir, "tw-animate.css"),
3317
+ "shadcn/tailwind.css": join11(src.cssDir, "shadcn-tailwind.css")
3137
3318
  };
3138
3319
  return async (id, base) => {
3139
3320
  const path = files[id];
3140
3321
  if (!path)
3141
3322
  throw new Error(`rpf dev: unknown stylesheet import "${id}"`);
3142
- return { path, base: dirname8(path), content: readFileSync13(path, "utf8") };
3323
+ return { path, base: dirname8(path), content: readFileSync14(path, "utf8") };
3143
3324
  };
3144
3325
  }
3145
3326
 
@@ -3236,8 +3417,8 @@ var init_tailwind = __esm(() => {
3236
3417
  });
3237
3418
 
3238
3419
  // ../forge-core/src/dev/structure.ts
3239
- import { existsSync as existsSync11, readdirSync as readdirSync4, readFileSync as readFileSync14 } from "node:fs";
3240
- import { join as join11 } from "node:path";
3420
+ import { existsSync as existsSync12, readdirSync as readdirSync4, readFileSync as readFileSync15 } from "node:fs";
3421
+ import { join as join12 } from "node:path";
3241
3422
  function roleList(v) {
3242
3423
  if (Array.isArray(v))
3243
3424
  return v.map(String).filter(Boolean);
@@ -3276,7 +3457,7 @@ function applyInstanceAudience(menus, visible) {
3276
3457
  return { menus: out, hidden };
3277
3458
  }
3278
3459
  async function readStructure(dir, ids) {
3279
- const def = await importPortal(join11(dir, "portal.mjs"));
3460
+ const def = await importPortal(join12(dir, "portal.mjs"));
3280
3461
  const used = new Set;
3281
3462
  const idOf = (unit) => ids[unit] || "local:" + unit;
3282
3463
  const placements = (list, owner, defaultRegion) => {
@@ -3479,39 +3660,39 @@ function cssVarsOf(schema) {
3479
3660
  }
3480
3661
  function workspaceComponents(dir) {
3481
3662
  const out = new Map;
3482
- const root = join11(dir, "components");
3483
- if (!existsSync11(root))
3663
+ const root = join12(dir, "components");
3664
+ if (!existsSync12(root))
3484
3665
  return out;
3485
3666
  for (const nsDir of readdirSync4(root)) {
3486
3667
  if (!nsDir.startsWith("@"))
3487
3668
  continue;
3488
3669
  const ns = nsDir.slice(1);
3489
- for (const key of readdirSync4(join11(root, nsDir))) {
3490
- const cdir = join11(root, nsDir, key);
3491
- const cj = join11(cdir, "component.json");
3492
- if (!existsSync11(cj))
3670
+ for (const key of readdirSync4(join12(root, nsDir))) {
3671
+ const cdir = join12(root, nsDir, key);
3672
+ const cj = join12(cdir, "component.json");
3673
+ if (!existsSync12(cj))
3493
3674
  continue;
3494
3675
  let meta = {};
3495
3676
  try {
3496
- meta = JSON.parse(readFileSync14(cj, "utf8"));
3677
+ meta = JSON.parse(readFileSync15(cj, "utf8"));
3497
3678
  } catch {
3498
3679
  meta = {};
3499
3680
  }
3500
3681
  let regions = [];
3501
- const rj = join11(cdir, "regions.json");
3502
- if (existsSync11(rj)) {
3682
+ const rj = join12(cdir, "regions.json");
3683
+ if (existsSync12(rj)) {
3503
3684
  try {
3504
- regions = JSON.parse(readFileSync14(rj, "utf8"));
3685
+ regions = JSON.parse(readFileSync15(rj, "utf8"));
3505
3686
  } catch {
3506
3687
  regions = [];
3507
3688
  }
3508
3689
  } else if (Array.isArray(meta.regions))
3509
3690
  regions = meta.regions;
3510
3691
  let optionsSchema = null;
3511
- const sj = join11(cdir, "options.schema.json");
3512
- if (existsSync11(sj)) {
3692
+ const sj = join12(cdir, "options.schema.json");
3693
+ if (existsSync12(sj)) {
3513
3694
  try {
3514
- optionsSchema = JSON.parse(readFileSync14(sj, "utf8"));
3695
+ optionsSchema = JSON.parse(readFileSync15(sj, "utf8"));
3515
3696
  } catch {
3516
3697
  optionsSchema = null;
3517
3698
  }
@@ -3538,8 +3719,8 @@ var init_structure = __esm(() => {
3538
3719
 
3539
3720
  // ../forge-core/src/dev/staging.ts
3540
3721
  import { createHash as createHash4 } from "node:crypto";
3541
- import { existsSync as existsSync12, readFileSync as readFileSync15 } from "node:fs";
3542
- import { join as join12 } from "node:path";
3722
+ import { existsSync as existsSync13, readFileSync as readFileSync16 } from "node:fs";
3723
+ import { join as join13 } from "node:path";
3543
3724
 
3544
3725
  class Staging {
3545
3726
  o;
@@ -3598,13 +3779,13 @@ class Staging {
3598
3779
  async localScript(uid) {
3599
3780
  const ws = this.o.workspace().get(uid);
3600
3781
  if (ws) {
3601
- const f = join12(ws.dir, "server.js");
3602
- return { script: existsSync12(f) ? readFileSync15(f, "utf8") : "", workspace: true };
3782
+ const f = join13(ws.dir, "server.js");
3783
+ return { script: existsSync13(f) ? readFileSync16(f, "utf8") : "", workspace: true };
3603
3784
  }
3604
3785
  try {
3605
3786
  const lib = await this.o.library.ensure(uid);
3606
- const f = join12(lib.dir, "server.js");
3607
- return { script: existsSync12(f) ? readFileSync15(f, "utf8") : "", workspace: false };
3787
+ const f = join13(lib.dir, "server.js");
3788
+ return { script: existsSync13(f) ? readFileSync16(f, "utf8") : "", workspace: false };
3608
3789
  } catch {
3609
3790
  return null;
3610
3791
  }
@@ -3744,15 +3925,15 @@ var init_staging = __esm(() => {
3744
3925
  // ../forge-core/src/dev/server.ts
3745
3926
  import { createServer as createServer2 } from "node:http";
3746
3927
  import {
3747
- existsSync as existsSync13,
3928
+ existsSync as existsSync14,
3748
3929
  mkdirSync as mkdirSync7,
3749
- readFileSync as readFileSync16,
3930
+ readFileSync as readFileSync17,
3750
3931
  readdirSync as readdirSync5,
3751
3932
  rmSync,
3752
3933
  watch,
3753
- writeFileSync as writeFileSync7
3934
+ writeFileSync as writeFileSync8
3754
3935
  } from "node:fs";
3755
- import { dirname as dirname9, extname, join as join13, normalize as normalize2, relative as relative7, sep as sep4 } from "node:path";
3936
+ import { dirname as dirname9, extname, join as join14, normalize as normalize2, relative as relative7, sep as sep4 } from "node:path";
3756
3937
  import { randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
3757
3938
  function proxied(path) {
3758
3939
  if (path.startsWith("/api/x_312987_portal/rp_forge"))
@@ -3770,19 +3951,54 @@ async function startDevServer(o) {
3770
3951
  for (const [uid, d] of Object.entries(inst && inst.dependencies || {}))
3771
3952
  ids["component:" + uid] = d.id;
3772
3953
  const forgeDir = ensureForgeDir(o.dir);
3773
- const runFile = join13(forgeDir, "dev", "run.json");
3954
+ const runFile = join14(forgeDir, "dev", "run.json");
3774
3955
  let saved = {};
3775
3956
  try {
3776
- saved = JSON.parse(readFileSync16(runFile, "utf8"));
3957
+ saved = JSON.parse(readFileSync17(runFile, "utf8"));
3777
3958
  } catch {
3778
3959
  saved = {};
3779
3960
  }
3780
3961
  const secret = !o.newKey && /^[0-9a-f]{64}$/.test(String(saved.key || "")) ? String(saved.key) : randomBytes4(32).toString("hex");
3781
- const library = new Library(o.client, join13(forgeDir, "dev", "lib"));
3962
+ const library = new Library(o.client, join14(forgeDir, "dev", "lib"));
3782
3963
  const ancestors = (o.frameAncestors || []).filter((x) => /^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(x));
3783
3964
  const csp = `${CSP}; frame-ancestors 'self'${ancestors.map((a) => " " + a).join("")}`;
3784
- let structure = await readStructure(o.dir, ids);
3785
3965
  let wsComponents = workspaceComponents(o.dir);
3966
+ const stageMode = isComponentWorkspace(o.dir);
3967
+ let stageFile = stageMode ? readStageFile(o.dir) : { components: {} };
3968
+ let stageUid = "";
3969
+ let stageMeta = null;
3970
+ let portalList = null;
3971
+ async function stagePortals() {
3972
+ if (!portalList) {
3973
+ const r = await o.client.get("/portals");
3974
+ portalList = Array.isArray(r) ? r : r && r.portals || [];
3975
+ }
3976
+ return (portalList || []).map((p) => {
3977
+ const t = p.themeInfo && p.themeInfo.key ? p.themeInfo : null;
3978
+ return {
3979
+ slug: String(p.slug || ""),
3980
+ name: String(p.name || p.slug || ""),
3981
+ theme: t ? { key: String(t.key), name: String(t.name || t.key) } : null
3982
+ };
3983
+ });
3984
+ }
3985
+ async function stageStructureNow() {
3986
+ stageUid = currentComponent(wsComponents, stageFile, stageFile.current || stageUid);
3987
+ const st = stateOf(stageFile, stageUid);
3988
+ let key = st.theme || "";
3989
+ if (!key && st.themePortal) {
3990
+ try {
3991
+ const p = (await stagePortals()).find((x) => x.slug === st.themePortal);
3992
+ key = p && p.theme ? p.theme.key : "";
3993
+ } catch (e) {
3994
+ o.log(`stage: portals not available (${e && e.message})`);
3995
+ }
3996
+ }
3997
+ const s = stageStructure(wsComponents, stageUid, st, key || STAGE_DEFAULT_THEME);
3998
+ stageMeta = s.stage;
3999
+ return s;
4000
+ }
4001
+ let structure = stageMode ? await stageStructureNow() : await readStructure(o.dir, ids);
3786
4002
  const staging = new Staging({
3787
4003
  client: o.client,
3788
4004
  app: inst && inst.app && inst.app.id ? { id: inst.app.id, scope: inst.app.scope } : null,
@@ -3859,11 +4075,11 @@ async function startDevServer(o) {
3859
4075
  const key = structure.theme;
3860
4076
  if (!key)
3861
4077
  return null;
3862
- const tdir = join13(o.dir, "themes", key);
3863
- if (existsSync13(join13(tdir, "tokens.json"))) {
3864
- const tokens = JSON.parse(readFileSync16(join13(tdir, "tokens.json"), "utf8"));
3865
- const meta = existsSync13(join13(tdir, "theme.json")) ? JSON.parse(readFileSync16(join13(tdir, "theme.json"), "utf8")) : {};
3866
- const css = existsSync13(join13(tdir, "theme.css")) ? readFileSync16(join13(tdir, "theme.css"), "utf8") : "";
4078
+ const tdir = join14(o.dir, "themes", key);
4079
+ if (existsSync14(join14(tdir, "tokens.json"))) {
4080
+ const tokens = JSON.parse(readFileSync17(join14(tdir, "tokens.json"), "utf8"));
4081
+ const meta = existsSync14(join14(tdir, "theme.json")) ? JSON.parse(readFileSync17(join14(tdir, "theme.json"), "utf8")) : {};
4082
+ const css = existsSync14(join14(tdir, "theme.css")) ? readFileSync17(join14(tdir, "theme.css"), "utf8") : "";
3867
4083
  return {
3868
4084
  key,
3869
4085
  name: meta.name || key,
@@ -3878,10 +4094,10 @@ async function startDevServer(o) {
3878
4094
  const f = Array.isArray(t && t.files) ? t.files.find((x) => x && x.path === name) : null;
3879
4095
  return f && typeof f.content === "string" ? f.content : "";
3880
4096
  };
3881
- const cache = join13(forgeDir, "dev", "themes", key, String(t && t.revision || 0));
4097
+ const cache = join14(forgeDir, "dev", "themes", key, String(t && t.revision || 0));
3882
4098
  mkdirSync7(cache, { recursive: true });
3883
- writeFileSync7(join13(cache, "tokens.json"), file("tokens.json") || "{}");
3884
- writeFileSync7(join13(cache, "theme.css"), file("theme.css"));
4099
+ writeFileSync8(join14(cache, "tokens.json"), file("tokens.json") || "{}");
4100
+ writeFileSync8(join14(cache, "theme.css"), file("theme.css"));
3885
4101
  const tokens = JSON.parse(file("tokens.json") || "{}");
3886
4102
  return {
3887
4103
  key,
@@ -3891,16 +4107,16 @@ async function startDevServer(o) {
3891
4107
  css: file("theme.css")
3892
4108
  };
3893
4109
  } catch (e) {
3894
- const dir = join13(forgeDir, "dev", "themes", key);
3895
- const revs = existsSync13(dir) ? readdirSync5(dir).filter((r) => /^\d+$/.test(r)).sort((a, b) => Number(b) - Number(a)) : [];
4110
+ const dir = join14(forgeDir, "dev", "themes", key);
4111
+ const revs = existsSync14(dir) ? readdirSync5(dir).filter((r) => /^\d+$/.test(r)).sort((a, b) => Number(b) - Number(a)) : [];
3896
4112
  if (revs.length) {
3897
- const tokens = JSON.parse(readFileSync16(join13(dir, revs[0], "tokens.json"), "utf8") || "{}");
4113
+ const tokens = JSON.parse(readFileSync17(join14(dir, revs[0], "tokens.json"), "utf8") || "{}");
3898
4114
  return {
3899
4115
  key,
3900
4116
  name: key,
3901
4117
  tokens: tokens.light || tokens,
3902
4118
  tokensDark: tokens.dark || null,
3903
- css: readFileSync16(join13(dir, revs[0], "theme.css"), "utf8")
4119
+ css: readFileSync17(join14(dir, revs[0], "theme.css"), "utf8")
3904
4120
  };
3905
4121
  }
3906
4122
  o.log(`theme ${key}: not available (${e && e.message})`);
@@ -3912,11 +4128,11 @@ async function startDevServer(o) {
3912
4128
  const meta = new Map;
3913
4129
  const missing = new Map;
3914
4130
  const assets = o.assetsDir;
3915
- const sheet = new Sheet(portalInput(), { cssDir: join13(assets, "css") });
3916
- const framework = new Sheet(frameworkInput(), { cssDir: join13(assets, "css") });
3917
- const kitCandidatesFile = join13(assets, "kit-candidates.json");
3918
- if (existsSync13(kitCandidatesFile))
3919
- await sheet.add(JSON.parse(readFileSync16(kitCandidatesFile, "utf8")));
4131
+ const sheet = new Sheet(portalInput(), { cssDir: join14(assets, "css") });
4132
+ const framework = new Sheet(frameworkInput(), { cssDir: join14(assets, "css") });
4133
+ const kitCandidatesFile = join14(assets, "kit-candidates.json");
4134
+ if (existsSync14(kitCandidatesFile))
4135
+ await sheet.add(JSON.parse(readFileSync17(kitCandidatesFile, "utf8")));
3920
4136
  async function compileOne(uid) {
3921
4137
  const ws = wsComponents.get(uid);
3922
4138
  let dir;
@@ -4059,6 +4275,7 @@ async function startDevServer(o) {
4059
4275
  cellRenderers: structure.cellRenderers,
4060
4276
  components,
4061
4277
  runtime,
4278
+ stage: stageMode ? stageMeta : null,
4062
4279
  session: session.mode,
4063
4280
  sheet: `/__rpf/sheet/${gen}/${sheet.rev}.css`,
4064
4281
  problems: problems()
@@ -4069,9 +4286,9 @@ async function startDevServer(o) {
4069
4286
  }
4070
4287
  async function hostChunk(folder, name, valid) {
4071
4288
  const version = String(inst && inst.reactPortal || "unknown").replace(/[^0-9A-Za-z._-]/g, "_");
4072
- const file = join13(forgeDir, "dev", folder, version, `${name}.js`);
4073
- if (existsSync13(file))
4074
- return readFileSync16(file, "utf8");
4289
+ const file = join14(forgeDir, "dev", folder, version, `${name}.js`);
4290
+ if (existsSync14(file))
4291
+ return readFileSync17(file, "utf8");
4075
4292
  const up = await upstream(`/uxasset/externals/@x-312987/portal-host/${name}.jsdbx`, {
4076
4293
  headers: { Accept: "*/*" }
4077
4294
  });
@@ -4081,7 +4298,7 @@ async function startDevServer(o) {
4081
4298
  if (!/export\s*\{/.test(text) || !valid(text))
4082
4299
  throw new Error(`${name}: not the expected module`);
4083
4300
  mkdirSync7(dirname9(file), { recursive: true });
4084
- writeFileSync7(file, text);
4301
+ writeFileSync8(file, text);
4085
4302
  return text;
4086
4303
  }
4087
4304
  const clients = new Set;
@@ -4130,14 +4347,25 @@ async function startDevServer(o) {
4130
4347
  if (/(^|\/)server\.js$|\.server\.(js|ts)$/.test(m[3]))
4131
4348
  continue;
4132
4349
  uids.add(`${m[1]}/${m[2]}`);
4133
- } else if (f === "portal.mjs")
4350
+ if (stageMode && /^(component|regions)\.json$|^options\.schema\.json$/.test(m[3]))
4351
+ structureChanged = true;
4352
+ } else if (f === "portal.mjs" && !stageMode)
4134
4353
  structureChanged = true;
4135
- else if (f.startsWith("themes/"))
4354
+ else if (f === STAGE_FILE && stageMode) {
4355
+ const fresh = readStageFile(o.dir);
4356
+ if (JSON.stringify(fresh) !== JSON.stringify(stageFile)) {
4357
+ stageFile = fresh;
4358
+ structureChanged = true;
4359
+ themeChanged = true;
4360
+ }
4361
+ } else if (f.startsWith("themes/"))
4136
4362
  themeChanged = true;
4137
4363
  }
4138
4364
  if (structureChanged) {
4139
4365
  try {
4140
- structure = await readStructure(o.dir, ids);
4366
+ if (stageMode)
4367
+ wsComponents = workspaceComponents(o.dir);
4368
+ structure = stageMode ? await stageStructureNow() : await readStructure(o.dir, ids);
4141
4369
  await compileClosure(structure.components);
4142
4370
  } catch (e) {
4143
4371
  emit({
@@ -4191,7 +4419,7 @@ async function startDevServer(o) {
4191
4419
  port = await tryPort(0);
4192
4420
  try {
4193
4421
  mkdirSync7(dirname9(runFile), { recursive: true });
4194
- writeFileSync7(runFile, JSON.stringify({ key: secret, port }, null, 2), { mode: 384 });
4422
+ writeFileSync8(runFile, JSON.stringify({ key: secret, port }, null, 2), { mode: 384 });
4195
4423
  } catch {}
4196
4424
  const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
4197
4425
  const secretBuf = Buffer.from(secret);
@@ -4502,6 +4730,88 @@ async function startDevServer(o) {
4502
4730
  <script type="module" src="/__rpf/host/boot.js"></script>
4503
4731
  </head><body style="margin:0"><rp-dev-portal style="display:block;height:100vh"></rp-dev-portal></body></html>`;
4504
4732
  }
4733
+ function stageHtml() {
4734
+ return `<!doctype html>
4735
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
4736
+ <title>Stage | rpf dev</title>
4737
+ <link rel="icon" href="data:,">
4738
+ <script type="module" src="/__rpf/host/stage.js"></script>
4739
+ </head><body><div id="rpf-stage"></div></body></html>`;
4740
+ }
4741
+ async function applyStage() {
4742
+ structure = await stageStructureNow();
4743
+ await compileClosure(structure.components);
4744
+ theme = await readTheme();
4745
+ await feedSheet();
4746
+ gen++;
4747
+ emit({ type: "structure", gen });
4748
+ emit({ type: "problems", problems: problems() });
4749
+ }
4750
+ async function stageInfo() {
4751
+ const server = await staging.availability().catch(() => null);
4752
+ return {
4753
+ slug: structure.slug,
4754
+ current: stageUid,
4755
+ components: Array.from(wsComponents.values()).sort((a, b) => a.uniqueId.localeCompare(b.uniqueId)).map((c) => ({
4756
+ uniqueId: c.uniqueId,
4757
+ name: c.name,
4758
+ kind: c.kind,
4759
+ serverMode: c.serverMode,
4760
+ defaults: c.defaults,
4761
+ optionsSchema: c.optionsSchema
4762
+ })),
4763
+ state: stateOf(stageFile, stageUid),
4764
+ server: server ? { available: !!server.available, message: server.message } : { available: false },
4765
+ instance: o.config.instance
4766
+ };
4767
+ }
4768
+ async function stageRoute(req, res, url) {
4769
+ const path = url.pathname;
4770
+ if (path === "/__rpf/stage") {
4771
+ send(res, 200, stageHtml(), MIME[".html"], { "Content-Security-Policy": csp });
4772
+ return true;
4773
+ }
4774
+ if (path === "/__rpf/stage/info") {
4775
+ const asked = url.searchParams.get("c") || "";
4776
+ if (asked && asked !== stageUid && wsComponents.has(asked)) {
4777
+ stageFile.current = asked;
4778
+ await writeStageFile(o.dir, stageFile);
4779
+ await (rebuilding = rebuilding.then(applyStage));
4780
+ }
4781
+ send(res, 200, JSON.stringify(await stageInfo()), MIME[".json"]);
4782
+ return true;
4783
+ }
4784
+ if (path === "/__rpf/stage/state" && req.method === "PUT") {
4785
+ let body = null;
4786
+ try {
4787
+ body = JSON.parse((await readBody(req)).toString("utf8") || "null");
4788
+ } catch {
4789
+ body = null;
4790
+ }
4791
+ const uid = body && typeof body.component === "string" ? body.component : "";
4792
+ if (!uid || !wsComponents.has(uid)) {
4793
+ send(res, 400, JSON.stringify({ error: `No component "${uid}" in this workspace` }), MIME[".json"]);
4794
+ return true;
4795
+ }
4796
+ stageFile.components[uid] = cleanStageState(body.state);
4797
+ stageFile.current = uid;
4798
+ await writeStageFile(o.dir, stageFile);
4799
+ await (rebuilding = rebuilding.then(applyStage));
4800
+ send(res, 200, JSON.stringify({ slug: structure.slug, gen }), MIME[".json"]);
4801
+ return true;
4802
+ }
4803
+ if (path === "/__rpf/stage/portals") {
4804
+ send(res, 200, JSON.stringify(await stagePortals()), MIME[".json"]);
4805
+ return true;
4806
+ }
4807
+ if (path === "/__rpf/stage/themes") {
4808
+ const r = await o.client.get("/themes");
4809
+ const list = (Array.isArray(r) ? r : r && r.themes || []).filter((t) => t && t.active !== false);
4810
+ send(res, 200, JSON.stringify(list.map((t) => ({ key: String(t.key), name: String(t.name || t.key) }))), MIME[".json"]);
4811
+ return true;
4812
+ }
4813
+ return false;
4814
+ }
4505
4815
  const server = createServer2(async (req, res) => {
4506
4816
  try {
4507
4817
  const host = String(req.headers.host || "");
@@ -4514,7 +4824,7 @@ async function startDevServer(o) {
4514
4824
  if (k.length !== secret.length || !timingSafeEqual(Buffer.from(k), secretBuf))
4515
4825
  return send(res, 403, "rpf dev: bad key");
4516
4826
  const asked = url.searchParams.get("to") || "";
4517
- const to = /^\/(?!\/)[^\\]*$/.test(asked) ? asked : `/x/312987/portal/site/${encodeURIComponent(structure.slug)}`;
4827
+ const to = /^\/(?!\/)[^\\]*$/.test(asked) ? asked : stageMode ? "/__rpf/stage" : `/x/312987/portal/site/${encodeURIComponent(structure.slug)}`;
4518
4828
  res.writeHead(302, {
4519
4829
  "Set-Cookie": [
4520
4830
  `rpf_run=${secret}; HttpOnly; SameSite=Strict; Path=/`,
@@ -4532,10 +4842,12 @@ async function startDevServer(o) {
4532
4842
  return send(res, 403, "rpf dev: cross-origin request refused");
4533
4843
  if (path.startsWith("/x/312987/portal/site/")) {
4534
4844
  const asked = decodeURIComponent(path.slice("/x/312987/portal/site/".length).split("/")[0] || "");
4535
- if (asked && asked !== structure.slug)
4845
+ if (asked && asked !== structure.slug && !stageMode)
4536
4846
  return send(res, 404, `<!doctype html><meta charset="utf-8"><title>rpf dev</title><body style="font:15px system-ui;max-width:640px;margin:60px auto;line-height:1.5"><h2>rpf dev: this server serves "${escapeHtml(structure.slug)}"</h2><p>The portal <code>${escapeHtml(asked)}</code> isn't in this workspace (${escapeHtml(structure.name)}). Each <code>rpf dev</code> server previews its own workspace's portal: run <code>rpf dev</code> in the workspace of <code>${escapeHtml(asked)}</code>, or <code>rpf pull</code> it into one first.</p><p><a href="/x/312987/portal/site/${encodeURIComponent(structure.slug)}">Open ${escapeHtml(structure.name)}</a></p></body>`, MIME[".html"]);
4537
4847
  return send(res, 200, shellHtml(), MIME[".html"], { "Content-Security-Policy": csp });
4538
4848
  }
4849
+ if (stageMode && path.startsWith("/__rpf/stage") && await stageRoute(req, res, url))
4850
+ return;
4539
4851
  if (path === "/__rpf/api/boot")
4540
4852
  return send(res, 200, JSON.stringify(bootJson()), MIME[".json"]);
4541
4853
  if (path === "/__rpf/events") {
@@ -4552,7 +4864,12 @@ async function startDevServer(o) {
4552
4864
  return;
4553
4865
  }
4554
4866
  if (path === "/__rpf/status")
4555
- return send(res, 200, JSON.stringify({ ...statsJson(), staging: await staging.summary(), problems: problems() }), MIME[".json"]);
4867
+ return send(res, 200, JSON.stringify({
4868
+ ...statsJson(),
4869
+ staging: await staging.summary(),
4870
+ problems: problems(),
4871
+ stage: stageMode ? { url: "/__rpf/stage", component: stageUid, slug: structure.slug } : undefined
4872
+ }), MIME[".json"]);
4556
4873
  const c = /^\/__rpf\/c\/(\d+)\/([a-z][a-z0-9_-]*)\/([a-z][a-z0-9-]*)\.js$/.exec(path);
4557
4874
  if (c) {
4558
4875
  const uid = `${c[2]}/${c[3]}`;
@@ -4584,10 +4901,10 @@ ${msg}`)}); }`, MIME[".js"]);
4584
4901
  return send(res, 200, await framework.text(), MIME[".css"]);
4585
4902
  if (path.startsWith("/__rpf/host/")) {
4586
4903
  const rel = normalize2(decodeURIComponent(path.slice("/__rpf/host/".length)));
4587
- const abs = join13(assets, rel);
4588
- if (relative7(assets, abs).startsWith("..") || !existsSync13(abs))
4904
+ const abs = join14(assets, rel);
4905
+ if (relative7(assets, abs).startsWith("..") || !existsSync14(abs))
4589
4906
  return send(res, 404, "not found");
4590
- return send(res, 200, readFileSync16(abs), MIME[extname(abs)] || "application/octet-stream", {
4907
+ return send(res, 200, readFileSync17(abs), MIME[extname(abs)] || "application/octet-stream", {
4591
4908
  "Cache-Control": "no-cache"
4592
4909
  });
4593
4910
  }
@@ -4636,7 +4953,7 @@ ${msg}`)}); }`, MIME[".js"]);
4636
4953
  };
4637
4954
  }
4638
4955
  const url = `http://127.0.0.1:${port}`;
4639
- const sessionFile = join13(forgeDir, "dev", "session.json");
4956
+ const sessionFile = join14(forgeDir, "dev", "session.json");
4640
4957
  try {
4641
4958
  const info = {
4642
4959
  url,
@@ -4645,7 +4962,7 @@ ${msg}`)}); }`, MIME[".js"]);
4645
4962
  pid: process.pid,
4646
4963
  startedAt: new Date().toISOString()
4647
4964
  };
4648
- writeFileSync7(sessionFile, JSON.stringify(info, null, 2), { mode: 384 });
4965
+ writeFileSync8(sessionFile, JSON.stringify(info, null, 2), { mode: 384 });
4649
4966
  } catch {}
4650
4967
  o.log(`ready in ${Date.now() - t0} ms`);
4651
4968
  staging.preflight().then(async (list) => {
@@ -4719,6 +5036,8 @@ function matchRoute(pattern, path) {
4719
5036
  }
4720
5037
  var MIME, DROP_REQ, DROP_RES, mean = (a) => a.length ? Math.round(a.reduce((x, y) => x + y, 0) / a.length) : 0, CSP = "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; frame-src 'self'; object-src 'none'; base-uri 'none'";
4721
5038
  var init_server = __esm(() => {
5039
+ init_stage();
5040
+ init_stage_protocol();
4722
5041
  init_manifest();
4723
5042
  init_layout();
4724
5043
  init_compile();
@@ -4768,16 +5087,16 @@ var init_server = __esm(() => {
4768
5087
  });
4769
5088
 
4770
5089
  // src/commands/dev.ts
4771
- import { existsSync as existsSync14 } from "node:fs";
4772
- import { basename, dirname as dirname10, join as join14, resolve as resolve5 } from "node:path";
5090
+ import { existsSync as existsSync15 } from "node:fs";
5091
+ import { basename, dirname as dirname10, join as join15, resolve as resolve5 } from "node:path";
4773
5092
  import { fileURLToPath as fileURLToPath2 } from "node:url";
4774
5093
  import { spawn as spawn2 } from "node:child_process";
4775
5094
  function assetsDir() {
4776
5095
  const here = dirname10(fileURLToPath2(import.meta.url));
4777
5096
  const fromSource = basename(here) === "commands";
4778
- const candidates = fromSource ? [resolve5(here, "..", "..", "..", "dev-host", "dist"), join14(here, "..", "..", "assets", "dev-host")] : [join14(here, "..", "assets", "dev-host")];
5097
+ const candidates = fromSource ? [resolve5(here, "..", "..", "..", "dev-host", "dist"), join15(here, "..", "..", "assets", "dev-host")] : [join15(here, "..", "assets", "dev-host")];
4779
5098
  for (const c of candidates)
4780
- if (existsSync14(join14(c, "boot.js")))
5099
+ if (existsSync15(join15(c, "boot.js")))
4781
5100
  return c;
4782
5101
  throw new CliError(EXIT.failed, "dev_host_missing", fromSource ? "The dev host assets are missing: build packages/dev-host (bun run build there)" : "The dev host assets are missing from this install: reinstall rpf");
4783
5102
  }
@@ -4790,8 +5109,8 @@ async function dev(ctx, o) {
4790
5109
  const ws = findWorkspace(ctx.opts.dir ? resolve5(ctx.opts.dir) : process.cwd());
4791
5110
  if (!ws)
4792
5111
  throw usage("No workspace here: cd into one (a folder with forge.workspace.json and portal.mjs) or pass --dir");
4793
- if (!existsSync14(join14(ws, "portal.mjs")))
4794
- throw usage(`${ws} has no portal.mjs (component-only workspaces come later)`);
5112
+ if (!existsSync15(join15(ws, "portal.mjs")) && !isComponentWorkspace(ws))
5113
+ throw usage(`${ws} has no portal.mjs and no components`);
4795
5114
  const r = resolveFor({ ...ctx, opts: { ...ctx.opts, dir: ws } });
4796
5115
  const client = new ForgeClient(r.config);
4797
5116
  const log = (s) => ctx.out.info(`[rpf dev] ${s}`);
@@ -4824,9 +5143,10 @@ async function dev(ctx, o) {
4824
5143
  process.once("SIGTERM", stop);
4825
5144
  }
4826
5145
  function registerDev(program, run) {
4827
- program.command("dev").description("Preview the workspace portal locally with live instance data; saving a file updates the page").option("--port <n>", "listen on this port (default: a random free port)").option("--open", "open the preview in the default browser").option("--new-key", "rotate the local run key (browsers that entered before must use the new link)").action(run((ctx) => dev(ctx, ctx.opts)));
5146
+ program.command("dev").description("Preview the workspace portal locally with live instance data (in a component workspace: the component stage); saving a file updates the page").option("--port <n>", "listen on this port (default: a random free port)").option("--open", "open the preview in the default browser").option("--new-key", "rotate the local run key (browsers that entered before must use the new link)").action(run((ctx) => dev(ctx, ctx.opts)));
4828
5147
  }
4829
5148
  var init_dev = __esm(() => {
5149
+ init_stage();
4830
5150
  init_client();
4831
5151
  init_profiles();
4832
5152
  init_server();
@@ -5089,20 +5409,20 @@ var init_doctor = __esm(() => {
5089
5409
  });
5090
5410
 
5091
5411
  // ../forge-core/src/workspace/remote.ts
5092
- import { existsSync as existsSync15, readdirSync as readdirSync6, statSync as statSync4 } from "node:fs";
5093
- import { delimiter, join as join15, relative as relative8 } from "node:path";
5412
+ import { existsSync as existsSync16, readdirSync as readdirSync6, statSync as statSync4 } from "node:fs";
5413
+ import { delimiter, join as join16, relative as relative8 } from "node:path";
5094
5414
  function candidates() {
5095
5415
  const roots2 = (roots.apps ? [roots.apps] : []).concat((process.env.FORGE_WORKSPACE_ROOTS || "").split(delimiter).filter(Boolean));
5096
5416
  const out = [];
5097
5417
  for (const root of roots2) {
5098
- if (!existsSync15(root))
5418
+ if (!existsSync16(root))
5099
5419
  continue;
5100
- if (existsSync15(join15(root, MANIFEST)))
5420
+ if (existsSync16(join16(root, MANIFEST)))
5101
5421
  out.push(root);
5102
5422
  for (const name of readdirSync6(root)) {
5103
- const d = join15(root, name);
5423
+ const d = join16(root, name);
5104
5424
  try {
5105
- if (statSync4(d).isDirectory() && existsSync15(join15(d, MANIFEST)))
5425
+ if (statSync4(d).isDirectory() && existsSync16(join16(d, MANIFEST)))
5106
5426
  out.push(d);
5107
5427
  } catch {}
5108
5428
  }
@@ -5354,14 +5674,15 @@ var init_normalize = __esm(() => {
5354
5674
  });
5355
5675
 
5356
5676
  // ../forge-core/src/workspace/snapshot.ts
5357
- async function fetchSnapshot(client, portal, opts = {}) {
5677
+ async function fetchSnapshot(client, target, opts = {}) {
5678
+ const where = typeof target === "string" ? { portal: target } : { app: target.app, components: target.components.join(",") || undefined };
5358
5679
  let offset = 0;
5359
5680
  let first = null;
5360
5681
  const components = [];
5361
5682
  const refs = {};
5362
5683
  for (let guard = 0;guard < 200; guard++) {
5363
5684
  const chunk = await client.get("/workspace/snapshot", {
5364
- portal,
5685
+ ...where,
5365
5686
  offset,
5366
5687
  budgetKb: opts.budgetKb,
5367
5688
  content: opts.content === false ? "false" : undefined
@@ -5376,12 +5697,20 @@ async function fetchSnapshot(client, portal, opts = {}) {
5376
5697
  throw new Error("snapshot paging did not advance");
5377
5698
  offset = chunk.components.next;
5378
5699
  }
5700
+ if (typeof target !== "string" && !first.app)
5701
+ throw new Error('The instance does not support component workspaces (React Portal with Forge feature "component-workspaces" needed)');
5379
5702
  return {
5380
5703
  format: first.format,
5704
+ ...typeof target === "string" ? {} : {
5705
+ kind: "component",
5706
+ usage: first.usage || {},
5707
+ missing: first.missing || [],
5708
+ foreign: first.foreign || []
5709
+ },
5381
5710
  reactPortal: first.reactPortal,
5382
5711
  instance: first.instance,
5383
5712
  user: first.user,
5384
- portal: first.portal,
5713
+ portal: first.portal || { id: "", slug: "", name: "", app: first.app },
5385
5714
  schema: first.schema,
5386
5715
  records: first.records,
5387
5716
  theme: first.theme,
@@ -5397,7 +5726,7 @@ function fetchImage(client, portal, name) {
5397
5726
  }
5398
5727
 
5399
5728
  // ../forge-core/src/workspace/units.ts
5400
- import { readFileSync as readFileSync17 } from "node:fs";
5729
+ import { readFileSync as readFileSync18 } from "node:fs";
5401
5730
  function ownFields(kind, node) {
5402
5731
  const slots = CHILD_SLOTS[kind] || [];
5403
5732
  const out = {};
@@ -5409,6 +5738,8 @@ function ownFields(kind, node) {
5409
5738
  function decompose(def, aliases) {
5410
5739
  const units = new Map;
5411
5740
  const duplicates = [];
5741
+ if (!def)
5742
+ return { units, duplicates };
5412
5743
  const al = (k) => aliases && aliases.get(k) || k;
5413
5744
  const add = (u) => {
5414
5745
  if (units.has(u.key)) {
@@ -5710,7 +6041,7 @@ function setUnits(doc, changes) {
5710
6041
  function headerOf(file) {
5711
6042
  let text = "";
5712
6043
  try {
5713
- text = readFileSync17(file, "utf8");
6044
+ text = readFileSync18(file, "utf8");
5714
6045
  } catch {
5715
6046
  return "";
5716
6047
  }
@@ -5870,6 +6201,8 @@ function serialize(snap, opts) {
5870
6201
  };
5871
6202
  const of = (table) => snap.records.filter((r) => r.table === table);
5872
6203
  const portalRec = of(TB.portal)[0];
6204
+ if (!portalRec)
6205
+ return componentsOnly(snap, records, check, notes, hashMismatches, ignored);
5873
6206
  const pages = of(TB.page);
5874
6207
  const variants = of(TB.variant);
5875
6208
  const panels = of(TB.panel);
@@ -6328,6 +6661,16 @@ function serialize(snap, opts) {
6328
6661
  dependencies[r.uniqueId] = { id: r.id, scope: r.scope, revision: r.revision, build: r.build };
6329
6662
  return { files, portal: def, records, dependencies, ignored, notes, hashMismatches };
6330
6663
  }
6664
+ function componentsOnly(snap, records, check, notes, hashMismatches, ignored) {
6665
+ const files = new Map;
6666
+ for (const c of snap.components.slice().sort((a, b) => a.uniqueId.localeCompare(b.uniqueId)))
6667
+ writeComponent(c, files, records, check, notes);
6668
+ const dependencies = {};
6669
+ for (const r of Object.values(snap.refs))
6670
+ if (r.scope !== snap.portal.app.id)
6671
+ dependencies[r.uniqueId] = { id: r.id, scope: r.scope, revision: r.revision, build: r.build };
6672
+ return { files, portal: null, records, dependencies, ignored, notes, hashMismatches };
6673
+ }
6331
6674
  function writeComponent(c, files, records, check, notes) {
6332
6675
  const f = c.fields;
6333
6676
  const [ns, key] = c.uniqueId.split("/");
@@ -6442,9 +6785,38 @@ var init_serialize = __esm(() => {
6442
6785
  };
6443
6786
  });
6444
6787
 
6788
+ // ../forge-core/src/workspace/tracked.ts
6789
+ import { existsSync as existsSync17, readdirSync as readdirSync7 } from "node:fs";
6790
+ import { join as join17 } from "node:path";
6791
+ function localComponentIds(dir) {
6792
+ const out = [];
6793
+ const root = join17(dir, "components");
6794
+ if (!existsSync17(root))
6795
+ return out;
6796
+ for (const ns of readdirSync7(root))
6797
+ if (ns.startsWith("@")) {
6798
+ for (const key of readdirSync7(join17(root, ns)))
6799
+ if (existsSync17(join17(root, ns, key, "component.json")))
6800
+ out.push(`${ns.slice(1)}/${key}`);
6801
+ }
6802
+ return out.sort();
6803
+ }
6804
+ function trackedComponents(dir, inst, extra = []) {
6805
+ const set = new Set(extra);
6806
+ for (const u of inst && inst.components || [])
6807
+ set.add(u);
6808
+ for (const k of Object.keys(inst && inst.records || {}))
6809
+ if (k.startsWith("component:"))
6810
+ set.add(k.slice(10));
6811
+ for (const u of localComponentIds(dir))
6812
+ set.add(u);
6813
+ return Array.from(set).sort();
6814
+ }
6815
+ var init_tracked = () => {};
6816
+
6445
6817
  // ../forge-core/src/workspace/compare.ts
6446
- import { readFileSync as readFileSync18 } from "node:fs";
6447
- import { join as join16 } from "node:path";
6818
+ import { readFileSync as readFileSync19 } from "node:fs";
6819
+ import { join as join18 } from "node:path";
6448
6820
  async function compareDirs(a, b, opts = {}) {
6449
6821
  const skip = opts.skip || LOCAL_ONLY;
6450
6822
  const fa = listFiles(a).filter((p) => !skip.has(p));
@@ -6459,8 +6831,8 @@ async function compareDirs(a, b, opts = {}) {
6459
6831
  portal: null
6460
6832
  };
6461
6833
  for (const p of fa.filter((x) => sb.has(x))) {
6462
- const ba = readFileSync18(join16(a, p));
6463
- const bb = readFileSync18(join16(b, p));
6834
+ const ba = readFileSync19(join18(a, p));
6835
+ const bb = readFileSync19(join18(b, p));
6464
6836
  if (sha2562(ba) === sha2562(bb)) {
6465
6837
  out.same++;
6466
6838
  continue;
@@ -6482,7 +6854,7 @@ async function compareDirs(a, b, opts = {}) {
6482
6854
  out.differ.push({ path: p, kind: await samePrettier(p, ta, tb) ? "format-only" : "content" });
6483
6855
  }
6484
6856
  if (sa.has("portal.mjs") && sb.has("portal.mjs"))
6485
- out.portal = diffData(await importPortal(join16(a, "portal.mjs")), await importPortal(join16(b, "portal.mjs")));
6857
+ out.portal = diffData(await importPortal(join18(a, "portal.mjs")), await importPortal(join18(b, "portal.mjs")));
6486
6858
  return out;
6487
6859
  }
6488
6860
  function idOf(v, i) {
@@ -6547,8 +6919,8 @@ var init_compare = __esm(() => {
6547
6919
  });
6548
6920
 
6549
6921
  // ../forge-core/src/workspace/rename.ts
6550
- import { cpSync, existsSync as existsSync16, readFileSync as readFileSync19 } from "node:fs";
6551
- import { join as join17 } from "node:path";
6922
+ import { cpSync, existsSync as existsSync18, readFileSync as readFileSync20 } from "node:fs";
6923
+ import { join as join19 } from "node:path";
6552
6924
  function renameRefs(def, refs) {
6553
6925
  const changed = [];
6554
6926
  if (!def || !refs.pages.size && !refs.panels.size)
@@ -6710,7 +7082,7 @@ async function rename(args) {
6710
7082
  const value = rule.value(from, to);
6711
7083
  if (value === null)
6712
7084
  throw new Error(kind === "variant" || kind === "item" || kind === "placement" ? `${to}: only the last part of the key may change (same ${kind === "variant" ? "page" : "parent"}), with letters, digits, - _ .` : `${to} is not a valid ${kind} key`);
6713
- const file = join17(dir, "portal.mjs");
7085
+ const file = join19(dir, "portal.mjs");
6714
7086
  const def = await importPortal(file);
6715
7087
  const before = decompose(def).units;
6716
7088
  const u = before.get(from);
@@ -6796,14 +7168,14 @@ async function renameComponent(dir, manifest, from, to) {
6796
7168
  const newUid = `${m2[1]}/${m2[2]}`;
6797
7169
  const oldDir = componentDir(oldUid);
6798
7170
  const newDir = componentDir(newUid);
6799
- if (!existsSync16(join17(dir, oldDir, "component.json")))
7171
+ if (!existsSync18(join19(dir, oldDir, "component.json")))
6800
7172
  throw new Error(`${oldDir} has no component.json`);
6801
- if (existsSync16(join17(dir, newDir)))
7173
+ if (existsSync18(join19(dir, newDir)))
6802
7174
  throw new Error(`${newDir} already exists`);
6803
7175
  const onInstance = Object.values(manifest.instances).some((inst) => !!inst.records[`component:${oldUid}`]);
6804
- cpSync(join17(dir, oldDir), join17(dir, newDir), { recursive: true });
7176
+ cpSync(join19(dir, oldDir), join19(dir, newDir), { recursive: true });
6805
7177
  const changed = [newDir + " (copy)"];
6806
- const file = join17(dir, "portal.mjs");
7178
+ const file = join19(dir, "portal.mjs");
6807
7179
  const def = await importPortal(file);
6808
7180
  const oldRef = mapKey(oldUid);
6809
7181
  const newRef = mapKey(newUid);
@@ -6830,7 +7202,7 @@ async function renameComponent(dir, manifest, from, to) {
6830
7202
  for (const p of listFiles(dir)) {
6831
7203
  if (!p.startsWith("components/") || !/\.(tsx?|jsx?|mjs)$/.test(p) || p.startsWith(oldDir))
6832
7204
  continue;
6833
- const text = readFileSync19(join17(dir, p), "utf8");
7205
+ const text = readFileSync20(join19(dir, p), "utf8");
6834
7206
  const next = text.replace(spec, (_m, q, ns) => `${q}${ns}:${newUid}${q}`);
6835
7207
  if (next !== text) {
6836
7208
  writeText(dir, p, next);
@@ -6838,15 +7210,15 @@ async function renameComponent(dir, manifest, from, to) {
6838
7210
  }
6839
7211
  }
6840
7212
  if (onInstance) {
6841
- const cj = join17(dir, oldDir, "component.json");
6842
- const meta = JSON.parse(readFileSync19(cj, "utf8"));
7213
+ const cj = join19(dir, oldDir, "component.json");
7214
+ const meta = JSON.parse(readFileSync20(cj, "utf8"));
6843
7215
  meta.active = false;
6844
7216
  writeText(dir, oldDir + "component.json", await formatFile(oldDir + "component.json", JSON.stringify(meta, null, 4) + `
6845
7217
  `));
6846
7218
  changed.push(oldDir + "component.json (active: false)");
6847
7219
  } else {
6848
7220
  const { rmSync } = await import("node:fs");
6849
- rmSync(join17(dir, oldDir), { recursive: true, force: true });
7221
+ rmSync(join19(dir, oldDir), { recursive: true, force: true });
6850
7222
  changed.push(oldDir + " (moved: it was never pushed)");
6851
7223
  }
6852
7224
  return {
@@ -6934,13 +7306,13 @@ var init_rename = __esm(() => {
6934
7306
 
6935
7307
  // ../forge-core/src/workspace/status.ts
6936
7308
  import { spawnSync as spawnSync2 } from "node:child_process";
6937
- import { existsSync as existsSync17, readFileSync as readFileSync20 } from "node:fs";
6938
- import { isAbsolute as isAbsolute2, join as join18, relative as relative9, resolve as resolve6, sep as sep5 } from "node:path";
7309
+ import { existsSync as existsSync19, readFileSync as readFileSync21 } from "node:fs";
7310
+ import { isAbsolute as isAbsolute2, join as join20, relative as relative9, resolve as resolve6, sep as sep5 } from "node:path";
6939
7311
  function workspaceDir(arg) {
6940
7312
  if (isAbsolute2(arg))
6941
7313
  return arg;
6942
7314
  if (roots.apps && /^[a-z][a-z0-9-]*$/.test(arg))
6943
- return join18(roots.apps, arg);
7315
+ return join20(roots.apps, arg);
6944
7316
  return resolve6(arg);
6945
7317
  }
6946
7318
  function fileHash(path, data) {
@@ -7007,16 +7379,16 @@ function gitBase(dir) {
7007
7379
  };
7008
7380
  }
7009
7381
  async function loadBase(dir, inst, r, rv) {
7010
- const baseDir = join18(dir, FORGE_DIR, "base");
7382
+ const baseDir = join20(dir, FORGE_DIR, "base");
7011
7383
  const notes = [];
7012
- if (existsSync17(join18(baseDir, "portal.mjs"))) {
7384
+ if (hasBase(baseDir)) {
7013
7385
  const files = new Map;
7014
7386
  for (const p of listFiles(baseDir)) {
7015
7387
  if (p === "portal.mjs" || LOCAL_ONLY.has(p))
7016
7388
  continue;
7017
- files.set(p, fileHash(p, readFileSync20(join18(baseDir, p))));
7389
+ files.set(p, fileHash(p, readFileSync21(join20(baseDir, p))));
7018
7390
  }
7019
- const def = await importPortal(join18(baseDir, "portal.mjs"));
7391
+ const def = existsSync19(join20(baseDir, "portal.mjs")) ? await importPortal(join20(baseDir, "portal.mjs")) : null;
7020
7392
  const units = new Map(aliasedUnits(def, rv).units);
7021
7393
  for (const id of inst.unknownBase || []) {
7022
7394
  if (isUnitKey(id))
@@ -7029,7 +7401,7 @@ async function loadBase(dir, inst, r, rv) {
7029
7401
  files,
7030
7402
  units,
7031
7403
  def,
7032
- content: (p) => existsSync17(join18(baseDir, p)) ? readFileSync20(join18(baseDir, p)) : null,
7404
+ content: (p) => existsSync19(join20(baseDir, p)) ? readFileSync21(join20(baseDir, p)) : null,
7033
7405
  git: null,
7034
7406
  notes
7035
7407
  };
@@ -7179,6 +7551,12 @@ async function renderInstance(snap, inst, manifest, full, baseFiles, localAssets
7179
7551
  function snapshotSource(client, portal) {
7180
7552
  return (content) => fetchSnapshot(client, portal, { content });
7181
7553
  }
7554
+ function componentSnapshotSource(client, dir, inst) {
7555
+ return (content) => fetchSnapshot(client, { app: inst.app.id, components: trackedComponents(dir, inst) }, { content });
7556
+ }
7557
+ function hasBase(baseDir) {
7558
+ return existsSync19(join20(baseDir, "portal.mjs")) || existsSync19(join20(baseDir, BASE_MARK));
7559
+ }
7182
7560
  async function analyze(dirArg, client, opts = {}) {
7183
7561
  const dir = workspaceDir(dirArg);
7184
7562
  const manifest = readManifest(dir);
@@ -7188,15 +7566,18 @@ async function analyze(dirArg, client, opts = {}) {
7188
7566
  if (!keys.length)
7189
7567
  throw new Error(`${MANIFEST} tracks no instance`);
7190
7568
  const first = manifest.instances[keys[0]];
7191
- const source = opts.source || snapshotSource(client, first.portal.id);
7569
+ const componentWs = isComponentManifest(manifest);
7570
+ const source = opts.source || (componentWs ? componentSnapshotSource(client, dir, first) : snapshotSource(client, first.portal.id));
7192
7571
  let snap = opts.snapshot || await source(!!opts.full);
7193
7572
  let full = !!opts.full || (opts.snapshot ? opts.snapshot.components.every((c) => ("client_script" in c.fields)) : false);
7194
7573
  const instKey = instanceKey(snap.instance);
7195
7574
  const inst = manifest.instances[instKey];
7196
7575
  if (!inst)
7197
7576
  throw new Error(`${MANIFEST} has no base for ${instKey} (it tracks ${keys.join(", ")}): pull first`);
7198
- if (inst.portal.id !== snap.portal.id)
7577
+ if (!componentWs && inst.portal.id !== snap.portal.id)
7199
7578
  throw new Error(`${dir} tracks portal ${inst.portal.slug} (${inst.portal.id}), not ${snap.portal.slug}`);
7579
+ if (componentWs && inst.app.id !== snap.portal.app.id)
7580
+ throw new Error(`${dir} tracks components of ${inst.app.scope}, not ${snap.portal.app.scope}`);
7200
7581
  const notes = [];
7201
7582
  const schemaHash = sha2562(canonicalJson(snap.schema));
7202
7583
  if (inst.schemaHash && inst.schemaHash !== schemaHash)
@@ -7210,29 +7591,34 @@ async function analyze(dirArg, client, opts = {}) {
7210
7591
  untracked.push(p);
7211
7592
  continue;
7212
7593
  }
7213
- lFileHashes.set(p, fileHash(p, readFileSync20(join18(dir, p))));
7594
+ lFileHashes.set(p, fileHash(p, readFileSync21(join20(dir, p))));
7214
7595
  }
7215
- const portalFile = join18(dir, "portal.mjs");
7216
- if (!existsSync17(portalFile))
7217
- throw new Error(`${dir}/portal.mjs is missing`);
7218
- let lDef;
7219
- try {
7220
- lDef = await importPortal(portalFile);
7221
- } catch (e) {
7222
- throw new Error(`portal.mjs doesn't load: ${e.message}`);
7596
+ const portalFile = join20(dir, "portal.mjs");
7597
+ let lDef = null;
7598
+ if (componentWs) {
7599
+ if (existsSync19(portalFile))
7600
+ notes.push("portal.mjs: a component workspace ignores it (it holds no portal)");
7601
+ } else {
7602
+ if (!existsSync19(portalFile))
7603
+ throw new Error(`${dir}/portal.mjs is missing`);
7604
+ try {
7605
+ lDef = await importPortal(portalFile);
7606
+ } catch (e) {
7607
+ throw new Error(`portal.mjs doesn't load: ${e.message}`);
7608
+ }
7609
+ assertPlainData(lDef);
7223
7610
  }
7224
- assertPlainData(lDef);
7225
7611
  const ld = decompose(lDef);
7226
7612
  if (ld.duplicates.length)
7227
7613
  notes.push(`portal.mjs: duplicate keys (the first one counts): ${ld.duplicates.join(", ")}`);
7228
7614
  const localAssets = [...lFileHashes.keys()].filter((p) => p.startsWith("assets/")).map((p) => p.slice(7));
7229
- const baseDir = join18(dir, FORGE_DIR, "base");
7615
+ const baseDir = join20(dir, FORGE_DIR, "base");
7230
7616
  let baseFiles = null;
7231
- if (existsSync17(join18(baseDir, "portal.mjs"))) {
7617
+ if (hasBase(baseDir)) {
7232
7618
  baseFiles = new Map;
7233
7619
  for (const p of listFiles(baseDir))
7234
7620
  if (p !== "portal.mjs" && !LOCAL_ONLY.has(p))
7235
- baseFiles.set(p, fileHash(p, readFileSync20(join18(baseDir, p))));
7621
+ baseFiles.set(p, fileHash(p, readFileSync21(join20(baseDir, p))));
7236
7622
  }
7237
7623
  let rendered = await renderInstance(snap, inst, manifest, full, baseFiles, localAssets);
7238
7624
  if (rendered.needFull.length) {
@@ -7291,7 +7677,7 @@ async function analyze(dirArg, client, opts = {}) {
7291
7677
  lFileHashes,
7292
7678
  lUnits: ld.units,
7293
7679
  lDef,
7294
- lHeader: headerOf(portalFile),
7680
+ lHeader: lDef ? headerOf(portalFile) : "",
7295
7681
  base,
7296
7682
  entries,
7297
7683
  untracked,
@@ -7448,7 +7834,7 @@ function report(a) {
7448
7834
  for (const e of a.entries) {
7449
7835
  if (e.unit || e.l === null || e.l === e.b || isBinary(e.id))
7450
7836
  continue;
7451
- const text = readFileSync20(join18(a.dir, e.id), "utf8");
7837
+ const text = readFileSync21(join20(a.dir, e.id), "utf8");
7452
7838
  if (MARKERS.test(text))
7453
7839
  markers.push(e.id);
7454
7840
  }
@@ -7518,6 +7904,9 @@ var isBinary = (p) => p.startsWith("assets/"), VIRTUAL, componentDir = (uid) =>
7518
7904
  return `components/@${ns}/${key}/`;
7519
7905
  }, FORMATTED, MARKERS;
7520
7906
  var init_status = __esm(() => {
7907
+ init_manifest();
7908
+ init_layout();
7909
+ init_tracked();
7521
7910
  init_normalize();
7522
7911
  init_serialize();
7523
7912
  init_layout();
@@ -7531,15 +7920,15 @@ var init_status = __esm(() => {
7531
7920
 
7532
7921
  // ../forge-core/src/workspace/resolve.ts
7533
7922
  import { spawnSync as spawnSync3 } from "node:child_process";
7534
- import { existsSync as existsSync18, mkdirSync as mkdirSync8, readdirSync as readdirSync7, readFileSync as readFileSync21, rmdirSync, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "node:fs";
7535
- import { dirname as dirname11, join as join19 } from "node:path";
7923
+ import { existsSync as existsSync20, mkdirSync as mkdirSync8, readdirSync as readdirSync8, readFileSync as readFileSync22, rmdirSync, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
7924
+ import { dirname as dirname11, join as join21 } from "node:path";
7536
7925
  function removeFile(root, rel) {
7537
- const full = join19(root, rel);
7538
- if (!existsSync18(full))
7926
+ const full = join21(root, rel);
7927
+ if (!existsSync20(full))
7539
7928
  return;
7540
7929
  rmSync2(full);
7541
7930
  let d = dirname11(full);
7542
- while (d.length > root.length && existsSync18(d) && !readdirSync7(d).length) {
7931
+ while (d.length > root.length && existsSync20(d) && !readdirSync8(d).length) {
7543
7932
  rmdirSync(d);
7544
7933
  d = dirname11(d);
7545
7934
  }
@@ -7559,12 +7948,15 @@ async function instanceContent(a, client, p) {
7559
7948
  return c === undefined ? null : c;
7560
7949
  }
7561
7950
  async function materializeBase(a) {
7562
- const baseDir = join19(ensureForgeDir(a.dir), "base");
7951
+ const baseDir = join21(ensureForgeDir(a.dir), "base");
7563
7952
  const aliases = a.renames.active.length ? a.renames.aliases : null;
7953
+ const componentWs = isComponentManifest(a.manifest);
7954
+ if (a.base.source === "base" && componentWs)
7955
+ return { doc: { root: null, aliases }, header: "" };
7564
7956
  if (a.base.source === "base") {
7565
- const root = await importPortal(join19(baseDir, "portal.mjs"));
7957
+ const root = await importPortal(join21(baseDir, "portal.mjs"));
7566
7958
  renameRefs(root, a.renames.refs);
7567
- return { doc: { root, aliases }, header: headerOf(join19(baseDir, "portal.mjs")) };
7959
+ return { doc: { root, aliases }, header: headerOf(join21(baseDir, "portal.mjs")) };
7568
7960
  }
7569
7961
  const unknown = new Set(a.inst.unknownBase || []);
7570
7962
  for (const [p, h] of a.base.files) {
@@ -7585,13 +7977,17 @@ async function materializeBase(a) {
7585
7977
  setUnits(doc, changes);
7586
7978
  a.inst.unknownBase = [...unknown].sort();
7587
7979
  const header = a.lHeader;
7588
- writeText(baseDir, "portal.mjs", await renderPortal(doc.root, header));
7980
+ if (componentWs)
7981
+ writeText(baseDir, BASE_MARK, `base
7982
+ `);
7983
+ else
7984
+ writeText(baseDir, "portal.mjs", await renderPortal(doc.root, header));
7589
7985
  return { doc, header };
7590
7986
  }
7591
7987
  async function applyOps(a, client, ops, opts = {}) {
7592
7988
  if (!a.full)
7593
7989
  throw new Error("internal: applyOps needs a full read");
7594
- const baseDir = join19(ensureForgeDir(a.dir), "base");
7990
+ const baseDir = join21(ensureForgeDir(a.dir), "base");
7595
7991
  const { doc: bDoc, header: bHeader } = await materializeBase(a);
7596
7992
  const lDoc = { root: clone2(a.lDef) };
7597
7993
  const out = { local: {}, base: {}, orphans: [] };
@@ -7692,7 +8088,7 @@ function restampFiles(a, baseDir) {
7692
8088
  const baseFiles = new Map;
7693
8089
  for (const p of listFiles(baseDir))
7694
8090
  if (p !== "portal.mjs" && !LOCAL_ONLY.has(p))
7695
- baseFiles.set(p, fileHash(p, readFileSync21(join19(baseDir, p))));
8091
+ baseFiles.set(p, fileHash(p, readFileSync22(join21(baseDir, p))));
7696
8092
  const groups = new Set([
7697
8093
  ...Object.keys(records).filter((k) => k.startsWith("component:") || k.startsWith("theme:")),
7698
8094
  ...Object.keys(a.ser.records).filter((k) => k.startsWith("component:") || k.startsWith("theme:"))
@@ -7797,14 +8193,14 @@ function mergeUnit(b, l, r) {
7797
8193
  };
7798
8194
  }
7799
8195
  function mergeText(dir, path, local, base, instance) {
7800
- const tmp = join19(dir, FORGE_DIR, "tmp");
8196
+ const tmp = join21(dir, FORGE_DIR, "tmp");
7801
8197
  mkdirSync8(tmp, { recursive: true });
7802
- const files = ["local", "base", "instance"].map((n) => join19(tmp, n));
7803
- writeFileSync8(files[0], local.replace(/\r\n/g, `
8198
+ const files = ["local", "base", "instance"].map((n) => join21(tmp, n));
8199
+ writeFileSync9(files[0], local.replace(/\r\n/g, `
7804
8200
  `), "utf8");
7805
- writeFileSync8(files[1], base.replace(/\r\n/g, `
8201
+ writeFileSync9(files[1], base.replace(/\r\n/g, `
7806
8202
  `), "utf8");
7807
- writeFileSync8(files[2], instance.replace(/\r\n/g, `
8203
+ writeFileSync9(files[2], instance.replace(/\r\n/g, `
7808
8204
  `), "utf8");
7809
8205
  const r = spawnSync3("git", ["merge-file", "-p", "-L", "local", "-L", "base", "-L", "instance", ...files], {
7810
8206
  maxBuffer: 64 * 1024 * 1024
@@ -7869,18 +8265,18 @@ async function resolveEntries(client, args, source) {
7869
8265
  conflicts.push({ id: e.id, fields: m.conflicts });
7870
8266
  } else {
7871
8267
  const pathB = a.base.content(e.id);
7872
- const lPath = join19(a.dir, e.id);
7873
- if (isBinary(e.id) || !pathB || !existsSync18(lPath) || !a.rFiles || !a.rFiles.has(e.id)) {
8268
+ const lPath = join21(a.dir, e.id);
8269
+ if (isBinary(e.id) || !pathB || !existsSync20(lPath) || !a.rFiles || !a.rFiles.has(e.id)) {
7874
8270
  skipped.push({
7875
8271
  id: e.id,
7876
- reason: isBinary(e.id) ? "binary file: use take-local or take-instance" : `${!pathB ? "no base copy" : !existsSync18(lPath) ? "removed locally" : "deleted on the instance"}: use take-local or take-instance`
8272
+ reason: isBinary(e.id) ? "binary file: use take-local or take-instance" : `${!pathB ? "no base copy" : !existsSync20(lPath) ? "removed locally" : "deleted on the instance"}: use take-local or take-instance`
7877
8273
  });
7878
8274
  continue;
7879
8275
  }
7880
- const m = mergeText(a.dir, e.id, readFileSync21(lPath, "utf8"), pathB.toString("utf8"), a.rFiles.get(e.id));
8276
+ const m = mergeText(a.dir, e.id, readFileSync22(lPath, "utf8"), pathB.toString("utf8"), a.rFiles.get(e.id));
7881
8277
  ops.push({ e, local: { content: m.text } });
7882
8278
  if (m.conflicts) {
7883
- const cdir = join19(a.dir, FORGE_DIR, "conflicts");
8279
+ const cdir = join21(a.dir, FORGE_DIR, "conflicts");
7884
8280
  writeText(cdir, e.id + ".base", pathB.toString("utf8"));
7885
8281
  writeText(cdir, e.id + ".instance", a.rFiles.get(e.id));
7886
8282
  conflicts.push({
@@ -7916,7 +8312,7 @@ async function resync(client, a, opts) {
7916
8312
  if (e.state === "conflict") {
7917
8313
  conflicts.push(e.id);
7918
8314
  if (!e.unit && a.rFiles && a.rFiles.has(e.id))
7919
- writeText(join19(a.dir, FORGE_DIR, "conflicts"), e.id + ".instance", a.rFiles.get(e.id));
8315
+ writeText(join21(a.dir, FORGE_DIR, "conflicts"), e.id + ".instance", a.rFiles.get(e.id));
7920
8316
  continue;
7921
8317
  }
7922
8318
  if (e.state === "instance") {
@@ -7950,21 +8346,24 @@ var init_resolve = __esm(() => {
7950
8346
  init_normalize();
7951
8347
  init_layout();
7952
8348
  init_manifest();
8349
+ init_manifest();
7953
8350
  init_rename();
7954
8351
  init_status();
7955
8352
  init_units();
7956
8353
  });
7957
8354
 
7958
8355
  // ../forge-core/src/workspace/pull.ts
7959
- import { existsSync as existsSync19, rmSync as rmSync3, writeFileSync as writeFileSync9 } from "node:fs";
7960
- import { isAbsolute as isAbsolute3, join as join20, resolve as resolve7 } from "node:path";
8356
+ import { existsSync as existsSync21, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
8357
+ import { isAbsolute as isAbsolute3, join as join22, resolve as resolve7 } from "node:path";
7961
8358
  function targetDir(args, slug) {
7962
8359
  if (args.out)
7963
8360
  return isAbsolute3(args.out) ? args.out : resolve7(args.out);
7964
8361
  const name = args.name || slug;
8362
+ if (!name)
8363
+ throw new Error("A new component workspace needs a folder: pass name or out");
7965
8364
  if (!/^[a-z][a-z0-9-]*$/.test(name))
7966
8365
  throw new Error(`Workspace name "${name}": lowercase letters, digits and -`);
7967
- return roots.apps ? join20(roots.apps, name) : resolve7(name);
8366
+ return roots.apps ? join22(roots.apps, name) : resolve7(name);
7968
8367
  }
7969
8368
  function pickUpdateSet(snap, wanted) {
7970
8369
  const sets = snap.updateSets;
@@ -7974,31 +8373,66 @@ function pickUpdateSet(snap, wanted) {
7974
8373
  throw new Error(`Update set "${wanted}": ${hit.length} in-progress sets of ${snap.portal.app.scope} match (in progress: ${sets.map((s) => s.name).join(", ") || "none"})`);
7975
8374
  return hit[0];
7976
8375
  }
7977
- throw Object.assign(new Error(`Which update set should pushes of ${snap.portal.slug} write into? Pass updateSet: one of the in-progress sets of ${snap.portal.app.scope}: ${sets.map((s) => `"${s.name}"`).join(", ") || "none (create one first)"}`), {
8376
+ throw Object.assign(new Error(`Which update set should pushes of ${snap.portal.slug || "these components"} write into? Pass updateSet: one of the in-progress sets of ${snap.portal.app.scope}: ${sets.map((s) => `"${s.name}"`).join(", ") || "none (create one first)"}`), {
7978
8377
  code: "update_set_required",
7979
8378
  details: { app: snap.portal.app.scope, updateSets: sets.map((s) => ({ id: s.id, name: s.name })) }
7980
8379
  });
7981
8380
  }
7982
8381
  async function pull(client, args) {
7983
8382
  const started = Date.now();
7984
- const snap = await fetchSnapshot(client, args.portal, { budgetKb: args.budgetKb });
7985
- const dir = targetDir(args, snap.portal.slug);
8383
+ const asked = args.out ? isAbsolute3(args.out) ? args.out : resolve7(args.out) : args.name ? targetDir(args, "") : "";
8384
+ const askedManifest = asked ? readManifest(asked) : null;
8385
+ const componentMode = !args.portal && (!!args.app || !!(args.components || []).length || !!askedManifest && askedManifest.kind === "component");
8386
+ if (!args.portal && !componentMode)
8387
+ throw new Error("pull needs a portal, or an app and components (a component workspace)");
8388
+ if (componentMode && askedManifest && askedManifest.kind !== "component")
8389
+ throw new Error(`${asked} is a portal workspace: pull components into a component workspace (another folder)`);
8390
+ let snap;
8391
+ let dir;
8392
+ if (componentMode) {
8393
+ dir = targetDir(args, "");
8394
+ const prior0 = askedManifest ? Object.values(askedManifest.instances)[0] : undefined;
8395
+ const app = args.app || prior0 && prior0.app.id || "";
8396
+ if (!app)
8397
+ throw new Error("A new component workspace needs its application (app: scope name or sys_id)");
8398
+ const wanted = trackedComponents(dir, prior0, args.components || []);
8399
+ snap = await fetchSnapshot(client, { app, components: wanted }, { budgetKb: args.budgetKb });
8400
+ if (snap.foreign && snap.foreign.length)
8401
+ throw new Error(`Not in ${snap.portal.app.scope}: ${snap.foreign.map((f) => `${f.uid} (${f.app})`).join(", ")}. A component workspace holds one application's components: pull those into a workspace of their own app`);
8402
+ const local = new Set(localComponentIds(dir));
8403
+ const unknown = (args.components || []).filter((u) => (snap.missing || []).includes(u) && !local.has(u));
8404
+ if (unknown.length)
8405
+ throw new Error(`No component ${unknown.join(", ")} on the instance (rpf new component creates one locally)`);
8406
+ } else {
8407
+ snap = await fetchSnapshot(client, args.portal, { budgetKb: args.budgetKb });
8408
+ dir = targetDir(args, snap.portal.slug);
8409
+ }
7986
8410
  const key = instanceKey(snap.instance);
7987
- const manifest = readManifest(dir) || { format: 1, ignore: [], images: [], instances: {} };
7988
- const hasManifest = existsSync19(join20(dir, MANIFEST));
7989
- const existing = existsSync19(dir) ? listFiles(dir) : [];
8411
+ const manifest = readManifest(dir) || {
8412
+ format: 1,
8413
+ ...componentMode ? { kind: "component" } : {},
8414
+ ignore: [],
8415
+ images: [],
8416
+ instances: {}
8417
+ };
8418
+ if (!componentMode && manifest.kind === "component")
8419
+ throw new Error(`${dir} is a component workspace: it holds no portal (pull the portal into another folder)`);
8420
+ const hasManifest = existsSync21(join22(dir, MANIFEST));
8421
+ const existing = existsSync21(dir) ? listFiles(dir) : [];
7990
8422
  const mode = hasManifest ? "resync" : existing.length ? "adopt" : "fresh";
7991
8423
  if (args.mode === "fresh" && mode !== "fresh")
7992
8424
  throw new Error(`${dir} is not empty: a fresh pull needs an empty or new folder (mode: auto adopts it)`);
7993
8425
  if (args.mode === "adopt" && mode !== "adopt")
7994
8426
  throw new Error(`${dir}: nothing to adopt (mode ${mode})`);
7995
8427
  const prior = manifest.instances[key];
7996
- if (prior && prior.portal.id !== snap.portal.id)
8428
+ if (componentMode && prior && prior.app.id !== snap.portal.app.id)
8429
+ throw new Error(`${dir} tracks components of ${prior.app.scope}, not ${snap.portal.app.scope}`);
8430
+ if (!componentMode && prior && prior.portal.id !== snap.portal.id)
7997
8431
  throw new Error(`${dir} tracks portal ${prior.portal.slug} (${prior.portal.id}) on ${key}, not ${snap.portal.slug}`);
7998
8432
  let localPortal = null;
7999
- if (existing.includes("portal.mjs")) {
8433
+ if (!componentMode && existing.includes("portal.mjs")) {
8000
8434
  try {
8001
- localPortal = await importPortal(join20(dir, "portal.mjs"));
8435
+ localPortal = await importPortal(join22(dir, "portal.mjs"));
8002
8436
  } catch (e) {
8003
8437
  if (mode === "adopt")
8004
8438
  throw new Error(`portal.mjs doesn't load: ${e.message}`);
@@ -8024,7 +8458,7 @@ async function pull(client, args) {
8024
8458
  if (FORMATTED.test(p))
8025
8459
  s.files.set(p, await formatFile(p, c));
8026
8460
  const forge = ensureForgeDir(dir);
8027
- const base = join20(forge, "base");
8461
+ const base = join22(forge, "base");
8028
8462
  if (mode === "resync") {
8029
8463
  if (!prior)
8030
8464
  throw new Error(`${dir} tracks ${Object.keys(manifest.instances).join(", ")}, not ${key}: pull ${key} into another folder`);
@@ -8042,14 +8476,15 @@ async function pull(client, args) {
8042
8476
  syncedBy: "pull",
8043
8477
  user: snap.user,
8044
8478
  schemaHash: sha2562(canonicalJson(snap.schema)),
8045
- dependencies: s.dependencies
8479
+ dependencies: s.dependencies,
8480
+ ...componentMode ? { components: presentComponents(dir, snap) } : {}
8046
8481
  }
8047
8482
  });
8048
- writeFileSync9(join20(forge, "snapshot.json"), JSON.stringify(snap), "utf8");
8483
+ writeFileSync10(join22(forge, "snapshot.json"), JSON.stringify(snap), "utf8");
8049
8484
  return {
8050
8485
  mode,
8051
8486
  dir,
8052
- portal: snap.portal,
8487
+ ...componentMode ? { kind: "component", app: snap.portal.app } : { portal: snap.portal },
8053
8488
  updateSet,
8054
8489
  reactPortal: snap.reactPortal,
8055
8490
  ...r,
@@ -8090,6 +8525,7 @@ async function pull(client, args) {
8090
8525
  rec.files[name] = fileHash(prefix + name, s.files.get(prefix + name));
8091
8526
  }
8092
8527
  const units = decompose(s.portal).units;
8528
+ const comps = componentMode ? presentComponents(dir, snap) : [];
8093
8529
  for (const [k, rec] of Object.entries(s.records))
8094
8530
  if (units.has(k))
8095
8531
  rec.unit = units.get(k).hash;
@@ -8098,7 +8534,10 @@ async function pull(client, args) {
8098
8534
  writeText(base, p, c);
8099
8535
  for (const [n, b] of Object.entries(images))
8100
8536
  writeBytes(base, "assets/" + n, b);
8101
- writeFileSync9(join20(forge, "snapshot.json"), JSON.stringify(snap), "utf8");
8537
+ if (componentMode)
8538
+ writeText(base, BASE_MARK, `base
8539
+ `);
8540
+ writeFileSync10(join22(forge, "snapshot.json"), JSON.stringify(snap), "utf8");
8102
8541
  let comparison = null;
8103
8542
  let written = 0;
8104
8543
  if (mode === "adopt")
@@ -8130,6 +8569,7 @@ async function pull(client, args) {
8130
8569
  app: snap.portal.app,
8131
8570
  updateSet,
8132
8571
  portal: { slug: snap.portal.slug, id: snap.portal.id },
8572
+ ...componentMode ? { components: comps } : {},
8133
8573
  reactPortal: snap.reactPortal,
8134
8574
  syncedAt: new Date().toISOString(),
8135
8575
  syncedBy: mode === "adopt" ? "adopt" : "pull",
@@ -8145,7 +8585,7 @@ async function pull(client, args) {
8145
8585
  return {
8146
8586
  mode,
8147
8587
  dir,
8148
- portal: snap.portal,
8588
+ ...componentMode ? { kind: "component", app: snap.portal.app, components: comps, usage: snap.usage } : { portal: snap.portal },
8149
8589
  updateSet,
8150
8590
  reactPortal: snap.reactPortal,
8151
8591
  counts: {
@@ -8174,6 +8614,12 @@ async function pull(client, args) {
8174
8614
  ms: Date.now() - started
8175
8615
  };
8176
8616
  }
8617
+ function presentComponents(dir, snap) {
8618
+ const set = new Set(snap.components.map((c) => c.uniqueId));
8619
+ for (const u of localComponentIds(dir))
8620
+ set.add(u);
8621
+ return Array.from(set).sort();
8622
+ }
8177
8623
  function brief(c) {
8178
8624
  return {
8179
8625
  same: c.same,
@@ -8188,6 +8634,7 @@ var init_pull = __esm(() => {
8188
8634
  init_serialize();
8189
8635
  init_layout();
8190
8636
  init_manifest();
8637
+ init_tracked();
8191
8638
  init_compare();
8192
8639
  init_status();
8193
8640
  init_resolve();
@@ -8196,16 +8643,16 @@ var init_pull = __esm(() => {
8196
8643
 
8197
8644
  // ../forge-core/src/workspace/diff.ts
8198
8645
  import { spawnSync as spawnSync4 } from "node:child_process";
8199
- import { existsSync as existsSync20, mkdirSync as mkdirSync9, readFileSync as readFileSync22, rmSync as rmSync4, writeFileSync as writeFileSync10 } from "node:fs";
8200
- import { join as join21 } from "node:path";
8646
+ import { existsSync as existsSync22, mkdirSync as mkdirSync9, readFileSync as readFileSync23, rmSync as rmSync4, writeFileSync as writeFileSync11 } from "node:fs";
8647
+ import { join as join23 } from "node:path";
8201
8648
  function unifiedDiff(dir, path, from, a, to, b) {
8202
- const tmp = join21(dir, FORGE_DIR, "tmp");
8649
+ const tmp = join23(dir, FORGE_DIR, "tmp");
8203
8650
  mkdirSync9(tmp, { recursive: true });
8204
- const fa = join21(tmp, "a");
8205
- const fb = join21(tmp, "b");
8206
- writeFileSync10(fa, (a ?? "").replace(/\r\n/g, `
8651
+ const fa = join23(tmp, "a");
8652
+ const fb = join23(tmp, "b");
8653
+ writeFileSync11(fa, (a ?? "").replace(/\r\n/g, `
8207
8654
  `), "utf8");
8208
- writeFileSync10(fb, (b ?? "").replace(/\r\n/g, `
8655
+ writeFileSync11(fb, (b ?? "").replace(/\r\n/g, `
8209
8656
  `), "utf8");
8210
8657
  const r = spawnSync4("git", ["diff", "--no-index", "--no-color", "-U3", fa, fb], { maxBuffer: 64 * 1024 * 1024 });
8211
8658
  rmSync4(tmp, { recursive: true, force: true });
@@ -8220,7 +8667,7 @@ ${hunks}`;
8220
8667
  }
8221
8668
  function text2(a, side, path) {
8222
8669
  if (side === "local")
8223
- return existsSync20(join21(a.dir, path)) ? readFileSync22(join21(a.dir, path), "utf8") : null;
8670
+ return existsSync22(join23(a.dir, path)) ? readFileSync23(join23(a.dir, path), "utf8") : null;
8224
8671
  if (side === "base") {
8225
8672
  const c = a.base.content(path);
8226
8673
  return c ? c.toString("utf8") : null;
@@ -8759,40 +9206,40 @@ var init_records = __esm(() => {
8759
9206
  });
8760
9207
 
8761
9208
  // ../forge-core/src/workspace/push.ts
8762
- import { cpSync as cpSync2, existsSync as existsSync21, mkdirSync as mkdirSync10, readFileSync as readFileSync23, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync11 } from "node:fs";
8763
- import { join as join22 } from "node:path";
9209
+ import { cpSync as cpSync2, existsSync as existsSync23, mkdirSync as mkdirSync10, readFileSync as readFileSync24, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync12 } from "node:fs";
9210
+ import { join as join24 } from "node:path";
8764
9211
  function fingerprint(dir) {
8765
9212
  const parts = [];
8766
9213
  for (const p of listFiles(dir))
8767
9214
  if (!LOCAL_ONLY.has(p) || p === "forge.workspace.json")
8768
- parts.push(p + ":" + sha2562(readFileSync23(join22(dir, p))));
9215
+ parts.push(p + ":" + sha2562(readFileSync24(join24(dir, p))));
8769
9216
  return sha2562(parts.join(`
8770
9217
  `));
8771
9218
  }
8772
9219
  function withLock(dir, fn) {
8773
9220
  const forge = ensureForgeDir(dir);
8774
- const lock = join22(forge, "push.lock");
8775
- if (existsSync21(lock) && Date.now() - statSync5(lock).mtimeMs < LOCK_MS)
9221
+ const lock = join24(forge, "push.lock");
9222
+ if (existsSync23(lock) && Date.now() - statSync5(lock).mtimeMs < LOCK_MS)
8776
9223
  throw new Error(`Another workspace_push holds ${lock} (started ${statSync5(lock).mtime.toISOString()}); wait for it, or delete the lock if it died`);
8777
- writeFileSync11(lock, String(process.pid), "utf8");
9224
+ writeFileSync12(lock, String(process.pid), "utf8");
8778
9225
  return fn().finally(() => rmSync5(lock, { force: true }));
8779
9226
  }
8780
9227
  function readPending(dir) {
8781
- const f = join22(dir, ".forge", "push-pending.json");
8782
- if (!existsSync21(f))
9228
+ const f = join24(dir, ".forge", "push-pending.json");
9229
+ if (!existsSync23(f))
8783
9230
  return null;
8784
9231
  try {
8785
- return JSON.parse(readFileSync23(f, "utf8"));
9232
+ return JSON.parse(readFileSync24(f, "utf8"));
8786
9233
  } catch {
8787
9234
  return null;
8788
9235
  }
8789
9236
  }
8790
9237
  function writePending(dir, p) {
8791
- const f = join22(ensureForgeDir(dir), "push-pending.json");
9238
+ const f = join24(ensureForgeDir(dir), "push-pending.json");
8792
9239
  if (!p)
8793
9240
  rmSync5(f, { force: true });
8794
9241
  else
8795
- writeFileSync11(f, JSON.stringify(p, null, 2), "utf8");
9242
+ writeFileSync12(f, JSON.stringify(p, null, 2), "utf8");
8796
9243
  }
8797
9244
  function pendingAfter(bodies, ids, since) {
8798
9245
  const resolve = (c) => {
@@ -8963,7 +9410,7 @@ function buildPayload(a, selected, args, force) {
8963
9410
  out.kept.push({ id: e.id, note: "image removed locally: never deleted" });
8964
9411
  continue;
8965
9412
  }
8966
- const bytes = readFileSync23(join22(a.dir, e.id));
9413
+ const bytes = readFileSync24(join24(a.dir, e.id));
8967
9414
  const unsafe = svgProblem(name, bytes);
8968
9415
  if (unsafe) {
8969
9416
  out.problems.push(`${e.id}: ${unsafe}`);
@@ -9194,10 +9641,10 @@ function compileOrder(a, groups) {
9194
9641
  for (const g of groups) {
9195
9642
  const prefix = componentDir(g.uid);
9196
9643
  const found = new Set;
9197
- for (const p of listFiles(join22(a.dir, prefix))) {
9644
+ for (const p of listFiles(join24(a.dir, prefix))) {
9198
9645
  if (!/\.(tsx?|jsx?)$/.test(p))
9199
9646
  continue;
9200
- const text = readFileSync23(join22(a.dir, prefix, p), "utf8");
9647
+ const text = readFileSync24(join24(a.dir, prefix, p), "utf8");
9201
9648
  for (const m of text.matchAll(LOCAL_IMPORT)) {
9202
9649
  const uid = `${m[1]}/${m[2]}`;
9203
9650
  if (uid !== g.uid && byUid.has(uid))
@@ -9226,7 +9673,7 @@ function chunks(a, b, args, pending) {
9226
9673
  const budget = (args.chunkKb || DEFAULT_CHUNK_KB) * 1024;
9227
9674
  const maxComps = args.chunkComponents || DEFAULT_CHUNK_COMPONENTS;
9228
9675
  const base = {
9229
- portal: a.snap.portal.id,
9676
+ ...isComponentManifest(a.manifest) ? { components: trackedComponents(a.dir, a.inst) } : { portal: a.snap.portal.id },
9230
9677
  targetApp: a.inst.app.id,
9231
9678
  updateSet: a.inst.updateSet.id,
9232
9679
  force: !!args.force
@@ -9300,7 +9747,7 @@ function chunks(a, b, args, pending) {
9300
9747
  return out.filter((c, i) => i === out.length - 1 || c.records.length || c.removeFiles.length);
9301
9748
  }
9302
9749
  function planFile(dir) {
9303
- return join22(ensureForgeDir(dir), "last-plan.json");
9750
+ return join24(ensureForgeDir(dir), "last-plan.json");
9304
9751
  }
9305
9752
  function chunkSummary(p) {
9306
9753
  return {
@@ -9382,7 +9829,7 @@ async function dryPush(client, args, started, opts = {}) {
9382
9829
  const planHash = overallHash(hashes, fp, force);
9383
9830
  const nothing = plans.every((p) => !p.creates.length && !p.updates.length && !(p.deletes || []).length) && !pending && !args.reprocess;
9384
9831
  const forge = ensureForgeDir(a.dir);
9385
- const ow = join22(forge, "last-plan-overwrite");
9832
+ const ow = join24(forge, "last-plan-overwrite");
9386
9833
  rmSync5(ow, { recursive: true, force: true });
9387
9834
  if (force && b.overwrites.length) {
9388
9835
  const units = {};
@@ -9409,7 +9856,7 @@ async function dryPush(client, args, started, opts = {}) {
9409
9856
  chunks: bodies.map((body, i) => ({ body, hash: hashes[i] })),
9410
9857
  pushed: b.pushed
9411
9858
  };
9412
- writeFileSync11(planFile(a.dir), JSON.stringify(saved), "utf8");
9859
+ writeFileSync12(planFile(a.dir), JSON.stringify(saved), "utf8");
9413
9860
  return {
9414
9861
  dryRun: true,
9415
9862
  dir: a.dir,
@@ -9438,12 +9885,12 @@ async function realPush(client, args, dir, started) {
9438
9885
  reason: "A real push needs the planHash of its dry run (workspace_push { dryRun: true } first)"
9439
9886
  };
9440
9887
  const f = planFile(dir);
9441
- if (!existsSync21(f))
9888
+ if (!existsSync23(f))
9442
9889
  return {
9443
9890
  refused: true,
9444
9891
  reason: "No dry run saved for this workspace: run workspace_push { dryRun: true } first"
9445
9892
  };
9446
- const saved = JSON.parse(readFileSync23(f, "utf8"));
9893
+ const saved = JSON.parse(readFileSync24(f, "utf8"));
9447
9894
  if (saved.planHash !== args.planHash)
9448
9895
  return {
9449
9896
  refused: true,
@@ -9474,10 +9921,10 @@ async function realPush(client, args, dir, started) {
9474
9921
  reason: `The plan of chunk(s) ${changed.map((i) => i + 1).join(", ")} changed since the dry run: run the dry run again`
9475
9922
  };
9476
9923
  const forge = ensureForgeDir(dir);
9477
- const ow = join22(forge, "last-plan-overwrite");
9924
+ const ow = join24(forge, "last-plan-overwrite");
9478
9925
  let overwritten;
9479
- if (existsSync21(ow)) {
9480
- overwritten = join22(forge, "overwritten", new Date().toISOString().replace(/[:.]/g, "-"));
9926
+ if (existsSync23(ow)) {
9927
+ overwritten = join24(forge, "overwritten", new Date().toISOString().replace(/[:.]/g, "-"));
9481
9928
  mkdirSync10(overwritten, { recursive: true });
9482
9929
  cpSync2(ow, overwritten, { recursive: true });
9483
9930
  }
@@ -9588,9 +10035,11 @@ async function checkComponents(client, a) {
9588
10035
  }
9589
10036
  return { checks, problems };
9590
10037
  }
9591
- var DEFAULT_CHUNK_KB = 900, DEFAULT_CHUNK_COMPONENTS = 15, LOCK_MS, KIND_ORDER, readLocal = (a, p) => existsSync21(join22(a.dir, p)) ? readFileSync23(join22(a.dir, p), "utf8").replace(/\r\n/g, `
10038
+ var DEFAULT_CHUNK_KB = 900, DEFAULT_CHUNK_COMPONENTS = 15, LOCK_MS, KIND_ORDER, readLocal = (a, p) => existsSync23(join24(a.dir, p)) ? readFileSync24(join24(a.dir, p), "utf8").replace(/\r\n/g, `
9592
10039
  `) : null, SVG_DANGER, size = (f) => Object.values(f).reduce((n, v) => n + v.length, 0), LOCAL_IMPORT, overallHash = (hashes, fp, force) => sha2562(canonicalJson({ hashes, fp, force })).slice(0, 16);
9593
10040
  var init_push = __esm(() => {
10041
+ init_manifest();
10042
+ init_tracked();
9594
10043
  init_normalize();
9595
10044
  init_layout();
9596
10045
  init_status();
@@ -9816,8 +10265,8 @@ var P2 = "x_312987_portal_", RP_SCOPE_NAME = "x_312987_portal", IN_CHUNK = 40, c
9816
10265
 
9817
10266
  // ../forge-core/src/workspace/check.ts
9818
10267
  import { spawnSync as spawnSync5 } from "node:child_process";
9819
- import { existsSync as existsSync22, readFileSync as readFileSync24, writeFileSync as writeFileSync12 } from "node:fs";
9820
- import { join as join23 } from "node:path";
10268
+ import { existsSync as existsSync24, readFileSync as readFileSync25, writeFileSync as writeFileSync13 } from "node:fs";
10269
+ import { join as join25 } from "node:path";
9821
10270
  import { createRequire as createRequire4 } from "node:module";
9822
10271
  function changedFiles(a) {
9823
10272
  const out = a.entries.filter((e) => !e.unit && e.l !== null && (e.state === "local" || e.state === "conflict")).map((e) => e.id).filter((p) => !p.startsWith("assets/"));
@@ -9832,7 +10281,7 @@ async function prettierCheck(a, files) {
9832
10281
  for (const p of files) {
9833
10282
  if (!PRETTIER_EXT.test(p))
9834
10283
  continue;
9835
- const text = readFileSync24(join23(a.dir, p), "utf8");
10284
+ const text = readFileSync25(join25(a.dir, p), "utf8");
9836
10285
  checked++;
9837
10286
  try {
9838
10287
  if (await formatFile(p, text) !== text)
@@ -9876,11 +10325,11 @@ function lint(a, files) {
9876
10325
  const out = [];
9877
10326
  for (const p of files)
9878
10327
  if (p.startsWith("components/"))
9879
- out.push(...lintText(p, readFileSync24(join23(a.dir, p), "utf8")));
10328
+ out.push(...lintText(p, readFileSync25(join25(a.dir, p), "utf8")));
9880
10329
  return out;
9881
10330
  }
9882
10331
  function findTsc(dir) {
9883
- for (const from of [join23(dir, "x.js"), import.meta.url]) {
10332
+ for (const from of [join25(dir, "x.js"), import.meta.url]) {
9884
10333
  try {
9885
10334
  return createRequire4(from).resolve("typescript/lib/tsc.js");
9886
10335
  } catch {}
@@ -9889,14 +10338,14 @@ function findTsc(dir) {
9889
10338
  }
9890
10339
  function tscCheck(a, files) {
9891
10340
  const tscJs = roots.tsc || findTsc(a.dir);
9892
- if (!tscJs || !existsSync22(tscJs))
10341
+ if (!tscJs || !existsSync24(tscJs))
9893
10342
  return {
9894
10343
  skipped: tscJs ? `TypeScript not found at ${tscJs} (npm install in the repo root)` : "TypeScript not found (install typescript in the workspace or next to the CLI)"
9895
10344
  };
9896
10345
  const forge = ensureForgeDir(a.dir);
9897
10346
  const types = roots.hostTypes ? roots.hostTypes.split("\\").join("/") : "";
9898
10347
  const nm = roots.typesFrom ? roots.typesFrom.split("\\").join("/") : "";
9899
- writeFileSync12(join23(forge, "stubs.d.ts"), `declare module 'components:*';
10348
+ writeFileSync13(join25(forge, "stubs.d.ts"), `declare module 'components:*';
9900
10349
  declare module 'utilities:*';
9901
10350
  declare module '*.css';
9902
10351
  `, "utf8");
@@ -9922,9 +10371,9 @@ declare module '*.css';
9922
10371
  },
9923
10372
  include: ["../components/**/*.tsx", "../components/**/*.ts", "stubs.d.ts"].concat(types ? [types + "/*.d.ts"] : [])
9924
10373
  };
9925
- writeFileSync12(join23(forge, "tsconfig.json"), JSON.stringify(config, null, 4) + `
10374
+ writeFileSync13(join25(forge, "tsconfig.json"), JSON.stringify(config, null, 4) + `
9926
10375
  `, "utf8");
9927
- const r = spawnSync5("node", [tscJs, "-p", join23(forge, "tsconfig.json"), "--pretty", "false"], {
10376
+ const r = spawnSync5("node", [tscJs, "-p", join25(forge, "tsconfig.json"), "--pretty", "false"], {
9928
10377
  cwd: forge,
9929
10378
  encoding: "utf8",
9930
10379
  maxBuffer: 64 * 1024 * 1024
@@ -10038,8 +10487,8 @@ var init_check = __esm(() => {
10038
10487
 
10039
10488
  // ../forge-core/src/dev/agent.ts
10040
10489
  import { spawn as spawn3 } from "node:child_process";
10041
- import { existsSync as existsSync23, mkdirSync as mkdirSync11, readFileSync as readFileSync25, rmSync as rmSync6 } from "node:fs";
10042
- import { join as join24 } from "node:path";
10490
+ import { existsSync as existsSync25, mkdirSync as mkdirSync11, readFileSync as readFileSync26, rmSync as rmSync6 } from "node:fs";
10491
+ import { join as join26 } from "node:path";
10043
10492
  function alive(pid) {
10044
10493
  try {
10045
10494
  process.kill(pid, 0);
@@ -10049,11 +10498,11 @@ function alive(pid) {
10049
10498
  }
10050
10499
  }
10051
10500
  function readDevSession(dir) {
10052
- const file = join24(dir, FORGE_DIR, "dev", "session.json");
10053
- if (!existsSync23(file))
10501
+ const file = join26(dir, FORGE_DIR, "dev", "session.json");
10502
+ if (!existsSync25(file))
10054
10503
  return null;
10055
10504
  try {
10056
- const s = JSON.parse(readFileSync25(file, "utf8"));
10505
+ const s = JSON.parse(readFileSync26(file, "utf8"));
10057
10506
  if (!s || !s.url || !s.enterUrl || !alive(Number(s.pid)))
10058
10507
  return null;
10059
10508
  return s;
@@ -10068,6 +10517,19 @@ async function devJson(s, path) {
10068
10517
  throw new Error(`rpf dev ${path}: HTTP ${res.status}`);
10069
10518
  return res.json();
10070
10519
  }
10520
+ async function devSend(s, path, method, body) {
10521
+ const key = new URL(s.enterUrl).searchParams.get("k") || "";
10522
+ const res = await fetch(s.url + path, {
10523
+ method,
10524
+ headers: { Cookie: `rpf_run=${key}`, Accept: "application/json", "Content-Type": "application/json" },
10525
+ body: JSON.stringify(body)
10526
+ });
10527
+ const text = await res.text();
10528
+ const json = text ? JSON.parse(text) : null;
10529
+ if (!res.ok)
10530
+ throw new Error(`rpf dev ${path}: ${json && json.error || `HTTP ${res.status}`}`);
10531
+ return json;
10532
+ }
10071
10533
  function browserCandidates() {
10072
10534
  const env = process.env.RPF_CHROME ? [process.env.RPF_CHROME] : [];
10073
10535
  if (process.platform === "win32") {
@@ -10077,7 +10539,7 @@ function browserCandidates() {
10077
10539
  "Microsoft\\Edge\\Application\\msedge.exe",
10078
10540
  "Chromium\\Application\\chrome.exe"
10079
10541
  ];
10080
- return env.concat(roots.flatMap((r) => rel.map((p) => join24(r, p))));
10542
+ return env.concat(roots.flatMap((r) => rel.map((p) => join26(r, p))));
10081
10543
  }
10082
10544
  if (process.platform === "darwin")
10083
10545
  return env.concat([
@@ -10096,7 +10558,7 @@ function browserCandidates() {
10096
10558
  }
10097
10559
  function findBrowser() {
10098
10560
  for (const c of browserCandidates())
10099
- if (c && existsSync23(c))
10561
+ if (c && existsSync25(c))
10100
10562
  return c;
10101
10563
  throw new Error("No Chrome, Edge or Chromium found for rpf preview: install one or set RPF_CHROME to its path");
10102
10564
  }
@@ -10168,7 +10630,7 @@ async function openBrowser3(o) {
10168
10630
  wsUrl = v.webSocketDebuggerUrl;
10169
10631
  } else {
10170
10632
  mkdirSync11(o.profileDir, { recursive: true });
10171
- const portFile = join24(o.profileDir, "DevToolsActivePort");
10633
+ const portFile = join26(o.profileDir, "DevToolsActivePort");
10172
10634
  rmSync6(portFile, { force: true });
10173
10635
  const args = [
10174
10636
  "--remote-debugging-port=0",
@@ -10185,8 +10647,8 @@ async function openBrowser3(o) {
10185
10647
  let port = "";
10186
10648
  while (!port && Date.now() < end) {
10187
10649
  await new Promise((r) => setTimeout(r, 100));
10188
- if (existsSync23(portFile))
10189
- port = readFileSync25(portFile, "utf8").split(/\r?\n/)[0].trim();
10650
+ if (existsSync25(portFile))
10651
+ port = readFileSync26(portFile, "utf8").split(/\r?\n/)[0].trim();
10190
10652
  if (proc.exitCode !== null)
10191
10653
  break;
10192
10654
  }
@@ -10335,6 +10797,9 @@ class DevPage {
10335
10797
  })()`);
10336
10798
  return { ...data, readOnly: this.readOnly };
10337
10799
  }
10800
+ async locate(selector, max = 10) {
10801
+ return await this.evaluate(`(${LOCATE})(${JSON.stringify(selector)}, ${Math.max(1, Math.floor(max))})`) || [];
10802
+ }
10338
10803
  async point(selector) {
10339
10804
  const p = await this.evaluate(`(() => {
10340
10805
  const el = (${FIND})(${JSON.stringify(selector)});
@@ -10510,7 +10975,47 @@ var FIND = `
10510
10975
  }
10511
10976
  for (const el of all) if (el.matches && el.matches(sel)) return el;
10512
10977
  return null;
10513
- }`, agentProfileDir = (dir) => join24(dir, FORGE_DIR, "dev", "agent-browser"), sessions;
10978
+ }`, LOCATE = `
10979
+ (sel, max) => {
10980
+ const all = [];
10981
+ const walk = (root) => { for (const el of root.querySelectorAll('*')) { all.push(el); if (el.shadowRoot) walk(el.shadowRoot); } };
10982
+ walk(document);
10983
+ const describe = (el) => el.tagName.toLowerCase() + [...el.classList].slice(0, 3).map((c) => '.' + c).join('');
10984
+ // Parent across shadow boundaries (a shadow root's host) and slots.
10985
+ const up = (el) => el.assignedSlot || el.parentElement || (el.parentNode && el.parentNode.host) || null;
10986
+ let hits;
10987
+ if (sel.startsWith('text=')) {
10988
+ const t = sel.slice(5).trim().toLowerCase();
10989
+ const has = all.filter((el) => (el.textContent || '').toLowerCase().includes(t) && !['SCRIPT', 'STYLE', 'TEMPLATE'].includes(el.tagName));
10990
+ hits = has.filter((el) => !has.some((o) => o !== el && el.contains(o)));
10991
+ } else hits = all.filter((el) => el.matches && el.matches(sel));
10992
+ const vw = innerWidth, vh = innerHeight;
10993
+ return hits.slice(0, max).map((el) => {
10994
+ const r = el.getBoundingClientRect();
10995
+ let hiddenBy = null;
10996
+ for (let n = el; n && n.nodeType === 1 && !hiddenBy; n = up(n)) {
10997
+ const s = getComputedStyle(n);
10998
+ if (s.display === 'none') hiddenBy = { element: describe(n), reason: 'display: none' };
10999
+ else if (s.visibility === 'hidden' || s.visibility === 'collapse') hiddenBy = { element: describe(n), reason: 'visibility: ' + s.visibility };
11000
+ else if (Number(s.opacity) === 0) hiddenBy = { element: describe(n), reason: 'opacity: 0' };
11001
+ else if (s.contentVisibility === 'hidden') hiddenBy = { element: describe(n), reason: 'content-visibility: hidden' };
11002
+ else if (n !== el && /hidden|clip/.test(s.overflow)) {
11003
+ const p = n.getBoundingClientRect();
11004
+ if (p.width === 0 || p.height === 0 || r.right <= p.left || r.left >= p.right || r.bottom <= p.top || r.top >= p.bottom)
11005
+ hiddenBy = { element: describe(n), reason: 'clipped by overflow' };
11006
+ }
11007
+ }
11008
+ if (!hiddenBy && (r.width === 0 || r.height === 0)) hiddenBy = { element: describe(el), reason: 'zero size' };
11009
+ if (!hiddenBy && (r.right <= 0 || r.bottom <= 0 || r.left >= vw || r.top >= vh)) hiddenBy = { element: describe(el), reason: 'outside the viewport (scroll to it)' };
11010
+ return {
11011
+ element: describe(el),
11012
+ text: (el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 160),
11013
+ visible: !hiddenBy,
11014
+ rect: { x: Math.round(r.left), y: Math.round(r.top), width: Math.round(r.width), height: Math.round(r.height) },
11015
+ ...(hiddenBy ? { hiddenBy } : {}),
11016
+ };
11017
+ });
11018
+ }`, agentProfileDir = (dir) => join26(dir, FORGE_DIR, "dev", "agent-browser"), sessions;
10514
11019
  var init_agent = __esm(() => {
10515
11020
  init_layout();
10516
11021
  sessions = new Map;
@@ -11207,6 +11712,89 @@ async function legacySwitch(c, app, dryRun) {
11207
11712
  }
11208
11713
  };
11209
11714
  }
11715
+ function docHeading(heading) {
11716
+ if (typeof heading !== "string")
11717
+ return;
11718
+ const text = heading.replace(/^\s*#+\s*/, "").trim();
11719
+ return text || undefined;
11720
+ }
11721
+ function optionWords(query) {
11722
+ const words = [];
11723
+ for (const w of String(query || "").split(/[^A-Za-z0-9_]+/)) {
11724
+ const parts = w.split(/(?<=[a-z0-9])(?=[A-Z])/);
11725
+ if (parts.length > 1) {
11726
+ for (const p of parts)
11727
+ if (p.length > 2)
11728
+ words.push(p.toLowerCase());
11729
+ }
11730
+ }
11731
+ return [...new Set(words)].join(" ");
11732
+ }
11733
+ function rankDocHits(main, extra, collection, limit) {
11734
+ const max = Math.max(1, Math.min(20, limit));
11735
+ const pick = (rows) => {
11736
+ if (collection)
11737
+ return rows;
11738
+ const kept = rows.filter((r) => r.collection !== "template-docs");
11739
+ return kept.length ? kept : rows;
11740
+ };
11741
+ const first = pick(main);
11742
+ const second = pick(extra).map((r, i) => ({ r, i })).sort((a, b) => (Number(b.r.score) || 0) - (Number(a.r.score) || 0) || Number(b.r.collection === "react-portal") - Number(a.r.collection === "react-portal") || a.i - b.i).map((x) => x.r);
11743
+ const seen = new Set;
11744
+ const key = (r) => `${r.collection}:${r.path}`;
11745
+ const shown = new Set(first.slice(0, Math.max(0, max - OPTION_SLOTS)).map(key));
11746
+ const fromExtra = [];
11747
+ for (const r of second) {
11748
+ if (fromExtra.length >= Math.min(OPTION_SLOTS, max))
11749
+ break;
11750
+ if (shown.has(key(r)))
11751
+ continue;
11752
+ fromExtra.push(r);
11753
+ }
11754
+ const out = [];
11755
+ for (const r of first) {
11756
+ if (out.length >= max - fromExtra.length)
11757
+ break;
11758
+ if (seen.has(key(r)))
11759
+ continue;
11760
+ out.push(r);
11761
+ seen.add(key(r));
11762
+ }
11763
+ for (const r of fromExtra) {
11764
+ if (seen.has(key(r)))
11765
+ continue;
11766
+ out.push(r);
11767
+ seen.add(key(r));
11768
+ }
11769
+ return out;
11770
+ }
11771
+ function compactReport(report) {
11772
+ if (!report || typeof report !== "object")
11773
+ return report;
11774
+ const out = { ...report };
11775
+ if (out.amb && typeof out.amb === "object" && Array.isArray(out.amb.channels)) {
11776
+ const channels = out.amb.channels;
11777
+ const odd = channels.filter((c) => c?.status !== "subscribed");
11778
+ out.amb = {
11779
+ connection: out.amb.state?.connection,
11780
+ channels: channels.length,
11781
+ ...odd.length ? { notSubscribed: odd.map((c) => ({ channel: c.channel, status: c.status })) } : {}
11782
+ };
11783
+ }
11784
+ if (Array.isArray(out.serverLog)) {
11785
+ const failed = out.serverLog.filter((e) => !(Number(e?.status) >= 200 && Number(e?.status) < 400));
11786
+ const kinds = {};
11787
+ for (const e of out.serverLog)
11788
+ kinds[e?.kind || "call"] = (kinds[e?.kind || "call"] || 0) + 1;
11789
+ out.serverLog = {
11790
+ calls: out.serverLog.length,
11791
+ ok: out.serverLog.length - failed.length,
11792
+ kinds,
11793
+ ...failed.length ? { failed } : {}
11794
+ };
11795
+ }
11796
+ return out;
11797
+ }
11210
11798
  function need(ok, action, what) {
11211
11799
  if (!ok)
11212
11800
  throw new Error(`${action} needs ${what}`);
@@ -11226,13 +11814,13 @@ var Ref = (description) => ({ type: "string", minLength: 1, maxLength: 300, desc
11226
11814
  maxItems: 30,
11227
11815
  items: { type: "string", minLength: 1, maxLength: 200 },
11228
11816
  description: `${what}: user criteria sys_ids or exact names`
11229
- }), CONDITION, SPEC_CRITERIA, specPlacement, specItem, specVariant, specPage, specPanel, menuItem, TOOLS, WORKSPACE, WS_KEYS, devPage = (args) => agentPage(workspaceDir(String(args.workspace)), {
11817
+ }), CONDITION, SPEC_CRITERIA, specPlacement, specItem, specVariant, specPage, specPanel, menuItem, OPTION_SLOTS = 3, TOOLS, WORKSPACE, WS_KEYS, devPage = (args) => agentPage(workspaceDir(String(args.workspace)), {
11230
11818
  headless: process.env.FORGE_DEV_HEADLESS === "1",
11231
11819
  attach: process.env.FORGE_DEV_ATTACH || undefined
11232
11820
  }), SELECTOR, withImage = (data, png) => ({
11233
11821
  ...data,
11234
11822
  image: { mimeType: "image/png", data: png }
11235
- });
11823
+ }), VERBOSE;
11236
11824
  var init_tools = __esm(() => {
11237
11825
  init_component_id();
11238
11826
  init_pull();
@@ -11517,18 +12105,26 @@ var init_tools = __esm(() => {
11517
12105
  limit: { type: "integer", minimum: 1, maximum: 20 }
11518
12106
  }, ["query"]),
11519
12107
  write: false,
11520
- run: (c, a) => c.get("/docs/search", { q: a.query, collection: a.collection, limit: a.limit })
12108
+ run: async (c, a) => {
12109
+ const words = optionWords(a.query);
12110
+ const [main, extra] = await Promise.all([
12111
+ c.get("/docs/search", { q: a.query, collection: a.collection, limit: 20 }),
12112
+ words ? c.get("/docs/search", { q: words, collection: a.collection, limit: 20 }) : Promise.resolve([])
12113
+ ]);
12114
+ const list = (v) => Array.isArray(v) ? v : [];
12115
+ return rankDocHits(list(main), list(extra), a.collection, a.limit || 8);
12116
+ }
11521
12117
  },
11522
12118
  {
11523
12119
  name: "read_doc",
11524
- description: "Read one doc page by path (from search_docs), optionally only the section under one heading.",
12120
+ description: "Read one doc page by path (from search_docs), optionally only the section under one heading (as listed in headings, with or without the leading #s).",
11525
12121
  inputSchema: obj2({
11526
12122
  path: { type: "string", maxLength: 300 },
11527
12123
  collection: { type: "string", enum: ["react-portal", "reference", "api-manifest"] },
11528
12124
  heading: { type: "string", maxLength: 200 }
11529
12125
  }, ["path"]),
11530
12126
  write: false,
11531
- run: (c, a) => c.get("/doc", { path: a.path, collection: a.collection, heading: a.heading })
12127
+ run: (c, a) => c.get("/doc", { path: a.path, collection: a.collection, heading: docHeading(a.heading) })
11532
12128
  },
11533
12129
  {
11534
12130
  name: "lookup_api",
@@ -12185,13 +12781,24 @@ var init_tools = __esm(() => {
12185
12781
  ];
12186
12782
  TOOLS.push({
12187
12783
  name: "workspace_pull",
12188
- description: "Bring a portal into a local workspace folder (<workspaces folder>/<name>/, the app-pack layout: portal.mjs, components/@<ns>/<key>/, themes/, assets/) plus its manifest forge.workspace.json (the base state of every record, committed) and the gitignored .forge/ (base snapshot). Read-only on the instance. Any portal of a scoped application, React Portal-owned ones included (sp, crm…: their records belong to React Portal, so reconcile edits after upgrades; only the React Portal components the portal uses are pulled). The workspaces folder is the folder the server was started in (or the apps/ folder it is configured with). A new or empty folder is a fresh pull; a folder with files but no manifest is adopted (nothing overwritten: the instance becomes the base and the local differences are reported); a folder with a manifest is re-synced three-way (instance changes taken, local changes kept, conflicts left local with the instance copy in .forge/conflicts/ for workspace_resolve; records deleted on the instance are removed locally; records removed locally are restored unless keepRemoved).",
12784
+ description: "Component workspaces: give app + components (and no portal) to pull components of one scoped application into a component-only workspace (components/@<ns>/<key>/ only, no portal.mjs; status / check / push work the same and push into that app and update set; a new component is just a new folder with component.json + main.tsx; rpf dev shows the component stage, see dev_stage); in such a folder, workspace_pull with only workspace-level arguments re-syncs every tracked component. Portals: " + "Bring a portal into a local workspace folder (<workspaces folder>/<name>/, the app-pack layout: portal.mjs, components/@<ns>/<key>/, themes/, assets/) plus its manifest forge.workspace.json (the base state of every record, committed) and the gitignored .forge/ (base snapshot). Read-only on the instance. Any portal of a scoped application, React Portal-owned ones included (sp, crm…: their records belong to React Portal, so reconcile edits after upgrades; only the React Portal components the portal uses are pulled). The workspaces folder is the folder the server was started in (or the apps/ folder it is configured with). A new or empty folder is a fresh pull; a folder with files but no manifest is adopted (nothing overwritten: the instance becomes the base and the local differences are reported); a folder with a manifest is re-synced three-way (instance changes taken, local changes kept, conflicts left local with the instance copy in .forge/conflicts/ for workspace_resolve; records deleted on the instance are removed locally; records removed locally are restored unless keepRemoved).",
12189
12785
  inputSchema: obj2({
12190
12786
  portal: PORTAL,
12787
+ app: {
12788
+ type: "string",
12789
+ maxLength: 100,
12790
+ description: "Component workspaces (no portal): the owning scoped application (scope name or sys_id); never Global or React Portal"
12791
+ },
12792
+ components: {
12793
+ type: "array",
12794
+ maxItems: 200,
12795
+ items: { type: "string", pattern: "^[a-z][a-z0-9_-]{0,39}/[a-z][a-z0-9-]{0,79}$" },
12796
+ description: "Component workspaces: component ids (<namespace>/<key>) of that app to add and pull"
12797
+ },
12191
12798
  name: {
12192
12799
  type: "string",
12193
12800
  pattern: "^[a-z][a-z0-9-]{0,59}$",
12194
- description: "Folder name in the workspaces folder (default: the portal slug)"
12801
+ description: "Folder name in the workspaces folder (default: the portal slug; required for a new component workspace)"
12195
12802
  },
12196
12803
  out: {
12197
12804
  type: "string",
@@ -12224,7 +12831,7 @@ var init_tools = __esm(() => {
12224
12831
  type: "boolean",
12225
12832
  description: "Resync: leave records and files removed locally removed (default: restore them)"
12226
12833
  }
12227
- }, ["portal"]),
12834
+ }, []),
12228
12835
  write: false,
12229
12836
  localWrite: true,
12230
12837
  run: (client, args) => pull(client, args)
@@ -12362,6 +12969,10 @@ var init_tools = __esm(() => {
12362
12969
  maxLength: 500,
12363
12970
  description: 'An element: a CSS selector (it pierces the portal shadow roots), "text=<visible text>" or "role=<role>[name=<accessible name>]"'
12364
12971
  };
12972
+ VERBOSE = {
12973
+ type: "boolean",
12974
+ description: "Return the full server-call log and record watch channels (default: counts and failures)"
12975
+ };
12365
12976
  TOOLS.push({
12366
12977
  name: "dev_status",
12367
12978
  description: "The workspace's rpf dev server: URL, portal, module generation, compiled components, staged server scripts, problems (compile errors, missing components), proxy and compile timings. Read-only. Start the server with `rpf dev` in the workspace first.",
@@ -12375,9 +12986,85 @@ var init_tools = __esm(() => {
12375
12986
  return { url: s.url, slug: s.slug, startedAt: s.startedAt, ...status };
12376
12987
  }
12377
12988
  });
12989
+ TOOLS.push({
12990
+ name: "dev_stage",
12991
+ description: `The component stage of a component workspace's rpf dev server: pick the component and set what it renders with: options (over its defaults), URL params and context (table, sysId, view, query, extra q pairs), the theme of any portal (themePortal: slug) or a theme key, light / dark, and a device width. Saved to the workspace's stage.json (local only, never pushed); the page rebuilds. Returns the state and the URLs: stageUrl (the chrome with the form) and frameUrl (the component alone; dev_open with route "stage" opens the same). Fields left out keep their value; pass reset: true to start from an empty state.`,
12992
+ inputSchema: obj2({
12993
+ workspace: WORKSPACE,
12994
+ component: {
12995
+ type: "string",
12996
+ maxLength: 121,
12997
+ description: "The component (<namespace>/<key>); default: the current one"
12998
+ },
12999
+ options: { type: "object", description: "Option values (replace the stored options object)" },
13000
+ params: {
13001
+ type: "object",
13002
+ properties: {
13003
+ table: { type: "string", maxLength: 80 },
13004
+ sysId: { type: "string", maxLength: 32 },
13005
+ view: { type: "string", maxLength: 80 },
13006
+ query: { type: "string", maxLength: 2000 },
13007
+ q: {
13008
+ type: "array",
13009
+ maxItems: 50,
13010
+ items: { type: "array", minItems: 2, maxItems: 2, items: { type: "string", maxLength: 1000 } },
13011
+ description: "Extra [name, value] pairs (carried in the q param)"
13012
+ }
13013
+ },
13014
+ description: "URL params and context (replace the stored params)"
13015
+ },
13016
+ themePortal: {
13017
+ type: "string",
13018
+ maxLength: 40,
13019
+ description: `Render with this portal's slug and theme ("" = none)`
13020
+ },
13021
+ theme: { type: "string", maxLength: 80, description: 'Or with this theme key ("" = none)' },
13022
+ mode: { type: "string", enum: ["light", "dark", "system"] },
13023
+ width: {
13024
+ description: "phone (390), tablet (820), laptop (1280), full, or a pixel width (the stage chrome's frame)",
13025
+ anyOf: [
13026
+ { type: "string", enum: ["phone", "tablet", "laptop", "full"] },
13027
+ { type: "integer", minimum: 240, maximum: 3840 }
13028
+ ]
13029
+ },
13030
+ reset: { type: "boolean", description: "Start from an empty state before applying the fields given" }
13031
+ }, ["workspace"]),
13032
+ write: false,
13033
+ localWrite: true,
13034
+ run: async (_c, args) => {
13035
+ const s = readDevSession(workspaceDir(String(args.workspace)));
13036
+ if (!s)
13037
+ throw new Error(`No rpf dev server runs for ${args.workspace}: start \`rpf dev\` in that workspace`);
13038
+ const q = args.component ? "?c=" + encodeURIComponent(String(args.component)) : "";
13039
+ const info = await devJson(s, "/__rpf/stage/info" + q);
13040
+ if (args.component && info.current !== args.component)
13041
+ throw new Error(`No component ${args.component} in this workspace (${(info.components || []).map((c) => c.uniqueId).join(", ")})`);
13042
+ const state = args.reset ? { options: {}, params: {} } : { ...info.state };
13043
+ for (const k of ["options", "params", "mode", "width"])
13044
+ if (args[k] !== undefined)
13045
+ state[k] = args[k];
13046
+ for (const k of ["themePortal", "theme"])
13047
+ if (args[k] !== undefined)
13048
+ state[k] = args[k] || undefined;
13049
+ const saved = await devSend(s, "/__rpf/stage/state", "PUT", { component: info.current, state });
13050
+ const after = await devJson(s, "/__rpf/stage/info");
13051
+ return {
13052
+ component: after.current,
13053
+ state: after.state,
13054
+ slug: saved.slug,
13055
+ stageUrl: `${s.url}/__rpf/stage?c=${encodeURIComponent(after.current)}`,
13056
+ frameUrl: `${s.url}/x/312987/portal/site/${encodeURIComponent(saved.slug)}/params/page-id/stage`,
13057
+ components: (after.components || []).map((c) => ({
13058
+ uniqueId: c.uniqueId,
13059
+ kind: c.kind,
13060
+ name: c.name
13061
+ }))
13062
+ };
13063
+ }
13064
+ });
12378
13065
  TOOLS.push({
12379
13066
  name: "dev_open",
12380
- description: "Open a route of the workspace's rpf dev page in the controlled browser (read-only) and wait until it's idle (no server call or data request in flight). Returns the URL, title, problems, console errors, the server-call log and record watch state. screenshot: true adds a PNG.",
13067
+ description: "Open a route of the workspace's rpf dev page in the controlled browser (read-only) and wait until it's idle (no server call or data request in flight). Returns the URL, title, problems, console errors, and server calls and record watch as counts plus failures (verbose: the full lists). screenshot: true adds a PNG: look at it, since text in the DOM can still be hidden.",
12381
13068
  inputSchema: obj2({
12382
13069
  workspace: WORKSPACE,
12383
13070
  route: {
@@ -12392,17 +13079,19 @@ var init_tools = __esm(() => {
12392
13079
  enum: ["light", "dark"],
12393
13080
  description: "Force the mode on the portal (never stored)"
12394
13081
  },
12395
- screenshot: { type: "boolean" }
13082
+ screenshot: { type: "boolean" },
13083
+ verbose: VERBOSE
12396
13084
  }, ["workspace"]),
12397
13085
  write: false,
12398
13086
  run: async (_c, args) => {
12399
13087
  const { page } = await devPage(args);
12400
- const report = await page.open({
13088
+ const opened = await page.open({
12401
13089
  route: args.route || "",
12402
13090
  width: args.width,
12403
13091
  height: args.height,
12404
13092
  theme: args.theme
12405
13093
  });
13094
+ const report = args.verbose ? opened : compactReport(opened);
12406
13095
  return args.screenshot ? withImage(report, await page.screenshot()) : report;
12407
13096
  }
12408
13097
  });
@@ -12416,7 +13105,8 @@ var init_tools = __esm(() => {
12416
13105
  text: { type: "string", maxLength: 5000, description: "type: the text; select: the option value or label" },
12417
13106
  key: { type: "string", maxLength: 40, description: "press: the key or combination" },
12418
13107
  dy: { type: "integer", description: "scroll: pixels down (negative = up)" },
12419
- screenshot: { type: "boolean" }
13108
+ screenshot: { type: "boolean" },
13109
+ verbose: VERBOSE
12420
13110
  }, ["workspace", "action"]),
12421
13111
  write: false,
12422
13112
  run: async (_c, args) => {
@@ -12444,7 +13134,8 @@ var init_tools = __esm(() => {
12444
13134
  await page.select(args.selector, args.text);
12445
13135
  }
12446
13136
  await page.waitIdle(1e4);
12447
- const report = await page.report();
13137
+ const full = await page.report();
13138
+ const report = args.verbose ? full : compactReport(full);
12448
13139
  return args.screenshot ? withImage(report, await page.screenshot()) : report;
12449
13140
  }
12450
13141
  });
@@ -12464,22 +13155,30 @@ var init_tools = __esm(() => {
12464
13155
  });
12465
13156
  TOOLS.push({
12466
13157
  name: "dev_inspect",
12467
- description: "Read the open dev page: the accessibility tree (roles, names, values, states; for finding what to click), the problems overlay, console messages and errors, the network log (method, URL, status, time), the server-call log, record watch channels, and whether it is idle. Read-only.",
13158
+ description: 'Read the open dev page: the accessibility tree (roles, names, values, states; for finding what to click), the problems overlay, console messages and errors, the network log (method, URL, status, time), the server-call log, record watch channels, and whether it is idle. find: "text=<text>" or a CSS selector, across the portal shadow roots: each match with visible (true / false), its rect and, when hidden, hiddenBy (the element and the reason: display: none, visibility, opacity 0, zero size, clipped, outside the viewport). Text in the DOM is not proof it is visible: use find (or a screenshot) to confirm. Read-only.',
12468
13159
  inputSchema: obj2({
12469
13160
  workspace: WORKSPACE,
12470
13161
  include: {
12471
13162
  type: "array",
12472
13163
  items: { type: "string", enum: ["accessibility", "problems", "console", "network", "server", "amb"] },
12473
- description: "What to return (default: all)"
13164
+ description: "What to return (default: all; with find, nothing else unless listed)"
13165
+ },
13166
+ find: {
13167
+ type: "string",
13168
+ minLength: 1,
13169
+ maxLength: 500,
13170
+ description: '"text=<text>" (hidden elements included) or a CSS selector: matches with their visibility'
12474
13171
  }
12475
13172
  }, ["workspace"]),
12476
13173
  write: false,
12477
13174
  run: async (_c, args) => {
12478
13175
  const { page } = await devPage(args);
12479
13176
  const all = ["accessibility", "problems", "console", "network", "server", "amb"];
12480
- const want = new Set(args.include && args.include.length ? args.include : all);
13177
+ const want = new Set(args.include && args.include.length ? args.include : args.find ? [] : all);
12481
13178
  const r = await page.report();
12482
13179
  const out = { url: r.url, title: r.title, idle: r.idle, readOnly: r.readOnly };
13180
+ if (args.find)
13181
+ out.found = await page.locate(String(args.find), 10);
12483
13182
  if (want.has("accessibility"))
12484
13183
  out.accessibility = await page.accessibility();
12485
13184
  if (want.has("problems"))
@@ -12497,7 +13196,7 @@ var init_tools = __esm(() => {
12497
13196
  });
12498
13197
  TOOLS.push({
12499
13198
  name: "dev_eval",
12500
- description: 'Evaluate a JavaScript expression in the open dev page (promises awaited) and return its JSON value, e.g. "window.__RPF_AGENT__.serverLog()" or "document.title". The page is read-only: instance writes from it are refused by rpf.',
13199
+ description: 'Evaluate a JavaScript expression in the open dev page (promises awaited) and return its JSON value, e.g. "window.__RPF_AGENT__.serverLog()" or "document.title". The portal renders inside open shadow roots, so document.querySelector does not reach its elements (walk element.shadowRoot, or use dev_inspect find, which also says whether a match is visible). The page is read-only: instance writes from it are refused by rpf.',
12501
13200
  inputSchema: obj2({ workspace: WORKSPACE, expression: { type: "string", minLength: 1, maxLength: 20000 } }, [
12502
13201
  "workspace",
12503
13202
  "expression"
@@ -12536,6 +13235,26 @@ import {
12536
13235
  ReadResourceRequestSchema
12537
13236
  } from "@modelcontextprotocol/sdk/types.js";
12538
13237
  import Ajv from "ajv";
13238
+ function serverInstructions(forceDryRun, forge = false) {
13239
+ const dry = forceDryRun ? "This server runs with FORGE_DRY_RUN: every write is a dry run, nothing is saved." : "";
13240
+ if (forge)
13241
+ return [
13242
+ "rpf tools for React Portal on a ServiceNow instance, as the signed-in user (their Studio roles apply).",
13243
+ "The work happens in a local workspace: the session's system prompt sets the workflow. Instance writes (create_*, update_*, apply_spec, place_component) only exist when the user allows remote writes, and every write accepts dryRun: true. Nothing is ever published or deleted.",
13244
+ dry
13245
+ ].filter(Boolean).join(" ");
13246
+ return [
13247
+ "Forge builds React Portal portals and components on a ServiceNow instance, as the signed-in user (their Studio roles apply).",
13248
+ "Workflow: get_context first; list_components to reuse; search_docs / lookup_api / read_doc before writing code;",
13249
+ "create_component then write_component_files and fix every compile error; place_component on a page; get_preview to check; get_execution_log for server script errors.",
13250
+ "Structure: create_panel / update_panel for side panels, create_variant / update_variant for page variants (one URL, a condition on URL params), set_criteria for audiences (roles and user criteria). For many pages, variants, panels, menus and placements at once, prefer apply_spec: one declarative spec, one plan, idempotent by keys, never deletes.",
13251
+ "rpf dev (a running local preview of a workspace): dev_status, then dev_open a route, dev_act to click / type / press, dev_inspect for the accessibility tree, console, network and server calls, dev_screenshot. The dev browser is read-only: instance writes from it are refused.",
13252
+ "Every write accepts dryRun:true and returns exactly what would change. Prefer a dry run before writes to live (active) portals.",
13253
+ "Forge creates portals as inactive drafts only; it cannot publish (active: true is refused). Publishing is a Studio action that needs the publish capability, so tell the user to publish the draft in Studio. Nothing is ever deleted: removals deactivate.",
13254
+ "Application scope: any app can own portals, components and themes (like Service Portal and Workspace content). New ones land in the user's current application (get_context scope.authoringApp; never Global); a portal's pages, placements and menus follow the portal's app. Editing a record needs its app to be current (wrong_scope otherwise: switch_app, and tell the user it changes their picker). Pass app on writes to pin the target app. Using React Portal's own components and themes from any app is fine; components or themes of a third app trigger a cross-app warning (they won't travel in the portal app's update set).",
13255
+ dry
13256
+ ].filter(Boolean).join(" ");
13257
+ }
12539
13258
  async function startServer(config, opts = {}) {
12540
13259
  const problem = configProblem(config);
12541
13260
  const client = new ForgeClient(config);
@@ -12561,21 +13280,12 @@ async function startServer(config, opts = {}) {
12561
13280
  if (blocked)
12562
13281
  log(blocked);
12563
13282
  }
13283
+ const forgeHost = process.env.RPFORGE_MCP_HOST === "forge";
12564
13284
  const ajv = new Ajv({ allErrors: true, strict: false });
12565
13285
  const validators = new Map(TOOLS.map((t) => [t.name, ajv.compile(t.inputSchema)]));
12566
13286
  const server = new Server({ name: "forge", version: VERSION2 }, {
12567
13287
  capabilities: { tools: {}, prompts: {}, resources: {} },
12568
- instructions: [
12569
- "Forge builds React Portal portals and components on a ServiceNow instance, as the signed-in user (their Studio roles apply).",
12570
- "Workflow: get_context first; list_components to reuse; search_docs / lookup_api / read_doc before writing code;",
12571
- "create_component then write_component_files and fix every compile error; place_component on a page; get_preview to check; get_execution_log for server script errors.",
12572
- "Structure: create_panel / update_panel for side panels, create_variant / update_variant for page variants (one URL, a condition on URL params), set_criteria for audiences (roles and user criteria). For many pages, variants, panels, menus and placements at once, prefer apply_spec: one declarative spec, one plan, idempotent by keys, never deletes.",
12573
- "rpf dev (a running local preview of a workspace): dev_status, then dev_open a route, dev_act to click / type / press, dev_inspect for the accessibility tree, console, network and server calls, dev_screenshot. The dev browser is read-only: instance writes from it are refused.",
12574
- "Every write accepts dryRun:true and returns exactly what would change. Prefer a dry run before writes to live (active) portals.",
12575
- "Forge creates portals as inactive drafts only; it cannot publish (active: true is refused). Publishing is a Studio action that needs the publish capability, so tell the user to publish the draft in Studio. Nothing is ever deleted: removals deactivate.",
12576
- "Application scope: any app can own portals, components and themes (like Service Portal and Workspace content). New ones land in the user's current application (get_context scope.authoringApp; never Global); a portal's pages, placements and menus follow the portal's app. Editing a record needs its app to be current (wrong_scope otherwise: switch_app, and tell the user it changes their picker). Pass app on writes to pin the target app. Using React Portal's own components and themes from any app is fine; components or themes of a third app trigger a cross-app warning (they won't travel in the portal app's update set).",
12577
- config.forceDryRun ? "This server runs with FORGE_DRY_RUN: every write is a dry run, nothing is saved." : ""
12578
- ].filter(Boolean).join(" ")
13288
+ instructions: serverInstructions(config.forceDryRun, forgeHost)
12579
13289
  });
12580
13290
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
12581
13291
  tools: TOOLS.map((t) => ({
@@ -12587,7 +13297,8 @@ async function startServer(config, opts = {}) {
12587
13297
  destructiveHint: false,
12588
13298
  idempotentHint: !t.write,
12589
13299
  openWorldHint: false
12590
- }
13300
+ },
13301
+ ...forgeHost && ALWAYS_LOAD_IN_FORGE.includes(t.name) ? { _meta: { "anthropic/alwaysLoad": true } } : {}
12591
13302
  }))
12592
13303
  }));
12593
13304
  const PROMPTS = [
@@ -12724,7 +13435,7 @@ async function startServer(config, opts = {}) {
12724
13435
  process.once("SIGTERM", shutdown);
12725
13436
  log(`ready (${TOOLS.length} tools)`);
12726
13437
  }
12727
- var VERSION2 = "0.3.0";
13438
+ var VERSION2 = "0.3.0", ALWAYS_LOAD_IN_FORGE;
12728
13439
  var init_server2 = __esm(() => {
12729
13440
  init_config();
12730
13441
  init_client();
@@ -12734,6 +13445,7 @@ var init_server2 = __esm(() => {
12734
13445
  init_tools();
12735
13446
  init_agent();
12736
13447
  init_themes();
13448
+ ALWAYS_LOAD_IN_FORGE = ["dev_open", "read_doc", "workspace_check"];
12737
13449
  });
12738
13450
 
12739
13451
  // src/commands/mcp.ts
@@ -12755,8 +13467,8 @@ var init_mcp = __esm(() => {
12755
13467
  });
12756
13468
 
12757
13469
  // src/commands/workspace.ts
12758
- import { existsSync as existsSync24, readFileSync as readFileSync26 } from "node:fs";
12759
- import { dirname as dirname12, join as join25, resolve as resolve8 } from "node:path";
13470
+ import { existsSync as existsSync26, readFileSync as readFileSync27 } from "node:fs";
13471
+ import { dirname as dirname12, join as join27, resolve as resolve8 } from "node:path";
12760
13472
  import * as p2 from "@clack/prompts";
12761
13473
  function startDir(ctx) {
12762
13474
  return ctx.opts.dir ? resolve8(ctx.opts.dir) : process.cwd();
@@ -12773,13 +13485,13 @@ function requireWorkspace(ctx) {
12773
13485
  function prettierConfigFor(dir) {
12774
13486
  let d = resolve8(dir);
12775
13487
  for (;; ) {
12776
- if (PRETTIER_FILES.some((f) => existsSync24(join25(d, f))))
12777
- return join25(dir, "portal.mjs");
12778
- const pkg = join25(d, "package.json");
12779
- if (existsSync24(pkg)) {
13488
+ if (PRETTIER_FILES.some((f) => existsSync26(join27(d, f))))
13489
+ return join27(dir, "portal.mjs");
13490
+ const pkg = join27(d, "package.json");
13491
+ if (existsSync26(pkg)) {
12780
13492
  try {
12781
- if (JSON.parse(readFileSync26(pkg, "utf8")).prettier)
12782
- return join25(dir, "portal.mjs");
13493
+ if (JSON.parse(readFileSync27(pkg, "utf8")).prettier)
13494
+ return join27(dir, "portal.mjs");
12783
13495
  } catch {}
12784
13496
  }
12785
13497
  const up = dirname12(d);
@@ -12861,14 +13573,17 @@ function newWorkspaceBase(ctx, c) {
12861
13573
  return { base: resolve8(own), why: `profile ${c.r.profile}` };
12862
13574
  if (pf.defaults.dir)
12863
13575
  return { base: resolve8(pf.defaults.dir), why: "the saved default folder" };
12864
- if (existsSync24(join25(process.cwd(), "apps")))
12865
- return { base: join25(process.cwd(), "apps"), why: "./apps" };
13576
+ if (existsSync26(join27(process.cwd(), "apps")))
13577
+ return { base: join27(process.cwd(), "apps"), why: "./apps" };
12866
13578
  return { base: process.cwd(), why: "the current folder" };
12867
13579
  }
12868
13580
  async function pull2(ctx, portalArg, o) {
12869
13581
  if (o.mode && !["auto", "fresh", "adopt"].includes(o.mode))
12870
13582
  throw usage(`--mode ${o.mode}: one of auto, fresh, adopt`);
12871
13583
  const ws = currentWorkspace(ctx);
13584
+ const wsManifest = ws ? readManifest(ws) : null;
13585
+ if (o.component || o.app || !portalArg && isComponentManifest(wsManifest))
13586
+ return pullComponents(ctx, ws, o);
12872
13587
  const c = await connect(ctx);
12873
13588
  let portal = portalArg || "";
12874
13589
  let out = o.out ? resolve8(o.out) : "";
@@ -12932,6 +13647,64 @@ async function pull2(ctx, portalArg, o) {
12932
13647
  renderPull(ctx.out, result);
12933
13648
  finish(ctx, "pull", c, result, failed(result));
12934
13649
  }
13650
+ async function pullComponents(ctx, ws, o) {
13651
+ const c = await connect(ctx);
13652
+ const ids = list3(o.component) || [];
13653
+ const bad = ids.filter((u) => !COMPONENT_ID_RE.test(u));
13654
+ if (bad.length)
13655
+ throw usage(`--component ${bad.join(", ")}: give <namespace>/<key>`);
13656
+ const m = ws ? readManifest(ws) : null;
13657
+ let out = o.out ? resolve8(o.out) : "";
13658
+ let base = "";
13659
+ if (!out && ws && m) {
13660
+ if (!isComponentManifest(m))
13661
+ throw usage(`${rel(ws)} is a portal workspace: pull components into a component workspace (--out <folder> --app <scope>)`);
13662
+ out = ws;
13663
+ }
13664
+ if (!out) {
13665
+ if (!o.app)
13666
+ throw usage("A new component workspace needs --app <scope> (and --name or --out)");
13667
+ if (!o.name)
13668
+ throw usage("A new component workspace needs a folder: --name <folder> or --out <path>");
13669
+ const b = newWorkspaceBase(ctx, c);
13670
+ base = b.base;
13671
+ ctx.out.info(`new workspaces go into ${rel(base)} (${b.why})`);
13672
+ }
13673
+ configure(base || dirname12(out), out || base);
13674
+ const args = {
13675
+ app: o.app,
13676
+ components: ids,
13677
+ name: o.name,
13678
+ out: out || undefined,
13679
+ updateSet: o.updateSet,
13680
+ mode: o.mode,
13681
+ keepRemoved: !!o.keepRemoved
13682
+ };
13683
+ let result;
13684
+ for (;; ) {
13685
+ try {
13686
+ result = await step(ctx, `Pulling ${ids.join(", ") || "components"} from ${c.key}`, () => pull(c.client, args));
13687
+ break;
13688
+ } catch (e) {
13689
+ const err = e;
13690
+ if (err && err.code === "update_set_required") {
13691
+ const sets = err.details && err.details.updateSets || [];
13692
+ if (ctx.interactive && sets.length && !args.updateSet) {
13693
+ args.updateSet = answered(await p2.select({
13694
+ message: `Which update set of ${err.details.app} should pushes write into?`,
13695
+ options: sets.map((s) => ({ value: s.name, label: s.name }))
13696
+ }));
13697
+ continue;
13698
+ }
13699
+ throw new CliError(EXIT.usage, "update_set_required", cliText(err.message), err.details);
13700
+ }
13701
+ throw e;
13702
+ }
13703
+ }
13704
+ if (!ctx.out.o.json)
13705
+ renderPull(ctx.out, result);
13706
+ finish(ctx, "pull", c, result, failed(result));
13707
+ }
12935
13708
  async function status3(ctx) {
12936
13709
  const ws = requireWorkspace(ctx);
12937
13710
  const c = await connect(ctx);
@@ -13056,7 +13829,7 @@ async function pushCmd(ctx, o) {
13056
13829
  requireTracked(ws, c);
13057
13830
  configure(dirname12(ws), ws);
13058
13831
  const inst = readManifest(ws).instances[c.key];
13059
- const slug = inst.portal.slug;
13832
+ const slug = inst.portal.slug || inst.app.scope;
13060
13833
  const force = !!o.force;
13061
13834
  const common = { workspace: ws, force, removeFiles: list3(o.removeFiles), reprocess: !!o.reprocess };
13062
13835
  const forced = c.r.config.forceDryRun;
@@ -13145,7 +13918,7 @@ async function renameCmd(ctx, from, to) {
13145
13918
  finish(ctx, "rename", null, result, failed(result));
13146
13919
  }
13147
13920
  function registerWorkspace(program, run) {
13148
- const pullCmd = program.command("pull").argument("[portal]", "portal slug or sys_id (default: the current workspace’s portal)").description("Bring a portal into a local workspace: a fresh pull into a new folder, adopt a folder with files, or a three-way re-sync of the current workspace. Read-only on the instance").option("--name <name>", "folder name for a new workspace (default: the portal slug)").option("--out <folder>", "the exact folder for a new workspace (default: <base>/<slug>)").option("--update-set <name>", "the in-progress update set pushes write into (name or sys_id)").option("--mode <mode>", "auto (default), fresh or adopt").option("--keep-removed", "re-sync: leave records and files removed locally removed").option("--ignore <keys>", "comma-separated keys the workspace never pulls (kept in the manifest)").option("--images <names>", "comma-separated image names to pull even when no file names them");
13921
+ const pullCmd = program.command("pull").argument("[portal]", "portal slug or sys_id (default: the current workspace’s portal)").description("Bring a portal into a local workspace: a fresh pull into a new folder, adopt a folder with files, or a three-way re-sync of the current workspace. Read-only on the instance").option("--component <ids>", "component workspace: components to add and pull (comma-separated <ns>/<key>)").option("--app <scope>", "component workspace: the application of a new one").option("--name <name>", "folder name for a new workspace (default: the portal slug)").option("--out <folder>", "the exact folder for a new workspace (default: <base>/<slug>)").option("--update-set <name>", "the in-progress update set pushes write into (name or sys_id)").option("--mode <mode>", "auto (default), fresh or adopt").option("--keep-removed", "re-sync: leave records and files removed locally removed").option("--ignore <keys>", "comma-separated keys the workspace never pulls (kept in the manifest)").option("--images <names>", "comma-separated image names to pull even when no file names them");
13149
13922
  pullCmd.action(run((ctx) => pull2(ctx, pullCmd.processedArgs[0], pullCmd.opts())));
13150
13923
  program.command("status").description("Three-way status: local changes, instance changes (who and when), conflicts, converged, renames, untracked files").action(run((ctx) => status3(ctx)));
13151
13924
  const diffCmd = program.command("diff").argument("[keys...]", "keys or paths as status lists them (default: everything changed)").description("Unified diffs for files, field diffs for portal.mjs records").option("--against <side>", "auto (default), base, instance or local-instance");
@@ -13164,6 +13937,7 @@ var init_workspace = __esm(() => {
13164
13937
  init_client();
13165
13938
  init_layout();
13166
13939
  init_manifest();
13940
+ init_component_id();
13167
13941
  init_pull();
13168
13942
  init_status();
13169
13943
  init_diff();
@@ -13514,18 +14288,588 @@ var init_init = __esm(() => {
13514
14288
  };
13515
14289
  });
13516
14290
 
13517
- // src/commands/init.ts
13518
- import { existsSync as existsSync25, mkdirSync as mkdirSync12, readFileSync as readFileSync27, readdirSync as readdirSync8, writeFileSync as writeFileSync13 } from "node:fs";
13519
- import { dirname as dirname13, isAbsolute as isAbsolute4, join as join26, resolve as resolve9 } from "node:path";
13520
- import { randomUUID } from "node:crypto";
13521
- import { spawnSync as spawnSync6 } from "node:child_process";
14291
+ // src/commands/new.ts
14292
+ import { existsSync as existsSync27, mkdirSync as mkdirSync12, readFileSync as readFileSync28, writeFileSync as writeFileSync14 } from "node:fs";
14293
+ import { join as join28 } from "node:path";
13522
14294
  import * as p3 from "@clack/prompts";
13523
- function list4(v) {
13524
- if (v === undefined)
14295
+ function title(key) {
14296
+ return key.split("-").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
14297
+ }
14298
+ function pascal(key) {
14299
+ return title(key).replace(/\s+/g, "") || "Component";
14300
+ }
14301
+ function scaffold(uid, kind, name, description) {
14302
+ const [, key] = uid.split("/");
14303
+ const C = pascal(key);
14304
+ const meta = { name, kind, description, tailwind: kind !== "layout" };
14305
+ const files = {};
14306
+ const doc = `/**
14307
+ * components:${uid}: ${description || name}.
14308
+ */
14309
+ `;
14310
+ if (kind === "widget") {
14311
+ meta.defaults = { title: name };
14312
+ files["main.tsx"] = `import { Card, CardHeader, CardTitle, CardContent } from 'components:card';
14313
+
14314
+ ${doc}` + `type Options = { title?: string };
14315
+
14316
+ ` + `export default function ${C}({ options = {} }: { options?: Options }) {
14317
+ ` + ` return (
14318
+ <Card>
14319
+ <CardHeader>
14320
+ <CardTitle>{options.title || '${name}'}</CardTitle>
14321
+ </CardHeader>
14322
+ ` + ` <CardContent>
14323
+ <p className="text-sm text-muted-foreground">Edit components/@${uid}/main.tsx.</p>
14324
+ </CardContent>
14325
+ </Card>
14326
+ );
14327
+ }
14328
+ `;
14329
+ files["options.schema.json"] = JSON.stringify({
14330
+ type: "object",
14331
+ properties: { title: { type: "string", title: "Title", default: name } }
14332
+ }, null, 4);
14333
+ } else if (kind === "primitive") {
14334
+ files["main.tsx"] = `import type { ReactNode } from 'react';
14335
+
14336
+ ${doc}` + `export interface ${C}Props {
14337
+ children?: ReactNode;
14338
+ className?: string;
14339
+ }
14340
+
14341
+ ` + `export function ${C}({ children, className = '' }: ${C}Props) {
14342
+ ` + ` return <div className={\`rounded-md border p-3 \${className}\`}>{children}</div>;
14343
+ }
14344
+
14345
+ ` + `/** Shown in Studio's preview of the primitive. */
14346
+ export default function ${C}Preview() {
14347
+ return <${C}>${name}</${C}>;
14348
+ }
14349
+ `;
14350
+ } else if (kind === "block") {
14351
+ meta.regions = [{ name: "main", label: "Content" }];
14352
+ meta.defaults = { gap: "1rem" };
14353
+ files["main.tsx"] = `import type { ReactNode } from 'react';
14354
+
14355
+ ${doc}` + `type Options = { gap?: string };
14356
+
14357
+ ` + `export default function ${C}({ options = {}, regions = {} }: { options?: Options; regions?: Record<string, ReactNode> }) {
14358
+ ` + ` return <div style={{ display: 'grid', gap: options.gap || '1rem' }}>{regions.main}</div>;
14359
+ }
14360
+ `;
14361
+ files["options.schema.json"] = JSON.stringify({ type: "object", properties: { gap: { type: "string", title: "Gap", default: "1rem" } } }, null, 4);
14362
+ } else if (kind === "layout") {
14363
+ meta.regions = [
14364
+ { name: "header", acceptsContributions: true },
14365
+ { name: "main", acceptsContributions: false },
14366
+ { name: "footer", acceptsContributions: true }
14367
+ ];
14368
+ meta.defaults = { contentPadding: "md" };
14369
+ files["main.tsx"] = `import type { ReactNode } from 'react';
14370
+
14371
+ ${doc}` + `type Options = { contentPadding?: 'none' | 'sm' | 'md' | 'lg' };
14372
+ ` + `const PAD = { none: '0', sm: '0.75rem', md: '1.5rem', lg: '2.5rem' };
14373
+
14374
+ ` + `export default function ${C}({ options = {}, regions = {} }: { options?: Options; regions?: Record<string, ReactNode> }) {
14375
+ ` + ` return (
14376
+ <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
14377
+ ` + ` <header>{regions.header}</header>
14378
+ ` + ` <main style={{ flex: 1, padding: PAD[options.contentPadding || 'md'] }}>{regions.main}</main>
14379
+ ` + ` <footer>{regions.footer}</footer>
14380
+ </div>
14381
+ );
14382
+ }
14383
+ `;
14384
+ files["options.schema.json"] = JSON.stringify({
14385
+ type: "object",
14386
+ properties: {
14387
+ contentPadding: {
14388
+ type: "string",
14389
+ title: "Content padding",
14390
+ enum: ["none", "sm", "md", "lg"],
14391
+ default: "md"
14392
+ }
14393
+ }
14394
+ }, null, 4);
14395
+ } else {
14396
+ files["main.tsx"] = `import { useMemo } from 'react';
14397
+
14398
+ ${doc}` + `/** Import it as utilities:${uid}. */
14399
+ export function use${C}(value: string) {
14400
+ return useMemo(() => value.trim(), [value]);
14401
+ }
14402
+ `;
14403
+ }
14404
+ files["component.json"] = JSON.stringify(meta, null, 4);
14405
+ return files;
14406
+ }
14407
+ function workspaceScope(ws) {
14408
+ try {
14409
+ const m = JSON.parse(readFileSync28(join28(ws, "forge.workspace.json"), "utf8"));
14410
+ const scopes = new Set;
14411
+ for (const inst of Object.values(m && m.instances || {}))
14412
+ if (inst && inst.app && inst.app.scope)
14413
+ scopes.add(String(inst.app.scope));
14414
+ return scopes.size === 1 ? [...scopes][0] : "";
14415
+ } catch {
14416
+ return "";
14417
+ }
14418
+ }
14419
+ async function newComponent(ctx, ref, o) {
14420
+ const ws = currentWorkspace(ctx);
14421
+ if (!ws)
14422
+ throw usage("No workspace here: run it inside a workspace (forge.workspace.json), or pass --dir");
14423
+ const scope = workspaceScope(ws);
14424
+ const defaultNs = defaultNamespaceFor(scope);
14425
+ let uid = String(ref || "").replace(/^@/, "");
14426
+ if (!uid && ctx.interactive) {
14427
+ const name = o.name || answered(await p3.text({
14428
+ message: "Name",
14429
+ placeholder: "Order card",
14430
+ validate: (v) => v ? undefined : "Required"
14431
+ }));
14432
+ o.name = name;
14433
+ const ns = answered(await p3.text({
14434
+ message: "Namespace",
14435
+ initialValue: defaultNs,
14436
+ placeholder: defaultNs || "acme",
14437
+ validate: (v) => namespaceProblem(v || "") || namespaceRefusal(v || "", scope) || undefined
14438
+ }));
14439
+ const key = answered(await p3.text({
14440
+ message: "Key",
14441
+ initialValue: keyFromName(name),
14442
+ validate: (v) => keyProblem(v || "") || undefined
14443
+ }));
14444
+ uid = `${ns}/${key}`;
14445
+ }
14446
+ if (uid && uid.indexOf("/") < 0 && defaultNs)
14447
+ uid = `${defaultNs}/${uid}`;
14448
+ const [ns, key, extra] = uid.split("/");
14449
+ const problem = !ns || !key || extra !== undefined ? `"${uid}": give <namespace>/<key>${defaultNs ? ` (or just <key> for ${defaultNs}/<key>)` : ""}` : namespaceProblem(ns) || keyProblem(key) || namespaceRefusal(ns, scope);
14450
+ if (problem)
14451
+ throw usage(problem);
14452
+ if (scope && ns !== scope && /^[a-z][a-z0-9]*_[a-z0-9_]+$/.test(ns) && !ctx.out.o.json)
14453
+ ctx.out.line(ctx.out.c.yellow(`warning: "${ns}" looks like another application's scope (this workspace is ${scope}); ids there can collide with what that app ships`));
14454
+ let kind = o.kind;
14455
+ if (!kind && ctx.interactive)
14456
+ kind = answered(await p3.select({
14457
+ message: "Kind",
14458
+ options: [
14459
+ { value: "widget", label: "widget", hint: "placeable on pages, with options" },
14460
+ { value: "primitive", label: "primitive", hint: "a reusable piece other components import" },
14461
+ { value: "block", label: "block", hint: "a placeable container with regions" },
14462
+ { value: "layout", label: "layout", hint: "a portal shell with regions" },
14463
+ { value: "utility", label: "utility", hint: "hooks and helpers (utilities:<ns>/<key>)" }
14464
+ ],
14465
+ initialValue: "widget"
14466
+ }));
14467
+ kind = kind || "widget";
14468
+ if (!KINDS.includes(kind))
14469
+ throw usage(`--kind ${kind}: one of ${KINDS.join(", ")}`);
14470
+ const dir = join28(ws, "components", "@" + ns, key);
14471
+ if (existsSync27(dir))
14472
+ throw usage(`${rel(dir)} already exists`);
14473
+ configureWorkspace({
14474
+ repo: "",
14475
+ apps: ws,
14476
+ prettierConfigFrom: prettierConfigFor(ws),
14477
+ tsc: "",
14478
+ hostTypes: "",
14479
+ typesFrom: ""
14480
+ });
14481
+ const written = await writeNewComponent(ws, `${ns}/${key}`, kind, o.name, o.description);
14482
+ if (!ctx.out.o.json) {
14483
+ ctx.out.line(ctx.out.c.green(`created ${kind} ${ns}/${key}`) + ctx.out.c.dim(` in ${rel(ws)}`));
14484
+ for (const f of written)
14485
+ ctx.out.line(" + " + f);
14486
+ ctx.out.line(ctx.out.c.dim("next: rpforge check (compiles it on the instance, writes nothing) · rpforge push"));
14487
+ }
14488
+ ctx.out.result("new component", { workspace: ws, uniqueId: `${ns}/${key}`, kind, files: written });
14489
+ }
14490
+ async function writeNewComponent(ws, uid, kind, name, description) {
14491
+ const [ns, key] = uid.split("/");
14492
+ const dir = join28(ws, "components", "@" + ns, key);
14493
+ const files = scaffold(uid, kind, name || title(key), description || "");
14494
+ mkdirSync12(dir, { recursive: true });
14495
+ const written = [];
14496
+ for (const [f, content] of Object.entries(files)) {
14497
+ const rp = `components/@${ns}/${key}/${f}`;
14498
+ writeFileSync14(join28(dir, f), await formatFile(rp, content.endsWith(`
14499
+ `) ? content : content + `
14500
+ `));
14501
+ written.push(rp);
14502
+ }
14503
+ const m = readManifest(ws);
14504
+ if (m && isComponentManifest(m)) {
14505
+ for (const inst of Object.values(m.instances))
14506
+ inst.components = Array.from(new Set([...inst.components || [], uid])).sort();
14507
+ await writeManifest(ws, m);
14508
+ }
14509
+ return written;
14510
+ }
14511
+ function registerNew(program, run) {
14512
+ const group = program.command("new").description("Scaffold local workspace files");
14513
+ const comp = group.command("component").argument("[ns/key]", "the component id, e.g. x_acme_crm/order-card; a bare key takes the workspace app's scope").description("Scaffold components/@<ns>/<key>/ (component.json, main.tsx, options.schema.json) in the workspace; rpforge check compiles it, rpforge push creates it").option("--kind <kind>", `${KINDS.join(", ")} (default widget)`).option("--name <name>", "the display name (default: from the key)").option("--description <text>", "the description");
14514
+ comp.action(run((ctx) => newComponent(ctx, comp.processedArgs[0], {
14515
+ ...comp.opts(),
14516
+ kind: comp.opts().kind || comp.optsWithGlobals().kind
14517
+ })));
14518
+ }
14519
+ var KINDS;
14520
+ var init_new = __esm(() => {
14521
+ init_component_id();
14522
+ init_layout();
14523
+ init_manifest();
14524
+ init_out();
14525
+ init_auth2();
14526
+ init_workspace();
14527
+ init_render();
14528
+ KINDS = ["widget", "primitive", "block", "layout", "utility"];
14529
+ });
14530
+
14531
+ // src/commands/init-component.ts
14532
+ import { existsSync as existsSync28, mkdirSync as mkdirSync13, readdirSync as readdirSync9, writeFileSync as writeFileSync15 } from "node:fs";
14533
+ import { join as join29, resolve as resolve9, dirname as dirname13 } from "node:path";
14534
+ import { spawnSync as spawnSync6 } from "node:child_process";
14535
+ import * as p4 from "@clack/prompts";
14536
+ function cmpVersion2(a, b) {
14537
+ const x = a.split(".").map((n) => parseInt(n, 10) || 0);
14538
+ const y = b.split(".").map((n) => parseInt(n, 10) || 0);
14539
+ for (let i = 0;i < Math.max(x.length, y.length); i++)
14540
+ if ((x[i] || 0) !== (y[i] || 0))
14541
+ return (x[i] || 0) - (y[i] || 0);
14542
+ return 0;
14543
+ }
14544
+ function componentIds(v, flag) {
14545
+ const out = [];
14546
+ for (const s of String(v || "").split(",")) {
14547
+ const id = s.trim().replace(/^@/, "");
14548
+ if (!id)
14549
+ continue;
14550
+ if (!COMPONENT_ID_RE.test(id))
14551
+ throw usage(`${flag} ${id}: give <namespace>/<key>`);
14552
+ if (!out.includes(id))
14553
+ out.push(id);
14554
+ }
14555
+ return out;
14556
+ }
14557
+ function defaultComponentFolder(scope) {
14558
+ const base = scope.replace(/^x_[a-z0-9]+_/, "").replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "app";
14559
+ return `${base}-components`;
14560
+ }
14561
+ async function step2(ctx, label, fn) {
14562
+ if (!ctx.interactive || ctx.out.o.json || ctx.out.o.quiet) {
14563
+ if (!ctx.out.o.quiet)
14564
+ ctx.out.info(label + "…");
14565
+ return fn();
14566
+ }
14567
+ const s = p4.spinner();
14568
+ s.start(label);
14569
+ try {
14570
+ const r = await fn();
14571
+ s.stop(label);
14572
+ return r;
14573
+ } catch (e) {
14574
+ s.stop(label + " (failed)");
14575
+ throw e;
14576
+ }
14577
+ }
14578
+ async function initComponent(ctx, o) {
14579
+ const human = !ctx.out.o.json;
14580
+ const k = ctx.out.c;
14581
+ let pullIds = componentIds(o.pull, "--pull");
14582
+ const newIds = componentIds(o.new, "--new");
14583
+ if (newIds.length > 1)
14584
+ throw usage("--new takes one component id (add more later with rpforge new component)");
14585
+ if (o.kind && !KINDS.includes(o.kind))
14586
+ throw usage(`--kind ${o.kind}: one of ${KINDS.join(", ")}`);
14587
+ if (o.updateSet && o.newUpdateSet)
14588
+ throw usage("--update-set and --new-update-set: give one");
14589
+ if (!ctx.interactive && !o.app)
14590
+ throw usage("missing: --app (the application the components belong to)");
14591
+ if (!ctx.interactive && !o.updateSet && !o.newUpdateSet)
14592
+ throw usage("missing: --update-set <name> or --new-update-set [name]");
14593
+ if (ctx.interactive)
14594
+ p4.intro(k.bold("React Portal") + k.dim(" rpforge init --component"));
14595
+ let profileName;
14596
+ if (ctx.interactive && !ctx.opts.profile && !ctx.opts.instance && !process.env.RPFORGE_PROFILE) {
14597
+ const pf = readProfiles();
14598
+ const names = Object.keys(pf.profiles);
14599
+ if (names.length > 1)
14600
+ profileName = answered(await p4.select({
14601
+ message: "Which instance profile?",
14602
+ options: names.map((n) => ({ value: n, label: n, hint: pf.profiles[n].instance })),
14603
+ initialValue: pf.default || names[0]
14604
+ }));
14605
+ }
14606
+ const r = resolveFor({ ...ctx, opts: { ...ctx.opts, kind: undefined } }, profileName);
14607
+ const client = new ForgeClient(r.config);
14608
+ const instance = r.config.instance;
14609
+ const status = await step2(ctx, `Checking ${instance}`, () => client.get("/status"));
14610
+ if (!status.enabled)
14611
+ throw new CliError(EXIT.incompatible, "forge_mcp_disabled", `Forge is disabled on ${instance}`);
14612
+ if (!status.capabilities || !status.capabilities.author)
14613
+ throw new CliError(EXIT.failed, "forbidden", `${status.user} has no React Portal author access on ${instance}`);
14614
+ const compat = checkForgeApi(status);
14615
+ if (compat.state === "too-old")
14616
+ throw new CliError(EXIT.incompatible, "incompatible", compat.message);
14617
+ if (!Array.isArray(status.features) || !status.features.includes(COMPONENT_FEATURE))
14618
+ throw new CliError(EXIT.incompatible, "incompatible", `${instance}'s React Portal (${status.reactPortal || "unknown"}) has no component workspaces yet: update React Portal there`);
14619
+ const helpers = String(status.globalHelpers || "");
14620
+ if (!helpers || cmpVersion2(helpers, HELPERS_SWITCH2) < 0)
14621
+ throw new CliError(EXIT.incompatible, "helper_missing", `Component pushes need React Portal Global Helpers ${HELPERS_SWITCH2}+ on ${instance} (found ${helpers || "none"})`);
14622
+ const apps = ((await step2(ctx, "Reading your applications", () => client.get("/apps", { list: "authoring" }))).apps || []).filter((x) => !x.reactPortal);
14623
+ if (!apps.length)
14624
+ throw new CliError(EXIT.failed, "no_apps", `${status.user} can't author in any scoped application on ${instance}`);
14625
+ let appRef = o.app || "";
14626
+ if (!appRef)
14627
+ appRef = answered(await p4.autocomplete({
14628
+ message: "Which application do the components belong to?",
14629
+ options: apps.map((x) => ({
14630
+ value: x.scope,
14631
+ label: `${x.name} (${x.scope})`,
14632
+ hint: x.current ? "current" : x.version
14633
+ })),
14634
+ initialValue: (apps.find((x) => x.current) || {}).scope,
14635
+ maxItems: 12
14636
+ }));
14637
+ const app = apps.find((x) => x.scope === appRef || x.id === appRef);
14638
+ if (!app)
14639
+ throw usage(`--app ${appRef}: not an application you can author in on ${instance} (React Portal itself can't hold a component workspace): ${apps.map((x) => x.scope).join(", ")}`);
14640
+ const sets = (await step2(ctx, `Reading ${app.scope}'s update sets`, () => client.get("/update-sets", { app: app.id }))).sets || [];
14641
+ let setRef = "";
14642
+ let newSetName = typeof o.newUpdateSet === "string" ? o.newUpdateSet : o.newUpdateSet ? `${app.name} components (rpf)` : "";
14643
+ if (o.updateSet) {
14644
+ const hit = sets.filter((s) => s.name === o.updateSet || s.id === o.updateSet);
14645
+ if (hit.length !== 1)
14646
+ throw usage(`--update-set ${o.updateSet}: not one in-progress set of ${app.scope} (${sets.map((s) => s.name).join(", ") || "none"})`);
14647
+ setRef = hit[0].id;
14648
+ } else if (!newSetName) {
14649
+ const canCreate = cmpVersion2(helpers, HELPERS_UPDATE_SETS2) >= 0;
14650
+ const options = sets.map((s) => ({
14651
+ value: s.id,
14652
+ label: s.name,
14653
+ hint: [s.isDefault ? "default" : "", s.remembered ? "yours" : ""].filter(Boolean).join(", ")
14654
+ }));
14655
+ if (canCreate)
14656
+ options.push({ value: "__new__", label: "Create a new update set", hint: "" });
14657
+ if (!options.length)
14658
+ throw new CliError(EXIT.failed, "no_update_set", `${app.scope} has no in-progress update set (create one first)`);
14659
+ const v = answered(await p4.select({ message: "Which update set captures the components?", options }));
14660
+ if (v === "__new__")
14661
+ newSetName = answered(await p4.text({
14662
+ message: "Update set name",
14663
+ initialValue: `${app.name} components (rpf)`,
14664
+ validate: (x) => String(x || "").trim() ? undefined : "Required"
14665
+ })).trim();
14666
+ else
14667
+ setRef = v;
14668
+ }
14669
+ if (newSetName && cmpVersion2(helpers, HELPERS_UPDATE_SETS2) < 0)
14670
+ throw new CliError(EXIT.incompatible, "helper_missing", `Creating an update set needs Global Helpers ${HELPERS_UPDATE_SETS2}+ (found ${helpers})`);
14671
+ if (ctx.interactive && !pullIds.length && !newIds.length) {
14672
+ const start = answered(await p4.select({
14673
+ message: "Start with",
14674
+ options: [
14675
+ { value: "pull", label: "Existing components of " + app.scope },
14676
+ { value: "new", label: "A new component" },
14677
+ { value: "none", label: "Nothing yet (rpforge new component / rpforge pull --component later)" }
14678
+ ]
14679
+ }));
14680
+ if (start === "pull") {
14681
+ let existing = [];
14682
+ try {
14683
+ existing = await client.tableRead("x_312987_portal_component", `sys_scope=${app.id}^active=true^ORDERBYunique_id`, ["unique_id", "name", "kind"], 500);
14684
+ } catch {
14685
+ existing = [];
14686
+ }
14687
+ if (existing.length)
14688
+ pullIds = answered(await p4.multiselect({
14689
+ message: "Which components?",
14690
+ options: existing.map((c) => ({
14691
+ value: String(c.unique_id),
14692
+ label: `${c.name} (${c.unique_id})`,
14693
+ hint: c.kind
14694
+ })),
14695
+ required: true
14696
+ }));
14697
+ else
14698
+ pullIds = componentIds(answered(await p4.text({
14699
+ message: "Component ids (comma-separated <namespace>/<key>)",
14700
+ validate: (x) => String(x || "").trim() ? undefined : "Required"
14701
+ })), "components");
14702
+ } else if (start === "new") {
14703
+ const id = answered(await p4.text({
14704
+ message: "New component id (<namespace>/<key>)",
14705
+ placeholder: `${app.scope}/my-widget`,
14706
+ validate: (x) => COMPONENT_ID_RE.test(String(x || "").trim()) ? undefined : "<namespace>/<key>"
14707
+ })).trim();
14708
+ newIds.push(id);
14709
+ if (!o.kind)
14710
+ o.kind = answered(await p4.select({
14711
+ message: "Kind",
14712
+ options: KINDS.map((x) => ({ value: x, label: x })),
14713
+ initialValue: "widget"
14714
+ }));
14715
+ }
14716
+ }
14717
+ let folder = o.out ? resolve9(o.out) : "";
14718
+ if (!folder) {
14719
+ const base = ctx.opts.dir ? resolve9(ctx.opts.dir) : existsSync28(join29(process.cwd(), "apps")) ? join29(process.cwd(), "apps") : process.cwd();
14720
+ let name = o.name || defaultComponentFolder(app.scope);
14721
+ if (ctx.interactive && !o.name)
14722
+ name = answered(await p4.text({
14723
+ message: "Folder",
14724
+ initialValue: name,
14725
+ validate: (x) => /^[a-z][a-z0-9-]*$/.test(String(x || "")) ? undefined : "lowercase letters, digits and -"
14726
+ }));
14727
+ folder = join29(base, name);
14728
+ }
14729
+ if (existsSync28(folder) && readdirSync9(folder).length)
14730
+ throw usage(`${rel(folder)} is not empty: pick a new folder (--out)`);
14731
+ const plan = [];
14732
+ if (newSetName)
14733
+ plan.push(`create the update set "${newSetName}" in ${app.scope}`);
14734
+ plan.push(`a component workspace for ${app.scope} in ${rel(folder) || folder}`);
14735
+ if (pullIds.length)
14736
+ plan.push(`pull ${pullIds.join(", ")}`);
14737
+ if (newIds.length)
14738
+ plan.push(`scaffold ${newIds[0]} (${o.kind || "widget"}), created on the instance by rpforge push`);
14739
+ if (ctx.opts.dryRun) {
14740
+ let setPlan = null;
14741
+ if (newSetName)
14742
+ setPlan = await client.post("/write/create_update_set", { app: app.id, name: newSetName, dryRun: true });
14743
+ if (human)
14744
+ for (const l of plan)
14745
+ ctx.out.line(" " + l);
14746
+ ctx.out.result("init", {
14747
+ kind: "component",
14748
+ dryRun: true,
14749
+ instance,
14750
+ app,
14751
+ plan,
14752
+ updateSetPlan: setPlan ? setPlan.plan || setPlan : undefined
14753
+ });
14754
+ return;
14755
+ }
14756
+ if (newSetName) {
14757
+ const made = await step2(ctx, `Creating the update set "${newSetName}"`, () => client.post("/write/create_update_set", { app: app.id, name: newSetName, dryRun: false }));
14758
+ const created = made.result && made.result.updateSet;
14759
+ if (!created || !created.id)
14760
+ throw new CliError(EXIT.failed, "update_set_failed", "The update set was not created");
14761
+ setRef = created.id;
14762
+ }
14763
+ mkdirSync13(folder, { recursive: true });
14764
+ configureWorkspace({
14765
+ repo: "",
14766
+ apps: dirname13(folder),
14767
+ prettierConfigFrom: o.prettierrc === false ? prettierConfigFor(folder) : "",
14768
+ tsc: "",
14769
+ hostTypes: "",
14770
+ typesFrom: ""
14771
+ });
14772
+ const pulled = await step2(ctx, `Pulling into ${rel(folder) || folder}`, () => pull(client, { app: app.id, components: pullIds, out: folder, updateSet: setRef, mode: "fresh" }));
14773
+ const files = [];
14774
+ if (newIds.length) {
14775
+ const made = await writeNewComponent(folder, newIds[0], o.kind || "widget");
14776
+ files.push(...made);
14777
+ }
14778
+ if (o.prettierrc !== false) {
14779
+ writeFileSync15(join29(folder, ".prettierrc.json"), prettierrcText());
14780
+ files.push(".prettierrc.json");
14781
+ }
14782
+ if (o.gitignore !== false) {
14783
+ writeFileSync15(join29(folder, ".gitignore"), `.forge/
14784
+ node_modules/
14785
+ `);
14786
+ files.push(".gitignore");
14787
+ }
14788
+ if (o.readme !== false) {
14789
+ writeFileSync15(join29(folder, "README.md"), `# ${app.name} components
14790
+
14791
+ A React Portal component workspace (application ${app.scope}) on ${instance}. Pushes write into the update set recorded in forge.workspace.json.
14792
+
14793
+ ` + `\`\`\`bash
14794
+ rpforge dev # the component stage: options, params, theme, light / dark, widths
14795
+ rpforge new component # another component
14796
+ rpforge pull --component # bring existing components of the app in
14797
+ rpforge status # what changed, here and on the instance
14798
+ rpforge check # format, lint, compile, the push dry run
14799
+ rpforge push # dry run, then the confirmed push
14800
+ \`\`\`
14801
+ `);
14802
+ files.push("README.md");
14803
+ }
14804
+ if (o.git !== false) {
14805
+ const g = spawnSync6("git", ["init", "-q"], { cwd: folder, encoding: "utf8" });
14806
+ if (g.status === 0)
14807
+ files.push(".git/");
14808
+ else
14809
+ ctx.out.info(k.yellow("warn ") + "git init failed: " + String(g.stderr || g.error || "").trim());
14810
+ }
14811
+ if (o.skills !== false) {
14812
+ try {
14813
+ const sk = syncSkills(join29(nearestProject(folder), ".claude", "skills"), { mode: "install" });
14814
+ files.push(`${rel(sk.root)} (${sk.skills.map((s) => s.name).join(", ")})`);
14815
+ } catch (e) {
14816
+ ctx.out.info(k.yellow("warn ") + "skills install failed: " + (e.message || e));
14817
+ }
14818
+ }
14819
+ const next = [`cd ${rel(folder) || folder}`, "rpforge dev", "rpforge check", "rpforge push"];
14820
+ if (human) {
14821
+ ctx.out.line("");
14822
+ ctx.out.line(k.green(`Component workspace for ${app.scope} ready`) + k.dim(` (update set ${pulled.updateSet ? `"${pulled.updateSet.name}"` : setRef})`));
14823
+ ctx.out.line(` folder: ${rel(folder) || folder}`);
14824
+ renderPull(ctx.out, pulled);
14825
+ for (const f of files)
14826
+ ctx.out.line(k.dim(` wrote ${f}`));
14827
+ ctx.out.line(` next: ${next.join(" · ")}`);
14828
+ }
14829
+ ctx.out.result("init", {
14830
+ kind: "component",
14831
+ dryRun: false,
14832
+ instance,
14833
+ app,
14834
+ folder,
14835
+ updateSet: pulled.updateSet,
14836
+ pull: pulled,
14837
+ files,
14838
+ next
14839
+ });
14840
+ if (ctx.interactive)
14841
+ p4.outro("Done.");
14842
+ }
14843
+ var COMPONENT_FEATURE = "component-workspaces", HELPERS_SWITCH2 = "1.3.0", HELPERS_UPDATE_SETS2 = "1.7.0";
14844
+ var init_init_component = __esm(() => {
14845
+ init_client();
14846
+ init_compat();
14847
+ init_component_id();
14848
+ init_init();
14849
+ init_layout();
14850
+ init_pull();
14851
+ init_profiles();
14852
+ init_out();
14853
+ init_context();
14854
+ init_auth2();
14855
+ init_workspace();
14856
+ init_skills();
14857
+ init_new();
14858
+ init_render();
14859
+ });
14860
+
14861
+ // src/commands/init.ts
14862
+ import { existsSync as existsSync29, mkdirSync as mkdirSync14, readFileSync as readFileSync29, readdirSync as readdirSync10, writeFileSync as writeFileSync16 } from "node:fs";
14863
+ import { dirname as dirname14, isAbsolute as isAbsolute4, join as join30, resolve as resolve10 } from "node:path";
14864
+ import { randomUUID } from "node:crypto";
14865
+ import { spawnSync as spawnSync7 } from "node:child_process";
14866
+ import * as p5 from "@clack/prompts";
14867
+ function list4(v) {
14868
+ if (v === undefined)
13525
14869
  return;
13526
14870
  return v.split(",").map((x) => x.trim()).filter(Boolean);
13527
14871
  }
13528
- function cmpVersion2(a, b) {
14872
+ function cmpVersion3(a, b) {
13529
14873
  const pa = String(a || "").split(".").map((x) => parseInt(x, 10) || 0);
13530
14874
  const pb = String(b || "").split(".").map((x) => parseInt(x, 10) || 0);
13531
14875
  for (let i = 0;i < 3; i++)
@@ -13680,12 +15024,12 @@ function flagAnswers(o, given) {
13680
15024
  a.extras = extras;
13681
15025
  return a;
13682
15026
  }
13683
- async function step2(ctx, label, fn) {
15027
+ async function step3(ctx, label, fn) {
13684
15028
  if (!ctx.interactive) {
13685
15029
  ctx.out.info(label + "…");
13686
15030
  return fn();
13687
15031
  }
13688
- const s = p3.spinner();
15032
+ const s = p5.spinner();
13689
15033
  s.start(label);
13690
15034
  try {
13691
15035
  const v = await fn();
@@ -13723,14 +15067,14 @@ async function swatch(ctx, tokens) {
13723
15067
  return out.join("");
13724
15068
  }
13725
15069
  function isEmptyDir(dir) {
13726
- return !existsSync25(dir) || readdirSync8(dir).length === 0;
15070
+ return !existsSync29(dir) || readdirSync10(dir).length === 0;
13727
15071
  }
13728
15072
  function insideGitRepo(dir) {
13729
- let d = resolve9(dir);
15073
+ let d = resolve10(dir);
13730
15074
  for (;; ) {
13731
- if (existsSync25(join26(d, ".git")))
15075
+ if (existsSync29(join30(d, ".git")))
13732
15076
  return true;
13733
- const up = dirname13(d);
15077
+ const up = dirname14(d);
13734
15078
  if (up === d)
13735
15079
  return false;
13736
15080
  d = up;
@@ -13738,16 +15082,16 @@ function insideGitRepo(dir) {
13738
15082
  }
13739
15083
  function defaultFolder(ctx, r, slug) {
13740
15084
  if (ctx.opts.dir)
13741
- return { dir: join26(resolve9(ctx.opts.dir), slug), why: "--dir" };
15085
+ return { dir: join30(resolve10(ctx.opts.dir), slug), why: "--dir" };
13742
15086
  const pf = readProfiles();
13743
15087
  const own = r.profile && pf.profiles[r.profile] ? pf.profiles[r.profile].dir : "";
13744
15088
  if (own)
13745
- return { dir: join26(resolve9(own), slug), why: `profile ${r.profile}` };
15089
+ return { dir: join30(resolve10(own), slug), why: `profile ${r.profile}` };
13746
15090
  if (pf.defaults.dir)
13747
- return { dir: join26(resolve9(pf.defaults.dir), slug), why: "the saved default folder" };
13748
- if (existsSync25(join26(process.cwd(), "apps")))
13749
- return { dir: join26(process.cwd(), "apps", slug), why: "./apps" };
13750
- return { dir: join26(process.cwd(), slug), why: "the current folder" };
15091
+ return { dir: join30(resolve10(pf.defaults.dir), slug), why: "the saved default folder" };
15092
+ if (existsSync29(join30(process.cwd(), "apps")))
15093
+ return { dir: join30(process.cwd(), "apps", slug), why: "./apps" };
15094
+ return { dir: join30(process.cwd(), slug), why: "the current folder" };
13751
15095
  }
13752
15096
  function groupCounts(creates) {
13753
15097
  const counts = {};
@@ -13770,7 +15114,7 @@ async function init(ctx, o, cmd) {
13770
15114
  if (o.answers) {
13771
15115
  let raw;
13772
15116
  try {
13773
- raw = JSON.parse(readFileSync27(resolve9(o.answers), "utf8"));
15117
+ raw = JSON.parse(readFileSync29(resolve10(o.answers), "utf8"));
13774
15118
  } catch (e) {
13775
15119
  throw usage(`--answers ${o.answers}: ${e.message}`);
13776
15120
  }
@@ -13789,13 +15133,13 @@ async function init(ctx, o, cmd) {
13789
15133
  throw usage(`missing: ${missing.join(", ")}; see rpforge init --help`, { missing });
13790
15134
  }
13791
15135
  if (ctx.interactive)
13792
- p3.intro(k.bold("React Portal") + k.dim(" rpforge init"));
15136
+ p5.intro(k.bold("React Portal") + k.dim(" rpforge init"));
13793
15137
  let profileName;
13794
15138
  if (ctx.interactive && !ctx.opts.profile && !ctx.opts.instance && !process.env.RPFORGE_PROFILE) {
13795
15139
  const pf = readProfiles();
13796
15140
  const names = Object.keys(pf.profiles);
13797
15141
  if (names.length > 1)
13798
- profileName = answered(await p3.select({
15142
+ profileName = answered(await p5.select({
13799
15143
  message: "Which instance profile?",
13800
15144
  options: names.map((n) => ({ value: n, label: n, hint: pf.profiles[n].instance })),
13801
15145
  initialValue: pf.default || names[0]
@@ -13804,7 +15148,7 @@ async function init(ctx, o, cmd) {
13804
15148
  const r = resolveFor(ctx, profileName);
13805
15149
  const client = new ForgeClient(r.config);
13806
15150
  const instance = r.config.instance;
13807
- const status = await step2(ctx, `Checking ${instance}`, () => client.get("/status"));
15151
+ const status = await step3(ctx, `Checking ${instance}`, () => client.get("/status"));
13808
15152
  if (!status.enabled)
13809
15153
  throw new CliError(EXIT.incompatible, "forge_mcp_disabled", `Forge is disabled on ${instance} (${status.property || "x_312987_portal.forge.mcp.enabled"} is not true)`);
13810
15154
  if (!status.capabilities || !status.capabilities.design)
@@ -13815,16 +15159,16 @@ async function init(ctx, o, cmd) {
13815
15159
  if (compat.state === "too-new")
13816
15160
  ctx.out.info(k.yellow("warn ") + compat.message);
13817
15161
  const helpers = String(status.globalHelpers || "");
13818
- if (!helpers || cmpVersion2(helpers, HELPERS_SWITCH2) < 0)
13819
- throw new CliError(EXIT.incompatible, "helper_missing", `init needs React Portal Global Helpers ${HELPERS_SWITCH2}+ on ${instance} (found ${helpers || "none"})`);
13820
- const canCreateSets = cmpVersion2(helpers, HELPERS_UPDATE_SETS2) >= 0;
15162
+ if (!helpers || cmpVersion3(helpers, HELPERS_SWITCH3) < 0)
15163
+ throw new CliError(EXIT.incompatible, "helper_missing", `init needs React Portal Global Helpers ${HELPERS_SWITCH3}+ on ${instance} (found ${helpers || "none"})`);
15164
+ const canCreateSets = cmpVersion3(helpers, HELPERS_UPDATE_SETS3) >= 0;
13821
15165
  const lists = { apps: [], sets: [], portals: [] };
13822
- lists.apps = (await step2(ctx, "Reading your applications", () => client.get("/apps", { list: "authoring" }))).apps;
15166
+ lists.apps = (await step3(ctx, "Reading your applications", () => client.get("/apps", { list: "authoring" }))).apps;
13823
15167
  if (!lists.apps.length)
13824
15168
  throw new CliError(EXIT.failed, "no_apps", `${status.user} can't author in any scoped application on ${instance}`);
13825
15169
  if (!a.app) {
13826
15170
  const current = lists.apps.find((x) => x.current && !x.reactPortal);
13827
- a.app = answered(await p3.autocomplete({
15171
+ a.app = answered(await p5.autocomplete({
13828
15172
  message: "Which application owns the portal?",
13829
15173
  options: lists.apps.map((x) => ({
13830
15174
  value: x.scope,
@@ -13841,7 +15185,7 @@ async function init(ctx, o, cmd) {
13841
15185
  a.app = app.scope;
13842
15186
  if (app.reactPortal)
13843
15187
  ctx.out.info(k.yellow("note ") + "React Portal itself owns the portal: its records belong to React Portal (reconcile your edits after upgrades)");
13844
- lists.sets = (await step2(ctx, `Reading ${app.scope}'s update sets`, () => client.get("/update-sets", { app: app.id }))).sets;
15188
+ lists.sets = (await step3(ctx, `Reading ${app.scope}'s update sets`, () => client.get("/update-sets", { app: app.id }))).sets;
13845
15189
  let pendingNewSet = false;
13846
15190
  if (!a.updateSet) {
13847
15191
  const pick = lists.sets.find((s) => s.remembered) || lists.sets.find((s) => s.isDefault) || lists.sets[0];
@@ -13854,7 +15198,7 @@ async function init(ctx, o, cmd) {
13854
15198
  options.push({ value: "__new__", label: "Create a new update set", hint: "" });
13855
15199
  if (!options.length)
13856
15200
  throw new CliError(EXIT.failed, "no_update_set", `${app.scope} has no in-progress update set (create one first)`);
13857
- const v = answered(await p3.select({
15201
+ const v = answered(await p5.select({
13858
15202
  message: "Which update set captures the portal?",
13859
15203
  options,
13860
15204
  initialValue: pick ? pick.id : undefined
@@ -13866,10 +15210,10 @@ async function init(ctx, o, cmd) {
13866
15210
  }
13867
15211
  if (typeof a.updateSet === "object" && a.updateSet) {
13868
15212
  if (!canCreateSets)
13869
- throw new CliError(EXIT.incompatible, "helper_missing", `Creating an update set needs React Portal Global Helpers ${HELPERS_UPDATE_SETS2}+ on ${instance} (found ${helpers})`);
15213
+ throw new CliError(EXIT.incompatible, "helper_missing", `Creating an update set needs React Portal Global Helpers ${HELPERS_UPDATE_SETS3}+ on ${instance} (found ${helpers})`);
13870
15214
  }
13871
15215
  if (!a.name)
13872
- a.name = answered(await p3.text({
15216
+ a.name = answered(await p5.text({
13873
15217
  message: "Portal name",
13874
15218
  placeholder: "HR Portal",
13875
15219
  validate: (v) => String(v || "").trim() && String(v).length <= 100 ? undefined : "1-100 characters"
@@ -13877,7 +15221,7 @@ async function init(ctx, o, cmd) {
13877
15221
  let slug = a.slug || slugFromName(a.name);
13878
15222
  for (;; ) {
13879
15223
  if (ctx.interactive && !a.slug)
13880
- slug = answered(await p3.text({
15224
+ slug = answered(await p5.text({
13881
15225
  message: "Slug (the URL: /x/312987/portal/site/<slug>)",
13882
15226
  initialValue: slug,
13883
15227
  validate: (v) => SLUG.test(String(v || "")) ? undefined : "2-40: lowercase letters, digits, dashes"
@@ -13888,15 +15232,15 @@ async function init(ctx, o, cmd) {
13888
15232
  const why = check.takenBy ? `taken by ${check.takenBy.name}${check.takenBy.active ? "" : " (draft)"}` : check.reason || "not available";
13889
15233
  if (!ctx.interactive || a.slug)
13890
15234
  throw new CliError(EXIT.failed, "slug_taken", `Slug "${slug}" is ${why}${check.suggestion ? `: try --slug ${check.suggestion}` : ""}`, check);
13891
- p3.log.warn(`"${slug}" is ${why}`);
15235
+ p5.log.warn(`"${slug}" is ${why}`);
13892
15236
  slug = check.suggestion || slug;
13893
15237
  }
13894
15238
  a.slug = slug;
13895
15239
  if (a.description === undefined && ctx.interactive)
13896
- a.description = answered(await p3.text({ message: "Description (optional)", defaultValue: "" })).trim();
15240
+ a.description = answered(await p5.text({ message: "Description (optional)", defaultValue: "" })).trim();
13897
15241
  if (pendingNewSet)
13898
15242
  a.updateSet = {
13899
- create: answered(await p3.text({
15243
+ create: answered(await p5.text({
13900
15244
  message: "New update set name",
13901
15245
  initialValue: defaultUpdateSetName(a.name),
13902
15246
  validate: (v) => String(v || "").trim() && String(v).length <= 80 ? undefined : "1-80 characters"
@@ -13919,11 +15263,11 @@ async function init(ctx, o, cmd) {
13919
15263
  if (lists.sets.some((s) => s.name === setName))
13920
15264
  throw usage(`${app.scope} already has an in-progress update set "${setName}": pick it with --update-set`);
13921
15265
  }
13922
- lists.portals = await step2(ctx, "Reading portals", () => client.get("/portals"));
15266
+ lists.portals = await step3(ctx, "Reading portals", () => client.get("/portals"));
13923
15267
  const templates = lists.portals.filter((x) => x.isTemplate).sort((x, y) => x.isDefaultTemplate ? -1 : y.isDefaultTemplate ? 1 : String(x.name).localeCompare(y.name));
13924
15268
  const src = a.source = a.source || {};
13925
15269
  if (!src.kind && ctx.interactive)
13926
- src.kind = answered(await p3.select({
15270
+ src.kind = answered(await p5.select({
13927
15271
  message: "Start from",
13928
15272
  options: [
13929
15273
  { value: "template", label: "A template", hint: "everything, pages included" },
@@ -13934,7 +15278,7 @@ async function init(ctx, o, cmd) {
13934
15278
  }));
13935
15279
  src.kind = src.kind || "template";
13936
15280
  if (src.kind === "template" && !src.portal && ctx.interactive && templates.length > 1)
13937
- src.portal = answered(await p3.select({
15281
+ src.portal = answered(await p5.select({
13938
15282
  message: "Which template?",
13939
15283
  options: templates.map((t) => ({
13940
15284
  value: t.slug,
@@ -13944,7 +15288,7 @@ async function init(ctx, o, cmd) {
13944
15288
  initialValue: templates[0].slug
13945
15289
  }));
13946
15290
  if (src.kind === "portal" && !src.portal)
13947
- src.portal = answered(await p3.autocomplete({
15291
+ src.portal = answered(await p5.autocomplete({
13948
15292
  message: "Copy which portal?",
13949
15293
  options: lists.portals.map((x) => ({
13950
15294
  value: x.slug,
@@ -13962,15 +15306,15 @@ async function init(ctx, o, cmd) {
13962
15306
  if (src.kind === "template" && !source.isTemplate)
13963
15307
  throw usage(`${source.slug} is not a template (use --from portal)`);
13964
15308
  }
13965
- const design = source ? await step2(ctx, `Reading ${source.slug}`, () => client.get("/portal", { ref: source.id })) : null;
15309
+ const design = source ? await step3(ctx, `Reading ${source.slug}`, () => client.get("/portal", { ref: source.id })) : null;
13966
15310
  const sourcePages = design ? (design.pages || []).filter((pg) => pg.active) : [];
13967
15311
  if (src.kind === "portal" && src.pages === undefined && ctx.interactive && sourcePages.length) {
13968
- const withPages = answered(await p3.confirm({
15312
+ const withPages = answered(await p5.confirm({
13969
15313
  message: `Copy ${source.slug}'s pages too? (${sourcePages.length})`,
13970
15314
  initialValue: false
13971
15315
  }));
13972
15316
  if (withPages)
13973
- src.pages = answered(await p3.multiselect({
15317
+ src.pages = answered(await p5.multiselect({
13974
15318
  message: "Which pages?",
13975
15319
  options: sourcePages.map((pg) => ({
13976
15320
  value: pg.route,
@@ -13982,7 +15326,7 @@ async function init(ctx, o, cmd) {
13982
15326
  }));
13983
15327
  }
13984
15328
  if (src.kind !== "empty" && ctx.interactive && src.variants === undefined && src.viewRules === undefined && src.criteria === undefined) {
13985
- const keep = answered(await p3.multiselect({
15329
+ const keep = answered(await p5.multiselect({
13986
15330
  message: "Also copy",
13987
15331
  options: [
13988
15332
  { value: "variants", label: "Page variants" },
@@ -13999,7 +15343,7 @@ async function init(ctx, o, cmd) {
13999
15343
  const layouts = await client.get("/components", { kind: "layout" });
14000
15344
  const sourceLayout = source ? layouts.find((l) => l.id === source.defaultLayout) : null;
14001
15345
  if (!a.layout && ctx.interactive && layouts.length > 1) {
14002
- const v = answered(await p3.select({
15346
+ const v = answered(await p5.select({
14003
15347
  message: "Layout",
14004
15348
  options: layouts.map((l) => ({
14005
15349
  value: l.uniqueId,
@@ -14014,7 +15358,7 @@ async function init(ctx, o, cmd) {
14014
15358
  if (a.layout && !layouts.some((l) => l.uniqueId === a.layout || l.id === a.layout))
14015
15359
  throw usage(`--layout ${a.layout}: no such layout (${layouts.map((l) => l.uniqueId).join(", ")})`);
14016
15360
  if (ctx.interactive && !a.layoutOptions && !a.contentWidth) {
14017
- const adjust = answered(await p3.confirm({
15361
+ const adjust = answered(await p5.confirm({
14018
15362
  message: "Adjust the layout options (frame, texture, padding, sub-header, width)?",
14019
15363
  initialValue: false
14020
15364
  }));
@@ -14028,7 +15372,7 @@ async function init(ctx, o, cmd) {
14028
15372
  const spec = props[key];
14029
15373
  if (!spec || !Array.isArray(spec.enum))
14030
15374
  continue;
14031
- const v = answered(await p3.select({
15375
+ const v = answered(await p5.select({
14032
15376
  message: spec.title || key,
14033
15377
  options: spec.enum.map((x) => ({ value: x, label: x })),
14034
15378
  initialValue: current[key] || (info.defaultOptions || {})[key] || spec.enum[0]
@@ -14038,7 +15382,7 @@ async function init(ctx, o, cmd) {
14038
15382
  }
14039
15383
  if (Object.keys(lo).length)
14040
15384
  a.layoutOptions = lo;
14041
- const width = answered(await p3.select({
15385
+ const width = answered(await p5.select({
14042
15386
  message: "Default content width",
14043
15387
  options: [{ value: "", label: "keep the source's" }].concat(CONTENT_WIDTHS.map((w) => ({ value: w, label: w }))),
14044
15388
  initialValue: ""
@@ -14050,7 +15394,7 @@ async function init(ctx, o, cmd) {
14050
15394
  const th = a.theme = a.theme || {};
14051
15395
  let themes = [];
14052
15396
  if (!th.key && !th.color && ctx.interactive) {
14053
- const how = answered(await p3.select({
15397
+ const how = answered(await p5.select({
14054
15398
  message: "Theme",
14055
15399
  options: [
14056
15400
  {
@@ -14075,15 +15419,15 @@ async function init(ctx, o, cmd) {
14075
15419
  label: `${await swatch(ctx, t.tokens)} ${t.name}`.trim(),
14076
15420
  hint: [t.key, t.presetGroup || t.source].filter(Boolean).join(", ")
14077
15421
  });
14078
- th.key = answered(await p3.autocomplete({ message: "Which theme?", options: opts, maxItems: 12 }));
15422
+ th.key = answered(await p5.autocomplete({ message: "Which theme?", options: opts, maxItems: 12 }));
14079
15423
  }
14080
15424
  if (how === "color") {
14081
- th.color = answered(await p3.text({
15425
+ th.color = answered(await p5.text({
14082
15426
  message: "Brand color (hex, rgb(), hsl() or oklch())",
14083
15427
  placeholder: "#2563eb",
14084
15428
  validate: (v) => String(v || "").trim() ? undefined : "Required"
14085
15429
  })).trim();
14086
- th.tint = answered(await p3.select({
15430
+ th.tint = answered(await p5.select({
14087
15431
  message: "Neutrals",
14088
15432
  options: [
14089
15433
  { value: "neutral", label: "Neutral grays" },
@@ -14091,7 +15435,7 @@ async function init(ctx, o, cmd) {
14091
15435
  ],
14092
15436
  initialValue: "neutral"
14093
15437
  }));
14094
- th.contrast = answered(await p3.select({
15438
+ th.contrast = answered(await p5.select({
14095
15439
  message: "Contrast target",
14096
15440
  options: [
14097
15441
  { value: "AA", label: "AA (4.5:1 text)" },
@@ -14101,7 +15445,7 @@ async function init(ctx, o, cmd) {
14101
15445
  }));
14102
15446
  }
14103
15447
  if ((how === "keep" || how === "pick") && th.copy === undefined)
14104
- th.copy = answered(await p3.confirm({ message: "Make an editable copy of the theme for this portal?", initialValue: false }));
15448
+ th.copy = answered(await p5.confirm({ message: "Make an editable copy of the theme for this portal?", initialValue: false }));
14105
15449
  if (!th.copy)
14106
15450
  delete th.copy;
14107
15451
  }
@@ -14138,12 +15482,12 @@ async function init(ctx, o, cmd) {
14138
15482
  if (src.kind !== "empty" && ctx.interactive) {
14139
15483
  if (!br.icon) {
14140
15484
  const current = source && source.brand && source.brand.icon || "box";
14141
- br.icon = answered(await p3.text({ message: "Sidebar brand icon (a Lucide name)", initialValue: current })).trim();
15485
+ br.icon = answered(await p5.text({ message: "Sidebar brand icon (a Lucide name)", initialValue: current })).trim();
14142
15486
  if (br.icon === current)
14143
15487
  delete br.icon;
14144
15488
  }
14145
15489
  if (br.logo === undefined) {
14146
- const v = answered(await p3.text({
15490
+ const v = answered(await p5.text({
14147
15491
  message: "Logo URL (https:// or /, empty for none)",
14148
15492
  defaultValue: "",
14149
15493
  validate: (v) => !v || /^(https:\/\/|\/)/.test(String(v)) ? undefined : "https:// or /"
@@ -14152,7 +15496,7 @@ async function init(ctx, o, cmd) {
14152
15496
  br.logo = v;
14153
15497
  }
14154
15498
  if (br.footer === undefined) {
14155
- const v = answered(await p3.text({ message: "Footer text", initialValue: `© ${a.name}` })).trim();
15499
+ const v = answered(await p5.text({ message: "Footer text", initialValue: `© ${a.name}` })).trim();
14156
15500
  br.footer = v;
14157
15501
  }
14158
15502
  }
@@ -14168,7 +15512,7 @@ async function init(ctx, o, cmd) {
14168
15512
  const pages = src.pages === "none" ? [] : Array.isArray(src.pages) ? sourcePages.filter((pg) => src.pages.includes(pg.route)) : src.kind === "template" ? sourcePages : [];
14169
15513
  if (!nav.home && pages.length > 1) {
14170
15514
  const home = sourcePages.find((pg) => pg.id === design.portal.homePage);
14171
- const v = answered(await p3.select({
15515
+ const v = answered(await p5.select({
14172
15516
  message: "Home page",
14173
15517
  options: pages.map((pg) => ({ value: pg.route, label: pg.title || pg.name, hint: "/" + pg.route })),
14174
15518
  initialValue: home && pages.includes(home) ? home.route : pages[0].route
@@ -14181,7 +15525,7 @@ async function init(ctx, o, cmd) {
14181
15525
  const edits = {};
14182
15526
  for (const m of menus) {
14183
15527
  const top = (m.items || []).filter((i) => !i.parentId && i.active !== false);
14184
- const how = answered(await p3.select({
15528
+ const how = answered(await p5.select({
14185
15529
  message: `Menu "${m.key}" (${top.length} top-level item${top.length === 1 ? "" : "s"})`,
14186
15530
  options: [
14187
15531
  { value: "keep", label: "Keep it" },
@@ -14193,7 +15537,7 @@ async function init(ctx, o, cmd) {
14193
15537
  if (how === "drop")
14194
15538
  edits[m.key] = false;
14195
15539
  if (how === "edit" && top.length) {
14196
- const keep = answered(await p3.multiselect({
15540
+ const keep = answered(await p5.multiselect({
14197
15541
  message: `Keep which items of "${m.key}"?`,
14198
15542
  options: top.map((i) => ({ value: i.id, label: i.label, hint: i.type })),
14199
15543
  initialValues: top.map((i) => i.id),
@@ -14205,7 +15549,7 @@ async function init(ctx, o, cmd) {
14205
15549
  edit.drop = drop;
14206
15550
  const rename = {};
14207
15551
  for (const i of top.filter((x) => keep.includes(x.id))) {
14208
- const v = answered(await p3.text({ message: `Label for "${i.label}"`, initialValue: i.label })).trim();
15552
+ const v = answered(await p5.text({ message: `Label for "${i.label}"`, initialValue: i.label })).trim();
14209
15553
  if (v && v !== i.label)
14210
15554
  rename[i.label] = v;
14211
15555
  }
@@ -14220,7 +15564,7 @@ async function init(ctx, o, cmd) {
14220
15564
  }
14221
15565
  const panels = (design.panels || []).filter((pn) => pn.active !== false);
14222
15566
  if (!nav.panels && panels.length) {
14223
- const keep = answered(await p3.multiselect({
15567
+ const keep = answered(await p5.multiselect({
14224
15568
  message: "Side panels to keep",
14225
15569
  options: panels.map((pn) => ({ value: pn.key, label: pn.title || pn.key, hint: pn.key })),
14226
15570
  initialValues: panels.map((pn) => pn.key),
@@ -14234,22 +15578,22 @@ async function init(ctx, o, cmd) {
14234
15578
  delete a.navigation;
14235
15579
  if (ctx.interactive && !a.access) {
14236
15580
  const roles = design && design.portal ? design.portal.roles || [] : [];
14237
- const change = answered(await p3.confirm({
15581
+ const change = answered(await p5.confirm({
14238
15582
  message: `Audience: ${roles.length ? `roles ${roles.join(", ")}` : "every signed-in user"}${source ? ` (from ${source.slug})` : ""}, plus the source's portal user criteria. Change it?`,
14239
15583
  initialValue: false
14240
15584
  }));
14241
15585
  if (change) {
14242
15586
  const access = {};
14243
- access.roles = list4(answered(await p3.text({
15587
+ access.roles = list4(answered(await p5.text({
14244
15588
  message: "Roles (comma-separated; empty = every signed-in user)",
14245
15589
  initialValue: roles.join(", "),
14246
15590
  defaultValue: ""
14247
15591
  })));
14248
- const can = answered(await p3.text({
15592
+ const can = answered(await p5.text({
14249
15593
  message: "Available for: user criteria names (comma-separated; empty = none)",
14250
15594
  defaultValue: ""
14251
15595
  }));
14252
- const cannot = answered(await p3.text({
15596
+ const cannot = answered(await p5.text({
14253
15597
  message: "Not available for: user criteria names (comma-separated; empty = none)",
14254
15598
  defaultValue: ""
14255
15599
  }));
@@ -14261,20 +15605,20 @@ async function init(ctx, o, cmd) {
14261
15605
  const noPull = o.pull === false;
14262
15606
  let folder = "";
14263
15607
  if (!noPull) {
14264
- const def = a.folder ? { dir: resolve9(a.folder), why: "--out" } : defaultFolder(ctx, r, slug);
15608
+ const def = a.folder ? { dir: resolve10(a.folder), why: "--out" } : defaultFolder(ctx, r, slug);
14265
15609
  folder = def.dir;
14266
15610
  if (ctx.interactive && !a.folder)
14267
- folder = resolve9(answered(await p3.text({
15611
+ folder = resolve10(answered(await p5.text({
14268
15612
  message: "Local folder",
14269
15613
  initialValue: rel(def.dir),
14270
- validate: (v) => isEmptyDir(resolve9(String(v || "."))) ? undefined : "Must be empty or new"
15614
+ validate: (v) => isEmptyDir(resolve10(String(v || "."))) ? undefined : "Must be empty or new"
14271
15615
  })));
14272
15616
  if (!isEmptyDir(folder))
14273
15617
  throw usage(`${rel(folder)} is not empty: init pulls into an empty or new folder (--out)`);
14274
15618
  a.folder = isAbsolute4(a.folder || "") ? a.folder : rel(folder);
14275
15619
  }
14276
15620
  const ex = a.extras = a.extras || {};
14277
- const inRepo = folder ? insideGitRepo(dirname13(folder)) : true;
15621
+ const inRepo = folder ? insideGitRepo(dirname14(folder)) : true;
14278
15622
  if (!noPull && ctx.interactive && Object.keys(ex).length === 0) {
14279
15623
  const opts = [
14280
15624
  { value: "prettierrc", label: ".prettierrc.json", hint: "React Portal's code style" },
@@ -14284,7 +15628,7 @@ async function init(ctx, o, cmd) {
14284
15628
  ];
14285
15629
  if (!inRepo)
14286
15630
  opts.push({ value: "git", label: "git init", hint: "not inside a repository" });
14287
- const pick = answered(await p3.multiselect({
15631
+ const pick = answered(await p5.multiselect({
14288
15632
  message: "Also write",
14289
15633
  options: opts,
14290
15634
  initialValues: opts.map((x) => x.value),
@@ -14304,18 +15648,18 @@ async function init(ctx, o, cmd) {
14304
15648
  git: ex.git !== undefined ? ex.git && !inRepo : !inRepo
14305
15649
  };
14306
15650
  if (o.saveAnswers) {
14307
- writeFileSync13(resolve9(o.saveAnswers), JSON.stringify(a, null, 4) + `
15651
+ writeFileSync16(resolve10(o.saveAnswers), JSON.stringify(a, null, 4) + `
14308
15652
  `);
14309
- ctx.out.info(`answers saved to ${rel(resolve9(o.saveAnswers))}`);
15653
+ ctx.out.info(`answers saved to ${rel(resolve10(o.saveAnswers))}`);
14310
15654
  }
14311
15655
  const previewSet = setRef || (lists.sets.find((s) => s.isDefault) || lists.sets[0] || {}).id || "";
14312
15656
  if (!previewSet)
14313
15657
  throw new CliError(EXIT.failed, "no_update_set", `${app.scope} has no in-progress update set to plan against`);
14314
15658
  let setPlan = null;
14315
15659
  if (!setRef)
14316
- setPlan = await step2(ctx, "Planning the update set", () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: true }));
15660
+ setPlan = await step3(ctx, "Planning the update set", () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: true }));
14317
15661
  const body = createRequest(a, { tokens, updateSetRef: previewSet, dryRun: true });
14318
- const dry = await step2(ctx, `Planning ${slug} on ${instance}`, () => client.post("/write/create_portal", body));
15662
+ const dry = await step3(ctx, `Planning ${slug} on ${instance}`, () => client.post("/write/create_portal", body));
14319
15663
  const plan = dry.plan || {};
14320
15664
  if (!setRef && Array.isArray(plan.warnings))
14321
15665
  plan.warnings = plan.warnings.map((w) => /^Created in /.test(w) ? w.replace(/update set "[^"]*"/, `the new update set "${setName}"`) : w);
@@ -14356,7 +15700,7 @@ async function init(ctx, o, cmd) {
14356
15700
  ctx.out.line(k.yellow("Dry run only (--dry-run / FORGE_DRY_RUN): nothing written."));
14357
15701
  ctx.out.result("init", { ...envelope, dryRun: true, plan, updateSetPlan: setPlan && setPlan.plan, local });
14358
15702
  if (ctx.interactive)
14359
- p3.outro("Dry run done.");
15703
+ p5.outro("Dry run done.");
14360
15704
  return;
14361
15705
  }
14362
15706
  if (!ctx.interactive && !ctx.opts.yes) {
@@ -14373,7 +15717,7 @@ async function init(ctx, o, cmd) {
14373
15717
  return;
14374
15718
  }
14375
15719
  if (ctx.interactive && !ctx.opts.yes) {
14376
- const go = answered(await p3.confirm({ message: `Create the draft portal ${slug} on ${instance}?`, initialValue: true }));
15720
+ const go = answered(await p5.confirm({ message: `Create the draft portal ${slug} on ${instance}?`, initialValue: true }));
14377
15721
  if (!go) {
14378
15722
  ctx.out.line("Nothing created.");
14379
15723
  ctx.out.result("init", { ...envelope, dryRun: true, plan, local, cancelled: true });
@@ -14382,47 +15726,47 @@ async function init(ctx, o, cmd) {
14382
15726
  }
14383
15727
  let createdSet = null;
14384
15728
  if (!setRef) {
14385
- const made = await step2(ctx, `Creating the update set "${setName}"`, () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: false }));
15729
+ const made = await step3(ctx, `Creating the update set "${setName}"`, () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: false }));
14386
15730
  createdSet = made.result && made.result.updateSet;
14387
15731
  if (!createdSet || !createdSet.id)
14388
15732
  throw new CliError(EXIT.failed, "update_set_failed", "The update set was not created");
14389
15733
  setRef = createdSet.id;
14390
15734
  }
14391
15735
  const requestId = o.requestId || randomUUID();
14392
- const real = await step2(ctx, `Creating ${slug}`, () => client.post("/write/create_portal", createRequest(a, { tokens, updateSetRef: setRef, dryRun: false, requestId, planHash: plan.hash })));
15736
+ const real = await step3(ctx, `Creating ${slug}`, () => client.post("/write/create_portal", createRequest(a, { tokens, updateSetRef: setRef, dryRun: false, requestId, planHash: plan.hash })));
14393
15737
  const created = real.result || {};
14394
15738
  const preview = await client.get("/preview", { portal: slug }).catch(() => null);
14395
15739
  let pulled = null;
14396
15740
  let pullError = "";
14397
15741
  const files = [];
14398
15742
  if (!noPull) {
14399
- mkdirSync12(folder, { recursive: true });
15743
+ mkdirSync14(folder, { recursive: true });
14400
15744
  configureWorkspace({
14401
15745
  repo: "",
14402
- apps: dirname13(folder),
15746
+ apps: dirname14(folder),
14403
15747
  prettierConfigFrom: extras.prettierrc ? "" : prettierConfigFor(folder),
14404
15748
  tsc: "",
14405
15749
  hostTypes: "",
14406
15750
  typesFrom: ""
14407
15751
  });
14408
15752
  try {
14409
- pulled = await step2(ctx, `Pulling ${slug} into ${rel(folder)}`, () => pull(client, { portal: created.id || slug, out: folder, updateSet: setRef, mode: "fresh" }));
15753
+ pulled = await step3(ctx, `Pulling ${slug} into ${rel(folder)}`, () => pull(client, { portal: created.id || slug, out: folder, updateSet: setRef, mode: "fresh" }));
14410
15754
  } catch (e) {
14411
15755
  pullError = e.message || String(e);
14412
15756
  }
14413
15757
  if (!pullError) {
14414
15758
  if (extras.prettierrc) {
14415
- writeFileSync13(join26(folder, ".prettierrc.json"), prettierrcText());
15759
+ writeFileSync16(join30(folder, ".prettierrc.json"), prettierrcText());
14416
15760
  files.push(".prettierrc.json");
14417
15761
  }
14418
15762
  if (extras.gitignore) {
14419
- writeFileSync13(join26(folder, ".gitignore"), `.forge/
15763
+ writeFileSync16(join30(folder, ".gitignore"), `.forge/
14420
15764
  node_modules/
14421
15765
  `);
14422
15766
  files.push(".gitignore");
14423
15767
  }
14424
15768
  if (extras.readme) {
14425
- writeFileSync13(join26(folder, "README.md"), `# ${a.name}
15769
+ writeFileSync16(join30(folder, "README.md"), `# ${a.name}
14426
15770
 
14427
15771
  A React Portal workspace for the portal \`${slug}\` (application ${app.scope}, update set "${setName}") on ${instance}.
14428
15772
 
@@ -14431,7 +15775,7 @@ A React Portal workspace for the portal \`${slug}\` (application ${app.scope}, u
14431
15775
  files.push("README.md");
14432
15776
  }
14433
15777
  if (extras.git) {
14434
- const g = spawnSync6("git", ["init", "-q"], { cwd: folder, encoding: "utf8" });
15778
+ const g = spawnSync7("git", ["init", "-q"], { cwd: folder, encoding: "utf8" });
14435
15779
  if (g.status === 0)
14436
15780
  files.push(".git/");
14437
15781
  else
@@ -14439,19 +15783,19 @@ A React Portal workspace for the portal \`${slug}\` (application ${app.scope}, u
14439
15783
  }
14440
15784
  if (extras.skills) {
14441
15785
  try {
14442
- const r = syncSkills(join26(nearestProject(folder), ".claude", "skills"), { mode: "install" });
15786
+ const r = syncSkills(join30(nearestProject(folder), ".claude", "skills"), { mode: "install" });
14443
15787
  const n = r.skills.reduce((x, s) => x + s.created.length + s.updated.length, 0);
14444
15788
  files.push(`${rel(r.root)} (${r.skills.map((s) => s.name).join(", ")}; ${n} file(s))`);
14445
15789
  } catch (e) {
14446
15790
  ctx.out.info(k.yellow("warn ") + "skills install failed: " + (e.message || e));
14447
15791
  }
14448
15792
  }
14449
- mkdirSync12(join26(folder, ".forge"), { recursive: true });
15793
+ mkdirSync14(join30(folder, ".forge"), { recursive: true });
14450
15794
  const saved = JSON.parse(JSON.stringify(a));
14451
15795
  delete saved.folder;
14452
15796
  if (typeof saved.updateSet === "object")
14453
15797
  saved.updateSet = setName;
14454
- writeFileSync13(join26(folder, ".forge", "init-answers.json"), JSON.stringify(saved, null, 4) + `
15798
+ writeFileSync16(join30(folder, ".forge", "init-answers.json"), JSON.stringify(saved, null, 4) + `
14455
15799
  `);
14456
15800
  }
14457
15801
  }
@@ -14495,16 +15839,36 @@ A React Portal workspace for the portal \`${slug}\` (application ${app.scope}, u
14495
15839
  if (pullError)
14496
15840
  process.exitCode = EXIT.failed;
14497
15841
  if (ctx.interactive)
14498
- p3.outro(pullError ? "The draft exists; the pull needs another try." : "Done.");
15842
+ p5.outro(pullError ? "The draft exists; the pull needs another try." : "Done.");
14499
15843
  }
14500
15844
  function collect(v, prev) {
14501
15845
  return prev.concat([v]);
14502
15846
  }
14503
15847
  function registerInit(program, run) {
14504
15848
  const cmd = program.command("init").description("Create a draft portal on the instance (in an application and update set you pick) and pull it into a new local workspace. Asks each question; every answer has a flag; never publishes").option("--answers <file>", "take the answers from a JSON file (rpforge init --answers-schema)").option("--save-answers <file>", "write the answers to a JSON file (before the create)").option("--answers-schema", "print the JSON schema of the answers file").option("--app <scope>", "the owning application (scope name or sys_id)").option("--update-set <name>", "an in-progress update set of that application (name or sys_id)").option("--new-update-set [name]", 'create a new update set (default name "<Portal name> (React Portal)")').option("--name <name>", "the portal name").option("--slug <slug>", "the portal slug (default: from the name)").option("--description <text>", "the portal description").option("--from <kind>", "template (default), portal (a copy) or empty").option("--source <portal>", "the template or portal to start from (slug or sys_id)").option("--pages <list>", "all, none, or the source's page routes to copy (comma-separated)").option("--no-variants", "don't copy page variants").option("--no-view-rules", "don't copy view rules").option("--no-criteria", "don't copy user criteria links").option("--layout <uid>", "the layout component (default: the source's)").option("--frame <v>", "layout option frame (inset, flat)").option("--texture <v>", "layout option texture (noise, plain)").option("--padding <v>", "layout option content padding (none, sm, md, lg)").option("--subheader <v>", "layout option sub-header (bar, banner, hidden)").option("--content-width <w>", `default content width (${CONTENT_WIDTHS.join(", ")})`).option("--theme <key>", "a theme or preset key (default: the source's)").option("--theme-copy", "make an editable copy of the theme for this portal").option("--theme-name <name>", "the new theme name (copy or brand color)").option("--brand-color <color>", "generate the theme from a brand color (made locally)").option("--tint <v>", "brand color neutrals: neutral or tinted").option("--contrast <v>", "brand color contrast target: AA or AAA").option("--radius <v>", "brand color theme radius (e.g. 0.5rem)").option("--brand-icon <name>", "the sidebar brand icon (Lucide name)").option("--logo <url>", "the sidebar logo (https:// or /)").option("--footer <text>", "the footer text").option("--home <route>", "a copied page's route to be the home page").option("--drop-menu <keys>", "menus to leave out (comma-separated keys)").option("--drop-item <menu:label>", "a menu item to leave out (repeatable)", collect, []).option("--rename-item <menu:label=New>", "a menu item to rename (repeatable)", collect, []).option("--panels <keys>", "side panels to keep (comma-separated keys; default all)").option("--roles <list>", "audience roles (comma-separated; empty = every signed-in user)").option("--available-for <names>", "portal user criteria Available for (comma-separated names)").option("--not-available-for <names>", "portal user criteria Not available for (comma-separated names)").option("--out <folder>", "the exact workspace folder (default: <--dir or ./apps or .>/<slug>)").option("--no-prettierrc", "don't write .prettierrc.json").option("--no-gitignore", "don't write .gitignore").option("--no-git", "don't git init").option("--no-readme", "don't write README.md").option("--no-skills", "don't install the agent skills into the project's .claude/skills").option("--no-pull", "create the draft only; don't pull it into a folder").option("--request-id <id>", "idempotency key: a retry with the same id replays instead of duplicating");
14505
- cmd.action(run((ctx) => init(ctx, cmd.opts(), cmd)));
15849
+ cmd.option("--component", "a component-only workspace (no portal): app, update set, then --pull and / or --new").option("--pull <ids>", "with --component: existing components of the app to pull (comma-separated <ns>/<key>)").option("--new <id>", "with --component: scaffold a new component (<ns>/<key>; --kind sets its kind)").option("--kind <kind>", "with --new: widget, primitive, block, layout or utility (default widget)");
15850
+ cmd.action(run((ctx) => {
15851
+ const o = cmd.opts();
15852
+ if (!o.component)
15853
+ return init(ctx, o, cmd);
15854
+ return initComponent(ctx, {
15855
+ app: o.app,
15856
+ updateSet: o.updateSet,
15857
+ newUpdateSet: o.newUpdateSet,
15858
+ pull: o.pull,
15859
+ new: o.new,
15860
+ kind: o.kind || cmd.optsWithGlobals().kind,
15861
+ name: o.name,
15862
+ out: o.out,
15863
+ prettierrc: o.prettierrc,
15864
+ gitignore: o.gitignore,
15865
+ git: o.git,
15866
+ readme: o.readme,
15867
+ skills: o.skills
15868
+ });
15869
+ }));
14506
15870
  }
14507
- var HELPERS_SWITCH2 = "1.3.0", HELPERS_UPDATE_SETS2 = "1.7.0", CONTENT_WIDTHS;
15871
+ var HELPERS_SWITCH3 = "1.3.0", HELPERS_UPDATE_SETS3 = "1.7.0", CONTENT_WIDTHS;
14508
15872
  var init_init2 = __esm(() => {
14509
15873
  init_client();
14510
15874
  init_compat();
@@ -14517,241 +15881,14 @@ var init_init2 = __esm(() => {
14517
15881
  init_auth2();
14518
15882
  init_workspace();
14519
15883
  init_skills();
15884
+ init_init_component();
14520
15885
  init_render();
14521
15886
  CONTENT_WIDTHS = ["full", "7xl", "6xl", "5xl", "4xl", "3xl"];
14522
15887
  });
14523
15888
 
14524
- // src/commands/new.ts
14525
- import { existsSync as existsSync26, mkdirSync as mkdirSync13, readFileSync as readFileSync28, writeFileSync as writeFileSync14 } from "node:fs";
14526
- import { join as join27 } from "node:path";
14527
- import * as p4 from "@clack/prompts";
14528
- function title(key) {
14529
- return key.split("-").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
14530
- }
14531
- function pascal(key) {
14532
- return title(key).replace(/\s+/g, "") || "Component";
14533
- }
14534
- function scaffold(uid, kind, name, description) {
14535
- const [, key] = uid.split("/");
14536
- const C = pascal(key);
14537
- const meta = { name, kind, description, tailwind: kind !== "layout" };
14538
- const files = {};
14539
- const doc = `/**
14540
- * components:${uid}: ${description || name}.
14541
- */
14542
- `;
14543
- if (kind === "widget") {
14544
- meta.defaults = { title: name };
14545
- files["main.tsx"] = `import { Card, CardHeader, CardTitle, CardContent } from 'components:card';
14546
-
14547
- ${doc}` + `type Options = { title?: string };
14548
-
14549
- ` + `export default function ${C}({ options = {} }: { options?: Options }) {
14550
- ` + ` return (
14551
- <Card>
14552
- <CardHeader>
14553
- <CardTitle>{options.title || '${name}'}</CardTitle>
14554
- </CardHeader>
14555
- ` + ` <CardContent>
14556
- <p className="text-sm text-muted-foreground">Edit components/@${uid}/main.tsx.</p>
14557
- </CardContent>
14558
- </Card>
14559
- );
14560
- }
14561
- `;
14562
- files["options.schema.json"] = JSON.stringify({
14563
- type: "object",
14564
- properties: { title: { type: "string", title: "Title", default: name } }
14565
- }, null, 4);
14566
- } else if (kind === "primitive") {
14567
- files["main.tsx"] = `import type { ReactNode } from 'react';
14568
-
14569
- ${doc}` + `export interface ${C}Props {
14570
- children?: ReactNode;
14571
- className?: string;
14572
- }
14573
-
14574
- ` + `export function ${C}({ children, className = '' }: ${C}Props) {
14575
- ` + ` return <div className={\`rounded-md border p-3 \${className}\`}>{children}</div>;
14576
- }
14577
-
14578
- ` + `/** Shown in Studio's preview of the primitive. */
14579
- export default function ${C}Preview() {
14580
- return <${C}>${name}</${C}>;
14581
- }
14582
- `;
14583
- } else if (kind === "block") {
14584
- meta.regions = [{ name: "main", label: "Content" }];
14585
- meta.defaults = { gap: "1rem" };
14586
- files["main.tsx"] = `import type { ReactNode } from 'react';
14587
-
14588
- ${doc}` + `type Options = { gap?: string };
14589
-
14590
- ` + `export default function ${C}({ options = {}, regions = {} }: { options?: Options; regions?: Record<string, ReactNode> }) {
14591
- ` + ` return <div style={{ display: 'grid', gap: options.gap || '1rem' }}>{regions.main}</div>;
14592
- }
14593
- `;
14594
- files["options.schema.json"] = JSON.stringify({ type: "object", properties: { gap: { type: "string", title: "Gap", default: "1rem" } } }, null, 4);
14595
- } else if (kind === "layout") {
14596
- meta.regions = [
14597
- { name: "header", acceptsContributions: true },
14598
- { name: "main", acceptsContributions: false },
14599
- { name: "footer", acceptsContributions: true }
14600
- ];
14601
- meta.defaults = { contentPadding: "md" };
14602
- files["main.tsx"] = `import type { ReactNode } from 'react';
14603
-
14604
- ${doc}` + `type Options = { contentPadding?: 'none' | 'sm' | 'md' | 'lg' };
14605
- ` + `const PAD = { none: '0', sm: '0.75rem', md: '1.5rem', lg: '2.5rem' };
14606
-
14607
- ` + `export default function ${C}({ options = {}, regions = {} }: { options?: Options; regions?: Record<string, ReactNode> }) {
14608
- ` + ` return (
14609
- <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
14610
- ` + ` <header>{regions.header}</header>
14611
- ` + ` <main style={{ flex: 1, padding: PAD[options.contentPadding || 'md'] }}>{regions.main}</main>
14612
- ` + ` <footer>{regions.footer}</footer>
14613
- </div>
14614
- );
14615
- }
14616
- `;
14617
- files["options.schema.json"] = JSON.stringify({
14618
- type: "object",
14619
- properties: {
14620
- contentPadding: {
14621
- type: "string",
14622
- title: "Content padding",
14623
- enum: ["none", "sm", "md", "lg"],
14624
- default: "md"
14625
- }
14626
- }
14627
- }, null, 4);
14628
- } else {
14629
- files["main.tsx"] = `import { useMemo } from 'react';
14630
-
14631
- ${doc}` + `/** Import it as utilities:${uid}. */
14632
- export function use${C}(value: string) {
14633
- return useMemo(() => value.trim(), [value]);
14634
- }
14635
- `;
14636
- }
14637
- files["component.json"] = JSON.stringify(meta, null, 4);
14638
- return files;
14639
- }
14640
- function workspaceScope(ws) {
14641
- try {
14642
- const m = JSON.parse(readFileSync28(join27(ws, "forge.workspace.json"), "utf8"));
14643
- const scopes = new Set;
14644
- for (const inst of Object.values(m && m.instances || {}))
14645
- if (inst && inst.app && inst.app.scope)
14646
- scopes.add(String(inst.app.scope));
14647
- return scopes.size === 1 ? [...scopes][0] : "";
14648
- } catch {
14649
- return "";
14650
- }
14651
- }
14652
- async function newComponent(ctx, ref, o) {
14653
- const ws = currentWorkspace(ctx);
14654
- if (!ws)
14655
- throw usage("No workspace here: run it inside a workspace (forge.workspace.json), or pass --dir");
14656
- const scope = workspaceScope(ws);
14657
- const defaultNs = defaultNamespaceFor(scope);
14658
- let uid = String(ref || "").replace(/^@/, "");
14659
- if (!uid && ctx.interactive) {
14660
- const name = o.name || answered(await p4.text({
14661
- message: "Name",
14662
- placeholder: "Order card",
14663
- validate: (v) => v ? undefined : "Required"
14664
- }));
14665
- o.name = name;
14666
- const ns = answered(await p4.text({
14667
- message: "Namespace",
14668
- initialValue: defaultNs,
14669
- placeholder: defaultNs || "acme",
14670
- validate: (v) => namespaceProblem(v || "") || namespaceRefusal(v || "", scope) || undefined
14671
- }));
14672
- const key = answered(await p4.text({
14673
- message: "Key",
14674
- initialValue: keyFromName(name),
14675
- validate: (v) => keyProblem(v || "") || undefined
14676
- }));
14677
- uid = `${ns}/${key}`;
14678
- }
14679
- if (uid && uid.indexOf("/") < 0 && defaultNs)
14680
- uid = `${defaultNs}/${uid}`;
14681
- const [ns, key, extra] = uid.split("/");
14682
- const problem = !ns || !key || extra !== undefined ? `"${uid}": give <namespace>/<key>${defaultNs ? ` (or just <key> for ${defaultNs}/<key>)` : ""}` : namespaceProblem(ns) || keyProblem(key) || namespaceRefusal(ns, scope);
14683
- if (problem)
14684
- throw usage(problem);
14685
- if (scope && ns !== scope && /^[a-z][a-z0-9]*_[a-z0-9_]+$/.test(ns) && !ctx.out.o.json)
14686
- ctx.out.line(ctx.out.c.yellow(`warning: "${ns}" looks like another application's scope (this workspace is ${scope}); ids there can collide with what that app ships`));
14687
- let kind = o.kind;
14688
- if (!kind && ctx.interactive)
14689
- kind = answered(await p4.select({
14690
- message: "Kind",
14691
- options: [
14692
- { value: "widget", label: "widget", hint: "placeable on pages, with options" },
14693
- { value: "primitive", label: "primitive", hint: "a reusable piece other components import" },
14694
- { value: "block", label: "block", hint: "a placeable container with regions" },
14695
- { value: "layout", label: "layout", hint: "a portal shell with regions" },
14696
- { value: "utility", label: "utility", hint: "hooks and helpers (utilities:<ns>/<key>)" }
14697
- ],
14698
- initialValue: "widget"
14699
- }));
14700
- kind = kind || "widget";
14701
- if (!KINDS.includes(kind))
14702
- throw usage(`--kind ${kind}: one of ${KINDS.join(", ")}`);
14703
- const dir = join27(ws, "components", "@" + ns, key);
14704
- if (existsSync26(dir))
14705
- throw usage(`${rel(dir)} already exists`);
14706
- const name = o.name || title(key);
14707
- const files = scaffold(`${ns}/${key}`, kind, name, o.description || "");
14708
- configureWorkspace({
14709
- repo: "",
14710
- apps: ws,
14711
- prettierConfigFrom: prettierConfigFor(ws),
14712
- tsc: "",
14713
- hostTypes: "",
14714
- typesFrom: ""
14715
- });
14716
- mkdirSync13(dir, { recursive: true });
14717
- const written = [];
14718
- for (const [f, content] of Object.entries(files)) {
14719
- const rp = `components/@${ns}/${key}/${f}`;
14720
- writeFileSync14(join27(dir, f), await formatFile(rp, content.endsWith(`
14721
- `) ? content : content + `
14722
- `));
14723
- written.push(rp);
14724
- }
14725
- if (!ctx.out.o.json) {
14726
- ctx.out.line(ctx.out.c.green(`created ${kind} ${ns}/${key}`) + ctx.out.c.dim(` in ${rel(ws)}`));
14727
- for (const f of written)
14728
- ctx.out.line(" + " + f);
14729
- ctx.out.line(ctx.out.c.dim("next: rpforge check (compiles it on the instance, writes nothing) · rpforge push"));
14730
- }
14731
- ctx.out.result("new component", { workspace: ws, uniqueId: `${ns}/${key}`, kind, files: written });
14732
- }
14733
- function registerNew(program, run) {
14734
- const group = program.command("new").description("Scaffold local workspace files");
14735
- const comp = group.command("component").argument("[ns/key]", "the component id, e.g. x_acme_crm/order-card; a bare key takes the workspace app's scope").description("Scaffold components/@<ns>/<key>/ (component.json, main.tsx, options.schema.json) in the workspace; rpforge check compiles it, rpforge push creates it").option("--kind <kind>", `${KINDS.join(", ")} (default widget)`).option("--name <name>", "the display name (default: from the key)").option("--description <text>", "the description");
14736
- comp.action(run((ctx) => newComponent(ctx, comp.processedArgs[0], {
14737
- ...comp.opts(),
14738
- kind: comp.opts().kind || comp.optsWithGlobals().kind
14739
- })));
14740
- }
14741
- var KINDS;
14742
- var init_new = __esm(() => {
14743
- init_component_id();
14744
- init_layout();
14745
- init_out();
14746
- init_auth2();
14747
- init_workspace();
14748
- init_render();
14749
- KINDS = ["widget", "primitive", "block", "layout", "utility"];
14750
- });
14751
-
14752
15889
  // src/commands/lookup.ts
14753
- import { mkdirSync as mkdirSync14, readFileSync as readFileSync29, writeFileSync as writeFileSync15 } from "node:fs";
14754
- import { dirname as dirname14, resolve as resolve10 } from "node:path";
15890
+ import { mkdirSync as mkdirSync15, readFileSync as readFileSync30, writeFileSync as writeFileSync17 } from "node:fs";
15891
+ import { dirname as dirname15, resolve as resolve11 } from "node:path";
14755
15892
  function connect2(ctx) {
14756
15893
  const r = resolveFor(ctx);
14757
15894
  return { client: new ForgeClient(r.config), envelope: { profile: r.profile || null, instance: r.config.instance } };
@@ -14950,7 +16087,7 @@ async function themesGenerate(ctx, o) {
14950
16087
  throw usage(`--color ${o.color}: ${e.message}`);
14951
16088
  }
14952
16089
  } else {
14953
- const css = readFileSync29(resolve10(String(o.fromCss)), "utf8");
16090
+ const css = readFileSync30(resolve11(String(o.fromCss)), "utf8");
14954
16091
  const parsed = await tokensFromCss(css);
14955
16092
  custom = parsed.custom;
14956
16093
  tokens = { light: parsed.light, dark: parsed.dark };
@@ -14971,9 +16108,9 @@ async function themesGenerate(ctx, o) {
14971
16108
  `;
14972
16109
  let written = "";
14973
16110
  if (o.out) {
14974
- written = resolve10(o.out);
14975
- mkdirSync14(dirname14(written), { recursive: true });
14976
- writeFileSync15(written, text);
16111
+ written = resolve11(o.out);
16112
+ mkdirSync15(dirname15(written), { recursive: true });
16113
+ writeFileSync17(written, text);
14977
16114
  }
14978
16115
  if (!ctx.out.o.json) {
14979
16116
  const k = ctx.out.c;
@@ -15028,9 +16165,9 @@ var init_lookup = __esm(() => {
15028
16165
  });
15029
16166
 
15030
16167
  // ../forge-core/src/workspace/seed.ts
15031
- import { existsSync as existsSync27, readFileSync as readFileSync30 } from "node:fs";
15032
- import { join as join28 } from "node:path";
15033
- function cmpVersion3(a, b) {
16168
+ import { existsSync as existsSync30, readFileSync as readFileSync31 } from "node:fs";
16169
+ import { join as join31 } from "node:path";
16170
+ function cmpVersion4(a, b) {
15034
16171
  const pa = String(a || "").split(".");
15035
16172
  const pb = String(b || "").split(".");
15036
16173
  for (let i = 0;i < 3; i++) {
@@ -15045,7 +16182,7 @@ function newerVersion(a, b) {
15045
16182
  return b;
15046
16183
  if (!b)
15047
16184
  return a;
15048
- return cmpVersion3(a, b) >= 0 ? a : b;
16185
+ return cmpVersion4(a, b) >= 0 ? a : b;
15049
16186
  }
15050
16187
  function strings2(v, out, depth = 0) {
15051
16188
  if (depth > 12)
@@ -15061,8 +16198,8 @@ function strings2(v, out, depth = 0) {
15061
16198
  }
15062
16199
  async function packInventory(dir) {
15063
16200
  const problems = [];
15064
- const file = join28(dir, "portal.mjs");
15065
- if (!existsSync27(file))
16201
+ const file = join31(dir, "portal.mjs");
16202
+ if (!existsSync30(file))
15066
16203
  throw new Error(`${dir} has no portal.mjs: not an app pack`);
15067
16204
  let def;
15068
16205
  try {
@@ -15111,7 +16248,7 @@ async function packInventory(dir) {
15111
16248
  const r = recordOfPath(p);
15112
16249
  if (r.kind === "other")
15113
16250
  continue;
15114
- parts.push(p + ":" + sha2562(readFileSync30(join28(dir, p))));
16251
+ parts.push(p + ":" + sha2562(readFileSync31(join31(dir, p))));
15115
16252
  if (r.kind === "component" || r.kind === "sourceFile") {
15116
16253
  const uid = r.group.slice("component:".length);
15117
16254
  let c = comps.get(uid);
@@ -15124,13 +16261,13 @@ async function packInventory(dir) {
15124
16261
  sourceFiles++;
15125
16262
  if (r.name === "component.json") {
15126
16263
  try {
15127
- c.kind = String(JSON.parse(readFileSync30(join28(dir, p), "utf8")).kind || "");
16264
+ c.kind = String(JSON.parse(readFileSync31(join31(dir, p), "utf8")).kind || "");
15128
16265
  } catch {
15129
16266
  problems.push(`${p}: not valid JSON`);
15130
16267
  }
15131
16268
  }
15132
16269
  if (/\.(tsx?|jsx?)$/.test(p)) {
15133
- const text = readFileSync30(join28(dir, p), "utf8");
16270
+ const text = readFileSync31(join31(dir, p), "utf8");
15134
16271
  for (const m of text.matchAll(IMPORT))
15135
16272
  deps.add(`${m[1]}/${m[2]}`);
15136
16273
  }
@@ -15182,11 +16319,11 @@ async function packInventory(dir) {
15182
16319
  reactPortal,
15183
16320
  tracked,
15184
16321
  problems,
15185
- fingerprint: sha2562(canonicalJson({ parts: parts.sort(), portal: readFileSync30(file, "utf8") }))
16322
+ fingerprint: sha2562(canonicalJson({ parts: parts.sort(), portal: readFileSync31(file, "utf8") }))
15186
16323
  };
15187
16324
  }
15188
16325
  async function retargetPortal(dir, t) {
15189
- const file = join28(dir, "portal.mjs");
16326
+ const file = join31(dir, "portal.mjs");
15190
16327
  const def = await importPortal(file);
15191
16328
  const changed = [];
15192
16329
  const oldSlug = String(def.slug || "");
@@ -15212,7 +16349,7 @@ async function retargetPortal(dir, t) {
15212
16349
  return { changed };
15213
16350
  }
15214
16351
  async function retargetPreview(dir, t) {
15215
- const def = await importPortal(join28(dir, "portal.mjs"));
16352
+ const def = await importPortal(join31(dir, "portal.mjs"));
15216
16353
  const out = [];
15217
16354
  for (const k of ["slug", "name", "app", "updateSet"])
15218
16355
  if (def[k] !== t[k])
@@ -15238,9 +16375,9 @@ async function trackEmpty(dir, st, key) {
15238
16375
  seed: { at: new Date().toISOString(), done: false }
15239
16376
  };
15240
16377
  m.instances[key] = entry;
15241
- writeText(join28(dir, FORGE_DIR), ".gitignore", `*
16378
+ writeText(join31(dir, FORGE_DIR), ".gitignore", `*
15242
16379
  `);
15243
- writeText(join28(dir, FORGE_DIR, "base"), "portal.mjs", `// Empty base written by a seed: every record of the pack is new on this instance.
16380
+ writeText(join31(dir, FORGE_DIR, "base"), "portal.mjs", `// Empty base written by a seed: every record of the pack is new on this instance.
15244
16381
  export default ${JSON.stringify({ slug: st.portal.slug })};
15245
16382
  `);
15246
16383
  await writeManifest(dir, m);
@@ -15272,16 +16409,16 @@ var init_seed = __esm(() => {
15272
16409
  });
15273
16410
 
15274
16411
  // src/commands/seed.ts
15275
- import { cpSync as cpSync3, existsSync as existsSync28, mkdirSync as mkdirSync15, readdirSync as readdirSync9 } from "node:fs";
15276
- import { dirname as dirname15, join as join29, relative as relative10, resolve as resolve11, sep as sep6 } from "node:path";
16412
+ import { cpSync as cpSync3, existsSync as existsSync31, mkdirSync as mkdirSync16, readdirSync as readdirSync11 } from "node:fs";
16413
+ import { dirname as dirname16, join as join32, relative as relative10, resolve as resolve12, sep as sep6 } from "node:path";
15277
16414
  import { randomUUID as randomUUID2 } from "node:crypto";
15278
- import * as p5 from "@clack/prompts";
15279
- async function step3(ctx, label, fn) {
16415
+ import * as p6 from "@clack/prompts";
16416
+ async function step4(ctx, label, fn) {
15280
16417
  if (!ctx.interactive) {
15281
16418
  ctx.out.info(label + "…");
15282
16419
  return fn();
15283
16420
  }
15284
- const s = p5.spinner();
16421
+ const s = p6.spinner();
15285
16422
  s.start(label);
15286
16423
  try {
15287
16424
  const v = await fn();
@@ -15314,12 +16451,12 @@ async function pool(items, n, fn) {
15314
16451
  return out;
15315
16452
  }
15316
16453
  function isEmptyDir2(dir) {
15317
- return !existsSync28(dir) || readdirSync9(dir).length === 0;
16454
+ return !existsSync31(dir) || readdirSync11(dir).length === 0;
15318
16455
  }
15319
16456
  function configure2(ws) {
15320
16457
  configureWorkspace({
15321
16458
  repo: "",
15322
- apps: dirname15(ws),
16459
+ apps: dirname16(ws),
15323
16460
  prettierConfigFrom: prettierConfigFor(ws),
15324
16461
  tsc: "",
15325
16462
  hostTypes: "",
@@ -15341,11 +16478,11 @@ function failed2(r) {
15341
16478
  async function seed(ctx, packArg, o) {
15342
16479
  const human = !ctx.out.o.json;
15343
16480
  const k = ctx.out.c;
15344
- const pack = resolve11(packArg || ".");
15345
- if (!existsSync28(join29(pack, "portal.mjs")))
16481
+ const pack = resolve12(packArg || ".");
16482
+ if (!existsSync31(join32(pack, "portal.mjs")))
15346
16483
  throw usage(`${rel(pack)} has no portal.mjs: rpforge seed <pack folder> (an app pack or workspace)`);
15347
- const out = o.out ? resolve11(o.out) : "";
15348
- if (out && resolve11(out) === pack)
16484
+ const out = o.out ? resolve12(o.out) : "";
16485
+ if (out && resolve12(out) === pack)
15349
16486
  throw usage("--out must be a different folder than the pack");
15350
16487
  if (out && !isEmptyDir2(out))
15351
16488
  throw usage(`--out ${rel(out)} is not empty: the copy goes into an empty or new folder`);
@@ -15369,7 +16506,7 @@ async function seed(ctx, packArg, o) {
15369
16506
  const okc = (m) => checks.push({ level: "ok", message: m });
15370
16507
  for (const pr of inv.problems)
15371
16508
  fail(pr);
15372
- const status = await step3(ctx, `Checking ${instance}`, () => client.get("/status"));
16509
+ const status = await step4(ctx, `Checking ${instance}`, () => client.get("/status"));
15373
16510
  if (!status.enabled)
15374
16511
  throw new CliError(EXIT.incompatible, "forge_mcp_disabled", `Forge is disabled on ${instance} (${status.property || "x_312987_portal.forge.mcp.enabled"} is not true)`);
15375
16512
  const compat = checkForgeApi(status);
@@ -15381,12 +16518,12 @@ async function seed(ctx, packArg, o) {
15381
16518
  if (!caps.design || !caps.author)
15382
16519
  fail(`${status.user} needs React Portal author and design access on ${instance} (a developer role)`);
15383
16520
  const helpers = String(status.globalHelpers || "");
15384
- if (!helpers || cmpVersion3(helpers, HELPERS_SWITCH3) < 0)
15385
- throw new CliError(EXIT.incompatible, "helper_missing", `seed needs React Portal Global Helpers ${HELPERS_SWITCH3}+ on ${instance} (found ${helpers || "none"})`);
15386
- if (inv.images.length && cmpVersion3(helpers, HELPERS_IMAGES2) < 0)
16521
+ if (!helpers || cmpVersion4(helpers, HELPERS_SWITCH4) < 0)
16522
+ throw new CliError(EXIT.incompatible, "helper_missing", `seed needs React Portal Global Helpers ${HELPERS_SWITCH4}+ on ${instance} (found ${helpers || "none"})`);
16523
+ if (inv.images.length && cmpVersion4(helpers, HELPERS_IMAGES2) < 0)
15387
16524
  fail(`the pack carries images: they need React Portal Global Helpers ${HELPERS_IMAGES2}+ (found ${helpers})`);
15388
16525
  const rp = String(status.reactPortal || "");
15389
- if (inv.reactPortal && (!rp || cmpVersion3(rp, inv.reactPortal) < 0))
16526
+ if (inv.reactPortal && (!rp || cmpVersion4(rp, inv.reactPortal) < 0))
15390
16527
  fail(`the pack was made with React Portal ${inv.reactPortal}; ${instance} runs ${rp || "an unknown version"}`);
15391
16528
  else
15392
16529
  okc(`React Portal ${rp}${inv.reactPortal ? ` (the pack needs ${inv.reactPortal}+)` : ""}`);
@@ -15395,14 +16532,14 @@ async function seed(ctx, packArg, o) {
15395
16532
  const appWanted = o.app || inv.app;
15396
16533
  if (!appWanted)
15397
16534
  throw usage("portal.mjs names no app: pass --app <scope>");
15398
- const apps = (await step3(ctx, "Reading your applications", () => client.get("/apps", { list: "authoring" }))).apps;
16535
+ const apps = (await step4(ctx, "Reading your applications", () => client.get("/apps", { list: "authoring" }))).apps;
15399
16536
  const app = apps.find((x) => x.scope === appWanted || x.id === appWanted);
15400
16537
  if (!app)
15401
16538
  throw new CliError(EXIT.failed, "no_app", `Application ${appWanted} isn't one you can author in on ${instance}${apps.length ? ` (${apps.map((x) => x.scope).join(", ")})` : ""}: install it first, or pass --app`);
15402
16539
  if (app.reactPortal)
15403
16540
  throw usage("React Portal's own application can't own a seeded portal: pick the app the pack belongs to (--app)");
15404
16541
  const appOverridden = !!o.app && o.app !== inv.app && o.app !== app.id;
15405
- const sets = (await step3(ctx, `Reading ${app.scope}'s update sets`, () => client.get("/update-sets", { app: app.id }))).sets;
16542
+ const sets = (await step4(ctx, `Reading ${app.scope}'s update sets`, () => client.get("/update-sets", { app: app.id }))).sets;
15406
16543
  let setRef = "";
15407
16544
  let setName = "";
15408
16545
  let createSet = false;
@@ -15429,7 +16566,7 @@ async function seed(ctx, packArg, o) {
15429
16566
  const suggested = want || defaultUpdateSetName(name);
15430
16567
  if (!ctx.interactive)
15431
16568
  throw usage(`${want ? `Update set "${want}" isn't` : "No update set is"} in progress in ${app.scope}: pass --new-update-set${want ? ` "${want}"` : ""} (creates "${suggested}") or --update-set <an existing set>`, { updateSets: sets.map((s) => s.name) });
15432
- const v = answered(await p5.select({
16569
+ const v = answered(await p6.select({
15433
16570
  message: `Which update set of ${app.scope} captures the portal?`,
15434
16571
  options: [{ value: "__new__", label: `Create "${suggested}"`, hint: "recommended" }].concat(sets.map((s) => ({
15435
16572
  value: s.id,
@@ -15447,15 +16584,15 @@ async function seed(ctx, packArg, o) {
15447
16584
  }
15448
16585
  }
15449
16586
  }
15450
- if (createSet && cmpVersion3(helpers, HELPERS_UPDATE_SETS3) < 0)
15451
- throw new CliError(EXIT.incompatible, "helper_missing", `Creating an update set needs React Portal Global Helpers ${HELPERS_UPDATE_SETS3}+ on ${instance} (found ${helpers}): pass --update-set <an existing set>`);
16587
+ if (createSet && cmpVersion4(helpers, HELPERS_UPDATE_SETS4) < 0)
16588
+ throw new CliError(EXIT.incompatible, "helper_missing", `Creating an update set needs React Portal Global Helpers ${HELPERS_UPDATE_SETS4}+ on ${instance} (found ${helpers}): pass --update-set <an existing set>`);
15452
16589
  const slugCheck = await client.get("/portals/slug-available", { slug });
15453
16590
  if (!slugCheck.available) {
15454
16591
  const why = slugCheck.takenBy ? `taken by ${slugCheck.takenBy.name}${slugCheck.takenBy.active ? "" : " (draft)"}` : slugCheck.reason || "not available";
15455
16592
  fail(`slug "${slug}" is ${why}${slugCheck.suggestion ? `: pass --slug ${slugCheck.suggestion}` : ""}`);
15456
16593
  } else
15457
16594
  okc(`slug ${slug} is free`);
15458
- const own = await step3(ctx, "Checking the pack’s components and themes", () => Promise.all([
16595
+ const own = await step4(ctx, "Checking the pack’s components and themes", () => Promise.all([
15459
16596
  pool(inv.components, 6, (c) => readOrNull(client, "/component", c.uid)),
15460
16597
  pool(inv.themes, 4, (t) => readOrNull(client, "/theme", t)),
15461
16598
  pool(inv.dependencies, 6, (u) => readOrNull(client, "/component", u))
@@ -15497,8 +16634,8 @@ async function seed(ctx, packArg, o) {
15497
16634
  if (!previewSet)
15498
16635
  throw new CliError(EXIT.failed, "no_update_set", `${app.scope} has no in-progress update set to plan against`);
15499
16636
  if (createSet)
15500
- setPlan = await step3(ctx, "Planning the update set", () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: true }));
15501
- const dry = await step3(ctx, `Planning the draft ${slug} on ${instance}`, () => client.post("/write/create_portal", { ...createBody, updateSet: previewSet, dryRun: true }));
16637
+ setPlan = await step4(ctx, "Planning the update set", () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: true }));
16638
+ const dry = await step4(ctx, `Planning the draft ${slug} on ${instance}`, () => client.post("/write/create_portal", { ...createBody, updateSet: previewSet, dryRun: true }));
15502
16639
  createPlan = dry.plan || {};
15503
16640
  if (createSet && Array.isArray(createPlan.warnings))
15504
16641
  createPlan.warnings = createPlan.warnings.map((w) => /^Created in /.test(w) ? w.replace(/update set "[^"]*"/, `the new update set "${setName}"`) : w);
@@ -15614,7 +16751,7 @@ To seed it: ${hint}`);
15614
16751
  return;
15615
16752
  }
15616
16753
  if (ctx.interactive && !ctx.opts.yes) {
15617
- const go = answered(await p5.confirm({
16754
+ const go = answered(await p6.confirm({
15618
16755
  message: `Create the draft ${slug} and push the pack to ${key} (${app.scope}, "${setName}")?`,
15619
16756
  initialValue: false
15620
16757
  }));
@@ -15626,14 +16763,14 @@ To seed it: ${hint}`);
15626
16763
  }
15627
16764
  let createdSet = null;
15628
16765
  if (createSet) {
15629
- const made = await step3(ctx, `Creating the update set "${setName}"`, () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: false }));
16766
+ const made = await step4(ctx, `Creating the update set "${setName}"`, () => client.post("/write/create_update_set", { app: app.id, name: setName, dryRun: false }));
15630
16767
  createdSet = made.result && made.result.updateSet;
15631
16768
  if (!createdSet || !createdSet.id)
15632
16769
  throw new CliError(EXIT.failed, "update_set_failed", "The update set was not created");
15633
16770
  setRef = createdSet.id;
15634
16771
  }
15635
16772
  const requestId = o.requestId || randomUUID2();
15636
- const real = await step3(ctx, `Creating the draft ${slug}`, () => client.post("/write/create_portal", {
16773
+ const real = await step4(ctx, `Creating the draft ${slug}`, () => client.post("/write/create_portal", {
15637
16774
  ...createBody,
15638
16775
  updateSet: setRef,
15639
16776
  dryRun: false,
@@ -15644,7 +16781,7 @@ To seed it: ${hint}`);
15644
16781
  if (!created.id)
15645
16782
  throw new CliError(EXIT.failed, "create_failed", "The draft portal was not created", real);
15646
16783
  if (out) {
15647
- mkdirSync15(out, { recursive: true });
16784
+ mkdirSync16(out, { recursive: true });
15648
16785
  cpSync3(pack, out, {
15649
16786
  recursive: true,
15650
16787
  filter: (src) => {
@@ -15708,7 +16845,7 @@ async function pushPhase(ctx, client, ws, key, force, confirmed, planHash) {
15708
16845
  configure2(ws);
15709
16846
  let dry;
15710
16847
  try {
15711
- dry = await step3(ctx, `Planning the push of ${rel(ws)} to ${key}`, () => push(client, { workspace: ws, force, dryRun: true }));
16848
+ dry = await step4(ctx, `Planning the push of ${rel(ws)} to ${key}`, () => push(client, { workspace: ws, force, dryRun: true }));
15712
16849
  } catch (e) {
15713
16850
  const err = e;
15714
16851
  if (human)
@@ -15742,7 +16879,7 @@ async function pushPhase(ctx, client, ws, key, force, confirmed, planHash) {
15742
16879
  if (!ctx.interactive && !ctx.opts.yes)
15743
16880
  return { dry, real: null, stopped: "needs --yes" };
15744
16881
  if (ctx.interactive && !ctx.opts.yes) {
15745
- const go = answered(await p5.confirm({
16882
+ const go = answered(await p6.confirm({
15746
16883
  message: `Push ${c.creates} create(s) and ${c.updates} update(s) to ${key}?`,
15747
16884
  initialValue: false
15748
16885
  }));
@@ -15752,7 +16889,7 @@ async function pushPhase(ctx, client, ws, key, force, confirmed, planHash) {
15752
16889
  }
15753
16890
  let real;
15754
16891
  try {
15755
- real = await step3(ctx, `Pushing to ${key} (${plural(c.creates, "create")}, ${plural(c.updates, "update")})`, () => push(client, { workspace: ws, force, dryRun: false, planHash: dry.planHash }));
16892
+ real = await step4(ctx, `Pushing to ${key} (${plural(c.creates, "create")}, ${plural(c.updates, "update")})`, () => push(client, { workspace: ws, force, dryRun: false, planHash: dry.planHash }));
15756
16893
  } catch (e) {
15757
16894
  const err = e;
15758
16895
  real = { failed: { chunk: 0, of: 0, code: err.code, message: err.message || String(e) } };
@@ -15812,7 +16949,7 @@ function registerSeed(program, run) {
15812
16949
  const cmd = program.command("seed").argument("<pack>", "the app pack folder (portal.mjs, components/, themes/, assets/)").description("Put an app pack onto an instance that doesn't have its portal yet: preflight, one plan (the empty draft plus the push), then the draft and a force push, all in the target update set. Never publishes, never deletes; a re-run finishes or plans nothing").option("--app <scope>", "the owning application (default: portal.mjs's app)").option("--update-set <name>", "an in-progress update set of that application (name or sys_id)").option("--new-update-set [name]", 'create the update set (default "<Portal name> (React Portal)")').option("--slug <slug>", "the portal slug on the target (default: portal.mjs's)").option("--name <name>", "the portal name on the target (default: portal.mjs's)").option("--out <folder>", "seed a copy of the pack in this new folder (needed when the pack tracks another instance)").option("--plan-hash <hash>", "seed only if the plan is still this one (from an earlier run)").option("--request-id <id>", "idempotency key for the create: a retry with the same id replays");
15813
16950
  cmd.action(run((ctx) => seed(ctx, cmd.processedArgs[0], cmd.opts())));
15814
16951
  }
15815
- var HELPERS_SWITCH3 = "1.3.0", HELPERS_IMAGES2 = "1.6.0", HELPERS_UPDATE_SETS3 = "1.7.0", plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
16952
+ var HELPERS_SWITCH4 = "1.3.0", HELPERS_IMAGES2 = "1.6.0", HELPERS_UPDATE_SETS4 = "1.7.0", plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
15816
16953
  var init_seed2 = __esm(() => {
15817
16954
  init_client();
15818
16955
  init_compat();
@@ -15830,8 +16967,8 @@ var init_seed2 = __esm(() => {
15830
16967
  });
15831
16968
 
15832
16969
  // ../forge-core/src/update/update-check.ts
15833
- import { existsSync as existsSync29, mkdirSync as mkdirSync16, readFileSync as readFileSync31, renameSync as renameSync4, writeFileSync as writeFileSync16 } from "node:fs";
15834
- import { dirname as dirname16, join as join30, sep as sep7 } from "node:path";
16970
+ import { existsSync as existsSync32, mkdirSync as mkdirSync17, readFileSync as readFileSync32, renameSync as renameSync4, writeFileSync as writeFileSync18 } from "node:fs";
16971
+ import { dirname as dirname17, join as join33, sep as sep7 } from "node:path";
15835
16972
  function parse2(v) {
15836
16973
  const m = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(v).trim());
15837
16974
  if (!m)
@@ -15880,14 +17017,14 @@ function isNewer(current, latest) {
15880
17017
  return compareVersions(current, latest) < 0;
15881
17018
  }
15882
17019
  function cacheFile(home) {
15883
- return join30(home, "update-check.json");
17020
+ return join33(home, "update-check.json");
15884
17021
  }
15885
17022
  function readCache(home) {
15886
17023
  const f = cacheFile(home);
15887
- if (!existsSync29(f))
17024
+ if (!existsSync32(f))
15888
17025
  return null;
15889
17026
  try {
15890
- const v = JSON.parse(readFileSync31(f, "utf8"));
17027
+ const v = JSON.parse(readFileSync32(f, "utf8"));
15891
17028
  if (!v || typeof v.checkedAt !== "number" || !isFinite(v.checkedAt))
15892
17029
  return null;
15893
17030
  return { checkedAt: v.checkedAt, latest: typeof v.latest === "string" ? v.latest : null };
@@ -15897,9 +17034,9 @@ function readCache(home) {
15897
17034
  }
15898
17035
  function writeCache(home, c) {
15899
17036
  const f = cacheFile(home);
15900
- mkdirSync16(dirname16(f), { recursive: true });
17037
+ mkdirSync17(dirname17(f), { recursive: true });
15901
17038
  const tmp = `${f}.${process.pid}.tmp`;
15902
- writeFileSync16(tmp, JSON.stringify(c) + `
17039
+ writeFileSync18(tmp, JSON.stringify(c) + `
15903
17040
  `);
15904
17041
  renameSync4(tmp, f);
15905
17042
  }
@@ -15993,7 +17130,7 @@ var init_update_check = __esm(() => {
15993
17130
  });
15994
17131
 
15995
17132
  // src/commands/update.ts
15996
- import { spawn as spawn4, spawnSync as spawnSync7 } from "node:child_process";
17133
+ import { spawn as spawn4, spawnSync as spawnSync8 } from "node:child_process";
15997
17134
  import { realpathSync } from "node:fs";
15998
17135
  function entryPath() {
15999
17136
  try {
@@ -16116,7 +17253,7 @@ async function update(ctx, o) {
16116
17253
  return;
16117
17254
  }
16118
17255
  ctx.out.info(`Running: ${cmd.text}`);
16119
- const r = spawnSync7(cmd.cmd, cmd.args, { stdio: ctx.opts.json ? "ignore" : "inherit", shell: true });
17256
+ const r = spawnSync8(cmd.cmd, cmd.args, { stdio: ctx.opts.json ? "ignore" : "inherit", shell: true });
16120
17257
  if (r.status !== 0)
16121
17258
  throw new CliError(EXIT.failed, "update_failed", `The install command failed (exit ${r.status}): ${cmd.text}`);
16122
17259
  ctx.out.line(`Updated to rpf ${latest}.`);
@@ -16133,10 +17270,10 @@ var init_update = __esm(() => {
16133
17270
  });
16134
17271
 
16135
17272
  // src/commands/preview.ts
16136
- import { writeFileSync as writeFileSync17 } from "node:fs";
16137
- import { resolve as resolve12 } from "node:path";
17273
+ import { writeFileSync as writeFileSync19 } from "node:fs";
17274
+ import { resolve as resolve13 } from "node:path";
16138
17275
  async function preview(ctx, route, o) {
16139
- const ws = findWorkspace(ctx.opts.dir ? resolve12(ctx.opts.dir) : process.cwd());
17276
+ const ws = findWorkspace(ctx.opts.dir ? resolve13(ctx.opts.dir) : process.cwd());
16140
17277
  if (!ws)
16141
17278
  throw usage("No workspace here: cd into one (a folder with forge.workspace.json) or pass --dir");
16142
17279
  const session = readDevSession(ws);
@@ -16160,8 +17297,8 @@ async function preview(ctx, route, o) {
16160
17297
  const out = { ...report, gen: status ? status.gen : undefined };
16161
17298
  if (o.screenshot) {
16162
17299
  const png = await page.screenshot({ fullPage: !!o.fullPage });
16163
- writeFileSync17(resolve12(o.screenshot), Buffer.from(png, "base64"));
16164
- out.screenshot = resolve12(o.screenshot);
17300
+ writeFileSync19(resolve13(o.screenshot), Buffer.from(png, "base64"));
17301
+ out.screenshot = resolve13(o.screenshot);
16165
17302
  }
16166
17303
  if (o.a11y)
16167
17304
  out.accessibility = await page.accessibility();
@@ -16199,7 +17336,7 @@ var init_preview = __esm(() => {
16199
17336
 
16200
17337
  // src/commands/forge-profiles.ts
16201
17338
  import { randomBytes as randomBytes5 } from "node:crypto";
16202
- import { existsSync as existsSync30 } from "node:fs";
17339
+ import { existsSync as existsSync33 } from "node:fs";
16203
17340
  function openStore() {
16204
17341
  try {
16205
17342
  return { store: new CredentialStore, problem: "" };
@@ -16304,7 +17441,7 @@ function makeProfiles() {
16304
17441
  if (!instance)
16305
17442
  throw new Error("Instance: a name (dev12345) or URL");
16306
17443
  for (const f of ["cert", "key", "ca"])
16307
- if (o[f] && !existsSync30(o[f]))
17444
+ if (o[f] && !existsSync33(o[f]))
16308
17445
  throw new Error(`${f}: no file at ${o[f]}`);
16309
17446
  const profiles = readProfiles();
16310
17447
  const oldName = o.replaces && profiles.profiles[o.replaces] ? o.replaces : o.name;
@@ -16525,14 +17662,14 @@ var init_forge_profiles = __esm(() => {
16525
17662
  });
16526
17663
 
16527
17664
  // src/commands/forge-create.ts
16528
- import { existsSync as existsSync31, mkdirSync as mkdirSync17, readdirSync as readdirSync10, writeFileSync as writeFileSync18 } from "node:fs";
16529
- import { dirname as dirname17, join as join31, resolve as resolve13 } from "node:path";
17665
+ import { existsSync as existsSync34, mkdirSync as mkdirSync18, readdirSync as readdirSync12, writeFileSync as writeFileSync20 } from "node:fs";
17666
+ import { dirname as dirname18, join as join34, resolve as resolve14 } from "node:path";
16530
17667
  import { randomUUID as randomUUID3 } from "node:crypto";
16531
- import { spawnSync as spawnSync8 } from "node:child_process";
17668
+ import { spawnSync as spawnSync9 } from "node:child_process";
16532
17669
  function refusal(code, message) {
16533
17670
  return Object.assign(new Error(message), { code });
16534
17671
  }
16535
- function cmpVersion4(a, b) {
17672
+ function cmpVersion5(a, b) {
16536
17673
  const pa = a.split(".").map((n) => parseInt(n, 10) || 0);
16537
17674
  const pb = b.split(".").map((n) => parseInt(n, 10) || 0);
16538
17675
  for (let i = 0;i < 3; i++)
@@ -16548,14 +17685,14 @@ function clientFor(profile) {
16548
17685
  return { client: new ForgeClient(r.config), instance: r.config.instance };
16549
17686
  }
16550
17687
  function isEmptyDir3(dir) {
16551
- return !existsSync31(dir) || readdirSync10(dir).length === 0;
17688
+ return !existsSync34(dir) || readdirSync12(dir).length === 0;
16552
17689
  }
16553
17690
  function insideGitRepo2(dir) {
16554
- let d = resolve13(dir);
17691
+ let d = resolve14(dir);
16555
17692
  for (;; ) {
16556
- if (existsSync31(join31(d, ".git")))
17693
+ if (existsSync34(join34(d, ".git")))
16557
17694
  return true;
16558
- const up = dirname17(d);
17695
+ const up = dirname18(d);
16559
17696
  if (up === d)
16560
17697
  return false;
16561
17698
  d = up;
@@ -16570,40 +17707,40 @@ function groupCounts2(creates) {
16570
17707
  return Object.entries(counts);
16571
17708
  }
16572
17709
  async function pullInto(client, o, step) {
16573
- mkdirSync17(o.folder, { recursive: true });
17710
+ mkdirSync18(o.folder, { recursive: true });
16574
17711
  configureWorkspace({
16575
17712
  repo: "",
16576
- apps: dirname17(o.folder),
17713
+ apps: dirname18(o.folder),
16577
17714
  prettierConfigFrom: o.extras.prettierrc ? "" : prettierConfigFor(o.folder),
16578
17715
  tsc: "",
16579
17716
  hostTypes: "",
16580
17717
  typesFrom: ""
16581
17718
  });
16582
- step(`Pulling ${o.portal} into ${o.folder}`);
17719
+ step(`Pulling ${o.portal || (o.components || []).join(", ") || "the component workspace"} into ${o.folder}`);
16583
17720
  const pulled = await pull(client, {
16584
- portal: o.portal,
17721
+ ...o.portal ? { portal: o.portal } : { app: o.app, components: o.components || [] },
16585
17722
  out: o.folder,
16586
17723
  updateSet: o.updateSet,
16587
17724
  mode: o.retry ? "auto" : "fresh"
16588
17725
  });
16589
17726
  const files = [];
16590
17727
  if (o.extras.prettierrc) {
16591
- writeFileSync18(join31(o.folder, ".prettierrc.json"), prettierrcText());
17728
+ writeFileSync20(join34(o.folder, ".prettierrc.json"), prettierrcText());
16592
17729
  files.push(".prettierrc.json");
16593
17730
  }
16594
17731
  if (o.extras.gitignore) {
16595
- writeFileSync18(join31(o.folder, ".gitignore"), `.forge/
17732
+ writeFileSync20(join34(o.folder, ".gitignore"), `.forge/
16596
17733
  node_modules/
16597
17734
  `);
16598
17735
  files.push(".gitignore");
16599
17736
  }
16600
17737
  if (o.extras.readme && o.readme) {
16601
- writeFileSync18(join31(o.folder, "README.md"), o.readme);
17738
+ writeFileSync20(join34(o.folder, "README.md"), o.readme);
16602
17739
  files.push("README.md");
16603
17740
  }
16604
17741
  if (o.extras.git) {
16605
17742
  step("git init");
16606
- const g = spawnSync8("git", ["init", "-q"], { cwd: o.folder, encoding: "utf8" });
17743
+ const g = spawnSync9("git", ["init", "-q"], { cwd: o.folder, encoding: "utf8" });
16607
17744
  if (g.status === 0)
16608
17745
  files.push(".git/");
16609
17746
  else
@@ -16612,7 +17749,7 @@ node_modules/
16612
17749
  if (o.extras.skills) {
16613
17750
  step("Installing the agent skills");
16614
17751
  try {
16615
- const r = syncSkills(join31(nearestProject(o.folder), ".claude", "skills"), { mode: "install" });
17752
+ const r = syncSkills(join34(nearestProject(o.folder), ".claude", "skills"), { mode: "install" });
16616
17753
  files.push(`${r.root} (${r.skills.map((s) => s.name).join(", ")})`);
16617
17754
  } catch (e) {
16618
17755
  step(`skills install failed: ${e.message || e}`);
@@ -16662,8 +17799,8 @@ function makeCreate() {
16662
17799
  if (compat.state === "unknown" || compat.state === "too-old")
16663
17800
  throw refusal("incompatible", compat.state === "unknown" ? `${instance} runs a React Portal without the Forge API handshake: a newer React Portal is needed` : compat.message);
16664
17801
  const helpers = String(status.globalHelpers || "");
16665
- if (!helpers || cmpVersion4(helpers, HELPERS_SWITCH4) < 0)
16666
- throw refusal("helper_missing", `React Portal Global Helpers ${HELPERS_SWITCH4}+ is needed on ${instance} (found ${helpers || "none"})`);
17802
+ if (!helpers || cmpVersion5(helpers, HELPERS_SWITCH5) < 0)
17803
+ throw refusal("helper_missing", `React Portal Global Helpers ${HELPERS_SWITCH5}+ is needed on ${instance} (found ${helpers || "none"})`);
16667
17804
  const apps = (await client.get("/apps", { list: "authoring" })).apps || [];
16668
17805
  if (!apps.length)
16669
17806
  throw refusal("no_apps", `${status.user} can't author in any scoped application on ${instance}`);
@@ -16673,7 +17810,8 @@ function makeCreate() {
16673
17810
  reactPortal: status.version || status.reactPortal || "",
16674
17811
  capabilities: status.capabilities,
16675
17812
  warning: compat.state === "too-new" ? compat.message : "",
16676
- canCreateSets: cmpVersion4(helpers, HELPERS_UPDATE_SETS4) >= 0,
17813
+ canCreateSets: cmpVersion5(helpers, HELPERS_UPDATE_SETS5) >= 0,
17814
+ componentWorkspaces: Array.isArray(status.features) && status.features.includes(COMPONENT_FEATURE),
16677
17815
  apps
16678
17816
  };
16679
17817
  },
@@ -16684,7 +17822,7 @@ function makeCreate() {
16684
17822
  layouts: async (profile) => await clientFor(profile).client.get("/components", { kind: "layout" }),
16685
17823
  slugAvailable: async (profile, slug) => await clientFor(profile).client.get("/portals/slug-available", { slug }),
16686
17824
  brandTheme: async (th) => brandTokens(th),
16687
- defaults: (folder) => ({ empty: isEmptyDir3(folder), inRepo: insideGitRepo2(dirname17(folder)) }),
17825
+ defaults: (folder) => ({ empty: isEmptyDir3(folder), inRepo: insideGitRepo2(dirname18(folder)) }),
16688
17826
  slugFromName,
16689
17827
  plan: async (profile, a, o) => {
16690
17828
  const problems = [...answersProblems(a), ...invalidAnswers(a)];
@@ -16775,12 +17913,12 @@ function makeCreate() {
16775
17913
  }, step);
16776
17914
  pulled = r.pull;
16777
17915
  files = r.files;
16778
- mkdirSync17(join31(o.folder, ".forge"), { recursive: true });
17916
+ mkdirSync18(join34(o.folder, ".forge"), { recursive: true });
16779
17917
  const saved = JSON.parse(JSON.stringify(a));
16780
17918
  delete saved.folder;
16781
17919
  if (typeof saved.updateSet === "object")
16782
17920
  saved.updateSet = set.name;
16783
- writeFileSync18(join31(o.folder, ".forge", "init-answers.json"), JSON.stringify(saved, null, 4) + `
17921
+ writeFileSync20(join34(o.folder, ".forge", "init-answers.json"), JSON.stringify(saved, null, 4) + `
16784
17922
  `);
16785
17923
  } catch (e) {
16786
17924
  pullError = e.message || String(e);
@@ -16796,6 +17934,54 @@ function makeCreate() {
16796
17934
  pullError: pullError || undefined
16797
17935
  };
16798
17936
  },
17937
+ components: async (profile, appId) => {
17938
+ const { client } = clientFor(profile);
17939
+ const rows = await client.tableRead("x_312987_portal_component", `sys_scope=${appId}^active=true^ORDERBYunique_id`, ["unique_id", "name", "kind"], 500);
17940
+ return rows.map((r) => ({ uniqueId: r.unique_id, name: r.name, kind: r.kind }));
17941
+ },
17942
+ componentWorkspace: async (profile, o, step) => {
17943
+ if (!isEmptyDir3(o.folder))
17944
+ throw refusal("folder_not_empty", `${o.folder} is not empty: pick an empty or new folder`);
17945
+ const { client, instance } = clientFor(profile);
17946
+ let setRef = typeof o.updateSet === "string" ? o.updateSet : "";
17947
+ let createdSet = null;
17948
+ if (typeof o.updateSet === "object") {
17949
+ step(`Creating the update set "${o.updateSet.create}"`);
17950
+ const made = await client.post("/write/create_update_set", {
17951
+ app: o.app,
17952
+ name: o.updateSet.create,
17953
+ dryRun: false
17954
+ });
17955
+ createdSet = made.result && made.result.updateSet;
17956
+ if (!createdSet || !createdSet.id)
17957
+ throw refusal("update_set_failed", "The update set was not created");
17958
+ setRef = createdSet.id;
17959
+ }
17960
+ const r = await pullInto(client, {
17961
+ app: o.app,
17962
+ components: o.components,
17963
+ folder: o.folder,
17964
+ updateSet: setRef,
17965
+ extras: o.extras,
17966
+ readme: `# Components
17967
+
17968
+ A React Portal component workspace on ${instance}. Pushes write into the update set recorded in forge.workspace.json.
17969
+
17970
+ ` + "```bash\nrpf dev # the component stage\nrpf status # what changed, here and on the instance\nrpf push # dry run, then the confirmed push\n```\n"
17971
+ }, step);
17972
+ const files = r.files.slice();
17973
+ if (o.newComponent) {
17974
+ step(`Scaffolding ${o.newComponent.id}`);
17975
+ files.push(...await writeNewComponent(o.folder, o.newComponent.id, o.newComponent.kind));
17976
+ }
17977
+ return {
17978
+ kind: "component",
17979
+ folder: o.folder,
17980
+ updateSet: createdSet || r.pull.updateSet,
17981
+ pull: r.pull,
17982
+ files
17983
+ };
17984
+ },
16799
17985
  pull: async (profile, o, step) => {
16800
17986
  if (!o.retry && !isEmptyDir3(o.folder))
16801
17987
  throw refusal("folder_not_empty", `${o.folder} is not empty: pick an empty or new folder`);
@@ -16805,8 +17991,10 @@ function makeCreate() {
16805
17991
  }
16806
17992
  };
16807
17993
  }
16808
- var HELPERS_SWITCH4 = "1.3.0", HELPERS_UPDATE_SETS4 = "1.7.0";
17994
+ var HELPERS_SWITCH5 = "1.3.0", HELPERS_UPDATE_SETS5 = "1.7.0";
16809
17995
  var init_forge_create = __esm(() => {
17996
+ init_new();
17997
+ init_init_component();
16810
17998
  init_client();
16811
17999
  init_compat();
16812
18000
  init_config();
@@ -16820,18 +18008,18 @@ var init_forge_create = __esm(() => {
16820
18008
  });
16821
18009
 
16822
18010
  // src/commands/forge.ts
16823
- import { existsSync as existsSync32 } from "node:fs";
16824
- import { basename as basename2, dirname as dirname18, join as join32, resolve as resolve14 } from "node:path";
18011
+ import { existsSync as existsSync35 } from "node:fs";
18012
+ import { basename as basename2, dirname as dirname19, join as join35, resolve as resolve15 } from "node:path";
16825
18013
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
16826
18014
  import { spawn as spawn5 } from "node:child_process";
16827
18015
  function forgeAssets() {
16828
- const here = dirname18(fileURLToPath3(import.meta.url));
18016
+ const here = dirname19(fileURLToPath3(import.meta.url));
16829
18017
  if (basename2(here) === "commands") {
16830
- const app = resolve14(here, "..", "..", "..", "forge-app");
16831
- return { server: join32(app, "src", "server", "index.ts"), appDir: join32(app, "dist", "app"), fromSource: true };
18018
+ const app = resolve15(here, "..", "..", "..", "forge-app");
18019
+ return { server: join35(app, "src", "server", "index.ts"), appDir: join35(app, "dist", "app"), fromSource: true };
16832
18020
  }
16833
- const assets = join32(here, "..", "assets", "forge-app");
16834
- return { server: join32(assets, "server.mjs"), appDir: join32(assets, "app"), fromSource: false };
18021
+ const assets = join35(here, "..", "assets", "forge-app");
18022
+ return { server: join35(assets, "server.mjs"), appDir: join35(assets, "app"), fromSource: false };
16835
18023
  }
16836
18024
  function makeForgeCore() {
16837
18025
  const home = rpforgeHome();
@@ -16841,7 +18029,7 @@ function makeForgeCore() {
16841
18029
  } catch {
16842
18030
  store = null;
16843
18031
  }
16844
- const here = dirname18(fileURLToPath3(import.meta.url));
18032
+ const here = dirname19(fileURLToPath3(import.meta.url));
16845
18033
  const fromSource = basename2(here) === "commands";
16846
18034
  return {
16847
18035
  version: VERSION,
@@ -16884,12 +18072,12 @@ function makeForgeCore() {
16884
18072
  workspace: {
16885
18073
  status: async (dir) => {
16886
18074
  const client = workspaceClient(dir);
16887
- configure(dirname18(dir), dir);
18075
+ configure(dirname19(dir), dir);
16888
18076
  return status2(client, { workspace: dir });
16889
18077
  },
16890
18078
  check: async (dir) => {
16891
18079
  const client = workspaceClient(dir);
16892
- configure(dirname18(dir), dir);
18080
+ configure(dirname19(dir), dir);
16893
18081
  return check(client, {
16894
18082
  workspace: dir,
16895
18083
  force: false,
@@ -16900,17 +18088,17 @@ function makeForgeCore() {
16900
18088
  },
16901
18089
  push: async (dir, args) => {
16902
18090
  const client = workspaceClient(dir);
16903
- configure(dirname18(dir), dir);
18091
+ configure(dirname19(dir), dir);
16904
18092
  return push(client, { workspace: dir, ...args });
16905
18093
  },
16906
18094
  diff: async (dir, keys) => {
16907
18095
  const client = workspaceClient(dir);
16908
- configure(dirname18(dir), dir);
18096
+ configure(dirname19(dir), dir);
16909
18097
  return diff(client, { workspace: dir, keys, against: "auto" });
16910
18098
  },
16911
18099
  resolve: async (dir, keys, action) => {
16912
18100
  const client = workspaceClient(dir);
16913
- configure(dirname18(dir), dir);
18101
+ configure(dirname19(dir), dir);
16914
18102
  return resolveEntries(client, { workspace: dir, keys, action });
16915
18103
  }
16916
18104
  },
@@ -16939,7 +18127,7 @@ function makeForgeCore() {
16939
18127
  onBrowserWrite: extra?.onBrowserWrite
16940
18128
  });
16941
18129
  },
16942
- mcpCommand: () => fromSource ? { command: process.execPath, args: ["run", resolve14(here, "..", "cli.ts"), "mcp"] } : { command: process.execPath, args: [resolve14(here, "cli.mjs"), "mcp"] },
18130
+ mcpCommand: () => fromSource ? { command: process.execPath, args: ["run", resolve15(here, "..", "cli.ts"), "mcp"] } : { command: process.execPath, args: [resolve15(here, "cli.mjs"), "mcp"] },
16943
18131
  agentGuide: () => readGuide("react-portal/SKILL.md") || "",
16944
18132
  skillsDir: () => {
16945
18133
  try {
@@ -16967,10 +18155,10 @@ function openBrowser4(url) {
16967
18155
  }
16968
18156
  async function forge(ctx, dir, o) {
16969
18157
  const a = forgeAssets();
16970
- if (!existsSync32(a.server) || !existsSync32(join32(a.appDir, "index.html")))
18158
+ if (!existsSync35(a.server) || !existsSync35(join35(a.appDir, "index.html")))
16971
18159
  throw new CliError(EXIT.failed, "forge_app_missing", a.fromSource ? "The Forge app is not built: run `bun run build` in packages/forge-app" : "The Forge app is missing from this install: reinstall rpf");
16972
18160
  const target = dir || ctx.opts.dir;
16973
- const open = target ? resolve14(target) : findWorkspace(process.cwd()) || undefined;
18161
+ const open = target ? resolve15(target) : findWorkspace(process.cwd()) || undefined;
16974
18162
  const mod = await import(pathToFileURL(a.server).href);
16975
18163
  const server = await mod.startForge({
16976
18164
  core: makeForgeCore(),