@donotdev/cli 0.3.6 → 0.3.8

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.
@@ -823,6 +823,148 @@ var init_cli_output = __esm({
823
823
  }
824
824
  });
825
825
 
826
+ // packages/tooling/src/utils/errors.ts
827
+ var DO_NOT_DEV_ERROR_CODES, DoNotDevError;
828
+ var init_errors = __esm({
829
+ "packages/tooling/src/utils/errors.ts"() {
830
+ "use strict";
831
+ init_utils2();
832
+ DO_NOT_DEV_ERROR_CODES = {
833
+ CONFIGURATION_ERROR: "configuration-error",
834
+ CONFIG_NOT_FOUND: "config-not-found",
835
+ CONFIG_INVALID: "config-invalid",
836
+ PATH_RESOLUTION_ERROR: "path-resolution-error",
837
+ FILE_OPERATION_ERROR: "file-operation-error",
838
+ FILE_NOT_FOUND: "file-not-found",
839
+ PERMISSION_DENIED: "permission-denied",
840
+ GENERATION_ERROR: "generation-error",
841
+ TEMPLATE_ERROR: "template-error",
842
+ TEMPLATE_NOT_FOUND: "template-not-found",
843
+ CLI_EXECUTION_ERROR: "cli-execution-error",
844
+ COMMAND_NOT_FOUND: "command-not-found",
845
+ COMMAND_FAILED: "command-failed",
846
+ VALIDATION_ERROR: "validation-error",
847
+ SCHEMA_ERROR: "schema-error",
848
+ DEPENDENCY_ERROR: "dependency-error",
849
+ DEPENDENCY_NOT_FOUND: "dependency-not-found",
850
+ DEPENDENCY_VERSION_ERROR: "dependency-version-error",
851
+ INVALID_ARGUMENT: "invalid-argument",
852
+ MISSING_ARGUMENT: "missing-argument",
853
+ MISSING_PROJECT_ID: "missing-project-id",
854
+ FIREBASE_CLI_ERROR: "firebase-cli-error",
855
+ DEPLOYMENT_FAILED: "deployment-failed",
856
+ VERCEL_API_ERROR: "vercel-api-error",
857
+ OPERATION_CANCELLED: "operation-cancelled",
858
+ TIMEOUT_ERROR: "timeout-error",
859
+ UNKNOWN_ERROR: "unknown-error"
860
+ };
861
+ DoNotDevError = class _DoNotDevError extends Error {
862
+ /** The error code categorizing this error */
863
+ code;
864
+ /** Original error if this is wrapping another error */
865
+ originalError;
866
+ /** Additional context for the error */
867
+ context;
868
+ /** Whether this error should be displayed to the user */
869
+ displayable;
870
+ /**
871
+ * Creates a new DoNotDev error
872
+ *
873
+ * @param {string} message - Error message
874
+ * @param {DoNotDevErrorCode} code - Error code
875
+ * @param {object} [options] - Additional error options
876
+ * @param {Error} [options.originalError] - Original error if wrapping
877
+ * @param {Record<string, unknown>} [options.context] - Additional context data
878
+ * @param {boolean} [options.displayable=true] - Whether this error should be displayed to the user
879
+ */
880
+ constructor(message, code = DO_NOT_DEV_ERROR_CODES.UNKNOWN_ERROR, options) {
881
+ super(message);
882
+ this.name = "DoNotDevError";
883
+ this.code = code;
884
+ this.originalError = options?.originalError;
885
+ this.context = options?.context;
886
+ this.displayable = options?.displayable !== false;
887
+ Object.setPrototypeOf(this, _DoNotDevError.prototype);
888
+ if (Error.captureStackTrace) {
889
+ Error.captureStackTrace(this, _DoNotDevError);
890
+ }
891
+ }
892
+ /**
893
+ * Formats the error for logging or display
894
+ *
895
+ * @returns {string} Formatted error message with code
896
+ */
897
+ format() {
898
+ return `[${this.code}] ${this.message}`;
899
+ }
900
+ /**
901
+ * Creates a wrapped error from another error
902
+ *
903
+ * @param {Error} error - Original error to wrap
904
+ * @param {string} [context] - Additional context for the error
905
+ * @param {DoNotDevErrorCode} [code='unknown-error'] - Error code
906
+ * @param {object} [options] - Additional error options
907
+ * @param {Record<string, unknown>} [options.context] - Additional context data
908
+ * @param {boolean} [options.displayable=true] - Whether this error should be displayed to the user
909
+ * @returns {DoNotDevError} New DoNotDev error wrapping the original
910
+ */
911
+ static from(error2, context, code = DO_NOT_DEV_ERROR_CODES.UNKNOWN_ERROR, options) {
912
+ if (!(error2 instanceof Error)) {
913
+ return new _DoNotDevError(
914
+ `Unknown error: ${String(error2)}`,
915
+ code,
916
+ options
917
+ );
918
+ }
919
+ if (error2 instanceof _DoNotDevError) {
920
+ if (!context) {
921
+ return error2;
922
+ }
923
+ return new _DoNotDevError(`${context}: ${error2.message}`, error2.code, {
924
+ originalError: error2.originalError || error2,
925
+ context: { ...error2.context, ...options?.context || {} },
926
+ displayable: options?.displayable ?? error2.displayable
927
+ });
928
+ }
929
+ const message = context ? `${context}: ${error2.message}` : error2.message;
930
+ return new _DoNotDevError(message, code, {
931
+ originalError: error2,
932
+ context: options?.context,
933
+ displayable: options?.displayable
934
+ });
935
+ }
936
+ /**
937
+ * Maps common error types to DoNotDevErrorCode
938
+ *
939
+ * @param {Error} error - Error to analyze
940
+ * @returns {DoNotDevErrorCode} Mapped error code
941
+ */
942
+ static getErrorCodeFromError(error2) {
943
+ if (error2 instanceof _DoNotDevError) {
944
+ return error2.code;
945
+ }
946
+ const message = error2.message.toLowerCase();
947
+ if (error2.name === "ValidationError" || message.includes("validation")) {
948
+ return DO_NOT_DEV_ERROR_CODES.VALIDATION_ERROR;
949
+ }
950
+ if (message.includes("not found") || message.includes("no such file")) {
951
+ return DO_NOT_DEV_ERROR_CODES.FILE_NOT_FOUND;
952
+ }
953
+ if (message.includes("permission") || message.includes("access denied")) {
954
+ return DO_NOT_DEV_ERROR_CODES.PERMISSION_DENIED;
955
+ }
956
+ if (message.includes("timeout") || message.includes("timed out")) {
957
+ return DO_NOT_DEV_ERROR_CODES.TIMEOUT_ERROR;
958
+ }
959
+ if (message.includes("dependency") || message.includes("module not found")) {
960
+ return DO_NOT_DEV_ERROR_CODES.DEPENDENCY_ERROR;
961
+ }
962
+ return DO_NOT_DEV_ERROR_CODES.UNKNOWN_ERROR;
963
+ }
964
+ };
965
+ }
966
+ });
967
+
826
968
  // node_modules/.bun/fast-glob@3.3.3/node_modules/fast-glob/out/utils/array.js
