@amaster.ai/cli 1.1.28 → 1.1.30

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
@@ -9,8 +9,9 @@ import { randomBytes, createHash, randomUUID } from 'crypto';
9
9
  import { tmpdir, homedir } from 'os';
10
10
  import * as tar from 'tar';
11
11
  import { createServer } from 'http';
12
- import { spawn, spawnSync } from 'child_process';
13
- import YAML from 'yaml';
12
+ import { execFile, spawn, spawnSync } from 'child_process';
13
+ import { promisify } from 'util';
14
+ import YAML2 from 'yaml';
14
15
  import ts from 'typescript';
15
16
 
16
17
  var EXCLUDED_NAMES = /* @__PURE__ */ new Set([".git", "node_modules", ".DS_Store"]);
@@ -554,6 +555,71 @@ function validateAddonManifest(manifest) {
554
555
  if (!Array.isArray(manifest.members)) {
555
556
  throw new Error("addon.json missing members");
556
557
  }
558
+ validateInstallRequirements(manifest);
559
+ validateInstallNpm(manifest);
560
+ }
561
+ function validateInstallRequirements(manifest) {
562
+ const requirements = manifest.install?.requirements;
563
+ if (!requirements) {
564
+ return;
565
+ }
566
+ if (requirements.envs !== void 0 && !Array.isArray(requirements.envs)) {
567
+ throw new Error("addon.json install.requirements.envs must be an array");
568
+ }
569
+ if (requirements.secrets !== void 0 && !Array.isArray(requirements.secrets)) {
570
+ throw new Error("addon.json install.requirements.secrets must be an array");
571
+ }
572
+ for (const item of requirements.envs ?? []) {
573
+ validateRequirementItem(item, "env");
574
+ }
575
+ for (const item of requirements.secrets ?? []) {
576
+ validateRequirementItem(item, "secret");
577
+ if (item.defaultValue !== void 0) {
578
+ throw new Error("addon.json install.requirements.secrets cannot declare defaultValue");
579
+ }
580
+ }
581
+ }
582
+ function validateRequirementItem(item, kind) {
583
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
584
+ throw new Error(`addon.json install.requirements.${kind}s item is invalid`);
585
+ }
586
+ const requirement = item;
587
+ if (typeof requirement.key !== "string" || !requirement.key.trim()) {
588
+ throw new Error(`addon.json install.requirements.${kind}s item missing key`);
589
+ }
590
+ if (requirement.required !== void 0 && typeof requirement.required !== "boolean") {
591
+ throw new Error(`addon.json install.requirements.${kind}s item required must be boolean`);
592
+ }
593
+ if (requirement.description !== void 0 && typeof requirement.description !== "string") {
594
+ throw new Error(`addon.json install.requirements.${kind}s item description must be string`);
595
+ }
596
+ if (requirement.defaultValue !== void 0 && typeof requirement.defaultValue !== "string") {
597
+ throw new Error(`addon.json install.requirements.${kind}s item defaultValue must be string`);
598
+ }
599
+ }
600
+ function validateInstallNpm(manifest) {
601
+ const npm = manifest.install?.npm;
602
+ if (npm === void 0) {
603
+ return;
604
+ }
605
+ if (!npm || typeof npm !== "object" || Array.isArray(npm)) {
606
+ throw new Error("addon.json install.npm must be an object");
607
+ }
608
+ const dependencies = npm.dependencies;
609
+ if (dependencies === void 0) {
610
+ return;
611
+ }
612
+ if (!dependencies || typeof dependencies !== "object" || Array.isArray(dependencies)) {
613
+ throw new Error("addon.json install.npm.dependencies must be an object");
614
+ }
615
+ for (const [name, version] of Object.entries(dependencies)) {
616
+ if (!name.trim()) {
617
+ throw new Error("addon.json install.npm.dependencies contains an empty package name");
618
+ }
619
+ if (typeof version !== "string" || !version.trim()) {
620
+ throw new Error(`addon.json install.npm.dependencies.${name} must be a string`);
621
+ }
622
+ }
557
623
  }
