@anvil-works/anvil-cli 0.8.0-dev.0 → 0.8.0

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.
Files changed (90) hide show
  1. package/README.md +55 -1
  2. package/dist/CLILogger.d.ts.map +1 -1
  3. package/dist/SavePathRouter.d.ts +4 -2
  4. package/dist/SavePathRouter.d.ts.map +1 -1
  5. package/dist/WatchSession.d.ts +5 -2
  6. package/dist/WatchSession.d.ts.map +1 -1
  7. package/dist/api.d.ts +7 -3
  8. package/dist/api.d.ts.map +1 -1
  9. package/dist/appRoot.d.ts +11 -0
  10. package/dist/appRoot.d.ts.map +1 -0
  11. package/dist/cli.d.ts +1 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +18736 -16819
  14. package/dist/cliProgram.d.ts +4 -0
  15. package/dist/cliProgram.d.ts.map +1 -0
  16. package/dist/cliReporting.d.ts +4 -0
  17. package/dist/cliReporting.d.ts.map +1 -0
  18. package/dist/commands/appDetection.d.ts +68 -1
  19. package/dist/commands/appDetection.d.ts.map +1 -1
  20. package/dist/commands/checkout.d.ts +1 -0
  21. package/dist/commands/checkout.d.ts.map +1 -1
  22. package/dist/commands/create.d.ts +52 -0
  23. package/dist/commands/create.d.ts.map +1 -0
  24. package/dist/commands/db.d.ts.map +1 -1
  25. package/dist/commands/deps.d.ts.map +1 -1
  26. package/dist/commands/env.d.ts +3 -1
  27. package/dist/commands/env.d.ts.map +1 -1
  28. package/dist/commands/index.d.ts +3 -0
  29. package/dist/commands/index.d.ts.map +1 -1
  30. package/dist/commands/repl.d.ts.map +1 -1
  31. package/dist/commands/secret.d.ts +3 -0
  32. package/dist/commands/secret.d.ts.map +1 -0
  33. package/dist/commands/test.d.ts +15 -0
  34. package/dist/commands/test.d.ts.map +1 -0
  35. package/dist/commands/validate.d.ts +11 -0
  36. package/dist/commands/validate.d.ts.map +1 -0
  37. package/dist/commands/watch.d.ts +1 -25
  38. package/dist/commands/watch.d.ts.map +1 -1
  39. package/dist/config.d.ts +3 -1
  40. package/dist/config.d.ts.map +1 -1
  41. package/dist/formTemplateValidation.d.ts.map +1 -1
  42. package/dist/index.js +663 -334
  43. package/dist/logger.d.ts +2 -2
  44. package/dist/program.d.ts +2 -9
  45. package/dist/program.d.ts.map +1 -1
  46. package/dist/programBase.d.ts +5 -0
  47. package/dist/programBase.d.ts.map +1 -0
  48. package/dist/reporting.d.ts +24 -0
  49. package/dist/reporting.d.ts.map +1 -0
  50. package/dist/serviceSources.d.ts.map +1 -1
  51. package/dist/services/anvil-api.d.ts +20 -0
  52. package/dist/services/anvil-api.d.ts.map +1 -1
  53. package/dist/services/db.d.ts +2 -0
  54. package/dist/services/db.d.ts.map +1 -1
  55. package/dist/services/deps.d.ts +7 -24
  56. package/dist/services/deps.d.ts.map +1 -1
  57. package/dist/services/depsCache.d.ts +25 -0
  58. package/dist/services/depsCache.d.ts.map +1 -0
  59. package/dist/services/environment.d.ts +4 -0
  60. package/dist/services/environment.d.ts.map +1 -1
  61. package/dist/services/git.d.ts +5 -2
  62. package/dist/services/git.d.ts.map +1 -1
  63. package/dist/services/path-open.d.ts +1 -0
  64. package/dist/services/path-open.d.ts.map +1 -1
  65. package/dist/services/repl.d.ts +2 -0
  66. package/dist/services/repl.d.ts.map +1 -1
  67. package/dist/services/secret.d.ts +43 -0
  68. package/dist/services/secret.d.ts.map +1 -0
  69. package/dist/services/server-tests.d.ts +47 -0
  70. package/dist/services/server-tests.d.ts.map +1 -0
  71. package/dist/services/validation.d.ts +2 -1
  72. package/dist/services/validation.d.ts.map +1 -1
  73. package/dist/validateFormTemplateHtml.d.ts.map +1 -1
  74. package/dist/validatePython.d.ts +5 -5
  75. package/dist/validatePython.d.ts.map +1 -1
  76. package/dist/validateThemeCss.d.ts +4 -0
  77. package/dist/validateThemeCss.d.ts.map +1 -0
  78. package/dist/validators.d.ts +2 -2
  79. package/dist/validators.d.ts.map +1 -1
  80. package/dist/watch/ConflictResolver.d.ts +5 -4
  81. package/dist/watch/ConflictResolver.d.ts.map +1 -1
  82. package/dist/watch/FileWatcher.d.ts +3 -1
  83. package/dist/watch/FileWatcher.d.ts.map +1 -1
  84. package/dist/watch/SaveProcessor.d.ts +5 -2
  85. package/dist/watch/SaveProcessor.d.ts.map +1 -1
  86. package/dist/watch/SyncManager.d.ts +3 -1
  87. package/dist/watch/SyncManager.d.ts.map +1 -1
  88. package/dist/watch/WebSocketClient.d.ts +3 -0
  89. package/dist/watch/WebSocketClient.d.ts.map +1 -1
  90. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -6705,6 +6705,10 @@ var __webpack_modules__ = {
6705
6705
  "use strict";
6706
6706
  module.exports = require("fs");
6707
6707
  },
6708
+ ora (module) {
6709
+ "use strict";
6710
+ module.exports = require("ora");
6711
+ },
6708
6712
  os (module) {
6709
6713
  "use strict";
6710
6714
  module.exports = require("os");
@@ -7373,6 +7377,7 @@ var __webpack_exports__ = {};
7373
7377
  AppIdWithContext: ()=>anvil_api_namespaceObject.AppIdWithContext,
7374
7378
  inspectCredentialHelperCommand: ()=>inspectCredentialHelperCommand,
7375
7379
  executeCheckout: ()=>executeCheckout,
7380
+ executeCreate: ()=>executeCreate,
7376
7381
  validateCheckoutDestination: ()=>validateCheckoutDestination,
7377
7382
  DeviceAuthorizationResponse: ()=>oauth_login_namespaceObject.DeviceAuthorizationResponse,
7378
7383
  OAuthTokenResponse: ()=>oauth_login_namespaceObject.OAuthTokenResponse,
@@ -7446,7 +7451,9 @@ var __webpack_exports__ = {};
7446
7451
  setInMemoryTokens: ()=>setInMemoryTokens,
7447
7452
  validateAppId: ()=>anvil_api_validateAppId,
7448
7453
  pollDeviceAuthorization: ()=>pollDeviceAuthorization,
7454
+ createAnvilApp: ()=>createAnvilApp,
7449
7455
  getValidAuthToken: ()=>auth_getValidAuthToken,
7456
+ CreatedAnvilApp: ()=>anvil_api_namespaceObject.CreatedAnvilApp,
7450
7457
  watch: ()=>src_api_watch,
7451
7458
  deleteConfig: ()=>deleteConfig,
7452
7459
  installModelTokenHelperScript: ()=>installModelTokenHelperScript,
@@ -7462,11 +7469,12 @@ var __webpack_exports__ = {};
7462
7469
  CheckoutResult: ()=>checkout_namespaceObject.CheckoutResult,
7463
7470
  ParsedCheckoutInput: ()=>checkout_namespaceObject.ParsedCheckoutInput,
7464
7471
  parseCredentialHelperCommand: ()=>parseCredentialHelperCommand,
7465
- MODEL_TOKEN_LOCK_TIMEOUT_MS: ()=>MODEL_TOKEN_LOCK_TIMEOUT_MS,
7472
+ CreateCheckoutError: ()=>CreateCheckoutError,
7466
7473
  GetValidAuthTokenOptions: ()=>auth_namespaceObject.GetValidAuthTokenOptions,
7467
- clearInMemoryTokens: ()=>clearInMemoryTokens,
7474
+ MODEL_TOKEN_LOCK_TIMEOUT_MS: ()=>MODEL_TOKEN_LOCK_TIMEOUT_MS,
7468
7475
  getDefaultDestinationDirectory: ()=>getDefaultDestinationDirectory,
7469
7476
  AUTH_FILE_LOCK_DEFAULTS: ()=>AUTH_FILE_LOCK_DEFAULTS,
7477
+ clearInMemoryTokens: ()=>clearInMemoryTokens,
7470
7478
  lookupByCommit: ()=>lookupByCommit,
7471
7479
  AppIdCandidate: ()=>anvil_api_namespaceObject.AppIdCandidate,
7472
7480
  verifyAuth: ()=>auth_verifyAuth
@@ -7483,6 +7491,7 @@ var __webpack_exports__ = {};
7483
7491
  P$: ()=>config_isCommandAvailable,
7484
7492
  n: ()=>config_isDevMode,
7485
7493
  Wj: ()=>config_isTestMode,
7494
+ Wc: ()=>config_normalizeAnvilOrigin,
7486
7495
  Vl: ()=>config_normalizeAnvilUrl,
7487
7496
  PW: ()=>parseConfigSetValue,
7488
7497
  cx: ()=>preferredEditors,
@@ -7511,19 +7520,20 @@ var __webpack_exports__ = {};
7511
7520
  var anvil_api_namespaceObject = {};
7512
7521
  __webpack_require__.r(anvil_api_namespaceObject);
7513
7522
  __webpack_require__.d(anvil_api_namespaceObject, {
7514
- lx: ()=>anvil_api_detectAppIdsByCommitLookup,
7515
- NZ: ()=>anvil_api_detectAppIdsFromAllRemotes,
7516
- rZ: ()=>anvil_api_filterCandidates,
7517
- T_: ()=>anvil_api_formatCandidateLabel,
7518
- OI: ()=>anvil_api_getGitFetchUrl,
7519
- _r: ()=>anvil_api_getGitPushUrl,
7520
- CA: ()=>getLatestVersion,
7521
- $0: ()=>getWebSocketUrl,
7522
- A1: ()=>listAppsForCheckout,
7523
- l9: ()=>lookupByCommit,
7524
- Wj: ()=>anvil_api_lookupRemoteInfoForAppId,
7525
- Us: ()=>saveUpdates,
7526
- zW: ()=>anvil_api_validateAppId
7523
+ createAnvilApp: ()=>createAnvilApp,
7524
+ detectAppIdsByCommitLookup: ()=>anvil_api_detectAppIdsByCommitLookup,
7525
+ detectAppIdsFromAllRemotes: ()=>anvil_api_detectAppIdsFromAllRemotes,
7526
+ filterCandidates: ()=>anvil_api_filterCandidates,
7527
+ formatCandidateLabel: ()=>anvil_api_formatCandidateLabel,
7528
+ getGitFetchUrl: ()=>anvil_api_getGitFetchUrl,
7529
+ getGitPushUrl: ()=>anvil_api_getGitPushUrl,
7530
+ getLatestVersion: ()=>getLatestVersion,
7531
+ getWebSocketUrl: ()=>getWebSocketUrl,
7532
+ listAppsForCheckout: ()=>listAppsForCheckout,
7533
+ lookupByCommit: ()=>lookupByCommit,
7534
+ lookupRemoteInfoForAppId: ()=>anvil_api_lookupRemoteInfoForAppId,
7535
+ saveUpdates: ()=>saveUpdates,
7536
+ validateAppId: ()=>anvil_api_validateAppId
7527
7537
  });
7528
7538
  var validators_namespaceObject = {};
7529
7539
  __webpack_require__.r(validators_namespaceObject);
@@ -7553,11 +7563,11 @@ var __webpack_exports__ = {};
7553
7563
  A9: ()=>isDirectoryNonEmpty,
7554
7564
  oU: ()=>isPathInsideGitRepo,
7555
7565
  Qx: ()=>parseCheckoutInput,
7566
+ B6: ()=>resolveCheckoutUrlForApi,
7556
7567
  KV: ()=>sanitizeDirectoryName,
7557
7568
  Bc: ()=>validateCheckoutDestination
7558
7569
  });
7559
- const external_chalk_namespaceObject = require("chalk");
7560
- var external_chalk_default = /*#__PURE__*/ __webpack_require__.n(external_chalk_namespaceObject);
7570
+ const external_node_util_namespaceObject = require("node:util");
7561
7571
  const external_path_namespaceObject = require("path");
7562
7572
  var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
7563
7573
  const external_node_buffer_namespaceObject = require("node:buffer");
@@ -11635,7 +11645,8 @@ var __webpack_exports__ = {};
11635
11645
  return !!this.data.unique_ids[entityType]?.[name];
11636
11646
  }
11637
11647
  }
11638
- const external_node_util_namespaceObject = require("node:util");
11648
+ const external_chalk_namespaceObject = require("chalk");
11649
+ var external_chalk_default = /*#__PURE__*/ __webpack_require__.n(external_chalk_namespaceObject);
11639
11650
  const external_node_process_namespaceObject = require("node:process");
11640
11651
  const external_node_fs_namespaceObject = require("node:fs");
11641
11652
  const external_node_crypto_namespaceObject = require("node:crypto");
@@ -12043,7 +12054,7 @@ var __webpack_exports__ = {};
12043
12054
  }
12044
12055
  const interceptor = new Interceptor();
12045
12056
  const whenExit = interceptor.register;
12046
- const node = whenExit;
12057
+ const dist_node = whenExit;
12047
12058
  const temp_Temp = {
12048
12059
  store: {},
12049
12060
  create: (filePath)=>{
@@ -12086,7 +12097,7 @@ var __webpack_exports__ = {};
12086
12097
  return `${filePath.slice(0, -basename.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
12087
12098
  }
12088
12099
  };
12089
- node(temp_Temp.purgeSyncAll);
12100
+ dist_node(temp_Temp.purgeSyncAll);
12090
12101
  const temp = temp_Temp;
12091
12102
  function writeFileSync(filePath, data, options = constants_DEFAULT_WRITE_OPTIONS) {
12092
12103
  if (lang_isString(options)) return writeFileSync(filePath, data, {
@@ -13109,12 +13120,25 @@ var __webpack_exports__ = {};
13109
13120
  if (!urlInput || "string" != typeof urlInput) return urlInput;
13110
13121
  let url = urlInput.trim();
13111
13122
  url = url.replace(/\/+$/, "");
13112
- if ("localhost" === url || url.startsWith("localhost:")) return "http://localhost:3000";
13113
- if ("http://localhost" === url || url.startsWith("http://localhost:")) return "http://localhost:3000";
13114
- if ("https://localhost" === url || url.startsWith("https://localhost:")) return "http://localhost:3000";
13115
- if (/^https?:\/\//.test(url)) return url;
13123
+ if ("localhost" === url) return "http://localhost:3000";
13124
+ if (url.startsWith("localhost:")) return `http://${url}`;
13125
+ if (/^https?:\/\//i.test(url)) return url;
13116
13126
  return `https://${url}`;
13117
13127
  }
13128
+ function config_normalizeAnvilOrigin(input) {
13129
+ try {
13130
+ const raw = input.trim();
13131
+ const normalized = config_normalizeAnvilUrl(raw);
13132
+ const url = new URL(raw.includes("://") ? raw : normalized);
13133
+ if (![
13134
+ "http:",
13135
+ "https:"
13136
+ ].includes(url.protocol) || url.username || url.password || "/" !== url.pathname || url.search || url.hash) throw new Error("Invalid origin");
13137
+ return normalized;
13138
+ } catch {
13139
+ throw new Error("Server URL must be an HTTP(S) origin without credentials, a path, query, or fragment.");
13140
+ }
13141
+ }
13118
13142
  function resolveAnvilUrl() {
13119
13143
  const fromConfig = config_getConfig("anvilUrl");
13120
13144
  if ("string" == typeof fromConfig && fromConfig.trim()) return fromConfig.trim();
@@ -13594,6 +13618,18 @@ var __webpack_exports__ = {};
13594
13618
  return "An unknown error occurred";
13595
13619
  }
13596
13620
  }
13621
+ const reporting_silentLogger = {
13622
+ debug () {},
13623
+ verbose () {},
13624
+ info () {},
13625
+ warn () {},
13626
+ error () {}
13627
+ };
13628
+ const silentProgress = {
13629
+ start () {},
13630
+ update () {},
13631
+ end () {}
13632
+ };
13597
13633
  const external_module_namespaceObject = require("module");
13598
13634
  const requireFromHere = (0, external_module_namespaceObject.createRequire)(__filename);
13599
13635
  const GIT_CREDENTIAL_HELPER_FILENAME = "anvil-credential-helper.cjs";
@@ -14299,6 +14335,7 @@ Promise.resolve()
14299
14335
  return WANT_NOT_VALID_RE.test(error.message || "");
14300
14336
  }
14301
14337
  class git_GitService extends Emitter {
14338
+ logger;
14302
14339
  git;
14303
14340
  repoPath;
14304
14341
  static INDEX_LOCK_RETRY_DELAYS_MS = [
@@ -14307,8 +14344,10 @@ Promise.resolve()
14307
14344
  100,
14308
14345
  200
14309
14346
  ];
14310
- constructor(repoPath){
14311
- super();
14347
+ constructor(repoPath, options = {}){
14348
+ const logger = options.logger ?? reporting_silentLogger;
14349
+ super((event, error)=>logger.error(`Error in event handler for '${event}': ${error}`));
14350
+ this.logger = logger;
14312
14351
  this.repoPath = external_path_default().resolve(repoPath);
14313
14352
  this.git = esm_default(this.repoPath);
14314
14353
  }
@@ -14463,8 +14502,16 @@ Promise.resolve()
14463
14502
  if ((511 & stat.mode) !== (511 & mode)) await external_fs_.promises.chmod(filePath, mode);
14464
14503
  }
14465
14504
  async hasUncommittedChanges() {
14466
- const status = await this.getStatus();
14467
- return !status.isClean;
14505
+ try {
14506
+ const status = await this.git.raw([
14507
+ "--no-optional-locks",
14508
+ "status",
14509
+ "--porcelain"
14510
+ ]);
14511
+ return status.trim().length > 0;
14512
+ } catch (e) {
14513
+ throw errors_createGitError.commandFailed("status", e.message);
14514
+ }
14468
14515
  }
14469
14516
  async fetch(url, refSpec) {
14470
14517
  let attempt = 0;
@@ -14493,7 +14540,7 @@ Promise.resolve()
14493
14540
  delayMs: FETCH_RETRY_DELAY_MS,
14494
14541
  error: err.message
14495
14542
  });
