@datarails-ai/dr-appspace-cli 0.12.79 → 0.12.81

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 (3) hide show
  1. package/README.md +24 -0
  2. package/dist/cli.js +331 -29
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -28,6 +28,30 @@ dr-appspace app-space whoami -s DEV
28
28
  or other users can access (anything but `0600` or `0400`) or that another
29
29
  user owns, and says to `chmod 600` it (DR-57810), so a file it reads
30
30
  directly must be owner-only.
31
+ - **`login-as <email>`** — act as a customer org's user (typically
32
+ `support@<org>`) without a browser, the operator recorded on the token
33
+ (`impersonator_id`, audited by the monolith). Log in as yourself first, then
34
+ pass `--account` to the commands that should run as that user:
35
+
36
+ ```
37
+ dr-appspace login -s DEMO
38
+ dr-appspace login-as support@customer.com -s DEMO
39
+ dr-appspace app-space push ./my-app -s DEMO --account support@customer.com
40
+ dr-appspace whoami -s DEMO --account support@customer.com # "Impersonated by: you@datarails.com"
41
+ ```
42
+
43
+ With two identities stored for the server, every command on it needs
44
+ `--account` — `--account you@datarails.com` for your own login too.
45
+ `dr-appspace logout -s DEMO --account support@customer.com` removes the
46
+ impersonated one.
47
+
48
+ It needs the same permission as Login As in the main app
49
+ (`support-manager:write`). `--user-id <n>` skips the email lookup; `--as
50
+ <operator-email>` picks the operator when you have several logins on the
51
+ server. Do not use `dr-appspace login` from a Login As browser tab instead:
52
+ that credential records no operator. `dr app-space …` reads this same
53
+ keychain, so `--account` works there too; `dr login-as` (dr-cli's own store)
54
+ does not.
31
55
  - **`app-space` commands** (ported from `dr-dev-cli app-space`, re-based onto
32
56
  this auth): `whoami`, `list`, `get`, `logs`, `try`, `push`, `publish`,
33
57
  `unpublish` — plus `scaffold`, `preview`, `test`, `contract`, `compile`,
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ import { fileURLToPath as fileURLToPath6 } from "url";
13
13
  // package.json
14
14
  var package_default = {
15
15
  name: "@datarails-ai/dr-appspace-cli",
16
- version: "0.12.79",
16
+ version: "0.12.81",
17
17
  description: "Datarails App Space CLI \u2014 build, try, push and publish App Space apps",
18
18
  type: "module",
19
19
  engines: {
@@ -57,7 +57,7 @@ var package_default = {
57
57
  };
58
58
 
59
59
  // src/buildInfo.ts
60
- var BUILD_TIME = "2026-11-10T15:24:10.013Z";
60
+ var BUILD_TIME = "2026-11-11T15:51:20.638Z";
61
61
  function formatBuildTime(iso) {
62
62
  if (iso === "") return "";
63
63
  const d = new Date(iso);
@@ -1208,6 +1208,19 @@ async function refreshExternalJwt(host, refreshToken, options) {
1208
1208
  }
1209
1209
  return { access: out.access, refresh: out.refresh, expiresAt };
1210
1210
  }
1211
+ async function revokeRefreshToken(host, refreshToken, options) {
1212
+ try {
1213
+ const res = await fetch(`${trimTrailingSlash(host)}/jwt/api/token/revoke/`, {
1214
+ method: "POST",
1215
+ headers: { "Content-Type": "application/json" },
1216
+ body: JSON.stringify({ refresh: refreshToken }),
1217
+ signal: options?.signal
1218
+ });
1219
+ return res.ok ? void 0 : `HTTP ${res.status}`;
1220
+ } catch (err) {
1221
+ return msgOf3(err);
1222
+ }
1223
+ }
1211
1224
  async function loginAs(host, operatorAccessToken, userId, options) {
1212
1225
  const base = trimTrailingSlash(host);
1213
1226
  const body = { user_id: userId };
@@ -1506,6 +1519,12 @@ async function recoverImpersonatedJwt(store, serverKey, email, session, host, op
1506
1519
  `${serverKey}:${email} (impersonation refresh dead and no user id stored to re-mint; re-run dr-appspace login-as)`
1507
1520
  );
1508
1521
  }
1522
+ const operatorStored = await store.getSession(serverKey, operatorEmail);
1523
+ if (operatorStored !== void 0 && (operatorStored.impersonatorEmail !== void 0 && operatorStored.impersonatorEmail !== "" || usesApiKey(operatorStored))) {
1524
+ throw new SessionExpiredError(
1525
+ `${serverKey}:${email} (operator ${operatorEmail} is no longer a direct login \u2014 re-run dr-appspace login --server ${serverKey} as ${operatorEmail}, then dr-appspace login-as)`
1526
+ );
1527
+ }
1509
1528
  let operator;
1510
1529
  try {
1511
1530
  operator = await ensureValidJwt(store, serverKey, operatorEmail, {
@@ -1534,6 +1553,15 @@ async function recoverImpersonatedJwt(store, serverKey, email, session, host, op
1534
1553
  jwtExpiresAt: result.expiresAt
1535
1554
  };
1536
1555
  await store.saveSession(serverKey, next);
1556
+ if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "") {
1557
+ const failure = await revokeRefreshToken(host, session.jwtRefresh, { signal: opts.signal });
1558
+ if (failure !== void 0) {
1559
+ process.stderr.write(
1560
+ `Warning: could not revoke the previous login-as token for ${serverKey}:${email} (${failure}); it stays valid until it expires.
1561
+ `
1562
+ );
1563
+ }
1564
+ }
1537
1565
  return next;
1538
1566
  }
1539
1567
 
@@ -2444,6 +2472,18 @@ function provisionedExternallyError(path3, action) {
2444
2472
  `cannot ${action}: the credentials in ${path3} were provisioned externally and carry no interactive session. Whatever provisioned them is responsible for renewing them; remove that file to log in interactively instead.`
2445
2473
  );
2446
2474
  }
2475
+ async function refuseImpersonationWithCredentialFile() {
2476
+ const action = "log in as another user";
2477
+ const path3 = credentialsFilePath();
2478
+ const creds = await readCredentialsFile(path3);
2479
+ if (creds === void 0) return;
2480
+ if (creds.sessionId === void 0 || creds.sessionId === "") {
2481
+ throw provisionedExternallyError(path3, action);
2482
+ }
2483
+ throw new Error(
2484
+ `cannot ${action}: ${path3} is in use as a single-identity credential store, which cannot hold a second identity. Remove that file to store sessions in the OS keychain instead.`
2485
+ );
2486
+ }
2447
2487
  function fileStoreServerKey(creds, serverFlag) {
2448
2488
  if (serverFlag === void 0 || serverFlag.trim() === "") return creds.server;
2449
2489
  const requested = resolveServer(serverFlag);
@@ -2585,6 +2625,246 @@ async function runLogin(cfg) {
2585
2625
  }
2586
2626
  }
2587
2627
 
2628
+ // src/commands/loginAs.ts
2629
+ import { z as z2 } from "zod";
2630
+ var SEARCH_PAGE_SIZE = 50;
2631
+ var canLoginAsPage = z2.object({
2632
+ next: z2.string().nullable(),
2633
+ results: z2.array(
2634
+ z2.object({
2635
+ id: z2.number().int().positive(),
2636
+ email: z2.string(),
2637
+ profile: z2.object({ organization_name: z2.string().optional() }).nullish()
2638
+ })
2639
+ )
2640
+ });
2641
+ async function resolveOperator(store, serverKey, operatorFlag) {
2642
+ const metas = await store.listSessions(serverKey);
2643
+ if (metas.length === 0) {
2644
+ throw new NotLoggedInError(
2645
+ `not logged in to ${serverKey}; run dr-appspace login --server ${serverKey}`
2646
+ );
2647
+ }
2648
+ const operators = [];
2649
+ const autoSelectable = [];
2650
+ for (const m of metas) {
2651
+ const s = await store.getSession(serverKey, m.email);
2652
+ if (s !== void 0 && (s.impersonatorEmail === void 0 || s.impersonatorEmail === "")) {
2653
+ operators.push(m.email);
2654
+ if (!usesApiKey(s)) autoSelectable.push(m.email);
2655
+ }
2656
+ }
2657
+ if (operatorFlag !== void 0 && operatorFlag !== "") {
2658
+ if (operators.includes(operatorFlag)) return operatorFlag;
2659
+ const list3 = operators.length > 0 ? operators.join(", ") : "(none \u2014 run dr-appspace login)";
2660
+ throw new Error(`${operatorFlag} is not an operator login on ${serverKey}. Operators: ${list3}`);
2661
+ }
2662
+ const candidates = autoSelectable.length > 0 ? autoSelectable : operators;
2663
+ if (candidates.length === 1) return candidates[0];
2664
+ if (candidates.length === 0) {
2665
+ throw new NotLoggedInError(
2666
+ `no operator (browser) login on ${serverKey}; run dr-appspace login --server ${serverKey}`
2667
+ );
2668
+ }
2669
+ const lines = candidates.map((e) => ` - ${e}`).join("\n");
2670
+ throw new Error(
2671
+ `multiple operator logins on ${serverKey}. Specify --as <operator-email>:
2672
+ ${lines}`
2673
+ );
2674
+ }
2675
+ async function resolveTargetUserId(client, targetEmail, signal) {
2676
+ const wanted = targetEmail.toLowerCase();
2677
+ const seen = [];
2678
+ for (let page = 1; ; page += 1) {
2679
+ const qs = new URLSearchParams({
2680
+ search: targetEmail,
2681
+ page: String(page),
2682
+ page_size: String(SEARCH_PAGE_SIZE)
2683
+ });
2684
+ const raw = await client.getJSON(`/api/it/users/can_login_as?${qs}`, { signal });
2685
+ if (raw === null) break;
2686
+ const parsed2 = canLoginAsPage.safeParse(raw);
2687
+ if (!parsed2.success) {
2688
+ throw new Error(`unexpected /api/it/users/can_login_as response: ${parsed2.error.message}`);
2689
+ }
2690
+ const resp = parsed2.data;
2691
+ for (const u of resp.results) {
2692
+ if (u.email.toLowerCase() === wanted) {
2693
+ return { id: u.id, email: u.email, orgName: u.profile?.organization_name ?? "" };
2694
+ }
2695
+ seen.push(u.email);
2696
+ }
2697
+ if (resp.next === null) break;
2698
+ }
2699
+ const near = seen.length > 0 ? ` Did you mean one of: ${seen.slice(0, 10).join(", ")}?` : "";
2700
+ throw new Error(
2701
+ `no user you can log in as matches "${targetEmail}".${near} Use --user-id <n> to impersonate by id.`
2702
+ );
2703
+ }
2704
+ function isImpersonated(s) {
2705
+ return s.impersonatorEmail !== void 0 && s.impersonatorEmail !== "";
2706
+ }
2707
+ async function storedCaseVariants(store, serverKey, email) {
2708
+ const wanted = email.toLowerCase();
2709
+ const out = [];
2710
+ for (const m of await store.listSessions(serverKey)) {
2711
+ if (m.email.toLowerCase() !== wanted) continue;
2712
+ const session = await store.getSession(serverKey, m.email);
2713
+ if (session !== void 0) out.push({ email: m.email, session });
2714
+ }
2715
+ return out;
2716
+ }
2717
+ function refuseOverwritingDirectLogin(serverKey, stored) {
2718
+ const direct = stored.find((s) => !isImpersonated(s.session));
2719
+ if (direct === void 0) return;
2720
+ throw new Error(
2721
+ `${direct.email} is one of your own logins on ${serverKey}; login-as will not replace it. Run dr-appspace logout --server ${serverKey} --account ${direct.email} first.`
2722
+ );
2723
+ }
2724
+ function friendlyLoginAsError(err, targetEmail) {
2725
+ if (err.code === "insufficient_scope" && err.httpStatus === 403) {
2726
+ return new Error(
2727
+ "Your login does not carry the support-manager:write scope that login-as needs."
2728
+ );
2729
+ }
2730
+ switch (err.code) {
2731
+ case "not_permitted":
2732
+ return new Error(`You are not permitted to impersonate ${targetEmail}.`);
2733
+ case "target_inactive":
2734
+ return new Error(`${targetEmail} is inactive and cannot be impersonated.`);
2735
+ case "impersonation_unavailable":
2736
+ return new Error("Impersonation service is temporarily unavailable; try again shortly.");
2737
+ default:
2738
+ return err;
2739
+ }
2740
+ }
2741
+ async function runLoginAs(cfg) {
2742
+ await refuseImpersonationWithCredentialFile();
2743
+ const host = cfg.host ?? resolve2(cfg.serverKey).host;
2744
+ const operatorEmail = await resolveOperator(cfg.store, cfg.serverKey, cfg.operatorFlag);
2745
+ const operatorSession = await cfg.store.getSession(cfg.serverKey, operatorEmail);
2746
+ if (operatorSession !== void 0 && usesApiKey(operatorSession)) {
2747
+ throw new Error(
2748
+ `cannot log in as another user: ${cfg.serverKey}:${operatorEmail} authenticates with an API key, and an API-key token cannot mint further credentials. Run dr-appspace login --server ${cfg.serverKey} as an operator first.`
2749
+ );
2750
+ }
2751
+ const operator = await ensureValidJwt(cfg.store, cfg.serverKey, operatorEmail, {
2752
+ buffer: JWT_REFRESH_BUFFER_MS,
2753
+ host,
2754
+ signal: cfg.signal
2755
+ });
2756
+ const operatorAccess = operator.jwtAccess ?? "";
2757
+ if (operatorAccess === "") {
2758
+ throw new NotLoggedInError(
2759
+ `operator ${operatorEmail} has no JWT on ${cfg.serverKey}; run dr-appspace login --server ${cfg.serverKey}`
2760
+ );
2761
+ }
2762
+ let userId;
2763
+ let targetEmail = cfg.targetEmail;
2764
+ let orgName = "";
2765
+ if (cfg.userIdOverride !== void 0) {
2766
+ userId = cfg.userIdOverride;
2767
+ } else {
2768
+ const client = await AuthorizedClient.create(cfg.store, cfg.serverKey, operatorEmail, {
2769
+ host
2770
+ });
2771
+ const target = await resolveTargetUserId(client, cfg.targetEmail, cfg.signal);
2772
+ userId = target.id;
2773
+ targetEmail = target.email;
2774
+ orgName = target.orgName;
2775
+ }
2776
+ const existing = await storedCaseVariants(cfg.store, cfg.serverKey, targetEmail);
2777
+ refuseOverwritingDirectLogin(cfg.serverKey, existing);
2778
+ const prevRefresh = existing.find((s) => isImpersonated(s.session))?.session.jwtRefresh;
2779
+ let result;
2780
+ try {
2781
+ result = await loginAs(host, operatorAccess, userId, {
2782
+ prevRefresh,
2783
+ signal: cfg.signal
2784
+ });
2785
+ } catch (err) {
2786
+ if (err instanceof LoginAsError) throw friendlyLoginAsError(err, cfg.targetEmail);
2787
+ throw err;
2788
+ }
2789
+ let storageEmail = cfg.targetEmail;
2790
+ try {
2791
+ const claim = decodeJwtClaims(result.access)["email"];
2792
+ if (typeof claim === "string" && claim !== "") storageEmail = claim;
2793
+ } catch {
2794
+ }
2795
+ const replaced = storageEmail.toLowerCase() === targetEmail.toLowerCase() ? existing : await storedCaseVariants(cfg.store, cfg.serverKey, storageEmail);
2796
+ try {
2797
+ refuseOverwritingDirectLogin(cfg.serverKey, replaced);
2798
+ } catch (err) {
2799
+ await revokeRefreshToken(host, result.refresh, { signal: cfg.signal });
2800
+ throw err;
2801
+ }
2802
+ const session = {
2803
+ email: storageEmail,
2804
+ sessionId: "",
2805
+ csrfToken: "",
2806
+ jwtAccess: result.access,
2807
+ jwtRefresh: result.refresh,
2808
+ jwtExpiresAt: result.expiresAt,
2809
+ savedAt: /* @__PURE__ */ new Date(),
2810
+ impersonatorEmail: operatorEmail,
2811
+ impersonatedUserId: userId,
2812
+ ...orgName !== "" && { impersonatedOrgName: orgName }
2813
+ };
2814
+ await cfg.store.saveSession(cfg.serverKey, session);
2815
+ for (const old of replaced) {
2816
+ if (old.email !== storageEmail) await cfg.store.removeSession(cfg.serverKey, old.email);
2817
+ const oldRefresh = old.session.jwtRefresh;
2818
+ if (oldRefresh === void 0 || oldRefresh === "" || oldRefresh === result.refresh) continue;
2819
+ const failure = await revokeRefreshToken(host, oldRefresh, { signal: cfg.signal });
2820
+ if (failure !== void 0) {
2821
+ cfg.out.write(
2822
+ `Warning: could not revoke the previous login-as token on ${cfg.serverKey} (${failure}); it stays valid until it expires.
2823
+ `
2824
+ );
2825
+ }
2826
+ }
2827
+ const remainingMs = result.expiresAt.getTime() - Date.now();
2828
+ cfg.out.write(
2829
+ `Logged into ${cfg.serverKey} as ${storageEmail} (impersonated by ${operatorEmail}). JWT expires in ${formatGoDuration(roundToMinuteMs(remainingMs))}.
2830
+ Use --account ${storageEmail} on later commands.
2831
+ `
2832
+ );
2833
+ }
2834
+ function registerLoginAsCommand(root) {
2835
+ const cmd = root.command("login-as").description(
2836
+ "Act as another user (e.g. support@<org>) with a JWT recording you as the operator. Requires your own dr-appspace login on the same server first."
2837
+ ).argument("<email>", "email of the user to act as").option("--as <operator-email>", "operator login to authorize with (auto-picked if sole)").option("--user-id <n>", "act as this user id directly (skips the directory lookup)").action(async (email, opts) => {
2838
+ await refuseImpersonationWithCredentialFile();
2839
+ const serverKey = resolveServer(opts.server);
2840
+ let userIdOverride;
2841
+ if (opts.userId !== void 0) {
2842
+ const n = Number(opts.userId);
2843
+ if (!Number.isInteger(n) || n <= 0 || String(n) !== opts.userId) {
2844
+ throw new Error(`--user-id must be a positive integer, got "${opts.userId}"`);
2845
+ }
2846
+ userIdOverride = n;
2847
+ }
2848
+ const store = await KeyringStore.defaultWithCleanup();
2849
+ const controller = new AbortController();
2850
+ const timer = setTimeout(() => controller.abort(), DEFAULT_CALL_TIMEOUT_MS);
2851
+ try {
2852
+ await runLoginAs({
2853
+ store,
2854
+ serverKey,
2855
+ targetEmail: email,
2856
+ operatorFlag: opts.as,
2857
+ userIdOverride,
2858
+ signal: controller.signal,
2859
+ out: process.stderr
2860
+ });
2861
+ } finally {
2862
+ clearTimeout(timer);
2863
+ }
2864
+ });
2865
+ addServerFlag(cmd);
2866
+ }
2867
+
2588
2868
  // src/commands/_accountFlag.ts
2589
2869
  function addAccountFlag(cmd) {
2590
2870
  return cmd.option(
@@ -2649,10 +2929,7 @@ async function runLogout(cfg) {
2649
2929
  for (const meta of sessions) {
2650
2930
  const session2 = await cfg.store.getSession(key, meta.email);
2651
2931
  if (session2 === void 0) continue;
2652
- try {
2653
- await revoker(host2, session2);
2654
- } catch {
2655
- }
2932
+ await revokeAndWarn(revoker, host2, session2, cfg.out);
2656
2933
  await cfg.store.removeSession(key, meta.email);
2657
2934
  cfg.out.write(`Logged out of ${key} as ${meta.email}.
2658
2935
  `);
@@ -2678,12 +2955,18 @@ async function runLogout(cfg) {
2678
2955
  return;
2679
2956
  }
2680
2957
  const host = resolve2(cfg.serverKey).host;
2958
+ await revokeAndWarn(revoker, host, session, cfg.out);
2959
+ await cfg.store.removeSession(cfg.serverKey, email);
2960
+ cfg.out.write(`Logged out of ${cfg.serverKey} as ${email}.
2961
+ `);
2962
+ }
2963
+ async function revokeAndWarn(revoker, host, session, out) {
2964
+ let warning = void 0;
2681
2965
  try {
2682
- await revoker(host, session);
2966
+ warning = await revoker(host, session);
2683
2967
  } catch {
2684
2968
  }
2685
- await cfg.store.removeSession(cfg.serverKey, email);
2686
- cfg.out.write(`Logged out of ${cfg.serverKey} as ${email}.
2969
+ if (typeof warning === "string" && warning !== "") out.write(`${warning}
2687
2970
  `);
2688
2971
  }
2689
2972
  async function bestEffortLogout(host, session) {
@@ -2692,6 +2975,16 @@ async function bestEffortLogout(host, session) {
2692
2975
  const controller = new AbortController();
2693
2976
  const timeout = setTimeout(() => controller.abort(), 5e3);
2694
2977
  try {
2978
+ if (session.impersonatorEmail !== void 0 && session.impersonatorEmail !== "") {
2979
+ if (session.jwtRefresh === void 0 || session.jwtRefresh === "") return;
2980
+ const failure = await revokeRefreshToken(base, session.jwtRefresh, {
2981
+ signal: controller.signal
2982
+ });
2983
+ if (failure !== void 0) {
2984
+ return `Warning: could not revoke the login-as token on ${base} (${failure}); it stays valid until it expires. Only the local copy was removed.`;
2985
+ }
2986
+ return;
2987
+ }
2695
2988
  await fetch(`${base}/oauth/revoke/`, {
2696
2989
  method: "POST",
2697
2990
  headers: {
@@ -12757,7 +13050,7 @@ var KEY_SHAPE = {
12757
13050
  var ROLE_KEYS = {
12758
13051
  not_own: {
12759
13052
  roles: ["decide", "save", "remove"],
12760
- why: "not_own refuses the caller's own row, and only a role that acts on one existing row has a row to refuse; a custom handler is written by hand and asks ctx.data.table(name).is_own(id) itself"
13053
+ why: "not_own refuses the caller's own row, and only a role that acts on one existing row has a row to refuse; a custom handler is written by hand and asks ctx.app.tables.table(name).is_own(id) itself"
12761
13054
  },
12762
13055
  // Required on `decide` (REQUIRED_KEYS), optional on `remove` and on `save`'s
12763
13056
  // update: the one state a row may be deleted from or changed in. Anywhere
@@ -17254,7 +17547,10 @@ function requiresLines(row, verb) {
17254
17547
  const noun = singular(row.table);
17255
17548
  return [
17256
17549
  " for column, (target, noun, display, conditions) in REQUIRES.items():",
17257
- " linked = ctx.data.table(target).get(row[column]) if row.get(column) else None",
17550
+ // Wrapped as `ruff format` wraps it: with the new name the line is 90 wide.
17551
+ " linked = (",
17552
+ " ctx.app.tables.table(target).get(row[column]) if row.get(column) else None",
17553
+ " )",
17258
17554
  " if linked is None:",
17259
17555
  " return {",
17260
17556
  ` "error": f${pyString(`this ${noun} names no {noun} this app can see`)},`,
@@ -17539,7 +17835,7 @@ function measuredSummary(row) {
17539
17835
  ...answers
17540
17836
  ];
17541
17837
  }
17542
- const body = ["def handle(ctx, payload):", " del payload", ' table = ctx.data.table(HANDLER["table"])', " answer = {}", ...loop, " return answer"].join("\n");
17838
+ const body = ["def handle(ctx, payload):", " del payload", ' table = ctx.app.tables.table(HANDLER["table"])', " answer = {}", ...loop, " return answer"].join("\n");
17543
17839
  const constants3 = [assignment("MEASURES", measures, Object.keys(measures))];
17544
17840
  if (kinds.length === 0) {
17545
17841
  return {
@@ -17710,7 +18006,7 @@ function groupedBy(row) {
17710
18006
  function singular(name) {
17711
18007
  return String(name).endsWith("s") ? String(name).slice(0, -1) : String(name);
17712
18008
  }
17713
- function queryCall(row, { receiver = 'ctx.data.table(HANDLER["table"])', indent: indent2 = 4, include = false } = {}) {
18009
+ function queryCall(row, { receiver = 'ctx.app.tables.table(HANDLER["table"])', indent: indent2 = 4, include = false } = {}) {
17714
18010
  const args = [];
17715
18011
  if (isPlainObject8(row.where)) args.push('where=HANDLER["where"]');
17716
18012
  if (named5(row.order_by)) args.push('order_by=HANDLER["order_by"]');
@@ -17753,7 +18049,7 @@ contract, not this file.`,
17753
18049
  "def handle(ctx, payload):",
17754
18050
  ...collectRow(row, enums),
17755
18051
  ...Object.keys(refs).length > 0 ? refLines() : [],
17756
- ' return {"row": ctx.data.table(HANDLER["table"]).save(row)}'
18052
+ ' return {"row": ctx.app.tables.table(HANDLER["table"]).save(row)}'
17757
18053
  ].join("\n")
17758
18054
  };
17759
18055
  }
@@ -17788,7 +18084,7 @@ function parentLines(row, parent, { missing, invisible }) {
17788
18084
  ' parent_id = str(uuid.UUID(str(payload.get(HANDLER["by"]))))',
17789
18085
  " except ValueError:",
17790
18086
  ` return ${missing}`,
17791
- " if ctx.data.table(PARENT).get(parent_id) is None:",
18087
+ " if ctx.app.tables.table(PARENT).get(parent_id) is None:",
17792
18088
  ` return ${invisible}`
17793
18089
  ];
17794
18090
  }
@@ -17817,7 +18113,7 @@ function refLines() {
17817
18113
  " row[field] = str(uuid.UUID(str(row[field])))",
17818
18114
  " except ValueError:",
17819
18115
  ' return {"error": f"{field} is not a {noun} this app can see"}',
17820
- " if ctx.data.table(target).get(row[field]) is None:",
18116
+ " if ctx.app.tables.table(target).get(row[field]) is None:",
17821
18117
  ' return {"error": f"{field} is not a {noun} this app can see"}'
17822
18118
  ];
17823
18119
  }
@@ -17846,7 +18142,7 @@ contract, not this file.`,
17846
18142
  " payload = payload or {}",
17847
18143
  ...parentLines(row, parent, { missing: '{"rows": []}', invisible: '{"rows": []}' }),
17848
18144
  where2,
17849
- ` rows = ctx.data.table(HANDLER["table"]).query(
18145
+ ` rows = ctx.app.tables.table(HANDLER["table"]).query(
17850
18146
  ${args.map((arg) => ` ${arg},`).join("\n")}
17851
18147
  )`,
17852
18148
  ' return {"rows": rows}'
@@ -17884,7 +18180,7 @@ contract, not this file.`,
17884
18180
  ' row_id = payload.get("id")',
17885
18181
  " if not row_id:",
17886
18182
  ' return {"error": "id is required"}',
17887
- ' table = ctx.data.table(HANDLER["table"])',
18183
+ ' table = ctx.app.tables.table(HANDLER["table"])',
17888
18184
  ...guardLines(row, model, "row", 4),
17889
18185
  ...notOwnLines(row, "row_id", "remove", 4),
17890
18186
  " table.delete(row_id)",
@@ -17914,7 +18210,7 @@ function decideMap(name, row, table, model) {
17914
18210
  ' if not isinstance(decision, str) or decision not in HANDLER["decision"]:',
17915
18211
  ' return {"error": f"{decision} is not a decision this app makes"}',
17916
18212
  ' spec = HANDLER["decision"][decision]',
17917
- ' table = ctx.data.table(HANDLER["table"])',
18213
+ ' table = ctx.app.tables.table(HANDLER["table"])',
17918
18214
  " try:",
17919
18215
  ' row_id = str(uuid.UUID(str(payload.get("id"))))',
17920
18216
  " except ValueError:",
@@ -18019,7 +18315,10 @@ contract, not this file.`,
18019
18315
  ' row_id = str(uuid.UUID(str(payload.get("id"))))',
18020
18316
  " except ValueError:",
18021
18317
  ' return {"rows": []}',
18022
- row.limit !== void 0 && row.limit !== null ? ' rows = ctx.data.table(HANDLER["table"]).history(row_id, limit=HANDLER["limit"])' : ' rows = ctx.data.table(HANDLER["table"]).history(row_id)',
18318
+ row.limit !== void 0 && row.limit !== null ? (
18319
+ // Wrapped as `ruff format` wraps it: with the new name the line is 89 wide.
18320
+ ' rows = ctx.app.tables.table(HANDLER["table"]).history(\n row_id, limit=HANDLER["limit"]\n )'
18321
+ ) : ' rows = ctx.app.tables.table(HANDLER["table"]).history(row_id)',
18023
18322
  ' return {"rows": rows}'
18024
18323
  ].join("\n")
18025
18324
  }),
@@ -18051,7 +18350,7 @@ contract, not this file.`,
18051
18350
  "def handle(ctx, payload):",
18052
18351
  ...collectRow(row, enums),
18053
18352
  ...Object.keys(refs).length > 0 ? refLines() : [],
18054
- ' table = ctx.data.table(HANDLER["table"])',
18353
+ ' table = ctx.app.tables.table(HANDLER["table"])',
18055
18354
  ' row_id = payload.get("id")',
18056
18355
  " if row_id:",
18057
18356
  ...guarded ? guardLines(row, model, "current", 8) : [],
@@ -18078,7 +18377,7 @@ contract, not this file.`,
18078
18377
  ' return {"error": "id is required"}',
18079
18378
  // `is_own` on a row that is not there is False, and `delete` then
18080
18379
  // raises NotFound exactly as it does without the guard.
18081
- ...row.not_own === true ? [' table = ctx.data.table(HANDLER["table"])', ...notOwnLines(row, "row_id", "remove", 4), " table.delete(row_id)"] : [' ctx.data.table(HANDLER["table"]).delete(row_id)'],
18380
+ ...row.not_own === true ? [' table = ctx.app.tables.table(HANDLER["table"])', ...notOwnLines(row, "row_id", "remove", 4), " table.delete(row_id)"] : [' ctx.app.tables.table(HANDLER["table"]).delete(row_id)'],
18082
18381
  ' return {"removed": row_id}'
18083
18382
  ].join("\n")
