@quatronic/qore 0.2.0-test.25bcaa2 → 0.2.0-test.8ed339c

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 (2) hide show
  1. package/dist/cli.js +257 -85
  2. package/package.json +1 -1
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]="28cd5ca7-9197-5e2a-b7a3-beb912fc49ed")}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) {
@@ -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"];
@@ -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));
@@ -2907,7 +2956,7 @@ function sourceText(mc) {
2907
2956
  }
2908
2957
  function contextLine(mc, app) {
2909
2958
  const parts = [mc.module.tenant.name, ...app ? [app.name] : [], mc.module.slug];
2910
- return `\u2192 ${parts.join(" / ")} (${sourceText(mc)})`;
2959
+ return `\u2192 ${parts.join(" / ")} (${sourceText(mc)})${portalNote(mc.portal)}`;
2911
2960
  }
2912
2961
  function contextJson(mc, app) {
2913
2962
  const { id, slug, name, type, access: access2 } = mc.module;
@@ -2927,14 +2976,26 @@ import { join as join14 } from "path";
2927
2976
 
2928
2977
  // src/core/projects/match.ts
2929
2978
  function readings(ref) {
2930
- 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) {
2931
2984
  if (s.some((x) => x === "")) return [];
2932
2985
  if (s.length === 1) return [{ app: s[0] }];
2933
2986
  if (s.length === 2) return [{ app: s[0], module: s[1] }, { tenant: s[0], app: s[1] }];
2934
2987
  if (s.length === 3) return [{ tenant: s[0], app: s[1], module: s[2] }];
2935
2988
  return [];
2936
2989
  }
2990
+ function folderOf(origin) {
2991
+ try {
2992
+ return portalFolder(resolvePortal(origin, void 0));
2993
+ } catch {
2994
+ return null;
2995
+ }
2996
+ }
2937
2997
  function hit(p, w) {
2998
+ if (w.portal !== void 0 && folderOf(p.portal) !== w.portal) return null;
2938
2999
  if (p.appSlug !== w.app || w.tenant !== void 0 && p.tenantSlug !== w.tenant) return null;
2939
3000
  if (p.kind === "module") return w.module === p.moduleSlug ? { project: p } : null;
2940
3001
  return w.module ? { project: p, module: w.module } : { project: p };
@@ -2959,8 +3020,19 @@ async function loggedInAs(ctx) {
2959
3020
  return p.email ?? p.sub ?? portal.apiOrigin;
2960
3021
  }
2961
3022
  var isDir = async (p) => (await stat3(p).catch(() => null))?.isDirectory() ?? false;
2962
- var label2 = (p) => `${p.tenantSlug} / ${p.appSlug}${p.kind === "module" ? ` / ${p.moduleSlug}` : ""}${p.source === "registry" ? ` (${p.path})` : ""}`;
2963
- 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
+ };
2964
3036
  var withCwd = (ctx, cwd) => ({ ...ctx, deps: { ...ctx.deps, cwd } });
2965
3037
  async function standingIn(ctx) {
2966
3038
  if (await findWorkspace(ctx.deps.cwd, ctx.deps.home)) return "workspace";
@@ -3632,6 +3704,16 @@ function providerDown(o) {
3632
3704
  action: { command: o.fix }
3633
3705
  };
3634
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
+ }
3635
3717
 
3636
3718
  // src/core/dev/project.ts
3637
3719
  import { access, readFile as readFile7 } from "fs/promises";
@@ -4079,6 +4161,63 @@ async function leftoverOwnsPort(deps2, run4, port) {
4079
4161
  return false;
4080
4162
  }
4081
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
+
4082
4221
  // src/core/dev/providers.ts
4083
4222
  var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
4084
4223
  function connPorts(env) {
@@ -4692,7 +4831,7 @@ async function prepareWorkspace(ctx, ws, f, waitTimeout, p) {
4692
4831
  const note = (human, event) => json2 ? io2.out(JSON.stringify(event)) : io2.err(human);
4693
4832
  const warn = (message, extra = {}) => note(`! ${message}`, { type: "warning", ...extra, message });
4694
4833
  const { am, online, offlineCause } = await workspaceContext(ctx, ws);
4695
- 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)}`);
4696
4835
  if (!online) warn("The portal is unreachable \u2014 starting every module from its env file as last written; values may be stale.");
4697
4836
  const color = !json2 && g.color !== false && !deps2.env.NO_COLOR;
4698
4837
  const problems = [];
@@ -4904,6 +5043,10 @@ async function prepareWorkspace(ctx, ws, f, waitTimeout, p) {
4904
5043
  );
4905
5044
  }
4906
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
+ }
4907
5050
  const services = servicesMissing(slug, dev.env, u.recipe, { servicesFlag: f.services, configured: u.cfg.dev?.services !== void 0 });
4908
5051
  if (services) renderFinding(ctx, services);
4909
5052
  try {
@@ -5159,14 +5302,15 @@ function parseWaitTimeout(raw) {
5159
5302
  var str3 = (v) => typeof v === "string" && v.length > 0;
5160
5303
  var SHELL_SAFE = /^[A-Za-z0-9_./,:@%+=-]*$/;
5161
5304
  var shellQuote = (s) => SHELL_SAFE.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
5162
- function cdAndDev(home, dir2) {
5163
- 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} && `;
5164
5307
  const h = home.length > 1 ? home.replace(/\/+$/, "") : home;
5165
5308
  let target = shellQuote(dir2);
5166
5309
  if (h && dir2 === h) target = "~";
5167
5310
  else if (h && dir2.startsWith(h + "/")) target = `~/${shellQuote(dir2.slice(h.length + 1))}`;
5168
- return `cd ${target} && qore dev`;
5311
+ return `cd ${target} && `;
5169
5312
  }
