@amaster.ai/cli 1.1.26 → 1.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,10 +1,1626 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, readFileSync, readdirSync, statSync, rmSync } from 'fs';
2
+ import { readFileSync, existsSync, writeFileSync, readdirSync, statSync, rmSync, mkdirSync, constants } from 'fs';
3
+ import { createInterface } from 'readline/promises';
4
+ import { stdin, stdout } from 'process';
5
+ import { Command, Option } from 'commander';
6
+ import { readFile, mkdtemp, stat, rm, writeFile, readdir, unlink, copyFile, mkdir, access } from 'fs/promises';
7
+ import { join, resolve, basename, dirname, relative, parse, extname } from 'path';
8
+ import { randomBytes, createHash, randomUUID } from 'crypto';
9
+ import { tmpdir, homedir } from 'os';
10
+ import * as tar from 'tar';
11
+ import { createServer } from 'http';
3
12
  import { spawn, spawnSync } from 'child_process';
4
- import { tmpdir } from 'os';
5
- import { join, resolve, relative, extname } from 'path';
13
+ import YAML from 'yaml';
6
14
  import ts from 'typescript';
7
15
 
16
+ var EXCLUDED_NAMES = /* @__PURE__ */ new Set([".git", "node_modules", ".DS_Store"]);
17
+ function sha256(buffer) {
18
+ return `sha256:${createHash("sha256").update(buffer).digest("hex")}`;
19
+ }
20
+ async function collectFiles(rootDir, currentDir = rootDir) {
21
+ const entries = await readdir(currentDir, { withFileTypes: true });
22
+ const results = [];
23
+ for (const entry of entries) {
24
+ if (EXCLUDED_NAMES.has(entry.name)) {
25
+ continue;
26
+ }
27
+ const absolutePath = join(currentDir, entry.name);
28
+ if (entry.isDirectory()) {
29
+ results.push(...await collectFiles(rootDir, absolutePath));
30
+ continue;
31
+ }
32
+ results.push(relative(rootDir, absolutePath));
33
+ }
34
+ return results.sort();
35
+ }
36
+ async function packageAddonDirectory(sourceDir) {
37
+ const absoluteSourceDir = resolve(sourceDir);
38
+ const sourceStat = await stat(absoluteSourceDir);
39
+ if (!sourceStat.isDirectory()) {
40
+ throw new Error(`Addon source is not a directory: ${sourceDir}`);
41
+ }
42
+ const files = await collectFiles(absoluteSourceDir);
43
+ if (!files.length) {
44
+ throw new Error(`Addon directory is empty: ${sourceDir}`);
45
+ }
46
+ const archiveDir = await mkdtemp(join(tmpdir(), "amaster-addon-pack-"));
47
+ const archivePath = join(archiveDir, `${basename(absoluteSourceDir)}-${randomUUID()}.tgz`);
48
+ await tar.c(
49
+ {
50
+ cwd: absoluteSourceDir,
51
+ gzip: true,
52
+ file: archivePath,
53
+ portable: true
54
+ },
55
+ files
56
+ );
57
+ return {
58
+ archivePath,
59
+ buffer: await readFile(archivePath)
60
+ };
61
+ }
62
+ async function extractAddonArchiveBuffer(buffer) {
63
+ const extractDir = await mkdtemp(join(tmpdir(), "amaster-addon-extract-"));
64
+ const archivePath = join(extractDir, "addon.tgz");
65
+ await writeFile(archivePath, buffer);
66
+ await tar.x({
67
+ cwd: extractDir,
68
+ file: archivePath,
69
+ gzip: true
70
+ });
71
+ return extractDir;
72
+ }
73
+ async function extractAddonArchiveFile(filePath) {
74
+ const absolutePath = resolve(filePath);
75
+ const extractDir = await mkdtemp(join(tmpdir(), "amaster-addon-extract-"));
76
+ await tar.x({
77
+ cwd: extractDir,
78
+ file: absolutePath,
79
+ gzip: true
80
+ });
81
+ return extractDir;
82
+ }
83
+ async function removeTempDirectory(directory) {
84
+ await rm(directory, { recursive: true, force: true });
85
+ }
86
+ var DEFAULT_CONFIG = {
87
+ sessions: {}
88
+ };
89
+ function getCliHome() {
90
+ const configured = process.env.AMASTER_CLI_HOME?.trim();
91
+ if (configured) {
92
+ return configured;
93
+ }
94
+ return join(homedir(), ".amaster", "cli");
95
+ }
96
+ function getConfigFilePath() {
97
+ return join(getCliHome(), "config.json");
98
+ }
99
+ function ensureCliHome() {
100
+ if (!existsSync(getCliHome())) {
101
+ mkdirSync(getCliHome(), { recursive: true, mode: 448 });
102
+ }
103
+ }
104
+ function getCliConfig() {
105
+ const filePath = getConfigFilePath();
106
+ if (!existsSync(filePath)) {
107
+ return { ...DEFAULT_CONFIG };
108
+ }
109
+ try {
110
+ const parsed = JSON.parse(readFileSync(filePath, "utf8"));
111
+ return {
112
+ sessions: parsed.sessions ?? {}
113
+ };
114
+ } catch {
115
+ return { ...DEFAULT_CONFIG };
116
+ }
117
+ }
118
+ function saveCliConfig(config) {
119
+ ensureCliHome();
120
+ writeFileSync(getConfigFilePath(), JSON.stringify(config, null, 2), { mode: 384 });
121
+ }
122
+ function getStoredSession(registry) {
123
+ return getCliConfig().sessions[registry] ?? null;
124
+ }
125
+ function saveStoredSession(session) {
126
+ const config = getCliConfig();
127
+ config.sessions[session.registry] = session;
128
+ saveCliConfig(config);
129
+ }
130
+ function clearStoredSession(registry) {
131
+ const config = getCliConfig();
132
+ if (config.sessions[registry]) {
133
+ delete config.sessions[registry];
134
+ saveCliConfig(config);
135
+ }
136
+ }
137
+
138
+ // src/marketplace/http.ts
139
+ var CliError = class extends Error {
140
+ constructor(message, statusCode, details) {
141
+ super(message);
142
+ this.name = "CliError";
143
+ this.statusCode = statusCode;
144
+ this.details = details;
145
+ }
146
+ };
147
+ function buildUrl(baseUrl, path) {
148
+ return new URL(path, `${baseUrl}/`).toString();
149
+ }
150
+ async function parseResponseBody(response) {
151
+ const contentType = response.headers.get("content-type") ?? "";
152
+ if (contentType.includes("application/json")) {
153
+ return await response.json();
154
+ }
155
+ const text = await response.text();
156
+ return text || null;
157
+ }
158
+ function extractErrorMessage(body, fallback) {
159
+ if (!body) {
160
+ return fallback;
161
+ }
162
+ if (typeof body === "string") {
163
+ return body;
164
+ }
165
+ if (typeof body === "object") {
166
+ const candidate = body;
167
+ const errorDescription = candidate.error_description;
168
+ if (typeof errorDescription === "string" && errorDescription) {
169
+ return errorDescription;
170
+ }
171
+ const message = candidate.message;
172
+ if (typeof message === "string" && message) {
173
+ return message;
174
+ }
175
+ const error = candidate.error;
176
+ if (typeof error === "string" && error) {
177
+ return error;
178
+ }
179
+ }
180
+ return fallback;
181
+ }
182
+ async function requestJson(baseUrl, path, options = {}) {
183
+ const { body, unwrapData = false, headers, ...init } = options;
184
+ const response = await fetch(buildUrl(baseUrl, path), {
185
+ ...init,
186
+ headers: {
187
+ Accept: "application/json",
188
+ ...body !== void 0 && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
189
+ ...headers ?? {}
190
+ },
191
+ body: body === void 0 ? void 0 : body instanceof FormData ? body : JSON.stringify(body)
192
+ });
193
+ const parsedBody = await parseResponseBody(response);
194
+ if (!response.ok) {
195
+ throw new CliError(
196
+ extractErrorMessage(parsedBody, `${response.status} ${response.statusText}`),
197
+ response.status,
198
+ parsedBody
199
+ );
200
+ }
201
+ if (unwrapData && typeof parsedBody === "object" && parsedBody !== null && "data" in parsedBody) {
202
+ return parsedBody.data;
203
+ }
204
+ return parsedBody;
205
+ }
206
+ async function requestBuffer(baseUrl, path, options = {}) {
207
+ const response = await fetch(buildUrl(baseUrl, path), options);
208
+ if (!response.ok) {
209
+ const parsedBody = await parseResponseBody(response);
210
+ throw new CliError(
211
+ extractErrorMessage(parsedBody, `${response.status} ${response.statusText}`),
212
+ response.status,
213
+ parsedBody
214
+ );
215
+ }
216
+ return Buffer.from(await response.arrayBuffer());
217
+ }
218
+
219
+ // src/marketplace/auth.ts
220
+ var OAUTH_CLIENT_ID = "amaster-cli";
221
+ var OAUTH_REDIRECT_URI = "http://127.0.0.1:18147/oauth/callback";
222
+ var REFRESH_AHEAD_MS = 60 * 1e3;
223
+ var BROWSER_LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
224
+ function buildPkcePair() {
225
+ const codeVerifier = randomBytes(32).toString("base64url");
226
+ const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
227
+ return { codeVerifier, codeChallenge };
228
+ }
229
+ function buildExpiresAt(expiresIn) {
230
+ if (!expiresIn || expiresIn <= 0) {
231
+ return void 0;
232
+ }
233
+ return new Date(Date.now() + expiresIn * 1e3).toISOString();
234
+ }
235
+ function isSessionFreshEnough(session) {
236
+ if (!session.expiresAt) {
237
+ return true;
238
+ }
239
+ return new Date(session.expiresAt).getTime() - Date.now() > REFRESH_AHEAD_MS;
240
+ }
241
+ function buildAuthorizationUrl(input) {
242
+ const authorizeUrl = new URL("/api/oauth/authorize", `${input.registry}/`);
243
+ authorizeUrl.searchParams.set("response_type", "code");
244
+ authorizeUrl.searchParams.set("client_id", OAUTH_CLIENT_ID);
245
+ authorizeUrl.searchParams.set("redirect_uri", OAUTH_REDIRECT_URI);
246
+ authorizeUrl.searchParams.set("scope", "openid profile email");
247
+ authorizeUrl.searchParams.set("state", input.state);
248
+ authorizeUrl.searchParams.set("code_challenge", input.codeChallenge);
249
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
250
+ if (input.responseMode) {
251
+ authorizeUrl.searchParams.set("response_mode", input.responseMode);
252
+ }
253
+ return authorizeUrl;
254
+ }
255
+ async function resolveBrowserLoginUrl(authorizeUrl) {
256
+ const response = await fetch(authorizeUrl, {
257
+ method: "GET",
258
+ redirect: "manual"
259
+ });
260
+ if (response.status >= 300 && response.status < 400) {
261
+ const location = response.headers.get("location");
262
+ if (location) {
263
+ return new URL(location, authorizeUrl).toString();
264
+ }
265
+ }
266
+ if (response.ok) {
267
+ return authorizeUrl.toString();
268
+ }
269
+ throw new CliError(`Failed to start browser login: ${response.status} ${response.statusText}`, response.status);
270
+ }
271
+ async function fetchOAuthUserInfo(registry, accessToken) {
272
+ return await requestJson(registry, "/api/oauth/userinfo", {
273
+ method: "GET",
274
+ headers: {
275
+ Authorization: `Bearer ${accessToken}`
276
+ },
277
+ unwrapData: true
278
+ });
279
+ }
280
+ async function exchangeAuthorizationCodeForOAuthToken(input) {
281
+ return await requestJson(input.registry, "/api/oauth/token", {
282
+ method: "POST",
283
+ body: {
284
+ grant_type: "authorization_code",
285
+ client_id: OAUTH_CLIENT_ID,
286
+ code: input.code,
287
+ redirect_uri: OAUTH_REDIRECT_URI,
288
+ code_verifier: input.codeVerifier
289
+ },
290
+ unwrapData: true
291
+ });
292
+ }
293
+ async function exchangePasswordLoginForOAuthToken(registry, platformAccessToken) {
294
+ const { codeVerifier, codeChallenge } = buildPkcePair();
295
+ const state = randomBytes(16).toString("hex");
296
+ const authorizeUrl = buildAuthorizationUrl({
297
+ registry,
298
+ state,
299
+ codeChallenge,
300
+ responseMode: "json"
301
+ });
302
+ const authorizeResponse = await requestJson(
303
+ registry,
304
+ `${authorizeUrl.pathname}${authorizeUrl.search}`,
305
+ {
306
+ method: "GET",
307
+ headers: {
308
+ Authorization: `Bearer ${platformAccessToken}`
309
+ },
310
+ unwrapData: false
311
+ }
312
+ );
313
+ const redirectUrl = authorizeResponse.redirectUrl ? new URL(authorizeResponse.redirectUrl) : (() => {
314
+ throw new Error("OAuth authorize response missing redirectUrl");
315
+ })();
316
+ const code = redirectUrl.searchParams.get("code");
317
+ if (!code) {
318
+ throw new Error("OAuth authorize response missing code");
319
+ }
320
+ return await exchangeAuthorizationCodeForOAuthToken({
321
+ registry,
322
+ code,
323
+ codeVerifier
324
+ });
325
+ }
326
+ function openUrlInBrowser(url) {
327
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
328
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
329
+ return new Promise((resolve6, reject) => {
330
+ const child = spawn(command, args, {
331
+ detached: true,
332
+ stdio: "ignore"
333
+ });
334
+ child.once("error", reject);
335
+ child.once("spawn", () => {
336
+ child.unref();
337
+ resolve6();
338
+ });
339
+ });
340
+ }
341
+ function waitForBrowserAuthorizationCode(input) {
342
+ const redirectUrl = new URL(OAUTH_REDIRECT_URI);
343
+ const timeoutMs = input.timeoutMs ?? BROWSER_LOGIN_TIMEOUT_MS;
344
+ return new Promise((resolve6, reject) => {
345
+ let closed = false;
346
+ const sockets = /* @__PURE__ */ new Set();
347
+ const server = createServer((request, response) => {
348
+ const requestUrl = new URL(request.url ?? "/", OAUTH_REDIRECT_URI);
349
+ if (requestUrl.pathname !== redirectUrl.pathname) {
350
+ response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
351
+ response.end("Not found");
352
+ return;
353
+ }
354
+ const code = requestUrl.searchParams.get("code");
355
+ const state = requestUrl.searchParams.get("state");
356
+ const error = requestUrl.searchParams.get("error");
357
+ const errorDescription = requestUrl.searchParams.get("error_description");
358
+ if (error) {
359
+ response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
360
+ response.end(`AMaster CLI login failed: ${errorDescription || error}`);
361
+ cleanup();
362
+ reject(new Error(errorDescription || error));
363
+ return;
364
+ }
365
+ if (!code) {
366
+ response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
367
+ response.end("AMaster CLI login failed: missing authorization code");
368
+ cleanup();
369
+ reject(new Error("OAuth callback missing code"));
370
+ return;
371
+ }
372
+ if (state !== input.expectedState) {
373
+ response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
374
+ response.end("AMaster CLI login failed: invalid state");
375
+ cleanup();
376
+ reject(new Error("OAuth callback state mismatch"));
377
+ return;
378
+ }
379
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", Connection: "close" });
380
+ response.end(
381
+ "<!doctype html><title>AMaster CLI</title><script>window.close();</script><p>Login completed. You can close this window.</p>"
382
+ );
383
+ cleanup();
384
+ resolve6(code);
385
+ });
386
+ const timer = setTimeout(() => {
387
+ cleanup();
388
+ reject(new Error("Browser login timed out"));
389
+ }, timeoutMs);
390
+ function cleanup() {
391
+ clearTimeout(timer);
392
+ if (!closed && server.listening) {
393
+ closed = true;
394
+ server.close();
395
+ }
396
+ for (const socket of sockets) {
397
+ socket.destroy();
398
+ }
399
+ sockets.clear();
400
+ }
401
+ server.on("connection", (socket) => {
402
+ sockets.add(socket);
403
+ socket.once("close", () => {
404
+ sockets.delete(socket);
405
+ });
406
+ });
407
+ server.once("error", (error) => {
408
+ cleanup();
409
+ reject(error);
410
+ });
411
+ server.listen(Number(redirectUrl.port), redirectUrl.hostname);
412
+ });
413
+ }
414
+ async function loginWithBrowser(options) {
415
+ const { codeVerifier, codeChallenge } = buildPkcePair();
416
+ const state = randomBytes(16).toString("hex");
417
+ const authorizeUrl = buildAuthorizationUrl({
418
+ registry: options.registry,
419
+ state,
420
+ codeChallenge
421
+ });
422
+ const codePromise = options.waitForCode ? options.waitForCode(state) : waitForBrowserAuthorizationCode({
423
+ expectedState: state,
424
+ timeoutMs: options.timeoutMs
425
+ });
426
+ const browserUrl = await (options.resolveLoginUrl ?? resolveBrowserLoginUrl)(authorizeUrl);
427
+ await (options.openUrl ?? openUrlInBrowser)(browserUrl);
428
+ const code = await codePromise;
429
+ const oauthToken = await exchangeAuthorizationCodeForOAuthToken({
430
+ registry: options.registry,
431
+ code,
432
+ codeVerifier
433
+ });
434
+ const user = await fetchOAuthUserInfo(options.registry, oauthToken.access_token);
435
+ const session = {
436
+ registry: options.registry,
437
+ accessToken: oauthToken.access_token,
438
+ refreshToken: oauthToken.refresh_token,
439
+ expiresAt: buildExpiresAt(oauthToken.expires_in),
440
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
441
+ user
442
+ };
443
+ saveStoredSession(session);
444
+ return session;
445
+ }
446
+ async function loginWithPassword(options) {
447
+ const { registry, email, username, password } = options;
448
+ if (!email && !username) {
449
+ throw new Error("Either email or username is required");
450
+ }
451
+ const platformLogin = await requestJson(registry, "/api/auth/login", {
452
+ method: "POST",
453
+ body: {
454
+ ...email ? { email } : {},
455
+ ...username ? { username } : {},
456
+ password
457
+ },
458
+ unwrapData: true
459
+ });
460
+ if (!platformLogin.accessToken) {
461
+ throw new Error("Password login succeeded but no platform access token was returned");
462
+ }
463
+ const oauthToken = await exchangePasswordLoginForOAuthToken(registry, platformLogin.accessToken);
464
+ const user = await fetchOAuthUserInfo(registry, oauthToken.access_token);
465
+ const session = {
466
+ registry,
467
+ accessToken: oauthToken.access_token,
468
+ refreshToken: oauthToken.refresh_token,
469
+ expiresAt: buildExpiresAt(oauthToken.expires_in),
470
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
471
+ user
472
+ };
473
+ saveStoredSession(session);
474
+ return session;
475
+ }
476
+ async function refreshStoredSession(session) {
477
+ if (!session.refreshToken) {
478
+ throw new Error(`Session for ${session.registry} has expired and cannot be refreshed`);
479
+ }
480
+ const refreshed = await requestJson(session.registry, "/api/oauth/token", {
481
+ method: "POST",
482
+ body: {
483
+ grant_type: "refresh_token",
484
+ client_id: OAUTH_CLIENT_ID,
485
+ refresh_token: session.refreshToken
486
+ },
487
+ unwrapData: true
488
+ });
489
+ const nextSession = {
490
+ ...session,
491
+ accessToken: refreshed.access_token,
492
+ refreshToken: refreshed.refresh_token ?? session.refreshToken,
493
+ expiresAt: buildExpiresAt(refreshed.expires_in),
494
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
495
+ };
496
+ try {
497
+ nextSession.user = await fetchOAuthUserInfo(session.registry, nextSession.accessToken);
498
+ } catch {
499
+ nextSession.user = session.user;
500
+ }
501
+ saveStoredSession(nextSession);
502
+ return nextSession;
503
+ }
504
+ async function getActiveSession(registry) {
505
+ const stored = getStoredSession(registry);
506
+ if (!stored) {
507
+ throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
508
+ }
509
+ if (isSessionFreshEnough(stored)) {
510
+ return stored;
511
+ }
512
+ return await refreshStoredSession(stored);
513
+ }
514
+ async function withAccessToken(registry, runner) {
515
+ let session = await getActiveSession(registry);
516
+ try {
517
+ return await runner(session.accessToken);
518
+ } catch (error) {
519
+ if (session.refreshToken && error instanceof CliError && (error.statusCode === 401 || error.statusCode === 403)) {
520
+ session = await refreshStoredSession(session);
521
+ return await runner(session.accessToken);
522
+ }
523
+ throw error;
524
+ }
525
+ }
526
+ async function getCurrentUser(registry) {
527
+ return await withAccessToken(registry, async (accessToken) => {
528
+ return await fetchOAuthUserInfo(registry, accessToken);
529
+ });
530
+ }
531
+ function logout(registry) {
532
+ clearStoredSession(registry);
533
+ }
534
+ async function loadAddonManifestFromDirectory(directory) {
535
+ const manifestPath = join(directory, "addon.json");
536
+ const manifestText = await readFile(manifestPath, "utf8");
537
+ const manifest = JSON.parse(manifestText);
538
+ validateAddonManifest(manifest);
539
+ return manifest;
540
+ }
541
+ function validateAddonManifest(manifest) {
542
+ if (!manifest || typeof manifest !== "object") {
543
+ throw new Error("addon.json is invalid");
544
+ }
545
+ if (!manifest.name || !manifest.version) {
546
+ throw new Error("addon.json missing name or version");
547
+ }
548
+ if (!manifest.display?.title || !manifest.display?.description) {
549
+ throw new Error("addon.json missing display.title or display.description");
550
+ }
551
+ if (!manifest.compatibility?.applicationTypes?.length || !manifest.compatibility?.phases?.length) {
552
+ throw new Error("addon.json missing compatibility.applicationTypes or compatibility.phases");
553
+ }
554
+ if (!Array.isArray(manifest.members)) {
555
+ throw new Error("addon.json missing members");
556
+ }
557
+ }
558
+ function resolveMemberSourcePath(member) {
559
+ const sourcePath = member.source?.path;
560
+ if (typeof sourcePath === "string" && sourcePath.trim()) {
561
+ return normalizeRelativePath(sourcePath);
562
+ }
563
+ const fallbackKeys = ["entry", "path", "contentPath"];
564
+ for (const key of fallbackKeys) {
565
+ const value = member[key];
566
+ if (typeof value === "string" && value.trim()) {
567
+ return normalizeRelativePath(value);
568
+ }
569
+ }
570
+ return null;
571
+ }
572
+ function normalizeRelativePath(value) {
573
+ const normalized = value.replace(/^\.?\//, "").replace(/\\/g, "/");
574
+ if (!normalized || normalized.startsWith("../") || normalized.includes("/../")) {
575
+ throw new Error(`Invalid member source path: ${value}`);
576
+ }
577
+ return normalized;
578
+ }
579
+ async function assertPathExists(rootDir, relativePath) {
580
+ await access(join(rootDir, relativePath), constants.F_OK);
581
+ }
582
+ function resolveNearestPackageRoot(startDir = process.cwd()) {
583
+ let current = resolve(startDir);
584
+ const root = parse(current).root;
585
+ while (true) {
586
+ if (existsSync(join(current, "package.json"))) {
587
+ return current;
588
+ }
589
+ if (current === root) {
590
+ throw new Error(`Unable to find package.json from ${resolve(startDir)}. Pass --target <path> explicitly.`);
591
+ }
592
+ current = dirname(current);
593
+ }
594
+ }
595
+ function tryResolveNearestPackageRoot(startDir = process.cwd()) {
596
+ try {
597
+ return resolveNearestPackageRoot(startDir);
598
+ } catch {
599
+ return null;
600
+ }
601
+ }
602
+ async function readAppSettingsApplicationType(packageRoot) {
603
+ const appSettingsPath = join(packageRoot, "app.settings.yml");
604
+ if (!existsSync(appSettingsPath)) {
605
+ return null;
606
+ }
607
+ const parsed = YAML.parse(await readFile(appSettingsPath, "utf8"));
608
+ if (parsed?.type === "web" || parsed?.type === "mini") {
609
+ return parsed.type;
610
+ }
611
+ return null;
612
+ }
613
+ async function detectApplicationType(targetDir, explicitType) {
614
+ if (explicitType) {
615
+ return explicitType;
616
+ }
617
+ const applicationType = await readAppSettingsApplicationType(targetDir);
618
+ if (applicationType) {
619
+ return applicationType;
620
+ }
621
+ if (existsSync(join(targetDir, "src", "app.config.ts"))) {
622
+ return "mini";
623
+ }
624
+ if (existsSync(join(targetDir, "src", "routes.tsx"))) {
625
+ return "web";
626
+ }
627
+ throw new Error("Unable to detect application type. Pass --application-type web|mini.");
628
+ }
629
+ async function tryDetectNearestApplicationType(startDir = process.cwd()) {
630
+ const packageRoot = tryResolveNearestPackageRoot(startDir);
631
+ if (!packageRoot) {
632
+ return void 0;
633
+ }
634
+ try {
635
+ return await detectApplicationType(packageRoot);
636
+ } catch {
637
+ return void 0;
638
+ }
639
+ }
640
+
641
+ // src/marketplace/install.ts
642
+ var AddonInstallConflictError = class extends Error {
643
+ constructor(input) {
644
+ super(`Addon ${input.operation} has ${input.conflicts.length} conflict(s)`);
645
+ this.code = "ADDON_INSTALL_CONFLICT";
646
+ this.name = "AddonInstallConflictError";
647
+ this.operation = input.operation;
648
+ this.addon = input.addon;
649
+ this.targetDir = input.targetDir;
650
+ this.conflicts = input.conflicts;
651
+ }
652
+ toJSON() {
653
+ return {
654
+ success: false,
655
+ code: this.code,
656
+ message: this.message,
657
+ operation: this.operation,
658
+ addon: this.addon,
659
+ targetDir: this.targetDir,
660
+ conflicts: this.conflicts
661
+ };
662
+ }
663
+ };
664
+ function isAddonInstallConflictError(error) {
665
+ return error instanceof AddonInstallConflictError;
666
+ }
667
+ function sha256Buffer(buffer) {
668
+ return `sha256:${createHash("sha256").update(buffer).digest("hex")}`;
669
+ }
670
+ function ensurePathInsideTarget(targetDir, relativePath) {
671
+ const absolute = resolve(targetDir, relativePath);
672
+ const normalizedTarget = resolve(targetDir);
673
+ if (!absolute.startsWith(`${normalizedTarget}/`) && absolute !== normalizedTarget) {
674
+ throw new Error(`Refusing to write outside target directory: ${relativePath}`);
675
+ }
676
+ return absolute;
677
+ }
678
+ function removeFileExtension(input) {
679
+ const extension = extname(input);
680
+ return extension ? input.slice(0, -extension.length) : input;
681
+ }
682
+ function toPascalCase(input) {
683
+ return input.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((part) => part[0].toUpperCase() + part.slice(1)).join("");
684
+ }
685
+ function parseScalarValue(rawValue, expectedType, enumValues) {
686
+ const primaryType = Array.isArray(expectedType) ? expectedType[0] : expectedType;
687
+ if (enumValues?.length) {
688
+ if (!enumValues.includes(rawValue)) {
689
+ throw new Error(`Invalid value "${rawValue}". Expected one of: ${enumValues.join(", ")}`);
690
+ }
691
+ return rawValue;
692
+ }
693
+ switch (primaryType) {
694
+ case "boolean":
695
+ if (rawValue === "true") return true;
696
+ if (rawValue === "false") return false;
697
+ throw new Error(`Invalid boolean value: ${rawValue}`);
698
+ case "number": {
699
+ const value = Number(rawValue);
700
+ if (Number.isNaN(value)) {
701
+ throw new Error(`Invalid number value: ${rawValue}`);
702
+ }
703
+ return value;
704
+ }
705
+ case "integer": {
706
+ const value = Number.parseInt(rawValue, 10);
707
+ if (Number.isNaN(value)) {
708
+ throw new Error(`Invalid integer value: ${rawValue}`);
709
+ }
710
+ return value;
711
+ }
712
+ case "object":
713
+ case "array":
714
+ return JSON.parse(rawValue);
715
+ default:
716
+ return rawValue;
717
+ }
718
+ }
719
+ function resolveInstallParameters(manifest, rawParameters) {
720
+ const schema = manifest.install?.parameters?.schema;
721
+ if (!schema?.properties) {
722
+ if (rawParameters && Object.keys(rawParameters).length) {
723
+ throw new Error("This addon does not declare install parameters");
724
+ }
725
+ return {};
726
+ }
727
+ const resolved = {};
728
+ const properties = schema.properties;
729
+ const provided = rawParameters ?? {};
730
+ for (const key of Object.keys(provided)) {
731
+ if (!properties[key]) {
732
+ throw new Error(`Unknown install parameter: ${key}`);
733
+ }
734
+ }
735
+ for (const [key, property] of Object.entries(properties)) {
736
+ if (key in provided) {
737
+ resolved[key] = parseScalarValue(provided[key], property.type, property.enum);
738
+ continue;
739
+ }
740
+ if (property.default !== void 0) {
741
+ resolved[key] = property.default;
742
+ }
743
+ }
744
+ for (const requiredKey of schema.required ?? []) {
745
+ if (!(requiredKey in resolved)) {
746
+ throw new Error(`Missing required install parameter: ${requiredKey}`);
747
+ }
748
+ }
749
+ return resolved;
750
+ }
751
+ function getAddonMetaPath(targetDir, addonName) {
752
+ return join(targetDir, "src", "addons", addonName, "meta.json");
753
+ }
754
+ async function readInstalledAddonMeta(metaPath) {
755
+ if (!existsSync(metaPath)) {
756
+ return null;
757
+ }
758
+ return JSON.parse(await readFile(metaPath, "utf8"));
759
+ }
760
+ async function listAddonMetaPaths(targetDir) {
761
+ const addonsDir = join(targetDir, "src", "addons");
762
+ if (!existsSync(addonsDir)) {
763
+ return [];
764
+ }
765
+ const entries = await readdir(addonsDir, { withFileTypes: true });
766
+ const paths = [];
767
+ for (const entry of entries) {
768
+ if (!entry.isDirectory()) {
769
+ continue;
770
+ }
771
+ const metaPath = join(addonsDir, entry.name, "meta.json");
772
+ if (existsSync(metaPath)) {
773
+ paths.push(metaPath);
774
+ }
775
+ }
776
+ return paths.sort();
777
+ }
778
+ async function listInstalledAddons(targetDir) {
779
+ const metaPaths = await listAddonMetaPaths(resolve(targetDir));
780
+ const metas = await Promise.all(metaPaths.map((metaPath) => readInstalledAddonMeta(metaPath)));
781
+ return metas.filter((meta) => Boolean(meta));
782
+ }
783
+ function buildOwnershipMap(metas, excludeAddonName) {
784
+ const ownership = /* @__PURE__ */ new Map();
785
+ for (const meta of metas) {
786
+ if (excludeAddonName && meta.name === excludeAddonName) {
787
+ continue;
788
+ }
789
+ for (const file of meta.files) {
790
+ ownership.set(file.path, meta.name);
791
+ }
792
+ }
793
+ return ownership;
794
+ }
795
+ async function collectDirectoryFiles(sourceDir) {
796
+ const entries = await readdir(sourceDir, { withFileTypes: true });
797
+ const files = [];
798
+ for (const entry of entries) {
799
+ const absolute = join(sourceDir, entry.name);
800
+ if (entry.isDirectory()) {
801
+ files.push(...await collectDirectoryFiles(absolute));
802
+ continue;
803
+ }
804
+ files.push(absolute);
805
+ }
806
+ return files.sort();
807
+ }
808
+ async function planCopyMember(sourceRoot, sourceRelativePath, targetBaseRelativeDir, member) {
809
+ const sourceAbsolutePath = join(sourceRoot, sourceRelativePath);
810
+ const sourceStat = await stat(sourceAbsolutePath);
811
+ const plannedFiles = [];
812
+ const targetPaths = [];
813
+ if (sourceStat.isDirectory()) {
814
+ const sourceFiles = await collectDirectoryFiles(sourceAbsolutePath);
815
+ for (const sourceFile of sourceFiles) {
816
+ const nestedRelativePath = relative(sourceAbsolutePath, sourceFile);
817
+ const targetPath = join(targetBaseRelativeDir, basename(sourceRelativePath), nestedRelativePath).replace(/\\/g, "/");
818
+ const sourcePackagePath = join(sourceRelativePath, nestedRelativePath).replace(/\\/g, "/");
819
+ plannedFiles.push({
820
+ sourcePath: sourceFile,
821
+ sourceRelativePath: sourcePackagePath,
822
+ targetPath,
823
+ memberName: member.name,
824
+ memberType: member.type
825
+ });
826
+ targetPaths.push(targetPath);
827
+ }
828
+ } else {
829
+ const targetPath = join(targetBaseRelativeDir, basename(sourceRelativePath)).replace(/\\/g, "/");
830
+ plannedFiles.push({
831
+ sourcePath: sourceAbsolutePath,
832
+ sourceRelativePath,
833
+ targetPath,
834
+ memberName: member.name,
835
+ memberType: member.type
836
+ });
837
+ targetPaths.push(targetPath);
838
+ }
839
+ return { files: plannedFiles, targetPaths };
840
+ }
841
+ async function buildInstallPlan(options) {
842
+ const targetDir = resolve(options.targetDir);
843
+ const manifest = await loadAddonManifestFromDirectory(options.extractedDir);
844
+ const applicationType = await detectApplicationType(targetDir, options.applicationType);
845
+ if (!manifest.compatibility.applicationTypes.includes(applicationType)) {
846
+ throw new Error(`Addon ${manifest.name}@${manifest.version} does not support application type ${applicationType}`);
847
+ }
848
+ if (!manifest.compatibility.phases.includes("design")) {
849
+ throw new Error(`Addon ${manifest.name}@${manifest.version} is not a design-time addon`);
850
+ }
851
+ const installParameters = resolveInstallParameters(manifest, options.installParameters);
852
+ const files = [];
853
+ const members = [];
854
+ for (const member of manifest.members) {
855
+ if (member.type === "skill") {
856
+ throw new Error(`Member ${member.name} is a runtime skill. Design-time CLI install does not support skill members yet.`);
857
+ }
858
+ if (member.type === "settings") {
859
+ throw new Error(`Member ${member.name} is a settings fragment. settings install is not implemented yet.`);
860
+ }
861
+ const sourceRelativePath = resolveMemberSourcePath(member);
862
+ if (!sourceRelativePath) {
863
+ throw new Error(`Member ${member.name} is missing source.path`);
864
+ }
865
+ await assertPathExists(options.extractedDir, sourceRelativePath);
866
+ let targetBaseRelativeDir;
867
+ switch (member.type) {
868
+ case "component":
869
+ targetBaseRelativeDir = join("src", "components", manifest.name);
870
+ break;
871
+ case "page":
872
+ targetBaseRelativeDir = join("src", "pages");
873
+ break;
874
+ case "theme":
875
+ targetBaseRelativeDir = join("src", "assets", manifest.name);
876
+ break;
877
+ case "workflow":
878
+ targetBaseRelativeDir = join("src", "workflow");
879
+ break;
880
+ case "bpmn":
881
+ targetBaseRelativeDir = join("src", "bpmn");
882
+ break;
883
+ case "entity":
884
+ targetBaseRelativeDir = join("src", "db", "entity");
885
+ break;
886
+ case "datasource":
887
+ targetBaseRelativeDir = join("src", "db", "datasource");
888
+ break;
889
+ default:
890
+ throw new Error(`Unsupported addon member type: ${member.type}`);
891
+ }
892
+ const planned = await planCopyMember(options.extractedDir, sourceRelativePath, targetBaseRelativeDir, member);
893
+ files.push(...planned.files);
894
+ const installedMember = {
895
+ name: member.name,
896
+ type: member.type,
897
+ sourcePath: sourceRelativePath,
898
+ targetPaths: planned.targetPaths
899
+ };
900
+ if (member.type === "page") {
901
+ if (applicationType === "web") {
902
+ const pageWeb = member.page?.web;
903
+ if (!pageWeb?.route || !pageWeb.entry) {
904
+ throw new Error(`Page member ${member.name} is missing page.web.route or page.web.entry`);
905
+ }
906
+ installedMember.page = {
907
+ web: {
908
+ route: pageWeb.route,
909
+ entry: pageWeb.entry,
910
+ title: pageWeb.title,
911
+ visible: pageWeb.visible
912
+ }
913
+ };
914
+ } else {
915
+ const pageMini = member.page?.mini;
916
+ if (!pageMini?.pagePath) {
917
+ throw new Error(`Page member ${member.name} is missing page.mini.pagePath`);
918
+ }
919
+ installedMember.page = {
920
+ mini: {
921
+ pagePath: pageMini.pagePath,
922
+ tabBar: pageMini.tabBar
923
+ }
924
+ };
925
+ }
926
+ }
927
+ members.push(installedMember);
928
+ }
929
+ return {
930
+ files,
931
+ members,
932
+ metaPath: getAddonMetaPath(targetDir, manifest.name),
933
+ applicationType,
934
+ installParameters,
935
+ manifest
936
+ };
937
+ }
938
+ async function readFileMeta(targetDir, relativePath, memberName, memberType) {
939
+ const absolutePath = ensurePathInsideTarget(targetDir, relativePath);
940
+ const buffer = await readFile(absolutePath);
941
+ return {
942
+ path: relativePath,
943
+ sha256: sha256Buffer(buffer),
944
+ size: buffer.length,
945
+ memberName,
946
+ memberType
947
+ };
948
+ }
949
+ function buildInstalledAddonMeta(options) {
950
+ const now = (/* @__PURE__ */ new Date()).toISOString();
951
+ const installedAt = options.installedAt ?? now;
952
+ return {
953
+ apiVersion: "addon.amaster.io/meta",
954
+ name: options.manifest.name,
955
+ version: options.manifest.version,
956
+ registry: options.registry,
957
+ applicationType: options.applicationType,
958
+ organizationCode: options.organizationCode,
959
+ installedAt,
960
+ updatedAt: now,
961
+ manifest: {
962
+ title: options.manifest.display.title,
963
+ description: options.manifest.display.description,
964
+ category: options.manifest.display.category,
965
+ applicationTypes: options.manifest.compatibility.applicationTypes,
966
+ phases: options.manifest.compatibility.phases,
967
+ memberTypes: [...new Set(options.manifest.members.map((member) => member.type))]
968
+ },
969
+ installParameters: options.installParameters,
970
+ members: options.members,
971
+ files: options.files
972
+ };
973
+ }
974
+ async function ensureParentDirectory(filePath) {
975
+ await mkdir(dirname(filePath), { recursive: true });
976
+ }
977
+ async function writePlannedFiles(targetDir, planFiles) {
978
+ for (const file of planFiles) {
979
+ const absoluteTargetPath = ensurePathInsideTarget(targetDir, file.targetPath);
980
+ await ensureParentDirectory(absoluteTargetPath);
981
+ await copyFile(file.sourcePath, absoluteTargetPath);
982
+ }
983
+ }
984
+ async function removeObsoleteFiles(targetDir, previousMeta, nextPaths) {
985
+ const removed = [];
986
+ for (const file of previousMeta.files) {
987
+ if (nextPaths.has(file.path)) {
988
+ continue;
989
+ }
990
+ const absolutePath = ensurePathInsideTarget(targetDir, file.path);
991
+ if (existsSync(absolutePath)) {
992
+ await unlink(absolutePath);
993
+ removed.push(file.path);
994
+ }
995
+ }
996
+ return removed;
997
+ }
998
+ async function validateInstallConflicts(targetDir, plan, existingMetas) {
999
+ const ownership = buildOwnershipMap(existingMetas);
1000
+ const conflicts = [];
1001
+ for (const file of plan.files) {
1002
+ const owner = ownership.get(file.targetPath);
1003
+ if (owner && owner !== plan.manifest.name) {
1004
+ conflicts.push({
1005
+ kind: "owned_by_other_addon",
1006
+ path: file.targetPath,
1007
+ sourcePath: file.sourceRelativePath,
1008
+ memberName: file.memberName,
1009
+ memberType: file.memberType,
1010
+ ownerAddon: owner,
1011
+ message: `${file.targetPath} is already managed by addon ${owner}`
1012
+ });
1013
+ continue;
1014
+ }
1015
+ const absoluteTargetPath = ensurePathInsideTarget(targetDir, file.targetPath);
1016
+ if (existsSync(absoluteTargetPath) && !owner) {
1017
+ conflicts.push({
1018
+ kind: "target_exists",
1019
+ path: file.targetPath,
1020
+ sourcePath: file.sourceRelativePath,
1021
+ memberName: file.memberName,
1022
+ memberType: file.memberType,
1023
+ message: `${file.targetPath} already exists in target application`
1024
+ });
1025
+ }
1026
+ }
1027
+ if (conflicts.length) {
1028
+ throw new AddonInstallConflictError({
1029
+ operation: "install",
1030
+ addon: {
1031
+ name: plan.manifest.name,
1032
+ version: plan.manifest.version,
1033
+ applicationType: plan.applicationType
1034
+ },
1035
+ targetDir,
1036
+ conflicts
1037
+ });
1038
+ }
1039
+ }
1040
+ async function validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta) {
1041
+ const ownership = buildOwnershipMap(existingMetas, previousMeta.name);
1042
+ const previousFilesByPath = new Map(previousMeta.files.map((file) => [file.path, file]));
1043
+ const nextPaths = new Set(plan.files.map((file) => file.targetPath));
1044
+ const conflicts = [];
1045
+ for (const managedFile of previousMeta.files) {
1046
+ const absolutePath = ensurePathInsideTarget(targetDir, managedFile.path);
1047
+ if (!existsSync(absolutePath)) {
1048
+ conflicts.push({
1049
+ kind: "managed_file_missing",
1050
+ path: managedFile.path,
1051
+ memberName: managedFile.memberName,
1052
+ memberType: managedFile.memberType,
1053
+ expectedSha256: managedFile.sha256,
1054
+ message: `managed file missing: ${managedFile.path}`
1055
+ });
1056
+ continue;
1057
+ }
1058
+ const currentBuffer = await readFile(absolutePath);
1059
+ const actualSha256 = sha256Buffer(currentBuffer);
1060
+ if (actualSha256 !== managedFile.sha256 && nextPaths.has(managedFile.path)) {
1061
+ conflicts.push({
1062
+ kind: "managed_file_modified",
1063
+ path: managedFile.path,
1064
+ memberName: managedFile.memberName,
1065
+ memberType: managedFile.memberType,
1066
+ expectedSha256: managedFile.sha256,
1067
+ actualSha256,
1068
+ message: `managed file modified locally: ${managedFile.path}`
1069
+ });
1070
+ }
1071
+ }
1072
+ for (const file of plan.files) {
1073
+ const owner = ownership.get(file.targetPath);
1074
+ if (owner) {
1075
+ conflicts.push({
1076
+ kind: "owned_by_other_addon",
1077
+ path: file.targetPath,
1078
+ sourcePath: file.sourceRelativePath,
1079
+ memberName: file.memberName,
1080
+ memberType: file.memberType,
1081
+ ownerAddon: owner,
1082
+ message: `${file.targetPath} is already managed by addon ${owner}`
1083
+ });
1084
+ continue;
1085
+ }
1086
+ const absoluteTargetPath = ensurePathInsideTarget(targetDir, file.targetPath);
1087
+ if (existsSync(absoluteTargetPath) && !previousFilesByPath.has(file.targetPath)) {
1088
+ conflicts.push({
1089
+ kind: "target_exists",
1090
+ path: file.targetPath,
1091
+ sourcePath: file.sourceRelativePath,
1092
+ memberName: file.memberName,
1093
+ memberType: file.memberType,
1094
+ message: `${file.targetPath} already exists in target application`
1095
+ });
1096
+ }
1097
+ }
1098
+ for (const oldFile of previousMeta.files) {
1099
+ if (!nextPaths.has(oldFile.path)) {
1100
+ const absolutePath = ensurePathInsideTarget(targetDir, oldFile.path);
1101
+ if (!existsSync(absolutePath)) {
1102
+ continue;
1103
+ }
1104
+ const currentBuffer = await readFile(absolutePath);
1105
+ const actualSha256 = sha256Buffer(currentBuffer);
1106
+ if (actualSha256 !== oldFile.sha256) {
1107
+ conflicts.push({
1108
+ kind: "obsolete_file_modified",
1109
+ path: oldFile.path,
1110
+ memberName: oldFile.memberName,
1111
+ memberType: oldFile.memberType,
1112
+ expectedSha256: oldFile.sha256,
1113
+ actualSha256,
1114
+ message: `file changed locally and would be removed: ${oldFile.path}`
1115
+ });
1116
+ }
1117
+ }
1118
+ }
1119
+ if (conflicts.length) {
1120
+ throw new AddonInstallConflictError({
1121
+ operation: "upgrade",
1122
+ addon: {
1123
+ name: plan.manifest.name,
1124
+ version: plan.manifest.version,
1125
+ applicationType: plan.applicationType
1126
+ },
1127
+ targetDir,
1128
+ conflicts
1129
+ });
1130
+ }
1131
+ }
1132
+ async function ensureWebRoutesPatched(targetDir) {
1133
+ const routesFile = join(targetDir, "src", "routes.tsx");
1134
+ const original = await readFile(routesFile, "utf8");
1135
+ let next = original;
1136
+ if (!next.includes("./amaster/registry/addon-routes.generated")) {
1137
+ next = next.replace(
1138
+ 'import type { ComponentType } from "react";',
1139
+ 'import type { ComponentType } from "react";\nimport { addonRoutes } from "./amaster/registry/addon-routes.generated";'
1140
+ );
1141
+ }
1142
+ if (!next.includes("...addonRoutes")) {
1143
+ const routeArrayPattern = /const routes:\s*RouteConfig\[\]\s*=\s*\[([\s\S]*?)\];/;
1144
+ const match = next.match(routeArrayPattern);
1145
+ if (!match) {
1146
+ throw new Error("Unable to patch src/routes.tsx for addon route registration");
1147
+ }
1148
+ const inner = match[1]?.trim() ?? "";
1149
+ const replacement = inner ? `const routes: RouteConfig[] = [
1150
+ ...addonRoutes,
1151
+ ${match[1]}
1152
+ ];` : "const routes: RouteConfig[] = [\n ...addonRoutes,\n];";
1153
+ next = next.replace(routeArrayPattern, replacement);
1154
+ }
1155
+ if (next !== original) {
1156
+ await writeFile(routesFile, next);
1157
+ }
1158
+ }
1159
+ async function ensureMiniAppConfigPatched(targetDir, needsTabBarItems) {
1160
+ const configFile = join(targetDir, "src", "app.config.ts");
1161
+ const original = await readFile(configFile, "utf8");
1162
+ let next = original;
1163
+ if (!next.includes("./amaster/registry/addon-pages.generated")) {
1164
+ next = `import { addonPages, addonTabBarItems } from "./amaster/registry/addon-pages.generated";
1165
+ ${next}`;
1166
+ }
1167
+ if (!next.includes("...addonPages")) {
1168
+ next = next.replace(/const pages\s*=\s*\[([\s\S]*?)\]/, (_full, inner) => {
1169
+ const trimmed = inner.trim();
1170
+ if (!trimmed) {
1171
+ return "const pages = [...addonPages]";
1172
+ }
1173
+ return `const pages = [${inner}, ...addonPages]`;
1174
+ });
1175
+ }
1176
+ if (needsTabBarItems && !next.includes("...addonTabBarItems")) {
1177
+ const listPattern = /list:\s*\[([\s\S]*?)\]/;
1178
+ const match = next.match(listPattern);
1179
+ if (!match) {
1180
+ throw new Error("Unable to patch src/app.config.ts for addon tabBar registration");
1181
+ }
1182
+ next = next.replace(listPattern, (_full, inner) => `list: [${inner}, ...addonTabBarItems]`);
1183
+ }
1184
+ if (next !== original) {
1185
+ await writeFile(configFile, next);
1186
+ }
1187
+ }
1188
+ async function rebuildRegistryFiles(targetDir, applicationType, metas) {
1189
+ const registryDir = join(targetDir, "src", "amaster", "registry");
1190
+ await mkdir(registryDir, { recursive: true });
1191
+ if (applicationType === "web") {
1192
+ const pageMembers2 = metas.flatMap(
1193
+ (meta) => meta.members.filter((member) => member.type === "page" && member.page?.web).map((member) => ({ addonName: meta.name, member }))
1194
+ ).sort((left, right) => `${left.addonName}:${left.member.name}`.localeCompare(`${right.addonName}:${right.member.name}`));
1195
+ const imports = pageMembers2.map(({ addonName, member }) => {
1196
+ const identifier = toPascalCase(`${addonName}-${member.name}-page`);
1197
+ const entry = member.page.web.entry;
1198
+ return {
1199
+ identifier,
1200
+ importPath: `../../${removeFileExtension(entry).replace(/\\/g, "/")}`,
1201
+ route: member.page.web.route,
1202
+ visible: member.page.web.visible,
1203
+ name: member.name
1204
+ };
1205
+ });
1206
+ const fileContent2 = [
1207
+ 'import type { ComponentType } from "react";',
1208
+ ...imports.map((item) => `import ${item.identifier} from "${item.importPath}";`),
1209
+ "",
1210
+ "type AddonRouteConfig = {",
1211
+ " name: string;",
1212
+ " path: string;",
1213
+ " Component: ComponentType<Record<string, unknown>>;",
1214
+ " visible?: boolean;",
1215
+ "};",
1216
+ "",
1217
+ "export const addonRoutes: AddonRouteConfig[] = [",
1218
+ ...imports.map(
1219
+ (item) => ` { name: ${JSON.stringify(item.name)}, path: ${JSON.stringify(item.route)}, Component: ${item.identifier},${item.visible === void 0 ? "" : ` visible: ${item.visible},`} },`
1220
+ ),
1221
+ "];",
1222
+ ""
1223
+ ].join("\n");
1224
+ await writeFile(join(registryDir, "addon-routes.generated.ts"), fileContent2);
1225
+ await ensureWebRoutesPatched(targetDir);
1226
+ return;
1227
+ }
1228
+ const pageMembers = metas.flatMap(
1229
+ (meta) => meta.members.filter((member) => member.type === "page" && member.page?.mini).map((member) => member.page.mini)
1230
+ ).sort((left, right) => left.pagePath.localeCompare(right.pagePath));
1231
+ const addonPages = pageMembers.map((page) => page.pagePath);
1232
+ const addonTabBarItems = pageMembers.filter((page) => page.tabBar).map((page) => ({
1233
+ pagePath: page.pagePath,
1234
+ ...page.tabBar
1235
+ }));
1236
+ const fileContent = [
1237
+ `export const addonPages = ${JSON.stringify(addonPages, null, 2)};`,
1238
+ "",
1239
+ `export const addonTabBarItems = ${JSON.stringify(addonTabBarItems, null, 2)};`,
1240
+ ""
1241
+ ].join("\n");
1242
+ await writeFile(join(registryDir, "addon-pages.generated.ts"), fileContent);
1243
+ await ensureMiniAppConfigPatched(targetDir, addonTabBarItems.length > 0);
1244
+ }
1245
+ async function materializeAddon(options) {
1246
+ const targetDir = resolve(options.targetDir);
1247
+ const existingMetas = await listInstalledAddons(targetDir);
1248
+ const plan = await buildInstallPlan(options);
1249
+ const previousMeta = existingMetas.find((meta2) => meta2.name === plan.manifest.name) ?? null;
1250
+ if (options.mode === "install" && previousMeta) {
1251
+ throw new Error(`Addon ${plan.manifest.name} is already installed. Use addon upgrade instead.`);
1252
+ }
1253
+ if (options.mode === "upgrade" && !previousMeta) {
1254
+ throw new Error(`Addon ${plan.manifest.name} is not installed yet. Use addon install instead.`);
1255
+ }
1256
+ if (previousMeta && previousMeta.applicationType !== plan.applicationType) {
1257
+ throw new Error(`Installed addon ${plan.manifest.name} uses application type ${previousMeta.applicationType}, not ${plan.applicationType}`);
1258
+ }
1259
+ if (options.mode === "install") {
1260
+ await validateInstallConflicts(targetDir, plan, existingMetas);
1261
+ } else if (previousMeta) {
1262
+ await validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta);
1263
+ }
1264
+ const removedFiles = previousMeta ? await removeObsoleteFiles(targetDir, previousMeta, new Set(plan.files.map((file) => file.targetPath))) : [];
1265
+ await writePlannedFiles(targetDir, plan.files);
1266
+ const installedFiles = [];
1267
+ for (const plannedFile of plan.files) {
1268
+ installedFiles.push(
1269
+ await readFileMeta(targetDir, plannedFile.targetPath, plannedFile.memberName, plannedFile.memberType)
1270
+ );
1271
+ }
1272
+ const meta = buildInstalledAddonMeta({
1273
+ registry: options.registry,
1274
+ manifest: plan.manifest,
1275
+ applicationType: plan.applicationType,
1276
+ organizationCode: options.organizationCode,
1277
+ installParameters: plan.installParameters,
1278
+ members: plan.members,
1279
+ files: installedFiles,
1280
+ installedAt: previousMeta?.installedAt
1281
+ });
1282
+ await ensureParentDirectory(plan.metaPath);
1283
+ await writeFile(plan.metaPath, JSON.stringify(meta, null, 2));
1284
+ const nextMetas = existingMetas.filter((item) => item.name !== meta.name).concat(meta);
1285
+ await rebuildRegistryFiles(targetDir, plan.applicationType, nextMetas.filter((item) => item.applicationType === plan.applicationType));
1286
+ return {
1287
+ meta,
1288
+ writtenFiles: installedFiles.map((file) => file.path),
1289
+ removedFiles
1290
+ };
1291
+ }
1292
+ async function installAddonFromExtractedDirectory(options) {
1293
+ return await materializeAddon({
1294
+ ...options,
1295
+ mode: "install"
1296
+ });
1297
+ }
1298
+ async function upgradeAddonFromExtractedDirectory(options) {
1299
+ return await materializeAddon({
1300
+ ...options,
1301
+ mode: "upgrade"
1302
+ });
1303
+ }
1304
+
1305
+ // src/marketplace/addons.ts
1306
+ function createOrganizationHeaders(organizationCode) {
1307
+ if (!organizationCode) {
1308
+ return void 0;
1309
+ }
1310
+ return {
1311
+ "x-organization-code": organizationCode
1312
+ };
1313
+ }
1314
+ function parseAddonSpecifier(specifier) {
1315
+ const trimmed = specifier.trim();
1316
+ if (!trimmed) {
1317
+ throw new Error("Addon specifier cannot be empty");
1318
+ }
1319
+ const atIndex = trimmed.lastIndexOf("@");
1320
+ if (atIndex <= 0) {
1321
+ return { name: trimmed };
1322
+ }
1323
+ const name = trimmed.slice(0, atIndex);
1324
+ const version = trimmed.slice(atIndex + 1);
1325
+ if (!version) {
1326
+ return { name };
1327
+ }
1328
+ return { name, version };
1329
+ }
1330
+ async function searchAddons(registry, options) {
1331
+ const query = new URLSearchParams();
1332
+ if (options.query) query.set("query", options.query);
1333
+ if (options.applicationType) query.set("applicationType", options.applicationType);
1334
+ if (options.phase) query.set("phase", options.phase);
1335
+ if (options.memberType) query.set("memberType", options.memberType);
1336
+ if (options.scope) query.set("scope", options.scope);
1337
+ if (options.page) query.set("page", String(options.page));
1338
+ if (options.pageSize) query.set("pageSize", String(options.pageSize));
1339
+ return await requestJson(registry, `/api/addons?${query.toString()}`, {
1340
+ method: "GET",
1341
+ headers: createOrganizationHeaders(options.organizationCode),
1342
+ unwrapData: true
1343
+ });
1344
+ }
1345
+ async function getAddon(registry, name, organizationCode) {
1346
+ return await requestJson(registry, `/api/addons/${encodeURIComponent(name)}`, {
1347
+ method: "GET",
1348
+ headers: createOrganizationHeaders(organizationCode),
1349
+ unwrapData: true
1350
+ });
1351
+ }
1352
+ async function listAddonVersions(registry, name, organizationCode) {
1353
+ return await requestJson(registry, `/api/addons/${encodeURIComponent(name)}/versions`, {
1354
+ method: "GET",
1355
+ headers: createOrganizationHeaders(organizationCode),
1356
+ unwrapData: true
1357
+ });
1358
+ }
1359
+ async function getAddonVersion(registry, name, version, organizationCode) {
1360
+ return await requestJson(
1361
+ registry,
1362
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}`,
1363
+ {
1364
+ method: "GET",
1365
+ headers: createOrganizationHeaders(organizationCode),
1366
+ unwrapData: true
1367
+ }
1368
+ );
1369
+ }
1370
+ async function listAddonMembers(registry, name, version, options = {}) {
1371
+ const query = new URLSearchParams();
1372
+ if (options.type) query.set("type", options.type);
1373
+ if (options.memberName) query.set("name", options.memberName);
1374
+ const suffix = query.toString() ? `?${query.toString()}` : "";
1375
+ return await requestJson(
1376
+ registry,
1377
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/members${suffix}`,
1378
+ {
1379
+ method: "GET",
1380
+ headers: createOrganizationHeaders(options.organizationCode),
1381
+ unwrapData: true
1382
+ }
1383
+ );
1384
+ }
1385
+ async function getAddonMemberContent(registry, name, version, memberName, organizationCode) {
1386
+ return await requestJson(
1387
+ registry,
1388
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/members/${encodeURIComponent(memberName)}/content`,
1389
+ {
1390
+ method: "GET",
1391
+ headers: createOrganizationHeaders(organizationCode),
1392
+ unwrapData: true
1393
+ }
1394
+ );
1395
+ }
1396
+ async function getAddonPackageUrl(registry, name, version, organizationCode) {
1397
+ return await requestJson(
1398
+ registry,
1399
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/package-url`,
1400
+ {
1401
+ method: "POST",
1402
+ headers: createOrganizationHeaders(organizationCode),
1403
+ unwrapData: true
1404
+ }
1405
+ );
1406
+ }
1407
+ async function downloadAddonArchiveBuffer(registry, name, version, organizationCode) {
1408
+ const packageUrl = await getAddonPackageUrl(registry, name, version, organizationCode);
1409
+ return await requestBuffer(registry, packageUrl.url, {
1410
+ method: "GET",
1411
+ headers: createOrganizationHeaders(organizationCode)
1412
+ });
1413
+ }
1414
+ async function publishAddon(options) {
1415
+ const sourcePath = resolve(options.sourcePath ?? process.cwd());
1416
+ const isArchive = sourcePath.endsWith(".tgz") || sourcePath.endsWith(".tar.gz");
1417
+ let archiveBuffer;
1418
+ let archiveName;
1419
+ let manifestDir = null;
1420
+ let tempArchiveDir = null;
1421
+ try {
1422
+ if (isArchive) {
1423
+ archiveBuffer = await readFile(sourcePath);
1424
+ archiveName = basename(sourcePath);
1425
+ manifestDir = await extractAddonArchiveFile(sourcePath);
1426
+ } else {
1427
+ const packaged = await packageAddonDirectory(sourcePath);
1428
+ archiveBuffer = packaged.buffer;
1429
+ archiveName = basename(packaged.archivePath);
1430
+ manifestDir = sourcePath;
1431
+ tempArchiveDir = dirname(packaged.archivePath);
1432
+ }
1433
+ const manifest = await loadAddonManifestFromDirectory(manifestDir);
1434
+ const digest = sha256(archiveBuffer);
1435
+ return await withAccessToken(options.registry, async (accessToken) => {
1436
+ const headers = {
1437
+ Authorization: `Bearer ${accessToken}`,
1438
+ ...options.organizationCode ? { "x-organization-code": options.organizationCode } : {}
1439
+ };
1440
+ const session = await requestJson(options.registry, "/api/addons/publish-sessions", {
1441
+ method: "POST",
1442
+ headers,
1443
+ body: {
1444
+ name: manifest.name,
1445
+ version: manifest.version,
1446
+ fileName: archiveName,
1447
+ contentLength: archiveBuffer.length,
1448
+ digest
1449
+ },
1450
+ unwrapData: true
1451
+ });
1452
+ const formData = new FormData();
1453
+ formData.set("file", new Blob([archiveBuffer], { type: "application/gzip" }), archiveName);
1454
+ await requestJson(
1455
+ options.registry,
1456
+ `/api/addons/publish-sessions/${encodeURIComponent(session.sessionId)}/file`,
1457
+ {
1458
+ method: "POST",
1459
+ headers,
1460
+ body: formData,
1461
+ unwrapData: true
1462
+ }
1463
+ );
1464
+ return await requestJson(
1465
+ options.registry,
1466
+ `/api/addons/${encodeURIComponent(manifest.name)}/versions`,
1467
+ {
1468
+ method: "POST",
1469
+ headers,
1470
+ body: {
1471
+ sessionId: session.sessionId,
1472
+ ...options.scope ? { scope: options.scope } : {}
1473
+ },
1474
+ unwrapData: true
1475
+ }
1476
+ );
1477
+ });
1478
+ } finally {
1479
+ if (tempArchiveDir) {
1480
+ await removeTempDirectory(tempArchiveDir).catch(() => void 0);
1481
+ }
1482
+ if (isArchive && manifestDir) {
1483
+ await removeTempDirectory(manifestDir).catch(() => void 0);
1484
+ }
1485
+ }
1486
+ }
1487
+ async function updateAddonStatus(options) {
1488
+ return await withAccessToken(options.registry, async (accessToken) => {
1489
+ return await requestJson(
1490
+ options.registry,
1491
+ `/api/addons/${encodeURIComponent(options.name)}/status`,
1492
+ {
1493
+ method: "PATCH",
1494
+ headers: {
1495
+ Authorization: `Bearer ${accessToken}`,
1496
+ ...options.organizationCode ? { "x-organization-code": options.organizationCode } : {}
1497
+ },
1498
+ body: {
1499
+ status: options.status
1500
+ },
1501
+ unwrapData: true
1502
+ }
1503
+ );
1504
+ });
1505
+ }
1506
+ async function deleteAddon(options) {
1507
+ return await withAccessToken(options.registry, async (accessToken) => {
1508
+ return await requestJson(
1509
+ options.registry,
1510
+ `/api/addons/${encodeURIComponent(options.name)}`,
1511
+ {
1512
+ method: "DELETE",
1513
+ headers: {
1514
+ Authorization: `Bearer ${accessToken}`,
1515
+ ...options.organizationCode ? { "x-organization-code": options.organizationCode } : {}
1516
+ },
1517
+ unwrapData: true
1518
+ }
1519
+ );
1520
+ });
1521
+ }
1522
+ async function resolveInstallVersion(registry, name, requestedVersion, organizationCode) {
1523
+ if (requestedVersion) {
1524
+ return requestedVersion;
1525
+ }
1526
+ const detail = await getAddon(registry, name, organizationCode);
1527
+ const version = detail.latestVersion?.version;
1528
+ if (!version) {
1529
+ throw new Error(`Addon ${name} has no published version`);
1530
+ }
1531
+ return version;
1532
+ }
1533
+ async function installAddonFromRegistry(options) {
1534
+ const { name, version: requestedVersion } = parseAddonSpecifier(options.specifier);
1535
+ const version = await resolveInstallVersion(options.registry, name, requestedVersion, options.organizationCode);
1536
+ const archiveBuffer = await downloadAddonArchiveBuffer(options.registry, name, version, options.organizationCode);
1537
+ const extractedDir = await extractAddonArchiveBuffer(archiveBuffer);
1538
+ try {
1539
+ return await installAddonFromExtractedDirectory({
1540
+ registry: options.registry,
1541
+ targetDir: options.targetDir,
1542
+ extractedDir,
1543
+ applicationType: options.applicationType,
1544
+ organizationCode: options.organizationCode,
1545
+ installParameters: options.installParameters
1546
+ });
1547
+ } finally {
1548
+ await removeTempDirectory(extractedDir).catch(() => void 0);
1549
+ }
1550
+ }
1551
+ async function upgradeAddonFromRegistry(options) {
1552
+ const { name, version: requestedVersion } = parseAddonSpecifier(options.specifier);
1553
+ const version = await resolveInstallVersion(options.registry, name, requestedVersion, options.organizationCode);
1554
+ const archiveBuffer = await downloadAddonArchiveBuffer(options.registry, name, version, options.organizationCode);
1555
+ const extractedDir = await extractAddonArchiveBuffer(archiveBuffer);
1556
+ try {
1557
+ return await upgradeAddonFromExtractedDirectory({
1558
+ registry: options.registry,
1559
+ targetDir: options.targetDir,
1560
+ extractedDir,
1561
+ applicationType: options.applicationType,
1562
+ organizationCode: options.organizationCode,
1563
+ installParameters: options.installParameters
1564
+ });
1565
+ } finally {
1566
+ await removeTempDirectory(extractedDir).catch(() => void 0);
1567
+ }
1568
+ }
1569
+
1570
+ // src/marketplace/registry.ts
1571
+ var REGISTRY_ALIASES = {
1572
+ helige: "https://www.helige.cn",
1573
+ "helige-int": "https://www.helige-int.cn"
1574
+ };
1575
+ var DEFAULT_REGISTRY_ALIAS = "helige";
1576
+ var DEFAULT_REGISTRY_ENV = "AMASTER_CLI_REGISTRY";
1577
+ function normalizeRegistryUrl(input) {
1578
+ const trimmed = input.trim();
1579
+ if (!trimmed) {
1580
+ throw new Error("Registry cannot be empty");
1581
+ }
1582
+ const aliased = REGISTRY_ALIASES[trimmed] ?? trimmed;
1583
+ const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(aliased);
1584
+ const inferredProtocol = inferRegistryProtocol(aliased);
1585
+ const withProtocol = hasProtocol ? aliased : inferredProtocol ? `${inferredProtocol}://${aliased}` : "";
1586
+ if (!withProtocol) {
1587
+ const known = Object.keys(REGISTRY_ALIASES).join(", ");
1588
+ throw new Error(`Unsupported registry: ${trimmed}. Use one of: ${known}, or provide a full URL.`);
1589
+ }
1590
+ let url;
1591
+ try {
1592
+ url = new URL(withProtocol);
1593
+ } catch {
1594
+ throw new Error(`Invalid registry URL: ${trimmed}`);
1595
+ }
1596
+ if (url.protocol === "https:" && (url.hostname === "helige.cn" || url.hostname === "helige-int.cn")) {
1597
+ url.hostname = `www.${url.hostname}`;
1598
+ }
1599
+ url.pathname = url.pathname.replace(/\/+$/, "");
1600
+ url.search = "";
1601
+ url.hash = "";
1602
+ return url.toString().replace(/\/$/, "");
1603
+ }
1604
+ function inferRegistryProtocol(input) {
1605
+ const hostname = input.split("/")[0]?.toLowerCase() ?? "";
1606
+ if (hostname === "localhost" || hostname.startsWith("localhost:") || hostname === "127.0.0.1" || hostname.startsWith("127.0.0.1:") || hostname === "::1" || hostname.endsWith(".local")) {
1607
+ return "http";
1608
+ }
1609
+ if (!input.includes(".")) {
1610
+ return "";
1611
+ }
1612
+ return "https";
1613
+ }
1614
+ function resolveRegistry(input) {
1615
+ if (input) {
1616
+ return normalizeRegistryUrl(input);
1617
+ }
1618
+ const envRegistry = process.env[DEFAULT_REGISTRY_ENV];
1619
+ if (envRegistry?.trim()) {
1620
+ return normalizeRegistryUrl(envRegistry);
1621
+ }
1622
+ return normalizeRegistryUrl(DEFAULT_REGISTRY_ALIAS);
1623
+ }
8
1624
  var DEFAULT_ROUTES_FILE = "src/routes.tsx";
