@multiplatform.one/cli 5.0.27 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,573 +1,837 @@
1
- // src/bin/multiplatformOne.ts
2
- import fsSync from "node:fs";
1
+ import { generateVscodeConfig } from "../generateVscode.mjs";
2
+ import { discoverE2EApp, runE2ESession } from "../commands/e2e.mjs";
3
+ import { init, runModifyStep } from "../commands/init.mjs";
4
+ import { createRequire } from "node:module";
3
5
  import fs from "node:fs/promises";
4
- import os from "node:os";
5
6
  import path from "node:path";
7
+ import fsSync from "node:fs";
6
8
  import { fileURLToPath } from "node:url";
7
- import {
8
- formatServiceList,
9
- lookupProjectRoot,
10
- waitForApi,
11
- waitForFrappe,
12
- waitForKeycloak,
13
- waitForPostgres,
14
- waitServices
15
- } from "@multiplatform.one/utils/dev";
16
- import { program } from "commander";
17
- import dotenv from "dotenv";
18
- import { execa } from "execa";
19
- import inquirer from "inquirer";
20
- import ora from "ora";
21
- var projectRoot = lookupProjectRoot();
22
- var availableServices = ["api", "frappe", "solana", "ethereum", "sui"];
23
- var defaultDotenvPath = path.resolve(projectRoot, ".env");
24
- var availablePlatforms = [
25
- "electron",
26
- "expo",
27
- "keycloak",
28
- "one",
29
- "storybook",
30
- "storybook-expo",
31
- "vocs",
32
- "vscode",
33
- "webext"
9
+ import { formatServiceList, lookupProjectRoot, waitForFrappe, waitForKeycloak, waitForPostgres, waitServices } from "@multiplatform.one/utils/dev";
10
+ import { Command } from "commander";
11
+ import spawn from "nano-spawn";
12
+ import YAML from "yaml";
13
+ import yoctoSpinner from "yocto-spinner";
14
+
15
+ //#region \0rolldown/runtime.js
16
+ var __create = Object.create;
17
+ var __defProp = Object.defineProperty;
18
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
19
+ var __getOwnPropNames = Object.getOwnPropertyNames;
20
+ var __getProtoOf = Object.getPrototypeOf;
21
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
22
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
26
+ key = keys[i];
27
+ if (!__hasOwnProp.call(to, key) && key !== except) {
28
+ __defProp(to, key, {
29
+ get: ((k) => from[k]).bind(null, key),
30
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
31
+ });
32
+ }
33
+ }
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
38
+ value: mod,
39
+ enumerable: true
40
+ }) : target, mod));
41
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
42
+
43
+ //#endregion
44
+ //#region ../../node_modules/dotenv/lib/main.js
45
+ var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
46
+ const fs$1 = __require("fs");
47
+ const path$1 = __require("path");
48
+ const os = __require("os");
49
+ const crypto = __require("crypto");
50
+ const TIPS = [
51
+ "◈ encrypted .env [www.dotenvx.com]",
52
+ "◈ secrets for agents [www.dotenvx.com]",
53
+ "⌁ auth for agents [www.vestauth.com]",
54
+ "⌘ custom filepath { path: '/custom/path/.env' }",
55
+ "⌘ enable debugging { debug: true }",
56
+ "⌘ override existing { override: true }",
57
+ "⌘ suppress logs { quiet: true }",
58
+ "⌘ multiple files { path: ['.env.local', '.env'] }"
59
+ ];
60
+ function _getRandomTip() {
61
+ return TIPS[Math.floor(Math.random() * TIPS.length)];
62
+ }
63
+ function parseBoolean(value) {
64
+ if (typeof value === "string") return ![
65
+ "false",
66
+ "0",
67
+ "no",
68
+ "off",
69
+ ""
70
+ ].includes(value.toLowerCase());
71
+ return Boolean(value);
72
+ }
73
+ function supportsAnsi() {
74
+ return process.stdout.isTTY;
75
+ }
76
+ function dim(text) {
77
+ return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
78
+ }
79
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
80
+ function parse(src) {
81
+ const obj = {};
82
+ let lines = src.toString();
83
+ lines = lines.replace(/\r\n?/gm, "\n");
84
+ let match;
85
+ while ((match = LINE.exec(lines)) != null) {
86
+ const key = match[1];
87
+ let value = match[2] || "";
88
+ value = value.trim();
89
+ const maybeQuote = value[0];
90
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
91
+ if (maybeQuote === "\"") {
92
+ value = value.replace(/\\n/g, "\n");
93
+ value = value.replace(/\\r/g, "\r");
94
+ }
95
+ obj[key] = value;
96
+ }
97
+ return obj;
98
+ }
99
+ function _parseVault(options) {
100
+ options = options || {};
101
+ const vaultPath = _vaultPath(options);
102
+ options.path = vaultPath;
103
+ const result = DotenvModule.configDotenv(options);
104
+ if (!result.parsed) {
105
+ const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
106
+ err.code = "MISSING_DATA";
107
+ throw err;
108
+ }
109
+ const keys = _dotenvKey(options).split(",");
110
+ const length = keys.length;
111
+ let decrypted;
112
+ for (let i = 0; i < length; i++) try {
113
+ const attrs = _instructions(result, keys[i].trim());
114
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
115
+ break;
116
+ } catch (error) {
117
+ if (i + 1 >= length) throw error;
118
+ }
119
+ return DotenvModule.parse(decrypted);
120
+ }
121
+ function _warn(message) {
122
+ console.error(`⚠ ${message}`);
123
+ }
124
+ function _debug(message) {
125
+ console.log(`┆ ${message}`);
126
+ }
127
+ function _log(message) {
128
+ console.log(`◇ ${message}`);
129
+ }
130
+ function _dotenvKey(options) {
131
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
132
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
133
+ return "";
134
+ }
135
+ function _instructions(result, dotenvKey) {
136
+ let uri;
137
+ try {
138
+ uri = new URL(dotenvKey);
139
+ } catch (error) {
140
+ if (error.code === "ERR_INVALID_URL") {
141
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
142
+ err.code = "INVALID_DOTENV_KEY";
143
+ throw err;
144
+ }
145
+ throw error;
146
+ }
147
+ const key = uri.password;
148
+ if (!key) {
149
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
150
+ err.code = "INVALID_DOTENV_KEY";
151
+ throw err;
152
+ }
153
+ const environment = uri.searchParams.get("environment");
154
+ if (!environment) {
155
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
156
+ err.code = "INVALID_DOTENV_KEY";
157
+ throw err;
158
+ }
159
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
160
+ const ciphertext = result.parsed[environmentKey];
161
+ if (!ciphertext) {
162
+ const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
163
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
164
+ throw err;
165
+ }
166
+ return {
167
+ ciphertext,
168
+ key
169
+ };
170
+ }
171
+ function _vaultPath(options) {
172
+ let possibleVaultPath = null;
173
+ if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
174
+ for (const filepath of options.path) if (fs$1.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
175
+ } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
176
+ else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault");
177
+ if (fs$1.existsSync(possibleVaultPath)) return possibleVaultPath;
178
+ return null;
179
+ }
180
+ function _resolveHome(envPath) {
181
+ return envPath[0] === "~" ? path$1.join(os.homedir(), envPath.slice(1)) : envPath;
182
+ }
183
+ function _configVault(options) {
184
+ const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
185
+ const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
186
+ if (debug || !quiet) _log("loading env from encrypted .env.vault");
187
+ const parsed = DotenvModule._parseVault(options);
188
+ let processEnv = process.env;
189
+ if (options && options.processEnv != null) processEnv = options.processEnv;
190
+ DotenvModule.populate(processEnv, parsed, options);
191
+ return { parsed };
192
+ }
193
+ function configDotenv(options) {
194
+ const dotenvPath = path$1.resolve(process.cwd(), ".env");
195
+ let encoding = "utf8";
196
+ let processEnv = process.env;
197
+ if (options && options.processEnv != null) processEnv = options.processEnv;
198
+ let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
199
+ let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
200
+ if (options && options.encoding) encoding = options.encoding;
201
+ else if (debug) _debug("no encoding is specified (UTF-8 is used by default)");
202
+ let optionPaths = [dotenvPath];
203
+ if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
204
+ else {
205
+ optionPaths = [];
206
+ for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
207
+ }
208
+ let lastError;
209
+ const parsedAll = {};
210
+ for (const path of optionPaths) try {
211
+ const parsed = DotenvModule.parse(fs$1.readFileSync(path, { encoding }));
212
+ DotenvModule.populate(parsedAll, parsed, options);
213
+ } catch (e) {
214
+ if (debug) _debug(`failed to load ${path} ${e.message}`);
215
+ lastError = e;
216
+ }
217
+ const populated = DotenvModule.populate(processEnv, parsedAll, options);
218
+ debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
219
+ quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
220
+ if (debug || !quiet) {
221
+ const keysCount = Object.keys(populated).length;
222
+ const shortPaths = [];
223
+ for (const filePath of optionPaths) try {
224
+ const relative = path$1.relative(process.cwd(), filePath);
225
+ shortPaths.push(relative);
226
+ } catch (e) {
227
+ if (debug) _debug(`failed to load ${filePath} ${e.message}`);
228
+ lastError = e;
229
+ }
230
+ _log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`);
231
+ }
232
+ if (lastError) return {
233
+ parsed: parsedAll,
234
+ error: lastError
235
+ };
236
+ else return { parsed: parsedAll };
237
+ }
238
+ function config(options) {
239
+ if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
240
+ const vaultPath = _vaultPath(options);
241
+ if (!vaultPath) {
242
+ _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`);
243
+ return DotenvModule.configDotenv(options);
244
+ }
245
+ return DotenvModule._configVault(options);
246
+ }
247
+ function decrypt(encrypted, keyStr) {
248
+ const key = Buffer.from(keyStr.slice(-64), "hex");
249
+ let ciphertext = Buffer.from(encrypted, "base64");
250
+ const nonce = ciphertext.subarray(0, 12);
251
+ const authTag = ciphertext.subarray(-16);
252
+ ciphertext = ciphertext.subarray(12, -16);
253
+ try {
254
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
255
+ aesgcm.setAuthTag(authTag);
256
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
257
+ } catch (error) {
258
+ const isRange = error instanceof RangeError;
259
+ const invalidKeyLength = error.message === "Invalid key length";
260
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
261
+ if (isRange || invalidKeyLength) {
262
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
263
+ err.code = "INVALID_DOTENV_KEY";
264
+ throw err;
265
+ } else if (decryptionFailed) {
266
+ const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
267
+ err.code = "DECRYPTION_FAILED";
268
+ throw err;
269
+ } else throw error;
270
+ }
271
+ }
272
+ function populate(processEnv, parsed, options = {}) {
273
+ const debug = Boolean(options && options.debug);
274
+ const override = Boolean(options && options.override);
275
+ const populated = {};
276
+ if (typeof parsed !== "object") {
277
+ const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
278
+ err.code = "OBJECT_REQUIRED";
279
+ throw err;
280
+ }
281
+ for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
282
+ if (override === true) {
283
+ processEnv[key] = parsed[key];
284
+ populated[key] = parsed[key];
285
+ }
286
+ if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
287
+ else _debug(`"${key}" is already defined and was NOT overwritten`);
288
+ } else {
289
+ processEnv[key] = parsed[key];
290
+ populated[key] = parsed[key];
291
+ }
292
+ return populated;
293
+ }
294
+ const DotenvModule = {
295
+ configDotenv,
296
+ _configVault,
297
+ _parseVault,
298
+ config,
299
+ decrypt,
300
+ parse,
301
+ populate
302
+ };
303
+ module.exports.configDotenv = DotenvModule.configDotenv;
304
+ module.exports._configVault = DotenvModule._configVault;
305
+ module.exports._parseVault = DotenvModule._parseVault;
306
+ module.exports.config = DotenvModule.config;
307
+ module.exports.decrypt = DotenvModule.decrypt;
308
+ module.exports.parse = DotenvModule.parse;
309
+ module.exports.populate = DotenvModule.populate;
310
+ module.exports = DotenvModule;
311
+ }));
312
+
313
+ //#endregion
314
+ //#region src/bin/multiplatformOne.ts
315
+ var import_main = /* @__PURE__ */ __toESM(require_main(), 1);
316
+ const projectRoot = lookupProjectRoot();
317
+ const availableServices = [
318
+ "api",
319
+ "frappe",
320
+ "solana",
321
+ "ethereum",
322
+ "sui"
34
323
  ];