14496
- logger_logger.verbose(`git fetch race (attempt ${attempt}, sleeping ${FETCH_RETRY_DELAY_MS}ms): ${err.message}`);
14543
+ this.logger.verbose(`git fetch race (attempt ${attempt}, sleeping ${FETCH_RETRY_DELAY_MS}ms): ${err.message}`);
14497
14544
  await (0, promises_namespaceObject.setTimeout)(FETCH_RETRY_DELAY_MS);
14498
14545
  }
14499
14546
  }
@@ -14774,6 +14821,39 @@ Promise.resolve()
14774
14821
  function anvil_api_getDefaultAnvilUrl() {
14775
14822
  return resolveAnvilUrl();
14776
14823
  }
14824
+ async function createAnvilApp(options) {
14825
+ let response;
14826
+ try {
14827
+ response = await fetch(`${options.anvilUrl}/ide/api/_/apps`, {
14828
+ method: "POST",
14829
+ headers: {
14830
+ Authorization: `Bearer ${options.authToken}`,
14831
+ "Content-Type": "application/json"
14832
+ },
14833
+ body: JSON.stringify({
14834
+ name: options.name,
14835
+ tags: options.tags
14836
+ })
14837
+ });
14838
+ } catch (error) {
14839
+ throw createNetworkError.network(error.message);
14840
+ }
14841
+ const data = await response.json().catch(()=>({}));
14842
+ if (!response.ok) {
14843
+ if (401 === response.status || 403 === response.status) throw createAuthError.invalid(data.error || "Not authorized to create an app");
14844
+ throw new Error(data.error || `Failed to create app: ${response.status} ${response.statusText}`);
14845
+ }
14846
+ if ("string" != typeof data.id || !data.id) throw new Error("App creation response did not contain an app ID.");
14847
+ return {
14848
+ id: data.id,
14849
+ ..."string" == typeof data.name ? {
14850
+ name: data.name
14851
+ } : {},
14852
+ ...data.tags ? {
14853
+ tags: data.tags
14854
+ } : {}
14855
+ };
14856
+ }
14777
14857
  async function anvil_api_validateAppId(appId, anvilUrl = anvil_api_getDefaultAnvilUrl(), username) {
14778
14858
  const authToken = await auth_getValidAuthToken(anvilUrl, username);
14779
14859
  try {
@@ -14945,14 +15025,15 @@ Promise.resolve()
14945
15025
  try {
14946
15026
  const remotes = await git.getRemotes(true);
14947
15027
  for (const remote of remotes){
14948
- const httpMatch = remote.refs.fetch?.match(/(?:http|https):\/\/(?:[^@]+@)?([^:\/]+)(?::\d+)?\/git\/([A-Z0-9]+)\.git/);
15028
+ const httpMatch = remote.refs.fetch?.match(/(https?):\/\/(?:[^@\/]+@)?([^\/]+)\/git\/([A-Z0-9]+)\.git/);
14949
15029
  if (httpMatch) {
14950
- const [, host, detectedAppId] = httpMatch;
15030
+ const [, scheme, host, detectedAppId] = httpMatch;
15031
+ const origin = new URL(`${scheme}://${host}`).origin;
14951
15032
  out.push({
14952
15033
  appId: detectedAppId,
14953
15034
  source: "remote",
14954
15035
  description: `Git remote '${remote.name}'`,
14955
- detectedUrl: config_normalizeAnvilUrl(host)
15036
+ detectedUrl: config_normalizeAnvilUrl(origin)
14956
15037
  });
14957
15038
  continue;
14958
15039
  }
@@ -15016,6 +15097,29 @@ Promise.resolve()
15016
15097
  }
15017
15098
  const external_fs_promises_namespaceObject = require("fs/promises");
15018
15099
  var external_fs_promises_default = /*#__PURE__*/ __webpack_require__.n(external_fs_promises_namespaceObject);
15100
+ function http_formatHttpError(prefix, status, body) {
15101
+ if (!body) return `${prefix}: ${status}`;
15102
+ try {
15103
+ const parsed = JSON.parse(body);
15104
+ if ("string" == typeof parsed.error && parsed.error.trim()) return `${prefix}: ${parsed.error} (${status})`;
15105
+ } catch {}
15106
+ return `${prefix}: ${status} ${body}`;
15107
+ }
15108
+ const ANVIL_GITIGNORE_ENTRY = "/.anvil/";
15109
+ async function ensureProjectGitignoreIgnoresAnvilDir(projectRoot) {
15110
+ const rootGitignorePath = external_path_default().join(projectRoot, ".gitignore");
15111
+ try {
15112
+ const existing = await external_fs_.promises.readFile(rootGitignorePath, "utf8");
15113
+ if (existing.includes(ANVIL_GITIGNORE_ENTRY)) return false;
15114
+ const prefix = existing.endsWith("\n") || 0 === existing.length ? "" : "\n";
15115
+ await external_fs_.promises.writeFile(rootGitignorePath, `${existing}${prefix}${ANVIL_GITIGNORE_ENTRY}\n`, "utf8");
15116
+ return true;
15117
+ } catch (error) {
15118
+ if ("ENOENT" !== error.code) throw error;
15119
+ await external_fs_.promises.writeFile(rootGitignorePath, `${ANVIL_GITIGNORE_ENTRY}\n`, "utf8");
15120
+ return true;
15121
+ }
15122
+ }
15019
15123
  function normalizeLineEndings(content) {
15020
15124
  return content.replace(/\r\n/g, "\n");
15021
15125
  }
@@ -15060,36 +15164,71 @@ Promise.resolve()
15060
15164
  html: htmlContent
15061
15165
  };
15062
15166
  }
15063
- function formatHttpError(prefix, status, body) {
15064
- if (!body) return `${prefix}: ${status}`;
15167
+ const ANVIL_DEPS_DIR = ".anvil/deps";
15168
+ const ANVIL_DEPS_MANIFEST = "manifest.json";
15169
+ const DEPS_MANIFEST_VERSION = 3;
15170
+ function depsCache_depsDir(projectRoot) {
15171
+ return external_path_default().join(projectRoot, ANVIL_DEPS_DIR);
15172
+ }
15173
+ function depsManifestPath(projectRoot) {
15174
+ return external_path_default().join(depsCache_depsDir(projectRoot), ANVIL_DEPS_MANIFEST);
15175
+ }
15176
+ function isResolvedDependencyManifestEntry(value) {
15177
+ if (!value || "object" != typeof value) return false;
15178
+ const entry = value;
15179
+ return "string" == typeof entry.app_id && entry.app_id.length > 0 && "string" == typeof entry.commit_id && entry.commit_id.length > 0 && (void 0 === entry.branch || "string" == typeof entry.branch);
15180
+ }
15181
+ function isCachedDependencyManifestEntry(value) {
15182
+ if (!isResolvedDependencyManifestEntry(value)) return false;
15183
+ const entry = value;
15184
+ return "string" == typeof entry.package_name && entry.package_name.length > 0;
15185
+ }
15186
+ function isDepsCacheManifest(value) {
15187
+ if (!value || "object" != typeof value) return false;
15188
+ const manifest = value;
15189
+ return manifest.version === DEPS_MANIFEST_VERSION && "boolean" == typeof manifest.includeDocs && (null === manifest.source_dependencies || Array.isArray(manifest.source_dependencies)) && Array.isArray(manifest.resolved_dependencies) && manifest.resolved_dependencies.every(isResolvedDependencyManifestEntry) && Array.isArray(manifest.cached_dependencies) && manifest.cached_dependencies.every(isCachedDependencyManifestEntry);
15190
+ }
15191
+ async function readDepsCacheManifest(projectRoot) {
15065
15192
  try {
15066
- const parsed = JSON.parse(body);
15067
- if ("string" == typeof parsed.error && parsed.error.trim()) return `${prefix}: ${parsed.error} (${status})`;
15068
- } catch {}
15069
- return `${prefix}: ${status} ${body}`;
15193
+ const raw = await external_fs_promises_default().readFile(depsManifestPath(projectRoot), "utf-8");
15194
+ const parsed = JSON.parse(raw);
15195
+ return isDepsCacheManifest(parsed) ? parsed : void 0;
15196
+ } catch {
15197
+ return;
15198
+ }
15070
15199
  }
15071
- const ANVIL_GITIGNORE_ENTRY = "/.anvil/";
15072
- async function ensureProjectGitignoreIgnoresAnvilDir(projectRoot) {
15073
- const rootGitignorePath = external_path_default().join(projectRoot, ".gitignore");
15200
+ function normalizeAnvilYamlDependenciesFromContent(content) {
15201
+ const parsed = external_js_yaml_default().load(content);
15202
+ if (!parsed || "object" != typeof parsed || !Array.isArray(parsed.dependencies)) return [];
15203
+ return normalizeAnvilYamlDependenciesValue(parsed.dependencies);
15204
+ }
15205
+ function normalizeAnvilYamlDependenciesValue(value) {
15206
+ if (!Array.isArray(value)) return [];
15207
+ return value.map(normalizeForComparison);
15208
+ }
15209
+ async function readAnvilYamlDependencies(projectRoot) {
15074
15210
  try {
15075
- const existing = await external_fs_.promises.readFile(rootGitignorePath, "utf8");
15076
- if (existing.includes(ANVIL_GITIGNORE_ENTRY)) return false;
15077
- const prefix = existing.endsWith("\n") || 0 === existing.length ? "" : "\n";
15078
- await external_fs_.promises.writeFile(rootGitignorePath, `${existing}${prefix}${ANVIL_GITIGNORE_ENTRY}\n`, "utf8");
15079
- return true;
15080
- } catch (error) {
15081
- if ("ENOENT" !== error.code) throw error;
15082
- await external_fs_.promises.writeFile(rootGitignorePath, `${ANVIL_GITIGNORE_ENTRY}\n`, "utf8");
15083
- return true;
15211
+ const content = await external_fs_promises_default().readFile(external_path_default().join(projectRoot, "anvil.yaml"), "utf-8");
15212
+ return normalizeAnvilYamlDependenciesFromContent(content);
15213
+ } catch {
15214
+ return [];
15084
15215
  }
15085
15216
  }
15086
- const ANVIL_DEPS_DIR = ".anvil/deps";
15087
- const ANVIL_DEPS_MANIFEST = "manifest.json";
15088
- const DEPS_MANIFEST_VERSION = 2;
15217
+ function anvilYamlDependenciesEqual(left, right) {
15218
+ return deepEqual(left, right);
15219
+ }
15220
+ function normalizeForComparison(value) {
15221
+ if (Array.isArray(value)) return value.map(normalizeForComparison);
15222
+ if (value && "object" == typeof value) return Object.fromEntries(Object.entries(value).sort(([left], [right])=>left.localeCompare(right)).map(([key, entryValue])=>[
15223
+ key,
15224
+ normalizeForComparison(entryValue)
15225
+ ]));
15226
+ return value;
15227
+ }
15089
15228
  async function fetchAllDependencies(appId, anvilUrl, options = {}) {
15090
15229
  const { commit, includeDocs = true, knownDependencies = [] } = options;
15091
15230
  anvilUrl ??= await auth_resolveAuthAnvilUrl();
15092
- const token = await auth_getValidAuthToken(anvilUrl);
15231
+ const token = await auth_getValidAuthToken(anvilUrl, options.username);
15093
15232
  const body = {
15094
15233
  include_docs: includeDocs,
15095
15234
  known_dependencies: knownDependencies
@@ -15105,7 +15244,7 @@ Promise.resolve()
15105
15244
  });
15106
15245
  if (!resp.ok) {
15107
15246
  const errorBody = await resp.text();
15108
- throw new Error(formatHttpError("Failed to fetch dependencies", resp.status, errorBody));
15247
+ throw new Error(http_formatHttpError("Failed to fetch dependencies", resp.status, errorBody));
15109
15248
  }
15110
15249
  return await resp.json();
15111
15250
  }
@@ -15113,9 +15252,19 @@ Promise.resolve()
15113
15252
  auth_setRepoContext(projectRoot);
15114
15253
  anvilUrl ??= await auth_resolveAuthAnvilUrl();
15115
15254
  const includeDocs = options.includeDocs ?? true;
15255
+ const git = new git_GitService(projectRoot, {
15256
+ logger: options.logger
15257
+ });
15258
+ const commit = options.commit ?? await git.getCommitId();
15259
+ const sourceYaml = await git.show(`${commit}:anvil.yaml`).catch((error)=>{
15260
+ if (options.commit) return null;
15261
+ throw error;
15262
+ });
15263
+ const sourceDependencies = null === sourceYaml ? null : normalizeAnvilYamlDependenciesFromContent(sourceYaml);
15116
15264
  const knownDependencies = await getKnownDependenciesForCache(projectRoot, includeDocs);
15117
15265
  const response = await fetchAllDependencies(appId, anvilUrl, {
15118
- commit: options.commit,
15266
+ username: options.username,
15267
+ commit,
15119
15268
  includeDocs,
15120
15269
  knownDependencies
15121
15270
  });
@@ -15128,43 +15277,14 @@ Promise.resolve()
15128
15277
  }
15129
15278
  const addedGitignoreEntry = await ensureProjectGitignoreIgnoresAnvilDir(projectRoot);
15130
15279
  await writeAllDepsToCache(projectRoot, response, {
15131
- includeDocs
15280
+ includeDocs,
15281
+ sourceDependencies
15132
15282
  });
15133
15283
  return {
15134
15284
  response,
15135
15285
  addedGitignoreEntry
15136
15286
  };
15137
15287
  }
15138
- function depsDir(projectRoot) {
15139
- return external_path_default().join(projectRoot, ANVIL_DEPS_DIR);
15140
- }
15141
- function depsManifestPath(projectRoot) {
15142
- return external_path_default().join(depsDir(projectRoot), ANVIL_DEPS_MANIFEST);
15143
- }
15144
- function isResolvedDependencyManifestEntry(value) {
15145
- if (!value || "object" != typeof value) return false;
15146
- const entry = value;
15147
- return "string" == typeof entry.app_id && entry.app_id.length > 0 && "string" == typeof entry.commit_id && entry.commit_id.length > 0 && (void 0 === entry.branch || "string" == typeof entry.branch);
15148
- }
15149
- function isCachedDependencyManifestEntry(value) {
15150
- if (!isResolvedDependencyManifestEntry(value)) return false;
15151
- const entry = value;
15152
- return "string" == typeof entry.package_name && entry.package_name.length > 0;
15153
- }
15154
- function isDepsCacheManifest(value) {
15155
- if (!value || "object" != typeof value) return false;
15156
- const manifest = value;
15157
- return manifest.version === DEPS_MANIFEST_VERSION && "boolean" == typeof manifest.includeDocs && Array.isArray(manifest.source_dependencies) && Array.isArray(manifest.resolved_dependencies) && manifest.resolved_dependencies.every(isResolvedDependencyManifestEntry) && Array.isArray(manifest.cached_dependencies) && manifest.cached_dependencies.every(isCachedDependencyManifestEntry);
15158
- }
15159
- async function readDepsCacheManifest(projectRoot) {
15160
- try {
15161
- const raw = await external_fs_promises_default().readFile(depsManifestPath(projectRoot), "utf-8");
15162
- const parsed = JSON.parse(raw);
15163
- return isDepsCacheManifest(parsed) ? parsed : void 0;
15164
- } catch {
15165
- return;
15166
- }
15167
- }
15168
15288
  async function getKnownDependenciesForCache(projectRoot, includeDocs) {
15169
15289
  const manifest = await readDepsCacheManifest(projectRoot);
15170
15290
  if (!manifest || manifest.includeDocs !== includeDocs) return [];
@@ -15190,34 +15310,6 @@ Promise.resolve()
15190
15310
  ];
15191
15311
  });
15192
15312
  }
15193
- function normalizeAnvilYamlDependenciesFromContent(content) {
15194
- const parsed = external_js_yaml_default().load(content);
15195
- if (!parsed || "object" != typeof parsed || !Array.isArray(parsed.dependencies)) return [];
15196
- return normalizeAnvilYamlDependenciesValue(parsed.dependencies);
15197
- }
15198
- function normalizeAnvilYamlDependenciesValue(value) {
15199
- if (!Array.isArray(value)) return [];
15200
- return value.map(normalizeForComparison);
15201
- }
15202
- async function readAnvilYamlDependencies(projectRoot) {
15203
- try {
15204
- const content = await external_fs_promises_default().readFile(external_path_default().join(projectRoot, "anvil.yaml"), "utf-8");
15205
- return normalizeAnvilYamlDependenciesFromContent(content);
15206
- } catch {
15207
- return [];
15208
- }
15209
- }
15210
- function anvilYamlDependenciesEqual(left, right) {
15211
- return deepEqual(left, right);
15212
- }
15213
- function normalizeForComparison(value) {
15214
- if (Array.isArray(value)) return value.map(normalizeForComparison);
15215
- if (value && "object" == typeof value) return Object.fromEntries(Object.entries(value).sort(([left], [right])=>left.localeCompare(right)).map(([key, entryValue])=>[
15216
- key,
15217
- normalizeForComparison(entryValue)
15218
- ]));
15219
- return value;
15220
- }
15221
15313
  function cachedManifestEntry(dep, packageName) {
15222
15314
  return {
15223
15315
  app_id: dep.app_id,
@@ -15239,7 +15331,7 @@ Promise.resolve()
15239
15331
  return external_path_default().join(...parts);
15240
15332
  }
15241
15333
  async function writeDepToCache(projectRoot, dep) {
15242
- const depDir = external_path_default().join(projectRoot, ANVIL_DEPS_DIR, dep.package_name);
15334
+ const depDir = external_path_default().join(depsCache_depsDir(projectRoot), dep.package_name);
15243
15335
  await external_fs_promises_default().rm(depDir, {
15244
15336
  recursive: true,
15245
15337
  force: true
@@ -15323,7 +15415,7 @@ Promise.resolve()
15323
15415
  if (!canReuseExistingCache) await clearDepsCache(projectRoot);
15324
15416
  const previousCached = canReuseExistingCache ? manifest.cached_dependencies : [];
15325
15417
  const resolvedAppIds = new Set(response.resolved_dependencies.map((dep)=>dep.app_id));
15326
- for (const dep of previousCached)if (!resolvedAppIds.has(dep.app_id)) await external_fs_promises_default().rm(external_path_default().join(projectRoot, ANVIL_DEPS_DIR, dep.package_name), {
15418
+ for (const dep of previousCached)if (!resolvedAppIds.has(dep.app_id)) await external_fs_promises_default().rm(external_path_default().join(depsCache_depsDir(projectRoot), dep.package_name), {
15327
15419
  recursive: true,
15328
15420
  force: true
15329
15421
  });
@@ -15346,17 +15438,17 @@ Promise.resolve()
15346
15438
  const newManifest = {
15347
15439
  version: DEPS_MANIFEST_VERSION,
15348
15440
  includeDocs,
15349
- source_dependencies: await readAnvilYamlDependencies(projectRoot),
15441
+ source_dependencies: void 0 === options.sourceDependencies ? await readAnvilYamlDependencies(projectRoot) : options.sourceDependencies,
15350
15442
  resolved_dependencies: response.resolved_dependencies,
15351
15443
  cached_dependencies: cachedDependencies
15352
15444
  };
15353
- await external_fs_promises_default().mkdir(depsDir(projectRoot), {
15445
+ await external_fs_promises_default().mkdir(depsCache_depsDir(projectRoot), {
15354
15446
  recursive: true
15355
15447
  });
15356
15448
  await external_fs_promises_default().writeFile(depsManifestPath(projectRoot), `${JSON.stringify(newManifest, null, 2)}\n`);
15357
15449
  }
15358
15450
  async function clearDepsCache(projectRoot) {
15359
- await external_fs_promises_default().rm(depsDir(projectRoot), {
15451
+ await external_fs_promises_default().rm(depsCache_depsDir(projectRoot), {
15360
15452
  recursive: true,
15361
15453
  force: true
15362
15454
  });
@@ -15364,6 +15456,7 @@ Promise.resolve()
15364
15456
  const external_chokidar_namespaceObject = require("chokidar");
15365
15457
  var external_chokidar_default = /*#__PURE__*/ __webpack_require__.n(external_chokidar_namespaceObject);
15366
15458
  class FileWatcher extends Emitter {
15459
+ logger;
15367
15460
  repoPath;
15368
15461
  gitDir;
15369
15462
  stagedOnly;
@@ -15373,7 +15466,9 @@ Promise.resolve()
15373
15466
  currentBranch = "";
15374
15467
  sessionId;
15375
15468
  constructor(options){
15376
- super();
15469
+ const logger = options.logger ?? reporting_silentLogger;
15470
+ super((event, error)=>logger.error(`Error in event handler for '${event}': ${error}`));
15471
+ this.logger = logger;
15377
15472
  this.repoPath = external_path_default().resolve(options.repoPath);
15378
15473
  this.gitDir = options.gitDir;
15379
15474
  this.stagedOnly = options.stagedOnly ?? false;
@@ -15382,14 +15477,14 @@ Promise.resolve()
15382
15477
  }
15383
15478
  async start(currentBranch) {
15384
15479
  this.currentBranch = currentBranch;
15385
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, "Starting watchers...");
15480
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, "Starting watchers..."));
15386
15481
  this.startHeadWatcher();
15387
15482
  if (this.stagedOnly) this.startIndexWatcher();
15388
15483
  else this.startFileWatcher();
15389
15484
  }
15390
15485
  startHeadWatcher() {
15391
15486
  const headPath = external_path_default().join(this.gitDir, "HEAD");
15392
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, `Setting up HEAD watcher: ${headPath}`);
15487
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, `Setting up HEAD watcher: ${headPath}`));
15393
15488
  this.headWatcher = external_chokidar_default().watch(headPath, {
15394
15489
  persistent: true,
15395
15490
  ignoreInitial: true,
@@ -15402,13 +15497,13 @@ Promise.resolve()
15402
15497
  if (newBranch !== this.currentBranch) {
15403
15498
  const oldBranch = this.currentBranch;
15404
15499
  this.currentBranch = newBranch;
15405
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, `Branch changed: ${oldBranch} -> ${newBranch}`);
15500
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, `Branch changed: ${oldBranch} -> ${newBranch}`));
15406
15501
  this.emit("branch-change", {
15407
15502
  newBranch
15408
15503
  });
15409
15504
  }
15410
15505
  } catch (error) {
15411
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, `Error getting current branch: ${error.message}`);
15506
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, `Error getting current branch: ${error.message}`));
15412
15507
  }
15413
15508
  });