558
624
  function resolveMemberSourcePath(member) {
559
625
  const sourcePath = member.source?.path;
@@ -604,7 +670,7 @@ async function readAppSettingsApplicationType(packageRoot) {
604
670
  if (!existsSync(appSettingsPath)) {
605
671
  return null;
606
672
  }
607
- const parsed = YAML.parse(await readFile(appSettingsPath, "utf8"));
673
+ const parsed = YAML2.parse(await readFile(appSettingsPath, "utf8"));
608
674
  if (parsed?.type === "web" || parsed?.type === "mini") {
609
675
  return parsed.type;
610
676
  }
@@ -639,6 +705,7 @@ async function tryDetectNearestApplicationType(startDir = process.cwd()) {
639
705
  }
640
706
 
641
707
  // src/marketplace/install.ts
708
+ var execFileAsync = promisify(execFile);
642
709
  var AddonInstallConflictError = class extends Error {
643
710
  constructor(input) {
644
711
  super(`Addon ${input.operation} has ${input.conflicts.length} conflict(s)`);
@@ -667,6 +734,18 @@ function isAddonInstallConflictError(error) {
667
734
  function sha256Buffer(buffer) {
668
735
  return `sha256:${createHash("sha256").update(buffer).digest("hex")}`;
669
736
  }
737
+ function stableJsonStringify(value) {
738
+ if (Array.isArray(value)) {
739
+ return `[${value.map((item) => stableJsonStringify(item)).join(",")}]`;
740
+ }
741
+ if (isPlainObject(value)) {
742
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJsonStringify(value[key])}`).join(",")}}`;
743
+ }
744
+ return JSON.stringify(value);
745
+ }
746
+ function sha256Value(value) {
747
+ return sha256Buffer(Buffer.from(stableJsonStringify(value) ?? "undefined"));
748
+ }
670
749
  function ensurePathInsideTarget(targetDir, relativePath) {
671
750
  const absolute = resolve(targetDir, relativePath);
672
751
  const normalizedTarget = resolve(targetDir);
@@ -748,6 +827,31 @@ function resolveInstallParameters(manifest, rawParameters) {
748
827
  }
749
828
  return resolved;
750
829
  }
830
+ function resolveInstallRequirements(manifest) {
831
+ const requirements = manifest.install?.requirements ?? {};
832
+ return {
833
+ envs: requirements.envs?.map((item) => ({ ...item })),
834
+ secrets: requirements.secrets?.map((item) => ({ ...item }))
835
+ };
836
+ }
837
+ function resolveInstallNpm(manifest) {
838
+ const npm = manifest.install?.npm ?? {};
839
+ return {
840
+ dependencies: npm.dependencies ? { ...npm.dependencies } : void 0
841
+ };
842
+ }
843
+ function listNpmDependencies(npm) {
844
+ return Object.entries(npm.dependencies ?? {}).map(([packageName, version]) => ({
845
+ packageName,
846
+ version
847
+ }));
848
+ }
849
+ function buildMissingRequirements(requirements) {
850
+ return {
851
+ envs: requirements.envs?.filter((item) => item.required !== false).map((item) => ({ ...item })),
852
+ secrets: requirements.secrets?.filter((item) => item.required !== false).map((item) => ({ ...item }))
853
+ };
854
+ }
751
855
  function getAddonMetaPath(targetDir, addonName) {
752
856
  return join(targetDir, "src", "addons", addonName, "meta.json");
753
857
  }
@@ -792,6 +896,36 @@ function buildOwnershipMap(metas, excludeAddonName) {
792
896
  }
793
897
  return ownership;
794
898
  }
899
+ async function readPackageJson(targetDir) {
900
+ const packageJsonPath = ensurePathInsideTarget(targetDir, "package.json");
901
+ const parsed = JSON.parse(await readFile(packageJsonPath, "utf8"));
902
+ if (!isPlainObject(parsed)) {
903
+ throw new Error("package.json must contain a JSON object");
904
+ }
905
+ return parsed;
906
+ }
907
+ function readDependencies(packageJson) {
908
+ const value = packageJson.dependencies;
909
+ if (value === void 0) {
910
+ return {};
911
+ }
912
+ if (!isPlainObject(value)) {
913
+ throw new Error("package.json dependencies must be an object");
914
+ }
915
+ const dependencies = {};
916
+ for (const [name, version] of Object.entries(value)) {
917
+ if (typeof version === "string") {
918
+ dependencies[name] = version;
919
+ }
920
+ }
921
+ return dependencies;
922
+ }
923
+ function findPackageDependency(packageJson, packageName) {
924
+ return readDependencies(packageJson)[packageName] ?? null;
925
+ }
926
+ function buildNpmDependencyMap(npm) {
927
+ return new Map(listNpmDependencies(npm).map((item) => [item.packageName, item]));
928
+ }
795
929
  async function collectDirectoryFiles(sourceDir) {
796
930
  const entries = await readdir(sourceDir, { withFileTypes: true });
797
931
  const files = [];
@@ -850,19 +984,37 @@ async function buildInstallPlan(options) {
850
984
  }
851
985
  const installParameters = resolveInstallParameters(manifest, options.installParameters);
852
986
  const files = [];
987
+ const settings = [];
853
988
  const members = [];
854
989
  for (const member of manifest.members) {
855
990
  if (member.type === "skill") {
856
991
  throw new Error(`Member ${member.name} is a runtime skill. Design-time CLI install does not support skill members yet.`);
857
992
  }
858
- if (member.type === "settings") {
859
- throw new Error(`Member ${member.name} is a settings fragment. settings install is not implemented yet.`);
860
- }
861
993
  const sourceRelativePath = resolveMemberSourcePath(member);
862
994
  if (!sourceRelativePath) {
863
995
  throw new Error(`Member ${member.name} is missing source.path`);
864
996
  }
865
997
  await assertPathExists(options.extractedDir, sourceRelativePath);
998
+ if (member.type === "settings") {
999
+ const sourcePath = join(options.extractedDir, sourceRelativePath);
1000
+ const patch = await readYamlObject(sourcePath);
1001
+ settings.push({
1002
+ sourcePath,
1003
+ sourceRelativePath,
1004
+ targetPath: "app.settings.yml",
1005
+ memberName: member.name,
1006
+ memberType: "settings",
1007
+ patch,
1008
+ paths: flattenSettingsPatch(patch)
1009
+ });
1010
+ members.push({
1011
+ name: member.name,
1012
+ type: member.type,
1013
+ sourcePath: sourceRelativePath,
1014
+ targetPaths: ["app.settings.yml"]
1015
+ });
1016
+ continue;
1017
+ }
866
1018
  let targetBaseRelativeDir;
867
1019
  switch (member.type) {
868
1020
  case "component":
@@ -928,6 +1080,7 @@ async function buildInstallPlan(options) {
928
1080
  }
929
1081
  return {
930
1082
  files,
1083
+ settings,
931
1084
  members,
932
1085
  metaPath: getAddonMetaPath(targetDir, manifest.name),
933
1086
  applicationType,
@@ -967,6 +1120,8 @@ function buildInstalledAddonMeta(options) {
967
1120
  memberTypes: [...new Set(options.manifest.members.map((member) => member.type))]
968
1121
  },
969
1122
  installParameters: options.installParameters,
1123
+ requirements: resolveInstallRequirements(options.manifest),
1124
+ npm: resolveInstallNpm(options.manifest),
970
1125
  members: options.members,
971
1126
  files: options.files
972
1127
  };
@@ -981,6 +1136,161 @@ async function writePlannedFiles(targetDir, planFiles) {
981
1136
  await copyFile(file.sourcePath, absoluteTargetPath);
982
1137
  }
983
1138
  }
1139
+ function isPlainObject(value) {
1140
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1141
+ }
1142
+ async function readYamlObject(filePath) {
1143
+ const parsed = YAML2.parse(await readFile(filePath, "utf8"));
1144
+ if (parsed == null) {
1145
+ return {};
1146
+ }
1147
+ if (!isPlainObject(parsed)) {
1148
+ throw new Error(`${filePath} must contain a YAML object`);
1149
+ }
1150
+ return parsed;
1151
+ }
1152
+ function flattenSettingsPatch(value, prefix = []) {
1153
+ const paths = [];
1154
+ for (const [key, child] of Object.entries(value)) {
1155
+ const segments = prefix.concat(key);
1156
+ if (isPlainObject(child)) {
1157
+ paths.push(...flattenSettingsPatch(child, segments));
1158
+ continue;
1159
+ }
1160
+ paths.push({
1161
+ path: segments.join("."),
1162
+ segments,
1163
+ value: child
1164
+ });
1165
+ }
1166
+ return paths;
1167
+ }
1168
+ async function readYamlDocument(targetPath) {
1169
+ const text = existsSync(targetPath) ? await readFile(targetPath, "utf8") : "";
1170
+ return YAML2.parseDocument(text);
1171
+ }
1172
+ function buildSettingsOwnershipMap(metas, excludeAddonName) {
1173
+ const ownership = /* @__PURE__ */ new Map();
1174
+ for (const meta of metas) {
1175
+ if (excludeAddonName && meta.name === excludeAddonName) {
1176
+ continue;
1177
+ }
1178
+ for (const member of meta.members) {
1179
+ for (const item of member.settings?.paths ?? []) {
1180
+ ownership.set(`${item.targetPath}#${item.path}`, meta.name);
1181
+ }
1182
+ }
1183
+ }
1184
+ return ownership;
1185
+ }
1186
+ function listPlannedSettingPaths(settings) {
1187
+ return settings.flatMap(
1188
+ (item) => item.paths.map((settingPath) => ({
1189
+ memberName: item.memberName,
1190
+ sourceRelativePath: item.sourceRelativePath,
1191
+ targetPath: item.targetPath,
1192
+ path: settingPath.path,
1193
+ segments: settingPath.segments,
1194
+ value: settingPath.value
1195
+ }))
1196
+ );
1197
+ }
1198
+ function getPlainYamlValue(document, segments) {
1199
+ const value = document.getIn(segments);
1200
+ if (value && typeof value === "object" && "toJSON" in value && typeof value.toJSON === "function") {
1201
+ return value.toJSON();
1202
+ }
1203
+ return value;
1204
+ }
1205
+ function attachAppliedSettings(members, appliedSettings) {
1206
+ return members.map((member) => {
1207
+ const applied = appliedSettings.find((item) => item.memberName === member.name);
1208
+ if (!applied) {
1209
+ return member;
1210
+ }
1211
+ return {
1212
+ ...member,
1213
+ settings: {
1214
+ targetPath: applied.targetPath,
1215
+ paths: applied.paths
1216
+ }
1217
+ };
1218
+ });
1219
+ }
1220
+ async function applyPlannedSettings(targetDir, settings) {
1221
+ const written = /* @__PURE__ */ new Set();
1222
+ const appliedSettings = [];
1223
+ for (const item of settings) {
1224
+ const targetPath = ensurePathInsideTarget(targetDir, item.targetPath);
1225
+ const document = await readYamlDocument(targetPath);
1226
+ const pathMetas = [];
1227
+ for (const settingPath of item.paths) {
1228
+ const previousValueExists = document.hasIn(settingPath.segments);
1229
+ const previousValue = previousValueExists ? getPlainYamlValue(document, settingPath.segments) : void 0;
1230
+ document.setIn(settingPath.segments, settingPath.value);
1231
+ pathMetas.push({
1232
+ targetPath: item.targetPath,
1233
+ path: settingPath.path,
1234
+ sha256: sha256Value(settingPath.value),
1235
+ previousValueExists,
1236
+ previousValue
1237
+ });
1238
+ }
1239
+ await ensureParentDirectory(targetPath);
1240
+ await writeFile(targetPath, document.toString());
1241
+ written.add(item.targetPath);
1242
+ appliedSettings.push({
1243
+ memberName: item.memberName,
1244
+ targetPath: item.targetPath,
1245
+ paths: pathMetas
1246
+ });
1247
+ }
1248
+ return {
1249
+ writtenFiles: [...written],
1250
+ appliedSettings
1251
+ };
1252
+ }
1253
+ async function restoreObsoleteSettings(targetDir, previousMeta, nextSettings) {
1254
+ if (!previousMeta) {
1255
+ return [];
1256
+ }
1257
+ const nextSettingKeys = new Set(
1258
+ listPlannedSettingPaths(nextSettings).map((item) => `${item.targetPath}#${item.path}`)
1259
+ );
1260
+ const documents = /* @__PURE__ */ new Map();
1261
+ const written = /* @__PURE__ */ new Set();
1262
+ const getDocument = async (targetPath) => {
1263
+ const cached = documents.get(targetPath);
1264
+ if (cached) {
1265
+ return cached;
1266
+ }
1267
+ const document = await readYamlDocument(ensurePathInsideTarget(targetDir, targetPath));
1268
+ documents.set(targetPath, document);
1269
+ return document;
1270
+ };
1271
+ for (const member of previousMeta.members) {
1272
+ for (const settingPath of member.settings?.paths ?? []) {
1273
+ if (nextSettingKeys.has(`${settingPath.targetPath}#${settingPath.path}`)) {
1274
+ continue;
1275
+ }
1276
+ const document = await getDocument(settingPath.targetPath);
1277
+ const segments = settingPath.path.split(".");
1278
+ if (settingPath.previousValueExists) {
1279
+ document.setIn(segments, settingPath.previousValue);
1280
+ } else {
1281
+ document.deleteIn(segments);
1282
+ }
1283
+ written.add(settingPath.targetPath);
1284
+ }
1285
+ }
1286
+ for (const targetPath of written) {
1287
+ const document = documents.get(targetPath);
1288
+ if (document) {
1289
+ await writeFile(ensurePathInsideTarget(targetDir, targetPath), document.toString());
1290
+ }
1291
+ }
1292
+ return [...written];
1293
+ }
984
1294
  async function removeObsoleteFiles(targetDir, previousMeta, nextPaths) {
985
1295
  const removed = [];
986
1296
  for (const file of previousMeta.files) {
@@ -995,9 +1305,77 @@ async function removeObsoleteFiles(targetDir, previousMeta, nextPaths) {
995
1305
  }
996
1306
  return removed;
997
1307
  }
1308
+ async function applyNpmDependencies(targetDir, npm) {
1309
+ const dependencies = listNpmDependencies(npm);
1310
+ if (!dependencies.length) {
1311
+ return [];
1312
+ }
1313
+ const packageJsonPath = ensurePathInsideTarget(targetDir, "package.json");
1314
+ const packageJson = await readPackageJson(targetDir);
1315
+ let changed = false;
1316
+ for (const dependency of dependencies) {
1317
+ const section = packageJson.dependencies;
1318
+ const nextSection = isPlainObject(section) ? section : {};
1319
+ if (!isPlainObject(section)) {
1320
+ packageJson.dependencies = nextSection;
1321
+ changed = true;
1322
+ }
1323
+ if (nextSection[dependency.packageName] !== dependency.version) {
1324
+ nextSection[dependency.packageName] = dependency.version;
1325
+ changed = true;
1326
+ }
1327
+ }
1328
+ if (!changed) {
1329
+ return [];
1330
+ }
1331
+ await writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
1332
+ `);
1333
+ return ["package.json"];
1334
+ }
1335
+ function resolvePackageManagerCommand(targetDir, packageJson) {
1336
+ const packageManager = typeof packageJson.packageManager === "string" ? packageJson.packageManager : "";
1337
+ if (existsSync(join(targetDir, "bun.lockb")) || existsSync(join(targetDir, "bun.lock")) || packageManager.startsWith("bun@")) {
1338
+ return { command: "bun", args: ["install"] };
1339
+ }
1340
+ if (existsSync(join(targetDir, "pnpm-lock.yaml")) || packageManager.startsWith("pnpm@")) {
1341
+ return { command: "pnpm", args: ["install"] };
1342
+ }
1343
+ if (existsSync(join(targetDir, "yarn.lock")) || packageManager.startsWith("yarn@")) {
1344
+ return { command: "yarn", args: ["install"] };
1345
+ }
1346
+ return { command: "npm", args: ["install"] };
1347
+ }
1348
+ async function installPackageDependencies(targetDir) {
1349
+ const packageJson = await readPackageJson(targetDir);
1350
+ const { command, args } = resolvePackageManagerCommand(targetDir, packageJson);
1351
+ try {
1352
+ await execFileAsync(command, args, {
1353
+ cwd: targetDir,
1354
+ maxBuffer: 1024 * 1024 * 10
1355
+ });
1356
+ } catch (error) {
1357
+ const message = error instanceof Error ? error.message : String(error);
1358
+ throw new Error(`Failed to install addon npm dependencies with ${command} ${args.join(" ")}: ${message}`);
1359
+ }
1360
+ }
998
1361
  async function validateInstallConflicts(targetDir, plan, existingMetas) {
999
1362
  const ownership = buildOwnershipMap(existingMetas);
1363
+ const settingsOwnership = buildSettingsOwnershipMap(existingMetas);
1000
1364
  const conflicts = [];
1365
+ const packageJson = await readPackageJson(targetDir);
1366
+ for (const dependency of listNpmDependencies(resolveInstallNpm(plan.manifest))) {
1367
+ const existing = findPackageDependency(packageJson, dependency.packageName);
1368
+ if (existing && existing !== dependency.version) {
1369
+ conflicts.push({
1370
+ kind: "package_dependency_conflict",
1371
+ path: `package.json#dependencies.${dependency.packageName}`,
1372
+ packageName: dependency.packageName,
1373
+ requestedVersion: dependency.version,
1374
+ existingVersion: existing,
1375
+ message: `${dependency.packageName} is already declared as ${existing} in package.json`
1376
+ });
1377
+ }
1378
+ }
1001
1379
  for (const file of plan.files) {
1002
1380
  const owner = ownership.get(file.targetPath);
1003
1381
  if (owner && owner !== plan.manifest.name) {
@@ -1024,6 +1402,22 @@ async function validateInstallConflicts(targetDir, plan, existingMetas) {
1024
1402
  });
1025
1403
  }
1026
1404
  }
1405
+ for (const item of listPlannedSettingPaths(plan.settings)) {
1406
+ const owner = settingsOwnership.get(`${item.targetPath}#${item.path}`);
1407
+ if (owner && owner !== plan.manifest.name) {
1408
+ conflicts.push({
1409
+ kind: "owned_by_other_addon",
1410
+ path: `${item.targetPath}#${item.path}`,
1411
+ sourcePath: item.sourceRelativePath,
1412
+ memberName: item.memberName,
1413
+ memberType: "settings",
1414
+ ownerAddon: owner,
1415
+ settingPath: item.path,
1416
+ nextValue: item.value,
1417
+ message: `${item.targetPath}#${item.path} is already managed by addon ${owner}`
1418
+ });
1419
+ }
1420
+ }
1027
1421
  if (conflicts.length) {
1028
1422
  throw new AddonInstallConflictError({
1029
1423
  operation: "install",
@@ -1039,9 +1433,42 @@ async function validateInstallConflicts(targetDir, plan, existingMetas) {
1039
1433
  }
1040
1434
  async function validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta) {
1041
1435
  const ownership = buildOwnershipMap(existingMetas, previousMeta.name);
1436
+ const settingsOwnership = buildSettingsOwnershipMap(existingMetas, previousMeta.name);
1042
1437
  const previousFilesByPath = new Map(previousMeta.files.map((file) => [file.path, file]));
1043
1438
  const nextPaths = new Set(plan.files.map((file) => file.targetPath));
1439
+ const plannedSettings = listPlannedSettingPaths(plan.settings);
1440
+ const nextSettingKeys = new Set(plannedSettings.map((item) => `${item.targetPath}#${item.path}`));
1441
+ const plannedSettingsByKey = new Map(plannedSettings.map((item) => [`${item.targetPath}#${item.path}`, item]));
1044
1442
  const conflicts = [];
1443
+ const packageJson = await readPackageJson(targetDir);
1444
+ const previousNpmByName = buildNpmDependencyMap(previousMeta.npm ?? {});
1445
+ for (const dependency of listNpmDependencies(resolveInstallNpm(plan.manifest))) {
1446
+ const existing = findPackageDependency(packageJson, dependency.packageName);
1447
+ const previous = previousNpmByName.get(dependency.packageName);
1448
+ if (!existing) {
1449
+ if (previous) {
1450
+ conflicts.push({
1451
+ kind: "package_dependency_conflict",
1452
+ path: `package.json#dependencies.${dependency.packageName}`,
1453
+ packageName: dependency.packageName,
1454
+ requestedVersion: dependency.version,
1455
+ message: `managed npm package missing from package.json: ${dependency.packageName}`
1456
+ });
1457
+ }
1458
+ continue;
1459
+ }
1460
+ const canUpdateManagedVersion = previous && existing === previous.version;
1461
+ if (existing !== dependency.version && !canUpdateManagedVersion) {
1462
+ conflicts.push({
1463
+ kind: "package_dependency_conflict",
1464
+ path: `package.json#dependencies.${dependency.packageName}`,
1465
+ packageName: dependency.packageName,
1466
+ requestedVersion: dependency.version,
1467
+ existingVersion: existing,
1468
+ message: `${dependency.packageName} is already declared as ${existing} in package.json`
1469
+ });
1470
+ }
1471
+ }
1045
1472
  for (const managedFile of previousMeta.files) {
1046
1473
  const absolutePath = ensurePathInsideTarget(targetDir, managedFile.path);
1047
1474
  if (!existsSync(absolutePath)) {
@@ -1095,6 +1522,60 @@ async function validateUpgradeConflicts(targetDir, plan, existingMetas, previous
1095
1522
  });
1096
1523
  }
1097
1524
  }
1525
+ const settingsDocuments = /* @__PURE__ */ new Map();
1526
+ const getSettingsDocument = async (targetPath) => {
1527
+ const cached = settingsDocuments.get(targetPath);
1528
+ if (cached) {
1529
+ return cached;
1530
+ }
1531
+ const document = await readYamlDocument(ensurePathInsideTarget(targetDir, targetPath));
1532
+ settingsDocuments.set(targetPath, document);
1533
+ return document;
1534
+ };
1535
+ for (const member of previousMeta.members) {
1536
+ for (const settingPath of member.settings?.paths ?? []) {
1537
+ const document = await getSettingsDocument(settingPath.targetPath);
1538
+ const segments = settingPath.path.split(".");
1539
+ const currentValue = document.hasIn(segments) ? getPlainYamlValue(document, segments) : void 0;
1540
+ const actualSha256 = sha256Value(currentValue);
1541
+ if (actualSha256 === settingPath.sha256) {
1542
+ continue;
1543
+ }
1544
+ const settingKey = `${settingPath.targetPath}#${settingPath.path}`;
1545
+ const isStillManaged = nextSettingKeys.has(settingKey);
1546
+ const nextSetting = plannedSettingsByKey.get(settingKey);
1547
+ conflicts.push({
1548
+ kind: isStillManaged ? "managed_file_modified" : "obsolete_file_modified",
1549
+ path: settingKey,
1550
+ sourcePath: member.sourcePath,
1551
+ memberName: member.name,
1552
+ memberType: "settings",
1553
+ expectedSha256: settingPath.sha256,
1554
+ actualSha256,
1555
+ settingPath: settingPath.path,
1556
+ currentValue,
1557
+ nextValue: nextSetting?.value,
1558
+ previousValue: settingPath.previousValue,
1559
+ message: isStillManaged ? `managed setting modified locally: ${settingKey}` : `setting changed locally and would be restored: ${settingKey}`
1560
+ });
1561
+ }
1562
+ }
1563
+ for (const item of plannedSettings) {
1564
+ const owner = settingsOwnership.get(`${item.targetPath}#${item.path}`);
1565
+ if (owner) {
1566
+ conflicts.push({
1567
+ kind: "owned_by_other_addon",
1568
+ path: `${item.targetPath}#${item.path}`,
1569
+ sourcePath: item.sourceRelativePath,
1570
+ memberName: item.memberName,
1571
+ memberType: "settings",
1572
+ ownerAddon: owner,
1573
+ settingPath: item.path,
1574
+ nextValue: item.value,
1575
+ message: `${item.targetPath}#${item.path} is already managed by addon ${owner}`
1576
+ });
1577
+ }
1578
+ }
1098
1579
  for (const oldFile of previousMeta.files) {
1099
1580
  if (!nextPaths.has(oldFile.path)) {
1100
1581
  const absolutePath = ensurePathInsideTarget(targetDir, oldFile.path);
@@ -1262,7 +1743,11 @@ async function materializeAddon(options) {
1262
1743
  await validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta);
1263
1744
  }
1264
1745
  const removedFiles = previousMeta ? await removeObsoleteFiles(targetDir, previousMeta, new Set(plan.files.map((file) => file.targetPath))) : [];
1746
+ const restoredSettingsFiles = await restoreObsoleteSettings(targetDir, previousMeta, plan.settings);
1747
+ const npm = resolveInstallNpm(plan.manifest);
1748
+ const packageJsonFiles = await applyNpmDependencies(targetDir, npm);
1265
1749
  await writePlannedFiles(targetDir, plan.files);
1750
+ const settingsResult = await applyPlannedSettings(targetDir, plan.settings);
1266
1751
  const installedFiles = [];
1267
1752
  for (const plannedFile of plan.files) {
1268
1753
  installedFiles.push(
@@ -1275,7 +1760,7 @@ async function materializeAddon(options) {
1275
1760
  applicationType: plan.applicationType,
1276
1761
  organizationCode: options.organizationCode,
1277
1762
  installParameters: plan.installParameters,
1278
- members: plan.members,
1763
+ members: attachAppliedSettings(plan.members, settingsResult.appliedSettings),
1279
1764
  files: installedFiles,
1280
1765
  installedAt: previousMeta?.installedAt
1281
1766
  });
@@ -1283,10 +1768,17 @@ async function materializeAddon(options) {
1283
1768
  await writeFile(plan.metaPath, JSON.stringify(meta, null, 2));
1284
1769
  const nextMetas = existingMetas.filter((item) => item.name !== meta.name).concat(meta);
1285
1770
  await rebuildRegistryFiles(targetDir, plan.applicationType, nextMetas.filter((item) => item.applicationType === plan.applicationType));
1771
+ if (options.installPackageDependencies && packageJsonFiles.length) {
1772
+ await installPackageDependencies(targetDir);
1773
+ }
1774
+ const requirements = resolveInstallRequirements(plan.manifest);
1286
1775
  return {
1287
1776
  meta,
1288
- writtenFiles: installedFiles.map((file) => file.path),
1289
- removedFiles
1777
+ writtenFiles: installedFiles.map((file) => file.path).concat(packageJsonFiles, restoredSettingsFiles, settingsResult.writtenFiles),
1778
+ removedFiles,
1779
+ requirements,
1780
+ missingRequirements: buildMissingRequirements(requirements),
1781
+ npm
1290
1782
  };
1291
1783
  }
1292
1784
  async function installAddonFromExtractedDirectory(options) {
@@ -1542,7 +2034,8 @@ async function installAddonFromRegistry(options) {
1542
2034
  extractedDir,
1543
2035
  applicationType: options.applicationType,
1544
2036
  organizationCode: options.organizationCode,
1545
- installParameters: options.installParameters
2037
+ installParameters: options.installParameters,
2038
+ installPackageDependencies: true
1546
2039
  });
1547
2040
  } finally {
1548
2041
  await removeTempDirectory(extractedDir).catch(() => void 0);
@@ -1560,7 +2053,8 @@ async function upgradeAddonFromRegistry(options) {
1560
2053
  extractedDir,
1561
2054
  applicationType: options.applicationType,
1562
2055
  organizationCode: options.organizationCode,
1563
- installParameters: options.installParameters
2056
+ installParameters: options.installParameters,
2057
+ installPackageDependencies: true
1564
2058
  });
1565
2059
  } finally {
1566
2060
  await removeTempDirectory(extractedDir).catch(() => void 0);