@quatronic/qore 0.2.0-rc.8 → 0.2.0-test.1384f05

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4be6a705-edee-51df-8b0e-e26c3410dcc4")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4e03d75d-eb39-5fde-97b7-e42c573ae760")}catch(e){}}();
4
4
  import { createRequire as __qoreCreateRequire } from "node:module"; const require = __qoreCreateRequire(import.meta.url);
5
5
  import {
6
6
  addSecretValues,
@@ -192,7 +192,7 @@ function createWaitForEnter(input2, output) {
192
192
  }
193
193
 
194
194
  // src/cli/program.ts
195
- import { Command, CommanderError } from "commander";
195
+ import { Command, CommanderError, Option } from "commander";
196
196
 
197
197
  // src/core/api/http.ts
198
198
  function abortableFetch(fetch3, signal) {
@@ -269,26 +269,26 @@ function byStatus(status2) {
269
269
  return "QORE_INTERNAL";
270
270
  }
271
271
  async function problemToError(res) {
272
- let body = {};
272
+ let body2 = {};
273
273
  try {
274
- body = await res.json();
274
+ body2 = await res.json();
275
275
  } catch {
276
276
  }
277
- const serverCode = body.code;
277
+ const serverCode = body2.code;
278
278
  const code = serverCode && BY_SERVER_CODE[serverCode] || byStatus(res.status);
279
279
  const requestId = res.headers.get("x-request-id") ?? void 0;
280
280
  const details = {};
281
- if (body.detail && typeof body.detail === "object") Object.assign(details, body.detail);
282
- const detail2 = typeof body.detail === "string" && body.detail ? body.detail : void 0;
281
+ if (body2.detail && typeof body2.detail === "object") Object.assign(details, body2.detail);
282
+ const detail2 = typeof body2.detail === "string" && body2.detail ? body2.detail : void 0;
283
283
  if (detail2) details.detail = detail2;
284
284
  const retry = res.headers.get("retry-after");
285
285
  if (retry && /^\d+$/.test(retry)) details.retryAfter = Number(retry);
286
286
  const hint = code === "QORE_UPGRADE_REQUIRED" ? "Run: npm i -g @quatronic/qore" : code === "QORE_RATE_LIMITED" ? `Wait ${details.retryAfter ?? "a moment"} s and retry.` : code === "QORE_API_UNAVAILABLE" ? "Qore is temporarily unavailable; retry in a minute." : code === "QORE_APP_AMBIGUOUS" ? "Pass --app <slug>." : void 0;
287
- const apps = body.detail?.apps;
287
+ const apps = body2.detail?.apps;
288
288
  const candidates = code === "QORE_APP_AMBIGUOUS" && Array.isArray(apps) ? apps.map((a) => ({ kind: "app", id: a.id, slug: a.slug, name: a.name })) : void 0;
289
289
  if (candidates) delete details.apps;
290
- const genericTitle = !body.title || body.title === "HTTP error" || body.title === serverCode;
291
- const message = genericTitle && detail2 || body.title || `Request failed (${res.status})`;
290
+ const genericTitle = !body2.title || body2.title === "HTTP error" || body2.title === serverCode;
291
+ const message = genericTitle && detail2 || body2.title || `Request failed (${res.status})`;
292
292
  return new QoreError(code, message, {
293
293
  status: res.status,
294
294
  requestId,
@@ -450,7 +450,7 @@ async function withProxyHint(deps2, e) {
450
450
  return proxy ? withSystemProxy(e, proxy, deps2.platform) : e;
451
451
  }
452
452
  function buildProgram(deps2, io2, signal, register, setExitCode) {
453
- const program = new Command("qore").description("Qore developer CLI").option("--portal <name|url>", "prod, staging, testing, or a portal URL (default: the portal you last logged in to, else prod)").option("--json", "print exactly one JSON document on stdout").option("--no-input", "never prompt").option("--verbose", "log request lines (never secrets)").option("--no-color", "disable colours").exitOverride().configureOutput({ writeOut: (s) => io2.out(s.trimEnd()), writeErr: (s) => io2.err(s.trimEnd()) });
453
+ const program = new Command("qore").description("Qore developer CLI").addOption(new Option("--portal <name|url>", "prod, staging, testing, or a portal URL").hideHelp()).option("--json", "print exactly one JSON document on stdout").option("--no-input", "never prompt").option("--verbose", "log request lines (never secrets)").option("--no-color", "disable colours").exitOverride().configureOutput({ writeOut: (s) => io2.out(s.trimEnd()), writeErr: (s) => io2.err(s.trimEnd()) });
454
454
  const ctx = { deps: deps2, io: io2, signal, opts: () => program.opts(), setExitCode };
455
455
  for (const r of register) r(program, ctx);
456
456
  return program;
@@ -504,7 +504,7 @@ async function run(argv2, deps2, io2, signal, register, hooks = {}) {
504
504
 
505
505
  // src/cli/commands/clone.ts
506
506
  import { join as join9, relative as relative3, resolve as resolve4 } from "path";
507
- import { Option } from "commander";
507
+ import { Option as Option2 } from "commander";
508
508
 
509
509
  // src/core/api/meta.ts
510
510
  var SUPPORTED = ["v1"];
@@ -660,7 +660,7 @@ var QoreApiClient = class {
660
660
  this.o = o;
661
661
  }
662
662
  o;
663
- async once(method, path2, body, force) {
663
+ async once(method, path2, body2, force) {
664
664
  const token = await this.o.token(force);
665
665
  const headers = {
666
666
  authorization: `Bearer ${token}`,
@@ -669,13 +669,13 @@ var QoreApiClient = class {
669
669
  "qore-command": this.o.command,
670
670
  "user-agent": `qore/${this.o.cliVersion} (${this.o.platform})`
671
671
  };
672
- if (body !== void 0) headers["content-type"] = "application/json";
672
+ if (body2 !== void 0) headers["content-type"] = "application/json";
673
673
  let res;
674
674
  try {
675
675
  res = await this.o.fetch(`${this.o.apiOrigin}${path2}`, {
676
676
  method,
677
677
  headers,
678
- body: body === void 0 ? void 0 : JSON.stringify(body)
678
+ body: body2 === void 0 ? void 0 : JSON.stringify(body2)
679
679
  });
680
680
  } catch (e) {
681
681
  throw fetchError(e, new URL(this.o.apiOrigin).host);
@@ -684,10 +684,10 @@ var QoreApiClient = class {
684
684
  this.o.onRequest?.(`${method} ${path2} \u2192 ${res.status}${rid ? ` (${rid})` : ""}`);
685
685
  return res;
686
686
  }
687
- async request(method, path2, body, parse2 = (r) => r.json()) {
688
- let res = await this.once(method, path2, body, false);
687
+ async request(method, path2, body2, parse2 = (r) => r.json()) {
688
+ let res = await this.once(method, path2, body2, false);
689
689
  if (res.status === 401) {
690
- res = await this.once(method, path2, body, true);
690
+ res = await this.once(method, path2, body2, true);
691
691
  if (res.status === 401) {
692
692
  const skew = clockSkewSeconds(res.headers.get("date"), (this.o.now ?? (() => /* @__PURE__ */ new Date()))());
693
693
  if (skew !== null && Math.abs(skew) > 60) {
@@ -714,8 +714,8 @@ var QoreApiClient = class {
714
714
  getText(path2) {
715
715
  return this.request("GET", path2, void 0, (r) => r.text());
716
716
  }
717
- post(path2, body) {
718
- return this.request("POST", path2, body);
717
+ post(path2, body2) {
718
+ return this.request("POST", path2, body2);
719
719
  }
720
720
  };
721
721
 
@@ -1362,14 +1362,23 @@ async function subdirs(dir2) {
1362
1362
  }
1363
1363
  async function scanRoot(root) {
1364
1364
  const out = [];
1365
- for (const tenant of (await subdirs(root)).sort()) {
1366
- for (const app of (await subdirs(join6(root, tenant))).sort()) {
1367
- const path2 = join6(root, tenant, app);
1368
- try {
1369
- const ws = await readWorkspace(path2);
1370
- if (ws) out.push({ kind: "workspace", path: path2, portal: ws.portal, tenantSlug: tenant, appId: ws.appId, appSlug: app });
1371
- } catch {
1372
- }
1365
+ for (const top of (await subdirs(root)).sort()) {
1366
+ if (top.startsWith("@")) {
1367
+ for (const tenant of (await subdirs(join6(root, top))).sort()) out.push(...await scanTenant(join6(root, top), tenant));
1368
+ } else {
1369
+ out.push(...await scanTenant(root, top));
1370
+ }
1371
+ }
1372
+ return out;
1373
+ }
1374
+ async function scanTenant(base, tenant) {
1375
+ const out = [];
1376
+ for (const app of (await subdirs(join6(base, tenant))).sort()) {
1377
+ const path2 = join6(base, tenant, app);
1378
+ try {
1379
+ const ws = await readWorkspace(path2);
1380
+ if (ws) out.push({ kind: "workspace", path: path2, portal: ws.portal, tenantSlug: tenant, appId: ws.appId, appSlug: app });
1381
+ } catch {
1373
1382
  }
1374
1383
  }
1375
1384
  return out;
@@ -1459,7 +1468,8 @@ function isInside(parent, child) {
1459
1468
  }
1460
1469
  function scannedBy(root, e) {
1461
1470
  if (e.kind !== "workspace" || !isInside(root, e.path)) return false;
1462
- return relative2(root, e.path).split(sep).filter(Boolean).length === 2;
1471
+ const parts = relative2(root, e.path).split(sep).filter(Boolean);
1472
+ return parts[0].startsWith("@") ? parts.length === 3 : parts.length === 2;
1463
1473
  }
1464
1474
  async function writableError(path2) {
1465
1475
  const probe = join8(path2, `.qore-write-test-${randomBytes3(6).toString("hex")}`);
@@ -1571,6 +1581,44 @@ function unsafeSlugError(slug) {
1571
1581
  });
1572
1582
  }
1573
1583
 
1584
+ // src/core/portals.ts
1585
+ var portalLabel = (p) => p.builtin ?? p.apiOrigin;
1586
+ var FOLDER = /^@[a-z0-9][a-z0-9.-]*$/;
1587
+ function portalFolder(p) {
1588
+ if (p.builtin === "prod") return null;
1589
+ if (p.builtin) return `@${p.builtin}`;
1590
+ const url = new URL(p.apiOrigin);
1591
+ const folder = `@${url.hostname.toLowerCase()}${url.port ? `-${url.port}` : ""}`;
1592
+ if (!FOLDER.test(folder)) {
1593
+ throw new QoreError("QORE_ROOT_INVALID", `${p.apiOrigin} cannot be a folder in the projects root`, {
1594
+ hint: "Pass a directory: qore clone <app> <dir>."
1595
+ });
1596
+ }
1597
+ return folder;
1598
+ }
1599
+ var ORDER = ["prod", "staging", "testing"];
1600
+ var rank = (p) => p.builtin ? ORDER.indexOf(p.builtin) : ORDER.length;
1601
+ async function loggedInPortals(deps2) {
1602
+ const cfg = await deps2.config.read();
1603
+ const active = resolvePortal(void 0, cfg.defaultProfile).apiOrigin;
1604
+ const out = [];
1605
+ for (const p of Object.values(cfg.profiles)) {
1606
+ if (!await new TokenStore(deps2.keychain, profileHash(p.apiOrigin, p.issuer)).getRefresh()) continue;
1607
+ const portal = resolvePortal(p.apiOrigin, void 0);
1608
+ out.push({ portal, label: portalLabel(portal), email: p.email ?? null, active: portal.apiOrigin === active });
1609
+ }
1610
+ return out.sort((a, b) => rank(a.portal) - rank(b.portal) || a.portal.apiOrigin.localeCompare(b.portal.apiOrigin));
1611
+ }
1612
+ async function setActivePortal(deps2, apiOrigin) {
1613
+ await deps2.config.update((c) => {
1614
+ if (apiOrigin === void 0) delete c.defaultProfile;
1615
+ else c.defaultProfile = apiOrigin;
1616
+ });
1617
+ }
1618
+
1619
+ // src/cli/portalNote.ts
1620
+ var portalNote = (p) => p.builtin === "prod" ? "" : ` (${portalLabel(p)})`;
1621
+
1574
1622
  // src/cli/workspaceReport.ts
1575
1623
  function exitFor(results) {
1576
1624
  const failures = results.filter((r) => r.status === "failed" || r.status === "conflict");
@@ -1725,7 +1773,8 @@ async function cloneApp(ctx, appArg, dirArg, flags) {
1725
1773
  const projectsRoot = cfg.projectsRoot;
1726
1774
  if (dirArg === void 0 && !isSafeSlug(app.app.slug)) throw unsafeSlugError(app.app.slug);
1727
1775
  if (dirArg === void 0 && projectsRoot && !isSafeSlug(app.app.tenant.slug)) throw unsafeSlugError(app.app.tenant.slug);
1728
- const root = dirArg !== void 0 ? resolve4(deps2.cwd, dirArg) : projectsRoot ? join9(projectsRoot, app.app.tenant.slug, app.app.slug) : resolve4(deps2.cwd, app.app.slug);
1776
+ const folder = dirArg === void 0 && projectsRoot ? portalFolder(portal) : null;
1777
+ const root = dirArg !== void 0 ? resolve4(deps2.cwd, dirArg) : projectsRoot ? join9(projectsRoot, ...folder ? [folder] : [], app.app.tenant.slug, app.app.slug) : resolve4(deps2.cwd, app.app.slug);
1729
1778
  const dirLabel = dirArg ?? (projectsRoot ? root : app.app.slug);
1730
1779
  const info = await deps2.git.inspect(root);
1731
1780
  if (info.exists && !info.empty) {
@@ -1769,7 +1818,7 @@ async function cloneApp(ctx, appArg, dirArg, flags) {
1769
1818
  const results = [...earlyFailures, ...applied];
1770
1819
  const err = reportWorkspaceRun(io2, results, Boolean(g.json));
1771
1820
  if (!g.json) {
1772
- io2.out(`\u2713 Wrote ${join9(dirLabel, "qore.workspace.json")}`);
1821
+ io2.out(`\u2713 Wrote ${join9(dirLabel, "qore.workspace.json")}${portalNote(portal)}`);
1773
1822
  const first = results.find((r) => r.status === "cloned" || r.status === "present");
1774
1823
  if (first && !err) io2.out(`Next: cd ${join9(dirLabel, first.slug)} && qore env pull`);
1775
1824
  }
@@ -1778,7 +1827,7 @@ async function cloneApp(ctx, appArg, dirArg, flags) {
1778
1827
  return { root, appSlug: app.app.slug };
1779
1828
  }
1780
1829
  function registerClone(program, ctx) {
1781
- program.command("clone").description("Clone an app's modules into a new workspace directory").argument("[app]", "app slug or id (omit to pick one interactively)").argument("[dir]", "target directory (default: the app's slug)").option("--tenant <slug>", "tenant the app slug belongs to, when it is not your active one").addOption(new Option("--protocol <https|ssh>", "clone URL protocol").choices(["https", "ssh"]).default("https")).action(async (appArg, dirArg, flags) => {
1830
+ program.command("clone").description("Clone an app's modules into a new workspace directory").argument("[app]", "app slug or id (omit to pick one interactively)").argument("[dir]", "target directory (default: the app's slug)").option("--tenant <slug>", "tenant the app slug belongs to, when it is not your active one").addOption(new Option2("--protocol <https|ssh>", "clone URL protocol").choices(["https", "ssh"]).default("https")).action(async (appArg, dirArg, flags) => {
1782
1831
  await cloneApp(ctx, appArg, dirArg, flags);
1783
1832
  });
1784
1833
  }
@@ -1866,8 +1915,8 @@ var SKIPPABLE = /* @__PURE__ */ new Set([
1866
1915
  ]);
1867
1916
  var label = (p) => p.builtin ?? p.apiOrigin;
1868
1917
  function byPreference(remotes2) {
1869
- const rank = (r) => r.name === "origin" ? 0 : r.name === "upstream" ? 1 : 2;
1870
- return [...remotes2].sort((a, b) => rank(a) - rank(b));
1918
+ const rank2 = (r) => r.name === "origin" ? 0 : r.name === "upstream" ? 1 : 2;
1919
+ return [...remotes2].sort((a, b) => rank2(a) - rank2(b));
1871
1920
  }
1872
1921
  var preferred = (remotes2) => byPreference(remotes2)[0];
1873
1922
  async function repoRemotes(deps2) {
@@ -1995,8 +2044,8 @@ async function workspaceRoot(deps2) {
1995
2044
  }
1996
2045
  function profileOrder(cfg, cachedOrigins, portalArg, wsPortal) {
1997
2046
  if (portalArg) return [resolvePortal(portalArg, cfg.defaultProfile)];
1998
- const rank = (o) => o === BUILTIN_PORTALS.prod.apiOrigin ? 0 : o === BUILTIN_PORTALS.staging.apiOrigin ? 1 : o === BUILTIN_PORTALS.testing.apiOrigin ? 2 : 3;
1999
- const rest = Object.keys(cfg.profiles).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
2047
+ const rank2 = (o) => o === BUILTIN_PORTALS.prod.apiOrigin ? 0 : o === BUILTIN_PORTALS.staging.apiOrigin ? 1 : o === BUILTIN_PORTALS.testing.apiOrigin ? 2 : 3;
2048
+ const rest = Object.keys(cfg.profiles).sort((a, b) => rank2(a) - rank2(b) || a.localeCompare(b));
2000
2049
  const cached2 = cachedOrigins.filter((c) => cfg.profiles[c]);
2001
2050
  const origins = [...wsPortal ? [wsPortal.apiOrigin] : [], ...cached2, resolvePortal(void 0, cfg.defaultProfile).apiOrigin, ...rest];
2002
2051
  return [...new Set(origins)].filter((c) => cfg.profiles[c]).map((c) => resolvePortal(c, void 0));
@@ -2497,12 +2546,13 @@ async function readRepoConfig(root) {
2497
2546
 
2498
2547
  // src/core/env/fetch.ts
2499
2548
  async function fetchLocalEnv(deps2, mc, app) {
2500
- await ensureCapability(deps2, mc.portal.apiOrigin, "module.local-env");
2549
+ const meta = await ensureCapability(deps2, mc.portal.apiOrigin, "module.local-env");
2501
2550
  try {
2502
2551
  const local = await mc.session.api.get(
2503
2552
  `/api/cli/v1/modules/${encodeURIComponent(mc.module.id)}/local-env?app_id=${encodeURIComponent(app.id)}`
2504
2553
  );
2505
2554
  deps2.registerSecrets(Object.values(local.env));
2555
+ if (!meta.capabilities.includes("module.local-env-rules")) delete local.rules;
2506
2556
  return local;
2507
2557
  } catch (e) {
2508
2558
  if (!(e instanceof QoreError) || e.code !== "QORE_ACCESS_DENIED") throw e;
@@ -2519,14 +2569,50 @@ async function fetchLocalEnv(deps2, mc, app) {
2519
2569
  }
2520
2570
 
2521
2571
  // src/core/env/merge.ts
2572
+ var KEY_LINE = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
2573
+ var stripCr = (line2) => line2.replace(/\r$/, "");
2574
+ var expandDouble = (raw) => raw.replace(/\\[nr]/g, (e) => e === "\\n" ? "\n" : "\r");
2575
+ function readValue(lines, at, rest) {
2576
+ const quote = rest[0];
2577
+ if (quote === '"' || quote === "'" || quote === "`") {
2578
+ let raw = "";
2579
+ let chunk = rest.slice(1);
2580
+ for (let j = at; ; ) {
2581
+ const end2 = chunk.indexOf(quote);
2582
+ if (end2 >= 0) {
2583
+ raw += chunk.slice(0, end2);
2584
+ return { value: quote === '"' ? expandDouble(raw) : raw, last: j };
2585
+ }
2586
+ raw += chunk + "\n";
2587
+ j++;
2588
+ if (j >= lines.length) break;
2589
+ chunk = stripCr(lines[j] ?? "");
2590
+ }
2591
+ }
2592
+ return { value: rest, last: at };
2593
+ }
2594
+ function readEntries(lines) {
2595
+ const entries = [];
2596
+ for (let i = 0; i < lines.length; i++) {
2597
+ const m = stripCr(lines[i] ?? "").match(KEY_LINE);
2598
+ if (m?.[1] === void 0 || m[2] === void 0) continue;
2599
+ const { value, last } = readValue(lines, i, m[2]);
2600
+ entries.push({ key: m[1], value, first: i, last });
2601
+ i = last;
2602
+ }
2603
+ return entries;
2604
+ }
2522
2605
  function parseEnv(contents) {
2523
2606
  const map = /* @__PURE__ */ new Map();
2524
- for (const line2 of contents.split("\n")) {
2525
- const m = line2.replace(/\r$/, "").match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
2526
- if (m?.[1] !== void 0 && m[2] !== void 0) map.set(m[1], m[2]);
2527
- }
2607
+ for (const { key: key2, value } of readEntries(contents.split("\n"))) map.set(key2, value);
2528
2608
  return map;
2529
2609
  }
2610
+ function renderValue(value) {
2611
+ if (!/[\r\n#"'`]|^\s|\s$/.test(value)) return value;
2612
+ if (!/["\\\r]/.test(value)) return `"${value.replace(/\n/g, "\\n")}"`;
2613
+ if (!value.includes("'")) return `'${value}'`;
2614
+ return `\`${value}\``;
2615
+ }
2530
2616
  function isManagedKey(key2, managed) {
2531
2617
  for (const pattern of managed) {
2532
2618
  if (pattern.endsWith("*")) {
@@ -2571,25 +2657,35 @@ function planEnvUpdate({
2571
2657
  }
2572
2658
  return { merged, conflicts, added, unchanged, overwritten };
2573
2659
  }
2660
+ var renderEntry = (key2, value, eol) => `${key2}=${renderValue(value)}`.replace(/\r?\n/g, eol);
2574
2661
  function renderEnv(original, merged) {
2575
2662
  const seen = /* @__PURE__ */ new Set();
2576
2663
  const lines = original.split("\n");
2577
- const out = lines.map((line2) => {
2578
- const m = line2.replace(/\r$/, "").match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
2579
- if (!m?.[1]) return line2;
2580
- const key2 = m[1];
2581
- if (!merged.has(key2)) return line2;
2664
+ const eol = /\r?\n/.exec(original)?.[0] ?? "\n";
2665
+ const out = [];
2666
+ let next = 0;
2667
+ for (const { key: key2, value, first, last } of readEntries(lines)) {
2668
+ out.push(...lines.slice(next, first));
2669
+ next = last + 1;
2670
+ if (!merged.has(key2) || merged.get(key2) === value) {
2671
+ out.push(...lines.slice(first, next));
2672
+ if (merged.has(key2)) seen.add(key2);
2673
+ continue;
2674
+ }
2582
2675
  seen.add(key2);
2583
- return `${key2}=${merged.get(key2) ?? ""}`;
2584
- });
2676
+ const cr = lines[last]?.endsWith("\r") ? "\r" : "";
2677
+ out.push(renderEntry(key2, merged.get(key2) ?? "", `${cr}
2678
+ `) + cr);
2679
+ }
2680
+ out.push(...lines.slice(next));
2585
2681
  const appended = [];
2586
2682
  for (const [key2, value] of merged) {
2587
- if (!seen.has(key2)) appended.push(`${key2}=${value}`);
2683
+ if (!seen.has(key2)) appended.push(renderEntry(key2, value, eol));
2588
2684
  }
2589
2685
  let text2 = out.join("\n");
2590
2686
  if (appended.length) {
2591
- if (text2.length && !text2.endsWith("\n")) text2 += "\n";
2592
- text2 += appended.join("\n") + "\n";
2687
+ if (text2.length && !text2.endsWith("\n")) text2 += eol;
2688
+ text2 += appended.join(eol) + eol;
2593
2689
  }
2594
2690
  return text2;
2595
2691
  }
@@ -2643,7 +2739,7 @@ function planPull(o) {
2643
2739
  for (const key2 of o.localSecrets) {
2644
2740
  const v = r.merged.get(key2);
2645
2741
  if (v === void 0 || v === "" || v === '""' || v === "''") {
2646
- r.merged.set(key2, o.random());
2742
+ r.merged.set(key2, o.random(key2));
2647
2743
  generated.push(key2);
2648
2744
  }
2649
2745
  }
@@ -2686,6 +2782,13 @@ async function writeSecurely(target, text2) {
2686
2782
  });
2687
2783
  }
2688
2784
  }
2785
+ function isGitIgnored(git, repoRoot, file) {
2786
+ return git.checkIgnore(repoRoot, file);
2787
+ }
2788
+ function notIgnoredWarning(file, repo) {
2789
+ const shown = repo ? join13(repo, file) : file;
2790
+ return `${shown} is not ignored by git. Add it to .gitignore; if it is already committed, run git ${repo ? `-C ${repo} ` : ""}rm --cached ${file}.`;
2791
+ }
2689
2792
  async function syncEnvFile(o) {
2690
2793
  const existing = await readOrNull(o.target);
2691
2794
  const plan = planPull({
@@ -2699,7 +2802,7 @@ async function syncEnvFile(o) {
2699
2802
  });
2700
2803
  if (existing !== null && plan.text === existing) await chmod2(o.target, 384);
2701
2804
  else await writeSecurely(o.target, plan.text);
2702
- return { created: plan.created, kept: plan.kept };
2805
+ return { created: plan.created, kept: plan.kept, ignored: await isGitIgnored(o.git, o.repoRoot, o.target) };
2703
2806
  }
2704
2807
 
2705
2808
  // src/core/erd/source.ts
@@ -2713,7 +2816,7 @@ async function resolveDatabaseUrl(deps2, mc, app) {
2713
2816
  const cfg = await readRepoConfig(mc.repoRoot);
2714
2817
  const envFile = await resolveTarget(mc.repoRoot, cfg.envFile ?? moduleDefaults(mc.module.type).envFile);
2715
2818
  const text2 = await readOrNull(envFile);
2716
- const url2 = text2 === null ? void 0 : parseEnv(text2).get("DATABASE_URL")?.trim().replace(/^["']|["']$/g, "");
2819
+ const url2 = text2 === null ? void 0 : parseEnv(text2).get("DATABASE_URL")?.trim();
2717
2820
  if (url2) {
2718
2821
  deps2.registerSecrets([url2]);
2719
2822
  return { url: url2, source: "env-file", envFile };
@@ -2770,9 +2873,9 @@ async function serveErd(o) {
2770
2873
  const produce = o.routes[path2];
2771
2874
  if (produce) {
2772
2875
  try {
2773
- const body = JSON.stringify(await produce());
2876
+ const body2 = JSON.stringify(await produce());
2774
2877
  res.writeHead(200, { "content-type": TYPES[".json"], "cache-control": "no-store" });
2775
- res.end(body);
2878
+ res.end(body2);
2776
2879
  return;
2777
2880
  } catch (e) {
2778
2881
  try {
@@ -2787,9 +2890,9 @@ async function serveErd(o) {
2787
2890
  const file = resolve6(root, `.${path2 === "/" ? "/index.html" : path2}`);
2788
2891
  if (file !== root && !file.startsWith(root + sep3)) return end(res, 404);
2789
2892
  try {
2790
- const body = await readFile6(file);
2893
+ const body2 = await readFile6(file);
2791
2894
  res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream" });
2792
- res.end(body);
2895
+ res.end(body2);
2793
2896
  } catch {
2794
2897
  end(res, 404);
2795
2898
  }
@@ -2853,7 +2956,7 @@ function sourceText(mc) {
2853
2956
  }
2854
2957
  function contextLine(mc, app) {
2855
2958
  const parts = [mc.module.tenant.name, ...app ? [app.name] : [], mc.module.slug];
2856
- return `\u2192 ${parts.join(" / ")} (${sourceText(mc)})`;
2959
+ return `\u2192 ${parts.join(" / ")} (${sourceText(mc)})${portalNote(mc.portal)}`;
2857
2960
  }
2858
2961
  function contextJson(mc, app) {
2859
2962
  const { id, slug, name, type, access: access2 } = mc.module;
@@ -2873,14 +2976,26 @@ import { join as join14 } from "path";
2873
2976
 
2874
2977
  // src/core/projects/match.ts
2875
2978
  function readings(ref) {
2876
- const s = ref.split("/").map((x) => x.trim());
2979
+ const all = ref.split("/").map((x) => x.trim());
2980
+ if (all[0]?.startsWith("@")) return all.length > 1 ? plain(all.slice(1)).map((w) => ({ ...w, portal: all[0] })) : [];
2981
+ return plain(all);
2982
+ }
2983
+ function plain(s) {
2877
2984
  if (s.some((x) => x === "")) return [];
2878
2985
  if (s.length === 1) return [{ app: s[0] }];
2879
2986
  if (s.length === 2) return [{ app: s[0], module: s[1] }, { tenant: s[0], app: s[1] }];
2880
2987
  if (s.length === 3) return [{ tenant: s[0], app: s[1], module: s[2] }];
2881
2988
  return [];
2882
2989
  }
2990
+ function folderOf(origin) {
2991
+ try {
2992
+ return portalFolder(resolvePortal(origin, void 0));
2993
+ } catch {
2994
+ return null;
2995
+ }
2996
+ }
2883
2997
  function hit(p, w) {
2998
+ if (w.portal !== void 0 && folderOf(p.portal) !== w.portal) return null;
2884
2999
  if (p.appSlug !== w.app || w.tenant !== void 0 && p.tenantSlug !== w.tenant) return null;
2885
3000
  if (p.kind === "module") return w.module === p.moduleSlug ? { project: p } : null;
2886
3001
  return w.module ? { project: p, module: w.module } : { project: p };
@@ -2905,8 +3020,19 @@ async function loggedInAs(ctx) {
2905
3020
  return p.email ?? p.sub ?? portal.apiOrigin;
2906
3021
  }
2907
3022
  var isDir = async (p) => (await stat3(p).catch(() => null))?.isDirectory() ?? false;
2908
- var label2 = (p) => `${p.tenantSlug} / ${p.appSlug}${p.kind === "module" ? ` / ${p.moduleSlug}` : ""}${p.source === "registry" ? ` (${p.path})` : ""}`;
2909
- var candidate = (p) => p.kind === "module" ? { kind: "module", id: p.moduleId, slug: p.moduleSlug, tenant: p.tenantSlug, name: p.path } : { kind: "app", slug: p.appSlug, tenant: p.tenantSlug, name: p.path };
3023
+ function folderOf2(p) {
3024
+ try {
3025
+ return portalFolder(resolvePortal(p.portal, void 0));
3026
+ } catch {
3027
+ return null;
3028
+ }
3029
+ }
3030
+ var label2 = (p) => `${folderOf2(p) ? `${folderOf2(p)} ` : ""}${p.tenantSlug} / ${p.appSlug}${p.kind === "module" ? ` / ${p.moduleSlug}` : ""}${p.source === "registry" ? ` (${p.path})` : ""}`;
3031
+ var candidate = (p) => {
3032
+ const portal = folderOf2(p);
3033
+ const base = p.kind === "module" ? { kind: "module", id: p.moduleId, slug: p.moduleSlug, tenant: p.tenantSlug, name: p.path } : { kind: "app", slug: p.appSlug, tenant: p.tenantSlug, name: p.path };
3034
+ return portal ? { ...base, portal } : base;
3035
+ };
2910
3036
  var withCwd = (ctx, cwd) => ({ ...ctx, deps: { ...ctx.deps, cwd } });
2911
3037
  async function standingIn(ctx) {
2912
3038
  if (await findWorkspace(ctx.deps.cwd, ctx.deps.home)) return "workspace";
@@ -3412,7 +3538,7 @@ async function loadLastStart(deps2, root) {
3412
3538
  function envPort(env, key2) {
3413
3539
  const raw = env[key2];
3414
3540
  if (raw === void 0) return null;
3415
- const v = raw.trim().replace(/^["']|["']$/g, "");
3541
+ const v = raw.trim();
3416
3542
  if (!/^\d+$/.test(v)) return null;
3417
3543
  const n = Number(v);
3418
3544
  return n >= 1024 && n <= 65535 ? n : null;
@@ -3431,7 +3557,9 @@ async function devEnv(deps2, o) {
3431
3557
  fetched: local.env,
3432
3558
  managed: local.managedKeys,
3433
3559
  localSecrets: o.cfg.localSecrets ?? defaults.localSecrets,
3434
- random: o.random
3560
+ random: (key2) => o.random(key2, local.rules?.[key2]),
3561
+ git: deps2.git,
3562
+ repoRoot: o.root
3435
3563
  });
3436
3564
  return {
3437
3565
  env: local.env,
@@ -3453,7 +3581,27 @@ async function devEnv(deps2, o) {
3453
3581
  });
3454
3582
  }
3455
3583
  const env = Object.fromEntries(parseEnv(text2));
3456
- return { env, offline: true, envFile: target, port: envPort(env, "PORT"), dbPort: envPort(env, "DB_PORT"), created: false, kept: [] };
3584
+ return { env, offline: true, envFile: target, port: envPort(env, "PORT"), dbPort: envPort(env, "DB_PORT"), created: false, kept: [], ignored: null };
3585
+ }
3586
+
3587
+ // src/core/env/secret.ts
3588
+ var DEFAULT_LENGTH = 64;
3589
+ function body(format, length, bytes) {
3590
+ if (length === 0) return "";
3591
+ if (format === "hex") return bytes(Math.ceil(length / 2)).toString("hex").slice(0, length);
3592
+ return bytes(Math.ceil(length * 3 / 4)).toString(format).slice(0, length);
3593
+ }
3594
+ function generateSecret(rules, bytes) {
3595
+ const prefix = rules?.startsWith ?? "";
3596
+ const suffix = rules?.endsWith ?? "";
3597
+ const format = rules?.format ?? "hex";
3598
+ let length = Math.max(rules?.minLength ?? 0, DEFAULT_LENGTH);
3599
+ if (rules?.maxLength !== void 0) length = Math.min(length, rules.maxLength);
3600
+ if (format === "base64" && length % 4) {
3601
+ const up = length + 4 - length % 4;
3602
+ length = rules?.maxLength === void 0 || up <= rules.maxLength ? up : length - length % 4;
3603
+ }
3604
+ return prefix + body(format, Math.max(0, length - prefix.length - suffix.length), bytes) + suffix;
3457
3605
  }
3458
3606
 
3459
3607
  // src/core/workspace/access.ts
@@ -3556,6 +3704,16 @@ function providerDown(o) {
3556
3704
  action: { command: o.fix }
3557
3705
  };
3558
3706
  }
3707
+ function noLocalRole(o) {
3708
+ return {
3709
+ code: "dev.no-local-role",
3710
+ severity: "warn",
3711
+ module: o.slug,
3712
+ message: `You have no role on local in ${o.app} \u2014 signing in to ${o.slug} will be refused.`,
3713
+ why: o.known.length > 0 ? `Roles known on local: ${o.known.join(", ")}. Sign in again after taking one.` : "Local knows no roles yet; `qore roles use` also announces the roles in your code. Sign in again after taking one.",
3714
+ action: { command: `${o.cd}${o.known.length === 1 ? `qore roles use ${o.known[0]}` : "qore roles use <role>"}` }
3715
+ };
3716
+ }
3559
3717
 
3560
3718
  // src/core/dev/project.ts
3561
3719
  import { access, readFile as readFile7 } from "fs/promises";
@@ -4003,6 +4161,63 @@ async function leftoverOwnsPort(deps2, run4, port) {
4003
4161
  return false;
4004
4162
  }
4005
4163
 
4164
+ // src/core/roles/api.ts
4165
+ var CAPABILITY = "module.local-roles";
4166
+ var path = (mc, app) => `/api/cli/v1/modules/${encodeURIComponent(mc.module.id)}/local-roles?app_id=${encodeURIComponent(app.id)}`;
4167
+ async function fetchLocalRoles(deps2, mc, app) {
4168
+ await ensureCapability(deps2, mc.portal.apiOrigin, CAPABILITY);
4169
+ return explained(mc, () => mc.session.api.get(path(mc, app)));
4170
+ }
4171
+ async function useLocalRoles(deps2, mc, app, roles, use) {
4172
+ await ensureCapability(deps2, mc.portal.apiOrigin, CAPABILITY);
4173
+ return explained(mc, () => mc.session.api.post(path(mc, app), { roles, use }));
4174
+ }
4175
+ var ANNOUNCE_CAPABILITY = "module.local-roles-announce";
4176
+ async function announceLocalRoles(deps2, mc, app, roles) {
4177
+ await ensureCapability(deps2, mc.portal.apiOrigin, ANNOUNCE_CAPABILITY);
4178
+ return explained(mc, () => mc.session.api.post(path(mc, app), { roles }));
4179
+ }
4180
+ async function explained(mc, call) {
4181
+ try {
4182
+ return await call();
4183
+ } catch (e) {
4184
+ if (!(e instanceof QoreError)) throw e;
4185
+ if (e.serverCode === "app.access.denied") {
4186
+ throw withDetails(
4187
+ e,
4188
+ { required: "write", have: mc.module.access },
4189
+ `You have ${mc.module.access} on ${mc.module.slug}; local roles need write. Ask a maintainer of the app's dev team for write access.`
4190
+ );
4191
+ }
4192
+ if (e.serverCode === "membership.permission.denied") {
4193
+ throw withDetails(e, {}, "Taking roles on this app needs write on one of its dev teams.");
4194
+ }
4195
+ if (e.serverCode === "auth.scope.insufficient") throw withDetails(e, {}, "Run `qore login` again.");
4196
+ if (e.serverCode === "app.no_platform_identity") {
4197
+ throw new QoreError("QORE_CONTEXT_UNSUPPORTED", "This app manages its own users; the portal hands out no roles for it", {
4198
+ hint: "Give yourself the role in the app's own user admin.",
4199
+ serverCode: e.serverCode,
4200
+ requestId: e.requestId
4201
+ });
4202
+ }
4203
+ throw e;
4204
+ }
4205
+ }
4206
+
4207
+ // src/core/dev/localRole.ts
4208
+ async function localRoleFinding(deps2, mc, app, env, cd) {
4209
+ if (!env.KC_CLIENT_ID) return null;
4210
+ try {
4211
+ if (!(await metaFor(deps2, mc.portal.apiOrigin)).capabilities.includes("module.local-roles")) return null;
4212
+ const roles = await fetchLocalRoles(deps2, mc, app);
4213
+ if (roles.effective.length > 0) return null;
4214
+ return noLocalRole({ slug: mc.module.slug, app: app.slug, known: roles.roles.map((r) => r.slug), cd });
4215
+ } catch (e) {
4216
+ if (e instanceof QoreError) return null;
4217
+ throw e;
4218
+ }
4219
+ }
4220
+
4006
4221
  // src/core/dev/providers.ts
4007
4222
  var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
4008
4223
  function connPorts(env) {
@@ -4616,7 +4831,7 @@ async function prepareWorkspace(ctx, ws, f, waitTimeout, p) {
4616
4831
  const note = (human, event) => json2 ? io2.out(JSON.stringify(event)) : io2.err(human);
4617
4832
  const warn = (message, extra = {}) => note(`! ${message}`, { type: "warning", ...extra, message });
4618
4833
  const { am, online, offlineCause } = await workspaceContext(ctx, ws);
4619
- if (online && !json2) io2.err(`\u2192 ${am.app.tenant.name} / ${am.app.name} (qore.workspace.json)`);
4834
+ if (online && !json2) io2.err(`\u2192 ${am.app.tenant.name} / ${am.app.name} (qore.workspace.json)${portalNote(online.portal)}`);
4620
4835
  if (!online) warn("The portal is unreachable \u2014 starting every module from its env file as last written; values may be stale.");
4621
4836
  const color = !json2 && g.color !== false && !deps2.env.NO_COLOR;
4622
4837
  const problems = [];
@@ -4805,7 +5020,7 @@ async function prepareWorkspace(ctx, ws, f, waitTimeout, p) {
4805
5020
  type: u.m.type,
4806
5021
  moduleId: u.m.id,
4807
5022
  cfg: u.cfg,
4808
- random: () => randomBytes5(32).toString("hex")
5023
+ random: (_key, rules) => generateSecret(rules, randomBytes5)
4809
5024
  });
4810
5025
  } catch (e) {
4811
5026
  if (offlineCause && isOffline(e)) throw offlineCause;
@@ -4817,6 +5032,10 @@ async function prepareWorkspace(ctx, ws, f, waitTimeout, p) {
4817
5032
  if (online && dev.offline) {
4818
5033
  warn(`${slug}: the portal is unreachable \u2014 starting from ${relative6(rootReal, dev.envFile)} as last written; values may be stale.`, { module: slug });
4819
5034
  }
5035
+ if (dev.ignored === false) {
5036
+ const repo = await realpath7(u.dir);
5037
+ warn(`${slug}: ${notIgnoredWarning(relative6(repo, dev.envFile), relative6(rootReal, repo))}`, { module: slug });
5038
+ }
4820
5039
  if (dev.kept.length) {
4821
5040
  warn(
4822
5041
  `${slug}: ${dev.kept.length} key(s) differ locally and were kept: ${dev.kept.join(", ")} \u2014 qore env pull --use-portal takes the portal's values`,
@@ -4824,6 +5043,10 @@ async function prepareWorkspace(ctx, ws, f, waitTimeout, p) {
4824
5043
  );
4825
5044
  }
4826
5045
  report({ module: slug, step: "env", status: "done", detail: relative6(rootReal, dev.envFile) });
5046
+ if (online && !dev.offline) {
5047
+ const role = await localRoleFinding(deps2, mcFor(u), appRef, dev.env, cdPrefix(deps2.home, u.dir));
5048
+ if (role) renderFinding(ctx, role);
5049
+ }
4827
5050
  const services = servicesMissing(slug, dev.env, u.recipe, { servicesFlag: f.services, configured: u.cfg.dev?.services !== void 0 });
4828
5051
  if (services) renderFinding(ctx, services);
4829
5052
  try {
@@ -5079,14 +5302,15 @@ function parseWaitTimeout(raw) {
5079
5302
  var str3 = (v) => typeof v === "string" && v.length > 0;
5080
5303
  var SHELL_SAFE = /^[A-Za-z0-9_./,:@%+=-]*$/;
5081
5304
  var shellQuote = (s) => SHELL_SAFE.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
5082
- function cdAndDev(home, dir2) {
5083
- if (/^[A-Za-z]:[\\/]|^\\\\/.test(dir2)) return `cd ${/\s/.test(dir2) ? `"${dir2}"` : dir2} && qore dev`;
5305
+ function cdPrefix(home, dir2) {
5306
+ if (/^[A-Za-z]:[\\/]|^\\\\/.test(dir2)) return `cd ${/\s/.test(dir2) ? `"${dir2}"` : dir2} && `;
5084
5307
  const h = home.length > 1 ? home.replace(/\/+$/, "") : home;
5085
5308
  let target = shellQuote(dir2);
5086
5309
  if (h && dir2 === h) target = "~";
5087
5310
  else if (h && dir2.startsWith(h + "/")) target = `~/${shellQuote(dir2.slice(h.length + 1))}`;
5088
- return `cd ${target} && qore dev`;
5311
+ return `cd ${target} && `;
5089
5312
  }
5313
+ var cdAndDev = (home, dir2) => `${cdPrefix(home, dir2)}qore dev`;
5090
5314
  async function providerFindings(ctx, root, mc, app, env) {
5091
5315
  const { deps: deps2 } = ctx;
5092
5316
  try {
@@ -5234,7 +5458,7 @@ async function prepareModule(ctx, f, waitTimeout, p) {
5234
5458
  type: c.module.type,
5235
5459
  moduleId: c.module.id,
5236
5460
  cfg,
5237
- random: () => randomBytes6(32).toString("hex")
5461
+ random: (_key, rules) => generateSecret(rules, randomBytes6)
5238
5462
  });
5239
5463
  } catch (e) {
5240
5464
  if (c.offlineCause && isOffline(e)) throw c.offlineCause;
@@ -5242,6 +5466,7 @@ async function prepareModule(ctx, f, waitTimeout, p) {
5242
5466
  }
5243
5467
  const envFile = relative7(await realpath8(root), dev.envFile);
5244
5468
  if (dev.offline) io2.err(`! The portal is unreachable \u2014 starting from ${envFile} as last written; values may be stale.`);
5469
+ if (dev.ignored === false) io2.err(`! ${notIgnoredWarning(envFile)}`);
5245
5470
  if (dev.kept.length) {
5246
5471
  io2.err(`! ${dev.kept.length} key(s) differ locally and were kept: ${dev.kept.join(", ")} \u2014 qore env pull --use-portal takes the portal's values`);
5247
5472
  }
@@ -5253,6 +5478,8 @@ async function prepareModule(ctx, f, waitTimeout, p) {
5253
5478
  if (c.online && !dev.offline) {
5254
5479
  const provider = await providerFindings(ctx, root, c.online.mc, c.online.app, dev.env);
5255
5480
  if (provider) renderFinding(ctx, provider);
5481
+ const role = await localRoleFinding(deps2, c.online.mc, c.online.app, dev.env, "");
5482
+ if (role) renderFinding(ctx, role);
5256
5483
  }
5257
5484
  const services = servicesMissing(slug, dev.env, recipe, { servicesFlag: f.services, configured: cfg.dev?.services !== void 0 });
5258
5485
  if (services) renderFinding(ctx, services);
@@ -5347,7 +5574,7 @@ var noop = () => {
5347
5574
  var ok = (label3, details) => ({ status: "ok", label: label3, ...details ? { details } : {} });
5348
5575
  var withError = (status2, label3, e) => ({ status: status2, label: label3, error: toJsonError(e) });
5349
5576
  var isCancel = (e, signal) => e instanceof CancelledError || signal.aborted;
5350
- var portalLabel = (p) => p.builtin ?? p.apiOrigin;
5577
+ var portalLabel2 = (p) => p.builtin ?? p.apiOrigin;
5351
5578
  var ToolTimeout = class extends Error {
5352
5579
  constructor(tool, ms2) {
5353
5580
  super(`${tool} did not answer within ${Math.round(ms2 / 1e3)} s`);
@@ -5454,10 +5681,10 @@ async function checkSession(deps2, portal, onRequest, sessions, selected, signal
5454
5681
  const rt = await session.tokens.getRefresh();
5455
5682
  const days = rt ? validDays(rt, deps2.now()) : null;
5456
5683
  const valid = days === null ? "" : ` \xB7 session valid ${days} ${days === 1 ? "day" : "days"}`;
5457
- return ok(`Logged in to ${portalLabel(portal)} as ${me.email}${valid}`, { email: me.email, ...days !== null ? { validDays: days } : {} });
5684
+ return ok(`Logged in to ${portalLabel2(portal)} as ${me.email}${valid}`, { email: me.email, ...days !== null ? { validDays: days } : {} });
5458
5685
  } catch (e) {
5459
5686
  if (isCancel(e, signal) || selected) throw e;
5460
- return withError("warn", `${portalLabel(portal)}: ${errorLabel(e)}`, e);
5687
+ return withError("warn", `${portalLabel2(portal)}: ${errorLabel(e)}`, e);
5461
5688
  }
5462
5689
  }
5463
5690
  function checkClock(meta) {
@@ -5558,10 +5785,10 @@ async function checkRepoNode(deps2, m, recipe, pkg, signal, ms2) {
5558
5785
  const found = await timed("node", signal, ms2, (s) => checkNode(deps2, recipe, pkg, m.slug, s));
5559
5786
  return ok(`Node ${found ?? "?"} (engines ${pkg.engines.node})`);
5560
5787
  }
5561
- async function loggedInPortals(deps2, profiles) {
5562
- const rank = (o) => o === BUILTIN_PORTALS.prod.apiOrigin ? 0 : o === BUILTIN_PORTALS.staging.apiOrigin ? 1 : o === BUILTIN_PORTALS.testing.apiOrigin ? 2 : 3;
5788
+ async function loggedInPortals2(deps2, profiles) {
5789
+ const rank2 = (o) => o === BUILTIN_PORTALS.prod.apiOrigin ? 0 : o === BUILTIN_PORTALS.staging.apiOrigin ? 1 : o === BUILTIN_PORTALS.testing.apiOrigin ? 2 : 3;
5563
5790
  const out = [];
5564
- for (const origin of Object.keys(profiles).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))) {
5791
+ for (const origin of Object.keys(profiles).sort((a, b) => rank2(a) - rank2(b) || a.localeCompare(b))) {
5565
5792
  const p = profiles[origin];
5566
5793
  if (await new TokenStore(deps2.keychain, profileHash(p.apiOrigin, p.issuer)).getRefresh()) out.push(resolvePortal(origin, void 0));
5567
5794
  }
@@ -5573,7 +5800,7 @@ async function resolveRepoModule(deps2, session, portal, meta, root) {
5573
5800
  if (keys.length === 0) return { status: "warn", label: "this repository has no remote Qore can match" };
5574
5801
  const { matches } = await session.api.post("/api/cli/v1/repos/resolve", { repoKeys: keys });
5575
5802
  const ids = [...new Set(matches.map((x) => x.module.id))];
5576
- if (ids.length === 0) return { status: "warn", label: `this repository matches no module on ${portalLabel(portal)}` };
5803
+ if (ids.length === 0) return { status: "warn", label: `this repository matches no module on ${portalLabel2(portal)}` };
5577
5804
  if (ids.length > 1) {
5578
5805
  return { status: "warn", label: `this repository matches several modules (${[...new Set(matches.map((x) => x.module.slug))].join(", ")})` };
5579
5806
  }
@@ -5600,15 +5827,15 @@ async function runDoctor(deps2, o = {}) {
5600
5827
  const results = [];
5601
5828
  const context = { kind: "none" };
5602
5829
  const push = async (id, group, fn, module) => {
5603
- let body;
5830
+ let body2;
5604
5831
  try {
5605
- body = await fn();
5832
+ body2 = await fn();
5606
5833
  } catch (e) {
5607
- if (e instanceof ToolTimeout) body = { status: "warn", label: e.message, details: { timeoutMs: e.ms } };
5834
+ if (e instanceof ToolTimeout) body2 = { status: "warn", label: e.message, details: { timeoutMs: e.ms } };
5608
5835
  else if (isCancel(e, signal)) throw e;
5609
- else body = withError("fail", errorLabel(e), e);
5836
+ else body2 = withError("fail", errorLabel(e), e);
5610
5837
  }
5611
- const r = { id, group, ...module ? { module } : {}, ...body };
5838
+ const r = { id, group, ...module ? { module } : {}, ...body2 };
5612
5839
  results.push(r);
5613
5840
  return r;
5614
5841
  };
@@ -5647,7 +5874,7 @@ async function runDoctor(deps2, o = {}) {
5647
5874
  const sessions = /* @__PURE__ */ new Map();
5648
5875
  let loggedIn = [];
5649
5876
  try {
5650
- loggedIn = await loggedInPortals(deps2, cfg.profiles);
5877
+ loggedIn = await loggedInPortals2(deps2, cfg.profiles);
5651
5878
  if (loggedIn.length === 0) await push("session", "session", () => ({ status: "warn", label: "not logged in \u2014 qore login" }));
5652
5879
  } catch (e) {
5653
5880
  if (isCancel(e, signal)) throw e;
@@ -5657,7 +5884,7 @@ async function runDoctor(deps2, o = {}) {
5657
5884
  }
5658
5885
  for (const p of loggedIn) {
5659
5886
  await push(
5660
- `session:${portalLabel(p)}`,
5887
+ `session:${portalLabel2(p)}`,
5661
5888
  "session",
5662
5889
  () => checkSession(deps2, p, o.onRequest, sessions, p.apiOrigin === portal.apiOrigin, signal)
5663
5890
  );
@@ -5667,7 +5894,7 @@ async function runDoctor(deps2, o = {}) {
5667
5894
  const notChecked = () => push(
5668
5895
  "modules",
5669
5896
  "workspace",
5670
- () => ({ status: "warn", label: `modules not checked \u2014 no working session for ${portalLabel(portal)}` })
5897
+ () => ({ status: "warn", label: `modules not checked \u2014 no working session for ${portalLabel2(portal)}` })
5671
5898
  );
5672
5899
  const perModule = async (m, prepared) => {
5673
5900
  if (!prepared?.recipe) return;
@@ -5796,7 +6023,7 @@ function registerEnv(program, ctx) {
5796
6023
  managed: local.managedKeys,
5797
6024
  localSecrets: cfg.localSecrets ?? defaults.localSecrets,
5798
6025
  defaultChoice: f.usePortal ? "use-portal" : "keep",
5799
- random: () => randomBytes7(32).toString("hex")
6026
+ random: (key2) => generateSecret(local.rules?.[key2], randomBytes7)
5800
6027
  };
5801
6028
  let plan = planPull(inputs);
5802
6029
  if (plan.conflicts.length && io2.interactive && !f.usePortal) {
@@ -5843,6 +6070,7 @@ function registerEnv(program, ctx) {
5843
6070
  renderJson(io2, { context: contextJson(mc, app), target: rel, ...names });
5844
6071
  return;
5845
6072
  }
6073
+ if (await isGitIgnored(deps2.git, mc.repoRoot, target) === false) io2.err(`! ${notIgnoredWarning(rel)}`);
5846
6074
  if (plan.kept.length && !io2.interactive) {
5847
6075
  io2.err(`! ${plan.kept.length} key(s) differ locally and were kept: ${plan.kept.join(", ")} \u2014 --use-portal takes the portal's values`);
5848
6076
  }
@@ -6053,10 +6281,11 @@ async function obsContext(ctx, flags, command, o) {
6053
6281
  const window = windowOf(flags);
6054
6282
  const onRequest = g.verbose ? (l) => io2.err(l) : void 0;
6055
6283
  const ws = flags.module === void 0 || flags.module === "all" ? await workspaceRoot(deps2) : null;
6056
- let api, tenant, app, mods, base, apiOrigin;
6284
+ let api, tenant, app, mods, base, apiOrigin, note;
6057
6285
  if (ws) {
6058
6286
  const portal = await flagPortal(deps2, g.portal, ws);
6059
6287
  apiOrigin = portal.apiOrigin;
6288
+ note = portalNote(portal);
6060
6289
  const session = await openSession(deps2, portal, command, onRequest);
6061
6290
  await ensureCapability(deps2, apiOrigin, "module.observability");
6062
6291
  await ensureCapability(deps2, apiOrigin, "app.modules");
@@ -6069,6 +6298,7 @@ async function obsContext(ctx, flags, command, o) {
6069
6298
  } else {
6070
6299
  const mc = await moduleContextFor(ctx, { module: flags.module === "all" ? void 0 : flags.module }, command);
6071
6300
  apiOrigin = mc.portal.apiOrigin;
6301
+ note = portalNote(mc.portal);
6072
6302
  await ensureCapability(deps2, apiOrigin, "module.observability");
6073
6303
  app = await appFor(ctx, mc, flags.app);
6074
6304
  api = mc.session.api;
@@ -6098,7 +6328,7 @@ async function obsContext(ctx, flags, command, o) {
6098
6328
  fanOut: fanOut2,
6099
6329
  env,
6100
6330
  window,
6101
- header: `\u2192 ${tenant.name} / ${app.name} / ${where} \xB7 ${env} \xB7 ${windowText(window)}`,
6331
+ header: `\u2192 ${tenant.name} / ${app.name} / ${where} \xB7 ${env} \xB7 ${windowText(window)}${note}`,
6102
6332
  json: { ...base, ...fanOut2 ? { modules: targets.map((t) => t.module) } : { module: targets[0].module }, env, window }
6103
6333
  };
6104
6334
  }
@@ -6551,6 +6781,7 @@ function registerTenant(program, ctx) {
6551
6781
  const cfg = await deps2.config.read();
6552
6782
  const portal = resolvePortal(g.portal, cfg.defaultProfile);
6553
6783
  const { profile, api } = await openSession(deps2, portal, "tenant list", requestLog(ctx));
6784
+ if (!g.json && portalNote(portal)) io2.err(`\u2192 ${portalNote(portal).trim()}`);
6554
6785
  const me = await api.get("/api/cli/v1/me");
6555
6786
  const activeId = profile.activeTenant?.id;
6556
6787
  if (g.json) {
@@ -6565,7 +6796,7 @@ function registerTenant(program, ctx) {
6565
6796
  tenant.command("use").description("Set the active tenant").argument("[slug]", "tenant slug").action(async (slug) => {
6566
6797
  const chosen = await useTenant(ctx, slug);
6567
6798
  if (ctx.opts().json) renderJson(ctx.io, { activeTenant: chosen });
6568
- else ctx.io.out(`\u2713 Using tenant ${chosen.slug}`);
6799
+ else ctx.io.out(`\u2713 Using tenant ${chosen.slug}${portalNote(resolvePortal(ctx.opts().portal, (await ctx.deps.config.read()).defaultProfile))}`);
6569
6800
  });
6570
6801
  }
6571
6802
  async function useTenant(ctx, slug, known) {
@@ -6717,54 +6948,76 @@ function registerLogout(program, ctx) {
6717
6948
  });
6718
6949
  done.push(p.apiOrigin);
6719
6950
  }
6720
- if (g.json) renderJson(io2, { loggedOut: done });
6951
+ const next = await fallBack(ctx, cmd.all === true, resolvePortal(void 0, cfg.defaultProfile), done);
6952
+ if (g.json) renderJson(io2, { loggedOut: done, ...next !== void 0 ? { activePortal: next } : {} });
6721
6953
  else if (done.length === 0) io2.out("Not logged in");
6722
6954
  else io2.out(`\u2713 Logged out of ${done.map((o) => resolvePortal(o, void 0).builtin ?? o).join(", ")}`);
6955
+ if (next && !g.json) io2.out(`\u2713 Now using ${next}`);
6723
6956
  });
6724
6957
  }
6725
-
6726
- // src/core/roles/api.ts
6727
- var CAPABILITY = "module.local-roles";
6728
- var path = (mc, app) => `/api/cli/v1/modules/${encodeURIComponent(mc.module.id)}/local-roles?app_id=${encodeURIComponent(app.id)}`;
6729
- async function fetchLocalRoles(deps2, mc, app) {
6730
- await ensureCapability(deps2, mc.portal.apiOrigin, CAPABILITY);
6731
- return explained(mc, () => mc.session.api.get(path(mc, app)));
6732
- }
6733
- async function useLocalRoles(deps2, mc, app, roles, use) {
6734
- await ensureCapability(deps2, mc.portal.apiOrigin, CAPABILITY);
6735
- return explained(mc, () => mc.session.api.post(path(mc, app), { roles, use }));
6736
- }
6737
- var ANNOUNCE_CAPABILITY = "module.local-roles-announce";
6738
- async function announceLocalRoles(deps2, mc, app, roles) {
6739
- await ensureCapability(deps2, mc.portal.apiOrigin, ANNOUNCE_CAPABILITY);
6740
- return explained(mc, () => mc.session.api.post(path(mc, app), { roles }));
6958
+ async function fallBack(ctx, all, active, done) {
6959
+ if (all) {
6960
+ await setActivePortal(ctx.deps, void 0);
6961
+ return void 0;
6962
+ }
6963
+ if (active.builtin === "prod" || !done.includes(active.apiOrigin)) return void 0;
6964
+ const left = await loggedInPortals(ctx.deps);
6965
+ const next = left.find((p) => p.portal.builtin === "prod") ?? (left.length === 1 ? left[0] : void 0);
6966
+ await setActivePortal(ctx.deps, next?.portal.apiOrigin);
6967
+ return next?.label ?? null;
6741
6968
  }
6742
- async function explained(mc, call) {
6969
+
6970
+ // src/cli/commands/portal.ts
6971
+ var loggedInTo = (list) => `Logged in to: ${list.map((p) => p.label).join(", ")}.`;
6972
+ function named(name, list) {
6743
6973
  try {
6744
- return await call();
6974
+ return resolvePortal(name, void 0);
6745
6975
  } catch (e) {
6746
- if (!(e instanceof QoreError)) throw e;
6747
- if (e.serverCode === "app.access.denied") {
6748
- throw withDetails(
6749
- e,
6750
- { required: "write", have: mc.module.access },
6751
- `You have ${mc.module.access} on ${mc.module.slug}; local roles need write. Ask a maintainer of the app's dev team for write access.`
6752
- );
6753
- }
6754
- if (e.serverCode === "membership.permission.denied") {
6755
- throw withDetails(e, {}, "Taking roles on this app needs write on one of its dev teams.");
6756
- }
6757
- if (e.serverCode === "auth.scope.insufficient") throw withDetails(e, {}, "Run `qore login` again.");
6758
- if (e.serverCode === "app.no_platform_identity") {
6759
- throw new QoreError("QORE_CONTEXT_UNSUPPORTED", "This app manages its own users; the portal hands out no roles for it", {
6760
- hint: "Give yourself the role in the app's own user admin.",
6761
- serverCode: e.serverCode,
6762
- requestId: e.requestId
6763
- });
6764
- }
6765
- throw e;
6976
+ if (!(e instanceof QoreError) || e.code !== "QORE_CONTEXT_INVALID") throw e;
6977
+ throw new QoreError("QORE_CONTEXT_INVALID", e.message, {
6978
+ hint: list.length > 0 ? loggedInTo(list) : `Run \`qore login --portal ${name}\`.`
6979
+ });
6766
6980
  }
6767
6981
  }
6982
+ function registerPortal(program, ctx) {
6983
+ const portal = program.command("portal", { hidden: true }).description("Switch between portals you are logged in to");
6984
+ portal.command("use").description("Set the active portal").argument("[name]", "prod, staging, testing or a portal URL").action(async (name) => {
6985
+ const { deps: deps2, io: io2 } = ctx;
6986
+ const g = ctx.opts();
6987
+ const list = await loggedInPortals(deps2);
6988
+ let chosen;
6989
+ if (name !== void 0) {
6990
+ const ref = named(name, list);
6991
+ const found = list.find((p) => p.portal.apiOrigin === ref.apiOrigin);
6992
+ if (!found) {
6993
+ throw new QoreError("QORE_NOT_LOGGED_IN", `Not logged in to ${ref.builtin ?? ref.apiOrigin}`, {
6994
+ hint: `Run \`qore login --portal ${ref.builtin ?? ref.apiOrigin}\`.`
6995
+ });
6996
+ }
6997
+ chosen = found;
6998
+ } else if (list.length === 0) {
6999
+ throw new QoreError("QORE_NOT_LOGGED_IN", "Not logged in to any portal", { hint: "Run `qore login`." });
7000
+ } else if (list.length === 1) {
7001
+ chosen = list[0];
7002
+ if (chosen.active && !g.json) {
7003
+ io2.out(`\u2713 Already using ${chosen.label}`);
7004
+ return;
7005
+ }
7006
+ } else if (io2.interactive) {
7007
+ const origin = await io2.select("Select a portal", list.map((p) => ({
7008
+ name: `${p.label} ${p.email ?? ""}${p.active ? " (active)" : ""}`,
7009
+ value: p.portal.apiOrigin
7010
+ })));
7011
+ chosen = list.find((p) => p.portal.apiOrigin === origin);
7012
+ } else {
7013
+ throw new QoreError("QORE_CONTEXT_REQUIRED", "Which portal? Pass a name or run interactively.", { hint: loggedInTo(list) });
7014
+ }
7015
+ await setActivePortal(deps2, chosen.portal.apiOrigin);
7016
+ const profile = (await deps2.config.read()).profiles[chosen.portal.apiOrigin];
7017
+ if (g.json) renderJson(io2, { portal: chosen.label, email: chosen.email, activeTenant: profile?.activeTenant ?? null });
7018
+ else io2.out(`\u2713 Using ${chosen.label}${chosen.email ? ` (${chosen.email})` : ""}`);
7019
+ });
7020
+ }
6768
7021
 
6769
7022
  // src/core/roles/read.ts
6770
7023
  import { join as join26 } from "path";
@@ -6938,7 +7191,7 @@ async function appStatus(ctx, ws, appFlag) {
6938
7191
  hint: "Pass --module <slug> --app <slug>."
6939
7192
  });
6940
7193
  }
6941
- if (!g.json) io2.err(`\u2192 ${tenant.name} / ${app.name} (${WORKSPACE_FILE})`);
7194
+ if (!g.json) io2.err(`\u2192 ${tenant.name} / ${app.name} (${WORKSPACE_FILE})${portalNote(portal)}`);
6942
7195
  const modules = [];
6943
7196
  for (const m of am.modules.filter((x) => x.repoUrl !== null)) {
6944
7197
  const st = await session.api.get(
@@ -6994,7 +7247,7 @@ function registerStatus(program, ctx) {
6994
7247
 
6995
7248
  // src/cli/commands/sync.ts
6996
7249
  import { join as join27, relative as relative9 } from "path";
6997
- import { Option as Option2 } from "commander";
7250
+ import { Option as Option3 } from "commander";
6998
7251
  function asFailure2(slug, e) {
6999
7252
  if (e instanceof QoreError && e.code !== "QORE_GIT_UNAVAILABLE") {
7000
7253
  return { slug, status: "failed", error: { code: e.code, message: e.message, hint: e.hint } };
@@ -7002,7 +7255,7 @@ function asFailure2(slug, e) {
7002
7255
  throw e;
7003
7256
  }
7004
7257
  function registerSync(program, ctx) {
7005
- program.command("sync").description("Clone new modules, fetch present ones, report removed and re-pointed ones").option("--pull", "fast-forward every clean present repository with an upstream").addOption(new Option2("--protocol <https|ssh>", "clone URL protocol").choices(["https", "ssh"]).default("https")).action(async (flags) => {
7258
+ program.command("sync").description("Clone new modules, fetch present ones, report removed and re-pointed ones").option("--pull", "fast-forward every clean present repository with an upstream").addOption(new Option3("--protocol <https|ssh>", "clone URL protocol").choices(["https", "ssh"]).default("https")).action(async (flags) => {
7006
7259
  const { deps: deps2, io: io2 } = ctx;
7007
7260
  const g = ctx.opts();
7008
7261
  const ws = await findWorkspace(deps2.cwd, deps2.home);
@@ -7014,7 +7267,7 @@ function registerSync(program, ctx) {
7014
7267
  const session = await openSession(deps2, portal, "sync", onRequest);
7015
7268
  await ensureCapability(deps2, portal.apiOrigin, "app.modules");
7016
7269
  const app = await workspaceAppModules(session, portal, ws);
7017
- if (!g.json) io2.err(`\u2192 ${app.app.tenant.name} / ${app.app.name} (qore.workspace.json)`);
7270
+ if (!g.json) io2.err(`\u2192 ${app.app.tenant.name} / ${app.app.name} (qore.workspace.json)${portalNote(portal)}`);
7018
7271
  const slugs = new Set(app.modules.map((m) => m.slug));
7019
7272
  const dirs = {};
7020
7273
  const earlyFailures = [];
@@ -7216,6 +7469,7 @@ var COMMANDS = [
7216
7469
  registerLogout,
7217
7470
  registerWhoami,
7218
7471
  registerTenant,
7472
+ registerPortal,
7219
7473
  registerStatus,
7220
7474
  registerLogs,
7221
7475
  registerTraces,
@@ -7519,6 +7773,14 @@ async function status(repoRoot) {
7519
7773
  if (r.code !== 0) return { ok: false, stderr: r.stderr, command };
7520
7774
  return parseStatus(r.stdout);
7521
7775
  }
7776
+ async function checkIgnore(repoRoot, file) {
7777
+ try {
7778
+ const r = await runGit(["-C", repoRoot, "check-ignore", "-q", "--", file], repoRoot);
7779
+ return r.code === 0 ? true : r.code === 1 ? false : null;
7780
+ } catch {
7781
+ return null;
7782
+ }
7783
+ }
7522
7784
  async function statOrThrow(path2) {
7523
7785
  try {
7524
7786
  return await stat7(path2);
@@ -7542,7 +7804,7 @@ async function inspect(dir2) {
7542
7804
  const dirRemotes = isRepo ? await remotes(dir2) : [];
7543
7805
  return { exists: true, empty: empty2, isRepo, remotes: dirRemotes };
7544
7806
  }
7545
- var systemGit = { remotes, clone, fetch, pullFfOnly, status, inspect };
7807
+ var systemGit = { remotes, clone, fetch, pullFfOnly, status, inspect, checkIgnore };
7546
7808
 
7547
7809
  // src/platform/keychain.ts
7548
7810
  import { Entry } from "@napi-rs/keyring";
@@ -8120,4 +8382,4 @@ if (!drained) {
8120
8382
  process.exit();
8121
8383
  }
8122
8384
  //# sourceMappingURL=cli.js.map
8123
- //# debugId=4be6a705-edee-51df-8b0e-e26c3410dcc4
8385
+ //# debugId=4e03d75d-eb39-5fde-97b7-e42c573ae760
@@ -2,6 +2,7 @@
2
2
  "capabilities": [
3
3
  "app.modules",
4
4
  "module.local-env",
5
+ "module.local-env-rules",
5
6
  "module.local-roles",
6
7
  "module.local-roles-announce",
7
8
  "module.observability",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quatronic/qore",
3
- "version": "0.2.0-rc.8",
3
+ "version": "0.2.0-test.1384f05",
4
4
  "description": "Qore developer CLI",
5
5
  "type": "module",
6
6
  "bin": {