15414
15509
  this.headWatcher.on("error", (err)=>{
@@ -15420,9 +15515,9 @@ Promise.resolve()
15420
15515
  }
15421
15516
  startIndexWatcher() {
15422
15517
  const indexPath = external_path_default().join(this.gitDir, "index");
15423
- logger_logger.verbose(`Setting up watcher for: ${indexPath}`);
15424
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, `Setting up index watcher (staged-only mode): ${indexPath}`);
15425
- if (!external_fs_.existsSync(indexPath)) return void logger_logger.error(`ERROR: Git index file not found at ${indexPath}`);
15518
+ this.logger.verbose(`Setting up watcher for: ${indexPath}`);
15519
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, `Setting up index watcher (staged-only mode): ${indexPath}`));
15520
+ if (!external_fs_.existsSync(indexPath)) return void this.logger.error(`ERROR: Git index file not found at ${indexPath}`);
15426
15521
  this.fileWatcher = external_chokidar_default().watch(indexPath, {
15427
15522
  persistent: true,
15428
15523
  ignoreInitial: true,
@@ -15430,23 +15525,23 @@ Promise.resolve()
15430
15525
  interval: 100
15431
15526
  });
15432
15527
  this.fileWatcher.on("ready", ()=>{
15433
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, "Staged-only watcher ready");
15528
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, "Staged-only watcher ready"));
15434
15529
  });
15435
15530
  this.fileWatcher.on("change", async ()=>{
15436
- logger_logger.verbose("Git index changed (staging event detected)");
15531
+ this.logger.verbose("Git index changed (staging event detected)");
15437
15532
  this.emit("index-change", void 0);
15438
15533
  });
15439
15534
  this.fileWatcher.on("error", (err)=>{
15440
15535
  const error = err instanceof Error ? err : new Error(String(err));
15441
- logger_logger.error(`Watcher error: ${error}`);
15536
+ this.logger.error(`Watcher error: ${error}`);
15442
15537
  this.emit("error", {
15443
15538
  error
15444
15539
  });
15445
15540
  });
15446
- logger_logger.success("Watching for staged changes. Press Ctrl-C to exit.");
15541
+ this.logger.info("Watching for staged changes. Press Ctrl-C to exit.");
15447
15542
  }
15448
15543
  startFileWatcher() {
15449
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, `Setting up file watcher (normal mode): ${this.repoPath}`);
15544
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, `Setting up file watcher (normal mode): ${this.repoPath}`));
15450
15545
  this.fileWatcher = external_chokidar_default().watch(this.repoPath, {
15451
15546
  ignored: [
15452
15547
  /(^|[\/\\])\../,
@@ -15471,12 +15566,12 @@ Promise.resolve()
15471
15566
  });
15472
15567
  this.fileWatcher.on("error", (err)=>{
15473
15568
  const error = err instanceof Error ? err : new Error(String(err));
15474
- logger_logger.error(`Watcher error: ${error}`);
15569
+ this.logger.error(`Watcher error: ${error}`);
15475
15570
  this.emit("error", {
15476
15571
  error
15477
15572
  });
15478
15573
  });
15479
- logger_logger.success("Watching for changes. Press Ctrl-C to exit.");
15574
+ this.logger.info("Watching for changes. Press Ctrl-C to exit.");
15480
15575
  }
15481
15576
  getCurrentWatchedBranch() {
15482
15577
  return this.currentBranch;
@@ -15485,23 +15580,24 @@ Promise.resolve()
15485
15580
  this.currentBranch = branch;
15486
15581
  }
15487
15582
  cleanup() {
15488
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, "Cleaning up watchers...");
15583
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, "Cleaning up watchers..."));
15489
15584
  if (this.headWatcher) {
15490
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, "Closing HEAD watcher");
15585
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, "Closing HEAD watcher"));
15491
15586
  this.headWatcher.close();
15492
15587
  this.headWatcher = null;
15493
15588
  }
15494
15589
  if (this.fileWatcher) {
15495
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, "Closing file watcher");
15590
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, "Closing file watcher"));
15496
15591
  this.fileWatcher.close();
15497
15592
  this.fileWatcher = null;
15498
15593
  }
15499
- logger_logger.debug(`[FileWatcher ${this.sessionId}]`, "Watcher cleanup complete");
15594
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[FileWatcher ${this.sessionId}]`, "Watcher cleanup complete"));
15500
15595
  }
15501
15596
  }
15502
15597
  const external_ws_namespaceObject = require("ws");
15503
15598
  var external_ws_default = /*#__PURE__*/ __webpack_require__.n(external_ws_namespaceObject);
15504
15599
  class WebSocketClient extends Emitter {
15600
+ logger;
15505
15601
  ws = null;
15506
15602
  appId;
15507
15603
  anvilUrl;
@@ -15530,7 +15626,9 @@ Promise.resolve()
15530
15626
  HEARTBEAT_INTERVAL_MS = 30000;
15531
15627
  HEARTBEAT_TIMEOUT_MS = 10000;
15532
15628
  constructor(options){
15533
- super();
15629
+ const logger = options.logger ?? reporting_silentLogger;
15630
+ super((event, error)=>logger.error(`Error in event handler for '${event}': ${error}`));
15631
+ this.logger = logger;
15534
15632
  this.appId = options.appId;
15535
15633
  this.anvilUrl = options.anvilUrl;
15536
15634
  this.authToken = options.authToken;
@@ -15546,24 +15644,24 @@ Promise.resolve()
15546
15644
  async connect() {
15547
15645
  this.isClosing = false;
15548
15646
  this.connectAttempts++;
15549
- if (this.ws?.readyState === external_ws_default().OPEN) return void logger_logger.debug(`[WebSocket ${this.sessionId}]`, "WebSocket already open, skipping connection");
15647
+ if (this.ws?.readyState === external_ws_default().OPEN) return void this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, "WebSocket already open, skipping connection"));
15550
15648
  if (this.ws) {
15551
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, "Closing existing WebSocket before reconnecting");
15649
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, "Closing existing WebSocket before reconnecting"));
15552
15650
  this.teardownSocket();
15553
15651
  }
15554
15652
  this.authToken = await auth_getValidAuthToken(this.anvilUrl, this.username);
15555
15653
  const wsUrl = getWebSocketUrl(this.appId, this.authToken, this.anvilUrl);
15556
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Connecting to: ${wsUrl.replace(this.authToken, "[TOKEN]")}`);
15557
- logger_logger.verbose(external_chalk_default().gray(`WebSocket connecting to ${this.getConnectionTarget(wsUrl)} (app ${this.appId}, branch ${this.currentBranch}, session ${this.sessionId}, connect attempt ${this.connectAttempts})`));
15654
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Connecting to: ${wsUrl.replace(this.authToken, "[TOKEN]")}`));
15655
+ this.logger.verbose(`WebSocket connecting to ${this.getConnectionTarget(wsUrl)} (app ${this.appId}, branch ${this.currentBranch}, session ${this.sessionId}, connect attempt ${this.connectAttempts})`);
15558
15656
  this.ws = new (external_ws_default())(wsUrl);
15559
15657
  this.ws.on("open", ()=>{
15560
- logger_logger.verbose(external_chalk_default().green("🔌 Connected to Anvil WebSocket"));
15561
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, "WebSocket opened");
15658
+ this.logger.verbose("🔌 Connected to Anvil WebSocket");
15659
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, "WebSocket opened"));
15562
15660
  this.reconnectAttempts = 0;
15563
15661
  this.reconnectDelayMs = this.RECONNECT_DELAY_BASE_MS;
15564
15662
  this.startHeartbeat();
15565
15663
  const subscribeMsg = this.buildSubscribeMessage(this.currentBranch);
15566
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Subscribing: ${JSON.stringify(subscribeMsg)}`);
15664
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Subscribing: ${JSON.stringify(subscribeMsg)}`));
15567
15665
  this.ws?.send(JSON.stringify(subscribeMsg));
15568
15666
  this.watchedPrimaryBranch = this.currentBranch;
15569
15667
  this.activeDependencySubscriptions.clear();
@@ -15573,7 +15671,7 @@ Promise.resolve()
15573
15671
  this.ws.on("unexpected-response", (request, response)=>{
15574
15672
  const summary = this.summarizeUnexpectedResponse(response, wsUrl);
15575
15673
  this.lastDisconnectSummary = summary;
15576
- logger_logger.error(external_chalk_default().red(summary));
15674
+ this.logger.error(summary);
15577
15675
  response.resume();
15578
15676
  request.destroy();
15579
15677
  if (this.isClosing) return;
@@ -15589,23 +15687,23 @@ Promise.resolve()
15589
15687
  this.markSocketResponsive();
15590
15688
  try {
15591
15689
  const msg = JSON.parse(data.toString());
15592
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Message: ${JSON.stringify(msg)}`);
15690
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Message: ${JSON.stringify(msg)}`));
15593
15691
  this.handleDependencySubscriptionReply(msg);
15594
15692
  this.handleMessage(msg);
15595
15693
  } catch (error) {
15596
- logger_logger.error(external_chalk_default().red(`Failed to parse WebSocket message: ${error.message}`));
15694
+ this.logger.error(`Failed to parse WebSocket message: ${error.message}`);
15597
15695
  }
15598
15696
  });
15599
15697
  this.ws.on("pong", ()=>{
15600
15698
  this.markSocketResponsive();
15601
15699
  });
15602
15700
  this.ws.on("close", (code, reason)=>{
15603
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Closed: code=${code}, reason=${reason.toString()}`);
15701
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Closed: code=${code}, reason=${reason.toString()}`));
15604
15702
  this.stopHeartbeat();
15605
15703
  this.ws = null;
15606
15704
  if (1008 === code || reason.toString().includes("unauthenticated")) {
15607
- logger_logger.warn(external_chalk_default().yellow(" WebSocket authentication failed - changes from the Anvil Editor won't be detected"));
15608
- logger_logger.verbose(external_chalk_default().gray(" Local changes will still sync to Anvil, but editor changes won't appear locally"));
15705
+ this.logger.warn(" WebSocket authentication failed - changes from the Anvil Editor won't be detected");
15706
+ this.logger.verbose(" Local changes will still sync to Anvil, but editor changes won't appear locally");
15609
15707
  this.emit("auth-failed", void 0);
15610
15708
  return;
15611
15709
  }
@@ -15618,13 +15716,13 @@ Promise.resolve()
15618
15716
  this.scheduleReconnect();
15619
15717
  });
15620
15718
  this.ws.on("error", (error)=>{
15621
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Error: ${error.message}`);
15719
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Error: ${error.message}`));
15622
15720
  if (this.isClosing) return;
15623
15721
  if (error.message.includes("Unexpected server response")) return;
15624
- if (error.message.includes("502")) logger_logger.error(external_chalk_default().red(`WebSocket connection failed (502 Bad Gateway) - the server could not open the live update connection (${this.getConnectionContext()})`));
15722
+ if (error.message.includes("502")) this.logger.error(`WebSocket connection failed (502 Bad Gateway) - the server could not open the live update connection (${this.getConnectionContext()})`);
15625
15723
  else {
15626
15724
  const details = this.getConnectionContext();
15627
- logger_logger.error(external_chalk_default().red(`WebSocket error: ${error.message} (${details})`));
15725
+ this.logger.error(`WebSocket error: ${error.message} (${details})`);
15628
15726
  }
15629
15727
  this.lastDisconnectSummary = `WebSocket error: ${error.message}`;
15630
15728
  this.emit("error", {
@@ -15638,7 +15736,7 @@ Promise.resolve()
15638
15736
  });
15639
15737
  if ("REPO_UPDATE" === msg.event) {
15640
15738
  const { ref_update, commit } = msg;
15641
- if (!ref_update) return void logger_logger.debug("Ignoring REPO_UPDATE with no ref_update");
15739
+ if (!ref_update) return void this.logger.debug("Ignoring REPO_UPDATE with no ref_update");
15642
15740
  const { ref } = ref_update;
15643
15741
  const commitHash = "string" == typeof commit ? commit : commit?.v;
15644
15742
  const appId = this.getMessageAppId(msg);
@@ -15649,7 +15747,7 @@ Promise.resolve()
15649
15747
  saveSeq: ref_update?.["save-seq"]
15650
15748
  });
15651
15749
  } else if ("REPO_INVALIDATE" === msg.event) {
15652
- logger_logger.warn(external_chalk_default().yellow(" Repository invalidated, refreshing..."));
15750
+ this.logger.warn(" Repository invalidated, refreshing...");
15653
15751
  this.emit("repo-invalidate", void 0);
15654
15752
  } else if ("ENV_UPDATE" === msg.event) this.emit("env-update", normalizeEnvironmentBinding(msg));
15655
15753
  }
@@ -15684,7 +15782,7 @@ Promise.resolve()
15684
15782
  close() {
15685
15783
  this.isClosing = true;
15686
15784
  if (this.reconnectTimer) {
15687
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, "Clearing reconnect timer");
15785
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, "Clearing reconnect timer"));
15688
15786
  clearTimeout(this.reconnectTimer);
15689
15787
  this.reconnectTimer = null;
15690
15788
  }
@@ -15712,7 +15810,7 @@ Promise.resolve()
15712
15810
  if (this.reconnectTimer || this.isClosing) return;
15713
15811
  this.reconnectAttempts++;
15714
15812
  const delayMs = this.reconnectDelayMs;
15715
- logger_logger.verbose(external_chalk_default().gray(`WebSocket disconnected (${this.lastDisconnectSummary ?? "unknown cause"}), reconnecting in ${Math.round(delayMs / 1000)}s (${this.getConnectionContext()}, next connect attempt ${this.connectAttempts + 1})...`));
15813
+ this.logger.verbose(`WebSocket disconnected (${this.lastDisconnectSummary ?? "unknown cause"}), reconnecting in ${Math.round(delayMs / 1000)}s (${this.getConnectionContext()}, next connect attempt ${this.connectAttempts + 1})...`);
15716
15814
  this.reconnectTimer = setTimeout(()=>{
15717
15815
  this.reconnectTimer = null;
15718
15816
  this.connect().catch((error)=>{
@@ -15756,8 +15854,8 @@ Promise.resolve()
15756
15854
  app: subscription.appId,
15757
15855
  only_branch: subscription.branch
15758
15856
  };
15759
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Subscribing dependency: ${JSON.stringify(subscribeMsg)}`);
15760
- logger_logger.verbose(external_chalk_default().gray(`Watching dependency ${subscription.packageName ?? subscription.appId} (${subscription.appId}, branch ${subscription.branch})`));
15857
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Subscribing dependency: ${JSON.stringify(subscribeMsg)}`));
15858
+ this.logger.verbose(`Watching dependency ${subscription.packageName ?? subscription.appId} (${subscription.appId}, branch ${subscription.branch})`);
15761
15859
  this.ws.send(JSON.stringify(subscribeMsg));
15762
15860
  }
15763
15861
  }
@@ -15768,7 +15866,7 @@ Promise.resolve()
15768
15866
  this.pendingDependencySubscriptionById.delete(msg.id);
15769
15867
  if (!msg.error) return;
15770
15868
  this.activeDependencySubscriptions.delete(this.dependencySubscriptionKey(subscription));
15771
- logger_logger.warn(external_chalk_default().yellow(`Could not watch dependency ${subscription.packageName ?? subscription.appId} (${subscription.appId}, branch ${subscription.branch}): ${this.formatDependencySubscriptionError(msg.error)}`));
15869
+ this.logger.warn(`Could not watch dependency ${subscription.packageName ?? subscription.appId} (${subscription.appId}, branch ${subscription.branch}): ${this.formatDependencySubscriptionError(msg.error)}`);
15772
15870
  }
15773
15871
  formatDependencySubscriptionError(error) {
15774
15872
  if ("string" == typeof error) return error;
@@ -15797,7 +15895,7 @@ Promise.resolve()
15797
15895
  const unwatchedAppIds = new Set();
15798
15896
  for (const subscription of subscriptions)if (!unwatchedAppIds.has(subscription.appId)) {
15799
15897
  unwatchedAppIds.add(subscription.appId);
15800
- logger_logger.verbose(external_chalk_default().gray(`Stopped watching dependency ${subscription.packageName ?? subscription.appId} (${subscription.appId})`));
15898
+ this.logger.verbose(`Stopped watching dependency ${subscription.packageName ?? subscription.appId} (${subscription.appId})`);
15801
15899
  this.ws.send(JSON.stringify(this.buildUnsubscribeMessage(subscription.appId)));
15802
15900
  }
15803
15901
  for (const subscription of subscriptions)this.activeDependencySubscriptions.delete(this.dependencySubscriptionKey(subscription));
@@ -15848,12 +15946,12 @@ Promise.resolve()
15848
15946
  try {
15849
15947
  ws.ping();
15850
15948
  } catch (error) {
15851
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, `Failed to send ping: ${error.message}`);
15949
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, `Failed to send ping: ${error.message}`));
15852
15950
  ws.terminate();
15853
15951
  return;
15854
15952
  }
15855
15953
  this.pongTimeoutTimer = setTimeout(()=>{
15856
- logger_logger.warn(external_chalk_default().yellow(" WebSocket heartbeat timed out - reconnecting"));
15954
+ this.logger.warn(" WebSocket heartbeat timed out - reconnecting");
15857
15955
  ws.terminate();
15858
15956
  }, this.HEARTBEAT_TIMEOUT_MS);
15859
15957
  }, this.HEARTBEAT_INTERVAL_MS);
@@ -15880,7 +15978,7 @@ Promise.resolve()
15880
15978
  this.ws = null;
15881
15979
  if (!socket) return;
15882
15980
  try {
15883
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, "Closing WebSocket");
15981
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, "Closing WebSocket"));
15884
15982
  if (socket.readyState === external_ws_default().CONNECTING) {
15885
15983
  socket.once("error", ()=>{});
15886
15984
  socket.terminate();
@@ -15888,7 +15986,7 @@ Promise.resolve()
15888
15986
  }
15889
15987
  if (socket.readyState === external_ws_default().OPEN) return void socket.close();
15890
15988
  } catch (e) {
15891
- logger_logger.debug(`[WebSocket ${this.sessionId}]`, "Error closing WebSocket (ignoring):", e);
15989
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[WebSocket ${this.sessionId}]`, "Error closing WebSocket (ignoring):", e));
15892
15990
  }
