@quixomatic/rpf 0.2.0 → 0.3.1

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 (133) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/assets/dev-host/kit-manifest.json +1 -1
  3. package/assets/forge-app/THIRD_PARTY_NOTICES.txt +5283 -0
  4. package/assets/forge-app/app/assets/_forge-shiki-langs-DaJjT17w.js +2 -0
  5. package/assets/forge-app/app/assets/andromeeda-CWX9QkEw.js +1 -0
  6. package/assets/forge-app/app/assets/appendItems-CWJJlOE7.js +10 -0
  7. package/assets/forge-app/app/assets/aurora-x-C7LW0A0Z.js +1 -0
  8. package/assets/forge-app/app/assets/ayu-dark-UyEq0fEv.js +1 -0
  9. package/assets/forge-app/app/assets/ayu-light-BGLrZRfL.js +1 -0
  10. package/assets/forge-app/app/assets/ayu-mirage-DU2uuvme.js +1 -0
  11. package/assets/forge-app/app/assets/catppuccin-frappe-Ba2J56Xe.js +1 -0
  12. package/assets/forge-app/app/assets/catppuccin-latte-Du_f_kXm.js +1 -0
  13. package/assets/forge-app/app/assets/catppuccin-macchiato-DAr1oMDX.js +1 -0
  14. package/assets/forge-app/app/assets/catppuccin-mocha-F6YLrtz0.js +1 -0
  15. package/assets/forge-app/app/assets/core-Dl2d1S-D.js +12 -0
  16. package/assets/forge-app/app/assets/css-C8fQr_0Q.js +1 -0
  17. package/assets/forge-app/app/assets/dark-plus-2IOGu4uA.js +1 -0
  18. package/assets/forge-app/app/assets/diff-view-Chujmqzi.js +28 -0
  19. package/assets/forge-app/app/assets/diff-woXpYk--.js +1 -0
  20. package/assets/forge-app/app/assets/dracula-DZjgIiCY.js +1 -0
  21. package/assets/forge-app/app/assets/dracula-soft-Buj7Kmgw.js +1 -0
  22. package/assets/forge-app/app/assets/engine-javascript-C4Jk_eU2.js +141 -0
  23. package/assets/forge-app/app/assets/engine-oniguruma-D--T0LcV.js +1 -0
  24. package/assets/forge-app/app/assets/everforest-dark-Lvcw1Pr0.js +1 -0
  25. package/assets/forge-app/app/assets/everforest-light-YrYDdHjZ.js +1 -0
  26. package/assets/forge-app/app/assets/file-panel-le_M5nHe.js +1199 -0
  27. package/assets/forge-app/app/assets/formatCSSVariablePrefix-KRh9vnZf.js +1 -0
  28. package/assets/forge-app/app/assets/github-dark-CdJXf8Kw.js +1 -0
  29. package/assets/forge-app/app/assets/github-dark-default-BqPxBNAT.js +1 -0
  30. package/assets/forge-app/app/assets/github-dark-dimmed-DyY5b2F0.js +1 -0
  31. package/assets/forge-app/app/assets/github-dark-high-contrast-xd2ezW53.js +1 -0
  32. package/assets/forge-app/app/assets/github-light-CX58plA4.js +1 -0
  33. package/assets/forge-app/app/assets/github-light-default-DKbnGXTT.js +1 -0
  34. package/assets/forge-app/app/assets/github-light-high-contrast-uBB_OJ7x.js +1 -0
  35. package/assets/forge-app/app/assets/gruvbox-dark-hard-4xwr00-8.js +1 -0
  36. package/assets/forge-app/app/assets/gruvbox-dark-medium-CpS6Oukh.js +1 -0
  37. package/assets/forge-app/app/assets/gruvbox-dark-soft-CgQlpZ36.js +1 -0
  38. package/assets/forge-app/app/assets/gruvbox-light-hard-o8ZwY_jI.js +1 -0
  39. package/assets/forge-app/app/assets/gruvbox-light-medium-BOAI5TwH.js +1 -0
  40. package/assets/forge-app/app/assets/gruvbox-light-soft-DYjh34qH.js +1 -0
  41. package/assets/forge-app/app/assets/highlights-BxaWC1ve.js +7 -0
  42. package/assets/forge-app/app/assets/horizon-BJ3G7U7Q.js +1 -0
  43. package/assets/forge-app/app/assets/horizon-bright-onknclPd.js +1 -0
  44. package/assets/forge-app/app/assets/houston-CzdgljLR.js +1 -0
  45. package/assets/forge-app/app/assets/html-wSbaAAK3.js +1 -0
  46. package/assets/forge-app/app/assets/index-BwYJlfwT.css +1 -0
  47. package/assets/forge-app/app/assets/index-UP3KtgHV.js +291 -0
  48. package/assets/forge-app/app/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  49. package/assets/forge-app/app/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  50. package/assets/forge-app/app/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  51. package/assets/forge-app/app/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  52. package/assets/forge-app/app/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  53. package/assets/forge-app/app/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  54. package/assets/forge-app/app/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  55. package/assets/forge-app/app/assets/javascript-BgS3c2Ky.js +1 -0
  56. package/assets/forge-app/app/assets/json-qhed-kSA.js +1 -0
  57. package/assets/forge-app/app/assets/jsonc-CYpm1nAK.js +1 -0
  58. package/assets/forge-app/app/assets/jsx-Bz0zcwM4.js +1 -0
  59. package/assets/forge-app/app/assets/kanagawa-dragon-BQVheBBo.js +1 -0
  60. package/assets/forge-app/app/assets/kanagawa-lotus-CPemrbqC.js +1 -0
  61. package/assets/forge-app/app/assets/kanagawa-wave-CoCEno9V.js +1 -0
  62. package/assets/forge-app/app/assets/laserwave-B5bEuTwe.js +1 -0
  63. package/assets/forge-app/app/assets/lib-BOh9Tw1y.js +1 -0
  64. package/assets/forge-app/app/assets/light-plus-BZZlmvcU.js +1 -0
  65. package/assets/forge-app/app/assets/loader-BMv9OYvr.js +1 -0
  66. package/assets/forge-app/app/assets/markdown-BYOwaDjH.js +1 -0
  67. package/assets/forge-app/app/assets/material-theme-aeHmkUm6.js +1 -0
  68. package/assets/forge-app/app/assets/material-theme-darker-0axHxn5k.js +1 -0
  69. package/assets/forge-app/app/assets/material-theme-lighter-BsSyB7lm.js +1 -0
  70. package/assets/forge-app/app/assets/material-theme-ocean-BVrhCaVf.js +1 -0
  71. package/assets/forge-app/app/assets/material-theme-palenight-C7ZR4CGM.js +1 -0
  72. package/assets/forge-app/app/assets/min-dark-BKaXaz6D.js +1 -0
  73. package/assets/forge-app/app/assets/min-light-CF3GufC7.js +1 -0
  74. package/assets/forge-app/app/assets/monokai-CkP2YA7x.js +1 -0
  75. package/assets/forge-app/app/assets/night-owl-BWMbd2rn.js +1 -0
  76. package/assets/forge-app/app/assets/night-owl-light-C_TsrL-a.js +1 -0
  77. package/assets/forge-app/app/assets/nord-62p94tpv.js +1 -0
  78. package/assets/forge-app/app/assets/one-dark-pro-DUBUnUMB.js +1 -0
  79. package/assets/forge-app/app/assets/one-light-CqcpbeDc.js +1 -0
  80. package/assets/forge-app/app/assets/pierre-dark-CFuQzxDG.js +1 -0
  81. package/assets/forge-app/app/assets/pierre-dark-DMS-zpcK.js +1 -0
  82. package/assets/forge-app/app/assets/pierre-dark-protanopia-deuteranopia-BSiWRjoV.js +1 -0
  83. package/assets/forge-app/app/assets/pierre-dark-protanopia-deuteranopia-Ddq4E1VN.js +1 -0
  84. package/assets/forge-app/app/assets/pierre-dark-soft-BMbLOt5W.js +1 -0
  85. package/assets/forge-app/app/assets/pierre-dark-soft-BUesjllf.js +1 -0
  86. package/assets/forge-app/app/assets/pierre-dark-tritanopia-BGSLfXJy.js +1 -0
  87. package/assets/forge-app/app/assets/pierre-dark-tritanopia-CX9_YYVl.js +1 -0
  88. package/assets/forge-app/app/assets/pierre-dark-vibrant-Dlj8tZff.js +1 -0
  89. package/assets/forge-app/app/assets/pierre-dark-vibrant-bYj7HUnF.js +1 -0
  90. package/assets/forge-app/app/assets/pierre-light-BHq6aQNU.js +1 -0
  91. package/assets/forge-app/app/assets/pierre-light-DGR1TxHn.js +1 -0
  92. package/assets/forge-app/app/assets/pierre-light-protanopia-deuteranopia-ChtB5hGy.js +1 -0
  93. package/assets/forge-app/app/assets/pierre-light-protanopia-deuteranopia-xNu39ZI5.js +1 -0
  94. package/assets/forge-app/app/assets/pierre-light-soft-BmBpKxVJ.js +1 -0
  95. package/assets/forge-app/app/assets/pierre-light-soft-DTxn6Rur.js +1 -0
  96. package/assets/forge-app/app/assets/pierre-light-tritanopia-DF_s91q9.js +1 -0
  97. package/assets/forge-app/app/assets/pierre-light-tritanopia-DyKDz8Fz.js +1 -0
  98. package/assets/forge-app/app/assets/pierre-light-vibrant-BEba13rj.js +1 -0
  99. package/assets/forge-app/app/assets/pierre-light-vibrant-DsCzsubQ.js +1 -0
  100. package/assets/forge-app/app/assets/plastic-baAbzXTu.js +1 -0
  101. package/assets/forge-app/app/assets/poimandres-64TexMzA.js +1 -0
  102. package/assets/forge-app/app/assets/red-cnNTP7m6.js +1 -0
  103. package/assets/forge-app/app/assets/rose-pine-Dcg36Rqi.js +1 -0
  104. package/assets/forge-app/app/assets/rose-pine-dawn-Sx7X9we0.js +1 -0
  105. package/assets/forge-app/app/assets/rose-pine-moon-CoglSunF.js +1 -0
  106. package/assets/forge-app/app/assets/shellscript-CLZ0U2zV.js +1 -0
  107. package/assets/forge-app/app/assets/shiki-CoRI3zWj.js +2 -0
  108. package/assets/forge-app/app/assets/slack-dark-C86YGzJx.js +1 -0
  109. package/assets/forge-app/app/assets/slack-ochin-DPmXYTYk.js +1 -0
  110. package/assets/forge-app/app/assets/snazzy-light-BD8dOedc.js +1 -0
  111. package/assets/forge-app/app/assets/solarized-dark-Bs7TdbJI.js +1 -0
  112. package/assets/forge-app/app/assets/solarized-light-DXYdl5LH.js +1 -0
  113. package/assets/forge-app/app/assets/stream-tokenizer-BMtK_3oz.js +4 -0
  114. package/assets/forge-app/app/assets/synthwave-84-JFh1mrS8.js +1 -0
  115. package/assets/forge-app/app/assets/terminal-view-BrP-ENHg.css +1 -0
  116. package/assets/forge-app/app/assets/terminal-view-D3CiLjfu.js +16 -0
  117. package/assets/forge-app/app/assets/themes-CLX9vH7e.js +2 -0
  118. package/assets/forge-app/app/assets/tokyo-night-BLjaCl8e.js +1 -0
  119. package/assets/forge-app/app/assets/tsx-udAQXfEw.js +1 -0
  120. package/assets/forge-app/app/assets/typescript-bsJCZSQ-.js +1 -0
  121. package/assets/forge-app/app/assets/useNextRenderData-dgMkjxGZ.js +149 -0
  122. package/assets/forge-app/app/assets/utils-C9Glzetk.js +2 -0
  123. package/assets/forge-app/app/assets/vesper-DZzlHXr_.js +1 -0
  124. package/assets/forge-app/app/assets/vitesse-black-BRf870Fc.js +1 -0
  125. package/assets/forge-app/app/assets/vitesse-dark-B9ZPQf4u.js +1 -0
  126. package/assets/forge-app/app/assets/vitesse-light-1s3aLQn3.js +1 -0
  127. package/assets/forge-app/app/assets/wasm-4KdTHw0F.js +1 -0
  128. package/assets/forge-app/app/assets/yaml-rwi0_p6S.js +1 -0
  129. package/assets/forge-app/app/favicon.svg +1 -0
  130. package/assets/forge-app/app/index.html +23 -0
  131. package/assets/forge-app/server.mjs +87314 -0
  132. package/dist/cli.mjs +936 -5
  133. package/package.json +3 -1
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // rpforge 0.2.0 (MIT). Built from packages/rpforge, packages/forge-core and packages/forge-mcp.
2
+ // rpforge 0.3.1 (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) {
@@ -1122,7 +1122,7 @@ var package_default;
1122
1122
  var init_package = __esm(() => {
1123
1123
  package_default = {
1124
1124
  name: "@quixomatic/rpf",
1125
- version: "0.2.0",
1125
+ version: "0.3.1",
1126
1126
  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
1127
  type: "module",
1128
1128
  license: "MIT",
@@ -1168,7 +1168,9 @@ var init_package = __esm(() => {
1168
1168
  "release:cli": "bun run scripts/release-cli.ts"
1169
1169
  },
1170
1170
  dependencies: {
1171
+ "@anthropic-ai/claude-agent-sdk": "0.3.332",
1171
1172
  "@clack/prompts": "1.9.0",
1173
+ "@lydell/node-pty": "1.1.0",
1172
1174
  "@modelcontextprotocol/sdk": "1.32.2",
1173
1175
  "@napi-rs/keyring": "2.1.2",
1174
1176
  ajv: "8.17.1",
@@ -3777,6 +3779,8 @@ async function startDevServer(o) {
3777
3779
  }
3778
3780
  const secret = !o.newKey && /^[0-9a-f]{64}$/.test(String(saved.key || "")) ? String(saved.key) : randomBytes4(32).toString("hex");
3779
3781
  const library = new Library(o.client, join13(forgeDir, "dev", "lib"));
3782
+ const ancestors = (o.frameAncestors || []).filter((x) => /^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(x));
3783
+ const csp = `${CSP}; frame-ancestors 'self'${ancestors.map((a) => " " + a).join("")}`;
3780
3784
  let structure = await readStructure(o.dir, ids);
3781
3785
  let wsComponents = workspaceComponents(o.dir);
3782
3786
  const staging = new Staging({
@@ -4255,6 +4259,40 @@ async function startDevServer(o) {
4255
4259
  }
4256
4260
  return refuse(`${method} ${path} is a write`);
4257
4261
  }
4262
+ async function writeRefusal(req, path) {
4263
+ const refused = await readOnlyRefusal(req, path);
4264
+ if (!refused || !o.onBrowserWrite)
4265
+ return refused;
4266
+ const body = bodies.get(req);
4267
+ let json = null;
4268
+ try {
4269
+ json = body && body.length ? JSON.parse(body.toString("utf8")) : null;
4270
+ } catch {
4271
+ json = null;
4272
+ }
4273
+ const table = /^\/api\/now\/(?:v\d+\/)?table\/([a-z0-9_]+)(?:\/([0-9a-f]{32}))?/.exec(path);
4274
+ const write = {
4275
+ method: String(req.method || ""),
4276
+ path,
4277
+ ...table ? { table: table[1], ...table[2] ? { sysId: table[2] } : {} } : {},
4278
+ ...json && typeof json === "object" && !Array.isArray(json) ? { fields: Object.keys(json).slice(0, 40) } : {},
4279
+ ...path.startsWith("/__rpf/server/execute/") && json?.action ? { action: String(json.action) } : {},
4280
+ reason: String(refused.error?.message || "")
4281
+ };
4282
+ let decision = null;
4283
+ try {
4284
+ decision = await o.onBrowserWrite(write);
4285
+ } catch {
4286
+ decision = null;
4287
+ }
4288
+ if (decision === true)
4289
+ return null;
4290
+ if (decision === false)
4291
+ return {
4292
+ error: { status: 403, code: "rpf_write_declined", message: "rpf dev: the user declined this write" }
4293
+ };
4294
+ return refused;
4295
+ }
4258
4296
  async function proxy(req, res, path) {
4259
4297
  const t = Date.now();
4260
4298
  const headers = {};
@@ -4496,7 +4534,7 @@ async function startDevServer(o) {
4496
4534
  const asked = decodeURIComponent(path.slice("/x/312987/portal/site/".length).split("/")[0] || "");
4497
4535
  if (asked && asked !== structure.slug)
4498
4536
  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"]);
4499
- return send(res, 200, shellHtml(), MIME[".html"], { "Content-Security-Policy": CSP });
4537
+ return send(res, 200, shellHtml(), MIME[".html"], { "Content-Security-Policy": csp });
4500
4538
  }
4501
4539
  if (path === "/__rpf/api/boot")
4502
4540
  return send(res, 200, JSON.stringify(bootJson()), MIME[".json"]);
@@ -4553,7 +4591,7 @@ ${msg}`)}); }`, MIME[".js"]);
4553
4591
  "Cache-Control": "no-cache"
4554
4592
  });
4555
4593
  }
4556
- const refused = await readOnlyRefusal(req, path);
4594
+ const refused = await writeRefusal(req, path);
4557
4595
  if (refused)
4558
4596
  return send(res, 403, JSON.stringify(refused), MIME[".json"]);
4559
4597
  if (path.startsWith("/__rpf/server/"))
@@ -9447,7 +9485,13 @@ async function realPush(client, args, dir, started) {
9447
9485
  const savePending = () => writePending(dir, pendingAfter(bodies, owed.ids, owed.since));
9448
9486
  savePending();
9449
9487
  const results = [];
9488
+ const progress = (phase, chunk) => {
9489
+ try {
9490
+ args.onProgress?.({ phase, chunk, of: bodies.length });
9491
+ } catch {}
9492
+ };
9450
9493
  for (let i = 0;i < bodies.length; i++) {
9494
+ progress("chunk", i + 1);
9451
9495
  try {
9452
9496
  const res = await client.post("/write/apply_workspace", {
9453
9497
  ...bodies[i],
@@ -9488,6 +9532,7 @@ async function realPush(client, args, dir, started) {
9488
9532
  writePending(dir, null);
9489
9533
  rmSync5(ow, { recursive: true, force: true });
9490
9534
  rmSync5(f, { force: true });
9535
+ progress("finishing", bodies.length);
9491
9536
  const a = await analyze(dir, client, { full: true });
9492
9537
  const ops = a.entries.filter((e) => e.state === "converged").map((e) => ({ e, local: "keep" }));
9493
9538
  if (ops.length)
@@ -15948,7 +15993,7 @@ var init_update_check = __esm(() => {
15948
15993
  });
15949
15994
 
15950
15995
  // src/commands/update.ts
15951
- import { spawnSync as spawnSync7 } from "node:child_process";
15996
+ import { spawn as spawn4, spawnSync as spawnSync7 } from "node:child_process";
15952
15997
  import { realpathSync } from "node:fs";
15953
15998
  function entryPath() {
15954
15999
  try {
@@ -15988,6 +16033,58 @@ ${noticeText(VERSION, cached.latest, currentInstaller())}
15988
16033
  await refreshCache(home, fetch);
15989
16034
  } catch {}
15990
16035
  }
16036
+ function makeUpdate(fetchImpl = fetch) {
16037
+ const home = rpforgeHome();
16038
+ const disabled = () => {
16039
+ const on = (v) => !!v && v !== "0" && v.toLowerCase() !== "false";
16040
+ if (on(process.env.RPF_NO_UPDATE_CHECK) || on(process.env.NO_UPDATE_NOTIFIER))
16041
+ return "RPF_NO_UPDATE_CHECK is set";
16042
+ if (configEnabled() === false)
16043
+ return "updateCheck is off in the rpf config";
16044
+ return "";
16045
+ };
16046
+ const state = () => {
16047
+ const c = readCache(home);
16048
+ const installer = currentInstaller();
16049
+ return {
16050
+ current: VERSION,
16051
+ latest: c?.latest ?? null,
16052
+ checkedAt: c?.checkedAt ? new Date(c.checkedAt).toISOString() : "",
16053
+ newer: !!c && isNewer(VERSION, c.latest),
16054
+ installer,
16055
+ command: installer === "unknown" ? "" : installCommand(installer).text,
16056
+ disabled: disabled()
16057
+ };
16058
+ };
16059
+ return {
16060
+ state,
16061
+ check: async () => {
16062
+ const latest = await fetchLatest(fetchImpl, 8000);
16063
+ try {
16064
+ writeCache(home, { checkedAt: Date.now(), latest });
16065
+ } catch {}
16066
+ return state();
16067
+ },
16068
+ run: (onLine) => new Promise((done) => {
16069
+ const installer = currentInstaller();
16070
+ if (installer === "unknown") {
16071
+ onLine("Couldn't tell how rpf was installed, so Forge can't update it. Update it in a terminal.");
16072
+ return done({ code: 1 });
16073
+ }
16074
+ const cmd = installCommand(installer);
16075
+ onLine(`$ ${cmd.text}`);
16076
+ const child = spawn4(cmd.cmd, cmd.args, { shell: true, windowsHide: true });
16077
+ const pipe = (b) => String(b).split(/\r?\n/).filter(Boolean).forEach((l) => onLine(l));
16078
+ child.stdout.on("data", pipe);
16079
+ child.stderr.on("data", pipe);
16080
+ child.on("error", (e) => {
16081
+ onLine(String(e.message || e));
16082
+ done({ code: 1 });
16083
+ });
16084
+ child.on("close", (code) => done({ code: code ?? 1 }));
16085
+ })
16086
+ };
16087
+ }
15991
16088
  async function update(ctx, o) {
15992
16089
  const latest = await fetchLatest(fetch, 8000);
15993
16090
  if (!latest)
@@ -16100,6 +16197,838 @@ var init_preview = __esm(() => {
16100
16197
  init_out();
16101
16198
  });
16102
16199
 
16200
+ // src/commands/forge-profiles.ts
16201
+ import { randomBytes as randomBytes5 } from "node:crypto";
16202
+ import { existsSync as existsSync30 } from "node:fs";
16203
+ function openStore() {
16204
+ try {
16205
+ return { store: new CredentialStore, problem: "" };
16206
+ } catch (e) {
16207
+ return { store: null, problem: String(e.message || e) };
16208
+ }
16209
+ }
16210
+ function tokenState2(c) {
16211
+ if (!c.auth.startsWith("oauth-"))
16212
+ return "-";
16213
+ try {
16214
+ const t = loadToken(c);
16215
+ if (!t)
16216
+ return "none";
16217
+ if (t.expiresAt < Date.now())
16218
+ return t.refreshToken ? "expired (refreshable)" : "expired";
16219
+ const mins = Math.round((t.expiresAt - Date.now()) / 60000);
16220
+ return `valid ${mins < 120 ? `${mins} min` : `${Math.round(mins / 60)} h`}${t.refreshToken ? " + refresh" : ""}`;
16221
+ } catch {
16222
+ return "?";
16223
+ }
16224
+ }
16225
+ function configOf(name) {
16226
+ const r = resolveConfig({ profile: name, profiles: readProfiles() }, { clientVersion: `rpforge/${VERSION}` });
16227
+ r.config.loginCommand = loginCommand(name);
16228
+ return r.config;
16229
+ }
16230
+ function markVerified(name, s) {
16231
+ if (!s?.enabled)
16232
+ return;
16233
+ const profiles = readProfiles();
16234
+ const pr = profiles.profiles[name];
16235
+ if (!pr)
16236
+ return;
16237
+ pr.verifiedAt = new Date().toISOString();
16238
+ pr.verifiedAs = s.user;
16239
+ writeProfiles(profiles);
16240
+ }
16241
+ function makeProfiles() {
16242
+ const logins = new Map;
16243
+ return {
16244
+ kinds: [...AUTH_KINDS].filter((k) => k !== "session"),
16245
+ kindSecrets: KIND_SECRETS,
16246
+ list() {
16247
+ const profiles = readProfiles();
16248
+ const { store, problem } = openStore();
16249
+ let content = null;
16250
+ let state = {
16251
+ state: "unavailable",
16252
+ file: store?.file || "",
16253
+ keySource: store?.keys.source || "",
16254
+ message: problem
16255
+ };
16256
+ if (store) {
16257
+ if (!store.exists())
16258
+ state = { state: "empty", file: store.file, keySource: store.keys.source };
16259
+ else
16260
+ try {
16261
+ content = store.read();
16262
+ state = { state: "ok", file: store.file, keySource: store.keys.source };
16263
+ } catch (e) {
16264
+ state = {
16265
+ state: "unreadable",
16266
+ file: store.file,
16267
+ keySource: store.keys.source,
16268
+ message: String(e.message || e)
16269
+ };
16270
+ }
16271
+ }
16272
+ const rows = Object.entries(profiles.profiles).map(([name, pr]) => {
16273
+ const c = buildConfig(profileSettings(pr, {}, {}, {}), {
16274
+ tokens: content ? { where: store.file, load: (k) => content.tokens[k] || null, save: () => {} } : memoryTokenStore()
16275
+ });
16276
+ return {
16277
+ name,
16278
+ default: profiles.default === name,
16279
+ instance: pr.instance,
16280
+ kind: pr.kind,
16281
+ user: pr.user,
16282
+ clientId: pr.clientId,
16283
+ scope: pr.scope,
16284
+ redirectUri: pr.redirectUri,
16285
+ apiKeyHeader: pr.apiKeyHeader,
16286
+ cert: pr.cert,
16287
+ key: pr.key,
16288
+ ca: pr.ca,
16289
+ secrets: content ? Object.keys(content.secrets[name] || {}) : state.state === "empty" ? [] : null,
16290
+ token: content || state.state === "empty" ? tokenState2(c) : "?",
16291
+ signIn: describeAuth(c),
16292
+ verifiedAt: pr.verifiedAt,
16293
+ verifiedAs: pr.verifiedAs
16294
+ };
16295
+ });
16296
+ return { default: profiles.default, store: state, profiles: rows };
16297
+ },
16298
+ async save(o) {
16299
+ if (!PROFILE_NAME.test(o.name))
16300
+ throw new Error("Profile name: letters, digits, . _ - (up to 64)");
16301
+ if (!isAuthKind(o.kind) || o.kind === "session")
16302
+ throw new Error(`Unknown sign-in kind ${o.kind}`);
16303
+ const instance = normalizeInstance(o.instance);
16304
+ if (!instance)
16305
+ throw new Error("Instance: a name (dev12345) or URL");
16306
+ for (const f of ["cert", "key", "ca"])
16307
+ if (o[f] && !existsSync30(o[f]))
16308
+ throw new Error(`${f}: no file at ${o[f]}`);
16309
+ const profiles = readProfiles();
16310
+ const oldName = o.replaces && profiles.profiles[o.replaces] ? o.replaces : o.name;
16311
+ if (oldName !== o.name && profiles.profiles[o.name])
16312
+ throw new Error(`A profile named ${o.name} exists`);
16313
+ const pr = { instance, kind: o.kind };
16314
+ for (const k of ["user", "clientId", "scope", "redirectUri", "apiKeyHeader", "cert", "key", "ca"])
16315
+ if (o[k]?.trim())
16316
+ pr[k] = o[k].trim();
16317
+ const { store, problem } = openStore();
16318
+ const kept = store && store.exists() && profiles.profiles[oldName] ? store.secrets(oldName) : {};
16319
+ const secrets = { ...kept };
16320
+ for (const [k, v] of Object.entries(o.secrets || {})) {
16321
+ if (v === "")
16322
+ delete secrets[k];
16323
+ else if (typeof v === "string")
16324
+ secrets[k] = v;
16325
+ }
16326
+ const want = KIND_SECRETS[o.kind];
16327
+ const relevant = new Set([
16328
+ ...want.required,
16329
+ ...want.optional,
16330
+ ...pr.key ? ["keyPassphrase"] : []
16331
+ ]);
16332
+ for (const k of Object.keys(secrets))
16333
+ if (!relevant.has(k))
16334
+ delete secrets[k];
16335
+ for (const f of want.required)
16336
+ if (!secrets[f])
16337
+ throw new Error(`Missing: ${f}`);
16338
+ if (Object.keys(secrets).length && !store)
16339
+ throw new Error(`Secrets can't be saved: ${problem}`);
16340
+ const config = buildConfig(profileSettings(pr, secrets, {}, {}), {
16341
+ tokens: memoryTokenStore(),
16342
+ clientVersion: `rpforge/${VERSION}`,
16343
+ loginCommand: loginCommand(o.name)
16344
+ });
16345
+ const why = configProblem(config);
16346
+ if (why)
16347
+ throw new Error(why);
16348
+ let forge = null;
16349
+ if (o.verify !== false && o.kind !== "oauth-code") {
16350
+ forge = await new ForgeClient(config).get("/status");
16351
+ if (forge?.enabled) {
16352
+ pr.verifiedAt = new Date().toISOString();
16353
+ pr.verifiedAs = forge.user;
16354
+ }
16355
+ }
16356
+ if (store && (Object.keys(secrets).length || store.exists())) {
16357
+ if (oldName !== o.name)
16358
+ store.removeProfile(oldName);
16359
+ store.setSecrets(o.name, secrets);
16360
+ }
16361
+ if (oldName !== o.name)
16362
+ delete profiles.profiles[oldName];
16363
+ profiles.profiles[o.name] = pr;
16364
+ if (o.makeDefault || !profiles.default || !profiles.profiles[profiles.default] || profiles.default === oldName)
16365
+ profiles.default = o.name;
16366
+ writeProfiles(profiles);
16367
+ return { profile: o.name, forge };
16368
+ },
16369
+ setDefault(name) {
16370
+ const profiles = readProfiles();
16371
+ if (!profiles.profiles[name])
16372
+ throw new Error(`No profile ${name}`);
16373
+ profiles.default = name;
16374
+ writeProfiles(profiles);
16375
+ },
16376
+ async remove(name) {
16377
+ const profiles = readProfiles();
16378
+ const pr = profiles.profiles[name];
16379
+ if (!pr)
16380
+ throw new Error(`No profile ${name}`);
16381
+ const { store } = openStore();
16382
+ let revoked = false;
16383
+ if (pr.kind.startsWith("oauth-") && store?.exists()) {
16384
+ try {
16385
+ const c = configOf(name);
16386
+ const t = loadToken(c);
16387
+ if (t) {
16388
+ await revoke(c, t.refreshToken || t.accessToken);
16389
+ revoked = true;
16390
+ }
16391
+ } catch {}
16392
+ }
16393
+ const key = profileTokenKey(pr);
16394
+ const shared = Object.entries(profiles.profiles).some(([n, x]) => n !== name && profileTokenKey(x) === key);
16395
+ store?.removeProfile(name, shared ? [] : [key]);
16396
+ delete profiles.profiles[name];
16397
+ if (profiles.default === name) {
16398
+ const rest = Object.keys(profiles.profiles);
16399
+ profiles.default = rest.length === 1 ? rest[0] : "";
16400
+ }
16401
+ writeProfiles(profiles);
16402
+ return { revoked };
16403
+ },
16404
+ async verify(name) {
16405
+ const s = await new ForgeClient(configOf(name)).get("/status");
16406
+ markVerified(name, s);
16407
+ return s;
16408
+ },
16409
+ async logout(name) {
16410
+ const c = configOf(name);
16411
+ const t = c.auth.startsWith("oauth-") ? loadToken(c) : null;
16412
+ if (!t)
16413
+ return { signedOut: false };
16414
+ await revoke(c, t.refreshToken || t.accessToken).catch(() => {});
16415
+ saveToken(c, null);
16416
+ return { signedOut: true };
16417
+ },
16418
+ async loginStart(name, opts = {}) {
16419
+ const c = configOf(name);
16420
+ const id = base64url(randomBytes5(12));
16421
+ if (c.auth !== "oauth-code") {
16422
+ const done = (async () => {
16423
+ if (c.auth.startsWith("oauth-")) {
16424
+ saveToken(c, null);
16425
+ await new ForgeClient(c).auth.headers();
16426
+ }
16427
+ const s = await new ForgeClient(c).get("/status");
16428
+ markVerified(name, s);
16429
+ return s;
16430
+ })();
16431
+ done.catch(() => {});
16432
+ logins.set(id, {
16433
+ profile: name,
16434
+ url: "",
16435
+ redirectUri: "",
16436
+ state: "",
16437
+ verifier: "",
16438
+ stop: () => {},
16439
+ done,
16440
+ paste: () => {}
16441
+ });
16442
+ return { id, url: "" };
16443
+ }
16444
+ const { verifier, challenge } = pkcePair();
16445
+ const state = base64url(randomBytes5(24));
16446
+ const url = authorizeUrl(c, state, challenge);
16447
+ const wait = waitForCode(c.oauth.redirectUri, state, 300000, "rpf forge");
16448
+ let pasted = () => {};
16449
+ const pastedCode = new Promise((r) => pasted = r);
16450
+ await wait.ready;
16451
+ const done = (async () => {
16452
+ const code = await Promise.race([wait.done, pastedCode]);
16453
+ wait.stop();
16454
+ if (!code)
16455
+ throw new Error("No authorization code came back");
16456
+ const t = await tokenRequest(c, {
16457
+ grant_type: "authorization_code",
16458
+ code,
16459
+ redirect_uri: c.oauth.redirectUri,
16460
+ code_verifier: verifier
16461
+ });
16462
+ saveToken(c, storedFrom(c, t));
16463
+ const s = await new ForgeClient(c).get("/status");
16464
+ markVerified(name, s);
16465
+ return s;
16466
+ })();
16467
+ done.catch(() => {});
16468
+ logins.set(id, {
16469
+ profile: name,
16470
+ url,
16471
+ redirectUri: c.oauth.redirectUri,
16472
+ state,
16473
+ verifier,
16474
+ stop: wait.stop,
16475
+ done,
16476
+ paste: (v) => {
16477
+ if (/^https?:\/\//.test(v)) {
16478
+ const u = new URL(v);
16479
+ if (u.searchParams.get("state") && u.searchParams.get("state") !== state)
16480
+ throw new Error("That address is from another sign-in (state mismatch)");
16481
+ pasted(u.searchParams.get("code") || "");
16482
+ } else
16483
+ pasted(v.trim());
16484
+ }
16485
+ });
16486
+ if (opts.openBrowser !== false)
16487
+ openBrowser(url);
16488
+ return { id, url };
16489
+ },
16490
+ async loginWait(id) {
16491
+ const s = logins.get(id);
16492
+ if (!s)
16493
+ throw new Error("That sign-in is no longer running");
16494
+ try {
16495
+ return await s.done;
16496
+ } finally {
16497
+ logins.delete(id);
16498
+ }
16499
+ },
16500
+ loginPaste(id, value) {
16501
+ const s = logins.get(id);
16502
+ if (!s)
16503
+ throw new Error("That sign-in is no longer running");
16504
+ s.paste(value);
16505
+ },
16506
+ loginCancel(id) {
16507
+ const s = logins.get(id);
16508
+ if (!s)
16509
+ return;
16510
+ s.stop();
16511
+ s.paste("");
16512
+ logins.delete(id);
16513
+ }
16514
+ };
16515
+ }
16516
+ var init_forge_profiles = __esm(() => {
16517
+ init_config();
16518
+ init_client();
16519
+ init_auth();
16520
+ init_login();
16521
+ init_store();
16522
+ init_profiles();
16523
+ init_context();
16524
+ init_version();
16525
+ });
16526
+
16527
+ // 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";
16530
+ import { randomUUID as randomUUID3 } from "node:crypto";
16531
+ import { spawnSync as spawnSync8 } from "node:child_process";
16532
+ function refusal(code, message) {
16533
+ return Object.assign(new Error(message), { code });
16534
+ }
16535
+ function cmpVersion4(a, b) {
16536
+ const pa = a.split(".").map((n) => parseInt(n, 10) || 0);
16537
+ const pb = b.split(".").map((n) => parseInt(n, 10) || 0);
16538
+ for (let i = 0;i < 3; i++)
16539
+ if ((pa[i] || 0) !== (pb[i] || 0))
16540
+ return (pa[i] || 0) < (pb[i] || 0) ? -1 : 1;
16541
+ return 0;
16542
+ }
16543
+ function clientFor(profile) {
16544
+ const r = resolveConfig({ profile: profile || undefined, profiles: readProfiles() }, { clientVersion: `rpforge/${VERSION}` });
16545
+ const problem = configProblem(r.config);
16546
+ if (problem)
16547
+ throw refusal("no_profile", problem);
16548
+ return { client: new ForgeClient(r.config), instance: r.config.instance };
16549
+ }
16550
+ function isEmptyDir3(dir) {
16551
+ return !existsSync31(dir) || readdirSync10(dir).length === 0;
16552
+ }
16553
+ function insideGitRepo2(dir) {
16554
+ let d = resolve13(dir);
16555
+ for (;; ) {
16556
+ if (existsSync31(join31(d, ".git")))
16557
+ return true;
16558
+ const up = dirname17(d);
16559
+ if (up === d)
16560
+ return false;
16561
+ d = up;
16562
+ }
16563
+ }
16564
+ function groupCounts2(creates) {
16565
+ const counts = {};
16566
+ for (const c of creates || []) {
16567
+ const t = String(c.table || "").replace(/^x_312987_portal_/, "");
16568
+ counts[t] = (counts[t] || 0) + 1;
16569
+ }
16570
+ return Object.entries(counts);
16571
+ }
16572
+ async function pullInto(client, o, step) {
16573
+ mkdirSync17(o.folder, { recursive: true });
16574
+ configureWorkspace({
16575
+ repo: "",
16576
+ apps: dirname17(o.folder),
16577
+ prettierConfigFrom: o.extras.prettierrc ? "" : prettierConfigFor(o.folder),
16578
+ tsc: "",
16579
+ hostTypes: "",
16580
+ typesFrom: ""
16581
+ });
16582
+ step(`Pulling ${o.portal} into ${o.folder}`);
16583
+ const pulled = await pull(client, {
16584
+ portal: o.portal,
16585
+ out: o.folder,
16586
+ updateSet: o.updateSet,
16587
+ mode: o.retry ? "auto" : "fresh"
16588
+ });
16589
+ const files = [];
16590
+ if (o.extras.prettierrc) {
16591
+ writeFileSync18(join31(o.folder, ".prettierrc.json"), prettierrcText());
16592
+ files.push(".prettierrc.json");
16593
+ }
16594
+ if (o.extras.gitignore) {
16595
+ writeFileSync18(join31(o.folder, ".gitignore"), `.forge/
16596
+ node_modules/
16597
+ `);
16598
+ files.push(".gitignore");
16599
+ }
16600
+ if (o.extras.readme && o.readme) {
16601
+ writeFileSync18(join31(o.folder, "README.md"), o.readme);
16602
+ files.push("README.md");
16603
+ }
16604
+ if (o.extras.git) {
16605
+ step("git init");
16606
+ const g = spawnSync8("git", ["init", "-q"], { cwd: o.folder, encoding: "utf8" });
16607
+ if (g.status === 0)
16608
+ files.push(".git/");
16609
+ else
16610
+ step(`git init failed: ${String(g.stderr || g.error || "").trim()}`);
16611
+ }
16612
+ if (o.extras.skills) {
16613
+ step("Installing the agent skills");
16614
+ try {
16615
+ const r = syncSkills(join31(nearestProject(o.folder), ".claude", "skills"), { mode: "install" });
16616
+ files.push(`${r.root} (${r.skills.map((s) => s.name).join(", ")})`);
16617
+ } catch (e) {
16618
+ step(`skills install failed: ${e.message || e}`);
16619
+ }
16620
+ }
16621
+ return { pull: pulled, files };
16622
+ }
16623
+ function readmeText(name, slug, scope, setName, instance) {
16624
+ return `# ${name}
16625
+
16626
+ A React Portal workspace for the portal \`${slug}\` (${scope ? `application ${scope}, ` : ""}update set "${setName}") on ${instance}.
16627
+
16628
+ ` + "```bash\nrpforge status # what changed, here and on the instance\nrpforge check # format, lint, compile, the push dry run\nrpforge push # dry run, then the confirmed push\n```\n\n" + `The portal is a draft: publish it in Studio (Portals) when it is ready.
16629
+ `;
16630
+ }
16631
+ async function brandTokens(th) {
16632
+ if (!th.color)
16633
+ return { contrast: [] };
16634
+ const tokens = await tokensFromColor({ color: th.color, tint: th.tint, contrast: th.contrast, radius: th.radius });
16635
+ return { tokens, contrast: await contrastSummary(tokens) };
16636
+ }
16637
+ async function resolveSet(client, appId, want) {
16638
+ const sets = (await client.get("/update-sets", { app: appId })).sets || [];
16639
+ if (typeof want === "string") {
16640
+ const hits = sets.filter((s) => s.id === want || s.name === want);
16641
+ if (hits.length !== 1)
16642
+ throw refusal("bad_answers", `Update set "${want}": ${hits.length ? "several" : "no"} in-progress sets match`);
16643
+ return { sets, ref: hits[0].id, name: hits[0].name, isNew: false };
16644
+ }
16645
+ const name = String(want?.create || "").trim();
16646
+ if (!name)
16647
+ throw refusal("bad_answers", "Pick an update set or name a new one");
16648
+ if (sets.some((s) => s.name === name))
16649
+ throw refusal("bad_answers", `An in-progress update set "${name}" already exists: pick it instead`);
16650
+ return { sets, ref: "", name, isNew: true };
16651
+ }
16652
+ function makeCreate() {
16653
+ return {
16654
+ preflight: async (profile) => {
16655
+ const { client, instance } = clientFor(profile);
16656
+ const status = await client.get("/status");
16657
+ if (!status.enabled)
16658
+ throw refusal("forge_mcp_disabled", `Forge is off on ${instance} (${status.property || "x_312987_portal.forge.mcp.enabled"} is not true)`);
16659
+ if (!status.capabilities || !status.capabilities.design)
16660
+ throw refusal("forbidden", `${status.user} has no React Portal design access (designer or developer role) on ${instance}`);
16661
+ const compat = checkForgeApi(status);
16662
+ if (compat.state === "unknown" || compat.state === "too-old")
16663
+ 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
+ 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"})`);
16667
+ const apps = (await client.get("/apps", { list: "authoring" })).apps || [];
16668
+ if (!apps.length)
16669
+ throw refusal("no_apps", `${status.user} can't author in any scoped application on ${instance}`);
16670
+ return {
16671
+ instance,
16672
+ user: status.user,
16673
+ reactPortal: status.version || status.reactPortal || "",
16674
+ capabilities: status.capabilities,
16675
+ warning: compat.state === "too-new" ? compat.message : "",
16676
+ canCreateSets: cmpVersion4(helpers, HELPERS_UPDATE_SETS4) >= 0,
16677
+ apps
16678
+ };
16679
+ },
16680
+ updateSets: async (profile, appId) => (await clientFor(profile).client.get("/update-sets", { app: appId })).sets || [],
16681
+ portals: async (profile) => await clientFor(profile).client.get("/portals"),
16682
+ portal: async (profile, ref) => await clientFor(profile).client.get("/portal", { ref }),
16683
+ themes: async (profile) => (await clientFor(profile).client.get("/themes")).filter((t) => t.active),
16684
+ layouts: async (profile) => await clientFor(profile).client.get("/components", { kind: "layout" }),
16685
+ slugAvailable: async (profile, slug) => await clientFor(profile).client.get("/portals/slug-available", { slug }),
16686
+ brandTheme: async (th) => brandTokens(th),
16687
+ defaults: (folder) => ({ empty: isEmptyDir3(folder), inRepo: insideGitRepo2(dirname17(folder)) }),
16688
+ slugFromName,
16689
+ plan: async (profile, a, o) => {
16690
+ const problems = [...answersProblems(a), ...invalidAnswers(a)];
16691
+ if (problems.length)
16692
+ throw refusal("bad_answers", problems.join("; "));
16693
+ if (!isEmptyDir3(o.folder))
16694
+ throw refusal("folder_not_empty", `${o.folder} is not empty: pick an empty or new folder`);
16695
+ const { client, instance } = clientFor(profile);
16696
+ const apps = (await client.get("/apps", { list: "authoring" })).apps || [];
16697
+ const app = apps.find((x) => x.scope === a.app || x.id === a.app);
16698
+ if (!app)
16699
+ throw refusal("bad_answers", `${a.app} is not an application you can author in on ${instance}`);
16700
+ const set = await resolveSet(client, app.id, a.updateSet);
16701
+ const previewSet = set.ref || (set.sets.find((s) => s.isDefault) || set.sets[0] || {}).id || "";
16702
+ if (!previewSet)
16703
+ throw refusal("no_update_set", `${app.scope} has no in-progress update set to plan against`);
16704
+ const setPlan = set.isNew ? await client.post("/write/create_update_set", { app: app.id, name: set.name, dryRun: true }) : null;
16705
+ const { tokens, contrast } = await brandTokens(a.theme || {});
16706
+ const dry = await client.post("/write/create_portal", createRequest(a, { tokens, updateSetRef: previewSet, dryRun: true }));
16707
+ const plan = dry.plan || {};
16708
+ if (set.isNew && Array.isArray(plan.warnings))
16709
+ plan.warnings = plan.warnings.map((w) => /^Created in /.test(w) ? w.replace(/update set "[^"]*"/, `the new update set "${set.name}"`) : w);
16710
+ const local = [`pull ${a.slug || slugFromName(a.name || "")} into ${o.folder}`];
16711
+ if (o.extras.prettierrc)
16712
+ local.push("write .prettierrc.json");
16713
+ if (o.extras.gitignore)
16714
+ local.push("write .gitignore");
16715
+ if (o.extras.readme)
16716
+ local.push("write README.md");
16717
+ if (o.extras.git)
16718
+ local.push("git init");
16719
+ if (o.extras.skills)
16720
+ local.push("install the agent skills (.claude/skills)");
16721
+ return {
16722
+ instance,
16723
+ app: { id: app.id, scope: app.scope, name: app.name, reactPortal: !!app.reactPortal },
16724
+ updateSet: { id: set.ref, name: set.name, isNew: set.isNew },
16725
+ plan,
16726
+ counts: groupCounts2(plan.creates || []),
16727
+ updateSetPlan: setPlan && setPlan.plan,
16728
+ contrast,
16729
+ local
16730
+ };
16731
+ },
16732
+ create: async (profile, a, o, step) => {
16733
+ const { client, instance } = clientFor(profile);
16734
+ const apps = (await client.get("/apps", { list: "authoring" })).apps || [];
16735
+ const app = apps.find((x) => x.scope === a.app || x.id === a.app);
16736
+ if (!app)
16737
+ throw refusal("bad_answers", `${a.app} is not an application you can author in`);
16738
+ const set = await resolveSet(client, app.id, a.updateSet);
16739
+ let setRef = set.ref;
16740
+ let createdSet = null;
16741
+ if (!setRef) {
16742
+ step(`Creating the update set "${set.name}"`);
16743
+ const made = await client.post("/write/create_update_set", {
16744
+ app: app.id,
16745
+ name: set.name,
16746
+ dryRun: false
16747
+ });
16748
+ createdSet = made.result && made.result.updateSet;
16749
+ if (!createdSet || !createdSet.id)
16750
+ throw refusal("update_set_failed", "The update set was not created");
16751
+ setRef = createdSet.id;
16752
+ }
16753
+ const slug = a.slug || slugFromName(a.name || "");
16754
+ const { tokens } = await brandTokens(a.theme || {});
16755
+ step(`Creating ${slug} on ${instance}`);
16756
+ const real = await client.post("/write/create_portal", createRequest(a, {
16757
+ tokens,
16758
+ updateSetRef: setRef,
16759
+ dryRun: false,
16760
+ requestId: o.requestId || randomUUID3(),
16761
+ planHash: o.planHash
16762
+ }));
16763
+ const created = real.result || {};
16764
+ const preview = await client.get("/preview", { portal: slug }).catch(() => null);
16765
+ let pulled = null;
16766
+ let files = [];
16767
+ let pullError = "";
16768
+ try {
16769
+ const r = await pullInto(client, {
16770
+ portal: created.id || slug,
16771
+ folder: o.folder,
16772
+ updateSet: setRef,
16773
+ extras: o.extras,
16774
+ readme: readmeText(a.name || slug, slug, app.scope, set.name, instance)
16775
+ }, step);
16776
+ pulled = r.pull;
16777
+ files = r.files;
16778
+ mkdirSync17(join31(o.folder, ".forge"), { recursive: true });
16779
+ const saved = JSON.parse(JSON.stringify(a));
16780
+ delete saved.folder;
16781
+ if (typeof saved.updateSet === "object")
16782
+ saved.updateSet = set.name;
16783
+ writeFileSync18(join31(o.folder, ".forge", "init-answers.json"), JSON.stringify(saved, null, 4) + `
16784
+ `);
16785
+ } catch (e) {
16786
+ pullError = e.message || String(e);
16787
+ }
16788
+ return {
16789
+ slug,
16790
+ created,
16791
+ updateSet: createdSet || { id: setRef, name: set.name },
16792
+ studioUrl: preview ? preview.studioUrl : null,
16793
+ folder: o.folder,
16794
+ pull: pulled,
16795
+ files,
16796
+ pullError: pullError || undefined
16797
+ };
16798
+ },
16799
+ pull: async (profile, o, step) => {
16800
+ if (!o.retry && !isEmptyDir3(o.folder))
16801
+ throw refusal("folder_not_empty", `${o.folder} is not empty: pick an empty or new folder`);
16802
+ const { client, instance } = clientFor(profile);
16803
+ const r = await pullInto(client, { ...o, readme: readmeText(o.portal, o.portal, "", o.updateSet, instance) }, step);
16804
+ return { folder: o.folder, pull: r.pull, files: r.files };
16805
+ }
16806
+ };
16807
+ }
16808
+ var HELPERS_SWITCH4 = "1.3.0", HELPERS_UPDATE_SETS4 = "1.7.0";
16809
+ var init_forge_create = __esm(() => {
16810
+ init_client();
16811
+ init_compat();
16812
+ init_config();
16813
+ init_layout();
16814
+ init_pull();
16815
+ init_profiles();
16816
+ init_init();
16817
+ init_workspace();
16818
+ init_skills();
16819
+ init_version();
16820
+ });
16821
+
16822
+ // 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";
16825
+ import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
16826
+ import { spawn as spawn5 } from "node:child_process";
16827
+ function forgeAssets() {
16828
+ const here = dirname18(fileURLToPath3(import.meta.url));
16829
+ 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 };
16832
+ }
16833
+ const assets = join32(here, "..", "assets", "forge-app");
16834
+ return { server: join32(assets, "server.mjs"), appDir: join32(assets, "app"), fromSource: false };
16835
+ }
16836
+ function makeForgeCore() {
16837
+ const home = rpforgeHome();
16838
+ let store = null;
16839
+ try {
16840
+ store = new CredentialStore;
16841
+ } catch {
16842
+ store = null;
16843
+ }
16844
+ const here = dirname18(fileURLToPath3(import.meta.url));
16845
+ const fromSource = basename2(here) === "commands";
16846
+ return {
16847
+ version: VERSION,
16848
+ home,
16849
+ secrets: store && {
16850
+ get: (entry) => ({ ...store.secrets(entry) }),
16851
+ set: (entry, secrets) => {
16852
+ if (Object.keys(secrets).length)
16853
+ store.setSecrets(entry, secrets);
16854
+ else
16855
+ store.removeProfile(entry);
16856
+ },
16857
+ describe: () => ({ file: store.file, keySource: store.keys.source })
16858
+ },
16859
+ findWorkspace: (dir) => findWorkspace(dir),
16860
+ workspaceFacts: (dir) => {
16861
+ let m;
16862
+ try {
16863
+ m = readManifest(dir);
16864
+ } catch {
16865
+ return null;
16866
+ }
16867
+ if (!m)
16868
+ return null;
16869
+ const states = Object.values(m.instances);
16870
+ const first = states[0];
16871
+ return {
16872
+ portal: first?.portal?.slug,
16873
+ scope: first?.app?.scope,
16874
+ appName: first?.app?.name,
16875
+ updateSet: first?.updateSet?.name,
16876
+ instance: first?.url,
16877
+ instances: states.map((s) => s.url)
16878
+ };
16879
+ },
16880
+ findBrowser: () => findBrowser(),
16881
+ profiles: makeProfiles(),
16882
+ update: makeUpdate(),
16883
+ create: makeCreate(),
16884
+ workspace: {
16885
+ status: async (dir) => {
16886
+ const client = workspaceClient(dir);
16887
+ configure(dirname18(dir), dir);
16888
+ return status2(client, { workspace: dir });
16889
+ },
16890
+ check: async (dir) => {
16891
+ const client = workspaceClient(dir);
16892
+ configure(dirname18(dir), dir);
16893
+ return check(client, {
16894
+ workspace: dir,
16895
+ force: false,
16896
+ tsc: false,
16897
+ updateSet: true,
16898
+ removeFiles: []
16899
+ });
16900
+ },
16901
+ push: async (dir, args) => {
16902
+ const client = workspaceClient(dir);
16903
+ configure(dirname18(dir), dir);
16904
+ return push(client, { workspace: dir, ...args });
16905
+ },
16906
+ diff: async (dir, keys) => {
16907
+ const client = workspaceClient(dir);
16908
+ configure(dirname18(dir), dir);
16909
+ return diff(client, { workspace: dir, keys, against: "auto" });
16910
+ },
16911
+ resolve: async (dir, keys, action) => {
16912
+ const client = workspaceClient(dir);
16913
+ configure(dirname18(dir), dir);
16914
+ return resolveEntries(client, { workspace: dir, keys, action });
16915
+ }
16916
+ },
16917
+ profileFor: (dir) => {
16918
+ try {
16919
+ return resolveConfig({ dir, profiles: readProfiles() }, { clientVersion: `rpforge/${VERSION}` }).profile || "";
16920
+ } catch {
16921
+ return "";
16922
+ }
16923
+ },
16924
+ startDevServer: async (dir, log, extra) => {
16925
+ const r = resolveConfig({ dir, profiles: readProfiles() }, { clientVersion: `rpforge/${VERSION}` });
16926
+ const problem = configProblem(r.config);
16927
+ if (problem) {
16928
+ const e = new Error(problem);
16929
+ e.code = "no_profile";
16930
+ throw e;
16931
+ }
16932
+ return startDevServer({
16933
+ dir,
16934
+ config: r.config,
16935
+ client: new ForgeClient(r.config),
16936
+ assetsDir: assetsDir(),
16937
+ log,
16938
+ frameAncestors: extra?.frameAncestors,
16939
+ onBrowserWrite: extra?.onBrowserWrite
16940
+ });
16941
+ },
16942
+ mcpCommand: () => fromSource ? { command: process.execPath, args: ["run", resolve14(here, "..", "cli.ts"), "mcp"] } : { command: process.execPath, args: [resolve14(here, "cli.mjs"), "mcp"] },
16943
+ agentGuide: () => readGuide("react-portal/SKILL.md") || "",
16944
+ skillsDir: () => {
16945
+ try {
16946
+ return bundledSkillsDir();
16947
+ } catch {
16948
+ return;
16949
+ }
16950
+ }
16951
+ };
16952
+ }
16953
+ function workspaceClient(dir) {
16954
+ const r = resolveConfig({ dir, profiles: readProfiles() }, { clientVersion: `rpforge/${VERSION}` });
16955
+ const problem = configProblem(r.config);
16956
+ if (problem) {
16957
+ const e = new Error(problem);
16958
+ e.code = "no_profile";
16959
+ throw e;
16960
+ }
16961
+ return new ForgeClient(r.config);
16962
+ }
16963
+ function openBrowser4(url) {
16964
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
16965
+ const args = process.platform === "win32" ? ["/c", "start", '""', url.replace(/&/g, "^&")] : [url];
16966
+ spawn5(cmd, args, { stdio: "ignore", detached: true }).unref();
16967
+ }
16968
+ async function forge(ctx, dir, o) {
16969
+ const a = forgeAssets();
16970
+ if (!existsSync32(a.server) || !existsSync32(join32(a.appDir, "index.html")))
16971
+ 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
+ const target = dir || ctx.opts.dir;
16973
+ const open = target ? resolve14(target) : findWorkspace(process.cwd()) || undefined;
16974
+ const mod = await import(pathToFileURL(a.server).href);
16975
+ const server = await mod.startForge({
16976
+ core: makeForgeCore(),
16977
+ appDir: a.appDir,
16978
+ open,
16979
+ port: o.port ? parseInt(o.port, 10) : undefined,
16980
+ newKey: !!o.newKey,
16981
+ devMock: a.fromSource && process.env.FORGE_DEV_MOCK === "1",
16982
+ log: (s) => ctx.out.info(`[rpf forge] ${s}`)
16983
+ });
16984
+ if (ctx.opts.json)
16985
+ process.stdout.write(JSON.stringify({ url: server.url, enterUrl: server.enterUrl }) + `
16986
+ `);
16987
+ else {
16988
+ ctx.out.info("");
16989
+ ctx.out.info(` rpf forge: ${server.enterUrl}`);
16990
+ ctx.out.info(" This link opens Forge on this machine only. Ctrl+C to stop.");
16991
+ }
16992
+ if (o.open !== false)
16993
+ openBrowser4(server.enterUrl);
16994
+ runState.keepRunning = true;
16995
+ const stop = async () => {
16996
+ await server.close();
16997
+ process.exit(0);
16998
+ };
16999
+ process.once("SIGINT", stop);
17000
+ process.once("SIGTERM", stop);
17001
+ }
17002
+ function registerForge(program, run) {
17003
+ const cmd = program.command("forge [dir]").description("Open Forge, the local agent workspace for React Portal projects, in your browser").option("--port <n>", "listen on this port (default: the last one used, else a free one)").option("--no-open", "print the link instead of opening the browser").option("--new-key", "rotate the local run key (browsers that entered before must use the new link)");
17004
+ cmd.action(run((ctx) => forge(ctx, cmd.args[0], cmd.opts())));
17005
+ }
17006
+ var init_forge = __esm(() => {
17007
+ init_store();
17008
+ init_profiles();
17009
+ init_manifest();
17010
+ init_guides();
17011
+ init_profiles();
17012
+ init_config();
17013
+ init_client();
17014
+ init_server();
17015
+ init_agent();
17016
+ init_dev();
17017
+ init_workspace();
17018
+ init_status();
17019
+ init_check();
17020
+ init_push();
17021
+ init_resolve();
17022
+ init_diff();
17023
+ init_out();
17024
+ init_context();
17025
+ init_version();
17026
+ init_forge_profiles();
17027
+ init_update();
17028
+ init_forge_create();
17029
+ init_skills();
17030
+ });
17031
+
16103
17032
  // src/program.ts
16104
17033
  import { Command, CommanderError, Option } from "commander";
16105
17034
  function buildProgram() {
@@ -16129,6 +17058,7 @@ function buildProgram() {
16129
17058
  registerUpdate(program, run);
16130
17059
  registerDev(program, run);
16131
17060
  registerPreview(program, run);
17061
+ registerForge(program, run);
16132
17062
  for (const c of allCommands(program))
16133
17063
  c.exitOverride().showHelpAfterError();
16134
17064
  return program;
@@ -16183,6 +17113,7 @@ var init_program = __esm(() => {
16183
17113
  init_update();
16184
17114
  init_dev();
16185
17115
  init_preview();
17116
+ init_forge();
16186
17117
  lastRun = { opts: null, name: "" };
16187
17118
  });
16188
17119