5313
+ var cdAndDev = (home, dir2) => `${cdPrefix(home, dir2)}qore dev`;
5170
5314
  async function providerFindings(ctx, root, mc, app, env) {
5171
5315
  const { deps: deps2 } = ctx;
5172
5316
  try {
@@ -5334,6 +5478,8 @@ async function prepareModule(ctx, f, waitTimeout, p) {
5334
5478
  if (c.online && !dev.offline) {
5335
5479
  const provider = await providerFindings(ctx, root, c.online.mc, c.online.app, dev.env);
5336
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);
5337
5483
  }
5338
5484
  const services = servicesMissing(slug, dev.env, recipe, { servicesFlag: f.services, configured: cfg.dev?.services !== void 0 });
5339
5485
  if (services) renderFinding(ctx, services);
@@ -5428,7 +5574,7 @@ var noop = () => {
5428
5574
  var ok = (label3, details) => ({ status: "ok", label: label3, ...details ? { details } : {} });
5429
5575
  var withError = (status2, label3, e) => ({ status: status2, label: label3, error: toJsonError(e) });
5430
5576
  var isCancel = (e, signal) => e instanceof CancelledError || signal.aborted;
5431
- var portalLabel = (p) => p.builtin ?? p.apiOrigin;
5577
+ var portalLabel2 = (p) => p.builtin ?? p.apiOrigin;
5432
5578
  var ToolTimeout = class extends Error {
5433
5579
  constructor(tool, ms2) {
5434
5580
  super(`${tool} did not answer within ${Math.round(ms2 / 1e3)} s`);
@@ -5535,10 +5681,10 @@ async function checkSession(deps2, portal, onRequest, sessions, selected, signal
5535
5681
  const rt = await session.tokens.getRefresh();
5536
5682
  const days = rt ? validDays(rt, deps2.now()) : null;
5537
5683
  const valid = days === null ? "" : ` \xB7 session valid ${days} ${days === 1 ? "day" : "days"}`;
5538
- 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 } : {} });
5539
5685
  } catch (e) {
5540
5686
  if (isCancel(e, signal) || selected) throw e;
5541
- return withError("warn", `${portalLabel(portal)}: ${errorLabel(e)}`, e);
5687
+ return withError("warn", `${portalLabel2(portal)}: ${errorLabel(e)}`, e);
5542
5688
  }
5543
5689
  }
5544
5690
  function checkClock(meta) {
@@ -5639,10 +5785,10 @@ async function checkRepoNode(deps2, m, recipe, pkg, signal, ms2) {
5639
5785
  const found = await timed("node", signal, ms2, (s) => checkNode(deps2, recipe, pkg, m.slug, s));
5640
5786
  return ok(`Node ${found ?? "?"} (engines ${pkg.engines.node})`);
5641
5787
  }
5642
- async function loggedInPortals(deps2, profiles) {
5643
- 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;
5644
5790
  const out = [];
5645
- 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))) {
5646
5792
  const p = profiles[origin];
5647
5793
  if (await new TokenStore(deps2.keychain, profileHash(p.apiOrigin, p.issuer)).getRefresh()) out.push(resolvePortal(origin, void 0));
5648
5794
  }