15893
15991
  }
15894
15992
  dependencySubscriptionKey(subscription) {
@@ -15914,12 +16012,13 @@ Promise.resolve()
15914
16012
  }
15915
16013
  return deduped;
15916
16014
  }
15917
- async function detectRemoteChanges(gitService, oldCommitId, newCommitId) {
16015
+ async function detectRemoteChanges(gitService, oldCommitId, newCommitId, options = {}) {
16016
+ const logger = options.logger ?? reporting_silentLogger;
15918
16017
  try {
15919
16018
  const files = await gitService.diffNames(oldCommitId, newCommitId);
15920
16019
  return new Set(files);
15921
16020
  } catch (e) {
15922
- logger_logger.debug("Git diff error:", errors_getErrorMessage(e));
16021
+ logger.debug(`Git diff error: ${errors_getErrorMessage(e)}`);
15923
16022
  return new Set();
15924
16023
  }
15925
16024
  }
@@ -15944,17 +16043,18 @@ Promise.resolve()
15944
16043
  remoteOnlyChanges
15945
16044
  };
15946
16045
  }
15947
- async function acceptRemoteChanges(gitService, remoteOnlyChanges) {
16046
+ async function acceptRemoteChanges(gitService, remoteOnlyChanges, options = {}) {
16047
+ const logger = options.logger ?? reporting_silentLogger;
15948
16048
  if (remoteOnlyChanges.length > 0) {
15949
- logger_logger.verbose(external_chalk_default().blue(`Accepting ${remoteOnlyChanges.length} remote-only change(s)...`));
16049
+ logger.verbose(`Accepting ${remoteOnlyChanges.length} remote-only change(s)...`);
15950
16050
  for (const file of remoteOnlyChanges)try {
15951
16051
  await gitService.checkout([
15952
16052
  file
15953
16053
  ]);
15954
- logger_logger.verbose(external_chalk_default().gray(` ✓ Accepted remote: ${file}`));
16054
+ logger.verbose(` ✓ Accepted remote: ${file}`);
15955
16055
  } catch (e) {
15956
16056
  const errorMsg = errors_getErrorMessage(e);
15957
- if (errorMsg.includes("pathspec") && errorMsg.includes("did not match any file")) logger_logger.warn(external_chalk_default().yellow(` Skipping ${file}: file not found in git repository`));
16057
+ if (errorMsg.includes("pathspec") && errorMsg.includes("did not match any file")) logger.warn(` Skipping ${file}: file not found in git repository`);
15958
16058
  else throw new Error(errorMsg);
15959
16059
  }
15960
16060
  }
@@ -16000,17 +16100,19 @@ Promise.resolve()
16000
16100
  ...renameChanges
16001
16101
  ];
16002
16102
  }
16003
- function logConflictResolution(result) {
16103
+ function logConflictResolution(result, options = {}) {
16104
+ const logger = options.logger ?? reporting_silentLogger;
16004
16105
  if (result.conflicts.length > 0) {
16005
- logger_logger.warn(external_chalk_default().yellow(` ${result.conflicts.length} file(s) changed both locally and remotely - keeping your local changes:`));
16006
- result.conflicts.forEach((c)=>logger_logger.info(external_chalk_default().yellow(` ${c.path}`)));
16106
+ logger.warn(` ${result.conflicts.length} file(s) changed both locally and remotely - keeping your local changes:`);
16107
+ result.conflicts.forEach((c)=>logger.info(` ${c.path}`));
16007
16108
  }
16008
16109
  if (result.localOnlyChanges.length > 0) {
16009
- logger_logger.info(external_chalk_default().blue(`📝 ${result.localOnlyChanges.length} local change(s) preserved:`));
16010
- result.localOnlyChanges.forEach((c)=>logger_logger.verbose(external_chalk_default().gray(` ${c.path}`)));
16110
+ logger.info(`📝 ${result.localOnlyChanges.length} local change(s) preserved:`);
16111
+ result.localOnlyChanges.forEach((c)=>logger.verbose(` ${c.path}`));
16011
16112
  }
16012
16113
  }
16013
16114
  async function deleteFilesRemovedOnAnvil(gitService, unstagedFiles, remotelyChangedFiles, options = {}) {
16115
+ const logger = options.logger ?? reporting_silentLogger;
16014
16116
  const filesToRemove = [];
16015
16117
  const localChangesToPreserve = options.localChangesToPreserve ?? new Set();
16016
16118
  for (const file of unstagedFiles)if (!localChangesToPreserve.has(file)) {
@@ -16030,7 +16132,7 @@ Promise.resolve()
16030
16132
  if (filesToRemove.length > 0) try {
16031
16133
  await gitService.clean(filesToRemove);
16032
16134
  filesToRemove.forEach((file)=>{
16033
- logger_logger.verbose(external_chalk_default().gray(` Deleted file removed on Anvil: ${file}`));
16135
+ logger.verbose(` Deleted file removed on Anvil: ${file}`);
16034
16136
  });
16035
16137
  await gitService.removeEmptyDirectories(filesToRemove);
16036
16138
  } catch (e) {}
@@ -16423,8 +16525,10 @@ Promise.resolve()
16423
16525
  }
16424
16526
  if (void 0 !== value.toolbox_item && !isPlainObject(value.toolbox_item)) formTemplateValidation_pushIssue(issues, path("toolbox_item"), "must be an object");
16425
16527
  if (void 0 !== value.layout_metadata && !isPlainObject(value.layout_metadata)) formTemplateValidation_pushIssue(issues, path("layout_metadata"), "must be an object");
16528
+ if (void 0 !== value.help_text && "string" != typeof value.help_text) formTemplateValidation_pushIssue(issues, path("help_text"), "must be a string");
16426
16529
  if (void 0 !== value.item_type) if (isPlainObject(value.item_type)) {
16427
- if ("number" != typeof value.item_type.table_id) formTemplateValidation_pushIssue(issues, path("item_type.table_id"), "must be a number");
16530
+ if (void 0 !== value.item_type.table_name) validateNonEmptyString(value.item_type.table_name, path("item_type.table_name"), issues);
16531
+ else if ("number" != typeof value.item_type.table_id) formTemplateValidation_pushIssue(issues, path("item_type.table_id"), "must be a number");
16428
16532
  } else formTemplateValidation_pushIssue(issues, path("item_type"), "must be an object");
16429
16533
  return issues;
16430
16534
  }
@@ -16475,6 +16579,28 @@ Promise.resolve()
16475
16579
  }));
16476
16580
  return issues;
16477
16581
  }
16582
+ function findAnvilAppRoot(filePath) {
16583
+ const existingPath = external_path_default().resolve(filePath);
16584
+ if (!external_fs_.existsSync(existingPath)) return null;
16585
+ let currentDir = external_fs_.statSync(existingPath).isDirectory() ? existingPath : external_path_default().dirname(existingPath);
16586
+ const candidates = [];
16587
+ while(true){
16588
+ if (external_fs_.existsSync(external_path_default().join(currentDir, "anvil.yaml"))) candidates.push(currentDir);
16589
+ const parentDir = external_path_default().dirname(currentDir);
16590
+ if (parentDir === currentDir) break;
16591
+ currentDir = parentDir;
16592
+ }
16593
+ return candidates.find((candidate)=>!candidates.some((outerCandidate)=>{
16594
+ if (candidate === outerCandidate) return false;
16595
+ return [
16596
+ "client_code",
16597
+ "server_code"
16598
+ ].some((codeDir)=>{
16599
+ const relativePath = external_path_default().relative(external_path_default().join(outerCandidate, codeDir), candidate);
16600
+ return !external_path_default().isAbsolute(relativePath) && ".." !== relativePath && !relativePath.startsWith(`..${external_path_default().sep}`);
16601
+ });
16602
+ })) ?? null;
16603
+ }
16478
16604
  const KNOWN_RUNTIME_SERVICE_SOURCES = new Set([
16479
16605
  "/runtime/services/tables.yml",
16480
16606
  "/runtime/services/google.yml",
@@ -16487,7 +16613,8 @@ Promise.resolve()
16487
16613
  "/runtime/services/anvil/saml.yml",
16488
16614
  "/runtime/services/anvil/microsoft.yml",
16489
16615
  "/runtime/services/anvil/email.yml",
16490
- "/runtime/services/anvil/files.yml"
16616
+ "/runtime/services/anvil/files.yml",
16617
+ "/runtime/services/anvil/tests.yml"
16491
16618
  ]);
16492
16619
  const FRONTMATTER_ALLOWED_KEYS = new Set([
16493
16620
  "custom_component",
@@ -16497,7 +16624,8 @@ Promise.resolve()
16497
16624
  "toolbox_item",
16498
16625
  "layout_metadata",
16499
16626
  "item_type",
16500
- "slots"
16627
+ "slots",
16628
+ "help_text"
16501
16629
  ]);
16502
16630
  const FRONTMATTER_DISALLOWED_KEYS = new Set([
16503
16631
  "container",
@@ -16847,6 +16975,38 @@ print(json.dumps({"issues": issues}))
16847
16975
  ok: true
16848
16976
  };
16849
16977
  }
16978
+ const css_namespaceObject = require("@lezer/css");
16979
+ function validateThemeCss(source) {
16980
+ if (!/anvil-dropzone/i.test(source)) return [];
16981
+ const warnings = [];
16982
+ let line = 1;
16983
+ let lineStart = 0;
16984
+ let nextLineBreak = source.indexOf("\n");
16985
+ css_namespaceObject.parser.parse(source).iterate({
16986
+ enter (node) {
16987
+ if ("SelectorQuery" === node.name) return false;
16988
+ if ("TagName" !== node.name || node.node.parent?.name !== "TagSelector" || "anvil-dropzone" !== source.slice(node.from, node.to).toLowerCase()) return;
16989
+ while(-1 !== nextLineBreak && nextLineBreak < node.from){
16990
+ line += 1;
16991
+ lineStart = nextLineBreak + 1;
16992
+ nextLineBreak = source.indexOf("\n", lineStart);
16993
+ }
16994
+ const column = node.from - lineStart + 1;
16995
+ warnings.push({
16996
+ path: "anvil-dropzone",
16997
+ code: "anvil-dropzone-selector",
16998
+ message: "HtmlComponent no longer renders anvil-dropzone elements. Target a component class or its surrounding element instead.",
16999
+ line,
17000
+ column,
17001
+ endLine: line,
17002
+ endColumn: column + node.to - node.from,
17003
+ offset: node.from,
17004
+ endOffset: node.to
17005
+ });
17006
+ }
17007
+ });
17008
+ return warnings;
17009
+ }
16850
17010
  const validators_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
16851
17011
  const DB_ACCESS_LEVELS = new Set([
16852
17012
  "none",
@@ -17250,6 +17410,10 @@ print(json.dumps({"issues": issues}))
17250
17410
  }
17251
17411
  function inferValidationTarget(filePath) {
17252
17412
  const normalizedPath = filePath.replace(/\\/g, "/");
17413
+ if (/(^|\/)theme\/assets\/.+\.css$/i.test(normalizedPath)) {
17414
+ const appRoot = findAnvilAppRoot(filePath);
17415
+ if (!appRoot || external_path_default().relative(appRoot, filePath).replace(/\\/g, "/").startsWith("theme/assets/")) return "css";
17416
+ }
17253
17417
  if ("anvil.yaml" === normalizedPath || normalizedPath.endsWith("/anvil.yaml")) return "anvil.yaml";
17254
17418
  const clientCodePrefix = "client_code/";
17255
17419
  if (normalizedPath.startsWith(clientCodePrefix) || normalizedPath.includes(`/${clientCodePrefix}`)) {
@@ -17271,28 +17435,6 @@ print(json.dumps({"issues": issues}))
17271
17435
  const absolutePath = external_path_default().resolve(filePath);
17272
17436
  return external_fs_.existsSync(absolutePath) ? absolutePath : null;
17273
17437
  }
17274
- function findAnvilAppRoot(filePath) {
17275
- const existingPath = resolveExistingPath(filePath);
17276
- if (!existingPath) return null;
17277
- let currentDir = external_fs_.statSync(existingPath).isDirectory() ? existingPath : external_path_default().dirname(existingPath);
17278
- const candidates = [];
17279
- while(true){
17280
- if (external_fs_.existsSync(external_path_default().join(currentDir, "anvil.yaml"))) candidates.push(currentDir);
17281
- const parentDir = external_path_default().dirname(currentDir);
17282
- if (parentDir === currentDir) break;
17283
- currentDir = parentDir;
17284
- }
17285
- return candidates.find((candidate)=>!candidates.some((outerCandidate)=>{
17286
- if (candidate === outerCandidate) return false;
17287
- return [
17288
- "client_code",
17289
- "server_code"
17290
- ].some((codeDir)=>{
17291
- const relativePath = external_path_default().relative(external_path_default().join(outerCandidate, codeDir), candidate);
17292
- return !external_path_default().isAbsolute(relativePath) && ".." !== relativePath && !relativePath.startsWith(`..${external_path_default().sep}`);
17293
- });
17294
- })) ?? null;
17295
- }
17296
17438
  function validatePath(filePath, fileContent, options = {}) {
17297
17439
  const target = inferValidationTarget(filePath);
17298
17440
  const existingPath = resolveExistingPath(filePath);
@@ -17308,6 +17450,7 @@ print(json.dumps({"issues": issues}))
17308
17450
  }
17309
17451
  ]
17310
17452
  };
17453
+ if ("css" === target) return validPathResult(target, validateThemeCss(fileContent));
17311
17454
  if ("anvil.yaml" === target) {
17312
17455
  if (existingPath && appRoot && external_path_default().resolve(existingPath) !== external_path_default().join(appRoot, "anvil.yaml")) return {
17313
17456
  ok: false,
@@ -17407,7 +17550,7 @@ print(json.dumps({"issues": issues}))
17407
17550
  issues: [
17408
17551
  {
17409
17552
  path: "",
17410
- message: "supported paths are anvil.yaml, client_code/**/form_template.yaml, client_code/**/*.yaml, client_code/**/*.html, client_code/**/*.py, and server_code/**/*.py"
17553
+ message: "supported paths are anvil.yaml, client_code/**/form_template.yaml, client_code/**/*.yaml, client_code/**/*.html, client_code/**/*.py, server_code/**/*.py, and theme/assets/**/*.css"
17411
17554
  }
17412
17555
  ]
17413
17556
  };
@@ -17649,7 +17792,8 @@ print(json.dumps({"issues": issues}))
17649
17792
  content: null
17650
17793
  };
17651
17794
  }
