@amaster.ai/cli 1.1.28 → 1.1.29

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
@@ -10,7 +10,7 @@ import { tmpdir, homedir } from 'os';
10
10
  import * as tar from 'tar';
11
11
  import { createServer } from 'http';
12
12
  import { spawn, spawnSync } from 'child_process';
13
- import YAML from 'yaml';
13
+ import YAML2 from 'yaml';
14
14
  import ts from 'typescript';
15
15
 
16
16
  var EXCLUDED_NAMES = /* @__PURE__ */ new Set([".git", "node_modules", ".DS_Store"]);
@@ -554,6 +554,46 @@ function validateAddonManifest(manifest) {
554
554
  if (!Array.isArray(manifest.members)) {
555
555
  throw new Error("addon.json missing members");
556
556
  }
557
+ validateInstallRequirements(manifest);
558
+ }
559
+ function validateInstallRequirements(manifest) {
560
+ const requirements = manifest.install?.requirements;
561
+ if (!requirements) {
562
+ return;
563
+ }
564
+ if (requirements.envs !== void 0 && !Array.isArray(requirements.envs)) {
565
+ throw new Error("addon.json install.requirements.envs must be an array");
566
+ }
567
+ if (requirements.secrets !== void 0 && !Array.isArray(requirements.secrets)) {
568
+ throw new Error("addon.json install.requirements.secrets must be an array");
569
+ }
570
+ for (const item of requirements.envs ?? []) {
571
+ validateRequirementItem(item, "env");
572
+ }
573
+ for (const item of requirements.secrets ?? []) {
574
+ validateRequirementItem(item, "secret");
575
+ if (item.defaultValue !== void 0) {
576
+ throw new Error("addon.json install.requirements.secrets cannot declare defaultValue");
577
+ }
578
+ }
579
+ }
580
+ function validateRequirementItem(item, kind) {
581
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
582
+ throw new Error(`addon.json install.requirements.${kind}s item is invalid`);
583
+ }
584
+ const requirement = item;
585
+ if (typeof requirement.key !== "string" || !requirement.key.trim()) {
586
+ throw new Error(`addon.json install.requirements.${kind}s item missing key`);
587
+ }
588
+ if (requirement.required !== void 0 && typeof requirement.required !== "boolean") {
589
+ throw new Error(`addon.json install.requirements.${kind}s item required must be boolean`);
590
+ }
591
+ if (requirement.description !== void 0 && typeof requirement.description !== "string") {
592
+ throw new Error(`addon.json install.requirements.${kind}s item description must be string`);
593
+ }
594
+ if (requirement.defaultValue !== void 0 && typeof requirement.defaultValue !== "string") {
595
+ throw new Error(`addon.json install.requirements.${kind}s item defaultValue must be string`);
596
+ }
557
597
  }