@@ -5654,7 +5800,7 @@ async function resolveRepoModule(deps2, session, portal, meta, root) {
5654
5800
  if (keys.length === 0) return { status: "warn", label: "this repository has no remote Qore can match" };
5655
5801
  const { matches } = await session.api.post("/api/cli/v1/repos/resolve", { repoKeys: keys });
5656
5802
  const ids = [...new Set(matches.map((x) => x.module.id))];
5657
- 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)}` };
5658
5804
  if (ids.length > 1) {
5659
5805
  return { status: "warn", label: `this repository matches several modules (${[...new Set(matches.map((x) => x.module.slug))].join(", ")})` };
5660
5806
  }
@@ -5728,7 +5874,7 @@ async function runDoctor(deps2, o = {}) {
5728
5874
  const sessions = /* @__PURE__ */ new Map();
5729
5875
  let loggedIn = [];
5730
5876
  try {
5731
- loggedIn = await loggedInPortals(deps2, cfg.profiles);
5877
+ loggedIn = await loggedInPortals2(deps2, cfg.profiles);
5732
5878
  if (loggedIn.length === 0) await push("session", "session", () => ({ status: "warn", label: "not logged in \u2014 qore login" }));
5733
5879
  } catch (e) {
5734
5880
  if (isCancel(e, signal)) throw e;
@@ -5738,7 +5884,7 @@ async function runDoctor(deps2, o = {}) {
5738
5884
  }
5739
5885
  for (const p of loggedIn) {
5740
5886
  await push(
5741
- `session:${portalLabel(p)}`,
5887
+ `session:${portalLabel2(p)}`,
5742
5888
  "session",
5743
5889
  () => checkSession(deps2, p, o.onRequest, sessions, p.apiOrigin === portal.apiOrigin, signal)
5744
5890
  );
@@ -5748,7 +5894,7 @@ async function runDoctor(deps2, o = {}) {
5748
5894
  const notChecked = () => push(
5749
5895
  "modules",
5750
5896
  "workspace",
5751
- () => ({ 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)}` })
5752
5898
  );