17652
- function deduplicateFormChanges(changes) {
17795
+ function deduplicateFormChanges(changes, options = {}) {
17796
+ const logger = options.logger ?? reporting_silentLogger;
17653
17797
  const filtered = [];
17654
17798
  const seenCodeFiles = new Set();
17655
17799
  for (const change of changes)if ("rename" === change.type || "add" === change.type) {
@@ -17679,7 +17823,7 @@ print(json.dumps({"issues": issues}))
17679
17823
  hasCorrespondingCode &&= seenCodeFiles.has(correspondingFromCodePath);
17680
17824
  }
17681
17825
  if (hasCorrespondingCode) {
17682
- logger_logger.verbose(external_chalk_default().gray(` Skipping form template ${change.type}: ${change.path} (handled by code file)`));
17826
+ logger.verbose(` Skipping form template ${change.type}: ${change.path} (handled by code file)`);
17683
17827
  continue;
17684
17828
  }
17685
17829
  if ("rename" === change.type && change.from) filtered.push({
@@ -17694,8 +17838,9 @@ print(json.dumps({"issues": issues}))
17694
17838
  return filtered;
17695
17839
  }
17696
17840
  async function routeFileChange(change, context) {
17841
+ const logger = context.logger ?? reporting_silentLogger;
17697
17842
  const { relativePath, changeType, fromPath } = change;
17698
- logger_logger.verbose(external_chalk_default().gray(`Routing ${changeType}: ${relativePath}${fromPath ? ` (from: ${fromPath})` : ""}`));
17843
+ logger.verbose(`Routing ${changeType}: ${relativePath}${fromPath ? ` (from: ${fromPath})` : ""}`);
17699
17844
  if (isGitRelatedFile(relativePath)) return {
17700
17845
  type: "ignore",
17701
17846
  reason: "Git internal file"
@@ -17759,10 +17904,11 @@ print(json.dumps({"issues": issues}))
17759
17904
  }
17760
17905
  ];
17761
17906
  async function handleRename(rename, context) {
17907
+ const logger = context.logger ?? reporting_silentLogger;
17762
17908
  const { fromPath, toPath } = rename;
17763
17909
  const validation = await validateRename(fromPath, toPath, context);
17764
17910
  if (!validation.valid) {
17765
- logger_logger.verbose(external_chalk_default().yellow(`Rename invalid (${validation.reason}), falling back to unlink + add`));
17911
+ logger.verbose(`Rename invalid (${validation.reason}), falling back to unlink + add`);
17766
17912
  const unlinkResult = await routeFileChange({
17767
17913
  relativePath: fromPath,
17768
17914
  changeType: "unlink"
@@ -17991,6 +18137,7 @@ print(json.dumps({"issues": issues}))
17991
18137
  };
17992
18138
  }
17993
18139
  async function handleDirectoryRenaming(rename, context) {
18140
+ const logger = context.logger ?? reporting_silentLogger;
17994
18141
  const { repoPath } = context;
17995
18142
  const { originalParts, pythonifiedParts, baseDir } = rename;
17996
18143
  const needsRename = originalParts.some((part, idx)=>part !== pythonifiedParts[idx]);
@@ -18000,7 +18147,7 @@ print(json.dumps({"issues": issues}))
18000
18147
  for(let i = 0; i < originalParts.length - 1; i++)if (originalParts[i] !== pythonifiedParts[i]) {
18001
18148
  const oldDirPath = external_path_default().join(repoPath, baseDir, ...originalParts.slice(0, i + 1));
18002
18149
  const newDirPath = external_path_default().join(repoPath, baseDir, ...pythonifiedParts.slice(0, i + 1));
18003
- logger_logger.verbose(external_chalk_default().yellow(`Renaming directory ${external_path_default().relative(repoPath, oldDirPath)} → ${external_path_default().relative(repoPath, newDirPath)} (pythonifying)`));
18150
+ logger.verbose(`Renaming directory ${external_path_default().relative(repoPath, oldDirPath)} → ${external_path_default().relative(repoPath, newDirPath)} (pythonifying)`);
18004
18151
  await external_fs_.promises.rename(oldDirPath, newDirPath);
18005
18152
  return {
18006
18153
  type: "ignore",
@@ -18011,6 +18158,7 @@ print(json.dumps({"issues": issues}))
18011
18158
  return null;
18012
18159
  }
18013
18160
  async function renameIfNeeded(rename, context) {
18161
+ const logger = context.logger ?? reporting_silentLogger;
18014
18162
  const { repoPath } = context;
18015
18163
  const { relativePath, originalNameOrParts, baseDir } = rename;
18016
18164
  let pythonifiedName;
@@ -18034,7 +18182,7 @@ print(json.dumps({"issues": issues}))
18034
18182
  if (needsRename) {
18035
18183
  const oldPath = external_path_default().join(repoPath, relativePath);
18036
18184
  const newPath = external_path_default().join(repoPath, newRelativePath);
18037
- logger_logger.verbose(external_chalk_default().yellow(`Renaming ${relativePath} → ${newRelativePath} (pythonifying)`));
18185
+ logger.verbose(`Renaming ${relativePath} → ${newRelativePath} (pythonifying)`);
18038
18186
  await external_fs_.promises.rename(oldPath, newPath);
18039
18187
  ignoreResult = {
18040
18188
  type: "ignore",
@@ -18186,6 +18334,7 @@ print(json.dumps({"issues": issues}))
18186
18334
  });
18187
18335
  }
18188
18336
  async function buildFormTemplateData(relativePath, templateInfo, context, missingCodeBehavior = "error") {
18337
+ const logger = context.logger ?? reporting_silentLogger;
18189
18338
  const { repoPath, stagedOnly = false } = context;
18190
18339
  const { kind } = templateInfo;
18191
18340
  const loadResult = await loadFormTemplateData(relativePath, templateInfo, context);
@@ -18208,7 +18357,7 @@ print(json.dumps({"issues": issues}))
18208
18357
  const knownForm = context.editorYaml.hasId("forms", className);
18209
18358
  if ("defer" === missingCodeBehavior || knownForm) {
18210
18359
  const action = knownForm ? `not saving existing form ${className}` : `deferring form ${className}`;
18211
- logger_logger.warn(external_chalk_default().yellow(`Form template ${relativePath} has no code file ${codeRelativePath} yet; ${action}.`));
18360
+ logger.warn(`Form template ${relativePath} has no code file ${codeRelativePath} yet; ${action}.`);
18212
18361
  return {
18213
18362
  formData: {},
18214
18363
  className: "",
@@ -18219,7 +18368,7 @@ print(json.dumps({"issues": issues}))
18219
18368
  };
18220
18369
  }
18221
18370
  codeContent = "";
18222
- logger_logger.warn(external_chalk_default().yellow(`Form template ${relativePath} has no code file ${codeRelativePath} yet; creating ${className} with empty code.`));
18371
+ logger.warn(`Form template ${relativePath} has no code file ${codeRelativePath} yet; creating ${className} with empty code.`);
18223
18372
  }
18224
18373
  const formData = (0, form_template_parser_namespaceObject.buildFormTemplateSavePayload)(loadResult.source, {
18225
18374
  className,
@@ -18381,7 +18530,8 @@ print(json.dumps({"issues": issues}))
18381
18530
  reason: "No matching deletion route"
18382
18531
  };
18383
18532
  }
18384
- async function getAnvilYamlChanges(repoPath, previousYaml) {
18533
+ async function getAnvilYamlChanges(repoPath, previousYaml, options = {}) {
18534
+ const logger = options.logger ?? reporting_silentLogger;
18385
18535
  const anvilYamlPath = external_path_default().join(repoPath, "anvil.yaml");
18386
18536
  let yamlContent;
18387
18537
  let parsedYaml;
@@ -18393,8 +18543,8 @@ print(json.dumps({"issues": issues}))
18393
18543
  try {
18394
18544
  parsedYaml = external_js_yaml_default().load(yamlContent, {
18395
18545
  onWarning: (warning)=>{
18396
- logger_logger.warn(external_chalk_default().yellow(` YAML warning in anvil.yaml: ${warning.message}`));
18397
- if (warning.mark) logger_logger.verbose(external_chalk_default().gray(` Line ${warning.mark.line + 1}, column ${warning.mark.column + 1}`));
18546
+ logger.warn(` YAML warning in anvil.yaml: ${warning.message}`);
18547
+ if (warning.mark) logger.verbose(` Line ${warning.mark.line + 1}, column ${warning.mark.column + 1}`);
18398
18548
  }
18399
18549
  });
18400
18550
  } catch (error) {
@@ -18586,6 +18736,8 @@ print(json.dumps({"issues": issues}))
18586
18736
  }
18587
18737
  }
18588
18738
  class SaveProcessor extends Emitter {
18739
+ logger;
18740
+ progress;
18589
18741
  hasPendingChanges = false;
18590
18742
  debounceTimer = null;
18591
18743
  saveLoopPromise = null;
@@ -18596,7 +18748,10 @@ print(json.dumps({"issues": issues}))
18596
18748
  syncCallback = null;
18597
18749
  postSaveCallback = null;
18598
18750
  constructor(config){
18599
- super();
18751
+ const logger = config.logger ?? reporting_silentLogger;
18752
+ super((event, error)=>logger.error(`Error in event handler for '${event}': ${error}`));
18753
+ this.logger = logger;
18754
+ this.progress = config.progress ?? silentProgress;
18600
18755
  this.config = config;
18601
18756
  }
18602
18757
  setSyncCallback(callback) {
@@ -18610,11 +18765,11 @@ print(json.dumps({"issues": issues}))
18610
18765
  const isFirstChange = !this.hasPendingChanges;
18611
18766
  this.hasPendingChanges = true;
18612
18767
  if (this.debounceTimer) clearTimeout(this.debounceTimer);
18613
- if (isFirstChange) logger_logger.progress("sync", "Change detected");
18768
+ if (isFirstChange) this.progress.start("sync", "Change detected");
18614
18769
  this.debounceTimer = setTimeout(()=>{
18615
18770
  this.debounceTimer = null;
18616
18771
  this.processSaveBatchWithEvents().catch((error)=>{
18617
- logger_logger.error(`Save failed: ${errors_getErrorMessage(error)}`);
18772
+ this.logger.error(`Save failed: ${errors_getErrorMessage(error)}`);
18618
18773
  });
18619
18774
  }, this.SAVE_DEBOUNCE_MS);
18620
18775
  }
@@ -18637,7 +18792,7 @@ print(json.dumps({"issues": issues}))
18637
18792
  }
18638
18793
  cleanup() {
18639
18794
  if (this.hasPendingChanges) {
18640
- logger_logger.progressEnd("sync");
18795
+ this.progress.end("sync");
18641
18796
  this.hasPendingChanges = false;
18642
18797
  }
18643
18798
  if (this.debounceTimer) {
@@ -18659,8 +18814,8 @@ print(json.dumps({"issues": issues}))
18659
18814
  }
18660
18815
  async processOneSaveBatchWithEvents() {
18661
18816
  if (this.config.isCleanedUp()) return;
18662
- logger_logger.progressUpdate("sync", "Processing");
18663
- if (!this.hasPendingChanges) return void logger_logger.progressEnd("sync");
18817
+ this.progress.update("sync", "Processing");
18818
+ if (!this.hasPendingChanges) return void this.progress.end("sync");
18664
18819
  let fileCount = 0;
18665
18820
  try {
18666
18821
  const status = await this.config.gitService.getStatus();
@@ -18682,7 +18837,7 @@ print(json.dumps({"issues": issues}))
18682
18837
  });
18683
18838
  let finalMessage;
18684
18839
  finalMessage = result.skipped ? void 0 : await this.getSuccessMessage();
18685
- logger_logger.progressEnd("sync", finalMessage);
18840
+ this.progress.end("sync", finalMessage);
18686
18841
  } catch (e) {
18687
18842
  const diagnostic = createWatchDiagnostic(e, {
18688
18843
  branch: this.config.getCurrentBranch(),
@@ -18697,7 +18852,7 @@ print(json.dumps({"issues": issues}))
18697
18852
  newCommitId: this.config.getCommitId(),
18698
18853
  fileCount
18699
18854
  });
18700
- logger_logger.progressEnd("sync", "Failed");
18855
+ this.progress.end("sync", "Failed");
18701
18856
  throw e;
18702
18857
  }
18703
18858
  }
@@ -18719,7 +18874,7 @@ print(json.dumps({"issues": issues}))
18719
18874
  reason: "No pending changes"
18720
18875
  };
18721
18876
  this.hasPendingChanges = false;
18722
- logger_logger.verbose(external_chalk_default().cyan(`\n📦 Processing batched file changes...`));
18877
+ this.logger.verbose(`\n📦 Processing batched file changes...`);
18723
18878
  if (!this.config.isSettlePeriodOver()) return {
18724
18879
  skipped: true,
18725
18880
  reason: `Waiting (${this.config.getRemainingSettleTime()}s settle period)`
@@ -18730,34 +18885,34 @@ print(json.dumps({"issues": issues}))
18730
18885
  try {
18731
18886
  status = await this.config.gitService.getStatus();
18732
18887
  } catch (e) {
18733
- logger_logger.error(external_chalk_default().red(`Error reading git status: ${errors_getErrorMessage(e)}`));
18888
+ this.logger.error(`Error reading git status: ${errors_getErrorMessage(e)}`);
18734
18889
  throw e;
18735
18890
  }
18736
18891
  let allChanges;
18737
18892
  if (this.config.stagedOnly) {
18738
18893
  allChanges = await this.getStagedChanges();
18739
18894
  if (0 === allChanges.length) {
18740
- logger_logger.verbose(external_chalk_default().gray("No staged changes found"));
18895
+ this.logger.verbose("No staged changes found");
18741
18896
  return {
18742
18897
  skipped: true,
18743
18898
  reason: "No staged changes"
18744
18899
  };
18745
18900
  }
18746
- logger_logger.verbose(external_chalk_default().blue(`Found ${allChanges.length} staged change(s):`));
18901
+ this.logger.verbose(`Found ${allChanges.length} staged change(s):`);
18747
18902
  } else {
18748
18903
  allChanges = await this.getUnstagedChanges(status);
18749
18904
  if (0 === allChanges.length) {
18750
- logger_logger.verbose(external_chalk_default().gray("No unstaged changes found"));
18905
+ this.logger.verbose("No unstaged changes found");
18751
18906
  return {
18752
18907
  skipped: true,
18753
18908
  reason: "No unstaged changes"
18754
18909
  };
18755
18910
  }
18756
- logger_logger.verbose(external_chalk_default().blue(`Found ${allChanges.length} unstaged change(s):`));
18911
+ this.logger.verbose(`Found ${allChanges.length} unstaged change(s):`);
18757
18912
  }
18758
18913
  allChanges.forEach((c)=>{
18759
- if ("rename" === c.type) logger_logger.verbose(external_chalk_default().gray(` ${c.type}: ${c.from} → ${c.path}`));
18760
- else logger_logger.verbose(external_chalk_default().gray(` ${c.type}: ${c.path}`));
18914
+ if ("rename" === c.type) this.logger.verbose(` ${c.type}: ${c.from} → ${c.path}`);
18915
+ else this.logger.verbose(` ${c.type}: ${c.path}`);
18761
18916
  });
18762
18917
  return this.processBatchedChanges(allChanges);
18763
18918
  }
@@ -18765,7 +18920,7 @@ print(json.dumps({"issues": issues}))
18765
18920
  try {
18766
18921
  return await getStagedFileChanges(this.config.gitService.getGit(), this.config.gitService);
18767
18922
  } catch (e) {
18768
- logger_logger.error(external_chalk_default().red(`Error getting staged changes: ${errors_getErrorMessage(e)}`));
18923
+ this.logger.error(`Error getting staged changes: ${errors_getErrorMessage(e)}`);
18769
18924
  return [];
18770
18925
  }
18771
18926
  }
@@ -18826,7 +18981,7 @@ print(json.dumps({"issues": issues}))
18826
18981
  const hash = external_crypto_namespaceObject.createHash("sha256").update(content).digest("hex");
18827
18982
  newFileHashes.set(newPath, hash);
18828
18983
  } catch (error) {
18829
- logger_logger.debug(`Could not read new file: ${newPath}`);
18984
+ this.logger.debug(`Could not read new file: ${newPath}`);
18830
18985
  }
18831
18986
  for (const [deletedPath, deletedHash] of deletedFileHashes.entries())for (const [newPath, newHash] of newFileHashes.entries())if (deletedHash === newHash && !matchedNewFiles.has(newPath)) {
18832
18987
  renames.push({
@@ -18862,16 +19017,20 @@ print(json.dumps({"issues": issues}))
18862
19017
  const saveArray = [];
18863
19018
  const originalFilePaths = [];
18864
19019
  let anvilYamlDependenciesChanged = false;
18865
- const deduplicatedChanges = deduplicateFormChanges(changes);
19020
+ const deduplicatedChanges = deduplicateFormChanges(changes, {
19021
+ logger: this.logger
19022
+ });
18866
19023
  for (const change of deduplicatedChanges){
18867
19024
  if ("anvil.yaml" === change.path) {
18868
19025
  const previousAnvilYaml = await this.getHeadAnvilYaml();
18869
- const anvilChanges = await getAnvilYamlChanges(this.config.repoPath, previousAnvilYaml);
19026
+ const anvilChanges = await getAnvilYamlChanges(this.config.repoPath, previousAnvilYaml, {
19027
+ logger: this.logger
19028
+ });
18870
19029
  const previousDependencies = normalizeAnvilYamlDependenciesValue(previousAnvilYaml?.dependencies);
18871
19030
  const currentDependencies = await readAnvilYamlDependencies(this.config.repoPath);
18872
19031
  if (!anvilYamlDependenciesEqual(previousDependencies, currentDependencies)) anvilYamlDependenciesChanged = true;
18873
19032
  if (0 === anvilChanges.length) {
18874
- logger_logger.verbose(external_chalk_default().gray(" Ignoring anvil.yaml: No changes detected"));
19033
+ this.logger.verbose(" Ignoring anvil.yaml: No changes detected");
18875
19034
  continue;
18876
19035
  }
18877
19036
  for (const { key, value } of anvilChanges){
@@ -18881,7 +19040,7 @@ print(json.dumps({"issues": issues}))
18881
19040
  ],
18882
19041
  value
18883
19042
  ]);
18884
- logger_logger.verbose(external_chalk_default().green(` ✓ anvil.yaml[${key}] → [["${key}"], ...]`));
19043
+ this.logger.verbose(` ✓ anvil.yaml[${key}] → [["${key}"], ...]`);
18885
19044
  }
18886
19045
  originalFilePaths.push(change.path);
18887
19046
  continue;
@@ -18891,6 +19050,7 @@ print(json.dumps({"issues": issues}))
18891
19050
  changeType: change.type,
18892
19051
  fromPath: change.from
18893
19052
  }, {
19053
+ logger: this.logger,
18894
19054
  repoPath: this.config.repoPath,
18895
19055
  editorYaml: this.config.editorYaml,
18896
19056
  stagedOnly: this.config.stagedOnly
@@ -18900,7 +19060,7 @@ print(json.dumps({"issues": issues}))
18900
19060
  ];
18901
19061
  for (const result of results){
18902
19062
  if ("ignore" === result.type) {
18903
- logger_logger.verbose(external_chalk_default().gray(` Ignoring ${change.path}: ${result.reason}`));
19063
+ this.logger.verbose(` Ignoring ${change.path}: ${result.reason}`);
18904
19064
  continue;
18905
19065
  }
18906
19066
  const { savePath, content } = result;
@@ -18913,7 +19073,7 @@ print(json.dumps({"issues": issues}))
18913
19073
  }
18914
19074
  }
18915
19075
  if (0 === saveArray.length) {
18916
- logger_logger.verbose(external_chalk_default().gray("No savable changes"));
19076
+ this.logger.verbose("No savable changes");
18917
19077
  return {
18918
19078
  skipped: true,
18919
19079
  reason: "No savable changes"
@@ -18937,25 +19097,25 @@ print(json.dumps({"issues": issues}))
18937
19097
  contentToLog = JSON.stringify(tempContent, null, 2);
18938
19098
  }
18939
19099
  const changeDesc = "rename" === change.type && change.from ? `${change.from} → ${change.path}` : change.path;
18940
- logger_logger.verbose(external_chalk_default().green(` ✓ ${changeDesc} → ${JSON.stringify(savePath)} → ${contentToLog}`));
19100
+ this.logger.verbose(` ✓ ${changeDesc} → ${JSON.stringify(savePath)} → ${contentToLog}`);
18941
19101
  }
18942
19102
  async sendSavesToAnvil(saveArray, originalFilePaths = [], retryCount = 0) {
18943
19103
  const fileCount = saveArray.length;
18944
19104
  const message = 1 === fileCount ? "Syncing to Anvil" : `Syncing ${fileCount} changes to Anvil`;
18945
- logger_logger.progressUpdate("sync", message);
19105
+ this.progress.update("sync", message);
18946
19106
  const payload = {
18947
19107
  edit_session: this.config.editSession,
18948
19108
  save_sequence: this.saveSequence++,
18949
19109
  version: this.config.getCommitId(),
18950
19110
  updates: saveArray
18951
19111
  };
18952
- logger_logger.debug("PAYLOAD:", external_chalk_default().white(JSON.stringify(this.sanitizePayload(payload), null, 2)));
19112
+ this.logger.debug((0, external_node_util_namespaceObject.format)("PAYLOAD:", JSON.stringify(this.sanitizePayload(payload), null, 2)));
18953
19113
  const currentBranch = this.config.getCurrentBranch();
18954
19114
  try {
18955
19115
  const branchFromGit = await this.config.gitService.getCurrentBranch();
18956
19116
  if (branchFromGit !== currentBranch) {
18957
19117
  const reason = `Branch ${branchFromGit} not validated`;
18958
- logger_logger.error(external_chalk_default().red(`Cannot sync - ${reason}`));
19118
+ this.logger.error(`Cannot sync - ${reason}`);
18959
19119
  const error = createSaveError.validationFailed(reason, branchFromGit);
18960
19120
  this.emit("validation-failed", {
18961
19121
  reason,
@@ -18969,7 +19129,7 @@ print(json.dumps({"issues": issues}))
18969
19129
  } catch (e) {
18970
19130
  if ("save_validation_failed" === e.type) throw e;
18971
19131
  const reason = "Branch unknown not validated";
18972
- logger_logger.error(external_chalk_default().red(`Cannot sync - ${reason}`));
19132
+ this.logger.error(`Cannot sync - ${reason}`);
18973
19133
  const error = createSaveError.validationFailed(reason, "unknown");
18974
19134
  this.emit("validation-failed", {
18975
19135
  reason,
@@ -18991,15 +19151,15 @@ print(json.dumps({"issues": issues}))
18991
19151
  body: JSON.stringify(payload)
18992
19152
  });
18993
19153
  const json_resp = await resp.json();
18994
- logger_logger.debug("JSON RESPONSE:", external_chalk_default().white(JSON.stringify(json_resp, null, 2)));
19154
+ this.logger.debug((0, external_node_util_namespaceObject.format)("JSON RESPONSE:", JSON.stringify(json_resp, null, 2)));
18995
19155
  if (401 === resp.status || 403 === resp.status) this.handleAuthError(resp.status, json_resp);
18996
19156
  if (409 === resp.status) {
18997
- logger_logger.progressUpdate("sync", "Conflict - retrying");
19157
+ this.progress.update("sync", "Conflict - retrying");
18998
19158
  await this.handleConflict(json_resp, originalFilePaths, retryCount);
18999
19159
  return;
19000
19160
  }
19001
19161
  if (200 === resp.status) return void await this.handleSuccess(json_resp, originalFilePaths);
19002
- logger_logger.error(`Unexpected response status: ${resp.status}`);
19162
+ this.logger.error(`Unexpected response status: ${resp.status}`);
19003
19163
  throw {
19004
19164
  type: "server_error",
19005
19165
  status: resp.status,
@@ -19035,15 +19195,15 @@ print(json.dumps({"issues": issues}))
19035
19195
  handleAuthError(status, json_resp) {
19036
19196
  const errorMsg = json_resp.error || "unauthorized";
19037
19197
  const detailedMsg = `Authentication failed (${status}): ${errorMsg}`;
19038
- if (403 === status) logger_logger.error(`${detailedMsg}\n This may indicate:\n - The OAuth token doesn't have permission to write to app ${this.config.appId}\n - The app belongs to a different user or organization\n - The OAuth token is missing required scopes (apps:write)`);
19039
- else logger_logger.error(detailedMsg);
19198
+ if (403 === status) this.logger.error(`${detailedMsg}\n This may indicate:\n - The OAuth token doesn't have permission to write to app ${this.config.appId}\n - The app belongs to a different user or organization\n - The OAuth token is missing required scopes (apps:write)`);
19199
+ else this.logger.error(detailedMsg);
19040
19200
  throw createAuthError.invalid(detailedMsg);
19041
19201
  }
19042
19202
  async handleConflict(json_resp, originalFilePaths, retryCount) {
19043
19203
  const conflict = this.getConflictDiagnosticInfo(json_resp);
19044
19204
  if (retryCount >= this.MAX_RETRIES) {
19045
- logger_logger.error(`Save failed after ${this.MAX_RETRIES} retries due to version conflicts.`);
19046
- logger_logger.warn("This usually means someone else is editing the app at the same time.");
19205
+ this.logger.error(`Save failed after ${this.MAX_RETRIES} retries due to version conflicts.`);
19206
+ this.logger.warn("This usually means someone else is editing the app at the same time.");
19047
19207
  const error = createSaveError.maxRetriesExceeded(this.MAX_RETRIES);
19048
19208
  this.emit("max-retries-exceeded", {
19049
19209
  retries: this.MAX_RETRIES,
@@ -19056,10 +19216,10 @@ print(json.dumps({"issues": issues}))
19056
19216
  });
19057
19217
  throw error;
19058
19218
  }
19059
- if (json_resp.overtaken) logger_logger.warn(`${conflict.reason}, fetching latest and retrying (attempt ${retryCount + 1}/${this.MAX_RETRIES})`);
19060
- else if (json_resp.latest_version) logger_logger.warn(`Version conflict detected, syncing to ${json_resp.latest_version.substring(0, 8)} and retrying (attempt ${retryCount + 1}/${this.MAX_RETRIES})`);
19219
+ if (json_resp.overtaken) this.logger.warn(`${conflict.reason}, fetching latest and retrying (attempt ${retryCount + 1}/${this.MAX_RETRIES})`);
19220
+ else if (json_resp.latest_version) this.logger.warn(`Version conflict detected, syncing to ${json_resp.latest_version.substring(0, 8)} and retrying (attempt ${retryCount + 1}/${this.MAX_RETRIES})`);
19061
19221
  else {
19062
- logger_logger.error("Save failed with 409 but no conflict info provided");
19222
+ this.logger.error("Save failed with 409 but no conflict info provided");
19063
19223
  throw createSaveError.conflict();
19064
19224
  }
19065
19225
  this.emit("sync-conflict", {
@@ -19077,7 +19237,7 @@ print(json.dumps({"issues": issues}))
19077
19237
  })
19078
19238
  });
19079
19239
  if (!this.syncCallback) throw createSaveError.noSyncCallback();
19080
- logger_logger.progressUpdate("sync", "Syncing back");
19240
+ this.progress.update("sync", "Syncing back");
19081
19241
  const syncResult = await this.syncCallback(new Set(originalFilePaths));
19082
19242
  const { localOnlyChanges, conflicts } = syncResult;
19083
19243
  const changesToSave = [
@@ -19111,13 +19271,13 @@ print(json.dumps({"issues": issues}))
19111
19271
  branch: this.config.getCurrentBranch()
19112
19272
  });
19113
19273
  if (this.postSaveCallback) {
19114
- logger_logger.progressUpdate("sync", "Syncing back");
19274
+ this.progress.update("sync", "Syncing back");
19115
19275
  await this.postSaveCallback(new Set(originalFilePaths));
19116
19276
  }
19117
19277
  if (this.config.getCommitId() === commitIdBeforePostSaveSync) this.config.setCommitId(version);
19118
19278
  }
19119
19279
  async rerouteChanges(changes) {
19120
- logger_logger.verbose(external_chalk_default().blue(`Re-routing ${changes.length} local change(s)...`));
19280
+ this.logger.verbose(`Re-routing ${changes.length} local change(s)...`);
19121
19281
  const newSaveArray = [];
19122
19282
  const newFilePaths = [];
19123
19283
  for (const change of changes){
@@ -19126,6 +19286,7 @@ print(json.dumps({"issues": issues}))
19126
19286
  changeType: change.type,
19127
19287
  fromPath: change.from
19128
19288
  }, {
19289
+ logger: this.logger,
19129
19290
  repoPath: this.config.repoPath,
19130
19291
  editorYaml: this.config.editorYaml,
19131
19292
  stagedOnly: this.config.stagedOnly
@@ -19135,7 +19296,7 @@ print(json.dumps({"issues": issues}))
19135
19296
  ];
19136
19297
  for (const result of results){
19137
19298
  if ("ignore" === result.type) {
19138
- logger_logger.verbose(external_chalk_default().gray(` Ignoring ${change.path}: ${result.reason}`));
19299
+ this.logger.verbose(` Ignoring ${change.path}: ${result.reason}`);
19139
19300
  continue;
19140
19301
  }
19141
19302
  newSaveArray.push([
@@ -19144,7 +19305,7 @@ print(json.dumps({"issues": issues}))
19144
19305
  ]);
19145
19306
  newFilePaths.push(change.path);
19146
19307
  const changeDesc = "rename" === change.type && change.from ? `${change.from} → ${change.path}` : change.path;
19147
- logger_logger.verbose(external_chalk_default().green(` ✓ ${changeDesc} → ${JSON.stringify(result.savePath)}`));
19308
+ this.logger.verbose(` ✓ ${changeDesc} → ${JSON.stringify(result.savePath)}`);
19148
19309
  }
19149
19310
  }
19150
19311
  return {
@@ -19167,10 +19328,13 @@ print(json.dumps({"issues": issues}))
19167
19328
  return normalized;
19168
19329
  }
19169
19330
  class SyncManager extends Emitter {
19331
+ logger;
19170
19332
  config;
19171
19333
  syncQueue = Promise.resolve();
19172
19334
  constructor(config){
19173
- super();
19335
+ const logger = config.logger ?? reporting_silentLogger;
19336
+ super((event, error)=>logger.error(`Error in event handler for '${event}': ${error}`));
19337
+ this.logger = logger;
19174
19338
  this.config = config;
19175
19339
  }
19176
19340
  async syncRemoteChanges(knownLocalChanges) {
@@ -19200,19 +19364,25 @@ print(json.dumps({"issues": issues}))
19200
19364
  };
19201
19365
  const newCommitId = await this.config.gitService.getCommitId();
19202
19366
  this.config.setCommitId(newCommitId);
19203
- const remoteChangedFiles = await detectRemoteChanges(this.config.gitService, oldCommitId, newCommitId);
19367
+ const remoteChangedFiles = await detectRemoteChanges(this.config.gitService, oldCommitId, newCommitId, {
19368
+ logger: this.logger
19369
+ });
19204
19370
  const statusAfter = await this.config.gitService.getStatus();
19205
19371
  const newChanges = extractChangesFromStatus(statusAfter);
19206
19372
  if (0 === newChanges.length) {
19207
- logger_logger.verbose(external_chalk_default().gray(" No local changes - working directory is clean"));
19373
+ this.logger.verbose(" No local changes - working directory is clean");
19208
19374
  return {
19209
19375
  localOnlyChanges: [],
19210
19376
  conflicts: []
19211
19377
  };
19212
19378
  }
19213
19379
  const result = categorizeChanges(newChanges, locallyChangedFiles, remoteChangedFiles);
19214
- await acceptRemoteChanges(this.config.gitService, result.remoteOnlyChanges);
19215
- logConflictResolution(result);
19380
+ await acceptRemoteChanges(this.config.gitService, result.remoteOnlyChanges, {
19381
+ logger: this.logger
19382
+ });
19383
+ logConflictResolution(result, {
19384
+ logger: this.logger
19385
+ });
19216
19386
  return {
19217
19387
  localOnlyChanges: result.localOnlyChanges,
19218
19388
  conflicts: result.conflicts
@@ -19271,13 +19441,16 @@ print(json.dumps({"issues": issues}))
19271
19441
  async deleteFilesRemovedOnAnvilLocally(oldCommitId, newCommitId, localChangesToPreserve) {
19272
19442
  try {
19273
19443
  const status = await this.config.gitService.getStatus();
19274
- const remotelyChangedFiles = await detectRemoteChanges(this.config.gitService, oldCommitId, newCommitId);
19444
+ const remotelyChangedFiles = await detectRemoteChanges(this.config.gitService, oldCommitId, newCommitId, {
19445
+ logger: this.logger
19446
+ });
19275
19447
  await deleteFilesRemovedOnAnvil(this.config.gitService, status.notAdded, remotelyChangedFiles, {
19448
+ logger: this.logger,
19276
19449
  oldCommitId,
19277
19450
  localChangesToPreserve
19278
19451
  });
19279
19452
  } catch (e) {
19280
- logger_logger.verbose(external_chalk_default().gray(` Failed to check git status: ${errors_getErrorMessage(e)}`));
19453
+ this.logger.verbose(` Failed to check git status: ${errors_getErrorMessage(e)}`);
19281
19454
  }
19282
19455
  }
19283
19456
  async discardFormattingOnlyYamlChanges() {
@@ -19285,7 +19458,7 @@ print(json.dumps({"issues": issues}))
19285
19458
  try {
19286
19459
  status = await this.config.gitService.getStatus();
19287
19460
  } catch (e) {
19288
- logger_logger.verbose(external_chalk_default().gray(` Failed to check git status: ${errors_getErrorMessage(e)}`));
19461
+ this.logger.verbose(` Failed to check git status: ${errors_getErrorMessage(e)}`);
19289
19462
  return;
19290
19463
  }
19291
19464
  const serverCreatedFiles = [
@@ -19297,7 +19470,7 @@ print(json.dumps({"issues": issues}))
19297
19470
  await this.config.gitService.checkout([
19298
19471
  yamlFile
19299
19472
  ]);
19300
- logger_logger.verbose(external_chalk_default().gray(` Accepted server-created file: ${yamlFile}`));
19473
+ this.logger.verbose(` Accepted server-created file: ${yamlFile}`);
19301
19474
  }
19302
19475
  const serverConvertedFormTemplates = status.deleted.filter((f)=>{
19303
19476
  const norm = f.replace(/\\/g, "/");
@@ -19310,7 +19483,7 @@ print(json.dumps({"issues": issues}))
19310
19483
  await this.config.gitService.checkout([
19311
19484
  htmlFile
19312
19485
  ]);
19313
- logger_logger.verbose(external_chalk_default().gray(` Accepted HTML form template: ${htmlFile}`));
19486
+ this.logger.verbose(` Accepted HTML form template: ${htmlFile}`);
19314
19487
  }
19315
19488
  const yamlFiles = status.modified.filter((f)=>f.endsWith(".yaml") || f.endsWith(".yml"));
19316
19489
  for (const yamlFile of yamlFiles)try {
@@ -19327,13 +19500,13 @@ print(json.dumps({"issues": issues}))
19327
19500
  const workingForCompare = stripNonSemanticYamlFields(yamlFile, workingParsed);
19328
19501
  const headForCompare = stripNonSemanticYamlFields(yamlFile, headParsed);
19329
19502
  if (deepEqual(workingForCompare, headForCompare)) {
19330
- logger_logger.verbose(external_chalk_default().gray(` Discarding formatting-only change: ${yamlFile}`));
19503
+ this.logger.verbose(` Discarding formatting-only change: ${yamlFile}`);
19331
19504
  await this.config.gitService.checkout([
19332
19505
  yamlFile
19333
19506
  ]);
19334
19507
  }
19335
19508
  } catch (error) {
19336
- logger_logger.verbose(external_chalk_default().gray(` Keeping ${yamlFile} (couldn't verify if formatting-only)`));
19509
+ this.logger.verbose(` Keeping ${yamlFile} (couldn't verify if formatting-only)`);
19337
19510
  }
19338
19511
  const htmlFiles = status.modified.filter((f)=>{
19339
19512
  const norm = f.replace(/\\/g, "/");
@@ -19351,18 +19524,20 @@ print(json.dumps({"issues": issues}))
19351
19524
  const working = parseHtmlWithFrontmatter(workingContent);
19352
19525
  const head = parseHtmlWithFrontmatter(headContent);
19353
19526
  if (deepEqual(working.frontmatter, head.frontmatter) && working.html === head.html) {
19354
- logger_logger.verbose(external_chalk_default().gray(` Discarding formatting-only change: ${htmlFile}`));
19527
+ this.logger.verbose(` Discarding formatting-only change: ${htmlFile}`);
19355
19528
  await this.config.gitService.checkout([
19356
19529
  htmlFile
19357
19530
  ]);
19358
19531
  }
19359
19532
  } catch (error) {
19360
- logger_logger.verbose(external_chalk_default().gray(` Keeping ${htmlFile} (couldn't verify if frontmatter-only change)`));
19533
+ this.logger.verbose(` Keeping ${htmlFile} (couldn't verify if frontmatter-only change)`);
19361
19534
  }
19362
19535
  }
19363
19536
  }
19364
19537
  class WatchSession_WatchSession extends Emitter {
19365
19538
  sessionId;
19539
+ logger;
19540
+ progress;
19366
19541
  repoPath;
19367
19542
  appId;
19368
19543
  anvilUrl;
@@ -19398,7 +19573,10 @@ print(json.dumps({"issues": issues}))
19398
19573
  LOCAL_CHANGE_POLL_MS = 2000;
19399
19574
  stagedOnly;
19400
19575
  constructor(repoPath, appId, options){
19401
- super();
19576
+ const logger = options.logger ?? reporting_silentLogger;
19577
+ super((event, error)=>logger.error(`Error in event handler for '${event}': ${error}`));
19578
+ this.logger = logger;
19579
+ this.progress = options.progress ?? silentProgress;
19402
19580
  this.sessionId = Math.random().toString(36).substring(2, 10);
19403
19581
  this.repoPath = external_path_default().resolve(repoPath);
19404
19582
  this.appId = appId;
@@ -19413,22 +19591,22 @@ print(json.dumps({"issues": issues}))
19413
19591
  this.envBranchChangeMode = options.envBranchChangeMode ?? "manual";
19414
19592
  this.dependencyWatchEnabled = options.dependencyWatch ?? true;
19415
19593
  this.editSession = "anvil-sync-" + Math.random().toString(36).substring(2, 15);
19416
- this.gitService = new git_GitService(this.repoPath);
19594
+ this.gitService = new git_GitService(this.repoPath, {
19595
+ logger: this.logger
19596
+ });
19417
19597
  this.gitService.on("fetch-retry", (data)=>this.emit("fetch-retry", data));
19418
19598
  this.gitService.on("fetch-retry-resolved", (data)=>this.emit("fetch-retry-resolved", data));
19419
19599
  this.editorYaml = new EditorYamlManager(this.repoPath);
19420
- logger_logger.debug(`[Session ${this.sessionId}]`, `Created for app ${appId} on branch ${options.currentBranch}`);
19600
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, `Created for app ${appId} on branch ${options.currentBranch}`));
19421
19601
  }
19422
19602
  getBranchName() {
19423
19603
  return this.currentBranch;
19424
19604
  }
19425
19605
  pauseForUserInput() {
19426
19606
  this.isPausedForUserInput = true;
19427
- logger_logger.pause();
19428
19607
  }
19429
19608
  resumeAfterUserInput() {
19430
19609
  this.isPausedForUserInput = false;
19431
- logger_logger.resume();
19432
19610
  }
19433
19611
  async initialize() {
19434
19612
  await this.editorYaml.load();
@@ -19437,13 +19615,14 @@ print(json.dumps({"issues": issues}))
19437
19615
  try {
19438
19616
  await this.connectWebSocket();
19439
19617
  } catch (error) {
19440
- logger_logger.warn(external_chalk_default().yellow(" WebSocket connection unavailable - changes from the Anvil Editor won't be detected"));
19441
- logger_logger.verbose(external_chalk_default().gray(" Local changes will still sync to Anvil, but editor changes won't appear locally"));
19442
- logger_logger.debug("WebSocket init error:", error.message);
19618
+ this.logger.warn(" WebSocket connection unavailable - changes from the Anvil Editor won't be detected");
19619
+ this.logger.verbose(" Local changes will still sync to Anvil, but editor changes won't appear locally");
19620
+ this.logger.debug((0, external_node_util_namespaceObject.format)("WebSocket init error:", error.message));
19443
19621
  }
19444
19622
  }
19445
19623
  initializeProcessors() {
19446
19624
  this.syncManager = new SyncManager({
19625
+ logger: this.logger,
19447
19626
  repoPath: this.repoPath,
19448
19627
  appId: this.appId,
19449
19628
  anvilUrl: this.anvilUrl,
@@ -19463,6 +19642,8 @@ print(json.dumps({"issues": issues}))
19463
19642
  }
19464
19643
  });
19465
19644
  this.saveProcessor = new SaveProcessor({
19645
+ logger: this.logger,
19646
+ progress: this.progress,
19466
19647
  repoPath: this.repoPath,
19467
19648
  appId: this.appId,
19468
19649
  anvilUrl: this.anvilUrl,
@@ -19508,6 +19689,7 @@ print(json.dumps({"issues": issues}))
19508
19689
  }
19509
19690
  async connectWebSocket() {
19510
19691
  this.wsClient = new WebSocketClient({
19692
+ logger: this.logger,
19511
19693
  appId: this.appId,
19512
19694
  anvilUrl: this.anvilUrl,
19513
19695
  authToken: this.authToken,
@@ -19526,23 +19708,23 @@ print(json.dumps({"issues": issues}))
19526
19708
  });
19527
19709
  this.wsClient.on("repo-update", async ({ appId, ref, commitHash, saveSeq })=>{
19528
19710
  if (appId !== this.appId) return void await this.handleDependencyRepoUpdate(appId, ref, commitHash);
19529
- if (saveSeq?.session === this.editSession) return void logger_logger.debug("Ignoring update from our own session");
19711
+ if (saveSeq?.session === this.editSession) return void this.logger.debug("Ignoring update from our own session");
19530
19712
  const branchName = ref.replace(/^refs\/heads\//, "");
19531
- if (branchName !== this.currentBranch) return void logger_logger.debug(`Ignoring update to different branch: ${branchName} (current: ${this.currentBranch})`);
19532
- logger_logger.warn(`Remote changes detected on branch ${this.currentBranch}`);
19713
+ if (branchName !== this.currentBranch) return void this.logger.debug(`Ignoring update to different branch: ${branchName} (current: ${this.currentBranch})`);
19714
+ this.logger.warn(`Remote changes detected on branch ${this.currentBranch}`);
19533
19715
  this.emit("remote-update", {
19534
19716
  branch: this.currentBranch,
19535
19717
  commitHash
19536
19718
  });
19537
- logger_logger.progress("remote-sync", "Syncing from Anvil");
19719
+ this.progress.start("remote-sync", "Syncing from Anvil");
19538
19720
  try {
19539
19721
  await this.syncRemoteChanges();
19540
19722
  const message = await this.getSuccessMessage();
19541
- logger_logger.progressEnd("remote-sync", message);
19723
+ this.progress.end("remote-sync", message);
19542
19724
  } catch (e) {
19543
- logger_logger.progressEnd("remote-sync", "Sync failed");
19725
+ this.progress.end("remote-sync", "Sync failed");
19544
19726
  this.emitRemoteSyncFailed(e, this.currentBranch, commitHash);
19545
- logger_logger.error(`Failed to sync remote changes: ${errors_getErrorMessage(e)}`);
19727
+ this.logger.error(`Failed to sync remote changes: ${errors_getErrorMessage(e)}`);
19546
19728
  }
19547
19729
  });
19548
19730
  await this.wsClient.connect();
@@ -19551,8 +19733,8 @@ print(json.dumps({"issues": issues}))
19551
19733
  if (!this.dependencyWatchEnabled) return;
19552
19734
  const branchName = ref.replace(/^refs\/heads\//, "");
19553
19735
  const subscription = this.wsClient?.getDependencySubscriptions().find((candidate)=>candidate.appId === appId && candidate.branch === branchName);
19554
- if (!subscription) return void logger_logger.debug(`Ignoring update for unwatched dependency app ${appId} on ${branchName}`);
19555
- logger_logger.verbose(external_chalk_default().cyan("Dependency update detected: ") + external_chalk_default().bold(subscription.packageName ?? appId) + external_chalk_default().gray(` (${branchName}, ${commitHash.substring(0, 8)})`));
19736
+ if (!subscription) return void this.logger.debug(`Ignoring update for unwatched dependency app ${appId} on ${branchName}`);
19737
+ this.logger.verbose(`Dependency update detected: ${subscription.packageName ?? appId} (${branchName}, ${commitHash.substring(0, 8)})`);
19556
19738
  await this.queueDependencyRefresh(`dependency ${appId} updated`);
19557
19739
  }
19558
19740
  async queueDependencyRefresh(reason) {
@@ -19573,19 +19755,21 @@ print(json.dumps({"issues": issues}))
19573
19755
  }
19574
19756
  async refreshDependencies(reason) {
19575
19757
  if (!this.dependencyWatchEnabled || this.isCleanedUp) return;
19576
- logger_logger.progress("dependency-refresh", "startup" === reason ? "Fetching dependencies" : "Refreshing dependencies");
19758
+ this.progress.start("dependency-refresh", "startup" === reason ? "Fetching dependencies" : "Refreshing dependencies");
19577
19759
  try {
19578
19760
  const previousSubscriptions = this.wsClient?.getDependencySubscriptions() ?? [];
19579
19761
  const { response, addedGitignoreEntry } = await refreshDependencyCache(this.repoPath, this.appId, this.anvilUrl, {
19762
+ logger: this.logger,
19763
+ username: this.username,
19580
19764
  includeDocs: true
19581
19765
  });
19582
- if (addedGitignoreEntry) logger_logger.info("Added /.anvil/ to .gitignore");
19766
+ if (addedGitignoreEntry) this.logger.info("Added /.anvil/ to .gitignore");
19583
19767
  const nextSubscriptions = await this.getDependencyWatchSubscriptions();
19584
19768
  this.reconcileDependencySubscriptions(previousSubscriptions, nextSubscriptions);
19585
- logger_logger.progressEnd("dependency-refresh", response.dependencies.length ? `Fetched ${response.dependencies.length} dependencies` : "Dependencies already up to date");
19769
+ this.progress.end("dependency-refresh", response.dependencies.length ? `Fetched ${response.dependencies.length} dependencies` : "Dependencies already up to date");
19586
19770
  } catch (error) {
19587
- logger_logger.progressEnd("dependency-refresh", "Failed");
19588
- logger_logger.warn(external_chalk_default().yellow(`Failed to refresh dependencies: ${errors_getErrorMessage(error)}`));
19771
+ this.progress.end("dependency-refresh", "Failed");
19772
+ this.logger.warn(`Failed to refresh dependencies: ${errors_getErrorMessage(error)}`);
19589
19773
  }
19590
19774
  }
19591
19775
  async getDependencyWatchSubscriptions() {
@@ -19642,7 +19826,7 @@ print(json.dumps({"issues": issues}))
19642
19826
  "-fd"
19643
19827
  ]);
19644
19828
  }
19645
- logger_logger.verbose(external_chalk_default().cyan(`Environment branch ${"snapshot" === source ? "snapshot" : "update"}: `) + external_chalk_default().bold(`${this.currentBranch} -> ${targetBranch}`));
19829
+ this.logger.verbose(`Environment branch ${"snapshot" === source ? "snapshot" : "update"}: ${this.currentBranch} -> ${targetBranch}`);
19646
19830
  this.authToken = await auth_getValidAuthToken(this.anvilUrl, this.username);
19647
19831
  this.wsClient?.updateAuthToken?.(this.authToken);
19648
19832
  const fetchUrl = anvil_api_getGitFetchUrl(this.appId, this.authToken, this.gitUrl);
@@ -19742,7 +19926,7 @@ print(json.dumps({"issues": issues}))
19742
19926
  }
19743
19927
  cleanup() {
19744
19928
  this.isCleanedUp = true;
19745
- logger_logger.debug(`[Session ${this.sessionId}]`, "Cleaning up...");
19929
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, "Cleaning up..."));
19746
19930
  this.saveProcessor?.cleanup();
19747
19931
  if (this.wsClient) {
19748
19932
  this.wsClient.close();
@@ -19756,12 +19940,13 @@ print(json.dumps({"issues": issues}))
19756
19940
  clearInterval(this.localChangePollTimer);
19757
19941
  this.localChangePollTimer = null;
19758
19942
  }
19759
- logger_logger.debug(`[Session ${this.sessionId}]`, "Cleanup complete");
19943
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, "Cleanup complete"));
19760
19944
  }
19761
19945
  async startWatching() {
19762
- logger_logger.debug(`[Session ${this.sessionId}]`, "Starting watchers...");
19946
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, "Starting watchers..."));
19763
19947
  const gitDir = await this.gitService.getGitDir();
19764
19948
  this.fileWatcher = new FileWatcher({
19949
+ logger: this.logger,
19765
19950
  repoPath: this.repoPath,
19766
19951
  gitDir,
19767
19952
  stagedOnly: this.stagedOnly,
@@ -19777,7 +19962,7 @@ print(json.dumps({"issues": issues}))
19777
19962
  try {
19778
19963
  await this.handleFileChange(event, filePath, relativePath);
19779
19964
  } catch (error) {
19780
- logger_logger.error(`Error handling file change for ${relativePath}: ${error.message}`);
19965
+ this.logger.error(`Error handling file change for ${relativePath}: ${error.message}`);
19781
19966
  }
19782
19967
  });
19783
19968
  await this.fileWatcher.start(this.currentBranch);
@@ -19786,9 +19971,9 @@ print(json.dumps({"issues": issues}))
19786
19971
  await new Promise(()=>{});
19787
19972
  }
19788
19973
  handleFileWatcherBranchChange(newBranch) {
19789
- if (this.isSwitchingForEnvironment && newBranch === this.environmentSwitchTargetBranch) return void logger_logger.debug(`Ignoring FileWatcher branch-change during environment switch: ${newBranch}`);
19974
+ if (this.isSwitchingForEnvironment && newBranch === this.environmentSwitchTargetBranch) return void this.logger.debug(`Ignoring FileWatcher branch-change during environment switch: ${newBranch}`);
19790
19975
  const oldBranch = this.currentBranch;
19791
- logger_logger.verbose(external_chalk_default().gray(" Pausing sync for 2 seconds to allow branch to settle..."));
19976
+ this.logger.verbose(" Pausing sync for 2 seconds to allow branch to settle...");
19792
19977
  this.currentBranch = newBranch;
19793
19978
  this.lastBranchChangeTime = Date.now();
19794
19979
  this.wsClient?.updateBranch(newBranch);
@@ -19814,7 +19999,7 @@ print(json.dumps({"issues": issues}))
19814
19999
  const status = await this.gitService.getStatus();
19815
20000
  this.lastLocalStatusFingerprint = this.getLocalStatusFingerprint(status);
19816
20001
  } catch (error) {
19817
- logger_logger.debug(`[Session ${this.sessionId}]`, `Failed to initialize local change fingerprint: ${error.message}`);
20002
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, `Failed to initialize local change fingerprint: ${error.message}`));
19818
20003
  }
19819
20004
  }
