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