5753
5899
  const perModule = async (m, prepared) => {
5754
5900
  if (!prepared?.recipe) return;
@@ -6135,10 +6281,11 @@ async function obsContext(ctx, flags, command, o) {
6135
6281
  const window = windowOf(flags);
6136
6282
  const onRequest = g.verbose ? (l) => io2.err(l) : void 0;
6137
6283
  const ws = flags.module === void 0 || flags.module === "all" ? await workspaceRoot(deps2) : null;
6138
- let api, tenant, app, mods, base, apiOrigin;
6284
+ let api, tenant, app, mods, base, apiOrigin, note;
6139
6285
  if (ws) {
6140
6286
  const portal = await flagPortal(deps2, g.portal, ws);
6141
6287
  apiOrigin = portal.apiOrigin;
6288
+ note = portalNote(portal);
6142
6289
  const session = await openSession(deps2, portal, command, onRequest);
6143
6290
  await ensureCapability(deps2, apiOrigin, "module.observability");
6144
6291
  await ensureCapability(deps2, apiOrigin, "app.modules");
@@ -6151,6 +6298,7 @@ async function obsContext(ctx, flags, command, o) {
6151
6298
  } else {
6152
6299
  const mc = await moduleContextFor(ctx, { module: flags.module === "all" ? void 0 : flags.module }, command);
6153
6300
  apiOrigin = mc.portal.apiOrigin;
6301
+ note = portalNote(mc.portal);
6154
6302
  await ensureCapability(deps2, apiOrigin, "module.observability");
6155
6303
  app = await appFor(ctx, mc, flags.app);
6156
6304
  api = mc.session.api;
@@ -6180,7 +6328,7 @@ async function obsContext(ctx, flags, command, o) {
6180
6328
  fanOut: fanOut2,
6181
6329
  env,
6182
6330
  window,
6183
- 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}`,
6184
6332
  json: { ...base, ...fanOut2 ? { modules: targets.map((t) => t.module) } : { module: targets[0].module }, env, window }
6185
6333
  };
6186
6334
  }
@@ -6633,6 +6781,7 @@ function registerTenant(program, ctx) {
6633
6781
  const cfg = await deps2.config.read();
6634
6782
  const portal = resolvePortal(g.portal, cfg.defaultProfile);
6635
6783
  const { profile, api } = await openSession(deps2, portal, "tenant list", requestLog(ctx));
6784
+ if (!g.json && portalNote(portal)) io2.err(`\u2192 ${portalNote(portal).trim()}`);
6636
6785
  const me = await api.get("/api/cli/v1/me");
6637
6786
  const activeId = profile.activeTenant?.id;
6638
6787
  if (g.json) {
@@ -6647,7 +6796,7 @@ function registerTenant(program, ctx) {
6647
6796
  tenant.command("use").description("Set the active tenant").argument("[slug]", "tenant slug").action(async (slug) => {
6648
6797
  const chosen = await useTenant(ctx, slug);
6649
6798
  if (ctx.opts().json) renderJson(ctx.io, { activeTenant: chosen });
6650
- 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))}`);
6651
6800
  });
6652
6801
  }
6653
6802
  async function useTenant(ctx, slug, known) {
@@ -6799,54 +6948,76 @@ function registerLogout(program, ctx) {
6799
6948
  });
6800
6949
  done.push(p.apiOrigin);
6801
6950
  }
6802
- 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 } : {} });
6803
6953
  else if (done.length === 0) io2.out("Not logged in");
6804
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}`);
6805
6956
  });
6806
6957
  }
6807
-
6808
- // src/core/roles/api.ts
6809
- var CAPABILITY = "module.local-roles";
6810
- var path = (mc, app) => `/api/cli/v1/modules/${encodeURIComponent(mc.module.id)}/local-roles?app_id=${encodeURIComponent(app.id)}`;
6811
- async function fetchLocalRoles(deps2, mc, app) {
6812
- await ensureCapability(deps2, mc.portal.apiOrigin, CAPABILITY);
6813
- return explained(mc, () => mc.session.api.get(path(mc, app)));
6814
- }
6815
- async function useLocalRoles(deps2, mc, app, roles, use) {
6816
- await ensureCapability(deps2, mc.portal.apiOrigin, CAPABILITY);
6817
- return explained(mc, () => mc.session.api.post(path(mc, app), { roles, use }));
6818
- }
6819
- var ANNOUNCE_CAPABILITY = "module.local-roles-announce";
6820
- async function announceLocalRoles(deps2, mc, app, roles) {
6821
- await ensureCapability(deps2, mc.portal.apiOrigin, ANNOUNCE_CAPABILITY);
6822
- 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;
6823
6968
  }
6824
- 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) {
6825
6973
  try {
6826
- return await call();
6974
+ return resolvePortal(name, void 0);
6827
6975
  } catch (e) {
6828
- if (!(e instanceof QoreError)) throw e;
6829
- if (e.serverCode === "app.access.denied") {
6830
- throw withDetails(
6831
- e,
6832
- { required: "write", have: mc.module.access },
6833
- `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.`
6834
- );
6835
- }
6836
- if (e.serverCode === "membership.permission.denied") {
6837
- throw withDetails(e, {}, "Taking roles on this app needs write on one of its dev teams.");
6838
- }
6839
- if (e.serverCode === "auth.scope.insufficient") throw withDetails(e, {}, "Run `qore login` again.");
6840
- if (e.serverCode === "app.no_platform_identity") {
6841
- throw new QoreError("QORE_CONTEXT_UNSUPPORTED", "This app manages its own users; the portal hands out no roles for it", {
6842
- hint: "Give yourself the role in the app's own user admin.",
6843
- serverCode: e.serverCode,
6844
- requestId: e.requestId
6845
- });
6846
- }
6847
- 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
+ });
6848
6980
  }
6849
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
+ }
6850
7021
 
6851
7022
  // src/core/roles/read.ts
6852
7023
  import { join as join26 } from "path";
@@ -7020,7 +7191,7 @@ async function appStatus(ctx, ws, appFlag) {
7020
7191
  hint: "Pass --module <slug> --app <slug>."
7021
7192
  });
7022
7193
  }
7023
- 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)}`);
7024
7195
  const modules = [];