19820
20005
  startLocalChangeFallbackPolling() {
@@ -19836,12 +20021,12 @@ print(json.dumps({"issues": issues}))
19836
20021
  if (fingerprint !== this.lastLocalStatusFingerprint) {
19837
20022
  this.lastLocalStatusFingerprint = fingerprint;
19838
20023
  if (fingerprint) {
19839
- logger_logger.debug(`[Session ${this.sessionId}]`, "Detected local change via fallback status poll");
20024
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, "Detected local change via fallback status poll"));
19840
20025
  this.saveProcessor?.queueSave();
19841
20026
  }
19842
20027
  }
19843
20028
  } catch (error) {
19844
- logger_logger.debug(`[Session ${this.sessionId}]`, `Fallback status poll failed: ${error.message}`);
20029
+ this.logger.debug((0, external_node_util_namespaceObject.format)(`[Session ${this.sessionId}]`, `Fallback status poll failed: ${error.message}`));
19845
20030
  } finally{
19846
20031
  this.isPollingLocalChanges = false;
19847
20032
  }
@@ -19870,11 +20055,11 @@ print(json.dumps({"issues": issues}))
19870
20055
  }
19871
20056
  async handleFileChange(event, filePath, relativePath) {
19872
20057
  if (this.isCleanedUp || this.isPausedForUserInput) return;
19873
- logger_logger.verbose(external_chalk_default().blue("File changed: ") + external_chalk_default().bold(relativePath));
20058
+ this.logger.verbose("File changed: " + relativePath);
19874
20059
  if (!this.isSettlePeriodOver()) return;
19875
20060
  if (relativePath.startsWith("server_code/") || relativePath.startsWith("client_code/")) {
19876
20061
  const didRename = await this.handlePythonification(filePath, relativePath);
19877
- if (didRename) return void logger_logger.verbose(external_chalk_default().gray(" Pythonified - waiting for new watch event"));
20062
+ if (didRename) return void this.logger.verbose(" Pythonified - waiting for new watch event");
19878
20063
  }
19879
20064
  this.saveProcessor?.queueSave();
19880
20065
  }