18084
18383
  },
@@ -18115,7 +18414,7 @@ contract, not this file.`,
18115
18414
  lines.push(...requiresLines(row, "saved"));
18116
18415
  }
18117
18416
  if (isPlainObject8(row.fixed) && Object.keys(row.fixed).length > 0) lines.push(' row.update(HANDLER["fixed"])');
18118
- lines.push(' return {"row": ctx.data.table(HANDLER["table"]).insert(row)}');
18417
+ lines.push(' return {"row": ctx.app.tables.table(HANDLER["table"]).insert(row)}');
18119
18418
  const linkDoc = parent === null ? "" : `
18120
18419
 
18121
18420
  \`by\` stamps the new ${singular(row.table)} with the ${singular(parent)} the reader opened, and
@@ -18145,7 +18444,7 @@ contract, not this file.`,
18145
18444
  ' decision = payload.get("decision") or HANDLER["decision"][0]',
18146
18445
  ' if decision not in HANDLER["decision"]:',
18147
18446
  ' return {"error": f"{decision} is not a decision this app makes"}',
18148
- ' table = ctx.data.table(HANDLER["table"])',
18447
+ ' table = ctx.app.tables.table(HANDLER["table"])',
18149
18448
  // Every table's key is a uuid (data_model: "pk must be uuid"), so an id