7025
7196
  for (const m of am.modules.filter((x) => x.repoUrl !== null)) {
7026
7197
  const st = await session.api.get(
@@ -7076,7 +7247,7 @@ function registerStatus(program, ctx) {
7076
7247
 
7077
7248
  // src/cli/commands/sync.ts
7078
7249
  import { join as join27, relative as relative9 } from "path";
7079
- import { Option as Option2 } from "commander";
7250
+ import { Option as Option3 } from "commander";
7080
7251
  function asFailure2(slug, e) {
7081
7252
  if (e instanceof QoreError && e.code !== "QORE_GIT_UNAVAILABLE") {
7082
7253
  return { slug, status: "failed", error: { code: e.code, message: e.message, hint: e.hint } };
@@ -7084,7 +7255,7 @@ function asFailure2(slug, e) {
7084
7255
  throw e;
7085
7256
  }
7086
7257
  function registerSync(program, ctx) {
7087
- 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) => {
7088
7259
  const { deps: deps2, io: io2 } = ctx;
7089
7260
  const g = ctx.opts();
7090
7261
  const ws = await findWorkspace(deps2.cwd, deps2.home);
@@ -7096,7 +7267,7 @@ function registerSync(program, ctx) {
7096
7267
  const session = await openSession(deps2, portal, "sync", onRequest);
7097
7268
  await ensureCapability(deps2, portal.apiOrigin, "app.modules");
7098
7269
  const app = await workspaceAppModules(session, portal, ws);
7099
- 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)}`);
7100
7271
  const slugs = new Set(app.modules.map((m) => m.slug));
7101
7272
  const dirs = {};
7102
7273
  const earlyFailures = [];
@@ -7298,6 +7469,7 @@ var COMMANDS = [
7298
7469
  registerLogout,
7299
7470
  registerWhoami,
7300
7471
  registerTenant,
7472
+ registerPortal,
7301
7473
  registerStatus,
7302
7474
  registerLogs,
7303
7475
  registerTraces,
@@ -8210,4 +8382,4 @@ if (!drained) {
8210
8382
  process.exit();
8211
8383
  }
8212
8384
  //# sourceMappingURL=cli.js.map
8213
- //# debugId=28cd5ca7-9197-5e2a-b7a3-beb912fc49ed
8385
+ //# debugId=4e03d75d-eb39-5fde-97b7-e42c573ae760
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quatronic/qore",
3
- "version": "0.2.0-test.25bcaa2",
3
+ "version": "0.2.0-test.8ed339c",
4
4
  "description": "Qore developer CLI",
5
5
  "type": "module",
6
6
  "bin": {