@@ -19913,7 +20098,7 @@ print(json.dumps({"issues": issues}))
19913
20098
  const pythonified = pythonifyName(dirName);
19914
20099
  if (dirName !== pythonified) {
19915
20100
  const newPath = external_path_default().join(external_path_default().dirname(absolutePath), pythonified);
19916
- logger_logger.verbose(external_chalk_default().yellow(`Renaming directory: ${relativePath} → ${external_path_default().relative(this.repoPath, newPath)}`));
20101
+ this.logger.verbose(`Renaming directory: ${relativePath} → ${external_path_default().relative(this.repoPath, newPath)}`);
19917
20102
  await external_fs_.promises.rename(absolutePath, newPath);
19918
20103
  return true;
19919
20104
  }
@@ -19925,7 +20110,7 @@ print(json.dumps({"issues": issues}))
19925
20110
  const pythonified = pythonifyName(fileName);
19926
20111
  if (fileName !== pythonified) {
19927
20112
  const newPath = external_path_default().join(external_path_default().dirname(absolutePath), pythonified + ".py");
19928
- logger_logger.verbose(external_chalk_default().yellow(`Renaming file: ${relativePath} → ${external_path_default().relative(this.repoPath, newPath)}`));
20113
+ this.logger.verbose(`Renaming file: ${relativePath} → ${external_path_default().relative(this.repoPath, newPath)}`);
19929
20114
  await external_fs_.promises.rename(absolutePath, newPath);
19930
20115
  return true;
19931
20116
  }
@@ -19957,8 +20142,9 @@ print(json.dumps({"issues": issues}))
19957
20142
  };
19958
20143
  }
19959
20144
  async function validation_validateBranchSyncStatus(git, branchName, options) {
20145
+ const logger = options.logger ?? reporting_silentLogger;
19960
20146
  const { appId, anvilUrl, gitUrl = anvilUrl, username } = options;
19961
- logger_logger.verbose(external_chalk_default().blue("Checking branch sync status..."));
20147
+ logger.verbose("Checking branch sync status...");
19962
20148
  let authToken;
19963
20149
  try {
19964
20150
  authToken = await auth_getValidAuthToken(anvilUrl, username);
@@ -19969,14 +20155,16 @@ print(json.dumps({"issues": issues}))
19969
20155
  return await validateViaGitFetch(git, branchName, {
19970
20156
  appId,
19971
20157
  gitUrl,
19972
- authToken
20158
+ authToken,
20159
+ logger
19973
20160
  });
19974
20161
  } catch (e) {
19975
- logger_logger.verbose(external_chalk_default().yellow("Git fetch failed, trying server validation..."));
20162
+ logger.verbose("Git fetch failed, trying server validation...");
19976
20163
  return validateViaAnvilServer(git, branchName, options);
19977
20164
  }
19978
20165
  }