18150
18449
  // that is not one names no row. It is the same miss as a row that is
18151
18450
  // not there, and it has to reach the guard as one: `table.get` refuses
@@ -18201,7 +18500,7 @@ contract, not this file.`,
18201
18500
  body: [
18202
18501
  "def handle(ctx, payload):",
18203
18502
  " del payload",
18204
- ' rows = ctx.data.table(HANDLER["table"]).aggregate(',
18503
+ ' rows = ctx.app.tables.table(HANDLER["table"]).aggregate(',
18205
18504
  " group_by=GROUP_BY,",
18206
18505
  ' metrics={"n": "count"},',
18207
18506
  " )",
@@ -31935,6 +32234,9 @@ function checkPage3(app) {
31935
32234
 
31936
32235
  // ../flows/appspace-builder/kit/checks/rules/singleton.mjs
31937
32236
  var SETTINGS_NAME = /(^|_)(settings?|config|configuration|preferences|prefs)(_|$)/;
32237
+ var TABLE_SURFACE = String.raw`ctx\s*\.\s*(?:data|app\s*\.\s*tables)`;
32238
+ var BOUND_TABLE = new RegExp(String.raw`\b([A-Za-z_]\w*)\s*=\s*${TABLE_SURFACE}\s*\.\s*table\(\s*(?:(["'])([^"'\n]+)\2|HANDLER\[["']table["']\])\s*\)`, "g");
32239
+ var QUERY_CALL = new RegExp(String.raw`(?:${TABLE_SURFACE}\s*\.\s*table\(\s*(?:(["'])([^"'\n]+)\1|HANDLER\[["']table["']\])\s*\)|\b([A-Za-z_]\w*))\s*\.query\(`, "g");
31938
32240
  function checkSingletons(app) {
31939
32241
  const violations = [];
31940
32242
  const tables = app.dataModel && typeof app.dataModel.tables === "object" && app.dataModel.tables !== null ? app.dataModel.tables : {};
@@ -31946,7 +32248,7 @@ function checkSingletons(app) {
31946
32248
  violations.push({
31947
32249
  rule: "A2.5",
31948
32250
  where: `${reader.where}:${reader.line}`,
31949
- message: `table "${name}" looks like a one-row settings table (handler "${reader.handler}" reads it with limit 1) but does not declare "singleton": true, so a save with no id inserts another row and limit 1 reads whichever row comes first. Declare "singleton": true on "${name}", read it with ctx.data.table("${name}").get() and write it with .save(values) (a "save" role does this when compiled)`
32251
+ message: `table "${name}" looks like a one-row settings table (handler "${reader.handler}" reads it with limit 1) but does not declare "singleton": true, so a save with no id inserts another row and limit 1 reads whichever row comes first. Declare "singleton": true on "${name}", read it with ctx.app.tables.table("${name}").get() and write it with .save(values) (a "save" role does this when compiled)`
31950
32252
  });
31951
32253
  }
31952
32254
  }
@@ -31970,11 +32272,10 @@ function oneRowReader(handlers, table) {
31970
32272
  const source = handler.source ?? "";
31971
32273
  const literal = handlerLiteral(source);
31972
32274
  const aliases = /* @__PURE__ */ new Map();
31973
- for (const bound of source.matchAll(/\b([A-Za-z_]\w*)\s*=\s*ctx\.data\.table\(\s*(?:(["'])([^"'\n]+)\2|HANDLER\[["']table["']\])\s*\)/g)) {
32275
+ for (const bound of source.matchAll(BOUND_TABLE)) {
31974
32276
  aliases.set(bound[1], bound[3] ?? literal.table);
31975
32277
  }
31976
- const calls = /(?:ctx\.data\.table\(\s*(?:(["'])([^"'\n]+)\1|HANDLER\[["']table["']\])\s*\)|\b([A-Za-z_]\w*))\s*\.query\(/g;
31977
- for (const call of source.matchAll(calls)) {
32278
+ for (const call of source.matchAll(QUERY_CALL)) {
31978
32279
  const receiver = call[3] !== void 0 ? aliases.get(call[3]) : call[2] ?? literal.table;
31979
32280
  if (receiver !== table) continue;
31980
32281
  const args = argumentsFrom(source, call.index + call[0].length);
@@ -43532,6 +43833,7 @@ function buildRootCommand() {
43532
43833
  root.exitOverride();
43533
43834
  root.enablePositionalOptions();
43534
43835
  registerLoginCommand(root);
43836
+ registerLoginAsCommand(root);
43535
43837
  registerLogoutCommand(root);
43536
43838
  registerWhoamiCommand(root);
43537
43839
  registerAppSpaceCommand(root);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datarails-ai/dr-appspace-cli",
3
- "version": "0.12.79",
3
+ "version": "0.12.81",
4
4
  "description": "Datarails App Space CLI — build, try, push and publish App Space apps",
5
5
  "type": "module",
6
6
  "engines": {