558
598
  function resolveMemberSourcePath(member) {
559
599
  const sourcePath = member.source?.path;
@@ -604,7 +644,7 @@ async function readAppSettingsApplicationType(packageRoot) {
604
644
  if (!existsSync(appSettingsPath)) {
605
645
  return null;
606
646
  }
607
- const parsed = YAML.parse(await readFile(appSettingsPath, "utf8"));
647
+ const parsed = YAML2.parse(await readFile(appSettingsPath, "utf8"));
608
648
  if (parsed?.type === "web" || parsed?.type === "mini") {
609
649
  return parsed.type;
610
650
  }
@@ -667,6 +707,18 @@ function isAddonInstallConflictError(error) {
667
707
  function sha256Buffer(buffer) {
668
708
  return `sha256:${createHash("sha256").update(buffer).digest("hex")}`;
669
709
  }
710
+ function stableJsonStringify(value) {
711
+ if (Array.isArray(value)) {
712
+ return `[${value.map((item) => stableJsonStringify(item)).join(",")}]`;
713
+ }
714
+ if (isPlainObject(value)) {
715
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJsonStringify(value[key])}`).join(",")}}`;
716
+ }
717
+ return JSON.stringify(value);
718
+ }
719
+ function sha256Value(value) {
720
+ return sha256Buffer(Buffer.from(stableJsonStringify(value) ?? "undefined"));
721
+ }
670
722
  function ensurePathInsideTarget(targetDir, relativePath) {
671
723
  const absolute = resolve(targetDir, relativePath);
672
724
  const normalizedTarget = resolve(targetDir);
@@ -748,6 +800,19 @@ function resolveInstallParameters(manifest, rawParameters) {
748
800
  }
749
801
  return resolved;
750
802
  }
803
+ function resolveInstallRequirements(manifest) {
804
+ const requirements = manifest.install?.requirements ?? {};
805
+ return {
806
+ envs: requirements.envs?.map((item) => ({ ...item })),
807
+ secrets: requirements.secrets?.map((item) => ({ ...item }))
808
+ };
809
+ }
810
+ function buildMissingRequirements(requirements) {
811
+ return {
812
+ envs: requirements.envs?.filter((item) => item.required !== false).map((item) => ({ ...item })),
813
+ secrets: requirements.secrets?.filter((item) => item.required !== false).map((item) => ({ ...item }))
814
+ };
815
+ }
751
816
  function getAddonMetaPath(targetDir, addonName) {
752
817
  return join(targetDir, "src", "addons", addonName, "meta.json");
753
818
  }
@@ -850,19 +915,37 @@ async function buildInstallPlan(options) {
850
915
  }
851
916
  const installParameters = resolveInstallParameters(manifest, options.installParameters);
852
917
  const files = [];
918
+ const settings = [];
853
919
  const members = [];
854
920
  for (const member of manifest.members) {
855
921
  if (member.type === "skill") {
856
922
  throw new Error(`Member ${member.name} is a runtime skill. Design-time CLI install does not support skill members yet.`);
857
923
  }
858
- if (member.type === "settings") {
859
- throw new Error(`Member ${member.name} is a settings fragment. settings install is not implemented yet.`);
860
- }
861
924
  const sourceRelativePath = resolveMemberSourcePath(member);
862
925
  if (!sourceRelativePath) {
863
926
  throw new Error(`Member ${member.name} is missing source.path`);
864
927
  }
865
928
  await assertPathExists(options.extractedDir, sourceRelativePath);
929
+ if (member.type === "settings") {
930
+ const sourcePath = join(options.extractedDir, sourceRelativePath);
931
+ const patch = await readYamlObject(sourcePath);
932
+ settings.push({
933
+ sourcePath,
934
+ sourceRelativePath,
935
+ targetPath: "app.settings.yml",
936
+ memberName: member.name,
937
+ memberType: "settings",
938
+ patch,
939
+ paths: flattenSettingsPatch(patch)
940
+ });
941
+ members.push({
942
+ name: member.name,
943
+ type: member.type,
944
+ sourcePath: sourceRelativePath,
945
+ targetPaths: ["app.settings.yml"]
946
+ });
947
+ continue;
948
+ }
866
949
  let targetBaseRelativeDir;
867
950
  switch (member.type) {
868
951
  case "component":
@@ -928,6 +1011,7 @@ async function buildInstallPlan(options) {
928
1011
  }
929
1012
  return {
930
1013
  files,
1014
+ settings,
931
1015
  members,
932
1016
  metaPath: getAddonMetaPath(targetDir, manifest.name),
933
1017
  applicationType,
@@ -967,6 +1051,7 @@ function buildInstalledAddonMeta(options) {
967
1051
  memberTypes: [...new Set(options.manifest.members.map((member) => member.type))]
968
1052
  },
969
1053
  installParameters: options.installParameters,
1054
+ requirements: resolveInstallRequirements(options.manifest),
970
1055
  members: options.members,
971
1056
  files: options.files
972
1057
  };
@@ -981,6 +1066,161 @@ async function writePlannedFiles(targetDir, planFiles) {
981
1066
  await copyFile(file.sourcePath, absoluteTargetPath);
982
1067
  }
983
1068
  }
1069
+ function isPlainObject(value) {
1070
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1071
+ }
1072
+ async function readYamlObject(filePath) {
1073
+ const parsed = YAML2.parse(await readFile(filePath, "utf8"));
1074
+ if (parsed == null) {
1075
+ return {};
1076
+ }
1077
+ if (!isPlainObject(parsed)) {
1078
+ throw new Error(`${filePath} must contain a YAML object`);
1079
+ }
1080
+ return parsed;
1081
+ }
1082
+ function flattenSettingsPatch(value, prefix = []) {
1083
+ const paths = [];
1084
+ for (const [key, child] of Object.entries(value)) {
1085
+ const segments = prefix.concat(key);
1086
+ if (isPlainObject(child)) {
1087
+ paths.push(...flattenSettingsPatch(child, segments));
1088
+ continue;
1089
+ }
1090
+ paths.push({
1091
+ path: segments.join("."),
1092
+ segments,
1093
+ value: child
1094
+ });
1095
+ }
1096
+ return paths;
1097
+ }
1098
+ async function readYamlDocument(targetPath) {
1099
+ const text = existsSync(targetPath) ? await readFile(targetPath, "utf8") : "";
1100
+ return YAML2.parseDocument(text);
1101
+ }
1102
+ function buildSettingsOwnershipMap(metas, excludeAddonName) {
1103
+ const ownership = /* @__PURE__ */ new Map();
1104
+ for (const meta of metas) {
1105
+ if (excludeAddonName && meta.name === excludeAddonName) {
1106
+ continue;
1107
+ }
1108
+ for (const member of meta.members) {
1109
+ for (const item of member.settings?.paths ?? []) {
1110
+ ownership.set(`${item.targetPath}#${item.path}`, meta.name);
1111
+ }
1112
+ }
1113
+ }
1114
+ return ownership;
1115
+ }
1116
+ function listPlannedSettingPaths(settings) {
1117
+ return settings.flatMap(
1118
+ (item) => item.paths.map((settingPath) => ({
1119
+ memberName: item.memberName,
1120
+ sourceRelativePath: item.sourceRelativePath,
1121
+ targetPath: item.targetPath,
1122
+ path: settingPath.path,
1123
+ segments: settingPath.segments,
1124
+ value: settingPath.value
1125
+ }))
1126
+ );
1127
+ }
1128
+ function getPlainYamlValue(document, segments) {
1129
+ const value = document.getIn(segments);
1130
+ if (value && typeof value === "object" && "toJSON" in value && typeof value.toJSON === "function") {
1131
+ return value.toJSON();
1132
+ }
1133
+ return value;
1134
+ }
1135
+ function attachAppliedSettings(members, appliedSettings) {
1136
+ return members.map((member) => {
1137
+ const applied = appliedSettings.find((item) => item.memberName === member.name);
1138
+ if (!applied) {
1139
+ return member;
1140
+ }
1141
+ return {
1142
+ ...member,
1143
+ settings: {
1144
+ targetPath: applied.targetPath,
1145
+ paths: applied.paths
1146
+ }
1147
+ };
1148
+ });
1149
+ }
1150
+ async function applyPlannedSettings(targetDir, settings) {
1151
+ const written = /* @__PURE__ */ new Set();
1152
+ const appliedSettings = [];
1153
+ for (const item of settings) {
1154
+ const targetPath = ensurePathInsideTarget(targetDir, item.targetPath);
1155
+ const document = await readYamlDocument(targetPath);
1156
+ const pathMetas = [];
1157
+ for (const settingPath of item.paths) {
1158
+ const previousValueExists = document.hasIn(settingPath.segments);
1159
+ const previousValue = previousValueExists ? getPlainYamlValue(document, settingPath.segments) : void 0;
1160
+ document.setIn(settingPath.segments, settingPath.value);
1161
+ pathMetas.push({
1162
+ targetPath: item.targetPath,
1163
+ path: settingPath.path,
1164
+ sha256: sha256Value(settingPath.value),
1165
+ previousValueExists,
1166
+ previousValue
1167
+ });
1168
+ }
1169
+ await ensureParentDirectory(targetPath);
1170
+ await writeFile(targetPath, document.toString());
1171
+ written.add(item.targetPath);
1172
+ appliedSettings.push({
1173
+ memberName: item.memberName,
1174
+ targetPath: item.targetPath,
1175
+ paths: pathMetas
1176
+ });
1177
+ }
1178
+ return {
1179
+ writtenFiles: [...written],
1180
+ appliedSettings
1181
+ };
1182
+ }
1183
+ async function restoreObsoleteSettings(targetDir, previousMeta, nextSettings) {
1184
+ if (!previousMeta) {
1185
+ return [];
1186
+ }
1187
+ const nextSettingKeys = new Set(
1188
+ listPlannedSettingPaths(nextSettings).map((item) => `${item.targetPath}#${item.path}`)
1189
+ );
1190
+ const documents = /* @__PURE__ */ new Map();
1191
+ const written = /* @__PURE__ */ new Set();
1192
+ const getDocument = async (targetPath) => {
1193
+ const cached = documents.get(targetPath);
1194
+ if (cached) {
1195
+ return cached;
1196
+ }
1197
+ const document = await readYamlDocument(ensurePathInsideTarget(targetDir, targetPath));
1198
+ documents.set(targetPath, document);
1199
+ return document;
1200
+ };
1201
+ for (const member of previousMeta.members) {
1202
+ for (const settingPath of member.settings?.paths ?? []) {
1203
+ if (nextSettingKeys.has(`${settingPath.targetPath}#${settingPath.path}`)) {
1204
+ continue;
1205
+ }
1206
+ const document = await getDocument(settingPath.targetPath);
1207
+ const segments = settingPath.path.split(".");
1208
+ if (settingPath.previousValueExists) {
1209
+ document.setIn(segments, settingPath.previousValue);
1210
+ } else {
1211
+ document.deleteIn(segments);
1212
+ }
1213
+ written.add(settingPath.targetPath);
1214
+ }
1215
+ }
1216
+ for (const targetPath of written) {
1217
+ const document = documents.get(targetPath);
1218
+ if (document) {
1219
+ await writeFile(ensurePathInsideTarget(targetDir, targetPath), document.toString());
1220
+ }
1221
+ }
1222
+ return [...written];
1223
+ }
984
1224
  async function removeObsoleteFiles(targetDir, previousMeta, nextPaths) {
985
1225
  const removed = [];
986
1226
  for (const file of previousMeta.files) {
@@ -997,6 +1237,7 @@ async function removeObsoleteFiles(targetDir, previousMeta, nextPaths) {
997
1237
  }
998
1238
  async function validateInstallConflicts(targetDir, plan, existingMetas) {
999
1239
  const ownership = buildOwnershipMap(existingMetas);
1240
+ const settingsOwnership = buildSettingsOwnershipMap(existingMetas);
1000
1241
  const conflicts = [];
1001
1242
  for (const file of plan.files) {
1002
1243
  const owner = ownership.get(file.targetPath);
@@ -1024,6 +1265,22 @@ async function validateInstallConflicts(targetDir, plan, existingMetas) {
1024
1265
  });
1025
1266
  }
1026
1267
  }
1268
+ for (const item of listPlannedSettingPaths(plan.settings)) {
1269
+ const owner = settingsOwnership.get(`${item.targetPath}#${item.path}`);
1270
+ if (owner && owner !== plan.manifest.name) {
1271
+ conflicts.push({
1272
+ kind: "owned_by_other_addon",
1273
+ path: `${item.targetPath}#${item.path}`,
1274
+ sourcePath: item.sourceRelativePath,
1275
+ memberName: item.memberName,
1276
+ memberType: "settings",
1277
+ ownerAddon: owner,
1278
+ settingPath: item.path,
1279
+ nextValue: item.value,
1280
+ message: `${item.targetPath}#${item.path} is already managed by addon ${owner}`
1281
+ });
1282
+ }
1283
+ }
1027
1284
  if (conflicts.length) {
1028
1285
  throw new AddonInstallConflictError({
1029
1286
  operation: "install",
@@ -1039,8 +1296,12 @@ async function validateInstallConflicts(targetDir, plan, existingMetas) {
1039
1296
  }
1040
1297
  async function validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta) {
1041
1298
  const ownership = buildOwnershipMap(existingMetas, previousMeta.name);
1299
+ const settingsOwnership = buildSettingsOwnershipMap(existingMetas, previousMeta.name);
1042
1300
  const previousFilesByPath = new Map(previousMeta.files.map((file) => [file.path, file]));
1043
1301
  const nextPaths = new Set(plan.files.map((file) => file.targetPath));
1302
+ const plannedSettings = listPlannedSettingPaths(plan.settings);
1303
+ const nextSettingKeys = new Set(plannedSettings.map((item) => `${item.targetPath}#${item.path}`));
1304
+ const plannedSettingsByKey = new Map(plannedSettings.map((item) => [`${item.targetPath}#${item.path}`, item]));
1044
1305
  const conflicts = [];
1045
1306
  for (const managedFile of previousMeta.files) {
1046
1307
  const absolutePath = ensurePathInsideTarget(targetDir, managedFile.path);
@@ -1095,6 +1356,60 @@ async function validateUpgradeConflicts(targetDir, plan, existingMetas, previous
1095
1356
  });
1096
1357
  }
1097
1358
  }
1359
+ const settingsDocuments = /* @__PURE__ */ new Map();
1360
+ const getSettingsDocument = async (targetPath) => {
1361
+ const cached = settingsDocuments.get(targetPath);
1362
+ if (cached) {
1363
+ return cached;
1364
+ }
1365
+ const document = await readYamlDocument(ensurePathInsideTarget(targetDir, targetPath));
1366
+ settingsDocuments.set(targetPath, document);
1367
+ return document;
1368
+ };
1369
+ for (const member of previousMeta.members) {
1370
+ for (const settingPath of member.settings?.paths ?? []) {
1371
+ const document = await getSettingsDocument(settingPath.targetPath);
1372
+ const segments = settingPath.path.split(".");
1373
+ const currentValue = document.hasIn(segments) ? getPlainYamlValue(document, segments) : void 0;
1374
+ const actualSha256 = sha256Value(currentValue);
1375
+ if (actualSha256 === settingPath.sha256) {
1376
+ continue;
1377
+ }
1378
+ const settingKey = `${settingPath.targetPath}#${settingPath.path}`;
1379
+ const isStillManaged = nextSettingKeys.has(settingKey);
1380
+ const nextSetting = plannedSettingsByKey.get(settingKey);
1381
+ conflicts.push({
1382
+ kind: isStillManaged ? "managed_file_modified" : "obsolete_file_modified",
1383
+ path: settingKey,
1384
+ sourcePath: member.sourcePath,
1385
+ memberName: member.name,
1386
+ memberType: "settings",
1387
+ expectedSha256: settingPath.sha256,
1388
+ actualSha256,
1389
+ settingPath: settingPath.path,
1390
+ currentValue,
1391
+ nextValue: nextSetting?.value,
1392
+ previousValue: settingPath.previousValue,
1393
+ message: isStillManaged ? `managed setting modified locally: ${settingKey}` : `setting changed locally and would be restored: ${settingKey}`
1394
+ });
1395
+ }
1396
+ }
1397
+ for (const item of plannedSettings) {
1398
+ const owner = settingsOwnership.get(`${item.targetPath}#${item.path}`);
1399
+ if (owner) {
1400
+ conflicts.push({
1401
+ kind: "owned_by_other_addon",
1402
+ path: `${item.targetPath}#${item.path}`,
1403
+ sourcePath: item.sourceRelativePath,
1404
+ memberName: item.memberName,
1405
+ memberType: "settings",
1406
+ ownerAddon: owner,
1407
+ settingPath: item.path,
1408
+ nextValue: item.value,
1409
+ message: `${item.targetPath}#${item.path} is already managed by addon ${owner}`
1410
+ });
1411
+ }
1412
+ }
1098
1413
  for (const oldFile of previousMeta.files) {
1099
1414
  if (!nextPaths.has(oldFile.path)) {
1100
1415
  const absolutePath = ensurePathInsideTarget(targetDir, oldFile.path);
@@ -1262,7 +1577,9 @@ async function materializeAddon(options) {
1262
1577
  await validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta);
1263
1578
  }
1264
1579
  const removedFiles = previousMeta ? await removeObsoleteFiles(targetDir, previousMeta, new Set(plan.files.map((file) => file.targetPath))) : [];
1580
+ const restoredSettingsFiles = await restoreObsoleteSettings(targetDir, previousMeta, plan.settings);
1265
1581
  await writePlannedFiles(targetDir, plan.files);
1582
+ const settingsResult = await applyPlannedSettings(targetDir, plan.settings);
1266
1583
  const installedFiles = [];
1267
1584
  for (const plannedFile of plan.files) {
1268
1585
  installedFiles.push(
@@ -1275,7 +1592,7 @@ async function materializeAddon(options) {
1275
1592
  applicationType: plan.applicationType,
1276
1593
  organizationCode: options.organizationCode,
1277
1594
  installParameters: plan.installParameters,
1278
- members: plan.members,
1595
+ members: attachAppliedSettings(plan.members, settingsResult.appliedSettings),
1279
1596
  files: installedFiles,
1280
1597
  installedAt: previousMeta?.installedAt
1281
1598
  });
@@ -1283,10 +1600,13 @@ async function materializeAddon(options) {
1283
1600
  await writeFile(plan.metaPath, JSON.stringify(meta, null, 2));
1284
1601
  const nextMetas = existingMetas.filter((item) => item.name !== meta.name).concat(meta);
1285
1602
  await rebuildRegistryFiles(targetDir, plan.applicationType, nextMetas.filter((item) => item.applicationType === plan.applicationType));
1603
+ const requirements = resolveInstallRequirements(plan.manifest);
1286
1604
  return {
1287
1605
  meta,
1288
- writtenFiles: installedFiles.map((file) => file.path),
1289
- removedFiles
1606
+ writtenFiles: installedFiles.map((file) => file.path).concat(restoredSettingsFiles, settingsResult.writtenFiles),
1607
+ removedFiles,
1608
+ requirements,
1609
+ missingRequirements: buildMissingRequirements(requirements)
1290
1610
  };
1291
1611
  }
1292
1612
  async function installAddonFromExtractedDirectory(options) {