19979
20166
  async function validateViaGitFetch(git, branchName, options) {
20167
+ const logger = options.logger ?? reporting_silentLogger;
19980
20168
  const { appId, gitUrl, authToken } = options;
19981
20169
  const baseUrl = new URL(gitUrl);
19982
20170
  const encodedToken = encodeURIComponent(authToken);
@@ -19988,7 +20176,7 @@ print(json.dumps({"issues": issues}))
19988
20176
  const host = baseUrl.hostname + (baseUrl.port ? `:${baseUrl.port}` : "");
19989
20177
  const httpUrl = `${baseUrl.protocol}//git:${encodedToken}@${host}${gitPath}?${searchParams.toString()}`;
19990
20178
  try {
19991
- logger_logger.verbose(external_chalk_default().gray("Fetching latest from Anvil..."));
20179
+ logger.verbose("Fetching latest from Anvil...");
19992
20180
  const tempRef = `anvil-sync-temp-${Date.now()}`;
19993
20181
  await git.fetch([
19994
20182
  httpUrl,
@@ -20032,15 +20220,16 @@ print(json.dumps({"issues": issues}))
20032
20220
  upstreamRef: branchName,
20033
20221
  diverged: false
20034
20222
  };
20035
- logger_logger.verbose(external_chalk_default().green(`✔ Branch '${branchName}' is up-to-date with Anvil.`));
20223
+ logger.verbose(`✔ Branch '${branchName}' is up-to-date with Anvil.`);
20036
20224
  return null;
20037
20225
  } catch (e) {
20038
20226
  throw errors_createGitError.fetchFailed(e.message);
20039
20227
  }
20040
20228
  }
20041
20229
  async function validateViaAnvilServer(git, branchName, options) {
20230
+ const logger = options.logger ?? reporting_silentLogger;
20042
20231
  const { appId, anvilUrl, username } = options;
20043
- logger_logger.verbose(external_chalk_default().blue("Validating sync status with Anvil server..."));
20232
+ logger.verbose("Validating sync status with Anvil server...");
20044
20233
  const authToken = await auth_getValidAuthToken(anvilUrl, username);
20045
20234
  let commitId;
20046
20235
  try {
@@ -20066,8 +20255,8 @@ print(json.dumps({"issues": issues}))
20066
20255
  const data = await resp.json();
20067
20256
  const matchingApp = data.apps?.find((app)=>app.app_id === appId);
20068
20257
  if (matchingApp) {
20069
- logger_logger.success(`Anvil server recognizes commit ${commitId.substring(0, 8)} for app ${appId}`);
20070
- logger_logger.verbose(external_chalk_default().gray(" You appear to be in sync with Anvil server"));
20258
+ logger.info(`Anvil server recognizes commit ${commitId.substring(0, 8)} for app ${appId}`);
20259
+ logger.verbose(" You appear to be in sync with Anvil server");
20071
20260
  return null;
20072
20261
  }
20073
20262
  const allBranches = data.apps?.flatMap((app)=>app.branches || []) || [];
@@ -20154,6 +20343,18 @@ print(json.dumps({"issues": issues}))
20154
20343
  }
20155
20344
  throw new Error("Device login expired before it was approved.");
20156
20345
  }
20346
+ function quoteForPosixShell(value) {
20347
+ if ("" === value) return "''";
20348
+ return `'${value.replace(/'/g, "'\"'\"'")}'`;
20349
+ }
20350
+ function quoteForCmdShell(value) {
20351
+ const escaped = value.replace(/[%^&|<>()"!]/g, "^$&");
20352
+ return `"${escaped}"`;
20353
+ }
20354
+ function buildShellCommandLine(tokens) {
20355
+ if ("win32" === process.platform) return tokens.map(quoteForCmdShell).join(" ");
20356
+ return tokens.map(quoteForPosixShell).join(" ");
20357
+ }
20157
20358
  const CHECKOUT_ERROR_VALUE = "__ERROR__";
20158
20359
  function isAbortLikeError(error) {
20159
20360
  if (error instanceof Error && "AbortError" === error.name) return true;
@@ -20330,8 +20531,122 @@ print(json.dumps({"issues": issues}))
20330
20531
  }
20331
20532
  };
20332
20533
  }
20333
- require("inquirer");
20334
- require("ora");
20534
+ class CreateCheckoutError extends Error {
20535
+ created;
20536
+ constructor(message, created, options){
20537
+ super(message, options), this.created = created;
20538
+ this.name = "CreateCheckoutError";
20539
+ }
20540
+ }
20541
+ const create_defaultDeps = {
20542
+ getAccountsForUrl: auth_getAccountsForUrl,
20543
+ getValidAuthToken: auth_getValidAuthToken,
20544
+ createApp: createAnvilApp,
20545
+ checkout: executeCheckout
20546
+ };
20547
+ function validateCheckoutOptions(options) {
20548
+ if (false === options.checkout && (void 0 !== options.directory || void 0 !== options.gitUrl || options.open)) throw new Error("--no-checkout cannot be combined with a destination argument, --directory, --git-url, or --open.");
20549
+ }
20550
+ async function validateCreateInput(options) {
20551
+ validateCheckoutOptions(options);
20552
+ const name = options.name.trim();
20553
+ if (!name) throw new Error("App name is required.");
20554
+ const tags = void 0 === options.tags ? void 0 : [
20555
+ ...new Set(options.tags.map((tag)=>tag.trim().toLowerCase()))
20556
+ ];
20557
+ if (tags && (tags.length > 20 || tags.some((tag)=>tag.length > 50 || !/^[a-z0-9_-]+$/.test(tag)))) throw new Error("Use at most 20 unique tags, each 1–50 characters: letters, numbers, hyphens, or underscores.");
20558
+ if (false === options.checkout) return {
20559
+ name,
20560
+ tags,
20561
+ destinationPath: void 0
20562
+ };
20563
+ const directory = options.directory ?? sanitizeDirectoryName(name);
20564
+ if (!directory) throw new Error("App name cannot be used as a directory. Pass --directory <PATH>.");
20565
+ const destinationPath = external_path_default().resolve(directory);
20566
+ await validateCheckoutDestination(destinationPath);
20567
+ return {
20568
+ name,
20569
+ tags,
20570
+ destinationPath
20571
+ };
20572
+ }
20573
+ async function executeCreate(options, deps = create_defaultDeps) {
20574
+ const { name, tags, destinationPath } = await validateCreateInput(options);
20575
+ const anvilUrl = config_normalizeAnvilOrigin(options.anvilUrl ?? await resolveCheckoutUrlForApi() ?? "");
20576
+ const gitUrl = void 0 === options.gitUrl ? void 0 : config_normalizeAnvilOrigin(options.gitUrl);
20577
+ const accounts = options.user ? [] : await deps.getAccountsForUrl(anvilUrl);
20578
+ const username = options.user ?? accounts[0];
20579
+ if (!username) throw new Error(`Not logged in to ${anvilUrl}. Run 'anvil login ${anvilUrl}' and retry.`);
20580
+ if (!options.user && accounts.length > 1) throw new Error(`Multiple accounts found for ${anvilUrl}: ${accounts.join(", ")}. Use --user <USERNAME>.`);
20581
+ const authToken = await deps.getValidAuthToken(anvilUrl, username);
20582
+ const created = await deps.createApp({
20583
+ name,
20584
+ anvilUrl,
20585
+ authToken,
20586
+ ...tags ? {
20587
+ tags
20588
+ } : {}
20589
+ });
20590
+ if (void 0 === destinationPath) return {
20591
+ appId: created.id,
20592
+ appName: created.name,
20593
+ anvilUrl,
20594
+ username,
20595
+ tags: created.tags ?? tags ?? [],
20596
+ editorUrl: `${anvilUrl}/build/apps/${encodeURIComponent(created.id)}`
20597
+ };
20598
+ try {
20599
+ const checkout = await deps.checkout({
20600
+ input: created.id,
20601
+ directory: destinationPath,
20602
+ anvilUrl,
20603
+ ...gitUrl ? {
20604
+ gitUrl
20605
+ } : {},
20606
+ user: username
20607
+ });
20608
+ return {
20609
+ ...checkout,
20610
+ tags: created.tags ?? tags ?? []
20611
+ };
20612
+ } catch (error) {
20613
+ const details = {
20614
+ appId: created.id,
20615
+ appName: created.name,
20616
+ anvilUrl,
20617
+ gitUrl,
20618
+ destinationPath,
20619
+ username,
20620
+ tags: created.tags ?? tags ?? []
20621
+ };
20622
+ const retry = buildShellCommandLine([
20623
+ "anvil",
20624
+ "checkout",
20625
+ created.id,
20626
+ destinationPath,
20627
+ "--url",
20628
+ anvilUrl,
20629
+ "--user",
20630
+ username,
20631
+ ...gitUrl ? [
20632
+ "--git-url",
20633
+ gitUrl
20634
+ ] : []
20635
+ ]);
20636
+ const remainingFiles = await isDirectoryNonEmpty(destinationPath).catch(()=>true);
20637
+ const recovery = remainingFiles ? `Inspect the existing checkout at ${destinationPath} before retrying. For Git authentication problems, run ${buildShellCommandLine([
20638
+ "anvil",
20639
+ "git-auth",
20640
+ "doctor",
20641
+ "--repo",
20642
+ destinationPath
20643
+ ])}.` : `Retry checkout with: ${retry}`;
20644
+ const message = errors_getErrorMessage(error).replaceAll(authToken, "[REDACTED]").replaceAll(encodeURIComponent(authToken), "[REDACTED]");
20645
+ throw new CreateCheckoutError(`Created app ${created.id} at ${anvilUrl}, but checkout failed: ${message}. Do not rerun create. ${recovery}`, details, {
20646
+ cause: error
20647
+ });
20648
+ }
20649
+ }
20335
20650
  const defaultGitAuthDoctorDeps = {
20336
20651
  getAppAuthBinding: git_auth_getAppAuthBinding,
20337
20652
  getAccountsForUrl: auth_getAccountsForUrl,
@@ -20787,7 +21102,7 @@ print(json.dumps({"issues": issues}))
20787
21102
  const token = await getModelToken(options);
20788
21103
  process.stdout.write(`${token}\n`);
20789
21104
  }
20790
- async function watch_decideFallbackUrl(explicitUrl, availableUrls) {
21105
+ async function appDetection_decideFallbackUrl(explicitUrl, availableUrls) {
20791
21106
  if (explicitUrl) return {
20792
21107
  source: "explicit",
20793
21108
  url: config_normalizeAnvilUrl(explicitUrl)
@@ -20873,7 +21188,7 @@ print(json.dumps({"issues": issues}))
20873
21188
  async function resolveCheckoutUrlForApi(explicitUrl, parsedUrl) {
20874
21189
  if (explicitUrl) return config_normalizeAnvilUrl(explicitUrl);
20875
21190
  if (parsedUrl) return config_normalizeAnvilUrl(parsedUrl);
20876
- const decision = await watch_decideFallbackUrl(void 0);
21191
+ const decision = await appDetection_decideFallbackUrl(void 0);
20877
21192
  if ("available-multiple" === decision.source) throw new Error(`Multiple logged-in Anvil URLs found: ${decision.urls.join(", ")}. Use --url <ANVIL_URL> to choose one.`);
20878
21193
  return decision.url;
20879
21194
  }
@@ -20933,7 +21248,7 @@ print(json.dumps({"issues": issues}))
20933
21248
  logger_logger.verbose(external_chalk_default().cyan("Resolved app ID: ") + external_chalk_default().bold(parsed.appId));
20934
21249
  const anvilUrl = await resolveCheckoutUrlForApi(options.anvilUrl, parsed.detectedUrl);
20935
21250
  if (!anvilUrl) throw new Error("Anvil URL is required. Use --url <ANVIL_URL> or pass an input URL containing the host.");
20936
- const gitUrl = options.gitUrl ?? anvilUrl;
21251
+ const gitUrl = void 0 === options.gitUrl ? anvilUrl : config_normalizeAnvilOrigin(options.gitUrl);
20937
21252
  const resolvedUsername = await resolveCheckoutUsernameForApi(anvilUrl, options.user);
20938
21253
  if (resolvedUsername) logger_logger.verbose(external_chalk_default().cyan("Using account: ") + external_chalk_default().bold(resolvedUsername));
20939
21254
  else logger_logger.verbose(external_chalk_default().cyan("No account preselected; resolving after auth token lookup."));
@@ -21025,6 +21340,8 @@ print(json.dumps({"issues": issues}))
21025
21340
  "HEAD"
21026
21341
  ])).trim();
21027
21342
  const session = new WatchSession_WatchSession(repoPath, appId, {
21343
+ logger: options.logger,
21344
+ progress: options.progress,
21028
21345
  anvilUrl,
21029
21346
  gitUrl,
21030
21347
  authToken,
@@ -21045,6 +21362,7 @@ print(json.dumps({"issues": issues}))
21045
21362
  }
21046
21363
  }
21047
21364
  async function src_api_watch(repoPath, appId, options = {}) {
21365
+ const logger = options.logger ?? reporting_silentLogger;
21048
21366
  repoPath = external_path_default().resolve(repoPath);
21049
21367
  auth_setRepoContext(repoPath);
21050
21368
  const anvilUrl = options.anvilUrl ?? await auth_resolveAuthAnvilUrl();
@@ -21106,13 +21424,14 @@ print(json.dumps({"issues": issues}))
21106
21424
  "HEAD"
21107
21425
  ])).trim();
21108
21426
  } else throw errors_createGitError.commandFailed("revparse", `Environment ${environment.envPid} is on branch '${environmentBranch}', but the local checkout is on '${currentBranch}'.`);
21109
- logger_logger.verbose(external_chalk_default().cyan("Current branch: ") + external_chalk_default().bold(currentBranch));
21110
- logger_logger.verbose(external_chalk_default().cyan("Current commit ID: ") + external_chalk_default().gray(commitId));
21427
+ logger.verbose("Current branch: " + currentBranch);
21428
+ logger.verbose("Current commit ID: " + commitId);
21111
21429
  const syncStatus = await validation_validateBranchSyncStatus(git, currentBranch, {
21112
21430
  appId,
21113
21431
  anvilUrl,
21114
21432
  gitUrl,
21115
- username
21433
+ username,
21434
+ logger
21116
21435
  });
21117
21436
  let hasUncommittedChanges = false;
21118
21437
  try {
@@ -21121,8 +21440,10 @@ print(json.dumps({"issues": issues}))
21121
21440
  } catch (e) {
21122
21441
  throw errors_createGitError.commandFailed("status", e.message);
21123
21442
  }
21124
- logger_logger.verbose(external_chalk_default().blue("Has uncommitted changes: ") + external_chalk_default().bold(hasUncommittedChanges));
21443
+ logger.verbose("Has uncommitted changes: " + hasUncommittedChanges);
21125
21444
  const session = new WatchSession_WatchSession(repoPath, appId, {
21445
+ logger: options.logger,
21446
+ progress: options.progress,
21126
21447
  anvilUrl,
21127
21448
  gitUrl,
21128
21449
  authToken,
@@ -21135,22 +21456,22 @@ print(json.dumps({"issues": issues}))
21135
21456
  dependencyWatch: options.dependencyWatch ?? true
21136
21457
  });
21137
21458
  session.on("branch-changed", (data)=>{
21138
- logger_logger.debug("Event: branch-changed", data);
21459
+ logger.debug((0, external_node_util_namespaceObject.format)("Event: branch-changed", data));
21139
21460
  });
21140
21461
  session.on("sync-conflict", (data)=>{
21141
- logger_logger.debug("Event: sync-conflict", data);
21462
+ logger.debug((0, external_node_util_namespaceObject.format)("Event: sync-conflict", data));
21142
21463
  });
21143
21464
  session.on("remote-update", (data)=>{
21144
- logger_logger.debug("Event: remote-update", data);
21465
+ logger.debug((0, external_node_util_namespaceObject.format)("Event: remote-update", data));
21145
21466
  });
21146
21467
  session.on("validation-failed", (data)=>{
21147
- logger_logger.debug("Event: validation-failed", data);
21468
+ logger.debug((0, external_node_util_namespaceObject.format)("Event: validation-failed", data));
21148
21469
  });
21149
21470
  session.on("save-complete", (data)=>{
21150
- logger_logger.debug("Event: save-complete", data);
21471
+ logger.debug((0, external_node_util_namespaceObject.format)("Event: save-complete", data));
21151
21472
  });
21152
21473
  session.on("save-started", (data)=>{
21153
- logger_logger.debug("Event: save-started", data);
21474
+ logger.debug((0, external_node_util_namespaceObject.format)("Event: save-started", data));
21154
21475
  });
21155
21476
  try {
21156
21477
  await session.initialize();
@@ -21173,6 +21494,8 @@ exports.CheckoutCloneOptions = __webpack_exports__.CheckoutCloneOptions;
21173
21494
  exports.CheckoutExecutionDeps = __webpack_exports__.CheckoutExecutionDeps;
21174
21495
  exports.CheckoutOptions = __webpack_exports__.CheckoutOptions;
21175
21496
  exports.CheckoutResult = __webpack_exports__.CheckoutResult;
21497
+ exports.CreateCheckoutError = __webpack_exports__.CreateCheckoutError;
21498
+ exports.CreatedAnvilApp = __webpack_exports__.CreatedAnvilApp;
21176
21499
  exports.DeviceAuthorizationResponse = __webpack_exports__.DeviceAuthorizationResponse;
21177
21500
  exports.FormTemplateValidationResult = __webpack_exports__.FormTemplateValidationResult;
21178
21501
  exports.GetValidAuthTokenOptions = __webpack_exports__.GetValidAuthTokenOptions;
@@ -21196,6 +21519,7 @@ exports.branchFromEnvironmentVersion = __webpack_exports__.branchFromEnvironment
21196
21519
  exports.buildGitAuthDoctorReport = __webpack_exports__.buildGitAuthDoctorReport;
21197
21520
  exports.checkUncommittedChanges = __webpack_exports__.checkUncommittedChanges;
21198
21521
  exports.clearInMemoryTokens = __webpack_exports__.clearInMemoryTokens;
21522
+ exports.createAnvilApp = __webpack_exports__.createAnvilApp;
21199
21523
  exports.createCheckoutPickerSource = __webpack_exports__.createCheckoutPickerSource;
21200
21524
  exports.createWatchDiagnostic = __webpack_exports__.createWatchDiagnostic;
21201
21525
  exports.createWatchDiagnosticFromMessage = __webpack_exports__.createWatchDiagnosticFromMessage;
@@ -21203,6 +21527,7 @@ exports.deleteConfig = __webpack_exports__.deleteConfig;
21203
21527
  exports.detectAppIdsByCommitLookup = __webpack_exports__.detectAppIdsByCommitLookup;
21204
21528
  exports.detectAppIdsFromAllRemotes = __webpack_exports__.detectAppIdsFromAllRemotes;
21205
21529
  exports.executeCheckout = __webpack_exports__.executeCheckout;
21530
+ exports.executeCreate = __webpack_exports__.executeCreate;
21206
21531
  exports.executeGitCredentialOperation = __webpack_exports__.executeGitCredentialOperation;
21207
21532
  exports.executeModelTokenOperation = __webpack_exports__.executeModelTokenOperation;
21208
21533
  exports.filterCandidates = __webpack_exports__.filterCandidates;
@@ -21276,6 +21601,8 @@ for(var __rspack_i in __webpack_exports__)if (-1 === [
21276
21601
  "CheckoutExecutionDeps",
21277
21602
  "CheckoutOptions",
21278
21603
  "CheckoutResult",
21604
+ "CreateCheckoutError",
21605
+ "CreatedAnvilApp",
21279
21606
  "DeviceAuthorizationResponse",
21280
21607
  "FormTemplateValidationResult",
21281
21608
  "GetValidAuthTokenOptions",
@@ -21299,6 +21626,7 @@ for(var __rspack_i in __webpack_exports__)if (-1 === [
21299
21626
  "buildGitAuthDoctorReport",
21300
21627
  "checkUncommittedChanges",
21301
21628
  "clearInMemoryTokens",
21629
+ "createAnvilApp",
21302
21630
  "createCheckoutPickerSource",
21303
21631
  "createWatchDiagnostic",
21304
21632
  "createWatchDiagnosticFromMessage",
@@ -21306,6 +21634,7 @@ for(var __rspack_i in __webpack_exports__)if (-1 === [
21306
21634
  "detectAppIdsByCommitLookup",
21307
21635
  "detectAppIdsFromAllRemotes",
21308
21636
  "executeCheckout",
21637
+ "executeCreate",
21309
21638
  "executeGitCredentialOperation",
21310
21639
  "executeModelTokenOperation",
21311
21640
  "filterCandidates",