9
1625
  var REACT_VITE_DEV_TIMEOUT = 15e3;
10
1626
  var REACT_VITE_BUILD_TIMEOUT = 3e4;
@@ -239,7 +1855,7 @@ async function runAstCheck(options) {
239
1855
  if (options.stack !== "react-vite") {
240
1856
  throw new Error(`AST check is not supported for stack: ${options.stack}`);
241
1857
  }
242
- const { parse, Lang } = await import('@ast-grep/napi');
1858
+ const { parse: parse2, Lang } = await import('@ast-grep/napi');
243
1859
  const RED = "\x1B[31m";
244
1860
  const YELLOW = "\x1B[33m";
245
1861
  const GREEN = "\x1B[32m";
@@ -257,8 +1873,8 @@ async function runAstCheck(options) {
257
1873
  }
258
1874
  const full = join(dir, entry);
259
1875
  try {
260
- const stat = statSync(full);
261
- if (stat.isDirectory()) {
1876
+ const stat3 = statSync(full);
1877
+ if (stat3.isDirectory()) {
262
1878
  files2.push(...findFiles(full, extensions));
263
1879
  } else if (extensions.includes(extname(full))) {
264
1880
  files2.push(full);
@@ -512,7 +2128,7 @@ async function runAstCheck(options) {
512
2128
  for (const file of files) {
513
2129
  try {
514
2130
  const code = readFileSync(file, "utf8");
515
- const ast = parse(Lang.Tsx, code);
2131
+ const ast = parse2(Lang.Tsx, code);
516
2132
  const root = ast.root();
517
2133
  const issues = [
518
2134
  ...checkSelectItemEmptyValue(root),
@@ -837,7 +2453,7 @@ function printBuildError(result) {
837
2453
  }
838
2454
  function runReactViteDevCheck(cwd) {
839
2455
  return new Promise((resolvePromise) => {
840
- let stdout = "";
2456
+ let stdout2 = "";
841
2457
  let stderr = "";
842
2458
  let lastOut = Date.now();
843
2459
  let interval = null;
@@ -850,8 +2466,8 @@ function runReactViteDevCheck(cwd) {
850
2466
  });
851
2467
  vite.stdout.on("data", (chunk) => {
852
2468
  const text = chunk.toString();
853
- if (stdout.length < REACT_VITE_MAX_OUTPUT) {
854
- stdout += text;
2469
+ if (stdout2.length < REACT_VITE_MAX_OUTPUT) {
2470
+ stdout2 += text;
855
2471
  }
856
2472
  lastOut = Date.now();
857
2473
  if (!scanning && (text.includes("VITE") || text.includes("vite") || /ready in \d+/i.test(text) || /Local:.*http/i.test(text))) {
@@ -893,13 +2509,13 @@ function runReactViteDevCheck(cwd) {
893
2509
  if (interval) {
894
2510
  clearInterval(interval);
895
2511
  }
896
- const output = stdout + stderr;
2512
+ const output = stdout2 + stderr;
897
2513
  const hasError = containsBuildError(stderr) || code !== 0 && code !== null && !timeoutReached;
898
2514
  if (timeoutReached) {
899
2515
  resolvePromise({ success: false, reason: "timeout", output });
900
2516
  } else if (hasError) {
901
2517
  resolvePromise({ success: false, reason: "error", output, stderr });
902
- } else if (scanning || /VITE|vite|ready|Local:/i.test(stdout)) {
2518
+ } else if (scanning || /VITE|vite|ready|Local:/i.test(stdout2)) {
903
2519
  resolvePromise({ success: true, output });
904
2520
  } else {
905
2521
  resolvePromise({ success: false, reason: "unknown", output });
@@ -916,7 +2532,7 @@ function runReactViteDevCheck(cwd) {
916
2532
  }
917
2533
  function runReactViteBuildCheckProcess(cwd) {
918
2534
  return new Promise((resolvePromise) => {
919
- let stdout = "";
2535
+ let stdout2 = "";
920
2536
  let stderr = "";
921
2537
  let timeoutReached = false;
922
2538
  const vite = spawn(
@@ -929,8 +2545,8 @@ function runReactViteBuildCheckProcess(cwd) {
929
2545
  }
930
2546
  );
931
2547
  vite.stdout.on("data", (chunk) => {
932
- if (stdout.length < REACT_VITE_MAX_OUTPUT) {
933
- stdout += chunk.toString();
2548
+ if (stdout2.length < REACT_VITE_MAX_OUTPUT) {
2549
+ stdout2 += chunk.toString();
934
2550
  }
935
2551
  });
936
2552
  vite.stderr.on("data", (chunk) => {
@@ -950,7 +2566,7 @@ function runReactViteBuildCheckProcess(cwd) {
950
2566
  }, REACT_VITE_BUILD_TIMEOUT);
951
2567
  vite.on("close", (code) => {
952
2568
  clearTimeout(timeout);
953
- const output = stdout + stderr;
2569
+ const output = stdout2 + stderr;
954
2570
  const hasStderrError = containsBuildError(stderr);
955
2571
  if (timeoutReached) {
956
2572
  resolvePromise({ success: false, reason: "timeout", output, stderr, code: null });
@@ -1005,7 +2621,7 @@ function runTaroBuildCheck(cwd) {
1005
2621
  console.log("Note: Taro build only checks files that are actually imported/referenced.\n");
1006
2622
  console.log("Running: taro build --type h5\n");
1007
2623
  return new Promise((resolvePromise, rejectPromise) => {
1008
- let stdout = "";
2624
+ let stdout2 = "";
1009
2625
  let stderr = "";
1010
2626
  let timeoutReached = false;
1011
2627
  const taro = spawn("npx", ["taro", "build", "--type", "h5"], {
@@ -1015,8 +2631,8 @@ function runTaroBuildCheck(cwd) {
1015
2631
  });
1016
2632
  taro.stdout.on("data", (chunk) => {
1017
2633
  const text = chunk.toString();
1018
- if (stdout.length < TARO_MAX_OUTPUT) {
1019
- stdout += text;
2634
+ if (stdout2.length < TARO_MAX_OUTPUT) {
2635
+ stdout2 += text;
1020
2636
  }
1021
2637
  process.stdout.write(text);
1022
2638
  });
@@ -1039,9 +2655,9 @@ function runTaroBuildCheck(cwd) {
1039
2655
  }, TARO_BUILD_TIMEOUT);
1040
2656
  taro.on("close", (code) => {
1041
2657
  clearTimeout(timeout);
1042
- const output = stdout + stderr;
2658
+ const output = stdout2 + stderr;
1043
2659
  const hasStderrError = containsBuildError(stderr);
1044
- const hasStdoutError = containsBuildError(stdout);
2660
+ const hasStdoutError = containsBuildError(stdout2);
1045
2661
  if (!timeoutReached && code === 0 && !hasStderrError && !hasStdoutError) {
1046
2662
  console.log("\n\u2705 No build errors detected\n");
1047
2663
  resolvePromise();
@@ -1185,91 +2801,342 @@ async function runPreCommitCheck(options) {
1185
2801
  }
1186
2802
 
1187
2803
  // src/cli.ts
1188
- function printUsage() {
1189
- console.error("Usage:");
1190
- console.error(" amaster-cli check route [--cwd <path>] [--routes-file <path>]");
1191
- console.error(" amaster-cli check ast --stack react-vite [--cwd <path>]");
1192
- console.error(" amaster-cli check type --stack <react-vite|taro> [--cwd <path>]");
1193
- console.error(" amaster-cli check build --stack <react-vite|taro> [--cwd <path>]");
1194
- console.error(" amaster-cli check all --stack <react-vite|taro> [--cwd <path>]");
1195
- }
1196
- function parseArgs(argv) {
1197
- const args = [...argv];
1198
- let cwd;
1199
- let routesFile;
1200
- let stack;
1201
- while (args.length > 0) {
1202
- const arg = args.shift();
1203
- if (arg === "--cwd") {
1204
- cwd = args.shift();
1205
- continue;
2804
+ function resolveCliVersion() {
2805
+ try {
2806
+ const packageJsonUrl = new URL("../package.json", import.meta.url);
2807
+ return JSON.parse(readFileSync(packageJsonUrl, "utf-8")).version || "0.0.0";
2808
+ } catch {
2809
+ return "0.0.0";
2810
+ }
2811
+ }
2812
+ function renderOutput(data, options = {}) {
2813
+ if (options.json || typeof data === "string") {
2814
+ if (typeof data === "string") {
2815
+ console.log(data);
2816
+ return;
1206
2817
  }
1207
- if (arg === "--routes-file") {
1208
- routesFile = args.shift();
1209
- continue;
2818
+ console.log(JSON.stringify(data, null, 2));
2819
+ return;
2820
+ }
2821
+ console.dir(data, { depth: null, colors: true });
2822
+ }
2823
+ function shouldRenderJsonError(argv) {
2824
+ return argv.includes("--json");
2825
+ }
2826
+ function renderError(error, options = {}) {
2827
+ if (isAddonInstallConflictError(error)) {
2828
+ if (options.json) {
2829
+ console.log(JSON.stringify(error.toJSON(), null, 2));
2830
+ return;
1210
2831
  }
1211
- if (arg === "--stack") {
1212
- const value = args.shift();
1213
- if (value !== "react-vite" && value !== "taro") {
1214
- throw new Error(`Unsupported stack: ${value}`);
1215
- }
1216
- stack = value;
1217
- continue;
2832
+ console.error(`${error.message}:`);
2833
+ for (const conflict of error.conflicts) {
2834
+ const owner = conflict.ownerAddon ? ` owner=${conflict.ownerAddon}` : "";
2835
+ const member = conflict.memberName ? ` member=${conflict.memberName}` : "";
2836
+ console.error(`- [${conflict.kind}] ${conflict.path}${member}${owner}`);
1218
2837
  }
1219
- throw new Error(`Unknown argument: ${arg}`);
2838
+ console.error("Run again with --json for MCP/AI-readable conflict details.");
2839
+ return;
1220
2840
  }
1221
- return { cwd, routesFile, stack };
2841
+ const message = error instanceof Error ? error.message : String(error);
2842
+ if (options.json) {
2843
+ console.log(JSON.stringify({ success: false, code: "CLI_ERROR", message }, null, 2));
2844
+ return;
2845
+ }
2846
+ console.error(message);
1222
2847
  }
1223
- async function main() {
1224
- const [command, target, ...rest] = process.argv.slice(2);
2848
+ async function promptForMissingCredentials(input) {
2849
+ if ((input.email || input.username) && input.password) {
2850
+ return {
2851
+ email: input.email,
2852
+ username: input.username,
2853
+ password: input.password
2854
+ };
2855
+ }
2856
+ if (!stdin.isTTY || !stdout.isTTY) {
2857
+ throw new Error("Missing login credentials. Provide --email/--username and --password in non-interactive mode.");
2858
+ }
2859
+ const rl = createInterface({ input: stdin, output: stdout });
1225
2860
  try {
1226
- if (command !== "check") {
1227
- printUsage();
1228
- process.exit(1);
1229
- }
1230
- const options = parseArgs(rest);
1231
- if (target === "route") {
1232
- checkRouteConfig(options);
1233
- console.log("\u2705 Home route found in the default-exported routes config");
1234
- return;
1235
- }
1236
- if (target === "all") {
1237
- if (!options.stack) {
1238
- throw new Error("Missing required argument: --stack <react-vite|taro>");
2861
+ let email = input.email;
2862
+ let username = input.username;
2863
+ if (!email && !username) {
2864
+ const login = (await rl.question("Email or username: ")).trim();
2865
+ if (login.includes("@")) {
2866
+ email = login;
2867
+ } else {
2868
+ username = login;
1239
2869
  }
1240
- await runPreCommitCheck({ cwd: options.cwd, stack: options.stack });
1241
- return;
1242
2870
  }
1243
- if (target === "type") {
1244
- if (!options.stack) {
1245
- throw new Error("Missing required argument: --stack <react-vite|taro>");
1246
- }
1247
- await runTypeCheck({ cwd: options.cwd, stack: options.stack });
1248
- return;
2871
+ const password = input.password ?? await rl.question("Password: ");
2872
+ if (!password) {
2873
+ throw new Error("Password is required");
1249
2874
  }
1250
- if (target === "ast") {
1251
- if (!options.stack) {
1252
- throw new Error("Missing required argument: --stack <react-vite|taro>");
1253
- }
1254
- runAstCheck({ cwd: options.cwd, stack: options.stack });
1255
- return;
2875
+ return { email, username, password };
2876
+ } finally {
2877
+ rl.close();
2878
+ }
2879
+ }
2880
+ function parseKeyValuePairs(values) {
2881
+ if (!values?.length) {
2882
+ return void 0;
2883
+ }
2884
+ const result = {};
2885
+ for (const value of values) {
2886
+ const separatorIndex = value.indexOf("=");
2887
+ if (separatorIndex <= 0) {
2888
+ throw new Error(`Invalid --set value: ${value}. Expected key=value.`);
1256
2889
  }
1257
- if (target === "build") {
1258
- if (!options.stack) {
1259
- throw new Error("Missing required argument: --stack <react-vite|taro>");
1260
- }
1261
- await runBuildCheck({ cwd: options.cwd, stack: options.stack });
1262
- return;
2890
+ const key = value.slice(0, separatorIndex).trim();
2891
+ const parsedValue = value.slice(separatorIndex + 1).trim();
2892
+ if (!key) {
2893
+ throw new Error(`Invalid --set value: ${value}. Key cannot be empty.`);
1263
2894
  }
1264
- printUsage();
1265
- process.exit(1);
1266
- } catch (error) {
1267
- console.error("\u274C Check failed.\n");
1268
- const message = error instanceof Error ? error.message : String(error);
1269
- console.error(message);
1270
- process.exit(1);
2895
+ result[key] = parsedValue;
2896
+ }
2897
+ return result;
2898
+ }
2899
+ function addRegistryOption(command) {
2900
+ return command.option("--registry <registry>", "Registry alias or URL, default: helige");
2901
+ }
2902
+ function addOrganizationOption(command) {
2903
+ return command.option("--organization-code <code>", "Organization code");
2904
+ }
2905
+ function addJsonOption(command) {
2906
+ return command.option("--json", "Output JSON");
2907
+ }
2908
+ function resolveRegistryFromOptions(options) {
2909
+ return resolveRegistry(options.registry);
2910
+ }
2911
+ function getUserStringField(user, key) {
2912
+ const value = user?.[key];
2913
+ return typeof value === "string" && value ? value : void 0;
2914
+ }
2915
+ function formatLoginIdentity(user) {
2916
+ return getUserStringField(user, "email") ?? getUserStringField(user, "username") ?? getUserStringField(user, "preferred_username") ?? getUserStringField(user, "name") ?? getUserStringField(user, "sub") ?? "unknown user";
2917
+ }
2918
+ function resolveAddonTargetDir(target) {
2919
+ return target ? target : resolveNearestPackageRoot();
2920
+ }
2921
+ function requireStack(value) {
2922
+ if (value === "react-vite" || value === "taro") {
2923
+ return value;
1271
2924
  }
2925
+ throw new Error("Missing required argument: --stack <react-vite|taro>");
1272
2926
  }
1273
- main();
2927
+ var program = new Command();
2928
+ program.name("amaster-cli").description("AMaster CLI").version(resolveCliVersion()).showHelpAfterError();
2929
+ addJsonOption(addRegistryOption(program.command("login").description("Login to an AMaster registry"))).option("--browser", "Login with browser OAuth flow").option("-e, --email <email>", "Email").option("-u, --username <username>", "Username").option("-p, --password <password>", "Password").action(async (options) => {
2930
+ const registry = resolveRegistryFromOptions(options);
2931
+ const session = options.browser ? await loginWithBrowser({ registry }) : await (async () => {
2932
+ const credentials = await promptForMissingCredentials({
2933
+ email: options.email,
2934
+ username: options.username,
2935
+ password: options.password
2936
+ });
2937
+ return await loginWithPassword({
2938
+ registry,
2939
+ email: credentials.email,
2940
+ username: credentials.username,
2941
+ password: credentials.password
2942
+ });
2943
+ })();
2944
+ const result = {
2945
+ registry,
2946
+ user: session.user ?? null,
2947
+ expiresAt: session.expiresAt ?? null
2948
+ };
2949
+ renderOutput(options.json ? result : `Login succeeded: ${formatLoginIdentity(session.user)} (${registry})`, options);
2950
+ });
2951
+ addJsonOption(addRegistryOption(program.command("logout").description("Clear the local AMaster registry session"))).action(
2952
+ async (options) => {
2953
+ const registry = resolveRegistryFromOptions(options);
2954
+ logout(registry);
2955
+ renderOutput(
2956
+ {
2957
+ registry,
2958
+ loggedOut: true
2959
+ },
2960
+ options
2961
+ );
2962
+ }
2963
+ );
2964
+ addJsonOption(addRegistryOption(program.command("whoami").description("Show the current AMaster registry session"))).action(
2965
+ async (options) => {
2966
+ const registry = resolveRegistryFromOptions(options);
2967
+ const user = await getCurrentUser(registry);
2968
+ renderOutput(
2969
+ {
2970
+ registry,
2971
+ user
2972
+ },
2973
+ options
2974
+ );
2975
+ }
2976
+ );
2977
+ var addon = program.command("addon").description("Addon marketplace commands");
2978
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("search [query]").description("Search addons")))).option("--application-type <type>", "Application type").option("--phase <phase>", "Phase filter").option("--member-type <type>", "Member type filter").option("--scope <scope>", "Scope filter").option("--page <page>", "Page number", (value) => Number.parseInt(value, 10)).option("--page-size <pageSize>", "Page size", (value) => Number.parseInt(value, 10)).action(async (query, options) => {
2979
+ const registry = resolveRegistryFromOptions(options);
2980
+ const applicationType = options.applicationType ?? await tryDetectNearestApplicationType();
2981
+ const result = await searchAddons(registry, {
2982
+ query,
2983
+ applicationType,
2984
+ phase: options.phase,
2985
+ memberType: options.memberType,
2986
+ scope: options.scope,
2987
+ page: options.page,
2988
+ pageSize: options.pageSize,
2989
+ organizationCode: options.organizationCode
2990
+ });
2991
+ renderOutput(result, options);
2992
+ });
2993
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("view <specifier>").description("View addon or addon version details")))).action(async (specifier, options) => {
2994
+ const registry = resolveRegistryFromOptions(options);
2995
+ const { name, version } = parseAddonSpecifier(specifier);
2996
+ const result = version ? await getAddonVersion(registry, name, version, options.organizationCode) : await getAddon(registry, name, options.organizationCode);
2997
+ renderOutput(result, options);
2998
+ });
2999
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("versions <name>").description("List addon versions")))).action(
3000
+ async (name, options) => {
3001
+ const registry = resolveRegistryFromOptions(options);
3002
+ const result = await listAddonVersions(registry, name, options.organizationCode);
3003
+ renderOutput(result, options);
3004
+ }
3005
+ );
3006
+ addJsonOption(
3007
+ addOrganizationOption(addRegistryOption(addon.command("members <specifier>").description("List addon members")))
3008
+ ).option("--type <type>", "Member type filter").option("--name <memberName>", "Member name filter").action(async (specifier, options) => {
3009
+ const registry = resolveRegistryFromOptions(options);
3010
+ const { name, version } = parseAddonSpecifier(specifier);
3011
+ if (!version) {
3012
+ throw new Error("Member queries require an explicit version, e.g. addon members crm-pages@1.0.0");
3013
+ }
3014
+ const result = await listAddonMembers(registry, name, version, {
3015
+ type: options.type,
3016
+ memberName: options.name,
3017
+ organizationCode: options.organizationCode
3018
+ });
3019
+ renderOutput(result, options);
3020
+ });
3021
+ addJsonOption(
3022
+ addOrganizationOption(
3023
+ addRegistryOption(addon.command("content <specifier> <memberName>").description("Read addon member content"))
3024
+ )
3025
+ ).action(async (specifier, memberName, options) => {
3026
+ const registry = resolveRegistryFromOptions(options);
3027
+ const { name, version } = parseAddonSpecifier(specifier);
3028
+ if (!version) {
3029
+ throw new Error("Member content queries require an explicit version, e.g. addon content crm-pages@1.0.0 lead-summary");
3030
+ }
3031
+ const result = await getAddonMemberContent(registry, name, version, memberName, options.organizationCode);
3032
+ renderOutput(options.json ? result : result.content, options);
3033
+ });
3034
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("publish [sourcePath]").description("Publish an addon directory or .tgz archive")))).addOption(new Option("--scope <scope>", "Publish scope").choices(["official", "organization"])).action(async (sourcePath, options) => {
3035
+ const registry = resolveRegistryFromOptions(options);
3036
+ const result = await publishAddon({
3037
+ registry,
3038
+ sourcePath,
3039
+ scope: options.scope,
3040
+ organizationCode: options.organizationCode
3041
+ });
3042
+ renderOutput(result, options);
3043
+ });
3044
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("activate <name>").description("Activate an addon")))).action(async (name, options) => {
3045
+ const registry = resolveRegistryFromOptions(options);
3046
+ const result = await updateAddonStatus({
3047
+ registry,
3048
+ name,
3049
+ status: "active",
3050
+ organizationCode: options.organizationCode
3051
+ });
3052
+ renderOutput(options.json ? result : `Addon activated: ${result.name}`, options);
3053
+ });
3054
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("deactivate <name>").description("Deactivate an addon")))).action(async (name, options) => {
3055
+ const registry = resolveRegistryFromOptions(options);
3056
+ const result = await updateAddonStatus({
3057
+ registry,
3058
+ name,
3059
+ status: "inactive",
3060
+ organizationCode: options.organizationCode
3061
+ });
3062
+ renderOutput(options.json ? result : `Addon deactivated: ${result.name}`, options);
3063
+ });
3064
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("delete <name>").description("Delete an addon")))).action(async (name, options) => {
3065
+ const registry = resolveRegistryFromOptions(options);
3066
+ const result = await deleteAddon({
3067
+ registry,
3068
+ name,
3069
+ organizationCode: options.organizationCode
3070
+ });
3071
+ renderOutput(options.json ? result : `Addon deleted: ${result.name}`, options);
3072
+ });
3073
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("install <specifier>").description("Install an addon into an application")))).option("--target <path>", "Application root directory, defaults to nearest package.json directory").addOption(new Option("--application-type <type>", "Application type").choices(["web", "mini"])).option("--set <key=value>", "Install parameter", (value, previous = []) => previous.concat(value), []).action(async (specifier, options) => {
3074
+ const registry = resolveRegistryFromOptions(options);
3075
+ const result = await installAddonFromRegistry({
3076
+ registry,
3077
+ specifier,
3078
+ targetDir: resolveAddonTargetDir(options.target),
3079
+ applicationType: options.applicationType,
3080
+ organizationCode: options.organizationCode,
3081
+ installParameters: parseKeyValuePairs(options.set)
3082
+ });
3083
+ renderOutput(result, options);
3084
+ });
3085
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("upgrade <specifier>").description("Upgrade an installed addon")))).option("--target <path>", "Application root directory, defaults to nearest package.json directory").addOption(new Option("--application-type <type>", "Application type").choices(["web", "mini"])).option("--set <key=value>", "Install parameter", (value, previous = []) => previous.concat(value), []).action(async (specifier, options) => {
3086
+ const registry = resolveRegistryFromOptions(options);
3087
+ const result = await upgradeAddonFromRegistry({
3088
+ registry,
3089
+ specifier,
3090
+ targetDir: resolveAddonTargetDir(options.target),
3091
+ applicationType: options.applicationType,
3092
+ organizationCode: options.organizationCode,
3093
+ installParameters: parseKeyValuePairs(options.set)
3094
+ });
3095
+ renderOutput(result, options);
3096
+ });
3097
+ addJsonOption(addon.command("list").description("List installed addons in an application")).option("--target <path>", "Application root directory, defaults to nearest package.json directory").action(async (options) => {
3098
+ const installed = await listInstalledAddons(resolveAddonTargetDir(options.target));
3099
+ renderOutput(installed, options);
3100
+ });
3101
+ var check = program.command("check").description("Template guard checks");
3102
+ check.command("route").option("--cwd <path>", "Working directory").option("--routes-file <path>", "Routes file path").action((options) => {
3103
+ checkRouteConfig({
3104
+ cwd: options.cwd,
3105
+ routesFile: options.routesFile
3106
+ });
3107
+ console.log("OK");
3108
+ });
3109
+ check.command("ast").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action((options) => {
3110
+ runAstCheck({
3111
+ cwd: options.cwd,
3112
+ stack: requireStack(options.stack)
3113
+ });
3114
+ console.log("OK");
3115
+ });
3116
+ check.command("type").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action(async (options) => {
3117
+ await runTypeCheck({
3118
+ cwd: options.cwd,
3119
+ stack: requireStack(options.stack)
3120
+ });
3121
+ console.log("OK");
3122
+ });
3123
+ check.command("build").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action(async (options) => {
3124
+ await runBuildCheck({
3125
+ cwd: options.cwd,
3126
+ stack: requireStack(options.stack)
3127
+ });
3128
+ console.log("OK");
3129
+ });
3130
+ check.command("all").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action(async (options) => {
3131
+ await runPreCommitCheck({
3132
+ cwd: options.cwd,
3133
+ stack: requireStack(options.stack)
3134
+ });
3135
+ console.log("OK");
3136
+ });
3137
+ program.parseAsync(process.argv).catch((error) => {
3138
+ renderError(error, { json: shouldRenderJsonError(process.argv) });
3139
+ process.exit(1);
3140
+ });
1274
3141
  //# sourceMappingURL=cli.js.map
1275
3142
  //# sourceMappingURL=cli.js.map