35
- process.env.COOKIECUTTER = `sh ${path.resolve(
36
- path.dirname(fileURLToPath(import.meta.url)),
37
- "../../scripts/cookiecutter.sh"
38
- )}`;
39
- program.name("multiplatform.one");
40
- program.version(
41
- JSON.parse(
42
- fsSync.readFileSync(
43
- path.resolve(
44
- path.dirname(fileURLToPath(import.meta.url)),
45
- "../../package.json"
46
- ),
47
- "utf8"
48
- )
49
- )?.version
50
- );
51
- program.command("init").option(
52
- "-r, --remote <remote>",
53
- "the remote to use",
54
- "https://gitlab.com/bitspur/multiplatform.one/cookiecutter"
55
- ).option(
56
- "-c, --checkout <branch>",
57
- "branch, tag or commit to checkout",
58
- "main"
59
- ).option("-p, --platforms <platforms>", "platforms to use").option("-s, --services <services>", "services to use").argument("[name]", "the name of the project", "").description("init multiplatform.one").action(async (name, options) => {
60
- let { services, platforms } = options;
61
- if ((await execa("git", ["rev-parse", "--is-inside-work-tree"], {
62
- reject: false
63
- })).exitCode === 0) {
64
- throw new Error(
65
- "multiplatform.one cannot be initialized inside a git repository"
66
- );
67
- }
68
- if (!name) {
69
- name = (await inquirer.prompt([
70
- {
71
- message: "What is the project name?",
72
- name: "name",
73
- type: "input"
74
- }
75
- ])).name;
76
- }
77
- if (!services) {
78
- const servicesResult = (await inquirer.prompt([
79
- {
80
- message: "What services are you using?",
81
- name: "services",
82
- type: "checkbox",
83
- choices: availableServices.map((name2) => ({ name: name2 }))
84
- }
85
- ])).services;
86
- services = servicesResult.join(",");
87
- }
88
- if (!platforms) {
89
- const platformsResult = (await inquirer.prompt([
90
- {
91
- message: "What platforms are you using?",
92
- name: "platforms",
93
- type: "checkbox",
94
- choices: availablePlatforms.map((name2) => ({ name: name2 }))
95
- }
96
- ])).platforms;
97
- platforms = platformsResult.join(",");
98
- }
99
- const cookieCutterConfig = {
100
- default_context: { name, platforms, services }
101
- };
102
- const cookieCutterConfigFile = path.join(
103
- await fs.mkdtemp(path.join(os.tmpdir(), "multiplatform-")),
104
- "config.json"
105
- );
106
- try {
107
- await fs.writeFile(
108
- cookieCutterConfigFile,
109
- JSON.stringify(cookieCutterConfig, null, 2)
110
- );
111
- await execa(
112
- "sh",
113
- [
114
- path.resolve(
115
- path.dirname(fileURLToPath(import.meta.url)),
116
- "../../scripts/init.sh"
117
- ),
118
- "--no-input",
119
- "-f",
120
- "--config-file",
121
- cookieCutterConfigFile,
122
- "--checkout",
123
- options.checkout,
124
- options.remote
125
- ],
126
- {
127
- stdio: "inherit"
128
- }
129
- );
130
- } finally {
131
- await fs.rm(cookieCutterConfigFile, { recursive: true, force: true });
132
- }
324
+ /** Map a service name to its relative directory from the project root. */
325
+ function serviceDir(name) {
326
+ return `apps/${name}`;
327
+ }
328
+ const defaultDotenvPath = path.resolve(projectRoot, ".env");
329
+ /** Apps that exist under apps/ and have package.json (discovered from filesystem). */
330
+ async function getPresentApps(root) {
331
+ const appsDir = path.join(root, "apps");
332
+ try {
333
+ const entries = await fs.readdir(appsDir, { withFileTypes: true });
334
+ const names = [];
335
+ for (const e of entries) {
336
+ if (!e.isDirectory()) continue;
337
+ const pkgPath = path.join(appsDir, e.name, "package.json");
338
+ try {
339
+ await fs.access(pkgPath);
340
+ names.push(e.name);
341
+ } catch {}
342
+ }
343
+ return names;
344
+ } catch {
345
+ return [];
346
+ }
347
+ }
348
+ /** Root-level services that exist and have package.json (discovered from filesystem). */
349
+ async function getPresentServices(root) {
350
+ const names = [];
351
+ for (const name of availableServices) {
352
+ const dir = path.join(root, serviceDir(name));
353
+ const pkgPath = path.join(dir, "package.json");
354
+ try {
355
+ if (!(await fs.stat(dir)).isDirectory()) continue;
356
+ await fs.access(pkgPath);
357
+ names.push(name);
358
+ } catch {}
359
+ }
360
+ return names;
361
+ }
362
+ /** Turbo --filter args to exclude root-level workspaces that are not present (so turbo only runs where they exist).
363
+ * Only generates exclude filters for directories that exist on disk (turbo errors on non-existent filter paths). */
364
+ async function getTurboExcludeFiltersForMissing(root) {
365
+ const present = await getPresentServices(root);
366
+ const filters = [];
367
+ for (const s of availableServices) {
368
+ if (present.includes(s)) continue;
369
+ const dir = serviceDir(s);
370
+ try {
371
+ if ((await fs.stat(path.join(root, dir))).isDirectory()) filters.push(`!./${dir}`);
372
+ } catch {}
373
+ }
374
+ return filters;
375
+ }
376
+ async function getStorybookVisualWorkspaces(root) {
377
+ const out = [];
378
+ const searchDirs = [{
379
+ base: path.join(root, "apps"),
380
+ prefix: "apps/"
381
+ }, {
382
+ base: path.join(root, "packages"),
383
+ prefix: "packages/"
384
+ }];
385
+ for (const { base, prefix: _prefix } of searchDirs) {
386
+ let entries;
387
+ try {
388
+ entries = (await fs.readdir(base, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => ({ name: e.name }));
389
+ } catch {
390
+ continue;
391
+ }
392
+ for (const { name } of entries) {
393
+ const dirPath = path.join(base, name);
394
+ const storybookDir = path.join(dirPath, ".storybook");
395
+ try {
396
+ if (!(await fs.stat(storybookDir)).isDirectory()) continue;
397
+ } catch {
398
+ continue;
399
+ }
400
+ const pkgPath = path.join(dirPath, "package.json");
401
+ let pkg = null;
402
+ try {
403
+ pkg = JSON.parse(await fs.readFile(pkgPath, "utf8"));
404
+ } catch {}
405
+ const hasLostPixel = pkg && (pkg.dependencies?.["lost-pixel"] || pkg.devDependencies?.["lost-pixel"]);
406
+ const scripts = pkg?.scripts ?? {};
407
+ const testVisualScript = scripts["test:visual"] ?? scripts["test/visual"] ?? scripts["test:visual:ci"];
408
+ const makefilePath = path.join(dirPath, "Makefile");
409
+ let makefileHasTestVisual = false;
410
+ try {
411
+ const makefile = await fs.readFile(makefilePath, "utf8");
412
+ makefileHasTestVisual = /test\/visual[\s:]/.test(makefile);
413
+ } catch {}
414
+ if (makefileHasTestVisual) out.push({
415
+ dirName: name,
416
+ absolutePath: dirPath,
417
+ runVisual: "make"
418
+ });
419
+ else if (testVisualScript) {
420
+ const scriptName = scripts["test:visual"] ? "test:visual" : scripts["test/visual"] ? "test/visual" : "test:visual:ci";
421
+ out.push({
422
+ dirName: name,
423
+ absolutePath: dirPath,
424
+ runVisual: "pnpm",
425
+ pnpmScript: scriptName
426
+ });
427
+ } else if (hasLostPixel) out.push({
428
+ dirName: name,
429
+ absolutePath: dirPath,
430
+ runVisual: "pnpm",
431
+ pnpmScript: void 0,
432
+ runLostPixelAfterBuild: true
433
+ });
434
+ }
435
+ }
436
+ return out;
437
+ }
438
+ /** Discover frappe apps from frappe.yaml that have local source paths.
439
+ * Supports both string entries (`- ./apps/core`) and object entries (`- name: core\n source: ./apps/core`). */
440
+ async function getFrappeApps(root) {
441
+ const frappeDir = path.join(root, "apps", "frappe");
442
+ const frappeYamlPath = path.join(frappeDir, "frappe.yaml");
443
+ if (!fsSync.existsSync(frappeYamlPath)) return [];
444
+ const raw = await fs.readFile(frappeYamlPath, "utf8");
445
+ const config = YAML.parse(raw);
446
+ const out = [];
447
+ for (const app of config?.apps ?? []) {
448
+ let src;
449
+ let name;
450
+ if (typeof app === "string") {
451
+ src = app;
452
+ name = path.basename(app);
453
+ } else {
454
+ if (!app.source || !app.name) continue;
455
+ src = app.source;
456
+ name = app.name;
457
+ }
458
+ src = src.startsWith("file://") ? src.slice(7) : src;
459
+ if (!src.startsWith("./") && !src.startsWith("../") && !src.startsWith("/")) continue;
460
+ const absPath = path.isAbsolute(src) ? src : path.resolve(frappeDir, src);
461
+ if (!fsSync.existsSync(absPath)) continue;
462
+ out.push({
463
+ name,
464
+ absolutePath: absPath
465
+ });
466
+ }
467
+ return out;
468
+ }
469
+ const program = new Command();
470
+ program.name("mpo");
471
+ program.version(JSON.parse(fsSync.readFileSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json"), "utf8"))?.version);
472
+ program.command("init").option("-c, --checkout <branch>", "branch, tag or commit to checkout", "main").option("-a, --apps <apps>", "comma-separated apps to include").option("-s, --services <services>", "comma-separated services to include").argument("[name]", "the name of the project").description("clone multiplatform.one and apply selected apps/services").action(async (name, options) => {
473
+ if (await spawn("git", ["rev-parse", "--is-inside-work-tree"]).then(() => true, () => false)) throw new Error("mpo cannot be initialized inside a git repository");
474
+ const cloneScript = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../scripts/clone.sh");
475
+ await init(name, {
476
+ ...options,
477
+ cloneScript
478
+ });
479
+ });
480
+ program.command("update").option("-c, --checkout <branch>", "branch, tag or commit to merge from upstream", "main").option("-r, --remote <url>", "upstream remote URL", "https://gitlab.com/bitspur/multiplatform.one/multiplatform.one.git").description("merge upstream and re-apply workspace config").action(async (options) => {
481
+ if (await spawn("git", ["rev-parse", "--is-inside-work-tree"]).then(() => false, () => true)) throw new Error("mpo cannot be updated outside of a git repository");
482
+ if (await spawn("git", [
483
+ "diff",
484
+ "--cached",
485
+ "--quiet"
486
+ ]).then(() => false, () => true)) throw new Error("mpo cannot be updated with uncommitted changes (staged changes present)");
487
+ if (await spawn("git", ["diff", "--quiet"]).then(() => false, () => true)) throw new Error("multiplatform.one cannot be updated with uncommitted changes (unstaged changes present)");
488
+ const rootPkgPath = path.resolve(projectRoot, "package.json");
489
+ const featuresPkgPath = path.resolve(projectRoot, "features/package.json");
490
+ try {
491
+ if (!(await fs.stat(rootPkgPath)).isFile()) throw new Error("mpo update requires a valid project: root package.json not found");
492
+ } catch (err) {
493
+ if (err instanceof Error && err.message.includes("valid project")) throw err;
494
+ throw new Error("mpo update requires a valid project: root package.json not found");
495
+ }
496
+ try {
497
+ if (!(await fs.stat(featuresPkgPath)).isFile()) throw new Error("mpo update requires a valid project: features/package.json not found");
498
+ } catch (err) {
499
+ if (err instanceof Error && err.message.includes("valid project")) throw err;
500
+ throw new Error("mpo update requires a valid project: features/package.json not found");
501
+ }
502
+ const featuresPkg = JSON.parse(await fs.readFile(featuresPkgPath, "utf8"));
503
+ if (!featuresPkg?.dependencies?.["multiplatform.one"] || !String(featuresPkg.dependencies["multiplatform.one"]).length) throw new Error("mpo update requires a valid project: features must depend on multiplatform.one");
504
+ await spawn("sh", [
505
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../scripts/update.sh"),
506
+ options.remote,
507
+ options.checkout
508
+ ], {
509
+ cwd: projectRoot,
510
+ stdio: "inherit",
511
+ shell: true
512
+ });
513
+ runModifyStep(projectRoot, await getPresentServices(projectRoot), await getPresentApps(projectRoot));
514
+ try {
515
+ await generateVscodeConfig(projectRoot);
516
+ } catch {}
517
+ });
518
+ program.command("wait").description("wait for a service to be ready").option("-i, --interval <interval>", "interval to wait for", "1000").option("-t, --timeout <timeout>", "timeout to wait for", "600000").option("-e, --dotenv <dotenv>", "dotenv file path", ".env").argument("<services>", `the services to wait for (${waitServices.join(", ")})`).action(async (servicesString, options) => {
519
+ import_main.default.config({ path: options.dotenv || defaultDotenvPath });
520
+ const interval = Number.parseInt(options.interval);
521
+ const timeout = Number.parseInt(options.timeout);
522
+ const services = servicesString.split(",");
523
+ try {
524
+ await waitWithSpinner(services, {
525
+ interval,
526
+ timeout
527
+ });
528
+ } catch {
529
+ process.exit(1);
530
+ }
531
+ });
532
+ const frappe = program.command("frappe").description("manage frappe development environment").option("-e, --dotenv <dotenv>", "dotenv file path", ".env");
533
+ frappe.command("bootstrap").description("bootstrap frappe development environment").option("-u, --update", "update dependencies").action(async (options) => {
534
+ const parentOptions = frappe.opts();
535
+ import_main.default.config({ path: parentOptions.dotenv || defaultDotenvPath });
536
+ await spawn("sh", [
537
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../scripts/frappe.sh"),
538
+ "bootstrap",
539
+ ...options.update ? ["--update"] : []
540
+ ], {
541
+ stdio: "inherit",
542
+ shell: true,
543
+ cwd: projectRoot
544
+ });
133
545
  });
134
- program.command("update").option(
135
- "-r, --remote <remote>",
136
- "the remote to use",
137
- "https://gitlab.com/bitspur/multiplatform.one/cookiecutter"
138
- ).option(
139
- "-c, --checkout <branch>",
140
- "branch, tag or commit to checkout",
141
- "main"
142
- ).option("-p, --platforms <platforms>", "platforms to keep").option("-s, --services <services>", "services to keep").option("--no-prompt", "do not prompt for services and platforms").description("update multiplatform.one").action(
143
- async (options) => {
144
- let platforms = [];
145
- let services = [];
146
- if (!options.platforms) {
147
- platforms = (await fs.readdir(path.join(projectRoot, "platforms"), {
148
- withFileTypes: true
149
- })).filter((d) => d.isDirectory()).map((d) => d.name).filter((name) => availablePlatforms.includes(name));
150
- }
151
- if (!options.services) {
152
- services = (await fs.readdir(projectRoot, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).filter((name) => availableServices.includes(name));
153
- }
154
- if (!options.noPrompt) {
155
- const servicesResult = await inquirer.prompt([
156
- {
157
- message: "What services are you using?",
158
- name: "services",
159
- type: "checkbox",
160
- choices: availableServices.map((name) => ({
161
- name,
162
- checked: services.includes(name)
163
- }))
164
- }
165
- ]);
166
- services = servicesResult.services;
167
- const platformsResult = await inquirer.prompt([
168
- {
169
- message: "What platforms are you using?",
170
- name: "platforms",
171
- type: "checkbox",
172
- choices: availablePlatforms.map((name) => ({
173
- name,
174
- checked: platforms.includes(name)
175
- }))
176
- }
177
- ]);
178
- platforms = platformsResult.platforms;
179
- }
180
- if ((await execa("git", ["rev-parse", "--is-inside-work-tree"], {
181
- reject: false
182
- })).exitCode !== 0) {
183
- throw new Error(
184
- "multiplatform.one cannot be updated outside of a git repository"
185
- );
186
- }
187
- if ((await execa("git", ["diff", "--cached", "--quiet"], {
188
- reject: false
189
- })).exitCode !== 0) {
190
- throw new Error(
191
- "multiplatform.one cannot be updated with uncommitted changes"
192
- );
193
- }
194
- let cookieCutterConfig;
195
- if ((await fs.stat(path.resolve(projectRoot, "package.json"))).isFile() && (await fs.stat(path.resolve(projectRoot, "app/package.json"))).isFile() && JSON.parse(
196
- await fs.readFile(
197
- path.resolve(projectRoot, "app/package.json"),
198
- "utf8"
199
- )
200
- )?.dependencies?.["multiplatform.one"]?.length) {
201
- const name = JSON.parse(
202
- await fs.readFile(path.resolve(projectRoot, "package.json"), "utf8")
203
- )?.name;
204
- if (name) {
205
- cookieCutterConfig = {
206
- default_context: {
207
- name,
208
- platforms: platforms.join(","),
209
- services: services.join(",")
210
- }
211
- };
212
- }
213
- }
214
- if (!cookieCutterConfig) {
215
- throw new Error("not a multiplatform.one project");
216
- }
217
- const cookieCutterConfigFile = path.join(
218
- await fs.mkdtemp(path.join(os.tmpdir(), "multiplatform-")),
219
- "config.json"
220
- );
221
- try {
222
- await fs.writeFile(
223
- cookieCutterConfigFile,
224
- JSON.stringify(cookieCutterConfig, null, 2)
225
- );
226
- await execa(
227
- "sh",
228
- [
229
- path.resolve(
230
- path.dirname(fileURLToPath(import.meta.url)),
231
- "../../scripts/update.sh"
232
- ),
233
- "--no-input",
234
- "-f",
235
- "--config-file",
236
- cookieCutterConfigFile,
237
- "--checkout",
238
- options.checkout,
239
- options.remote
240
- ],
241
- {
242
- cwd: projectRoot,
243
- stdio: "inherit",
244
- shell: true
245
- }
246
- );
247
- } finally {
248
- await fs.rm(cookieCutterConfigFile, { recursive: true, force: true });
249
- }
250
- }
251
- );
252
- program.command("wait").description("wait for a service to be ready").option("-i, --interval <interval>", "interval to wait for", "1000").option("-t, --timeout <timeout>", "timeout to wait for", "600000").option("-e, --dotenv <dotenv>", "dotenv file path", ".env").argument(
253
- "<services>",
254
- `the services to wait for (${waitServices.join(", ")})`
255
- ).action(async (servicesString, options) => {
256
- dotenv.config({ path: options.dotenv || defaultDotenvPath });
257
- const interval = Number.parseInt(options.interval);
258
- const timeout = Number.parseInt(options.timeout);
259
- const services = servicesString.split(",");
260
- try {
261
- await waitWithSpinner(services, { interval, timeout });
262
- } catch (err) {
263
- process.exit(1);
264
- }
546
+ frappe.command("clean").description("clean frappe bench artifacts").option("--cache", "also remove frappe cache").action(async (options) => {
547
+ await spawn("sh", [
548
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../scripts/frappe.sh"),
549
+ "clean",
550
+ ...options.cache ? ["--cache"] : []
551
+ ], {
552
+ stdio: "inherit",
553
+ shell: true,
554
+ cwd: projectRoot
555
+ });
265
556
  });
266
- program.command("mesh").description("start the mesh server").option("-a, --api", "use api", false).option("-e, --dotenv <dotenv>", "dotenv file path", ".env").option("-f, --frappe", "use frappe", false).option("-i, --interval <interval>", "interval to wait for", "1000").option("-p, --port <port>", "port to run mesh on", "5002").option("-t, --timeout <timeout>", "timeout to wait for", "600000").action(async (options) => {
267
- dotenv.config({ path: options.dotenv || defaultDotenvPath });
268
- process.env.UWS_HTTP_MAX_HEADERS_SIZE = "16384";
269
- if (options.frappe || options.api) {
270
- process.env.MESH_API = options.api ? "1" : "0";
271
- process.env.MESH_FRAPPE = options.frappe ? "1" : "0";
272
- }
273
- if (!await fs.stat(path.resolve(projectRoot, "app/main.ts")).catch(() => false)) {
274
- process.env.MESH_APP = "0";
275
- }
276
- if (!await fs.stat(path.resolve(projectRoot, "frappe/package.json")).catch(() => false)) {
277
- process.env.MESH_FRAPPE = "0";
278
- }
279
- const services = [
280
- ...process.env.MESH_API === "1" ? ["api"] : [],
281
- ...process.env.MESH_FRAPPE === "1" ? ["frappe"] : []
282
- ];
283
- if (services.length > 0) {
284
- const interval = Number.parseInt(options.interval);
285
- const timeout = Number.parseInt(options.timeout);
286
- try {
287
- await waitWithSpinner(services, { interval, timeout });
288
- } catch (err) {
289
- process.exit(1);
290
- }
291
- }
292
- await execa(
293
- "mesh",
294
- [
295
- "dev",
296
- "--port",
297
- Number(options.port || process.env.MESH_PORT || 5002).toString()
298
- ],
299
- {
300
- stdio: "inherit"
301
- }
302
- );
557
+ frappe.command("dev").description("start frappe development server").action(async () => {
558
+ const parentOptions = frappe.opts();
559
+ import_main.default.config({ path: parentOptions.dotenv || defaultDotenvPath });
560
+ await spawn("sh", [path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../scripts/frappe.sh"), "dev"], {
561
+ stdio: "inherit",
562
+ shell: true,
563
+ cwd: projectRoot
564
+ });
303
565
  });
304
- program.command("build").argument(
305
- "[args...]",
306
- `build to run: ${[...availableServices, "packages"].join(", ")} (default: all)`
307
- ).description("run build command").action(async (args) => {
308
- args = args.flatMap((arg) => arg.split(","));
309
- const packages = args.includes("packages");
310
- const projects = args.filter((arg) => arg !== "packages");
311
- if (!projects.length && !packages || packages) {
312
- await execa(
313
- "pnpm",
314
- [
315
- "turbo",
316
- "run",
317
- "build",
318
- "--filter",
319
- "'!./platforms/*'",
320
- "--filter",
321
- "'!./api'",
322
- "--filter",
323
- "'!./solana'",
324
- "--filter",
325
- "'!./ethereum'",
326
- "--filter",
327
- "'!./sui'"
328
- ],
329
- {
330
- stdio: "inherit",
331
- shell: true,
332
- cwd: projectRoot
333
- }
334
- );
335
- }
336
- for (const platform of await fs.readdir("platforms")) {
337
- if ((!projects.length && !packages || projects.includes(platform)) && await fs.access(path.join(projectRoot, "platforms", platform, "package.json")).then(
338
- () => JSON.parse(
339
- fsSync.readFileSync(
340
- path.join(projectRoot, "platforms", platform, "package.json"),
341
- "utf8"
342
- )
343
- ).scripts?.build
344
- ).catch(() => false)) {
345
- await execa("./mkpm", [`${platform}/build`], {
346
- stdio: "inherit",
347
- shell: true,
348
- cwd: projectRoot
349
- });
350
- }
351
- }
352
- for (const service of availableServices) {
353
- if ((!projects.length && !packages || projects.includes(service)) && await fs.access(path.join(projectRoot, service, "package.json")).then(
354
- () => JSON.parse(
355
- fsSync.readFileSync(
356
- path.join(projectRoot, service, "package.json"),
357
- "utf8"
358
- )
359
- ).scripts?.build
360
- ).catch(() => false)) {
361
- await execa("./mkpm", [`${service}/build`], {
362
- stdio: "inherit",
363
- shell: true,
364
- cwd: projectRoot
365
- });
366
- }
367
- }
566
+ frappe.command("bench").description("run bench command").action(async () => {
567
+ const parentOptions = frappe.opts();
568
+ import_main.default.config({ path: parentOptions.dotenv || defaultDotenvPath });
569
+ await spawn("sh", [path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../scripts/frappe.sh"), "bench"], {
570
+ stdio: "inherit",
571
+ shell: true,
572
+ cwd: projectRoot
573
+ });
368
574
  });
369
- program.command("test").argument(
370
- "[args...]",
371
- `test to run: ${[...availableServices, "packages"].join(", ")} (default: all)`
372
- ).description("run test command").action(async (args) => {
373
- args = args.flatMap((arg) => arg.split(","));
374
- const packages = args.includes("packages");
375
- const projects = args.filter((arg) => arg !== "packages");
376
- if (!projects.length && !packages || packages) {
377
- await execa(
378
- "pnpm",
379
- [
380
- "turbo",
381
- "run",
382
- "test",
383
- "--filter",
384
- "'!./platforms/*'",
385
- "--filter",
386
- "'!./api'",
387
- "--filter",
388
- "'!./solana'",
389
- "--filter",
390
- "'!./ethereum'",
391
- "--filter",
392
- "'!./sui'"
393
- ],
394
- {
395
- stdio: "inherit",
396
- shell: true,
397
- cwd: projectRoot
398
- }
399
- );
400
- }
401
- for (const platform of await fs.readdir("platforms")) {
402
- if ((!projects.length && !packages || projects.includes(platform)) && await fs.access(path.join(projectRoot, "platforms", platform, "package.json")).then(
403
- () => JSON.parse(
404
- fsSync.readFileSync(
405
- path.join(projectRoot, "platforms", platform, "package.json"),
406
- "utf8"
407
- )
408
- ).scripts?.test
409
- ).catch(() => false)) {
410
- await execa("./mkpm", [`${platform}/test`], {
411
- stdio: "inherit",
412
- shell: true,
413
- cwd: projectRoot
414
- });
415
- }
416
- }
417
- for (const service of availableServices) {
418
- if ((!projects.length && !packages || projects.includes(service)) && await fs.access(path.join(projectRoot, service, "package.json")).then(
419
- () => JSON.parse(
420
- fsSync.readFileSync(
421
- path.join(projectRoot, service, "package.json"),
422
- "utf8"
423
- )
424
- ).scripts?.test
425
- ).catch(() => false)) {
426
- await execa("./mkpm", [`${service}/test`], {
427
- stdio: "inherit",
428
- shell: true,
429
- cwd: projectRoot
430
- });
431
- }
432
- }
575
+ program.command("build").argument("[args...]", `build to run: ${[...availableServices, "packages"].join(", ")} (default: all)`).description("run build command").action(async (args) => {
576
+ const parsed = args.flatMap((arg) => arg.split(","));
577
+ const packages = parsed.includes("packages");
578
+ const projects = parsed.filter((arg) => arg !== "packages");
579
+ const presentApps = await getPresentApps(projectRoot);
580
+ const presentServices = await getPresentServices(projectRoot);
581
+ if (!projects.length && !packages || packages) await spawn("pnpm", [
582
+ "turbo",
583
+ "run",
584
+ "build",
585
+ "--filter",
586
+ "'!./apps/*'",
587
+ ...presentServices.flatMap((s) => ["--filter", `'!./${serviceDir(s)}'`])
588
+ ], {
589
+ stdio: "inherit",
590
+ shell: true,
591
+ cwd: projectRoot
592
+ });
593
+ for (const platform of presentApps) if (!projects.length && !packages || projects.includes(platform)) {
594
+ if (await fs.access(path.join(projectRoot, "apps", platform, "package.json")).then(() => JSON.parse(fsSync.readFileSync(path.join(projectRoot, "apps", platform, "package.json"), "utf8")).scripts?.build).catch(() => false)) await spawn("pnpm", [
595
+ "turbo",
596
+ "run",
597
+ "build",
598
+ `--filter=./apps/${platform}`
599
+ ], {
600
+ stdio: "inherit",
601
+ shell: true,
602
+ cwd: projectRoot
603
+ });
604
+ }
605
+ for (const service of presentServices) if (!projects.length && !packages || projects.includes(service)) {
606
+ const dir = serviceDir(service);
607
+ if (await fs.access(path.join(projectRoot, dir, "package.json")).then(() => JSON.parse(fsSync.readFileSync(path.join(projectRoot, dir, "package.json"), "utf8")).scripts?.build).catch(() => false)) await spawn("pnpm", [
608
+ "turbo",
609
+ "run",
610
+ "build",
611
+ `--filter=./${dir}`
612
+ ], {
613
+ stdio: "inherit",
614
+ shell: true,
615
+ cwd: projectRoot
616
+ });
617
+ }
618
+ });
619
+ program.command("test").argument("[args...]", "test to run: unit, integration, e2e, visual (default: unit)").option("--up-only", "start E2E environment and exit (for agent/manual testing)").option("--down", "tear down E2E test environment").option("--port-offset <number>", "port offset from defaults", "1000").option("--project <name>", "Docker project name for E2E").option("--no-build", "skip image builds for E2E").option("--filter <pattern>", "run specific Playwright test files").description("run test command").action(async (args, options) => {
620
+ const parsed = args.flatMap((arg) => arg.split(","));
621
+ if (parsed.includes("unit")) {
622
+ const excludeFilters = await getTurboExcludeFiltersForMissing(projectRoot);
623
+ const e2eApp = await discoverE2EApp(projectRoot);
624
+ await spawn("pnpm", [
625
+ "turbo",
626
+ "run",
627
+ "test",
628
+ ...[...excludeFilters.flatMap((f) => ["--filter", f]), ...e2eApp ? ["--filter", `'!./apps/${e2eApp}'`] : []]
629
+ ], {
630
+ stdio: "inherit",
631
+ shell: true,
632
+ cwd: projectRoot
633
+ });
634
+ const frappeApps = await getFrappeApps(projectRoot);
635
+ for (const app of frappeApps) if (await fs.access(path.join(app.absolutePath, "pyproject.toml")).then(() => true).catch(() => false)) try {
636
+ await spawn("bench", [
637
+ "run-tests",
638
+ "--app",
639
+ app.name,
640
+ "--",
641
+ "-m",
642
+ "not integration"
643
+ ], {
644
+ stdio: "inherit",
645
+ cwd: path.join(projectRoot, "apps", "frappe")
646
+ });
647
+ } catch {
648
+ console.warn(`frappe app ${app.name} unit tests failed (bench may not be available)`);
649
+ }
650
+ if (parsed.length === 1) return;
651
+ }
652
+ if (parsed.includes("integration")) {
653
+ const excludeFilters = await getTurboExcludeFiltersForMissing(projectRoot);
654
+ const e2eApp = await discoverE2EApp(projectRoot);
655
+ await spawn("pnpm", [
656
+ "turbo",
657
+ "run",
658
+ "test",
659
+ ...[...excludeFilters.flatMap((f) => ["--filter", f]), ...e2eApp ? ["--filter", `'!./apps/${e2eApp}'`] : []]
660
+ ], {
661
+ stdio: "inherit",
662
+ shell: true,
663
+ cwd: projectRoot
664
+ });
665
+ const frappeApps = await getFrappeApps(projectRoot);
666
+ for (const app of frappeApps) if (await fs.access(path.join(app.absolutePath, "pyproject.toml")).then(() => true).catch(() => false)) try {
667
+ await spawn("bench", [
668
+ "run-tests",
669
+ "--app",
670
+ app.name,
671
+ "--",
672
+ "-m",
673
+ "integration"
674
+ ], {
675
+ stdio: "inherit",
676
+ cwd: path.join(projectRoot, "apps", "frappe")
677
+ });
678
+ } catch {
679
+ console.warn(`frappe app ${app.name} integration tests failed (bench may not be available)`);
680
+ }
681
+ if (parsed.length === 1) return;
682
+ }
683
+ if (parsed.includes("e2e")) {
684
+ const teardownHandler = () => {
685
+ runE2ESession(projectRoot, { down: true }).then(() => process.exit(130));
686
+ };
687
+ if (!options.down) {
688
+ process.on("SIGINT", teardownHandler);
689
+ process.on("SIGTERM", teardownHandler);
690
+ }
691
+ await runE2ESession(projectRoot, {
692
+ upOnly: options.upOnly,
693
+ down: options.down,
694
+ portOffset: Number.parseInt(options.portOffset),
695
+ project: options.project,
696
+ noBuild: options.build === false,
697
+ filter: options.filter
698
+ });
699
+ return;
700
+ }
701
+ if (parsed.includes("visual")) {
702
+ const workspaces = await getStorybookVisualWorkspaces(projectRoot);
703
+ if (!workspaces.length) {
704
+ console.warn("No visual regression workspaces found (.storybook + Makefile test/visual, test:visual script, or lost-pixel).");
705
+ return;
706
+ }
707
+ for (const w of workspaces) if (w.runVisual === "make") await spawn("make", [
708
+ "-C",
709
+ w.absolutePath,
710
+ "test/visual"
711
+ ], {
712
+ stdio: "inherit",
713
+ cwd: projectRoot
714
+ });
715
+ else if (w.runLostPixelAfterBuild) {
716
+ await spawn("pnpm", ["run", "build"], {
717
+ stdio: "inherit",
718
+ cwd: w.absolutePath
719
+ });
720
+ await spawn("pnpm", ["exec", "lost-pixel"], {
721
+ stdio: "inherit",
722
+ cwd: w.absolutePath
723
+ });
724
+ } else if (w.pnpmScript) await spawn("pnpm", ["run", w.pnpmScript], {
725
+ stdio: "inherit",
726
+ cwd: w.absolutePath
727
+ });
728
+ return;
729
+ }
730
+ });
731
+ /**
732
+ * Run ruff format or check on the Frappe Python apps (if present).
733
+ * Returns true if the ruff step failed.
734
+ */
735
+ async function ruffStep(mode) {
736
+ const frappeApps = path.join(projectRoot, "apps", "frappe", "apps");
737
+ if (!fsSync.existsSync(frappeApps)) return false;
738
+ console.log(`\n── ${mode === "format" ? "ruff format" : "ruff check"} (Python) ──`);
739
+ try {
740
+ await spawn("ruff", [mode, frappeApps], {
741
+ stdio: "inherit",
742
+ cwd: projectRoot
743
+ });
744
+ return false;
745
+ } catch {
746
+ return true;
747
+ }
748
+ }
749
+ program.command("format").description("format all supported files (TS, Python, etc.) via turbo").action(async () => {
750
+ await spawn("turbo", [
751
+ "run",
752
+ "format",
753
+ "--filter=//"
754
+ ], {
755
+ stdio: "inherit",
756
+ cwd: projectRoot
757
+ });
758
+ await ruffStep("format");
433
759
  });
434
- program.command("check").argument("[args...]", "checks to run: spelling, types, lint (default: all)").description("run check command").action(async (args) => {
435
- args = args.flatMap((arg) => arg.split(","));
436
- const spelling = !args.length || args.includes("spelling");
437
- const types = !args.length || args.includes("types");
438
- const lint = !args.length || args.includes("lint");
439
- let exitCode = 0;
440
- if (spelling) {
441
- try {
442
- await execa(
443
- "pnpm",
444
- [
445
- "cspell",
446
- "--unique",
447
- "`(git ls-files && (git lfs ls-files | cut -d' ' -f3))`"
448
- ],
449
- {
450
- stdio: "inherit",
451
- shell: true,
452
- cwd: projectRoot
453
- }
454
- );
455
- } catch (err) {
456
- if (err instanceof Error && "exitCode" in err) {
457
- exitCode = err.exitCode;
458
- } else {
459
- exitCode = 1;
460
- }
461
- }
462
- }
463
- if (types) {
464
- try {
465
- await execa("turbo", ["run", "typecheck"], {
466
- stdio: "inherit",
467
- shell: true,
468
- cwd: projectRoot
469
- });
470
- } catch (err) {
471
- if (err instanceof Error && "exitCode" in err) {
472
- exitCode = err.exitCode;
473
- } else {
474
- exitCode = 1;
475
- }
476
- }
477
- }
478
- if (lint) {
479
- try {
480
- await execa(
481
- "pnpm",
482
- [
483
- "biome",
484
- "check",
485
- "--fix",
486
- "--unsafe",
487
- "`(git ls-files && (git lfs ls-files | cut -d' ' -f3)) | sort | uniq -u | grep -E '(html)|(s?css)|(md)|(json)|(yaml)|([jt]sx?)$'`"
488
- ],
489
- {
490
- stdio: "inherit",
491
- shell: true,
492
- cwd: projectRoot
493
- }
494
- );
495
- } catch (err) {
496
- if (err instanceof Error && "exitCode" in err) {
497
- exitCode = err.exitCode;
498
- } else {
499
- exitCode = 1;
500
- }
501
- }
502
- }
503
- process.exit(exitCode);
760
+ program.command("lint").description("lint and typecheck all supported files (TS, Python, etc.) via turbo").action(async () => {
761
+ const excludeFilters = await getTurboExcludeFiltersForMissing(projectRoot);
762
+ let turboFailed = false;
763
+ try {
764
+ await spawn("turbo", [
765
+ "run",
766
+ "lint",
767
+ "typecheck",
768
+ "--filter=//",
769
+ "--continue",
770
+ "--filter",
771
+ "!@package/features",
772
+ ...excludeFilters.flatMap((f) => ["--filter", f])
773
+ ], {
774
+ stdio: "inherit",
775
+ cwd: projectRoot
776
+ });
777
+ } catch {
778
+ turboFailed = true;
779
+ }
780
+ const ruffFailed = await ruffStep("check");
781
+ if (turboFailed || ruffFailed) process.exit(1);
504
782
  });
505
783
  program.command("count").description("count lines of code").action(async () => {
506
- await execa(
507
- "cloc",
508
- [
509
- "`(git ls-files && (git lfs ls-files | cut -d' ' -f3)) | sort | uniq -u | grep -E '(html)|(s?css)|(md)|(json)|(yaml)|([jt]sx?)$'`"
510
- ],
511
- {
512
- stdio: "inherit",
513
- shell: true,
514
- cwd: projectRoot
515
- }
516
- );
784
+ await spawn("cloc", ["`git ls-files | grep -E '(html)|(s?css)|(md)|(json)|(yaml)|([jt]sx?)$'`"], {
785
+ stdio: "inherit",
786
+ shell: true,
787
+ cwd: projectRoot
788
+ });
517
789
  });
518
790
  program.command("generate").description("run generate command").action(async () => {
519
- await execa("pnpm", ["turbo", "run", "generate"], {
520
- stdio: "inherit",
521
- shell: true,
522
- cwd: projectRoot
523
- });
791
+ await spawn("pnpm", [
792
+ "turbo",
793
+ "run",
794
+ "generate"
795
+ ], {
796
+ stdio: "inherit",
797
+ shell: true,
798
+ cwd: projectRoot
799
+ });
524
800
  });
525
801
  program.parse(process.argv);
526
802
  async function waitWithSpinner(services, options = {}) {
527
- const { interval = 1e3, timeout = 6e5 } = options;
528
- const waitFunctions = {
529
- api: waitForApi,
530
- frappe: waitForFrappe,
531
- postgres: waitForPostgres,
532
- keycloak: waitForKeycloak
533
- };
534
- const unreadyServices = [...services];
535
- const spinner = ora(
536
- `waiting for ${formatServiceList(unreadyServices)}`
537
- ).start();
538
- function updateSpinner(readyService) {
539
- unreadyServices.splice(unreadyServices.indexOf(readyService), 1);
540
- spinner.succeed(`${readyService} is ready`);
541
- if (unreadyServices.length) {
542
- spinner.start(`waiting for ${formatServiceList(unreadyServices)}`);
543
- }
544
- }
545
- let timeoutId;
546
- try {
547
- await Promise.race([
548
- Promise.all(
549
- services.map(async (service) => {
550
- const waitFn = waitFunctions[service];
551
- if (!waitFn) throw new Error(`Unknown service: ${service}`);
552
- await waitFn(interval);
553
- updateSpinner(service);
554
- })
555
- ),
556
- new Promise((_, reject) => {
557
- timeoutId = setTimeout(() => reject(new Error("Timeout")), timeout);
558
- })
559
- ]);
560
- } catch (err) {
561
- const error = err;
562
- if (error.message === "Timeout") {
563
- spinner.fail(
564
- `${formatServiceList(unreadyServices)} timed out after ${timeout}ms`
565
- );
566
- } else {
567
- spinner.fail(error.message);
568
- }
569
- throw error;
570
- } finally {
571
- clearTimeout(timeoutId);
572
- }
803
+ const { interval = 1e3, timeout = 6e5 } = options;
804
+ const waitFunctions = {
805
+ frappe: waitForFrappe,
806
+ postgres: waitForPostgres,
807
+ keycloak: waitForKeycloak
808
+ };
809
+ const unreadyServices = [...services];
810
+ const spinner = yoctoSpinner({ text: `waiting for ${formatServiceList(unreadyServices)}` }).start();
811
+ function updateSpinner(readyService) {
812
+ unreadyServices.splice(unreadyServices.indexOf(readyService), 1);
813
+ spinner.success(`${readyService} is ready`);
814
+ if (unreadyServices.length) spinner.start(`waiting for ${formatServiceList(unreadyServices)}`);
815
+ }
816
+ let timeoutId;
817
+ try {
818
+ await Promise.race([Promise.all(services.map(async (service) => {
819
+ const waitFn = waitFunctions[service];
820
+ if (!waitFn) throw new Error(`Unknown service: ${service}`);
821
+ await waitFn(interval);
822
+ updateSpinner(service);
823
+ })), new Promise((_, reject) => {
824
+ timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error("Timeout")), timeout);
825
+ })]);
826
+ } catch (err) {
827
+ const error = err;
828
+ if (error.message === "Timeout") spinner.error(`${formatServiceList(unreadyServices)} timed out after ${timeout}ms`);
829
+ else spinner.error(error.message);
830
+ throw error;
831
+ } finally {
832
+ clearTimeout(timeoutId);
833
+ }
573
834
  }
835
+
836
+ //#endregion
837
+ export { };