@datarails-ai/dr-appspace-cli 0.12.74 → 0.12.75

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 +16 -2
  2. package/dist/cli.js +707 -127
  3. package/package.json +1 -1
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.74",
16
+ version: "0.12.75",
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-08T22:36:01.631Z";
60
+ var BUILD_TIME = "2026-11-09T18:04:05.952Z";
61
61
  function formatBuildTime(iso) {
62
62
  if (iso === "") return "";
63
63
  const d = new Date(iso);
@@ -1102,18 +1102,18 @@ async function loginAs(host, operatorAccessToken, userId, options) {
1102
1102
  throw new Error("jwt loginas parse: expected object");
1103
1103
  }
1104
1104
  const obj5 = raw;
1105
- const access = typeof obj5["access"] === "string" ? obj5["access"] : "";
1105
+ const access2 = typeof obj5["access"] === "string" ? obj5["access"] : "";
1106
1106
  const refresh = typeof obj5["refresh"] === "string" ? obj5["refresh"] : "";
1107
- if (access === "") {
1107
+ if (access2 === "") {
1108
1108
  throw new Error("jwt loginas: empty access token");
1109
1109
  }
1110
1110
  let expiresAt;
1111
1111
  try {
1112
- expiresAt = decodeJwtExpiration(access);
1112
+ expiresAt = decodeJwtExpiration(access2);
1113
1113
  } catch (err) {
1114
1114
  throw new Error(`jwt loginas: ${msgOf3(err)}`);
1115
1115
  }
1116
- return { access, refresh, expiresAt, user: obj5["user"] };
1116
+ return { access: access2, refresh, expiresAt, user: obj5["user"] };
1117
1117
  }
1118
1118
  async function exchangeApiKey(host, apiKey, options) {
1119
1119
  const key = apiKey.trim();
@@ -1158,17 +1158,17 @@ async function exchangeApiKey(host, apiKey, options) {
1158
1158
  if (raw === null || typeof raw !== "object") {
1159
1159
  throw new Error("api-key exchange parse: expected object");
1160
1160
  }
1161
- const access = raw["access_token"];
1162
- if (typeof access !== "string" || access === "") {
1161
+ const access2 = raw["access_token"];
1162
+ if (typeof access2 !== "string" || access2 === "") {
1163
1163
  throw new Error("api-key exchange: empty access token");
1164
1164
  }
1165
1165
  let expiresAt;
1166
1166
  try {
1167
- expiresAt = decodeJwtExpiration(access);
1167
+ expiresAt = decodeJwtExpiration(access2);
1168
1168
  } catch (err) {
1169
1169
  throw new Error(`api-key exchange: ${msgOf3(err)}`);
1170
1170
  }
1171
- return { access, expiresAt };
1171
+ return { access: access2, expiresAt };
1172
1172
  }
1173
1173
  function apiKeyFingerprint(apiKey) {
1174
1174
  return createHash("sha256").update(apiKey.trim()).digest("hex").slice(0, 32);
@@ -1577,15 +1577,15 @@ var AuthorizedClient = class _AuthorizedClient {
1577
1577
  * `whoami` precedent.
1578
1578
  */
1579
1579
  getCurrentOrgId() {
1580
- const access = this._session.jwtAccess ?? "";
1581
- if (access === "") {
1580
+ const access2 = this._session.jwtAccess ?? "";
1581
+ if (access2 === "") {
1582
1582
  throw new Error(
1583
1583
  `no JWT stored for ${this._serverKey}; run dr-appspace login --server ${this._serverKey} to refresh`
1584
1584
  );
1585
1585
  }
1586
1586
  let claims;
1587
1587
  try {
1588
- claims = decodeJwtClaims(access);
1588
+ claims = decodeJwtClaims(access2);
1589
1589
  } catch (err) {
1590
1590
  const msg = err instanceof Error ? err.message : String(err);
1591
1591
  throw new Error(`decode JWT for ${this._serverKey}: ${msg}`);
@@ -2023,9 +2023,9 @@ var AuthorizedClient = class _AuthorizedClient {
2023
2023
  * mintJwt inside ensureValidJwt pick the right path based on what's set.
2024
2024
  */
2025
2025
  async ensureFreshAuth(bufferMs, signal) {
2026
- const access = this._session.jwtAccess ?? "";
2026
+ const access2 = this._session.jwtAccess ?? "";
2027
2027
  const refresh = this._session.jwtRefresh ?? "";
2028
- if (access === "" && refresh === "" && !usesApiKey(this._session)) {
2028
+ if (access2 === "" && refresh === "" && !usesApiKey(this._session)) {
2029
2029
  return;
2030
2030
  }
2031
2031
  try {
@@ -2966,8 +2966,8 @@ async function connect(opts) {
2966
2966
  email: client.email,
2967
2967
  claims() {
2968
2968
  try {
2969
- const access = client.session.jwtAccess ?? "";
2970
- return access === "" ? null : decodeJwtClaims(access);
2969
+ const access2 = client.session.jwtAccess ?? "";
2970
+ return access2 === "" ? null : decodeJwtClaims(access2);
2971
2971
  } catch {
2972
2972
  return null;
2973
2973
  }
@@ -3123,11 +3123,11 @@ function conflictGuidance(body) {
3123
3123
  return lines;
3124
3124
  }
3125
3125
  function hostsNeedingApproval(body) {
3126
- const isObj5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3127
- const found = isObj5(body) && isObj5(body["detail"]) ? body["detail"] : body;
3128
- if (!isObj5(found) || found["error"] !== "http_hosts_need_approval") return void 0;
3126
+ const isObj6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3127
+ const found = isObj6(body) && isObj6(body["detail"]) ? body["detail"] : body;
3128
+ if (!isObj6(found) || found["error"] !== "http_hosts_need_approval") return void 0;
3129
3129
  const hosts = Array.isArray(found["hosts"]) ? found["hosts"].filter((h) => typeof h === "string") : [];
3130
- const entries = Array.isArray(found["entries"]) ? found["entries"].filter(isObj5).map((e) => ({
3130
+ const entries = Array.isArray(found["entries"]) ? found["entries"].filter(isObj6).map((e) => ({
3131
3131
  name: String(e["name"] ?? "?"),
3132
3132
  host: String(e["host"] ?? "?"),
3133
3133
  change: String(e["change"] ?? "needs approval")
@@ -5054,8 +5054,8 @@ function pyLiteral(value, { indent: indent2 = 0, width = DEFAULT_WIDTH, callable
5054
5054
  function writeSpec(data, { library = null, name = "SPEC", width = DEFAULT_WIDTH } = {}) {
5055
5055
  const problems = [];
5056
5056
  const table = tableOf(data);
5057
- const constants = /* @__PURE__ */ new Map();
5058
- const hoisted = hoist(table, [], constants, null);
5057
+ const constants2 = /* @__PURE__ */ new Map();
5058
+ const hoisted = hoist(table, [], constants2, null);
5059
5059
  const callables = /* @__PURE__ */ new Set();
5060
5060
  let text4 = null;
5061
5061
  try {
@@ -5076,7 +5076,7 @@ function writeSpec(data, { library = null, name = "SPEC", width = DEFAULT_WIDTH
5076
5076
  });
5077
5077
  }
5078
5078
  if (unknown.length > 0) return { text: null, imports: [], constants: [], problems };
5079
- const rows2 = [...constants].map(([constant, held]) => ({
5079
+ const rows2 = [...constants2].map(([constant, held]) => ({
5080
5080
  name: constant,
5081
5081
  value: held,
5082
5082
  text: `${constant} = ${pyLiteral(held, { indent: 0, width, callables, pointer: `/${constant}` })}`
@@ -5093,11 +5093,11 @@ function writeSpec(data, { library = null, name = "SPEC", width = DEFAULT_WIDTH
5093
5093
  if (problems.length > 0) return { text: null, imports: [], constants: [], problems };
5094
5094
  return { text: text4, imports, constants: rows2, problems };
5095
5095
  }
5096
- function writeModule({ docstring = null, imports = [], constants = [], tables = [], body = null } = {}) {
5096
+ function writeModule({ docstring = null, imports = [], constants: constants2 = [], tables = [], body = null } = {}) {
5097
5097
  const blocks = [];
5098
5098
  if (docstring !== null) blocks.push(asDocstring(docstring));
5099
5099
  if (imports.length > 0) blocks.push(imports.join("\n"));
5100
- if (constants.length > 0) blocks.push(constants.join("\n"));
5100
+ if (constants2.length > 0) blocks.push(constants2.join("\n"));
5101
5101
  for (const table of tables) blocks.push(table.replace(/\n+$/, ""));
5102
5102
  if (body !== null) blocks.push(body.replace(/\n+$/, ""));
5103
5103
  let text4 = "";
@@ -5237,34 +5237,34 @@ function pyString(text4) {
5237
5237
  }
5238
5238
  return out + quote;
5239
5239
  }
5240
- function hoist(value, path3, constants, key) {
5240
+ function hoist(value, path3, constants2, key) {
5241
5241
  if (Array.isArray(value)) {
5242
- const next = value.map((item, index) => hoist(item, [...path3, String(index)], constants, null));
5243
- return atLiteral(next, path3, constants, key);
5242
+ const next = value.map((item, index) => hoist(item, [...path3, String(index)], constants2, null));
5243
+ return atLiteral(next, path3, constants2, key);
5244
5244
  }
5245
5245
  if (isPlainObject(value) && !("$callable" in value) && !("$const" in value)) {
5246
5246
  const next = {};
5247
- for (const [name, held] of Object.entries(value)) next[name] = hoist(held, [...path3, name], constants, name);
5248
- return atLiteral(next, path3, constants, key);
5247
+ for (const [name, held] of Object.entries(value)) next[name] = hoist(held, [...path3, name], constants2, name);
5248
+ return atLiteral(next, path3, constants2, key);
5249
5249
  }
5250
5250
  return value;
5251
5251
  }
5252
- function atLiteral(value, path3, constants, key) {
5252
+ function atLiteral(value, path3, constants2, key) {
5253
5253
  if (path3.length === 0) return value;
5254
5254
  if (numbersIn(value) < MIN_NUMBERS) return value;
5255
5255
  if (key !== null && LITERAL_CONTEXT.test(`"${key}": `)) return value;
5256
- return nameNumbers(value, path3, constants);
5256
+ return nameNumbers(value, path3, constants2);
5257
5257
  }
5258
- function nameNumbers(value, path3, constants) {
5258
+ function nameNumbers(value, path3, constants2) {
5259
5259
  if (typeof value === "number") {
5260
- const name = constantName(path3, constants);
5261
- constants.set(name, value);
5260
+ const name = constantName(path3, constants2);
5261
+ constants2.set(name, value);
5262
5262
  return { $const: name };
5263
5263
  }
5264
- if (Array.isArray(value)) return value.map((item, index) => nameNumbers(item, [...path3, String(index)], constants));
5264
+ if (Array.isArray(value)) return value.map((item, index) => nameNumbers(item, [...path3, String(index)], constants2));
5265
5265
  if (isPlainObject(value) && !("$callable" in value) && !("$const" in value)) {
5266
5266
  const out = {};
5267
- for (const [key, held] of Object.entries(value)) out[key] = nameNumbers(held, [...path3, key], constants);
5267
+ for (const [key, held] of Object.entries(value)) out[key] = nameNumbers(held, [...path3, key], constants2);
5268
5268
  return out;
5269
5269
  }
5270
5270
  return value;
@@ -5278,11 +5278,11 @@ function numbersIn(value) {
5278
5278
  }
5279
5279
  return 0;
5280
5280
  }
5281
- function constantName(path3, constants) {
5281
+ function constantName(path3, constants2) {
5282
5282
  const base = path3.join("_").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
5283
5283
  const start = /^[A-Z_]/.test(base) ? base : `N_${base}`;
5284
- if (!constants.has(start)) return start;
5285
- for (let n = 2; ; n += 1) if (!constants.has(`${start}_${n}`)) return `${start}_${n}`;
5284
+ if (!constants2.has(start)) return start;
5285
+ for (let n = 2; ; n += 1) if (!constants2.has(`${start}_${n}`)) return `${start}_${n}`;
5286
5286
  }
5287
5287
  function asDocstring(text4) {
5288
5288
  const body = String(text4).replace(/\\/g, "\\\\").replace(/"""/g, '\\"\\"\\"').replace(/\s+$/, "");
@@ -10973,17 +10973,17 @@ function handlerFile(contract, handlerName, written, library, transforms = {}) {
10973
10973
  "contract, not this file."
10974
10974
  ].join("\n");
10975
10975
  const imports = ["from appspace import widgets", ...written.imports].sort(natural3);
10976
- const constants = [];
10976
+ const constants2 = [];
10977
10977
  if (library !== null && typeof library.version === "string") {
10978
- constants.push("# The release of the hook library this table was built against.");
10979
- constants.push(`LIBRARY_VERSION = ${pyString2(library.version)}`);
10978
+ constants2.push("# The release of the hook library this table was built against.");
10979
+ constants2.push(`LIBRARY_VERSION = ${pyString2(library.version)}`);
10980
10980
  }
10981
- for (const row of written.constants) constants.push(row.text);
10981
+ for (const row of written.constants) constants2.push(row.text);
10982
10982
  const carried = Object.keys(transforms).length > 0;
10983
10983
  return writeModule({
10984
10984
  docstring,
10985
10985
  imports,
10986
- constants,
10986
+ constants: constants2,
10987
10987
  tables: carried ? [written.text, transformsTable(transforms)] : [written.text],
10988
10988
  body: [
10989
10989
  "def handle(ctx, payload):",
@@ -17462,7 +17462,7 @@ function measuredSummary(row) {
17462
17462
  ];
17463
17463
  }
17464
17464
  const body = ["def handle(ctx, payload):", " del payload", ' table = ctx.data.table(HANDLER["table"])', " answer = {}", ...loop, " return answer"].join("\n");
17465
- const constants = [assignment("MEASURES", measures, Object.keys(measures))];
17465
+ const constants2 = [assignment("MEASURES", measures, Object.keys(measures))];
17466
17466
  if (kinds.length === 0) {
17467
17467
  return {
17468
17468
  docstring: `Answer each tile on the page with a count of the events of ${row.table}.
@@ -17474,7 +17474,7 @@ wrote it \u2014 so none counts an event of a row this caller may not see.
17474
17474
 
17475
17475
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
17476
17476
  contract, not this file.`,
17477
- constants,
17477
+ constants: constants2,
17478
17478
  body
17479
17479
  };
17480
17480
  }
@@ -17488,7 +17488,7 @@ may not see. \`$today\` and its siblings are UTC. An average over no rows is
17488
17488
  None, which a stat shows as a dash.
17489
17489
 
17490
17490
  ` + (events ? "A count of events is what the platform recorded for rows this caller may\nread \u2014 each event its route stamped with the handler that wrote it.\n\n" : "") + "Generated by dashboard-kit/contract compile from contract.json \u2014 edit the\ncontract, not this file.",
17491
- constants,
17491
+ constants: constants2,
17492
17492
  body
17493
17493
  };
17494
17494
  }
@@ -17655,8 +17655,8 @@ function notOwnLines(row, id, verb, indent2) {
17655
17655
  function singletonSave(row, table) {
17656
17656
  const enums = enumsOf(row, table);
17657
17657
  const refs = refsOf(row, table);
17658
- const constants = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17659
- if (Object.keys(refs).length > 0) constants.push(assignment("REFS", refs, Object.keys(refs)));
17658
+ const constants2 = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17659
+ if (Object.keys(refs).length > 0) constants2.push(assignment("REFS", refs, Object.keys(refs)));
17660
17660
  return {
17661
17661
  docstring: `Save the ${singular(row.table)}: the table holds one row, so there is no id to send.
17662
17662
 
@@ -17668,7 +17668,7 @@ rather than written.
17668
17668
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
17669
17669
  contract, not this file.`,
17670
17670
  imports: Object.keys(refs).length > 0 ? ["import uuid"] : [],
17671
- constants,
17671
+ constants: constants2,
17672
17672
  body: [
17673
17673
  "def handle(ctx, payload):",
17674
17674
  ...collectRow(row, enums),
@@ -17948,8 +17948,8 @@ contract, not this file.`,
17948
17948
  const enums = enumsOf(row, table);
17949
17949
  const refs = refsOf(row, table);
17950
17950
  const guarded = named5(row.guard);
17951
- const constants = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17952
- if (Object.keys(refs).length > 0) constants.push(assignment("REFS", refs, Object.keys(refs)));
17951
+ const constants2 = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17952
+ if (Object.keys(refs).length > 0) constants2.push(assignment("REFS", refs, Object.keys(refs)));
17953
17953
  const guardDoc = guarded ? `
17954
17954
 
17955
17955
  \`guard\` holds an edit to one state: only a row that is still ${row.guard} may be
@@ -17966,7 +17966,7 @@ is a column anyone may set.${guardDoc}
17966
17966
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
17967
17967
  contract, not this file.`,
17968
17968
  imports: Object.keys(refs).length > 0 || guarded ? ["import uuid"] : [],
17969
- constants,
17969
+ constants: constants2,
17970
17970
  body: [
17971
17971
  "def handle(ctx, payload):",
17972
17972
  ...collectRow(row, enums),
@@ -18005,9 +18005,9 @@ contract, not this file.`,
18005
18005
  submit: (name, row, table, model) => {
18006
18006
  const enums = enumsOf(row, table);
18007
18007
  const decimals = decimalsOf(row, table);
18008
- const constants = [];
18009
- if (Object.keys(enums).length > 0) constants.push(assignment("ENUMS", enums, Object.keys(enums)));
18010
- if (decimals.length > 0) constants.push(`DECIMALS = ${pyLiteral(decimals)}`);
18008
+ const constants2 = [];
18009
+ if (Object.keys(enums).length > 0) constants2.push(assignment("ENUMS", enums, Object.keys(enums)));
18010
+ if (decimals.length > 0) constants2.push(`DECIMALS = ${pyLiteral(decimals)}`);
18011
18011
  const lines = ["def handle(ctx, payload):", ...collectRow(row, enums)];
18012
18012
  if (decimals.length > 0) {
18013
18013
  lines.push(
@@ -18021,17 +18021,17 @@ contract, not this file.`,
18021
18021
  }
18022
18022
  const refs = refsOf(row, table);
18023
18023
  if (Object.keys(refs).length > 0) {
18024
- constants.push(assignment("REFS", refs, Object.keys(refs)));
18024
+ constants2.push(assignment("REFS", refs, Object.keys(refs)));
18025
18025
  lines.push(...refLines());
18026
18026
  }
18027
18027
  const parent = linkedParent(row, model);
18028
18028
  if (parent !== null) {
18029
- constants.push(`PARENT = ${pyString(parent)}`);
18029
+ constants2.push(`PARENT = ${pyString(parent)}`);
18030
18030
  lines.push(...parentLines(row, parent, { missing: `{"error": ${pyString(`${row.by} is required`)}}`, invisible: `{"error": ${pyString(`${row.by} names no ${singular(parent)} this app can see`)}}` }));
18031
18031
  lines.push(' row[HANDLER["by"]] = parent_id');
18032
18032
  }
18033
18033
  if (isPlainObject8(row.requires)) {
18034
- constants.push(...requiresConstants(row, model));
18034
+ constants2.push(...requiresConstants(row, model));
18035
18035
  lines.push(...requiresLines(row, "saved"));
18036
18036
  }
18037
18037
  if (isPlainObject8(row.fixed) && Object.keys(row.fixed).length > 0) lines.push(' row.update(HANDLER["fixed"])');
@@ -18050,7 +18050,7 @@ browser could choose is a status anyone can choose.${linkDoc}${requiresDoc(row)}
18050
18050
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
18051
18051
  contract, not this file.`,
18052
18052
  imports: [...parent !== null || Object.keys(refs).length > 0 ? ["import uuid"] : [], ...decimals.length > 0 ? ["from decimal import Decimal, InvalidOperation"] : []],
18053
- constants,
18053
+ constants: constants2,
18054
18054
  body: lines.join("\n")
18055
18055
  };
18056
18056
  },
@@ -21013,7 +21013,7 @@ function mergeData(contract, drafts, base, problems, did, merge = false) {
21013
21013
  const setBy = /* @__PURE__ */ new Map();
21014
21014
  const declared = (key) => /* @__PURE__ */ new Set([...Object.keys(isObj(data[key]) ? data[key] : {}), ...drafts.flatMap((draft) => Object.keys(draft[key] ?? {}))]);
21015
21015
  const taken = { reads: declared("reads"), datasets: declared("datasets") };
21016
- const rename2 = (key, name) => {
21016
+ const rename3 = (key, name) => {
21017
21017
  let fresh = `${name}_2`;
21018
21018
  for (let n = 3; taken[key].has(fresh); n += 1) fresh = `${name}_${String(n)}`;
21019
21019
  taken[key].add(fresh);
@@ -21048,7 +21048,7 @@ function mergeData(contract, drafts, base, problems, did, merge = false) {
21048
21048
  );
21049
21049
  continue;
21050
21050
  }
21051
- const fresh = rename2(key, name);
21051
+ const fresh = rename3(key, name);
21052
21052
  (key === "reads" ? readAs : datasetAs).set(name, fresh);
21053
21053
  setBy.set(`${key}.${fresh}`, { name: draft.name, value: entry });
21054
21054
  into[fresh] = clone4(entry);
@@ -21138,10 +21138,10 @@ function canonical2(value) {
21138
21138
  }
21139
21139
  function frame(skeleton, pages, appId) {
21140
21140
  const described = skeleton.app.description === void 0 ? {} : { description: skeleton.app.description };
21141
- const rendered = rendererOf2({ app: skeleton.app }) === "runtime" ? { renderer: skeleton.app.renderer } : {};
21141
+ const rendered2 = rendererOf2({ app: skeleton.app }) === "runtime" ? { renderer: skeleton.app.renderer } : {};
21142
21142
  return {
21143
21143
  v: 1,
21144
- app: { id: appId, name: skeleton.app.name, ...described, kind: "dashboard", ...rendered, routes: pages.map((plan) => plan.address) },
21144
+ app: { id: appId, name: skeleton.app.name, ...described, kind: "dashboard", ...rendered2, routes: pages.map((plan) => plan.address) },
21145
21145
  pages: pages.map(pageFrom),
21146
21146
  elements: {},
21147
21147
  data: { source: "static", widgets: {} }
@@ -25320,24 +25320,24 @@ function stripPositional(contract, { keepTree = true, order: order2 } = {}) {
25320
25320
  const ordered2 = order2 === "keys" ? uids : rank !== null ? stated2(uids) : documentOrder(elements, uids, pagesByPath.get(page));
25321
25321
  ordered2.forEach((uid, index) => renamed.set(uid, `${page}#${index + 1}`));
25322
25322
  }
25323
- const rename2 = (uid) => typeof uid === "string" && renamed.has(uid) ? renamed.get(uid) : uid;
25323
+ const rename3 = (uid) => typeof uid === "string" && renamed.has(uid) ? renamed.get(uid) : uid;
25324
25324
  const rekeyed = {};
25325
25325
  for (const [uid, element] of Object.entries(elements)) {
25326
- const next = rename2(uid);
25326
+ const next = rename3(uid);
25327
25327
  for (const key of POSITIONAL_KEYS) delete element[key];
25328
25328
  element.uid = next;
25329
- if (element.parent !== void 0) element.parent = element.parent === null ? null : rename2(element.parent);
25330
- if (Array.isArray(element.children)) element.children = element.children.map(rename2).sort(natural3);
25329
+ if (element.parent !== void 0) element.parent = element.parent === null ? null : rename3(element.parent);
25330
+ if (Array.isArray(element.children)) element.children = element.children.map(rename3).sort(natural3);
25331
25331
  if (isPlainObject10(element.grid)) for (const key of POSITIONAL_GRID_KEYS) delete element.grid[key];
25332
25332
  rekeyed[next] = element;
25333
25333
  }
25334
25334
  out.elements = sortKeys2(rekeyed);
25335
25335
  for (const page of Array.isArray(out.pages) ? out.pages : []) {
25336
25336
  if (!Array.isArray(page.tree)) continue;
25337
- if (keepTree) page.tree = page.tree.map(rename2).sort(natural3);
25337
+ if (keepTree) page.tree = page.tree.map(rename3).sort(natural3);
25338
25338
  else delete page.tree;
25339
25339
  }
25340
- if (out.bindings !== void 0) out.bindings = renameDeep(out.bindings, rename2);
25340
+ if (out.bindings !== void 0) out.bindings = renameDeep(out.bindings, rename3);
25341
25341
  for (const problem6 of Array.isArray(out.problems) ? out.problems : []) {
25342
25342
  if (typeof problem6.where === "string") problem6.where = fileOf(problem6.where);
25343
25343
  }
@@ -25409,12 +25409,12 @@ function rootsAmong(elements, uids) {
25409
25409
  }
25410
25410
  return uids.filter((uid) => !claimed.has(uid) && (elements[uid]?.parent ?? null) === null);
25411
25411
  }
25412
- function renameDeep(value, rename2) {
25413
- if (typeof value === "string") return rename2(value);
25414
- if (Array.isArray(value)) return value.map((item) => renameDeep(item, rename2));
25412
+ function renameDeep(value, rename3) {
25413
+ if (typeof value === "string") return rename3(value);
25414
+ if (Array.isArray(value)) return value.map((item) => renameDeep(item, rename3));
25415
25415
  if (isPlainObject10(value)) {
25416
25416
  const out = {};
25417
- for (const [key, held] of Object.entries(value)) out[key] = renameDeep(held, rename2);
25417
+ for (const [key, held] of Object.entries(value)) out[key] = renameDeep(held, rename3);
25418
25418
  return out;
25419
25419
  }
25420
25420
  return value;
@@ -34870,13 +34870,592 @@ function registerLogsCommand(parent) {
34870
34870
  });
34871
34871
  }
34872
34872
 
34873
+ // src/commands/appspace/migrate.ts
34874
+ import { constants } from "fs";
34875
+ import { access, lstat as lstat2, readFile as readFile11, rename as rename2, rm as rm5, writeFile as writeFile9 } from "fs/promises";
34876
+ import { basename as basename2, dirname as dirname9, join as join17 } from "path";
34877
+ var MIGRATE_ROUTE = "/apps/migrate-preview";
34878
+ var RUNTIMES_NOW = [1];
34879
+ var MigrateRefused = class extends Error {
34880
+ };
34881
+ function isObj5(value) {
34882
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34883
+ }
34884
+ function targetRuntime(value) {
34885
+ if (value === void 0) return 1;
34886
+ const n = /^\d+$/.test(value.trim()) ? Number(value.trim()) : NaN;
34887
+ if (n === 2) {
34888
+ throw new MigrateRefused(
34889
+ "--to-runtime 2 is not available: runtime 2 (no ctx.data, ctx.state or ctx.financeos) is proposed (DR-58160) and the platform runs runtime 1 only, so the server cannot migrate to it. Run migrate with no --to-runtime: it moves the names inside runtime 1."
34890
+ );
34891
+ }
34892
+ if (!RUNTIMES_NOW.includes(n)) {
34893
+ throw new MigrateRefused(
34894
+ `--to-runtime ${JSON.stringify(value)} is not a runtime migrate knows. Use 1 (the default).`
34895
+ );
34896
+ }
34897
+ return n;
34898
+ }
34899
+ var DIFF_PATH_RE = /^(handlers|lib)\/[A-Za-z0-9_][A-Za-z0-9_-]{0,127}\.py$/;
34900
+ var HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
34901
+ var NO_NEWLINE = "\";
34902
+ function linesOf(text4) {
34903
+ const parts = text4.split(/(?<=\n)/);
34904
+ return parts.length > 0 && parts[parts.length - 1] === "" ? parts.slice(0, -1) : parts;
34905
+ }
34906
+ function applyDiff(diff, sent) {
34907
+ const lines = linesOf(diff);
34908
+ const hunks = /* @__PURE__ */ new Map();
34909
+ const invalid = () => new MigrateRefused("the diff from the server is not valid.");
34910
+ let current = null;
34911
+ for (let n = 0; n < lines.length; ) {
34912
+ const line2 = lines[n];
34913
+ if (line2.startsWith("--- a/")) {
34914
+ const next = lines[n + 1] ?? "";
34915
+ const path3 = line2.slice("--- a/".length).replace(/\n$/, "");
34916
+ if (next.replace(/\n$/, "") !== `+++ b/${path3}`) {
34917
+ throw new MigrateRefused(`the diff from the server is not valid near ${JSON.stringify(path3)}.`);
34918
+ }
34919
+ if (!DIFF_PATH_RE.test(path3) || !Object.prototype.hasOwnProperty.call(sent, path3)) {
34920
+ throw new MigrateRefused(
34921
+ `the diff from the server names ${JSON.stringify(path3)}, which is not a handler or lib file that was sent.`
34922
+ );
34923
+ }
34924
+ if (hunks.has(path3)) throw new MigrateRefused(`the diff from the server names ${path3} two times.`);
34925
+ current = [];
34926
+ hunks.set(path3, current);
34927
+ n += 2;
34928
+ continue;
34929
+ }
34930
+ const header = HUNK_RE.exec(line2);
34931
+ if (header === null || current === null) throw invalid();
34932
+ const hunk = {
34933
+ oldStart: Number(header[1]),
34934
+ oldCount: header[2] === void 0 ? 1 : Number(header[2]),
34935
+ newCount: header[4] === void 0 ? 1 : Number(header[4]),
34936
+ lines: []
34937
+ };
34938
+ current.push(hunk);
34939
+ n += 1;
34940
+ let oldLeft = hunk.oldCount;
34941
+ let newLeft = hunk.newCount;
34942
+ while (oldLeft > 0 || newLeft > 0) {
34943
+ const body = lines[n];
34944
+ if (body === void 0) throw invalid();
34945
+ if (body[0] === " ") {
34946
+ oldLeft -= 1;
34947
+ newLeft -= 1;
34948
+ } else if (body[0] === "-") oldLeft -= 1;
34949
+ else if (body[0] === "+") newLeft -= 1;
34950
+ else throw invalid();
34951
+ if (oldLeft < 0 || newLeft < 0) throw invalid();
34952
+ hunk.lines.push(body);
34953
+ n += 1;
34954
+ if (lines[n] !== void 0 && lines[n].replace(/\n$/, "") === NO_NEWLINE) {
34955
+ hunk.lines[hunk.lines.length - 1] = body.replace(/\n$/, "");
34956
+ n += 1;
34957
+ }
34958
+ }
34959
+ }
34960
+ const out = {};
34961
+ for (const [path3, fileHunks] of hunks) {
34962
+ const old = linesOf(sent[path3]);
34963
+ const result = [];
34964
+ let cursor = 0;
34965
+ for (const one of fileHunks) {
34966
+ const start = one.oldCount === 0 ? one.oldStart : one.oldStart - 1;
34967
+ if (start < cursor || start > old.length) {
34968
+ throw new MigrateRefused(`the diff from the server does not fit ${path3}.`);
34969
+ }
34970
+ result.push(...old.slice(cursor, start));
34971
+ let at = start;
34972
+ let removed = 0;
34973
+ let added = 0;
34974
+ for (const line2 of one.lines) {
34975
+ const body = line2.slice(1);
34976
+ if (line2[0] === "+") {
34977
+ result.push(body);
34978
+ added += 1;
34979
+ continue;
34980
+ }
34981
+ if (old[at] !== body) {
34982
+ throw new MigrateRefused(`the diff from the server does not fit ${path3} at line ${String(at + 1)}.`);
34983
+ }
34984
+ if (line2[0] === " ") {
34985
+ result.push(body);
34986
+ added += 1;
34987
+ }
34988
+ removed += 1;
34989
+ at += 1;
34990
+ }
34991
+ if (removed !== one.oldCount || added !== one.newCount) {
34992
+ throw new MigrateRefused(`the diff from the server does not fit ${path3}: a hunk has the wrong length.`);
34993
+ }
34994
+ cursor = at;
34995
+ }
34996
+ result.push(...old.slice(cursor));
34997
+ out[path3] = result.join("");
34998
+ }
34999
+ return out;
35000
+ }
35001
+ function mergeManifest(manifest, additions) {
35002
+ const out = { ...manifest };
35003
+ const added = [];
35004
+ const skipped = [];
35005
+ if (!isObj5(additions)) return { manifest: out, added, skipped };
35006
+ for (const key of Object.keys(additions)) {
35007
+ if (key !== "capabilities" && key !== "http") {
35008
+ skipped.push(`${key}: migrate does not know this addition; add it by hand`);
35009
+ }
35010
+ }
35011
+ const caps = additions["capabilities"];
35012
+ const words = isObj5(caps) && Array.isArray(caps["dr"]) ? caps["dr"].filter((w) => typeof w === "string") : [];
35013
+ if (words.length > 0) {
35014
+ const held = out["capabilities"];
35015
+ if (held !== void 0 && !isObj5(held)) {
35016
+ skipped.push("capabilities: it is not an object in manifest.json; add capabilities.dr by hand");
35017
+ } else {
35018
+ const capabilities = { ...held ?? {} };
35019
+ const dr = capabilities["dr"];
35020
+ if (dr !== void 0 && !Array.isArray(dr)) {
35021
+ skipped.push("capabilities.dr: it is not a list in manifest.json; add the scope words by hand");
35022
+ } else {
35023
+ const list3 = [...dr ?? []];
35024
+ for (const word of words) {
35025
+ if (!list3.includes(word)) {
35026
+ list3.push(word);
35027
+ added.push(`capabilities.dr: ${word}`);
35028
+ }
35029
+ }
35030
+ capabilities["dr"] = list3;
35031
+ out["capabilities"] = capabilities;
35032
+ }
35033
+ }
35034
+ }
35035
+ const http = additions["http"];
35036
+ if (isObj5(http) && Object.keys(http).length > 0) {
35037
+ const held = out["http"];
35038
+ if (held !== void 0 && !isObj5(held)) {
35039
+ skipped.push("http: it is not an object in manifest.json; add the http entries by hand");
35040
+ } else {
35041
+ const entries = { ...held ?? {} };
35042
+ for (const [name, entry] of Object.entries(http)) {
35043
+ if (Object.prototype.hasOwnProperty.call(entries, name)) {
35044
+ skipped.push(`http.${name}: the manifest has this name already; it is not changed`);
35045
+ continue;
35046
+ }
35047
+ Object.defineProperty(entries, name, { value: entry, enumerable: true, writable: true, configurable: true });
35048
+ added.push(`http.${name}`);
35049
+ }
35050
+ out["http"] = entries;
35051
+ }
35052
+ }
35053
+ return { manifest: out, added, skipped };
35054
+ }
35055
+ var NotJson = class extends Error {
35056
+ };
35057
+ function skipSpace(text4, i) {
35058
+ while (i < text4.length && " \r\n".includes(text4[i])) i += 1;
35059
+ return i;
35060
+ }
35061
+ function stringEnd3(text4, i) {
35062
+ if (text4[i] !== '"') throw new NotJson();
35063
+ for (let n = i + 1; n < text4.length; n++) {
35064
+ if (text4[n] === "\\") n += 1;
35065
+ else if (text4[n] === '"') return n + 1;
35066
+ }
35067
+ throw new NotJson();
35068
+ }
35069
+ function valueEnd(text4, i) {
35070
+ const c = text4[i];
35071
+ if (c === '"') return stringEnd3(text4, i);
35072
+ if (c === "{" || c === "[") return containerOf(text4, i).close + 1;
35073
+ let n = i;
35074
+ while (n < text4.length && !",}] \r\n".includes(text4[n])) n += 1;
35075
+ if (n === i) throw new NotJson();
35076
+ return n;
35077
+ }
35078
+ function containerOf(text4, open2) {
35079
+ const object = text4[open2] === "{";
35080
+ const closer = object ? "}" : "]";
35081
+ const members = [];
35082
+ let i = skipSpace(text4, open2 + 1);
35083
+ if (text4[i] === closer) return { open: open2, close: i, members };
35084
+ for (; ; ) {
35085
+ let key = null;
35086
+ const start = i;
35087
+ if (object) {
35088
+ const keyEnd = stringEnd3(text4, i);
35089
+ key = JSON.parse(text4.slice(i, keyEnd));
35090
+ i = skipSpace(text4, keyEnd);
35091
+ if (text4[i] !== ":") throw new NotJson();
35092
+ i = skipSpace(text4, i + 1);
35093
+ }
35094
+ const valueStart = i;
35095
+ const end = valueEnd(text4, i);
35096
+ members.push({ key, start: object ? valueStart : start, end });
35097
+ i = skipSpace(text4, end);
35098
+ if (text4[i] === ",") {
35099
+ i = skipSpace(text4, i + 1);
35100
+ continue;
35101
+ }
35102
+ if (text4[i] === closer) return { open: open2, close: i, members };
35103
+ throw new NotJson();
35104
+ }
35105
+ }
35106
+ function memberOf(container, key) {
35107
+ for (let n = container.members.length - 1; n >= 0; n--) {
35108
+ if (container.members[n]?.key === key) return container.members[n];
35109
+ }
35110
+ return void 0;
35111
+ }
35112
+ function styleOf(text4) {
35113
+ const newline = text4.includes("\r\n") ? "\r\n" : "\n";
35114
+ const indented = /\n([ \t]+)\S/.exec(text4);
35115
+ return { unit: indented?.[1] ?? " ", newline };
35116
+ }
35117
+ function insertion(text4, container, items, depth, style) {
35118
+ const multiline = text4.slice(container.open, container.close).includes("\n");
35119
+ const last = container.members[container.members.length - 1];
35120
+ if (!multiline) {
35121
+ const joined2 = items.join(", ");
35122
+ return last === void 0 ? { at: container.open + 1, text: joined2 } : { at: last.end, text: `, ${joined2}` };
35123
+ }
35124
+ const indent2 = style.unit.repeat(depth + 1);
35125
+ const joined = items.map((item) => `${style.newline}${indent2}${item}`).join(",");
35126
+ return last === void 0 ? { at: container.open + 1, text: joined } : { at: last.end, text: `,${joined}` };
35127
+ }
35128
+ function rendered(value, depth, style, multiline) {
35129
+ if (!multiline) return JSON.stringify(value);
35130
+ return JSON.stringify(value, null, style.unit).split("\n").join(`${style.newline}${style.unit.repeat(depth)}`);
35131
+ }
35132
+ function canonical5(value) {
35133
+ if (Array.isArray(value)) return `[${value.map(canonical5).join(",")}]`;
35134
+ if (isObj5(value)) {
35135
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical5(value[k])}`).join(",")}}`;
35136
+ }
35137
+ return JSON.stringify(value);
35138
+ }
35139
+ function manifestText(raw, merge, before) {
35140
+ if (merge.added.length === 0) return raw;
35141
+ try {
35142
+ const style = styleOf(raw);
35143
+ const start = skipSpace(raw, raw.charCodeAt(0) === 65279 ? 1 : 0);
35144
+ if (raw[start] !== "{") throw new NotJson();
35145
+ const root = containerOf(raw, start);
35146
+ const rootMultiline = raw.slice(root.open, root.close).includes("\n");
35147
+ const edits = [];
35148
+ const rootItems = [];
35149
+ const words = merge.manifest["capabilities"]?.["dr"];
35150
+ const heldCaps = before["capabilities"];
35151
+ const newWords = Array.isArray(words) ? words.slice(isObj5(heldCaps) && Array.isArray(heldCaps["dr"]) ? heldCaps["dr"].length : 0) : [];
35152
+ if (newWords.length > 0) {
35153
+ const caps = memberOf(root, "capabilities");
35154
+ if (caps === void 0) {
35155
+ rootItems.push(`"capabilities": ${rendered({ dr: newWords }, 1, style, rootMultiline)}`);
35156
+ } else {
35157
+ const capsBox = containerOf(raw, caps.start);
35158
+ const dr = memberOf(capsBox, "dr");
35159
+ if (dr === void 0) {
35160
+ const multiline = raw.slice(capsBox.open, capsBox.close).includes("\n");
35161
+ edits.push(insertion(raw, capsBox, [`"dr": ${rendered(newWords, 2, style, multiline)}`], 1, style));
35162
+ } else {
35163
+ const list3 = containerOf(raw, dr.start);
35164
+ edits.push(insertion(raw, list3, newWords.map((w) => JSON.stringify(w)), 2, style));
35165
+ }
35166
+ }
35167
+ }
35168
+ const http = merge.manifest["http"];
35169
+ const heldHttp = before["http"];
35170
+ const newEntries = isObj5(http) ? Object.keys(http).filter((name) => !(isObj5(heldHttp) && Object.prototype.hasOwnProperty.call(heldHttp, name))) : [];
35171
+ if (newEntries.length > 0 && isObj5(http)) {
35172
+ const box = memberOf(root, "http");
35173
+ if (box === void 0) {
35174
+ const entries = Object.fromEntries(newEntries.map((name) => [name, http[name]]));
35175
+ rootItems.push(`"http": ${rendered(entries, 1, style, rootMultiline)}`);
35176
+ } else {
35177
+ const httpBox = containerOf(raw, box.start);
35178
+ const multiline = raw.slice(httpBox.open, httpBox.close).includes("\n");
35179
+ edits.push(
35180
+ insertion(
35181
+ raw,
35182
+ httpBox,
35183
+ newEntries.map((name) => `${JSON.stringify(name)}: ${rendered(http[name], 2, style, multiline)}`),
35184
+ 1,
35185
+ style
35186
+ )
35187
+ );
35188
+ }
35189
+ }
35190
+ if (rootItems.length > 0) edits.push(insertion(raw, root, rootItems, 0, style));
35191
+ let out = raw;
35192
+ for (const edit of [...edits].sort((a, b) => b.at - a.at)) {
35193
+ out = out.slice(0, edit.at) + edit.text + out.slice(edit.at);
35194
+ }
35195
+ if (canonical5(JSON.parse(out)) !== canonical5(merge.manifest)) throw new NotJson();
35196
+ return out;
35197
+ } catch (err) {
35198
+ if (!(err instanceof NotJson) && !(err instanceof SyntaxError)) throw err;
35199
+ throw new MigrateRefused(
35200
+ `migrate could not add ${merge.added.join(", ")} to manifest.json in its own layout; add them by hand.`
35201
+ );
35202
+ }
35203
+ }
35204
+ function previewOf(body) {
35205
+ if (!isObj5(body) || typeof body["diff"] !== "string" || !Array.isArray(body["files"]) || !Array.isArray(body["points"]) || !isObj5(body["manifest"])) {
35206
+ throw new MigrateRefused("the server answered, but not with a migrate preview.");
35207
+ }
35208
+ return body;
35209
+ }
35210
+ function failureOf(err) {
35211
+ if (err instanceof AppSpaceHttpError) {
35212
+ const detail = isObj5(err.body) ? err.body["detail"] : void 0;
35213
+ if (err.status === 404 && detail === "Not Found" || err.status === 405) {
35214
+ return `this server has no migrate preview (POST ${MIGRATE_ROUTE}); it predates it (DR-58157).`;
35215
+ }
35216
+ if (err.status === 422 && isObj5(detail) && Array.isArray(detail["problems"])) {
35217
+ return `the server refused the package (422):
35218
+ ${detail["problems"].map((p) => ` ${String(p)}`).join("\n")}`;
35219
+ }
35220
+ return err.message;
35221
+ }
35222
+ return `could not get the migrate preview (${err instanceof Error ? err.message : String(err)}).`;
35223
+ }
35224
+ function renderPreview(preview) {
35225
+ const out = [];
35226
+ if (preview.diff !== "") out.push(preview.diff.replace(/\n$/, ""), "");
35227
+ if (preview.points.length > 0) {
35228
+ out.push(`Open points (${String(preview.points.length)}), each needs a person:`);
35229
+ const kinds = [...new Set(preview.points.map((p) => p.kind))].sort();
35230
+ for (const kind of kinds) {
35231
+ out.push(` ${kind}:`);
35232
+ for (const p of preview.points.filter((one) => one.kind === kind)) {
35233
+ const where2 = p.line === null ? p.file : `${p.file}:${String(p.line)}`;
35234
+ out.push(` ${where2} ${p.text}${p.target === void 0 ? "" : ` [${p.target}]`}`);
35235
+ }
35236
+ }
35237
+ out.push("");
35238
+ }
35239
+ const additions = Object.keys(preview.manifest);
35240
+ if (additions.length > 0) {
35241
+ out.push("manifest.json additions:", ...JSON.stringify(preview.manifest, null, 2).split("\n").map((l) => ` ${l}`), "");
35242
+ }
35243
+ const files = preview.files.length;
35244
+ out.push(
35245
+ preview.diff === "" && additions.length === 0 ? "Nothing to move: the code uses no old ctx name that the preview can rewrite." : `${String(preview.rewrites)} rewrite(s) in ${String(files)} file(s).`
35246
+ );
35247
+ return out.join("\n") + "\n";
35248
+ }
35249
+ function renderCheck(check5) {
35250
+ const out = [];
35251
+ if (check5.problems.length === 0 && check5.skipped.length === 0) {
35252
+ out.push("Package check: the push would go through.");
35253
+ }
35254
+ for (const p of check5.problems) out.push(`[${p.code}] ${p.message} ${p.fix}`.trim());
35255
+ for (const s of check5.skipped) out.push(`Not checked: ${s.what} (${s.why}).`);
35256
+ return out.join("\n") + "\n";
35257
+ }
35258
+ async function runMigrate(dir, opts) {
35259
+ try {
35260
+ targetRuntime(opts.toRuntime);
35261
+ const { manifest } = await readManifest(dir).catch((err) => {
35262
+ throw new MigrateRefused(err instanceof Error ? err.message : String(err));
35263
+ });
35264
+ const manifestSent = await readFile11(join17(dir, "manifest.json"), "utf8");
35265
+ if (canonical5(JSON.parse(manifestSent)) !== canonical5(manifest)) {
35266
+ throw new MigrateRefused("manifest.json changed while migrate read it. Run migrate again.");
35267
+ }
35268
+ const handlers = await readHandlers(join17(dir, "handlers"), await readState(dir));
35269
+ const lib = await readLib(join17(dir, "lib"));
35270
+ const sent = {};
35271
+ for (const [name, spec] of Object.entries(handlers)) sent[`handlers/${name}.py`] = spec.code;
35272
+ for (const [name, code] of Object.entries(lib)) sent[`lib/${name}.py`] = code;
35273
+ let preview;
35274
+ const client = await connect(opts).catch((err) => {
35275
+ throw new MigrateRefused(failureOf(err));
35276
+ });
35277
+ try {
35278
+ const body = await client.request(MIGRATE_ROUTE, { method: "POST", body: { manifest, handlers, lib } }).catch((err) => {
35279
+ throw new MigrateRefused(failureOf(err));
35280
+ });
35281
+ preview = previewOf(body);
35282
+ } finally {
35283
+ client.cleanup();
35284
+ }
35285
+ if (opts.write !== true) {
35286
+ if (opts.json === true) printJson({ ...preview, written: [] });
35287
+ else {
35288
+ process.stdout.write(renderPreview(preview));
35289
+ if (preview.diff !== "" || Object.keys(preview.manifest).length > 0) {
35290
+ process.stdout.write("Dry run: nothing was written. Run again with --write to apply the diff and the manifest additions.\n");
35291
+ }
35292
+ }
35293
+ return 0;
35294
+ }
35295
+ const files = applyDiff(preview.diff, sent);
35296
+ const manifestNow = await readFile11(join17(dir, "manifest.json"), "utf8");
35297
+ if (manifestNow !== manifestSent) {
35298
+ throw new MigrateRefused("manifest.json changed since migrate read it. Run migrate again.");
35299
+ }
35300
+ const merge = mergeManifest(JSON.parse(manifestSent), preview.manifest);
35301
+ const plan = [];
35302
+ for (const [path3, text4] of Object.entries(files)) {
35303
+ if (text4 !== sent[path3]) plan.push({ path: path3, old: sent[path3], text: text4 });
35304
+ }
35305
+ if (merge.added.length > 0) {
35306
+ plan.push({
35307
+ path: "manifest.json",
35308
+ old: manifestSent,
35309
+ text: manifestText(manifestSent, merge, JSON.parse(manifestSent))
35310
+ });
35311
+ }
35312
+ for (const step of plan) await writable(dir, step.path, step.old);
35313
+ const written = [];
35314
+ let check5 = null;
35315
+ let warnings = [];
35316
+ try {
35317
+ for (const step of plan) {
35318
+ await replaceFile(join17(dir, step.path), step.text);
35319
+ written.push(step.path);
35320
+ }
35321
+ const compiled = await recordedDigests(dir);
35322
+ warnings = written.filter((path3) => Object.prototype.hasOwnProperty.call(compiled, path3)).map(
35323
+ (path3) => `${path3} is a file app-space compile wrote; the next compile counts this edit as a hand edit (eject it to keep it as yours, or move the contract to the new names).`
35324
+ );
35325
+ if (opts.check !== false && written.length > 0) {
35326
+ let contract = null;
35327
+ try {
35328
+ const raw = await readIfPresent(join17(dir, "contract.json"));
35329
+ contract = raw === void 0 ? null : JSON.parse(raw);
35330
+ } catch {
35331
+ contract = null;
35332
+ }
35333
+ check5 = await checkPackage(dir, {}, contract, opts, true);
35334
+ }
35335
+ } catch (err) {
35336
+ const restored = [];
35337
+ const lost = [];
35338
+ for (const step of plan.filter((one) => written.includes(one.path)).reverse()) {
35339
+ try {
35340
+ await replaceFile(join17(dir, step.path), step.old);
35341
+ restored.push(step.path);
35342
+ } catch {
35343
+ lost.push(step.path);
35344
+ }
35345
+ }
35346
+ const why = err instanceof Error ? err.message : String(err);
35347
+ const said2 = `migrate --write failed (${why}). ` + (restored.length > 0 ? `Put back the old text of: ${restored.join(", ")}. ` : "") + (lost.length > 0 ? `Could NOT put back: ${lost.join(", ")}; these files hold the new text.` : "The folder is as it was.");
35348
+ if (opts.json === true) printJson({ ok: false, error: said2, restored, not_restored: lost });
35349
+ process.stderr.write(`${said2}
35350
+ `);
35351
+ return 1;
35352
+ }
35353
+ if (opts.json === true) {
35354
+ printJson({
35355
+ ...preview,
35356
+ written,
35357
+ manifest_added: merge.added,
35358
+ manifest_skipped: merge.skipped,
35359
+ warnings,
35360
+ check: check5
35361
+ });
35362
+ } else {
35363
+ process.stdout.write(renderPreview(preview));
35364
+ process.stdout.write(
35365
+ written.length === 0 ? "Nothing was written: the folder has the new names already.\n" : `Wrote:
35366
+ ${written.map((p) => ` ${p}
35367
+ `).join("")}`
35368
+ );
35369
+ for (const line2 of merge.added) process.stdout.write(` added ${line2}
35370
+ `);
35371
+ for (const line2 of merge.skipped) process.stderr.write(`warning: manifest.json ${line2}
35372
+ `);
35373
+ for (const line2 of warnings) process.stderr.write(`warning: ${line2}
35374
+ `);
35375
+ if (check5 !== null) process.stdout.write(renderCheck(check5));
35376
+ }
35377
+ return check5 !== null && check5.problems.length > 0 ? 1 : 0;
35378
+ } catch (err) {
35379
+ const said2 = err instanceof MigrateRefused ? err.message : `migrate failed (${err instanceof Error ? err.message : String(err)}).`;
35380
+ if (opts.json === true) printJson({ ok: false, error: `${said2} Nothing was written.` });
35381
+ process.stderr.write(`${said2} Nothing was written.
35382
+ `);
35383
+ return 1;
35384
+ }
35385
+ }
35386
+ var _io = { rename: rename2, writeFile: writeFile9 };
35387
+ async function writable(dir, path3, sent) {
35388
+ const full = join17(dir, path3);
35389
+ const parts = path3.split("/");
35390
+ for (let n = 1; n < parts.length; n += 1) {
35391
+ const folder = parts.slice(0, n).join("/");
35392
+ let kind;
35393
+ try {
35394
+ kind = await lstat2(join17(dir, folder));
35395
+ } catch {
35396
+ throw new MigrateRefused(`${path3} is gone since migrate read it. Run migrate again.`);
35397
+ }
35398
+ if (!kind.isDirectory()) {
35399
+ throw new MigrateRefused(`${folder}/ is not a plain folder (a link, or another kind); migrate writes only inside the app folder.`);
35400
+ }
35401
+ }
35402
+ let info;
35403
+ try {
35404
+ info = await lstat2(full);
35405
+ } catch {
35406
+ throw new MigrateRefused(`${path3} is gone since migrate read it. Run migrate again.`);
35407
+ }
35408
+ if (!info.isFile()) {
35409
+ throw new MigrateRefused(`${path3} is not a regular file (a link, or another kind); migrate writes only regular files.`);
35410
+ }
35411
+ try {
35412
+ await access(full, constants.W_OK);
35413
+ await access(dirname9(full), constants.W_OK);
35414
+ } catch {
35415
+ throw new MigrateRefused(`${path3} cannot be written (no permission).`);
35416
+ }
35417
+ const bytes = await readFile11(full);
35418
+ const text4 = bytes.toString("utf8");
35419
+ if (!Buffer.from(text4, "utf8").equals(bytes)) {
35420
+ throw new MigrateRefused(`${path3} is not valid UTF-8; migrate would change bytes it did not mean to.`);
35421
+ }
35422
+ if (text4 !== sent) {
35423
+ throw new MigrateRefused(`${path3} changed since migrate read it. Run migrate again.`);
35424
+ }
35425
+ }
35426
+ var temporaries = 0;
35427
+ async function replaceFile(full, text4) {
35428
+ temporaries += 1;
35429
+ const temporary = join17(dirname9(full), `.${basename2(full)}.migrate-${String(process.pid)}-${String(temporaries)}.tmp`);
35430
+ const mode = (await lstat2(full)).mode & 511;
35431
+ await _io.writeFile(temporary, text4, { flag: "wx", mode });
35432
+ try {
35433
+ await _io.rename(temporary, full);
35434
+ } catch (err) {
35435
+ await rm5(temporary, { force: true });
35436
+ throw err;
35437
+ }
35438
+ }
35439
+ function registerMigrateCommand(parent) {
35440
+ withJsonOption(
35441
+ withServerOptions(
35442
+ parent.command("migrate [dir]").description(
35443
+ "Move a folder to the new ctx names (ctx.app.tables, ctx.app.state, ctx.dr): a dry run that prints the diff, or --write."
35444
+ ).option("--write", "Apply the diff to the files and add the manifest additions, then run the package check.").option("--to-runtime <n>", "The runtime to move to. Only 1 today: runtime 2 is proposed (DR-58160).").option("--no-check", "With --write: do not run the package check after the write.")
35445
+ )
35446
+ ).action(async (dirArg, opts) => {
35447
+ const code = await runMigrate(dirArg ?? ".", opts);
35448
+ if (code !== 0) process.exitCode = code;
35449
+ });
35450
+ }
35451
+
34873
35452
  // src/commands/appspace/test.ts
34874
- import { readFile as readFile13 } from "fs/promises";
34875
- import { join as join18, resolve as resolve16 } from "path";
35453
+ import { readFile as readFile14 } from "fs/promises";
35454
+ import { join as join19, resolve as resolve16 } from "path";
34876
35455
 
34877
35456
  // src/commands/appspace/_files.ts
34878
- import { readFile as readFile11, realpath } from "fs/promises";
34879
- import { basename as basename2, extname, resolve as resolve14, sep as sep5 } from "path";
35457
+ import { readFile as readFile12, realpath } from "fs/promises";
35458
+ import { basename as basename3, extname, resolve as resolve14, sep as sep5 } from "path";
34880
35459
 
34881
35460
  // src/commands/appspace/_samplePdf.ts
34882
35461
  function pdfString(text4) {
@@ -35033,7 +35612,7 @@ function readFailure(path3, full, err) {
35033
35612
  if (code === void 0 || code === "ENOENT") return new Error(`no file at ${path3} (looked for ${full}).`);
35034
35613
  return new Error(`could not read ${path3} (${String(code)}).`);
35035
35614
  }
35036
- async function resolveFile(path3, base, { read = readFile11, confine = false, realpath: real = realpath } = {}) {
35615
+ async function resolveFile(path3, base, { read = readFile12, confine = false, realpath: real = realpath } = {}) {
35037
35616
  if (path3 === null) {
35038
35617
  return { bytes: sampleInvoiceBytes(), filename: SAMPLE_INVOICE.filename, mimeType: SAMPLE_INVOICE.mimeType };
35039
35618
  }
@@ -35057,7 +35636,7 @@ async function resolveFile(path3, base, { read = readFile11, confine = false, re
35057
35636
  throw readFailure(path3, full, err);
35058
35637
  }
35059
35638
  if (bytes.length === 0) throw new Error(`${path3} is empty, and the platform refuses an empty upload.`);
35060
- const filename = basename2(full);
35639
+ const filename = basename3(full);
35061
35640
  return { bytes, filename, mimeType: mimeTypeOf(filename) };
35062
35641
  }
35063
35642
  function isPlainObject18(value) {
@@ -35079,7 +35658,7 @@ function fileColumnsOf(model) {
35079
35658
  }
35080
35659
  async function readFileColumns(dir) {
35081
35660
  try {
35082
- return fileColumnsOf(JSON.parse(await readFile11(resolve14(dir, "data_model.json"), "utf8")));
35661
+ return fileColumnsOf(JSON.parse(await readFile12(resolve14(dir, "data_model.json"), "utf8")));
35083
35662
  } catch {
35084
35663
  return null;
35085
35664
  }
@@ -37177,10 +37756,10 @@ async function runUiSmoke(opts) {
37177
37756
  // src/commands/appspace/_screenshot.ts
37178
37757
  import { spawn } from "child_process";
37179
37758
  import { existsSync as existsSync3, statSync as statSync3 } from "fs";
37180
- import { mkdir as mkdir8, mkdtemp as mkdtemp4, readFile as readFile12, readdir as readdir3, rm as rm5, stat as stat2, writeFile as writeFile9 } from "fs/promises";
37759
+ import { mkdir as mkdir8, mkdtemp as mkdtemp4, readFile as readFile13, readdir as readdir3, rm as rm6, stat as stat2, writeFile as writeFile10 } from "fs/promises";
37181
37760
  import { createServer } from "http";
37182
37761
  import { tmpdir as tmpdir5 } from "os";
37183
- import { delimiter, extname as extname2, join as join17, relative as relative3, resolve as resolve15, sep as sep6 } from "path";
37762
+ import { delimiter, extname as extname2, join as join18, relative as relative3, resolve as resolve15, sep as sep6 } from "path";
37184
37763
 
37185
37764
  // ../tests/vendor/fixtures/widgets/kpi.json
37186
37765
  var kpi_default = {
@@ -38207,7 +38786,7 @@ function findChrome(env = process.env, exists = isFile, appPaths = CHROME_APP_PA
38207
38786
  const dirs = (env["PATH"] ?? "").split(delimiter).filter((dir) => dir !== "");
38208
38787
  for (const name of CHROME_NAMES) {
38209
38788
  for (const dir of dirs) {
38210
- const path3 = join17(dir, name);
38789
+ const path3 = join18(dir, name);
38211
38790
  if (exists(path3)) return path3;
38212
38791
  }
38213
38792
  }
@@ -38418,7 +38997,7 @@ var Shelf = class {
38418
38997
  const full = inside(this.source.root, rel);
38419
38998
  if (full === null) continue;
38420
38999
  try {
38421
- return { status: 200, type: contentType(full), body: await readFile12(full) };
39000
+ return { status: 200, type: contentType(full), body: await readFile13(full) };
38422
39001
  } catch {
38423
39002
  }
38424
39003
  }
@@ -38548,8 +39127,8 @@ async function startStubServer(opts) {
38548
39127
  const body = await readBody(req);
38549
39128
  const log = logOf(id);
38550
39129
  note(log.called, inApp);
38551
- const access = accessFor(opts.manifest, shot.role, opts.allowedByRole?.[shot.role], opts.sources ?? []);
38552
- if (access.allowed[inApp] === false) {
39130
+ const access2 = accessFor(opts.manifest, shot.role, opts.allowedByRole?.[shot.role], opts.sources ?? []);
39131
+ if (access2.allowed[inApp] === false) {
38553
39132
  note(log.refused, inApp);
38554
39133
  return sendJson(res, 403, { detail: `role ${shot.role} may not call ${inApp}` });
38555
39134
  }
@@ -38622,7 +39201,7 @@ function asRoot(getuid = process.getuid?.bind(process) ?? null) {
38622
39201
  return getuid !== null && getuid() === 0;
38623
39202
  }
38624
39203
  async function runChrome(run) {
38625
- const profile = await mkdtemp4(join17(tmpdir5(), "dr-appspace-shot-"));
39204
+ const profile = await mkdtemp4(join18(tmpdir5(), "dr-appspace-shot-"));
38626
39205
  const args = [
38627
39206
  // Chrome will not start as root without it, and a container's shell is
38628
39207
  // root (the managed build sandbox). Elsewhere its own sandbox stays on.
@@ -38688,7 +39267,7 @@ async function runChrome(run) {
38688
39267
  }
38689
39268
  } finally {
38690
39269
  killGroup(child);
38691
- await rm5(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => void 0);
39270
+ await rm6(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => void 0);
38692
39271
  }
38693
39272
  if (ok) return { ok, stdout, profile };
38694
39273
  const error = spawnError ?? (Date.now() >= deadline ? `timed out after ${String(Math.round(run.timeoutMs / 1e3))}s` : run.out === void 0 ? "Chrome printed no DOM" : "Chrome exited without writing the screenshot");
@@ -38805,13 +39384,13 @@ async function runScreenshots(opts) {
38805
39384
  seen = rows2 === null ? { look: null, skipped: measured.error ?? "the page never settled" } : { look: rows2 };
38806
39385
  }
38807
39386
  }
38808
- const out = join17(opts.outDir, file);
39387
+ const out = join18(opts.outDir, file);
38809
39388
  let id = -1;
38810
39389
  let result;
38811
39390
  for (let attempt = 0; attempt < 2 && now() < pageUntil - 500; attempt++) {
38812
39391
  id = nextId++;
38813
39392
  stub.register(id, { role });
38814
- await rm5(out, { force: true });
39393
+ await rm6(out, { force: true });
38815
39394
  result = await runChrome({
38816
39395
  chrome: opts.chrome,
38817
39396
  url: stub.urlFor(id, entry),
@@ -38840,7 +39419,7 @@ async function runScreenshots(opts) {
38840
39419
  shots[index2] = { ...entryOut, error: result.error ?? "no picture" };
38841
39420
  return;
38842
39421
  }
38843
- const bytes = await readFile12(out);
39422
+ const bytes = await readFile13(out);
38844
39423
  if (look && seen === void 0) toLook.push(index2);
38845
39424
  shots[index2] = {
38846
39425
  ...entryOut,
@@ -38884,11 +39463,11 @@ async function runScreenshots(opts) {
38884
39463
  sample,
38885
39464
  shots
38886
39465
  };
38887
- await writeFile9(join17(opts.outDir, "index.json"), JSON.stringify(index, null, 2) + "\n");
39466
+ await writeFile10(join18(opts.outDir, "index.json"), JSON.stringify(index, null, 2) + "\n");
38888
39467
  return index;
38889
39468
  }
38890
39469
  async function readLocalUi(dir) {
38891
- const root = join17(dir, "ui");
39470
+ const root = join18(dir, "ui");
38892
39471
  const out = {};
38893
39472
  const walk5 = async (folder) => {
38894
39473
  let names;
@@ -38898,16 +39477,16 @@ async function readLocalUi(dir) {
38898
39477
  return;
38899
39478
  }
38900
39479
  for (const one of names) {
38901
- const full = join17(folder, one.name);
39480
+ const full = join18(folder, one.name);
38902
39481
  if (one.isDirectory()) await walk5(full);
38903
- else if (one.isFile()) out[relative3(root, full).split(sep6).join("/")] = await readFile12(full);
39482
+ else if (one.isFile()) out[relative3(root, full).split(sep6).join("/")] = await readFile13(full);
38904
39483
  }
38905
39484
  };
38906
39485
  await walk5(root);
38907
39486
  return out;
38908
39487
  }
38909
39488
  function looksLikeShelf(root) {
38910
- return existsSync3(join17(root, "vendor"));
39489
+ return existsSync3(join18(root, "vendor"));
38911
39490
  }
38912
39491
  function renderShotTable(index, outDir) {
38913
39492
  const rows2 = index.shots.map((shot) => [
@@ -38941,7 +39520,7 @@ screenshots \u2192 ${outDir} (${String(written)} of ${String(index.shots.length
38941
39520
  `;
38942
39521
  }
38943
39522
  out += lookLine(index);
38944
- out += ` index: ${join17(outDir, "index.json")}
39523
+ out += ` index: ${join18(outDir, "index.json")}
38945
39524
  `;
38946
39525
  return out;
38947
39526
  }
@@ -40034,7 +40613,7 @@ function partFindings(runs) {
40034
40613
  }
40035
40614
  return out;
40036
40615
  }
40037
- function linesOf(text4) {
40616
+ function linesOf2(text4) {
40038
40617
  if (typeof text4 !== "string" || text4 === "") return 0;
40039
40618
  return text4.replace(/\n$/, "").split("\n").length;
40040
40619
  }
@@ -40134,13 +40713,13 @@ function partsSummary(contract, bundle, handlerCode) {
40134
40713
  }
40135
40714
  }
40136
40715
  let customUiLines = 0;
40137
- for (const module of modules) customUiLines += linesOf(bundle[module] ?? bundle[`ui/${module}`]);
40716
+ for (const module of modules) customUiLines += linesOf2(bundle[module] ?? bundle[`ui/${module}`]);
40138
40717
  let customHandlers = 0;
40139
40718
  let customHandlerLines = 0;
40140
40719
  for (const [name, handler] of Object.entries(contract.data?.app?.handlers ?? {})) {
40141
40720
  if (handler?.role !== "custom") continue;
40142
40721
  customHandlers += 1;
40143
- customHandlerLines += linesOf(handlerCode[name]);
40722
+ customHandlerLines += linesOf2(handlerCode[name]);
40144
40723
  }
40145
40724
  const components = registry2 + customUi;
40146
40725
  const summary = {
@@ -40618,7 +41197,7 @@ function collectRoles(value, previous = []) {
40618
41197
  }
40619
41198
  async function readLocalManifest(dir) {
40620
41199
  try {
40621
- return JSON.parse(await readFile13(join18(dir, "manifest.json"), "utf8"));
41200
+ return JSON.parse(await readFile14(join19(dir, "manifest.json"), "utf8"));
40622
41201
  } catch {
40623
41202
  return null;
40624
41203
  }
@@ -40758,10 +41337,10 @@ function evaluateCase(kase, res) {
40758
41337
  return problems;
40759
41338
  }
40760
41339
  async function loadFixtures(dir, explicit) {
40761
- const path3 = explicit ?? join18(dir, DEFAULT_FIXTURES);
41340
+ const path3 = explicit ?? join19(dir, DEFAULT_FIXTURES);
40762
41341
  let raw;
40763
41342
  try {
40764
- raw = await readFile13(path3, "utf8");
41343
+ raw = await readFile14(path3, "utf8");
40765
41344
  } catch {
40766
41345
  if (explicit !== void 0) throw new Error(`no fixtures file at ${path3}.`);
40767
41346
  return { fixtures: { cases: [], ui: { entry: "index.html" } } };
@@ -40776,14 +41355,14 @@ async function loadFixtures(dir, explicit) {
40776
41355
  }
40777
41356
  async function runHandlerCases(cases, dir, appId, client, roleOf = () => void 0) {
40778
41357
  const code = /* @__PURE__ */ new Map();
40779
- const lib = await readLib(join18(dir, "lib"));
41358
+ const lib = await readLib(join19(dir, "lib"));
40780
41359
  const outcomes = [];
40781
41360
  for (const kase of cases) {
40782
41361
  requirePlainName("handler", kase.handler, "read");
40783
41362
  if (!code.has(kase.handler)) {
40784
41363
  code.set(
40785
41364
  kase.handler,
40786
- await readFile13(join18(dir, "handlers", `${kase.handler}.py`), "utf8").catch(() => null)
41365
+ await readFile14(join19(dir, "handlers", `${kase.handler}.py`), "utf8").catch(() => null)
40787
41366
  );
40788
41367
  }
40789
41368
  const source = code.get(kase.handler);
@@ -41038,7 +41617,7 @@ function contractUid(contract, page, component) {
41038
41617
  }
41039
41618
  async function isDashboardFolder2(dir) {
41040
41619
  try {
41041
- const doc = JSON.parse(await readFile13(join18(dir, "contract.json"), "utf8"));
41620
+ const doc = JSON.parse(await readFile14(join19(dir, "contract.json"), "utf8"));
41042
41621
  return doc.app?.kind === "dashboard";
41043
41622
  } catch {
41044
41623
  return false;
@@ -41239,7 +41818,7 @@ function mergeDomComponents(contract, components, page) {
41239
41818
  async function writeMergedContract(dir, page, components) {
41240
41819
  let contract;
41241
41820
  try {
41242
- contract = JSON.parse(await readFile13(contractPath(dir), "utf8"));
41821
+ contract = JSON.parse(await readFile14(contractPath(dir), "utf8"));
41243
41822
  } catch {
41244
41823
  contract = await extractContract(dir);
41245
41824
  }
@@ -41249,7 +41828,7 @@ async function writeMergedContract(dir, page, components) {
41249
41828
  async function uiIsStale(dir, entry, stored) {
41250
41829
  if (stored === void 0) return false;
41251
41830
  try {
41252
- const local = await readFile13(join18(dir, "ui", entry));
41831
+ const local = await readFile14(join19(dir, "ui", entry));
41253
41832
  return !local.equals(Buffer.from(stored, "utf8"));
41254
41833
  } catch {
41255
41834
  return false;
@@ -41337,7 +41916,7 @@ function untouchedHandlers(declared, cases, interactions, runs = []) {
41337
41916
  async function readSeed(dir) {
41338
41917
  let parsed2;
41339
41918
  try {
41340
- parsed2 = JSON.parse(await readFile13(join18(dir, "seed.json"), "utf8"));
41919
+ parsed2 = JSON.parse(await readFile14(join19(dir, "seed.json"), "utf8"));
41341
41920
  } catch {
41342
41921
  return null;
41343
41922
  }
@@ -41353,7 +41932,7 @@ async function readSeed(dir) {
41353
41932
  }
41354
41933
  async function handlerOwnership(dir, pushed) {
41355
41934
  try {
41356
- const local = JSON.parse(await readFile13(join18(dir, "contract.json"), "utf8"));
41935
+ const local = JSON.parse(await readFile14(join19(dir, "contract.json"), "utf8"));
41357
41936
  const owned = ownershipOf(local);
41358
41937
  if (owned !== null) return owned;
41359
41938
  } catch {
@@ -41681,7 +42260,7 @@ function registerTestCommand(parent) {
41681
42260
  const files = pushedPages ? store.bundle : await readLocalUi(dir);
41682
42261
  const pages = pushedPages ? store.pages : orderPages(Object.keys(files));
41683
42262
  const manifest = pushedPages && typeof store.manifest === "object" && store.manifest !== null ? store.manifest : await readLocalManifest(dir);
41684
- const outDir = resolve16(opts.out ?? join18(dir, ".screenshots"));
42263
+ const outDir = resolve16(opts.out ?? join19(dir, ".screenshots"));
41685
42264
  const index = await runScreenshots({
41686
42265
  appId,
41687
42266
  pages: choosePages(opts.pages, pages, fixtures.ui.entry).load,
@@ -41800,12 +42379,12 @@ ${String(failed)} failure(s).
41800
42379
  }
41801
42380
 
41802
42381
  // src/commands/appspace/try.ts
41803
- import { readFile as readFile14 } from "fs/promises";
41804
- import { join as join19 } from "path";
42382
+ import { readFile as readFile15 } from "fs/promises";
42383
+ import { join as join20 } from "path";
41805
42384
  function collect2(value, previous = []) {
41806
42385
  return [...previous, value];
41807
42386
  }
41808
- async function readPayloadOption(raw, read = (path3) => readFile14(path3, "utf8")) {
42387
+ async function readPayloadOption(raw, read = (path3) => readFile15(path3, "utf8")) {
41809
42388
  if (raw.startsWith("@")) {
41810
42389
  const path3 = raw.slice(1);
41811
42390
  if (path3 === "") throw new Error("--payload @ names no file; write --payload @./payload.json.");
@@ -41885,15 +42464,15 @@ function registerTryCommand(parent) {
41885
42464
  ).action(async (handler, opts) => {
41886
42465
  requirePlainName("handler", handler, "read");
41887
42466
  const appId = await readManifestId(opts.dir);
41888
- const code = await readFile14(
41889
- join19(opts.dir, "handlers", `${handler}.py`),
42467
+ const code = await readFile15(
42468
+ join20(opts.dir, "handlers", `${handler}.py`),
41890
42469
  "utf8"
41891
42470
  ).catch(() => {
41892
42471
  throw new Error(
41893
42472
  `no handlers/${handler}.py in ${opts.dir} \u2014 is this an app folder?`
41894
42473
  );
41895
42474
  });
41896
- const lib = await readLib(join19(opts.dir, "lib"));
42475
+ const lib = await readLib(join20(opts.dir, "lib"));
41897
42476
  let payload = await readPayloadOption(opts.payload ?? "{}");
41898
42477
  const files = parseFileSpecs(opts.file ?? []);
41899
42478
  const withFiles = payloadForFiles(payload, files);
@@ -42011,8 +42590,8 @@ function registerPublishCommands(parent) {
42011
42590
  }
42012
42591
 
42013
42592
  // src/commands/appspace/scaffold.ts
42014
- import { mkdir as mkdir9, readdir as readdir4, stat as stat3, writeFile as writeFile10 } from "fs/promises";
42015
- import { dirname as dirname9, join as join20 } from "path";
42593
+ import { mkdir as mkdir9, readdir as readdir4, stat as stat3, writeFile as writeFile11 } from "fs/promises";
42594
+ import { dirname as dirname10, join as join21 } from "path";
42016
42595
 
42017
42596
  // src/commands/appspace/starters.ts
42018
42597
  var STARTER_KINDS = ["dashboard", "app"];
@@ -42369,7 +42948,7 @@ async function existingFiles(dir, relPaths) {
42369
42948
  const present3 = [];
42370
42949
  for (const rel of relPaths) {
42371
42950
  try {
42372
- await stat3(join20(dir, rel));
42951
+ await stat3(join21(dir, rel));
42373
42952
  present3.push(rel);
42374
42953
  } catch {
42375
42954
  }
@@ -42408,13 +42987,13 @@ function registerScaffoldCommand(parent) {
42408
42987
  const table = ownsData ? (opts.table ?? DEFAULT_TABLE).trim() : void 0;
42409
42988
  const record2 = ownsData ? ((opts.record ?? "").trim() || singularize(table ?? DEFAULT_TABLE)).trim() : void 0;
42410
42989
  checkNames({ id, table, record: record2 });
42411
- const dir = (dirArg ?? "").trim() || join20(".", id);
42990
+ const dir = (dirArg ?? "").trim() || join21(".", id);
42412
42991
  await checkTarget(dir, opts.force === true);
42413
42992
  const contract = starterContract(kind, { id, name, table, record: record2 });
42414
42993
  const overwritten = opts.force === true ? await existingFiles(dir, [CONTRACT_FILE]) : [];
42415
- const target = join20(dir, CONTRACT_FILE);
42416
- await mkdir9(dirname9(target), { recursive: true });
42417
- await writeFile10(target, `${JSON.stringify(contract, null, 2)}
42994
+ const target = join21(dir, CONTRACT_FILE);
42995
+ await mkdir9(dirname10(target), { recursive: true });
42996
+ await writeFile11(target, `${JSON.stringify(contract, null, 2)}
42418
42997
  `);
42419
42998
  if (opts.json === true) {
42420
42999
  printJson({ id, name, dir, kind, table, record: record2, files: [CONTRACT_FILE], overwritten });
@@ -42656,6 +43235,7 @@ function registerAppSpaceCommand(root) {
42656
43235
  registerCompileCommand(cmd);
42657
43236
  registerShipCommand(cmd);
42658
43237
  registerEjectCommand(cmd);
43238
+ registerMigrateCommand(cmd);
42659
43239
  registerPublishCommands(cmd);
42660
43240
  registerSecretsCommand(cmd);
42661
43241
  }