827
969
  var require_array = __commonJS({
828
970
  "node_modules/.bun/fast-glob@3.3.3/node_modules/fast-glob/out/utils/array.js"(exports) {
@@ -2725,7 +2867,7 @@ var require_scan = __commonJS({
2725
2867
  }
2726
2868
  let base = str;
2727
2869
  let prefix = "";
2728
- let glob = "";
2870
+ let glob2 = "";
2729
2871
  if (start > 0) {
2730
2872
  prefix = str.slice(0, start);
2731
2873
  str = str.slice(start);
@@ -2733,10 +2875,10 @@ var require_scan = __commonJS({
2733
2875
  }
2734
2876
  if (base && isGlob === true && lastIndex > 0) {
2735
2877
  base = str.slice(0, lastIndex);
2736
- glob = str.slice(lastIndex);
2878
+ glob2 = str.slice(lastIndex);
2737
2879
  } else if (isGlob === true) {
2738
2880
  base = "";
2739
- glob = str;
2881
+ glob2 = str;
2740
2882
  } else {
2741
2883
  base = str;
2742
2884
  }
@@ -2746,7 +2888,7 @@ var require_scan = __commonJS({
2746
2888
  }
2747
2889
  }
2748
2890
  if (opts.unescape === true) {
2749
- if (glob) glob = utils.removeBackslashes(glob);
2891
+ if (glob2) glob2 = utils.removeBackslashes(glob2);
2750
2892
  if (base && backslashes === true) {
2751
2893
  base = utils.removeBackslashes(base);
2752
2894
  }
@@ -2756,7 +2898,7 @@ var require_scan = __commonJS({
2756
2898
  input,
2757
2899
  start,
2758
2900
  base,
2759
- glob,
2901
+ glob: glob2,
2760
2902
  isBrace,
2761
2903
  isBracket,
2762
2904
  isGlob,
@@ -3825,9 +3967,9 @@ var require_picomatch = __commonJS({
3825
3967
  var utils = require_utils2();
3826
3968
  var constants2 = require_constants2();
3827
3969
  var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
3828
- var picomatch = (glob, options, returnState = false) => {
3829
- if (Array.isArray(glob)) {
3830
- const fns = glob.map((input) => picomatch(input, options, returnState));
3970
+ var picomatch = (glob2, options, returnState = false) => {
3971
+ if (Array.isArray(glob2)) {
3972
+ const fns = glob2.map((input) => picomatch(input, options, returnState));
3831
3973
  const arrayMatcher = (str) => {
3832
3974
  for (const isMatch of fns) {
3833
3975
  const state2 = isMatch(str);
@@ -3837,13 +3979,13 @@ var require_picomatch = __commonJS({
3837
3979
  };
3838
3980
  return arrayMatcher;
3839
3981
  }
3840
- const isState = isObject(glob) && glob.tokens && glob.input;
3841
- if (glob === "" || typeof glob !== "string" && !isState) {
3982
+ const isState = isObject(glob2) && glob2.tokens && glob2.input;
3983
+ if (glob2 === "" || typeof glob2 !== "string" && !isState) {
3842
3984
  throw new TypeError("Expected pattern to be a non-empty string");
3843
3985
  }
3844
3986
  const opts = options || {};
3845
3987
  const posix = utils.isWindows(options);
3846
- const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
3988
+ const regex = isState ? picomatch.compileRe(glob2, options) : picomatch.makeRe(glob2, options, false, true);
3847
3989
  const state = regex.state;
3848
3990
  delete regex.state;
3849
3991
  let isIgnored = () => false;
@@ -3852,8 +3994,8 @@ var require_picomatch = __commonJS({
3852
3994
  isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
3853
3995
  }
3854
3996
  const matcher = (input, returnObject = false) => {
3855
- const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
3856
- const result = { glob, state, regex, posix, input, output, match, isMatch };
3997
+ const { isMatch, match, output } = picomatch.test(input, regex, options, { glob: glob2, posix });
3998
+ const result = { glob: glob2, state, regex, posix, input, output, match, isMatch };
3857
3999
  if (typeof opts.onResult === "function") {
3858
4000
  opts.onResult(result);
3859
4001
  }
@@ -3878,7 +4020,7 @@ var require_picomatch = __commonJS({
3878
4020
  }
3879
4021
  return matcher;
3880
4022
  };
3881
- picomatch.test = (input, regex, options, { glob, posix } = {}) => {
4023
+ picomatch.test = (input, regex, options, { glob: glob2, posix } = {}) => {
3882
4024
  if (typeof input !== "string") {
3883
4025
  throw new TypeError("Expected input to be a string");
3884
4026
  }
@@ -3887,11 +4029,11 @@ var require_picomatch = __commonJS({
3887
4029
  }
3888
4030
  const opts = options || {};
3889
4031
  const format = opts.format || (posix ? utils.toPosixSlashes : null);
3890
- let match = input === glob;
4032
+ let match = input === glob2;
3891
4033
  let output = match && format ? format(input) : input;
3892
4034
  if (match === false) {
3893
4035
  output = format ? format(input) : input;
3894
- match = output === glob;
4036
+ match = output === glob2;
3895
4037
  }
3896
4038
  if (match === false || opts.capture === true) {
3897
4039
  if (opts.matchBase === true || opts.basename === true) {
@@ -3902,8 +4044,8 @@ var require_picomatch = __commonJS({
3902
4044
  }
3903
4045
  return { isMatch: Boolean(match), match, output };
3904
4046
  };
3905
- picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
3906
- const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
4047
+ picomatch.matchBase = (input, glob2, options, posix = utils.isWindows(options)) => {
4048
+ const regex = glob2 instanceof RegExp ? glob2 : picomatch.makeRe(glob2, options);
3907
4049
  return regex.test(path.basename(input));
3908
4050
  };
3909
4051
  picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
@@ -4092,9 +4234,9 @@ var require_micromatch = __commonJS({
4092
4234
  }
4093
4235
  return [].concat(patterns).every((p) => picomatch(p, options)(str));
4094
4236
  };
4095
- micromatch.capture = (glob, input, options) => {
4237
+ micromatch.capture = (glob2, input, options) => {
4096
4238
  let posix = utils.isWindows(options);
4097
- let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
4239
+ let regex = picomatch.makeRe(String(glob2), { ...options, capture: true });
4098
4240
  let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
4099
4241
  if (match) {
4100
4242
  return match.slice(1).map((v) => v === void 0 ? "" : v);
@@ -4583,7 +4725,7 @@ var require_async = __commonJS({
4583
4725
  init_utils2();
4584
4726
  Object.defineProperty(exports, "__esModule", { value: true });
4585
4727
  exports.read = void 0;
4586
- function read(path, settings2, callback) {
4728
+ function read2(path, settings2, callback) {
4587
4729
  settings2.fs.lstat(path, (lstatError, lstat) => {
4588
4730
  if (lstatError !== null) {
4589
4731
  callFailureCallback(callback, lstatError);
@@ -4609,7 +4751,7 @@ var require_async = __commonJS({
4609
4751
  });
4610
4752
  });
4611
4753
  }
4612
- exports.read = read;
4754
+ exports.read = read2;
4613
4755
  function callFailureCallback(callback, error2) {
4614
4756
  callback(error2);
4615
4757
  }
@@ -4626,7 +4768,7 @@ var require_sync = __commonJS({
4626
4768
  init_utils2();
4627
4769
  Object.defineProperty(exports, "__esModule", { value: true });
4628
4770
  exports.read = void 0;
4629
- function read(path, settings2) {
4771
+ function read2(path, settings2) {
4630
4772
  const lstat = settings2.fs.lstatSync(path);
4631
4773
  if (!lstat.isSymbolicLink() || !settings2.followSymbolicLink) {
4632
4774
  return lstat;
@@ -4644,7 +4786,7 @@ var require_sync = __commonJS({
4644
4786
  throw error2;
4645
4787
  }
4646
4788
  }
4647
- exports.read = read;
4789
+ exports.read = read2;
4648
4790
  }
4649
4791
  });
4650
4792
 
@@ -4714,11 +4856,11 @@ var require_out = __commonJS({
4714
4856
  async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
4715
4857
  }
4716
4858
  exports.stat = stat;
4717
- function statSync2(path, optionsOrSettings) {
4859
+ function statSync3(path, optionsOrSettings) {
4718
4860
  const settings2 = getSettings(optionsOrSettings);
4719
4861
  return sync.read(path, settings2);
4720
4862
  }
4721
- exports.statSync = statSync2;
4863
+ exports.statSync = statSync3;
4722
4864
  function getSettings(settingsOrOptions = {}) {
4723
4865
  if (settingsOrOptions instanceof settings_1.default) {
4724
4866
  return settingsOrOptions;
@@ -4878,14 +5020,14 @@ var require_async2 = __commonJS({
4878
5020
  var constants_1 = require_constants3();
4879
5021
  var utils = require_utils4();
4880
5022
  var common = require_common();
4881
- function read(directory, settings2, callback) {
5023
+ function read2(directory, settings2, callback) {
4882
5024
  if (!settings2.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
4883
5025
  readdirWithFileTypes(directory, settings2, callback);
4884
5026
  return;
4885
5027
  }
4886
5028
  readdir(directory, settings2, callback);
4887
5029
  }
4888
- exports.read = read;
5030
+ exports.read = read2;
4889
5031
  function readdirWithFileTypes(directory, settings2, callback) {
4890
5032
  settings2.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
4891
5033
  if (readdirError !== null) {
@@ -4988,13 +5130,13 @@ var require_sync2 = __commonJS({
4988
5130
  var constants_1 = require_constants3();
4989
5131
  var utils = require_utils4();
4990
5132
  var common = require_common();
4991
- function read(directory, settings2) {
5133
+ function read2(directory, settings2) {
4992
5134
  if (!settings2.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
4993
5135
  return readdirWithFileTypes(directory, settings2);
4994
5136
  }
4995
5137
  return readdir(directory, settings2);
4996
5138
  }
4997
- exports.read = read;
5139
+ exports.read = read2;
4998
5140
  function readdirWithFileTypes(directory, settings2) {
4999
5141
  const dirents = settings2.fs.readdirSync(directory, { withFileTypes: true });
5000
5142
  return dirents.map((dirent) => {
@@ -7873,19 +8015,139 @@ import {
7873
8015
  isAbsolute as pathIsAbsolute
7874
8016
  } from "node:path";
7875
8017
  import { fileURLToPath } from "node:url";
7876
- var pathResolverInstance, normalizePath, pathExists, readSync, writeSync, ensureDirSync, getDirname, joinPath;
8018
+ function readdirSync3(dirPath, options) {
8019
+ if (options !== null && typeof options === "object" && options.withFileTypes === true) {
8020
+ return pathResolverInstance.readdirSync(dirPath, options);
8021
+ }
8022
+ return pathResolverInstance.readdirSync(dirPath, options);
8023
+ }
8024
+ function getDirnameFromUrl(importMetaUrl) {
8025
+ return dirname3(fileURLToPath(importMetaUrl));
8026
+ }
8027
+ function detectExecutionMode() {
8028
+ const fileUrlPath = fileURLToPath(import.meta.url);
8029
+ if (fileUrlPath.includes("node_modules")) {
8030
+ return "published";
8031
+ }
8032
+ if (fileUrlPath.includes("/dist/")) {
8033
+ return "published";
8034
+ }
8035
+ return "development";
8036
+ }
8037
+ function getTemplatesRoot() {
8038
+ const mode = detectExecutionMode();
8039
+ if (mode === "development") {
8040
+ const fileUrlPath = fileURLToPath(import.meta.url);
8041
+ const frameworkRoot = normalizePath(dirname3(fileUrlPath), "../../../..");
8042
+ return normalizePath(frameworkRoot, PACKAGE_PATHS.CLI, "templates");
8043
+ } else {
8044
+ try {
8045
+ const cliRoot2 = resolveFrameworkPackage("@donotdev/cli");
8046
+ if (cliRoot2) {
8047
+ const templatesPath = normalizePath(cliRoot2, "templates");
8048
+ if (pathExists(templatesPath)) {
8049
+ return templatesPath;
8050
+ }
8051
+ }
8052
+ } catch {
8053
+ }
8054
+ try {
8055
+ const req = createRequire2(import.meta.url);
8056
+ const cliPackageJsonPath = req.resolve("@donotdev/cli/package.json");
8057
+ const cliRoot2 = normalizePath(dirname3(cliPackageJsonPath));
8058
+ const templatesPath = normalizePath(cliRoot2, "templates");
8059
+ if (pathExists(templatesPath)) {
8060
+ return templatesPath;
8061
+ }
8062
+ } catch {
8063
+ }
8064
+ try {
8065
+ const currentScriptDir = getDirnameFromUrl(import.meta.url);
8066
+ const packageRoot = findPackageRootUp(currentScriptDir, "@donotdev/cli");
8067
+ if (packageRoot) {
8068
+ const templatesPath = normalizePath(packageRoot, "templates");
8069
+ if (pathExists(templatesPath)) {
8070
+ return templatesPath;
8071
+ }
8072
+ }
8073
+ } catch {
8074
+ }
8075
+ const cliRoot = getCliRootFromBundle();
8076
+ return normalizePath(cliRoot, "templates");
8077
+ }
8078
+ }
8079
+ function findPackageRootUp(startDir, packageName) {
8080
+ let currentDir = normalizePath(startDir);
8081
+ const root = parse(currentDir).root;
8082
+ const fs2 = createRequire2(import.meta.url)("node:fs");
8083
+ while (currentDir !== root) {
8084
+ const packageJsonPath = joinPath(currentDir, "package.json");
8085
+ if (fs2.existsSync(packageJsonPath)) {
8086
+ try {
8087
+ const content = fs2.readFileSync(packageJsonPath, "utf8");
8088
+ const pkg = JSON.parse(content);
8089
+ if (pkg.name === packageName) {
8090
+ return currentDir;
8091
+ }
8092
+ } catch {
8093
+ }
8094
+ }
8095
+ const parentDir = getDirname(currentDir);
8096
+ if (parentDir === currentDir) break;
8097
+ currentDir = parentDir;
8098
+ }
8099
+ return null;
8100
+ }
8101
+ function getCliRootFromBundle() {
8102
+ const currentDir = getDirnameFromUrl(import.meta.url);
8103
+ return normalizePath(currentDir, "..", "..", "..");
8104
+ }
8105
+ async function glob(pattern, options = {}) {
8106
+ const patterns = Array.isArray(pattern) ? pattern : [pattern];
8107
+ const cwd = options.cwd || pathResolverInstance.getAppRoot() || process.cwd();
8108
+ const normalizeCwd = pathResolverInstance.normalizePath(cwd);
8109
+ const relativePatterns = patterns.map((p) => {
8110
+ const normalizedPattern = pathResolverInstance.normalizePath(p);
8111
+ if (normalizedPattern.startsWith(normalizeCwd)) {
8112
+ return normalizedPattern.slice(normalizeCwd.length + 1);
8113
+ }
8114
+ if (normalizedPattern.startsWith("/") || /^[A-Z]:/.test(normalizedPattern)) {
8115
+ return normalizedPattern;
8116
+ }
8117
+ return normalizedPattern;
8118
+ });
8119
+ const shouldReturnAbsolute = options.absolute === true;
8120
+ return await pathResolverInstance._globWithNormalization(relativePatterns, {
8121
+ cwd,
8122
+ absolute: shouldReturnAbsolute,
8123
+ onlyFiles: options.nodir !== false && options.onlyDirectories !== true,
8124
+ onlyDirectories: options.onlyDirectories,
8125
+ ignore: options.ignore,
8126
+ dot: options.dot,
8127
+ braceExpansion: true,
8128
+ extglob: true,
8129
+ globstar: true
8130
+ });
8131
+ }
8132
+ var pathResolverInstance, getAppRoot, resolveFrameworkPackage, normalizePath, pathExists, read, readSync, write, writeSync, statSync2, ensureDir, ensureDirSync, getDirname, joinPath;
7877
8133
  var init_pathResolver = __esm({
7878
8134
  "packages/tooling/src/utils/pathResolver.ts"() {
7879
8135
  "use strict";
7880
8136
  init_utils2();
7881
8137
  init_PathResolver();
7882
8138
  pathResolverInstance = PathResolver.getInstance({ debug: false });
8139
+ getAppRoot = () => pathResolverInstance.getAppRoot();
8140
+ resolveFrameworkPackage = (name, from) => pathResolverInstance.resolveFrameworkPackage(name, from || null);
7883
8141
  normalizePath = (...pathSegments) => {
7884
8142
  return pathResolverInstance.normalizePath(join3(...pathSegments));
7885
8143
  };
7886
8144
  pathExists = (filePath, silent = false) => pathResolverInstance.pathExists(filePath, silent);
8145
+ read = async (filePath, options) => pathResolverInstance.read(filePath, options);
7887
8146
  readSync = (filePath, options) => pathResolverInstance.readSync(filePath, options);
8147
+ write = async (filePath, content, options) => pathResolverInstance.write(filePath, content, options);
7888
8148
  writeSync = (filePath, content, options) => pathResolverInstance.writeSync(filePath, content, options);
8149
+ statSync2 = (filePath) => pathResolverInstance.statSync(filePath);
8150
+ ensureDir = async (dirPath) => pathResolverInstance.ensureDir(dirPath);
7889
8151
  ensureDirSync = (dirPath) => pathResolverInstance.ensureDirSync(dirPath);
7890
8152
  getDirname = (filePath) => {
7891
8153
  return normalizePath(dirname3(filePath));
@@ -7896,14 +8158,56 @@ var init_pathResolver = __esm({
7896
8158
  }
7897
8159
  });
7898
8160
 
8161
+ // packages/tooling/src/utils/typed-file-operations.ts
8162
+ function readPackageJson(filePath) {
8163
+ if (!pathExists(filePath)) {
8164
+ throw new DoNotDevError(
8165
+ `package.json not found: ${filePath}`,
8166
+ DO_NOT_DEV_ERROR_CODES.FILE_NOT_FOUND,
8167
+ { context: { filePath } }
8168
+ );
8169
+ }
8170
+ const content = readSync(filePath, { format: "json" });
8171
+ if (!content || typeof content !== "object" || !("name" in content)) {
8172
+ throw new DoNotDevError(
8173
+ `Invalid package.json: ${filePath}`,
8174
+ DO_NOT_DEV_ERROR_CODES.CONFIG_INVALID,
8175
+ { context: { filePath } }
8176
+ );
8177
+ }
8178
+ return content;
8179
+ }
8180
+ var init_typed_file_operations = __esm({
8181
+ "packages/tooling/src/utils/typed-file-operations.ts"() {
8182
+ "use strict";
8183
+ init_utils2();
8184
+ init_errors();
8185
+ init_pathResolver();
8186
+ }
8187
+ });
8188
+
7899
8189
  // packages/tooling/src/utils/type-guards.ts
7900
- function isObjectLike(value) {
7901
- return typeof value === "object" && value !== null;
8190
+ function isRecord(value) {
8191
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8192
+ }
8193
+ function asText(value) {
8194
+ return typeof value === "string" ? value : null;
8195
+ }
8196
+ function requireText(value, filePath) {
8197
+ if (typeof value !== "string") {
8198
+ throw new DoNotDevError(
8199
+ `Cannot read text file: ${filePath}`,
8200
+ DO_NOT_DEV_ERROR_CODES.FILE_NOT_FOUND,
8201
+ { context: { filePath } }
8202
+ );
8203
+ }
8204
+ return value;
7902
8205
  }
7903
8206
  var init_type_guards = __esm({
7904
8207
  "packages/tooling/src/utils/type-guards.ts"() {
7905
8208
  "use strict";
7906
8209
  init_utils2();
8210
+ init_errors();
7907
8211
  }
7908
8212
  });
7909
8213
 
@@ -7934,6 +8238,184 @@ var init_utils2 = __esm({
7934
8238
  }
7935
8239
  });
7936
8240
 
8241
+ // packages/tooling/src/utils/app-detection.ts
8242
+ function isVercelFunctionsDir(functionsDir) {
8243
+ return statSync2(joinPath(functionsDir, "src", "api"))?.isDirectory() ?? false;
8244
+ }
8245
+ function detectApps(projectRoot) {
8246
+ const apps = [];
8247
+ const appsDir = joinPath(projectRoot, "apps");
8248
+ const appsDirStat = statSync2(appsDir);
8249
+ if (pathExists(appsDir) && appsDirStat?.isDirectory()) {
8250
+ const appDirs = readdirSync3(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name).sort();
8251
+ for (const appDir of appDirs) {
8252
+ const appPath = joinPath(appsDir, appDir);
8253
+ const packageJsonPath = joinPath(appPath, "package.json");
8254
+ if (pathExists(packageJsonPath)) {
8255
+ const appInfo = analyzeApp(appPath, appDir);
8256
+ if (appInfo) {
8257
+ apps.push(appInfo);
8258
+ }
8259
+ }
8260
+ }
8261
+ } else {
8262
+ const packageJsonPath = joinPath(projectRoot, "package.json");
8263
+ if (pathExists(packageJsonPath)) {
8264
+ try {
8265
+ const packageJson = readPackageJson(packageJsonPath);
8266
+ if (packageJson && (packageJson.dependencies?.vite || packageJson.devDependencies?.vite || packageJson.dependencies?.next || packageJson.devDependencies?.next)) {
8267
+ const pathParts = projectRoot.split(/[/\\]/);
8268
+ const appName = pathParts[pathParts.length - 1] || "app";
8269
+ const appInfo = analyzeApp(projectRoot, appName);
8270
+ if (appInfo) {
8271
+ apps.push(appInfo);
8272
+ }
8273
+ }
8274
+ } catch {
8275
+ }
8276
+ }
8277
+ }
8278
+ return apps;
8279
+ }
8280
+ function analyzeApp(appPath, appName) {
8281
+ const packageJsonPath = joinPath(appPath, "package.json");
8282
+ if (!pathExists(packageJsonPath)) {
8283
+ return null;
8284
+ }
8285
+ let packageJson = null;
8286
+ try {
8287
+ packageJson = readPackageJson(packageJsonPath);
8288
+ if (!packageJson.name) {
8289
+ return null;
8290
+ }
8291
+ } catch {
8292
+ return null;
8293
+ }
8294
+ let framework = "unknown";
8295
+ if (pathExists(joinPath(appPath, "next.config.js")) || pathExists(joinPath(appPath, "next.config.ts")) || pathExists(joinPath(appPath, "next.config.mjs")) || packageJson.dependencies?.next || packageJson.devDependencies?.next) {
8296
+ framework = "nextjs";
8297
+ } else if (pathExists(joinPath(appPath, "vite.config.ts")) || pathExists(joinPath(appPath, "vite.config.js")) || pathExists(joinPath(appPath, "vite.config.mjs")) || packageJson.dependencies?.vite || packageJson.devDependencies?.vite) {
8298
+ framework = "vite";
8299
+ }
8300
+ const firebaseJsonPath = joinPath(appPath, "firebase.json");
8301
+ const hasFirebase = pathExists(firebaseJsonPath);
8302
+ const supabaseDir = joinPath(appPath, "supabase");
8303
+ const supabaseConfigPath = joinPath(supabaseDir, "config.toml");
8304
+ const hasSupabaseDep = !!(packageJson.dependencies?.["@donotdev/supabase"] || packageJson.dependencies?.["@supabase/supabase-js"]);
8305
+ let hasSupabase = pathExists(supabaseDir) || pathExists(supabaseConfigPath) || hasSupabaseDep;
8306
+ if (!hasSupabase) {
8307
+ try {
8308
+ const envPath = joinPath(appPath, ".env");
8309
+ if (pathExists(envPath)) {
8310
+ const envContent = requireText(readSync(envPath), envPath);
8311
+ if (envContent.match(/VITE_SUPABASE_URL=.+/)) {
8312
+ hasSupabase = true;
8313
+ }
8314
+ }
8315
+ } catch {
8316
+ }
8317
+ }
8318
+ let provider = "unknown";
8319
+ if (hasFirebase && hasSupabase) {
8320
+ provider = "both";
8321
+ } else if (hasFirebase) {
8322
+ provider = "firebase";
8323
+ } else if (hasSupabase) {
8324
+ provider = "supabase";
8325
+ }
8326
+ let firebaseConfig;
8327
+ if (hasFirebase) {
8328
+ try {
8329
+ const config = readSync(firebaseJsonPath, { format: "json" });
8330
+ if (config && typeof config === "object") {
8331
+ const fb = config;
8332
+ firebaseConfig = {
8333
+ projectId: fb.projectId,
8334
+ hasHosting: !!fb.hosting,
8335
+ hasFunctions: !!fb.functions,
8336
+ hasFirestoreRules: !!fb.firestore?.rules,
8337
+ hasStorageRules: !!fb.storage?.rules
8338
+ };
8339
+ }
8340
+ } catch {
8341
+ firebaseConfig = {
8342
+ hasHosting: false,
8343
+ hasFunctions: false,
8344
+ hasFirestoreRules: false,
8345
+ hasStorageRules: false
8346
+ };
8347
+ }
8348
+ }
8349
+ const supabaseFunctionsDir = joinPath(supabaseDir, "functions");
8350
+ const supabaseMigrationsDir = joinPath(supabaseDir, "migrations");
8351
+ let supabaseConfig;
8352
+ if (hasSupabase) {
8353
+ let url;
8354
+ try {
8355
+ const envPath = joinPath(appPath, ".env");
8356
+ if (pathExists(envPath)) {
8357
+ const envContent = requireText(readSync(envPath), envPath);
8358
+ const urlMatch = envContent.match(/VITE_SUPABASE_URL=(.+)/);
8359
+ if (urlMatch && urlMatch[1]) {
8360
+ url = urlMatch[1].trim();
8361
+ }
8362
+ }
8363
+ } catch {
8364
+ }
8365
+ supabaseConfig = {
8366
+ url,
8367
+ hasFunctions: pathExists(supabaseFunctionsDir),
8368
+ hasMigrations: pathExists(supabaseMigrationsDir)
8369
+ };
8370
+ }
8371
+ let functions;
8372
+ if (hasFirebase && firebaseConfig?.hasFunctions) {
8373
+ const firebaseFunctionsDir = joinPath(appPath, "functions");
8374
+ const firebaseFunctionsStat = statSync2(firebaseFunctionsDir);
8375
+ if (pathExists(firebaseFunctionsDir) && (firebaseFunctionsStat?.isDirectory() ?? false)) {
8376
+ functions = "firebase";
8377
+ }
8378
+ }
8379
+ if (!functions && hasSupabase) {
8380
+ const sbFunctionsStat = statSync2(supabaseFunctionsDir);
8381
+ if (pathExists(supabaseFunctionsDir) && (sbFunctionsStat?.isDirectory() ?? false)) {
8382
+ functions = "supabase";
8383
+ }
8384
+ }
8385
+ if (!functions && isVercelFunctionsDir(joinPath(appPath, "functions"))) {
8386
+ functions = "vercel";
8387
+ }
8388
+ let hosting;
8389
+ if (hasFirebase && firebaseConfig?.hasHosting) {
8390
+ hosting = "firebase";
8391
+ }
8392
+ if (!hosting) {
8393
+ if (pathExists(joinPath(appPath, "vercel.json")) || pathExists(joinPath(appPath, ".vercel"))) {
8394
+ hosting = "vercel";
8395
+ }
8396
+ }
8397
+ return {
8398
+ name: appName,
8399
+ packageName: packageJson.name || appName,
8400
+ path: appPath,
8401
+ framework,
8402
+ provider,
8403
+ functions,
8404
+ hosting,
8405
+ firebaseConfig,
8406
+ supabaseConfig
8407
+ };
8408
+ }
8409
+ var init_app_detection = __esm({
8410
+ "packages/tooling/src/utils/app-detection.ts"() {
8411
+ "use strict";
8412
+ init_utils2();
8413
+ init_pathResolver();
8414
+ init_typed_file_operations();
8415
+ init_type_guards();
8416
+ }
8417
+ });
8418
+
7937
8419
  // packages/tooling/src/utils/error-handling.ts
7938
8420
  function isError(error2) {
7939
8421
  return error2 instanceof Error;
@@ -7973,129 +8455,442 @@ init_utils2();
7973
8455
 
7974
8456
  // packages/tooling/src/cli/index.ts
7975
8457
  init_utils2();
7976
- init_create_utils();
7977
8458
 
7978
- // packages/tooling/src/cli/agent-setup.ts
8459
+ // packages/tooling/src/maintenance/template-sync.ts
7979
8460
  init_utils2();
7980
8461
  init_cli_output();
7981
- init_error_handling();
7982
- init_type_guards();
8462
+ init_errors();
7983
8463
  init_pathResolver();
7984
- var mcpConfig = {
7985
- command: "bunx",
7986
- args: ["@donotdev/mcp-server@latest"]
7987
- };
7988
- function readJsonConfig(filePath, fallback) {
8464
+ init_app_detection();
8465
+ init_type_guards();
8466
+ var PROJECT_MANIFEST = [
8467
+ // Documentation: the framework's instructions and rules for any agent
8468
+ { pattern: "AGENTS.md.example", kind: "docs", strategy: "replace" },
8469
+ { pattern: "CLAUDE.md.example", kind: "docs", strategy: "create-if-missing" },
8470
+ {
8471
+ pattern: ".claude/rules/**/*.md.example",
8472
+ ignore: [".claude/rules/consumer-ux.md.example"],
8473
+ kind: "docs",
8474
+ strategy: "replace"
8475
+ },
8476
+ { pattern: ".cursor/rules/**/*.mdc.example", kind: "docs", strategy: "replace" },
8477
+ { pattern: ".dndev/args.json.example", kind: "docs", strategy: "create-if-missing" },
8478
+ // AI harness: agents, skills, hooks, their registration, the MCP servers
8479
+ { pattern: ".claude/agents/**/*.md.example", kind: "harness", strategy: "replace" },
8480
+ { pattern: ".claude/skills/**/*", kind: "harness", strategy: "replace" },
8481
+ { pattern: ".claude/hooks/**/*.example", kind: "harness", strategy: "replace" },
8482
+ { pattern: ".claude/settings.json.example", kind: "harness", strategy: "merge-settings" },
8483
+ { pattern: ".claude/rules/consumer-ux.md.example", kind: "harness", strategy: "replace" },
8484
+ { pattern: ".mcp.json.example", kind: "harness", strategy: "merge-mcp" },
8485
+ { pattern: ".cursor/mcp.json.example", kind: "harness", strategy: "merge-mcp" },
8486
+ { pattern: ".gemini/settings.json.example", kind: "harness", strategy: "merge-mcp" }
8487
+ ];
8488
+ var MCP_TEMPLATE_FILE = ".mcp.json.example";
8489
+ function isGlobalHarness() {
8490
+ return process.env.DNDEV_HARNESS === "global";
8491
+ }
8492
+ function toDest(relativeTemplatePath) {
8493
+ return relativeTemplatePath.endsWith(".example") ? relativeTemplatePath.slice(0, -".example".length) : relativeTemplatePath;
8494
+ }
8495
+ async function listTemplateFiles(sourceRoot, kind) {
8496
+ const root = normalizePath(sourceRoot);
8497
+ const files = [];
8498
+ for (const entry of PROJECT_MANIFEST) {
8499
+ if (entry.kind !== kind) continue;
8500
+ const matches = await glob(entry.pattern, {
8501
+ cwd: root,
8502
+ onlyFiles: true,
8503
+ ignore: entry.ignore
8504
+ });
8505
+ for (const match of matches) {
8506
+ const relativeTemplatePath = normalizePath(match);
8507
+ files.push({
8508
+ sourceFile: joinPath(root, relativeTemplatePath),
8509
+ relativeDest: toDest(relativeTemplatePath),
8510
+ strategy: entry.strategy
8511
+ });
8512
+ }
8513
+ }
8514
+ return files;
8515
+ }
8516
+ function getSourceTemplatesPath() {
7989
8517
  try {
7990
- if (pathExists(filePath)) {
7991
- const content = readSync(filePath, { format: "json" });
7992
- return content;
8518
+ const templatesRoot = getTemplatesRoot();
8519
+ const rootConsumerPath = joinPath(templatesRoot, "root-consumer");
8520
+ if (pathExists(rootConsumerPath)) {
8521
+ return normalizePath(rootConsumerPath);
7993
8522
  }
7994
8523
  } catch {
7995
8524
  }
7996
- return fallback;
8525
+ const appRoot = getAppRoot();
8526
+ if (appRoot) {
8527
+ const directPath = joinPath(
8528
+ appRoot,
8529
+ "node_modules",
8530
+ "@donotdev",
8531
+ "cli",
8532
+ "templates",
8533
+ "root-consumer"
8534
+ );
8535
+ if (pathExists(directPath)) {
8536
+ log2.info("Found templates via node_modules lookup");
8537
+ return normalizePath(directPath);
8538
+ }
8539
+ }
8540
+ log2.error("Could not find the framework templates (@donotdev/cli).");
8541
+ log2.info(" Templates are looked up the same way as create-project:");
8542
+ log2.info(" \u2022 Published mode: the templates shipped with the running CLI");
8543
+ log2.info(" \u2022 Dev mode: packages/cli/templates (from monorepo)");
8544
+ log2.info(" Run the global CLI (dndev), not a copy inside the project.");
8545
+ return null;
8546
+ }
8547
+ var PROJECT_SECTION_MARKER = "<!-- dndev:project-specific -->";
8548
+ function detectProjectPlatform(projectRoot) {
8549
+ const apps = detectApps(projectRoot);
8550
+ const withProvider = apps.find(
8551
+ (app) => app.provider === "firebase" || app.provider === "supabase"
8552
+ );
8553
+ if (withProvider?.provider === "firebase") return "firebase";
8554
+ if (withProvider?.provider === "supabase") return "supabase";
8555
+ if (apps.some((app) => app.functions === "vercel")) return "vercel";
8556
+ return "none";
7997
8557
  }
7998
- function setMcpServer(config, filePath, name, server) {
7999
- if (!isObjectLike(config)) {
8000
- throw new Error(`Invalid JSON config: ${filePath}`);
8558
+ function mergeProjectSection(template, existing) {
8559
+ const templateIndex = template.indexOf(PROJECT_SECTION_MARKER);
8560
+ if (templateIndex === -1 || existing === null) return template;
8561
+ const existingIndex = existing.indexOf(PROJECT_SECTION_MARKER);
8562
+ if (existingIndex === -1) return template;
8563
+ return template.slice(0, templateIndex + PROJECT_SECTION_MARKER.length) + existing.slice(existingIndex + PROJECT_SECTION_MARKER.length);
8564
+ }
8565
+ function mergeMcpConfig(template, existing) {
8566
+ if (existing === null) return template;
8567
+ const templateConfig = JSON.parse(template);
8568
+ const existingConfig = JSON.parse(existing);
8569
+ const merged = {
8570
+ ...existingConfig,
8571
+ ...templateConfig,
8572
+ mcpServers: {
8573
+ ...existingConfig.mcpServers,
8574
+ ...templateConfig.mcpServers
8575
+ }
8576
+ };
8577
+ if (JSON.stringify(merged) === JSON.stringify(existingConfig)) {
8578
+ return existing;
8001
8579
  }
8002
- const servers = config.mcpServers || {};
8003
- if (!isObjectLike(servers)) {
8004
- throw new Error(`Invalid "mcpServers" in ${filePath}`);
8580
+ return JSON.stringify(merged, null, 2) + "\n";
8581
+ }
8582
+ function mergeHookGroups(existing, template) {
8583
+ const groupHooks = (group) => isRecord(group) && Array.isArray(group.hooks) ? group.hooks : [];
8584
+ const hookCommand = (hook) => isRecord(hook) ? hook.command : void 0;
8585
+ const templateCommands = new Set(
8586
+ template.flatMap((group) => groupHooks(group).map(hookCommand))
8587
+ );
8588
+ const kept = existing.flatMap((group) => {
8589
+ if (!isRecord(group)) return [group];
8590
+ const ownHooks = groupHooks(group).filter(
8591
+ (hook) => !templateCommands.has(hookCommand(hook))
8592
+ );
8593
+ return ownHooks.length > 0 ? [{ ...group, hooks: ownHooks }] : [];
8594
+ });
8595
+ return [...template, ...kept];
8596
+ }
8597
+ function mergeJsonValue(existing, template, path) {
8598
+ if (Array.isArray(existing) && Array.isArray(template)) {
8599
+ if (path.length === 2 && path[0] === "hooks") {
8600
+ return mergeHookGroups(existing, template);
8601
+ }
8602
+ const existingItems = new Set(existing.map((item) => JSON.stringify(item)));
8603
+ return [
8604
+ ...existing,
8605
+ ...template.filter((item) => !existingItems.has(JSON.stringify(item)))
8606
+ ];
8607
+ }
8608
+ if (isRecord(existing) && isRecord(template)) {
8609
+ const merged = {};
8610
+ for (const key of Object.keys(existing)) {
8611
+ merged[key] = key in template ? mergeJsonValue(existing[key], template[key], [...path, key]) : existing[key];
8612
+ }
8613
+ for (const key of Object.keys(template)) {
8614
+ if (!(key in existing)) merged[key] = template[key];
8615
+ }
8616
+ return merged;
8005
8617
  }
8006
- config.mcpServers = servers;
8007
- servers[name] = server;
8008
- return config;
8618
+ return template;
8009
8619
  }
8010
- function writeJsonConfig(filePath, data) {
8011
- ensureDirSync(getDirname(filePath));
8012
- writeSync(filePath, data, { overwrite: true });
8620
+ function mergeClaudeSettings(template, existing) {
8621
+ if (existing === null) return template;
8622
+ const existingSettings = JSON.parse(existing);
8623
+ const merged = mergeJsonValue(existingSettings, JSON.parse(template), []);
8624
+ if (JSON.stringify(merged) === JSON.stringify(existingSettings)) {
8625
+ return existing;
8626
+ }
8627
+ return JSON.stringify(merged, null, 2) + "\n";
8013
8628
  }
8014
- async function main(options = {}) {
8015
- intro("DoNotDev Agent Setup");
8016
- const cwd = process.cwd();
8017
- const isWindows = process.platform === "win32";
8018
- const isMac = process.platform === "darwin";
8019
- const homeDir = process.env.HOME || process.env.USERPROFILE || "";
8020
- const mcpJsonPath = joinPath(cwd, ".mcp.json");
8021
- if (options.dryRun) {
8022
- note(`[DRY RUN] Would write ${mcpJsonPath}`, "Claude Code");
8023
- } else {
8629
+ async function syncFile(file, appRoot) {
8630
+ const destPath = joinPath(appRoot, file.relativeDest);
8631
+ const exists = pathExists(destPath);
8632
+ if (file.strategy === "create-if-missing" && exists) return "preserved";
8633
+ const templateContent = asText(await read(file.sourceFile, { format: "text" }));
8634
+ if (!templateContent) {
8635
+ throw new Error(`Template file is empty or unreadable: ${file.sourceFile}`);
8636
+ }
8637
+ const existingContent = exists ? asText(await read(destPath, { format: "text" })) : null;
8638
+ let content;
8639
+ switch (file.strategy) {
8640
+ case "merge-mcp":
8641
+ content = mergeMcpConfig(templateContent, existingContent);
8642
+ break;
8643
+ case "merge-settings":
8644
+ content = mergeClaudeSettings(templateContent, existingContent);
8645
+ break;
8646
+ case "create-if-missing":
8647
+ content = templateContent.replace("{{platform}}", detectProjectPlatform(appRoot));
8648
+ break;
8649
+ case "replace":
8650
+ content = mergeProjectSection(templateContent, existingContent);
8651
+ break;
8652
+ }
8653
+ if (existingContent === content) return "unchanged";
8654
+ await ensureDir(getDirname(destPath));
8655
+ await write(destPath, content, { format: "text", overwrite: true });
8656
+ return "synced";
8657
+ }
8658
+ async function syncTemplateFiles(files, appRoot, options = {}) {
8659
+ const result = { synced: 0, preserved: 0, errors: 0 };
8660
+ for (const file of files) {
8661
+ const exists = pathExists(joinPath(appRoot, file.relativeDest));
8662
+ if (options.dryRun) {
8663
+ if (file.strategy === "create-if-missing" && exists) {
8664
+ log2.info(`[DRY RUN] Would preserve: ${file.relativeDest}`);
8665
+ result.preserved++;
8666
+ } else {
8667
+ log2.info(`[DRY RUN] Would sync: ${file.relativeDest}`);
8668
+ result.synced++;
8669
+ }
8670
+ continue;
8671
+ }
8024
8672
  try {
8025
- const config = setMcpServer(
8026
- readJsonConfig(mcpJsonPath, { mcpServers: {} }),
8027
- mcpJsonPath,
8028
- "donotdev",
8029
- mcpConfig
8673
+ const outcome = await syncFile(file, appRoot);
8674
+ if (outcome === "synced") {
8675
+ result.synced++;
8676
+ log2.info(`Synced: ${file.relativeDest}`);
8677
+ } else if (outcome === "preserved") {
8678
+ result.preserved++;
8679
+ }
8680
+ } catch (error2) {
8681
+ result.errors++;
8682
+ log2.error(
8683
+ `Error syncing ${file.relativeDest}:`,
8684
+ DoNotDevError.from(
8685
+ error2,
8686
+ `Failed to sync ${file.relativeDest}`,
8687
+ "file-operation-error"
8688
+ )
8030
8689
  );
8031
- writeJsonConfig(mcpJsonPath, config);
8032
- log2.success(".mcp.json configured (Claude Code).");
8033
- } catch (e) {
8034
- log2.error(`Failed to configure .mcp.json: ${getErrorMessage(e)}`);
8035
8690
  }
8036
8691
  }
8037
- const cursorMcpPath = joinPath(cwd, ".cursor", "mcp.json");
8038
- if (options.dryRun) {
8039
- note(`[DRY RUN] Would write ${cursorMcpPath}`, "Cursor");
8040
- } else {
8692
+ return result;
8693
+ }
8694
+
8695
+ // packages/tooling/src/cli/index.ts
8696
+ init_create_utils();
8697
+
8698
+ // packages/tooling/src/maintenance/sync-harness.ts
8699
+ init_utils2();
8700
+ init_cli_output();
8701
+ init_errors();
8702
+ init_pathResolver();
8703
+ init_type_guards();
8704
+ import { readdirSync as readdirSync4, rmdirSync, rmSync as rmSync2 } from "node:fs";
8705
+ function stripTemplateHooks(template, existing) {
8706
+ const settings2 = JSON.parse(existing);
8707
+ const templateSettings = JSON.parse(template);
8708
+ if (!isRecord(settings2) || !isRecord(settings2.hooks)) return existing;
8709
+ const templateHooks = isRecord(templateSettings) && isRecord(templateSettings.hooks) ? templateSettings.hooks : {};
8710
+ const commandsOf = (groups) => new Set(
8711
+ (Array.isArray(groups) ? groups : []).flatMap(
8712
+ (group) => isRecord(group) && Array.isArray(group.hooks) ? group.hooks.map((hook) => isRecord(hook) ? hook.command : void 0) : []
8713
+ )
8714
+ );
8715
+ const hooks = {};
8716
+ for (const [event, groups] of Object.entries(settings2.hooks)) {
8717
+ const templateCommands = commandsOf(templateHooks[event]);
8718
+ const kept = (Array.isArray(groups) ? groups : []).flatMap((group) => {
8719
+ if (!isRecord(group) || !Array.isArray(group.hooks)) return [group];
8720
+ const own = group.hooks.filter(
8721
+ (hook) => !(isRecord(hook) && templateCommands.has(hook.command))
8722
+ );
8723
+ return own.length > 0 ? [{ ...group, hooks: own }] : [];
8724
+ });
8725
+ if (kept.length > 0) hooks[event] = kept;
8726
+ }
8727
+ const { hooks: _removed, ...rest } = settings2;
8728
+ const next = Object.keys(hooks).length > 0 ? { ...rest, hooks } : rest;
8729
+ if (JSON.stringify(next) === JSON.stringify(settings2)) return existing;
8730
+ return JSON.stringify(next, null, 2) + "\n";
8731
+ }
8732
+ function stripTemplateServers(template, existing) {
8733
+ const config = JSON.parse(existing);
8734
+ const templateConfig = JSON.parse(template);
8735
+ if (!isRecord(config) || !isRecord(config.mcpServers)) return existing;
8736
+ const templateNames = new Set(
8737
+ isRecord(templateConfig) && isRecord(templateConfig.mcpServers) ? Object.keys(templateConfig.mcpServers) : []
8738
+ );
8739
+ const servers = Object.fromEntries(
8740
+ Object.entries(config.mcpServers).filter(([name]) => !templateNames.has(name))
8741
+ );
8742
+ if (Object.keys(servers).length === Object.keys(config.mcpServers).length) {
8743
+ return existing;
8744
+ }
8745
+ const { mcpServers: _servers, ...rest } = config;
8746
+ if (Object.keys(servers).length === 0 && Object.keys(rest).length === 0) {
8747
+ return null;
8748
+ }
8749
+ return JSON.stringify({ ...rest, mcpServers: servers }, null, 2) + "\n";
8750
+ }
8751
+ async function planRemoval(file, appRoot) {
8752
+ const destPath = joinPath(appRoot, file.relativeDest);
8753
+ if (!pathExists(destPath)) return null;
8754
+ if (file.strategy !== "merge-mcp" && file.strategy !== "merge-settings") {
8755
+ return { action: "delete" };
8756
+ }
8757
+ const template = asText(await read(file.sourceFile, { format: "text" }));
8758
+ const existing = asText(await read(destPath, { format: "text" }));
8759
+ if (template === null || existing === null) {
8760
+ throw new Error(`Cannot read ${file.relativeDest} or its template`);
8761
+ }
8762
+ const next = file.strategy === "merge-mcp" ? stripTemplateServers(template, existing) : stripTemplateHooks(template, existing);
8763
+ if (next === existing) return null;
8764
+ return next === null ? { action: "delete" } : { action: "write", content: next };
8765
+ }
8766
+ function removeHarnessFile(file, appRoot) {
8767
+ rmSync2(file);
8768
+ const stop = joinPath(appRoot, ".claude");
8769
+ let dir = getDirname(file);
8770
+ while (dir.startsWith(stop + "/") && readdirSync4(dir).length === 0) {
8771
+ rmdirSync(dir);
8772
+ dir = getDirname(dir);
8773
+ }
8774
+ }
8775
+ async function removeHarnessCopies(files, appRoot, dryRun) {
8776
+ let removed = 0;
8777
+ let errors = 0;
8778
+ for (const file of files) {
8041
8779
  try {
8042
- const config = setMcpServer(
8043
- readJsonConfig(cursorMcpPath, { mcpServers: {} }),
8044
- cursorMcpPath,
8045
- "donotdev",
8046
- mcpConfig
8780
+ const removal = await planRemoval(file, appRoot);
8781
+ if (!removal) continue;
8782
+ removed++;
8783
+ if (dryRun) {
8784
+ log2.info(`[DRY RUN] Global harness, would remove the template copy or entries: ${file.relativeDest}`);
8785
+ continue;
8786
+ }
8787
+ const destPath = joinPath(appRoot, file.relativeDest);
8788
+ if (removal.action === "delete") {
8789
+ removeHarnessFile(destPath, appRoot);
8790
+ } else {
8791
+ await write(destPath, removal.content, { format: "text", overwrite: true });
8792
+ }
8793
+ log2.info(`Global harness, removed the template copy or entries: ${file.relativeDest}`);
8794
+ } catch (error2) {
8795
+ errors++;
8796
+ log2.error(
8797
+ `Error removing ${file.relativeDest}:`,
8798
+ DoNotDevError.from(
8799
+ error2,
8800
+ `Failed to remove ${file.relativeDest}`,
8801
+ "file-operation-error"
8802
+ )
8047
8803
  );
8048
- writeJsonConfig(cursorMcpPath, config);
8049
- log2.success(".cursor/mcp.json configured (Cursor).");
8050
- } catch (e) {
8051
- log2.error(`Failed to configure Cursor: ${getErrorMessage(e)}`);
8052
8804
  }
8053
8805
  }
8054
- const geminiConfigPath = joinPath(cwd, ".gemini", "settings.json");
8806
+ if (removed === 0 && errors === 0) {
8807
+ log2.info("Global harness: no harness copy in this app");
8808
+ }
8809
+ return errors > 0 ? 1 : 0;
8810
+ }
8811
+ async function syncHarness(options = {}) {
8812
+ const appRoot = getAppRoot();
8813
+ if (!appRoot) {
8814
+ log2.error("Could not determine project root");
8815
+ return 1;
8816
+ }
8817
+ const sourceRoot = getSourceTemplatesPath();
8818
+ if (!sourceRoot) return 1;
8819
+ const files = await listTemplateFiles(sourceRoot, "harness");
8820
+ if (isGlobalHarness()) {
8821
+ return removeHarnessCopies(files, appRoot, options.dryRun ?? false);
8822
+ }
8823
+ const result = await syncTemplateFiles(files, appRoot, options);
8055
8824
  if (options.dryRun) {
8056
- note(`[DRY RUN] Would write ${geminiConfigPath}`, "Gemini");
8825
+ log2.info(`[DRY RUN] Would sync ${result.synced} harness file(s)`);
8826
+ return 0;
8827
+ }
8828
+ if (result.synced > 0) {
8829
+ log2.success(`Synced ${result.synced} harness file(s) from framework`);
8057
8830
  } else {
8058
- try {
8059
- const config = setMcpServer(
8060
- readJsonConfig(geminiConfigPath, { mcpServers: {} }),
8061
- geminiConfigPath,
8062
- "donotdev",
8063
- { ...mcpConfig, trust: true }
8064
- );
8065
- writeJsonConfig(geminiConfigPath, config);
8066
- log2.success(".gemini/settings.json configured (Gemini).");
8067
- } catch (e) {
8068
- log2.error(`Failed to configure Gemini: ${getErrorMessage(e)}`);
8069
- }
8070
- }
8071
- const claudeConfigPath = isWindows ? joinPath(
8072
- process.env.APPDATA || "",
8073
- "Claude",
8074
- "claude_desktop_config.json"
8075
- ) : isMac ? joinPath(
8076
- homeDir,
8077
- "Library",
8078
- "Application Support",
8079
- "Claude",
8080
- "claude_desktop_config.json"
8081
- ) : null;
8082
- if (claudeConfigPath) {
8083
- if (options.dryRun) {
8084
- note(`[DRY RUN] Would update ${claudeConfigPath}`, "Claude Desktop");
8085
- } else {
8086
- try {
8087
- const config = setMcpServer(
8088
- readJsonConfig(claudeConfigPath, { mcpServers: {} }),
8089
- claudeConfigPath,
8090
- "donotdev",
8091
- mcpConfig
8092
- );
8093
- writeJsonConfig(claudeConfigPath, config);
8094
- log2.success("Claude Desktop configured (global).");
8095
- } catch (e) {
8096
- log2.error(`Failed to configure Claude Desktop: ${getErrorMessage(e)}`);
8097
- }
8831
+ log2.info("AI harness up to date");
8832
+ }
8833
+ if (result.errors > 0) {
8834
+ log2.warn(`${result.errors} harness file(s) could not be synced`);
8835
+ return 1;
8836
+ }
8837
+ return 0;
8838
+ }
8839
+
8840
+ // packages/tooling/src/cli/agent-setup.ts
8841
+ init_utils2();
8842
+ init_cli_output();
8843
+ init_error_handling();
8844
+ init_pathResolver();
8845
+ init_type_guards();
8846
+ function claudeDesktopConfigPath() {
8847
+ if (process.platform === "win32") {
8848
+ return joinPath(process.env.APPDATA || "", "Claude", "claude_desktop_config.json");
8849
+ }
8850
+ if (process.platform === "darwin") {
8851
+ return joinPath(
8852
+ process.env.HOME || "",
8853
+ "Library",
8854
+ "Application Support",
8855
+ "Claude",
8856
+ "claude_desktop_config.json"
8857
+ );
8858
+ }
8859
+ return null;
8860
+ }
8861
+ function configureClaudeDesktop(configPath, dryRun) {
8862
+ if (dryRun) {
8863
+ note(`[DRY RUN] Would update ${configPath}`, "Claude Desktop");
8864
+ return;
8865
+ }
8866
+ const sourceRoot = getSourceTemplatesPath();
8867
+ if (!sourceRoot) return;
8868
+ try {
8869
+ const template = asText(
8870
+ readSync(joinPath(sourceRoot, MCP_TEMPLATE_FILE), { format: "text" })
8871
+ );
8872
+ if (!template) throw new Error(`Cannot read the template ${MCP_TEMPLATE_FILE}`);
8873
+ const existing = pathExists(configPath) ? asText(readSync(configPath, { format: "text" })) : null;
8874
+ const content = mergeMcpConfig(template, existing);
8875
+ if (content === existing) {
8876
+ log2.info("Claude Desktop already configured (global).");
8877
+ return;
8098
8878
  }
8879
+ ensureDirSync(getDirname(configPath));
8880
+ writeSync(configPath, content, { format: "text", overwrite: true });
8881
+ log2.success("Claude Desktop configured (global).");
8882
+ } catch (e) {
8883
+ log2.error(`Failed to configure Claude Desktop: ${getErrorMessage(e)}`);
8884
+ }
8885
+ }
8886
+ async function main(options = {}) {
8887
+ intro("DoNotDev Agent Setup");
8888
+ if (await syncHarness(options) !== 0) {
8889
+ process.exitCode = 1;
8890
+ }
8891
+ const claudeConfigPath = claudeDesktopConfigPath();
8892
+ if (claudeConfigPath) {
8893
+ configureClaudeDesktop(claudeConfigPath, options.dryRun ?? false);
8099
8894
  }
8100
8895
  note(
8101
8896
  '1. Restart your IDE (Cursor, VS Code, etc.)\n2. Tell your AI agent: "Read AGENTS.md and build my app"\n3. The agent handles the rest.',