@camunda8/cli 4.7.0-alpha.23 → 4.7.0-alpha.25

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.
@@ -0,0 +1,2604 @@
1
+ // default-plugins/mcp/c8ctl-plugin.ts
2
+ import { existsSync as existsSync4, realpathSync as realpathSync3 } from "node:fs";
3
+ import { resolve as resolve3 } from "node:path";
4
+
5
+ // src/core/config.ts
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import {
8
+ closeSync,
9
+ constants,
10
+ existsSync,
11
+ fchmodSync,
12
+ fstatSync,
13
+ linkSync,
14
+ lstatSync,
15
+ mkdirSync,
16
+ openSync,
17
+ readFileSync as readFileSync2,
18
+ renameSync,
19
+ rmSync,
20
+ statSync,
21
+ writeFileSync
22
+ } from "node:fs";
23
+ import { homedir, platform } from "node:os";
24
+ import { join as join2 } from "node:path";
25
+
26
+ // src/core/env-address.ts
27
+ function resolveEnvBaseUrl(vars = process.env) {
28
+ return vars.CAMUNDA_BASE_URL?.trim() || vars.CAMUNDA_REST_ADDRESS?.trim() || void 0;
29
+ }
30
+
31
+ // src/core/runtime.ts
32
+ import { readFileSync } from "node:fs";
33
+ import { dirname, join } from "node:path";
34
+ import { fileURLToPath } from "node:url";
35
+ var __filename = fileURLToPath(import.meta.url);
36
+ var __dirname = dirname(__filename);
37
+ var UNVERSIONED_DEV_BUILD = "0.0.0-semantically-released";
38
+ function getVersion() {
39
+ try {
40
+ const packageJsonPath = join(__dirname, "..", "..", "package.json");
41
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
42
+ return packageJson.version || UNVERSIONED_DEV_BUILD;
43
+ } catch {
44
+ return UNVERSIONED_DEV_BUILD;
45
+ }
46
+ }
47
+ var C8ctl = class {
48
+ _activeProfile;
49
+ _activeTenant;
50
+ _outputMode = "text";
51
+ _fields;
52
+ _dryRun;
53
+ _verbose;
54
+ _quiet;
55
+ _resolvedBaseUrl;
56
+ _deps;
57
+ env = {
58
+ version: getVersion(),
59
+ nodeVersion: process.version,
60
+ platform: process.platform,
61
+ arch: process.arch,
62
+ cwd: process.cwd(),
63
+ rootDir: join(__dirname, "..", "..")
64
+ };
65
+ /**
66
+ * Inject dependencies that cannot be imported at module level
67
+ * due to circular imports. Must be called once during startup,
68
+ * before any plugin or command accesses createClient/resolveTenantId/getLogger.
69
+ */
70
+ init(deps) {
71
+ if (this._deps) {
72
+ throw new Error("c8ctl.init() must only be called once");
73
+ }
74
+ this._deps = deps;
75
+ }
76
+ createClient(profileFlag, additionalSdkConfig) {
77
+ if (!this._deps) {
78
+ throw new Error("c8ctl.init() must be called before createClient()");
79
+ }
80
+ return this._deps.createClient(profileFlag, additionalSdkConfig);
81
+ }
82
+ resolveTenantId(profileFlag) {
83
+ if (!this._deps) {
84
+ throw new Error("c8ctl.init() must be called before resolveTenantId()");
85
+ }
86
+ return this._deps.resolveTenantId(profileFlag);
87
+ }
88
+ getLogger(mode) {
89
+ if (!this._deps) {
90
+ throw new Error("c8ctl.init() must be called before getLogger()");
91
+ }
92
+ return this._deps.getLogger(mode);
93
+ }
94
+ getUserDataDir() {
95
+ if (!this._deps) {
96
+ throw new Error("c8ctl.init() must be called before getUserDataDir()");
97
+ }
98
+ return this._deps.getUserDataDir();
99
+ }
100
+ getModelerDataDir() {
101
+ if (!this._deps) {
102
+ throw new Error("c8ctl.init() must be called before getModelerDataDir()");
103
+ }
104
+ return this._deps.getModelerDataDir();
105
+ }
106
+ npm(options) {
107
+ if (!this._deps) {
108
+ throw new Error("c8ctl.init() must be called before npm()");
109
+ }
110
+ return options.stdout === true ? this._deps.npm(options) : this._deps.npm(options);
111
+ }
112
+ // Expose env properties directly for plugin compatibility
113
+ get version() {
114
+ return this.env.version;
115
+ }
116
+ get nodeVersion() {
117
+ return this.env.nodeVersion;
118
+ }
119
+ get platform() {
120
+ return this.env.platform;
121
+ }
122
+ get arch() {
123
+ return this.env.arch;
124
+ }
125
+ get cwd() {
126
+ return this.env.cwd;
127
+ }
128
+ get activeProfile() {
129
+ return this._activeProfile;
130
+ }
131
+ set activeProfile(value) {
132
+ this._activeProfile = value;
133
+ }
134
+ get activeTenant() {
135
+ return this._activeTenant;
136
+ }
137
+ set activeTenant(value) {
138
+ this._activeTenant = value;
139
+ }
140
+ get outputMode() {
141
+ return this._outputMode;
142
+ }
143
+ set outputMode(value) {
144
+ this._outputMode = value;
145
+ }
146
+ get fields() {
147
+ return this._fields;
148
+ }
149
+ set fields(value) {
150
+ this._fields = value;
151
+ }
152
+ get dryRun() {
153
+ return this._dryRun;
154
+ }
155
+ set dryRun(value) {
156
+ this._dryRun = value;
157
+ }
158
+ get verbose() {
159
+ return this._verbose;
160
+ }
161
+ set verbose(value) {
162
+ this._verbose = value;
163
+ }
164
+ get quiet() {
165
+ return this._quiet;
166
+ }
167
+ set quiet(value) {
168
+ this._quiet = value;
169
+ }
170
+ get resolvedBaseUrl() {
171
+ return this._resolvedBaseUrl;
172
+ }
173
+ set resolvedBaseUrl(value) {
174
+ this._resolvedBaseUrl = value;
175
+ }
176
+ };
177
+ var c8ctl = new C8ctl();
178
+
179
+ // src/core/logger.ts
180
+ function isRecord(value) {
181
+ return value != null && typeof value === "object" && !Array.isArray(value);
182
+ }
183
+
184
+ // src/core/config.ts
185
+ var TARGET_TYPES = {
186
+ CAMUNDA_CLOUD: "camundaCloud",
187
+ SELF_HOSTED: "selfHosted"
188
+ };
189
+ var AUTH_TYPES = {
190
+ NONE: "none",
191
+ BASIC: "basic",
192
+ OAUTH: "oauth"
193
+ };
194
+ var VALIDATION_PATTERNS = {
195
+ URL: /^https?:\/\//,
196
+ CAMUNDA_CLOUD_REST_URL: /^https:\/\/[a-z]+-\d+\.zeebe\.camunda\.io(:443|)\/[a-z\d-]+\/?$/
197
+ };
198
+ var CAMUNDA_CLOUD_URL_PATTERN = VALIDATION_PATTERNS.CAMUNDA_CLOUD_REST_URL;
199
+ function getUserDataDir() {
200
+ if (process.env.C8CTL_DATA_DIR) {
201
+ return process.env.C8CTL_DATA_DIR;
202
+ }
203
+ const plat = platform();
204
+ const home = homedir();
205
+ switch (plat) {
206
+ case "win32":
207
+ return join2(
208
+ process.env.APPDATA || join2(home, "AppData", "Roaming"),
209
+ "c8ctl"
210
+ );
211
+ case "darwin":
212
+ return join2(home, "Library", "Application Support", "c8ctl");
213
+ default:
214
+ return join2(
215
+ process.env.XDG_CONFIG_HOME || join2(home, ".config"),
216
+ "c8ctl"
217
+ );
218
+ }
219
+ }
220
+ function getModelerDataDir() {
221
+ if (process.env.C8CTL_MODELER_DIR) {
222
+ return process.env.C8CTL_MODELER_DIR;
223
+ }
224
+ const plat = platform();
225
+ const home = homedir();
226
+ switch (plat) {
227
+ case "win32":
228
+ return join2(
229
+ process.env.APPDATA || join2(home, "AppData", "Roaming"),
230
+ "camunda-modeler"
231
+ );
232
+ case "darwin":
233
+ return join2(home, "Library", "Application Support", "camunda-modeler");
234
+ default:
235
+ return join2(
236
+ process.env.XDG_CONFIG_HOME || join2(home, ".config"),
237
+ "camunda-modeler"
238
+ );
239
+ }
240
+ }
241
+ function ensureUserDataDir() {
242
+ const dir = getUserDataDir();
243
+ if (!existsSync(dir)) {
244
+ mkdirSync(dir, { recursive: true });
245
+ }
246
+ return dir;
247
+ }
248
+ function getProfilesPath() {
249
+ return join2(ensureUserDataDir(), "profiles.json");
250
+ }
251
+ function getModelerSettingsPath() {
252
+ return join2(getModelerDataDir(), "settings.json");
253
+ }
254
+ function fileMode(path) {
255
+ try {
256
+ return statSync(path).mode & 511;
257
+ } catch {
258
+ return void 0;
259
+ }
260
+ }
261
+ var isWindows = platform() === "win32";
262
+ function pinFdMode(fd, mode) {
263
+ if (!isWindows) fchmodSync(fd, mode);
264
+ }
265
+ var OPTIONAL_STRING_PROFILE_FIELDS = [
266
+ "clientId",
267
+ "clientSecret",
268
+ "audience",
269
+ "oAuthUrl",
270
+ "scope",
271
+ "username",
272
+ "password",
273
+ "defaultTenantId"
274
+ ];
275
+ function isStringRecord(value) {
276
+ return isRecord(value) && Object.values(value).every((v) => typeof v === "string");
277
+ }
278
+ function isValidProfile(value) {
279
+ if (!isRecord(value) || typeof value.name !== "string" || typeof value.baseUrl !== "string") {
280
+ return false;
281
+ }
282
+ for (const field of OPTIONAL_STRING_PROFILE_FIELDS) {
283
+ if (value[field] !== void 0 && typeof value[field] !== "string") {
284
+ return false;
285
+ }
286
+ }
287
+ if (value.exactBaseUrl !== void 0 && typeof value.exactBaseUrl !== "boolean") {
288
+ return false;
289
+ }
290
+ if (value.headers !== void 0 && !isStringRecord(value.headers)) {
291
+ return false;
292
+ }
293
+ if (value.authStrategy !== void 0 && !CAMUNDA_AUTH_STRATEGIES.some((s) => s === value.authStrategy)) {
294
+ return false;
295
+ }
296
+ return true;
297
+ }
298
+ function extractValidProfiles(parsed) {
299
+ if (!isRecord(parsed)) return null;
300
+ const rawProfiles = parsed.profiles;
301
+ if (!Array.isArray(rawProfiles)) return null;
302
+ if (!rawProfiles.every(isValidProfile)) return null;
303
+ return rawProfiles;
304
+ }
305
+ function backupCorruptProfiles(profilesPath, data) {
306
+ const mode = fileMode(profilesPath) ?? 384;
307
+ const hash = createHash("sha256").update(data).digest("hex");
308
+ const backup = `${profilesPath}.corrupt-${hash}`;
309
+ const tmp = `${profilesPath}.corrupt-tmp-${randomUUID()}`;
310
+ let stagedFd;
311
+ try {
312
+ stagedFd = openSync(
313
+ tmp,
314
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
315
+ mode
316
+ );
317
+ writeFileSync(stagedFd, data);
318
+ pinFdMode(stagedFd, mode);
319
+ } catch {
320
+ if (stagedFd !== void 0) closeQuietly(stagedFd);
321
+ removeQuietly(tmp);
322
+ return { backup, backedUp: false };
323
+ }
324
+ closeQuietly(stagedFd);
325
+ try {
326
+ for (const name of [backup, `${backup}.dup`]) {
327
+ if (publishBackup(tmp, name, data, mode)) {
328
+ return { backup: name, backedUp: true };
329
+ }
330
+ }
331
+ return { backup, backedUp: false };
332
+ } finally {
333
+ removeQuietly(tmp);
334
+ }
335
+ }
336
+ function publishBackup(tmp, name, data, mode) {
337
+ try {
338
+ linkSync(tmp, name);
339
+ return true;
340
+ } catch (err) {
341
+ if (isRecord(err) && err.code === "EEXIST") {
342
+ return reuseCanonicalBackup(name, data, mode);
343
+ }
344
+ return false;
345
+ }
346
+ }
347
+ function removeQuietly(path) {
348
+ try {
349
+ rmSync(path, { force: true });
350
+ } catch {
351
+ }
352
+ }
353
+ function pathEntryExists(path) {
354
+ try {
355
+ lstatSync(path);
356
+ return true;
357
+ } catch (err) {
358
+ if (isRecord(err) && err.code === "ENOENT") return false;
359
+ return true;
360
+ }
361
+ }
362
+ function reuseCanonicalBackup(backup, data, mode) {
363
+ let fd;
364
+ try {
365
+ fd = openSync(
366
+ backup,
367
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
368
+ );
369
+ const st = fstatSync(fd);
370
+ if (!st.isFile()) return false;
371
+ if (st.nlink !== 1) return false;
372
+ if (!readFileSync2(fd).equals(data)) return false;
373
+ if ((st.mode & 511) !== mode) {
374
+ try {
375
+ pinFdMode(fd, mode);
376
+ } catch {
377
+ return false;
378
+ }
379
+ }
380
+ return true;
381
+ } catch {
382
+ return false;
383
+ } finally {
384
+ if (fd !== void 0) closeQuietly(fd);
385
+ }
386
+ }
387
+ function closeQuietly(fd) {
388
+ try {
389
+ closeSync(fd);
390
+ } catch {
391
+ }
392
+ }
393
+ function throwCorruptProfiles(profilesPath, data, detail) {
394
+ const { backup, backedUp } = backupCorruptProfiles(profilesPath, data);
395
+ const backupNote = backedUp ? `Its contents were backed up to ${backup}. ` : `A backup could not be written, but the original file is still on disk untouched. `;
396
+ throw new Error(
397
+ `profiles.json at ${profilesPath} is corrupt (${detail}). ${backupNote}Refusing to overwrite it to avoid destroying your saved profiles \u2014 fix or remove the file, then re-run.`
398
+ );
399
+ }
400
+ function loadProfiles() {
401
+ const profilesPath = getProfilesPath();
402
+ let data;
403
+ let fd;
404
+ try {
405
+ fd = openSync(profilesPath, constants.O_RDONLY | constants.O_NONBLOCK);
406
+ const st = fstatSync(fd);
407
+ if (!st.isFile()) {
408
+ throw new Error(
409
+ `profiles file at ${profilesPath} is not a regular file (e.g. a FIFO, device, or directory). Refusing to treat it as empty (that would overwrite your saved profiles) \u2014 fix or remove it, then re-run.`
410
+ );
411
+ }
412
+ data = readFileSync2(fd);
413
+ } catch (err) {
414
+ if (isRecord(err) && err.code === "ENOENT") {
415
+ if (pathEntryExists(profilesPath)) {
416
+ throw new Error(
417
+ `profiles file at ${profilesPath} exists but its contents could not be read (e.g. a dangling symlink). Refusing to treat it as empty (that would overwrite your saved profiles) \u2014 fix or remove it, then re-run.`
418
+ );
419
+ }
420
+ return [];
421
+ }
422
+ if (!(isRecord(err) && typeof err.code === "string")) {
423
+ throw err;
424
+ }
425
+ throw new Error(
426
+ `Failed to read profiles at ${profilesPath}: ${err instanceof Error ? err.message : String(err)}. Refusing to treat an unreadable profiles file as empty (that would overwrite your saved profiles).`
427
+ );
428
+ } finally {
429
+ if (fd !== void 0) closeQuietly(fd);
430
+ }
431
+ try {
432
+ let text;
433
+ try {
434
+ text = new TextDecoder("utf-8", { fatal: true }).decode(data);
435
+ } catch {
436
+ throwCorruptProfiles(
437
+ profilesPath,
438
+ data,
439
+ "contains invalid UTF-8 byte sequences"
440
+ );
441
+ }
442
+ const parsed = JSON.parse(text);
443
+ const profiles = extractValidProfiles(parsed);
444
+ if (profiles === null) {
445
+ throwCorruptProfiles(
446
+ profilesPath,
447
+ data,
448
+ 'does not contain a valid "profiles" array'
449
+ );
450
+ }
451
+ return profiles;
452
+ } catch (err) {
453
+ if (err instanceof SyntaxError) {
454
+ throwCorruptProfiles(
455
+ profilesPath,
456
+ data,
457
+ `could not be parsed: ${err.message}`
458
+ );
459
+ }
460
+ throw err;
461
+ }
462
+ }
463
+ function getProfile(name) {
464
+ const profiles = loadProfiles();
465
+ return profiles.find((p) => p.name === name);
466
+ }
467
+ var MODELER_PREFIX = "modeler:";
468
+ function loadModelerConnections() {
469
+ const settingsPath = getModelerSettingsPath();
470
+ if (!existsSync(settingsPath)) {
471
+ return [];
472
+ }
473
+ try {
474
+ const data = readFileSync2(settingsPath, "utf-8");
475
+ const settings = JSON.parse(data);
476
+ const connections = settings["connectionManagerPlugin.c8connections"];
477
+ if (!connections || !Array.isArray(connections)) {
478
+ return [];
479
+ }
480
+ return connections.filter((c) => c?.id);
481
+ } catch {
482
+ return [];
483
+ }
484
+ }
485
+ function getProfileOrModeler(name) {
486
+ const c8ctlProfile = getProfile(name);
487
+ if (c8ctlProfile) {
488
+ return c8ctlProfile;
489
+ }
490
+ const modelerName = name.startsWith(MODELER_PREFIX) ? name.slice(MODELER_PREFIX.length) : name;
491
+ const modelerConnections = loadModelerConnections();
492
+ const modelerConnection = modelerConnections.find(
493
+ (c) => c.name === modelerName || c.id === modelerName
494
+ );
495
+ if (modelerConnection) {
496
+ const profile = connectionToProfile(modelerConnection);
497
+ return {
498
+ ...profile,
499
+ name: `${MODELER_PREFIX}${profile.name}`
500
+ };
501
+ }
502
+ return void 0;
503
+ }
504
+ function connectionToClusterConfig(conn) {
505
+ if (conn.targetType === TARGET_TYPES.CAMUNDA_CLOUD) {
506
+ const audience = conn.audience?.trim();
507
+ const oAuthUrl = conn.oauthURL?.trim();
508
+ const scope = conn.scope?.trim();
509
+ return {
510
+ baseUrl: conn.camundaCloudClusterUrl || "",
511
+ clientId: conn.camundaCloudClientId,
512
+ clientSecret: conn.camundaCloudClientSecret,
513
+ audience: audience || void 0,
514
+ oAuthUrl: oAuthUrl || "https://login.cloud.camunda.io/oauth/token",
515
+ scope: scope || void 0
516
+ };
517
+ }
518
+ const config = {
519
+ baseUrl: conn.contactPoint || "http://localhost:8080/v2"
520
+ };
521
+ if (conn.authType === AUTH_TYPES.BASIC) {
522
+ config.username = conn.basicAuthUsername;
523
+ config.password = conn.basicAuthPassword;
524
+ } else if (conn.authType === AUTH_TYPES.OAUTH) {
525
+ config.clientId = conn.clientId;
526
+ config.clientSecret = conn.clientSecret;
527
+ config.oAuthUrl = conn.oauthURL;
528
+ config.audience = conn.audience;
529
+ config.scope = conn.scope;
530
+ }
531
+ return config;
532
+ }
533
+ function connectionToProfile(conn) {
534
+ const config = connectionToClusterConfig(conn);
535
+ return {
536
+ name: conn.name || conn.id,
537
+ baseUrl: config.baseUrl,
538
+ clientId: config.clientId,
539
+ clientSecret: config.clientSecret,
540
+ audience: config.audience,
541
+ oAuthUrl: config.oAuthUrl,
542
+ scope: config.scope,
543
+ username: config.username,
544
+ password: config.password,
545
+ defaultTenantId: conn.tenantId
546
+ };
547
+ }
548
+ var DEFAULT_PROFILE = "local";
549
+ var CAMUNDA_AUTH_STRATEGIES = ["NONE", "BASIC", "OAUTH"];
550
+
551
+ // src/core/errors.ts
552
+ var SilentError = class extends Error {
553
+ constructor(message) {
554
+ super(message);
555
+ this.name = "SilentError";
556
+ }
557
+ };
558
+ function normalizeToError(error, fallbackMessage = "Operation failed") {
559
+ if (error instanceof Error) {
560
+ return error;
561
+ }
562
+ const raw = isRecord(error) ? error : {};
563
+ const title = typeof raw.title === "string" ? raw.title : void 0;
564
+ const detail = typeof raw.detail === "string" ? raw.detail : void 0;
565
+ const status = typeof raw.status === "number" ? raw.status : void 0;
566
+ const head = [title ?? fallbackMessage, detail].filter((p) => Boolean(p)).join(": ");
567
+ const message = status !== void 0 ? `${head} (status ${status})` : head;
568
+ return new Error(message, { cause: error });
569
+ }
570
+ function renderCommandFailure(logger, message, error, { verbose = false } = {}) {
571
+ const normalizedError = normalizeToError(error, message);
572
+ if (verbose) {
573
+ throw normalizedError;
574
+ }
575
+ if (error instanceof SilentError) {
576
+ return;
577
+ }
578
+ if (normalizedError.message === message) {
579
+ logger.error(message);
580
+ } else {
581
+ logger.error(message, normalizedError);
582
+ }
583
+ logger.info("For more details on the error, run with the --verbose flag", {
584
+ essential: true
585
+ });
586
+ }
587
+
588
+ // src/core/update-check.ts
589
+ var CHECK_INTERVAL_MS = 60 * 60 * 1e3;
590
+
591
+ // src/utils/command-local/mcp-install-helpers.ts
592
+ import { randomUUID as randomUUID2 } from "node:crypto";
593
+ import {
594
+ closeSync as closeSync2,
595
+ existsSync as existsSync3,
596
+ fchmodSync as fchmodSync2,
597
+ fsyncSync,
598
+ lstatSync as lstatSync3,
599
+ mkdirSync as mkdirSync2,
600
+ openSync as openSync2,
601
+ readFileSync as readFileSync3,
602
+ realpathSync as realpathSync2,
603
+ renameSync as renameSync2,
604
+ rmSync as rmSync3,
605
+ statSync as statSync3,
606
+ writeFileSync as writeFileSync2
607
+ } from "node:fs";
608
+ import { homedir as homedir2 } from "node:os";
609
+ import { basename as basename2, dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";
610
+ import { isDeepStrictEqual } from "node:util";
611
+
612
+ // node_modules/jsonc-parser/lib/esm/impl/scanner.js
613
+ function createScanner(text, ignoreTrivia = false) {
614
+ const len = text.length;
615
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
616
+ function scanHexDigits(count, exact) {
617
+ let digits = 0;
618
+ let value2 = 0;
619
+ while (digits < count || !exact) {
620
+ let ch = text.charCodeAt(pos);
621
+ if (ch >= 48 && ch <= 57) {
622
+ value2 = value2 * 16 + ch - 48;
623
+ } else if (ch >= 65 && ch <= 70) {
624
+ value2 = value2 * 16 + ch - 65 + 10;
625
+ } else if (ch >= 97 && ch <= 102) {
626
+ value2 = value2 * 16 + ch - 97 + 10;
627
+ } else {
628
+ break;
629
+ }
630
+ pos++;
631
+ digits++;
632
+ }
633
+ if (digits < count) {
634
+ value2 = -1;
635
+ }
636
+ return value2;
637
+ }
638
+ function setPosition(newPosition) {
639
+ pos = newPosition;
640
+ value = "";
641
+ tokenOffset = 0;
642
+ token = 16;
643
+ scanError = 0;
644
+ }
645
+ function scanNumber() {
646
+ let start = pos;
647
+ if (text.charCodeAt(pos) === 48) {
648
+ pos++;
649
+ } else {
650
+ pos++;
651
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
652
+ pos++;
653
+ }
654
+ }
655
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
656
+ pos++;
657
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
658
+ pos++;
659
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
660
+ pos++;
661
+ }
662
+ } else {
663
+ scanError = 3;
664
+ return text.substring(start, pos);
665
+ }
666
+ }
667
+ let end = pos;
668
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
669
+ pos++;
670
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
671
+ pos++;
672
+ }
673
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
674
+ pos++;
675
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
676
+ pos++;
677
+ }
678
+ end = pos;
679
+ } else {
680
+ scanError = 3;
681
+ }
682
+ }
683
+ return text.substring(start, end);
684
+ }
685
+ function scanString() {
686
+ let result = "", start = pos;
687
+ while (true) {
688
+ if (pos >= len) {
689
+ result += text.substring(start, pos);
690
+ scanError = 2;
691
+ break;
692
+ }
693
+ const ch = text.charCodeAt(pos);
694
+ if (ch === 34) {
695
+ result += text.substring(start, pos);
696
+ pos++;
697
+ break;
698
+ }
699
+ if (ch === 92) {
700
+ result += text.substring(start, pos);
701
+ pos++;
702
+ if (pos >= len) {
703
+ scanError = 2;
704
+ break;
705
+ }
706
+ const ch2 = text.charCodeAt(pos++);
707
+ switch (ch2) {
708
+ case 34:
709
+ result += '"';
710
+ break;
711
+ case 92:
712
+ result += "\\";
713
+ break;
714
+ case 47:
715
+ result += "/";
716
+ break;
717
+ case 98:
718
+ result += "\b";
719
+ break;
720
+ case 102:
721
+ result += "\f";
722
+ break;
723
+ case 110:
724
+ result += "\n";
725
+ break;
726
+ case 114:
727
+ result += "\r";
728
+ break;
729
+ case 116:
730
+ result += " ";
731
+ break;
732
+ case 117:
733
+ const ch3 = scanHexDigits(4, true);
734
+ if (ch3 >= 0) {
735
+ result += String.fromCharCode(ch3);
736
+ } else {
737
+ scanError = 4;
738
+ }
739
+ break;
740
+ default:
741
+ scanError = 5;
742
+ }
743
+ start = pos;
744
+ continue;
745
+ }
746
+ if (ch >= 0 && ch <= 31) {
747
+ if (isLineBreak(ch)) {
748
+ result += text.substring(start, pos);
749
+ scanError = 2;
750
+ break;
751
+ } else {
752
+ scanError = 6;
753
+ }
754
+ }
755
+ pos++;
756
+ }
757
+ return result;
758
+ }
759
+ function scanNext() {
760
+ value = "";
761
+ scanError = 0;
762
+ tokenOffset = pos;
763
+ lineStartOffset = lineNumber;
764
+ prevTokenLineStartOffset = tokenLineStartOffset;
765
+ if (pos >= len) {
766
+ tokenOffset = len;
767
+ return token = 17;
768
+ }
769
+ let code = text.charCodeAt(pos);
770
+ if (isWhiteSpace(code)) {
771
+ do {
772
+ pos++;
773
+ value += String.fromCharCode(code);
774
+ code = text.charCodeAt(pos);
775
+ } while (isWhiteSpace(code));
776
+ return token = 15;
777
+ }
778
+ if (isLineBreak(code)) {
779
+ pos++;
780
+ value += String.fromCharCode(code);
781
+ if (code === 13 && text.charCodeAt(pos) === 10) {
782
+ pos++;
783
+ value += "\n";
784
+ }
785
+ lineNumber++;
786
+ tokenLineStartOffset = pos;
787
+ return token = 14;
788
+ }
789
+ switch (code) {
790
+ // tokens: []{}:,
791
+ case 123:
792
+ pos++;
793
+ return token = 1;
794
+ case 125:
795
+ pos++;
796
+ return token = 2;
797
+ case 91:
798
+ pos++;
799
+ return token = 3;
800
+ case 93:
801
+ pos++;
802
+ return token = 4;
803
+ case 58:
804
+ pos++;
805
+ return token = 6;
806
+ case 44:
807
+ pos++;
808
+ return token = 5;
809
+ // strings
810
+ case 34:
811
+ pos++;
812
+ value = scanString();
813
+ return token = 10;
814
+ // comments
815
+ case 47:
816
+ const start = pos - 1;
817
+ if (text.charCodeAt(pos + 1) === 47) {
818
+ pos += 2;
819
+ while (pos < len) {
820
+ if (isLineBreak(text.charCodeAt(pos))) {
821
+ break;
822
+ }
823
+ pos++;
824
+ }
825
+ value = text.substring(start, pos);
826
+ return token = 12;
827
+ }
828
+ if (text.charCodeAt(pos + 1) === 42) {
829
+ pos += 2;
830
+ const safeLength = len - 1;
831
+ let commentClosed = false;
832
+ while (pos < safeLength) {
833
+ const ch = text.charCodeAt(pos);
834
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
835
+ pos += 2;
836
+ commentClosed = true;
837
+ break;
838
+ }
839
+ pos++;
840
+ if (isLineBreak(ch)) {
841
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
842
+ pos++;
843
+ }
844
+ lineNumber++;
845
+ tokenLineStartOffset = pos;
846
+ }
847
+ }
848
+ if (!commentClosed) {
849
+ pos++;
850
+ scanError = 1;
851
+ }
852
+ value = text.substring(start, pos);
853
+ return token = 13;
854
+ }
855
+ value += String.fromCharCode(code);
856
+ pos++;
857
+ return token = 16;
858
+ // numbers
859
+ case 45:
860
+ value += String.fromCharCode(code);
861
+ pos++;
862
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
863
+ return token = 16;
864
+ }
865
+ // found a minus, followed by a number so
866
+ // we fall through to proceed with scanning
867
+ // numbers
868
+ case 48:
869
+ case 49:
870
+ case 50:
871
+ case 51:
872
+ case 52:
873
+ case 53:
874
+ case 54:
875
+ case 55:
876
+ case 56:
877
+ case 57:
878
+ value += scanNumber();
879
+ return token = 11;
880
+ // literals and unknown symbols
881
+ default:
882
+ while (pos < len && isUnknownContentCharacter(code)) {
883
+ pos++;
884
+ code = text.charCodeAt(pos);
885
+ }
886
+ if (tokenOffset !== pos) {
887
+ value = text.substring(tokenOffset, pos);
888
+ switch (value) {
889
+ case "true":
890
+ return token = 8;
891
+ case "false":
892
+ return token = 9;
893
+ case "null":
894
+ return token = 7;
895
+ }
896
+ return token = 16;
897
+ }
898
+ value += String.fromCharCode(code);
899
+ pos++;
900
+ return token = 16;
901
+ }
902
+ }
903
+ function isUnknownContentCharacter(code) {
904
+ if (isWhiteSpace(code) || isLineBreak(code)) {
905
+ return false;
906
+ }
907
+ switch (code) {
908
+ case 125:
909
+ case 93:
910
+ case 123:
911
+ case 91:
912
+ case 34:
913
+ case 58:
914
+ case 44:
915
+ case 47:
916
+ return false;
917
+ }
918
+ return true;
919
+ }
920
+ function scanNextNonTrivia() {
921
+ let result;
922
+ do {
923
+ result = scanNext();
924
+ } while (result >= 12 && result <= 15);
925
+ return result;
926
+ }
927
+ return {
928
+ setPosition,
929
+ getPosition: () => pos,
930
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
931
+ getToken: () => token,
932
+ getTokenValue: () => value,
933
+ getTokenOffset: () => tokenOffset,
934
+ getTokenLength: () => pos - tokenOffset,
935
+ getTokenStartLine: () => lineStartOffset,
936
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
937
+ getTokenError: () => scanError
938
+ };
939
+ }
940
+ function isWhiteSpace(ch) {
941
+ return ch === 32 || ch === 9;
942
+ }
943
+ function isLineBreak(ch) {
944
+ return ch === 10 || ch === 13;
945
+ }
946
+ function isDigit(ch) {
947
+ return ch >= 48 && ch <= 57;
948
+ }
949
+ var CharacterCodes;
950
+ (function(CharacterCodes2) {
951
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
952
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
953
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
954
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
955
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
956
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
957
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
958
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
959
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
960
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
961
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
962
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
963
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
964
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
965
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
966
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
967
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
968
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
969
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
970
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
971
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
972
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
973
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
974
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
975
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
976
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
977
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
978
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
979
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
980
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
981
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
982
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
983
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
984
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
985
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
986
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
987
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
988
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
989
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
990
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
991
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
992
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
993
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
994
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
995
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
996
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
997
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
998
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
999
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
1000
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
1001
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
1002
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
1003
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
1004
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
1005
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
1006
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
1007
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
1008
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
1009
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
1010
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
1011
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
1012
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
1013
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
1014
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
1015
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
1016
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
1017
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
1018
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
1019
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
1020
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
1021
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
1022
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
1023
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
1024
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
1025
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
1026
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
1027
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
1028
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
1029
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
1030
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
1031
+ })(CharacterCodes || (CharacterCodes = {}));
1032
+
1033
+ // node_modules/jsonc-parser/lib/esm/impl/string-intern.js
1034
+ var cachedSpaces = new Array(20).fill(0).map((_, index) => {
1035
+ return " ".repeat(index);
1036
+ });
1037
+ var maxCachedValues = 200;
1038
+ var cachedBreakLinesWithSpaces = {
1039
+ " ": {
1040
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1041
+ return "\n" + " ".repeat(index);
1042
+ }),
1043
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
1044
+ return "\r" + " ".repeat(index);
1045
+ }),
1046
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1047
+ return "\r\n" + " ".repeat(index);
1048
+ })
1049
+ },
1050
+ " ": {
1051
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1052
+ return "\n" + " ".repeat(index);
1053
+ }),
1054
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
1055
+ return "\r" + " ".repeat(index);
1056
+ }),
1057
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1058
+ return "\r\n" + " ".repeat(index);
1059
+ })
1060
+ }
1061
+ };
1062
+ var supportedEols = ["\n", "\r", "\r\n"];
1063
+
1064
+ // node_modules/jsonc-parser/lib/esm/impl/format.js
1065
+ function format(documentText, range, options) {
1066
+ let initialIndentLevel;
1067
+ let formatText;
1068
+ let formatTextStart;
1069
+ let rangeStart;
1070
+ let rangeEnd;
1071
+ if (range) {
1072
+ rangeStart = range.offset;
1073
+ rangeEnd = rangeStart + range.length;
1074
+ formatTextStart = rangeStart;
1075
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
1076
+ formatTextStart--;
1077
+ }
1078
+ let endOffset = rangeEnd;
1079
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
1080
+ endOffset++;
1081
+ }
1082
+ formatText = documentText.substring(formatTextStart, endOffset);
1083
+ initialIndentLevel = computeIndentLevel(formatText, options);
1084
+ } else {
1085
+ formatText = documentText;
1086
+ initialIndentLevel = 0;
1087
+ formatTextStart = 0;
1088
+ rangeStart = 0;
1089
+ rangeEnd = documentText.length;
1090
+ }
1091
+ const eol = getEOL(options, documentText);
1092
+ const eolFastPathSupported = supportedEols.includes(eol);
1093
+ let numberLineBreaks = 0;
1094
+ let indentLevel = 0;
1095
+ let indentValue;
1096
+ if (options.insertSpaces) {
1097
+ indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
1098
+ } else {
1099
+ indentValue = " ";
1100
+ }
1101
+ const indentType = indentValue === " " ? " " : " ";
1102
+ let scanner = createScanner(formatText, false);
1103
+ let hasError = false;
1104
+ function newLinesAndIndent() {
1105
+ if (numberLineBreaks > 1) {
1106
+ return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
1107
+ }
1108
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
1109
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {
1110
+ return eol + repeat(indentValue, initialIndentLevel + indentLevel);
1111
+ }
1112
+ if (amountOfSpaces <= 0) {
1113
+ return eol;
1114
+ }
1115
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
1116
+ }
1117
+ function scanNext() {
1118
+ let token = scanner.scan();
1119
+ numberLineBreaks = 0;
1120
+ while (token === 15 || token === 14) {
1121
+ if (token === 14 && options.keepLines) {
1122
+ numberLineBreaks += 1;
1123
+ } else if (token === 14) {
1124
+ numberLineBreaks = 1;
1125
+ }
1126
+ token = scanner.scan();
1127
+ }
1128
+ hasError = token === 16 || scanner.getTokenError() !== 0;
1129
+ return token;
1130
+ }
1131
+ const editOperations = [];
1132
+ function addEdit(text, startOffset, endOffset) {
1133
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
1134
+ editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
1135
+ }
1136
+ }
1137
+ let firstToken = scanNext();
1138
+ if (options.keepLines && numberLineBreaks > 0) {
1139
+ addEdit(repeat(eol, numberLineBreaks), 0, 0);
1140
+ }
1141
+ if (firstToken !== 17) {
1142
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
1143
+ let initialIndent = indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
1144
+ addEdit(initialIndent, formatTextStart, firstTokenStart);
1145
+ }
1146
+ while (firstToken !== 17) {
1147
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
1148
+ let secondToken = scanNext();
1149
+ let replaceContent = "";
1150
+ let needsLineBreak = false;
1151
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
1152
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
1153
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
1154
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
1155
+ needsLineBreak = secondToken === 12;
1156
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
1157
+ secondToken = scanNext();
1158
+ }
1159
+ if (secondToken === 2) {
1160
+ if (firstToken !== 1) {
1161
+ indentLevel--;
1162
+ }
1163
+ ;
1164
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
1165
+ replaceContent = newLinesAndIndent();
1166
+ } else if (options.keepLines) {
1167
+ replaceContent = cachedSpaces[1];
1168
+ }
1169
+ } else if (secondToken === 4) {
1170
+ if (firstToken !== 3) {
1171
+ indentLevel--;
1172
+ }
1173
+ ;
1174
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
1175
+ replaceContent = newLinesAndIndent();
1176
+ } else if (options.keepLines) {
1177
+ replaceContent = cachedSpaces[1];
1178
+ }
1179
+ } else {
1180
+ switch (firstToken) {
1181
+ case 3:
1182
+ case 1:
1183
+ indentLevel++;
1184
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
1185
+ replaceContent = newLinesAndIndent();
1186
+ } else {
1187
+ replaceContent = cachedSpaces[1];
1188
+ }
1189
+ break;
1190
+ case 5:
1191
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
1192
+ replaceContent = newLinesAndIndent();
1193
+ } else {
1194
+ replaceContent = cachedSpaces[1];
1195
+ }
1196
+ break;
1197
+ case 12:
1198
+ replaceContent = newLinesAndIndent();
1199
+ break;
1200
+ case 13:
1201
+ if (numberLineBreaks > 0) {
1202
+ replaceContent = newLinesAndIndent();
1203
+ } else if (!needsLineBreak) {
1204
+ replaceContent = cachedSpaces[1];
1205
+ }
1206
+ break;
1207
+ case 6:
1208
+ if (options.keepLines && numberLineBreaks > 0) {
1209
+ replaceContent = newLinesAndIndent();
1210
+ } else if (!needsLineBreak) {
1211
+ replaceContent = cachedSpaces[1];
1212
+ }
1213
+ break;
1214
+ case 10:
1215
+ if (options.keepLines && numberLineBreaks > 0) {
1216
+ replaceContent = newLinesAndIndent();
1217
+ } else if (secondToken === 6 && !needsLineBreak) {
1218
+ replaceContent = "";
1219
+ }
1220
+ break;
1221
+ case 7:
1222
+ case 8:
1223
+ case 9:
1224
+ case 11:
1225
+ case 2:
1226
+ case 4:
1227
+ if (options.keepLines && numberLineBreaks > 0) {
1228
+ replaceContent = newLinesAndIndent();
1229
+ } else {
1230
+ if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
1231
+ replaceContent = cachedSpaces[1];
1232
+ } else if (secondToken !== 5 && secondToken !== 17) {
1233
+ hasError = true;
1234
+ }
1235
+ }
1236
+ break;
1237
+ case 16:
1238
+ hasError = true;
1239
+ break;
1240
+ }
1241
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
1242
+ replaceContent = newLinesAndIndent();
1243
+ }
1244
+ }
1245
+ if (secondToken === 17) {
1246
+ if (options.keepLines && numberLineBreaks > 0) {
1247
+ replaceContent = newLinesAndIndent();
1248
+ } else {
1249
+ replaceContent = options.insertFinalNewline ? eol : "";
1250
+ }
1251
+ }
1252
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
1253
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
1254
+ firstToken = secondToken;
1255
+ }
1256
+ return editOperations;
1257
+ }
1258
+ function repeat(s, count) {
1259
+ let result = "";
1260
+ for (let i = 0; i < count; i++) {
1261
+ result += s;
1262
+ }
1263
+ return result;
1264
+ }
1265
+ function computeIndentLevel(content, options) {
1266
+ let i = 0;
1267
+ let nChars = 0;
1268
+ const tabSize = options.tabSize || 4;
1269
+ while (i < content.length) {
1270
+ let ch = content.charAt(i);
1271
+ if (ch === cachedSpaces[1]) {
1272
+ nChars++;
1273
+ } else if (ch === " ") {
1274
+ nChars += tabSize;
1275
+ } else {
1276
+ break;
1277
+ }
1278
+ i++;
1279
+ }
1280
+ return Math.floor(nChars / tabSize);
1281
+ }
1282
+ function getEOL(options, text) {
1283
+ for (let i = 0; i < text.length; i++) {
1284
+ const ch = text.charAt(i);
1285
+ if (ch === "\r") {
1286
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
1287
+ return "\r\n";
1288
+ }
1289
+ return "\r";
1290
+ } else if (ch === "\n") {
1291
+ return "\n";
1292
+ }
1293
+ }
1294
+ return options && options.eol || "\n";
1295
+ }
1296
+ function isEOL(text, offset) {
1297
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
1298
+ }
1299
+
1300
+ // node_modules/jsonc-parser/lib/esm/impl/parser.js
1301
+ var ParseOptions;
1302
+ (function(ParseOptions2) {
1303
+ ParseOptions2.DEFAULT = {
1304
+ allowTrailingComma: false
1305
+ };
1306
+ })(ParseOptions || (ParseOptions = {}));
1307
+ function parse(text, errors = [], options = ParseOptions.DEFAULT) {
1308
+ let currentProperty = null;
1309
+ let currentParent = [];
1310
+ const previousParents = [];
1311
+ function onValue(value) {
1312
+ if (Array.isArray(currentParent)) {
1313
+ currentParent.push(value);
1314
+ } else if (currentProperty !== null) {
1315
+ currentParent[currentProperty] = value;
1316
+ }
1317
+ }
1318
+ const visitor = {
1319
+ onObjectBegin: () => {
1320
+ const object = {};
1321
+ onValue(object);
1322
+ previousParents.push(currentParent);
1323
+ currentParent = object;
1324
+ currentProperty = null;
1325
+ },
1326
+ onObjectProperty: (name) => {
1327
+ currentProperty = name;
1328
+ },
1329
+ onObjectEnd: () => {
1330
+ currentParent = previousParents.pop();
1331
+ },
1332
+ onArrayBegin: () => {
1333
+ const array = [];
1334
+ onValue(array);
1335
+ previousParents.push(currentParent);
1336
+ currentParent = array;
1337
+ currentProperty = null;
1338
+ },
1339
+ onArrayEnd: () => {
1340
+ currentParent = previousParents.pop();
1341
+ },
1342
+ onLiteralValue: onValue,
1343
+ onError: (error, offset, length) => {
1344
+ errors.push({ error, offset, length });
1345
+ }
1346
+ };
1347
+ visit(text, visitor, options);
1348
+ return currentParent[0];
1349
+ }
1350
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
1351
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
1352
+ function ensurePropertyComplete(endOffset) {
1353
+ if (currentParent.type === "property") {
1354
+ currentParent.length = endOffset - currentParent.offset;
1355
+ currentParent = currentParent.parent;
1356
+ }
1357
+ }
1358
+ function onValue(valueNode) {
1359
+ currentParent.children.push(valueNode);
1360
+ return valueNode;
1361
+ }
1362
+ const visitor = {
1363
+ onObjectBegin: (offset) => {
1364
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
1365
+ },
1366
+ onObjectProperty: (name, offset, length) => {
1367
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
1368
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
1369
+ },
1370
+ onObjectEnd: (offset, length) => {
1371
+ ensurePropertyComplete(offset + length);
1372
+ currentParent.length = offset + length - currentParent.offset;
1373
+ currentParent = currentParent.parent;
1374
+ ensurePropertyComplete(offset + length);
1375
+ },
1376
+ onArrayBegin: (offset, length) => {
1377
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
1378
+ },
1379
+ onArrayEnd: (offset, length) => {
1380
+ currentParent.length = offset + length - currentParent.offset;
1381
+ currentParent = currentParent.parent;
1382
+ ensurePropertyComplete(offset + length);
1383
+ },
1384
+ onLiteralValue: (value, offset, length) => {
1385
+ onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
1386
+ ensurePropertyComplete(offset + length);
1387
+ },
1388
+ onSeparator: (sep2, offset, length) => {
1389
+ if (currentParent.type === "property") {
1390
+ if (sep2 === ":") {
1391
+ currentParent.colonOffset = offset;
1392
+ } else if (sep2 === ",") {
1393
+ ensurePropertyComplete(offset);
1394
+ }
1395
+ }
1396
+ },
1397
+ onError: (error, offset, length) => {
1398
+ errors.push({ error, offset, length });
1399
+ }
1400
+ };
1401
+ visit(text, visitor, options);
1402
+ const result = currentParent.children[0];
1403
+ if (result) {
1404
+ delete result.parent;
1405
+ }
1406
+ return result;
1407
+ }
1408
+ function findNodeAtLocation(root, path) {
1409
+ if (!root) {
1410
+ return void 0;
1411
+ }
1412
+ let node = root;
1413
+ for (let segment of path) {
1414
+ if (typeof segment === "string") {
1415
+ if (node.type !== "object" || !Array.isArray(node.children)) {
1416
+ return void 0;
1417
+ }
1418
+ let found = false;
1419
+ for (const propertyNode of node.children) {
1420
+ if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
1421
+ node = propertyNode.children[1];
1422
+ found = true;
1423
+ break;
1424
+ }
1425
+ }
1426
+ if (!found) {
1427
+ return void 0;
1428
+ }
1429
+ } else {
1430
+ const index = segment;
1431
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
1432
+ return void 0;
1433
+ }
1434
+ node = node.children[index];
1435
+ }
1436
+ }
1437
+ return node;
1438
+ }
1439
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
1440
+ const _scanner = createScanner(text, false);
1441
+ const _jsonPath = [];
1442
+ let suppressedCallbacks = 0;
1443
+ function toNoArgVisit(visitFunction) {
1444
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
1445
+ }
1446
+ function toOneArgVisit(visitFunction) {
1447
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
1448
+ }
1449
+ function toOneArgVisitWithPath(visitFunction) {
1450
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
1451
+ }
1452
+ function toBeginVisit(visitFunction) {
1453
+ return visitFunction ? () => {
1454
+ if (suppressedCallbacks > 0) {
1455
+ suppressedCallbacks++;
1456
+ } else {
1457
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
1458
+ if (cbReturn === false) {
1459
+ suppressedCallbacks = 1;
1460
+ }
1461
+ }
1462
+ } : () => true;
1463
+ }
1464
+ function toEndVisit(visitFunction) {
1465
+ return visitFunction ? () => {
1466
+ if (suppressedCallbacks > 0) {
1467
+ suppressedCallbacks--;
1468
+ }
1469
+ if (suppressedCallbacks === 0) {
1470
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
1471
+ }
1472
+ } : () => true;
1473
+ }
1474
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
1475
+ const disallowComments = options && options.disallowComments;
1476
+ const allowTrailingComma = options && options.allowTrailingComma;
1477
+ function scanNext() {
1478
+ while (true) {
1479
+ const token = _scanner.scan();
1480
+ switch (_scanner.getTokenError()) {
1481
+ case 4:
1482
+ handleError(
1483
+ 14
1484
+ /* ParseErrorCode.InvalidUnicode */
1485
+ );
1486
+ break;
1487
+ case 5:
1488
+ handleError(
1489
+ 15
1490
+ /* ParseErrorCode.InvalidEscapeCharacter */
1491
+ );
1492
+ break;
1493
+ case 3:
1494
+ handleError(
1495
+ 13
1496
+ /* ParseErrorCode.UnexpectedEndOfNumber */
1497
+ );
1498
+ break;
1499
+ case 1:
1500
+ if (!disallowComments) {
1501
+ handleError(
1502
+ 11
1503
+ /* ParseErrorCode.UnexpectedEndOfComment */
1504
+ );
1505
+ }
1506
+ break;
1507
+ case 2:
1508
+ handleError(
1509
+ 12
1510
+ /* ParseErrorCode.UnexpectedEndOfString */
1511
+ );
1512
+ break;
1513
+ case 6:
1514
+ handleError(
1515
+ 16
1516
+ /* ParseErrorCode.InvalidCharacter */
1517
+ );
1518
+ break;
1519
+ }
1520
+ switch (token) {
1521
+ case 12:
1522
+ case 13:
1523
+ if (disallowComments) {
1524
+ handleError(
1525
+ 10
1526
+ /* ParseErrorCode.InvalidCommentToken */
1527
+ );
1528
+ } else {
1529
+ onComment();
1530
+ }
1531
+ break;
1532
+ case 16:
1533
+ handleError(
1534
+ 1
1535
+ /* ParseErrorCode.InvalidSymbol */
1536
+ );
1537
+ break;
1538
+ case 15:
1539
+ case 14:
1540
+ break;
1541
+ default:
1542
+ return token;
1543
+ }
1544
+ }
1545
+ }
1546
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
1547
+ onError(error);
1548
+ if (skipUntilAfter.length + skipUntil.length > 0) {
1549
+ let token = _scanner.getToken();
1550
+ while (token !== 17) {
1551
+ if (skipUntilAfter.indexOf(token) !== -1) {
1552
+ scanNext();
1553
+ break;
1554
+ } else if (skipUntil.indexOf(token) !== -1) {
1555
+ break;
1556
+ }
1557
+ token = scanNext();
1558
+ }
1559
+ }
1560
+ }
1561
+ function parseString(isValue) {
1562
+ const value = _scanner.getTokenValue();
1563
+ if (isValue) {
1564
+ onLiteralValue(value);
1565
+ } else {
1566
+ onObjectProperty(value);
1567
+ _jsonPath.push(value);
1568
+ }
1569
+ scanNext();
1570
+ return true;
1571
+ }
1572
+ function parseLiteral() {
1573
+ switch (_scanner.getToken()) {
1574
+ case 11:
1575
+ const tokenValue = _scanner.getTokenValue();
1576
+ let value = Number(tokenValue);
1577
+ if (isNaN(value)) {
1578
+ handleError(
1579
+ 2
1580
+ /* ParseErrorCode.InvalidNumberFormat */
1581
+ );
1582
+ value = 0;
1583
+ }
1584
+ onLiteralValue(value);
1585
+ break;
1586
+ case 7:
1587
+ onLiteralValue(null);
1588
+ break;
1589
+ case 8:
1590
+ onLiteralValue(true);
1591
+ break;
1592
+ case 9:
1593
+ onLiteralValue(false);
1594
+ break;
1595
+ default:
1596
+ return false;
1597
+ }
1598
+ scanNext();
1599
+ return true;
1600
+ }
1601
+ function parseProperty() {
1602
+ if (_scanner.getToken() !== 10) {
1603
+ handleError(3, [], [
1604
+ 2,
1605
+ 5
1606
+ /* SyntaxKind.CommaToken */
1607
+ ]);
1608
+ return false;
1609
+ }
1610
+ parseString(false);
1611
+ if (_scanner.getToken() === 6) {
1612
+ onSeparator(":");
1613
+ scanNext();
1614
+ if (!parseValue()) {
1615
+ handleError(4, [], [
1616
+ 2,
1617
+ 5
1618
+ /* SyntaxKind.CommaToken */
1619
+ ]);
1620
+ }
1621
+ } else {
1622
+ handleError(5, [], [
1623
+ 2,
1624
+ 5
1625
+ /* SyntaxKind.CommaToken */
1626
+ ]);
1627
+ }
1628
+ _jsonPath.pop();
1629
+ return true;
1630
+ }
1631
+ function parseObject() {
1632
+ onObjectBegin();
1633
+ scanNext();
1634
+ let needsComma = false;
1635
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
1636
+ if (_scanner.getToken() === 5) {
1637
+ if (!needsComma) {
1638
+ handleError(4, [], []);
1639
+ }
1640
+ onSeparator(",");
1641
+ scanNext();
1642
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
1643
+ break;
1644
+ }
1645
+ } else if (needsComma) {
1646
+ handleError(6, [], []);
1647
+ }
1648
+ if (!parseProperty()) {
1649
+ handleError(4, [], [
1650
+ 2,
1651
+ 5
1652
+ /* SyntaxKind.CommaToken */
1653
+ ]);
1654
+ }
1655
+ needsComma = true;
1656
+ }
1657
+ onObjectEnd();
1658
+ if (_scanner.getToken() !== 2) {
1659
+ handleError(7, [
1660
+ 2
1661
+ /* SyntaxKind.CloseBraceToken */
1662
+ ], []);
1663
+ } else {
1664
+ scanNext();
1665
+ }
1666
+ return true;
1667
+ }
1668
+ function parseArray() {
1669
+ onArrayBegin();
1670
+ scanNext();
1671
+ let isFirstElement = true;
1672
+ let needsComma = false;
1673
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
1674
+ if (_scanner.getToken() === 5) {
1675
+ if (!needsComma) {
1676
+ handleError(4, [], []);
1677
+ }
1678
+ onSeparator(",");
1679
+ scanNext();
1680
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
1681
+ break;
1682
+ }
1683
+ } else if (needsComma) {
1684
+ handleError(6, [], []);
1685
+ }
1686
+ if (isFirstElement) {
1687
+ _jsonPath.push(0);
1688
+ isFirstElement = false;
1689
+ } else {
1690
+ _jsonPath[_jsonPath.length - 1]++;
1691
+ }
1692
+ if (!parseValue()) {
1693
+ handleError(4, [], [
1694
+ 4,
1695
+ 5
1696
+ /* SyntaxKind.CommaToken */
1697
+ ]);
1698
+ }
1699
+ needsComma = true;
1700
+ }
1701
+ onArrayEnd();
1702
+ if (!isFirstElement) {
1703
+ _jsonPath.pop();
1704
+ }
1705
+ if (_scanner.getToken() !== 4) {
1706
+ handleError(8, [
1707
+ 4
1708
+ /* SyntaxKind.CloseBracketToken */
1709
+ ], []);
1710
+ } else {
1711
+ scanNext();
1712
+ }
1713
+ return true;
1714
+ }
1715
+ function parseValue() {
1716
+ switch (_scanner.getToken()) {
1717
+ case 3:
1718
+ return parseArray();
1719
+ case 1:
1720
+ return parseObject();
1721
+ case 10:
1722
+ return parseString(true);
1723
+ default:
1724
+ return parseLiteral();
1725
+ }
1726
+ }
1727
+ scanNext();
1728
+ if (_scanner.getToken() === 17) {
1729
+ if (options.allowEmptyContent) {
1730
+ return true;
1731
+ }
1732
+ handleError(4, [], []);
1733
+ return false;
1734
+ }
1735
+ if (!parseValue()) {
1736
+ handleError(4, [], []);
1737
+ return false;
1738
+ }
1739
+ if (_scanner.getToken() !== 17) {
1740
+ handleError(9, [], []);
1741
+ }
1742
+ return true;
1743
+ }
1744
+ function getNodeType(value) {
1745
+ switch (typeof value) {
1746
+ case "boolean":
1747
+ return "boolean";
1748
+ case "number":
1749
+ return "number";
1750
+ case "string":
1751
+ return "string";
1752
+ case "object": {
1753
+ if (!value) {
1754
+ return "null";
1755
+ } else if (Array.isArray(value)) {
1756
+ return "array";
1757
+ }
1758
+ return "object";
1759
+ }
1760
+ default:
1761
+ return "null";
1762
+ }
1763
+ }
1764
+
1765
+ // node_modules/jsonc-parser/lib/esm/impl/edit.js
1766
+ function setProperty(text, originalPath, value, options) {
1767
+ const path = originalPath.slice();
1768
+ const errors = [];
1769
+ const root = parseTree(text, errors);
1770
+ let parent = void 0;
1771
+ let lastSegment = void 0;
1772
+ while (path.length > 0) {
1773
+ lastSegment = path.pop();
1774
+ parent = findNodeAtLocation(root, path);
1775
+ if (parent === void 0 && value !== void 0) {
1776
+ if (typeof lastSegment === "string") {
1777
+ value = { [lastSegment]: value };
1778
+ } else {
1779
+ value = [value];
1780
+ }
1781
+ } else {
1782
+ break;
1783
+ }
1784
+ }
1785
+ if (!parent) {
1786
+ if (value === void 0) {
1787
+ throw new Error("Can not delete in empty document");
1788
+ }
1789
+ return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
1790
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
1791
+ const existing = findNodeAtLocation(parent, [lastSegment]);
1792
+ if (existing !== void 0) {
1793
+ if (value === void 0) {
1794
+ if (!existing.parent) {
1795
+ throw new Error("Malformed AST");
1796
+ }
1797
+ const propertyIndex = parent.children.indexOf(existing.parent);
1798
+ let removeBegin;
1799
+ let removeEnd = existing.parent.offset + existing.parent.length;
1800
+ if (propertyIndex > 0) {
1801
+ let previous = parent.children[propertyIndex - 1];
1802
+ removeBegin = previous.offset + previous.length;
1803
+ } else {
1804
+ removeBegin = parent.offset + 1;
1805
+ if (parent.children.length > 1) {
1806
+ let next = parent.children[1];
1807
+ removeEnd = next.offset;
1808
+ }
1809
+ }
1810
+ return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
1811
+ } else {
1812
+ return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
1813
+ }
1814
+ } else {
1815
+ if (value === void 0) {
1816
+ return [];
1817
+ }
1818
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1819
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
1820
+ let edit;
1821
+ if (index > 0) {
1822
+ let previous = parent.children[index - 1];
1823
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
1824
+ } else if (parent.children.length === 0) {
1825
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
1826
+ } else {
1827
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
1828
+ }
1829
+ return withFormatting(text, edit, options);
1830
+ }
1831
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
1832
+ const insertIndex = lastSegment;
1833
+ if (insertIndex === -1) {
1834
+ const newProperty = `${JSON.stringify(value)}`;
1835
+ let edit;
1836
+ if (parent.children.length === 0) {
1837
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
1838
+ } else {
1839
+ const previous = parent.children[parent.children.length - 1];
1840
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
1841
+ }
1842
+ return withFormatting(text, edit, options);
1843
+ } else if (value === void 0 && parent.children.length >= 0) {
1844
+ const removalIndex = lastSegment;
1845
+ const toRemove = parent.children[removalIndex];
1846
+ let edit;
1847
+ if (parent.children.length === 1) {
1848
+ edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
1849
+ } else if (parent.children.length - 1 === removalIndex) {
1850
+ let previous = parent.children[removalIndex - 1];
1851
+ let offset = previous.offset + previous.length;
1852
+ let parentEndOffset = parent.offset + parent.length;
1853
+ edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
1854
+ } else {
1855
+ edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
1856
+ }
1857
+ return withFormatting(text, edit, options);
1858
+ } else if (value !== void 0) {
1859
+ let edit;
1860
+ const newProperty = `${JSON.stringify(value)}`;
1861
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
1862
+ const toModify = parent.children[lastSegment];
1863
+ edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
1864
+ } else if (parent.children.length === 0 || lastSegment === 0) {
1865
+ edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
1866
+ } else {
1867
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
1868
+ const previous = parent.children[index - 1];
1869
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
1870
+ }
1871
+ return withFormatting(text, edit, options);
1872
+ } else {
1873
+ throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
1874
+ }
1875
+ } else {
1876
+ throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
1877
+ }
1878
+ }
1879
+ function withFormatting(text, edit, options) {
1880
+ if (!options.formattingOptions) {
1881
+ return [edit];
1882
+ }
1883
+ let newText = applyEdit(text, edit);
1884
+ let begin = edit.offset;
1885
+ let end = edit.offset + edit.content.length;
1886
+ if (edit.length === 0 || edit.content.length === 0) {
1887
+ while (begin > 0 && !isEOL(newText, begin - 1)) {
1888
+ begin--;
1889
+ }
1890
+ while (end < newText.length && !isEOL(newText, end)) {
1891
+ end++;
1892
+ }
1893
+ }
1894
+ const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
1895
+ for (let i = edits.length - 1; i >= 0; i--) {
1896
+ const edit2 = edits[i];
1897
+ newText = applyEdit(newText, edit2);
1898
+ begin = Math.min(begin, edit2.offset);
1899
+ end = Math.max(end, edit2.offset + edit2.length);
1900
+ end += edit2.content.length - edit2.length;
1901
+ }
1902
+ const editLength = text.length - (newText.length - end) - begin;
1903
+ return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
1904
+ }
1905
+ function applyEdit(text, edit) {
1906
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1907
+ }
1908
+
1909
+ // node_modules/jsonc-parser/lib/esm/main.js
1910
+ var ScanError;
1911
+ (function(ScanError2) {
1912
+ ScanError2[ScanError2["None"] = 0] = "None";
1913
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1914
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1915
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1916
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
1917
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1918
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
1919
+ })(ScanError || (ScanError = {}));
1920
+ var SyntaxKind;
1921
+ (function(SyntaxKind2) {
1922
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
1923
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
1924
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
1925
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
1926
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
1927
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
1928
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
1929
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
1930
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
1931
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
1932
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
1933
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1934
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1935
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1936
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
1937
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
1938
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
1939
+ })(SyntaxKind || (SyntaxKind = {}));
1940
+ var parse2 = parse;
1941
+ var parseTree2 = parseTree;
1942
+ var findNodeAtLocation2 = findNodeAtLocation;
1943
+ var ParseErrorCode;
1944
+ (function(ParseErrorCode2) {
1945
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
1946
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1947
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1948
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
1949
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
1950
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
1951
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1952
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1953
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1954
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1955
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1956
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1957
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1958
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
1959
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1960
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
1961
+ })(ParseErrorCode || (ParseErrorCode = {}));
1962
+ function modify(text, path, value, options) {
1963
+ return setProperty(text, path, value, options);
1964
+ }
1965
+ function applyEdits(text, edits) {
1966
+ let sortedEdits = edits.slice(0).sort((a, b) => {
1967
+ const diff = a.offset - b.offset;
1968
+ if (diff === 0) {
1969
+ return a.length - b.length;
1970
+ }
1971
+ return diff;
1972
+ });
1973
+ let lastModifiedOffset = text.length;
1974
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
1975
+ let e = sortedEdits[i];
1976
+ if (e.offset + e.length <= lastModifiedOffset) {
1977
+ text = applyEdit(text, e);
1978
+ } else {
1979
+ throw new Error("Overlapping edit");
1980
+ }
1981
+ lastModifiedOffset = e.offset;
1982
+ }
1983
+ return text;
1984
+ }
1985
+
1986
+ // src/utils/command-local/skills-install-helpers.ts
1987
+ import {
1988
+ existsSync as existsSync2,
1989
+ lstatSync as lstatSync2,
1990
+ realpathSync,
1991
+ rmSync as rmSync2,
1992
+ statSync as statSync2,
1993
+ unlinkSync
1994
+ } from "node:fs";
1995
+ import {
1996
+ basename,
1997
+ dirname as dirname2,
1998
+ isAbsolute,
1999
+ posix,
2000
+ relative,
2001
+ resolve,
2002
+ sep,
2003
+ win32
2004
+ } from "node:path";
2005
+ var CAMUNDA_SKILLS_REPOSITORY = "camunda/skills";
2006
+ var CAMUNDA_SKILLS_URL = `https://github.com/${CAMUNDA_SKILLS_REPOSITORY}`;
2007
+ function joinForPlatform(platform2, ...paths) {
2008
+ return platform2 === "win32" ? win32.join(...paths) : posix.join(...paths);
2009
+ }
2010
+ function executableIsOnPath({
2011
+ name,
2012
+ env,
2013
+ platform: platform2
2014
+ }) {
2015
+ const pathSeparator = platform2 === "win32" ? ";" : ":";
2016
+ const directories = (env.PATH ?? "").split(pathSeparator).filter((directory) => directory.length > 0);
2017
+ const extensions = platform2 === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((extension) => extension.length > 0) : [""];
2018
+ return directories.some(
2019
+ (directory) => extensions.some(
2020
+ (extension) => existsSync2(joinForPlatform(platform2, directory, `${name}${extension}`))
2021
+ )
2022
+ );
2023
+ }
2024
+
2025
+ // src/utils/command-local/mcp-install-helpers.ts
2026
+ var DOCS_URL = "https://camunda-docs.mcp.kapa.ai";
2027
+ function buildHarnesses() {
2028
+ const home = (process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME) || homedir2();
2029
+ const appData = process.platform === "darwin" ? join3(home, "Library", "Application Support") : process.platform === "win32" ? process.env.APPDATA || join3(home, "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join3(home, ".config");
2030
+ const claude = process.env.CLAUDE_CONFIG_DIR || join3(home, ".claude");
2031
+ const copilot = process.env.COPILOT_HOME || join3(home, ".copilot");
2032
+ const harnesses = [
2033
+ {
2034
+ id: "claude-code",
2035
+ path: join3(process.env.CLAUDE_CONFIG_DIR || home, ".claude.json"),
2036
+ key: "mcpServers",
2037
+ directories: [claude],
2038
+ executable: "claude",
2039
+ stdioType: "stdio"
2040
+ },
2041
+ {
2042
+ id: "github-copilot",
2043
+ path: join3(copilot, "mcp-config.json"),
2044
+ key: "mcpServers",
2045
+ directories: [copilot],
2046
+ executable: "copilot",
2047
+ stdioType: "local"
2048
+ },
2049
+ {
2050
+ id: "cursor",
2051
+ path: join3(home, ".cursor", "mcp.json"),
2052
+ key: "mcpServers",
2053
+ directories: [join3(home, ".cursor"), join3(appData, "Cursor")],
2054
+ executable: "cursor",
2055
+ stdioType: "stdio"
2056
+ },
2057
+ {
2058
+ id: "vscode",
2059
+ path: join3(appData, "Code", "User", "mcp.json"),
2060
+ key: "servers",
2061
+ directories: [join3(appData, "Code")],
2062
+ executable: "code",
2063
+ stdioType: "stdio"
2064
+ }
2065
+ ];
2066
+ if (process.platform === "darwin" || process.platform === "win32") {
2067
+ harnesses.push({
2068
+ id: "claude-desktop",
2069
+ path: join3(appData, "Claude", "claude_desktop_config.json"),
2070
+ key: "mcpServers",
2071
+ directories: [join3(appData, "Claude")]
2072
+ });
2073
+ }
2074
+ return harnesses;
2075
+ }
2076
+ function detectMcpHarnesses() {
2077
+ return buildHarnesses().filter(
2078
+ (harness) => existsSync3(harness.path) || harness.directories.some((directory) => existsSync3(directory)) || harness.executable !== void 0 && executableIsOnPath({
2079
+ name: harness.executable,
2080
+ env: process.env,
2081
+ platform: process.platform
2082
+ })
2083
+ );
2084
+ }
2085
+ function selectHarnesses(requested) {
2086
+ const harnesses = buildHarnesses();
2087
+ const aliases = {
2088
+ claude: "claude-code",
2089
+ copilot: "github-copilot",
2090
+ code: "vscode"
2091
+ };
2092
+ if (requested.length > 0) {
2093
+ const ids = new Set(
2094
+ requested.map((name) => {
2095
+ const id = name.trim().toLowerCase();
2096
+ return Object.hasOwn(aliases, id) ? aliases[id] : id;
2097
+ })
2098
+ );
2099
+ return [...ids].map((id) => {
2100
+ const harness = harnesses.find((candidate) => candidate.id === id);
2101
+ if (!harness) {
2102
+ throw new Error(
2103
+ `Unsupported MCP harness '${id}' on ${process.platform}. Choose: ${harnesses.map((candidate) => candidate.id).join(", ")}.`
2104
+ );
2105
+ }
2106
+ return harness;
2107
+ });
2108
+ }
2109
+ const detected = detectMcpHarnesses();
2110
+ if (detected.length === 0) {
2111
+ throw new Error(
2112
+ `No supported MCP harness was detected. Specify a harness: ${harnesses.map((harness) => harness.id).join(", ")}.`
2113
+ );
2114
+ }
2115
+ return detected;
2116
+ }
2117
+ function docsEntry(harness) {
2118
+ if (harness.id === "claude-desktop") {
2119
+ return process.platform === "win32" ? {
2120
+ command: "cmd.exe",
2121
+ args: ["/d", "/c", "npx", "-y", "mcp-remote", DOCS_URL]
2122
+ } : { command: "npx", args: ["-y", "mcp-remote", DOCS_URL] };
2123
+ }
2124
+ return {
2125
+ ...harness.id === "cursor" ? {} : { type: "http" },
2126
+ url: DOCS_URL
2127
+ };
2128
+ }
2129
+ function isOrchestrationEntry(entry) {
2130
+ if (!isRecord(entry) || !Array.isArray(entry.args)) return false;
2131
+ const [script, command, flag, profile] = entry.args;
2132
+ return typeof entry.command === "string" && ["node", "node.exe"].includes(basename2(entry.command)) && entry.args.length === 4 && typeof script === "string" && ["index.js", "index.ts"].includes(basename2(script)) && command === "mcp-proxy" && flag === "--profile" && typeof profile === "string" && isRecord(entry.env) && typeof entry.env.C8CTL_DATA_DIR === "string";
2133
+ }
2134
+ function updateManagedEntry({
2135
+ content,
2136
+ path,
2137
+ current,
2138
+ expected
2139
+ }) {
2140
+ const formattingOptions = {
2141
+ insertSpaces: true,
2142
+ tabSize: 2,
2143
+ eol: content.includes("\r\n") ? "\r\n" : "\n"
2144
+ };
2145
+ const edit = (keyPath, value) => {
2146
+ content = applyEdits(
2147
+ content,
2148
+ modify(content, keyPath, value, { formattingOptions })
2149
+ );
2150
+ };
2151
+ for (const [key, value] of Object.entries(expected)) {
2152
+ const currentEnv = isRecord(current.env) ? current.env : void 0;
2153
+ if (key === "env" && isRecord(value) && currentEnv) {
2154
+ for (const [envKey, envValue] of Object.entries(value)) {
2155
+ if (!isDeepStrictEqual(currentEnv[envKey], envValue)) {
2156
+ edit([...path, "env", envKey], envValue);
2157
+ }
2158
+ }
2159
+ continue;
2160
+ }
2161
+ if (!isDeepStrictEqual(current[key], value)) edit([...path, key], value);
2162
+ }
2163
+ if (Object.hasOwn(current, "type") && !Object.hasOwn(expected, "type")) {
2164
+ edit([...path, "type"], void 0);
2165
+ }
2166
+ return content;
2167
+ }
2168
+ function readOptionalFile(path) {
2169
+ try {
2170
+ return readFileSync3(path, "utf8");
2171
+ } catch (error) {
2172
+ if (isRecord(error) && error.code === "ENOENT") return void 0;
2173
+ throw error;
2174
+ }
2175
+ }
2176
+ function matchesServerConfig(current, expected) {
2177
+ return isRecord(current) && Object.entries(expected).every(
2178
+ ([key, value]) => Object.hasOwn(current, key) && (isRecord(value) ? matchesServerConfig(current[key], value) : isDeepStrictEqual(current[key], value))
2179
+ );
2180
+ }
2181
+ function planMcpConfigs({
2182
+ requested,
2183
+ operation,
2184
+ docs,
2185
+ orchestration,
2186
+ alias,
2187
+ connection,
2188
+ preserveConflicts = false,
2189
+ onError
2190
+ }) {
2191
+ const plans = [];
2192
+ const plansByTarget = /* @__PURE__ */ new Map();
2193
+ for (const harness of selectHarnesses(requested)) {
2194
+ try {
2195
+ const path = resolve2(harness.path);
2196
+ const existing = lstatSync3(path, { throwIfNoEntry: false });
2197
+ const targetPath = existing ? realpathSync2(path) : path;
2198
+ const previous = plansByTarget.get(targetPath);
2199
+ const original = previous ? previous.original : readOptionalFile(targetPath);
2200
+ let content = previous ? previous.content : original ?? "{}\n";
2201
+ const errors = [];
2202
+ const parseOptions = {
2203
+ disallowComments: harness.id !== "vscode",
2204
+ allowTrailingComma: harness.id === "vscode"
2205
+ };
2206
+ const root = parseTree2(content, errors, parseOptions);
2207
+ if (errors.length > 0 || !root || root.type !== "object") {
2208
+ throw new Error(
2209
+ `Invalid MCP config in ${path}. Repair it before continuing.`
2210
+ );
2211
+ }
2212
+ const config = parse2(content, void 0, parseOptions);
2213
+ if (!isRecord(config)) throw new Error(`Expected an object in ${path}.`);
2214
+ const servers = Object.hasOwn(config, harness.key) ? config[harness.key] : {};
2215
+ if (!isRecord(servers)) {
2216
+ throw new Error(
2217
+ `Expected '${harness.key}' to be an object in ${path}.`
2218
+ );
2219
+ }
2220
+ for (const node of [root, findNodeAtLocation2(root, [harness.key])]) {
2221
+ const keys = node?.children?.map((property) => property.children?.[0]?.value) ?? [];
2222
+ if (new Set(keys).size !== keys.length) {
2223
+ throw new Error(
2224
+ `Duplicate configuration keys in ${path}. Repair them before continuing.`
2225
+ );
2226
+ }
2227
+ }
2228
+ const entries = [];
2229
+ if (orchestration) {
2230
+ entries.push({
2231
+ name: alias,
2232
+ config: {
2233
+ ...harness.stdioType ? { type: harness.stdioType } : {},
2234
+ ...connection
2235
+ },
2236
+ docs: false
2237
+ });
2238
+ }
2239
+ if (docs)
2240
+ entries.push({
2241
+ name: "camunda-docs",
2242
+ config: docsEntry(harness),
2243
+ docs: true
2244
+ });
2245
+ const changes = entries.map((entry) => {
2246
+ const present = Object.hasOwn(servers, entry.name);
2247
+ const current = servers[entry.name];
2248
+ const matches = operation === "uninstall" && !entry.docs ? isOrchestrationEntry(current) : matchesServerConfig(current, entry.config);
2249
+ const owned = !entry.docs && isOrchestrationEntry(current);
2250
+ if (present && !matches && !(operation === "install" && owned)) {
2251
+ if (operation === "uninstall" && preserveConflicts) {
2252
+ return { server: entry.name, status: "preserved" };
2253
+ }
2254
+ throw new Error(
2255
+ `MCP entry '${entry.name}' conflicts in ${path}. Inspect it before changing it${entry.docs ? "." : ", or choose another --alias."}`
2256
+ );
2257
+ }
2258
+ const status = operation === "install" ? !present ? "installed" : matches ? "unchanged" : "updated" : present ? "removed" : "absent";
2259
+ if (status === "updated") {
2260
+ content = updateManagedEntry({
2261
+ content,
2262
+ path: [harness.key, entry.name],
2263
+ current: isRecord(current) ? current : {},
2264
+ expected: entry.config
2265
+ });
2266
+ } else if (status === "installed" || status === "removed") {
2267
+ content = applyEdits(
2268
+ content,
2269
+ modify(
2270
+ content,
2271
+ [harness.key, entry.name],
2272
+ operation === "install" ? entry.config : void 0,
2273
+ {
2274
+ formattingOptions: {
2275
+ insertSpaces: true,
2276
+ tabSize: 2,
2277
+ eol: content.includes("\r\n") ? "\r\n" : "\n"
2278
+ }
2279
+ }
2280
+ )
2281
+ );
2282
+ }
2283
+ return {
2284
+ server: entry.name,
2285
+ status,
2286
+ ...operation === "install" ? { config: entry.config } : {}
2287
+ };
2288
+ });
2289
+ const mode = previous?.mode ?? (existing ? statSync3(targetPath).mode & 384 : 384);
2290
+ const plan = {
2291
+ harness: harness.id,
2292
+ path,
2293
+ targetPath,
2294
+ original,
2295
+ content,
2296
+ mode,
2297
+ changes
2298
+ };
2299
+ const target = previous ?? {
2300
+ original,
2301
+ content,
2302
+ mode,
2303
+ plans: []
2304
+ };
2305
+ target.content = content;
2306
+ target.plans.push(plan);
2307
+ plansByTarget.set(targetPath, target);
2308
+ plans.push(plan);
2309
+ } catch (error) {
2310
+ if (!onError) throw error;
2311
+ onError(harness.id, error);
2312
+ }
2313
+ }
2314
+ for (const target of plansByTarget.values()) {
2315
+ for (const plan of target.plans) plan.content = target.content;
2316
+ }
2317
+ return plans;
2318
+ }
2319
+ function acquireConfigLock(targetPath, timeoutMs, retryMs) {
2320
+ const lockPath = `${targetPath}.lock`;
2321
+ const deadline = Date.now() + timeoutMs;
2322
+ const waitSlot = new Int32Array(new SharedArrayBuffer(4));
2323
+ for (; ; ) {
2324
+ try {
2325
+ closeSync2(openSync2(lockPath, "wx", 384));
2326
+ return lockPath;
2327
+ } catch (error) {
2328
+ if (!(isRecord(error) && error.code === "EEXIST")) throw error;
2329
+ if (Date.now() >= deadline) {
2330
+ throw new Error(
2331
+ `Another c8ctl process is updating ${targetPath}. Retry shortly, or remove the stale lock ${lockPath} if that process crashed.`
2332
+ );
2333
+ }
2334
+ Atomics.wait(waitSlot, 0, 0, retryMs);
2335
+ }
2336
+ }
2337
+ }
2338
+ function writeMcpConfig(plan, options) {
2339
+ if (!plan.changes.some(
2340
+ (change) => change.status === "installed" || change.status === "updated" || change.status === "removed"
2341
+ ))
2342
+ return;
2343
+ mkdirSync2(dirname3(plan.targetPath), { recursive: true });
2344
+ const lockPath = acquireConfigLock(
2345
+ plan.targetPath,
2346
+ options?.lockTimeoutMs ?? 5e3,
2347
+ options?.lockRetryMs ?? 50
2348
+ );
2349
+ try {
2350
+ const temp = `${plan.targetPath}.${randomUUID2()}.tmp`;
2351
+ let fd;
2352
+ let created = false;
2353
+ try {
2354
+ fd = openSync2(temp, "wx", 384);
2355
+ created = true;
2356
+ writeFileSync2(fd, plan.content, "utf8");
2357
+ if (process.platform !== "win32") fchmodSync2(fd, plan.mode);
2358
+ fsyncSync(fd);
2359
+ closeSync2(fd);
2360
+ fd = void 0;
2361
+ const current = readOptionalFile(plan.targetPath);
2362
+ if (current === plan.content) return;
2363
+ if (current !== plan.original) {
2364
+ throw new Error(
2365
+ `MCP config changed during installation: ${plan.path}. Run the command again.`
2366
+ );
2367
+ }
2368
+ renameSync2(temp, plan.targetPath);
2369
+ } finally {
2370
+ if (fd !== void 0) closeSync2(fd);
2371
+ if (created) rmSync3(temp, { force: true });
2372
+ }
2373
+ } finally {
2374
+ rmSync3(lockPath, { force: true });
2375
+ }
2376
+ }
2377
+
2378
+ // default-plugins/mcp/c8ctl-plugin.ts
2379
+ var metadata = {
2380
+ name: "mcp",
2381
+ description: "Install or uninstall Camunda MCP connections in AI harnesses",
2382
+ commands: {
2383
+ mcp: {
2384
+ description: "Install or uninstall Camunda MCP connections in AI harnesses",
2385
+ helpDescription: `Configure user-scoped Camunda orchestration and docs MCP servers.
2386
+
2387
+ Harnesses: claude-code, github-copilot, cursor, vscode, claude-desktop (macOS/Windows).
2388
+ Omit harness names to configure all detected supported harnesses.
2389
+ Aliases: claude = claude-code, copilot = github-copilot, code = vscode.
2390
+ Targets: orchestration by default; --docs selects only docs; --docs --orchestration selects both.
2391
+ Orchestration references --profile, the active saved profile, or the default local profile; credentials are not copied.
2392
+ Docs uses camunda-docs, needs no cluster profile, and requires sign-in on first use.
2393
+ Claude Desktop docs uses npx mcp-remote; other harnesses connect over HTTP.
2394
+ VS Code's editor-managed config uses servers. For the newer Copilot harness, select github-copilot.
2395
+ On uninstall, --preserve-conflicts leaves entries that no longer match the c8ctl-managed shape untouched instead of failing.
2396
+ --dry-run previews selected entries without writing or exposing unrelated config values.`,
2397
+ subcommands: [
2398
+ {
2399
+ name: "install",
2400
+ description: "Install MCP connections for detected or named harnesses"
2401
+ },
2402
+ {
2403
+ name: "uninstall",
2404
+ description: "Remove MCP connections from detected or named harnesses"
2405
+ }
2406
+ ],
2407
+ examples: [
2408
+ {
2409
+ command: "c8ctl mcp install",
2410
+ description: "Install orchestration MCP for detected harnesses"
2411
+ },
2412
+ {
2413
+ command: "c8ctl mcp install --docs",
2414
+ description: "Install only docs MCP for detected harnesses"
2415
+ },
2416
+ {
2417
+ command: "c8ctl mcp install claude-code cursor --docs --orchestration",
2418
+ description: "Install both MCP servers for selected harnesses"
2419
+ },
2420
+ {
2421
+ command: "c8ctl mcp uninstall claude-code --docs",
2422
+ description: "Remove only the docs MCP entry"
2423
+ }
2424
+ ]
2425
+ }
2426
+ }
2427
+ };
2428
+ var CLI_ENTRY = (() => {
2429
+ const dir = realpathSync3(import.meta.dirname);
2430
+ const candidates = [
2431
+ resolve3(dir, "..", "..", "index.js"),
2432
+ resolve3(dir, "..", "..", "src", "index.ts")
2433
+ ];
2434
+ return candidates.find((candidate) => existsSync4(candidate)) ?? candidates[0];
2435
+ })();
2436
+ function buildMcpConnection(profile) {
2437
+ if (profile === void 0 && resolveEnvBaseUrl()) {
2438
+ throw new Error(
2439
+ "MCP installation requires a saved profile. Save your environment with 'c8ctl add profile <name> --from-env', then pass --profile <name>."
2440
+ );
2441
+ }
2442
+ const name = profile ?? DEFAULT_PROFILE;
2443
+ const resolved = getProfileOrModeler(name);
2444
+ if (!resolved) {
2445
+ throw new Error(
2446
+ `Profile '${name}' not found. Run 'c8ctl list profiles' and select one with --profile.`
2447
+ );
2448
+ }
2449
+ const entry = {
2450
+ command: process.execPath,
2451
+ args: [CLI_ENTRY, "mcp-proxy", "--profile", resolved.name],
2452
+ env: {
2453
+ C8CTL_DATA_DIR: resolve3(getUserDataDir()),
2454
+ ...resolved.name.startsWith("modeler:") ? { C8CTL_MODELER_DIR: resolve3(getModelerDataDir()) } : {}
2455
+ }
2456
+ };
2457
+ if ([entry.command, ...entry.args, ...Object.values(entry.env)].some(
2458
+ (value) => value.includes("${")
2459
+ )) {
2460
+ throw new Error(
2461
+ `MCP harnesses expand \${...} placeholders. Use a profile name and Node.js, c8ctl, and data-directory paths without that syntax.`
2462
+ );
2463
+ }
2464
+ return entry;
2465
+ }
2466
+ function targets({
2467
+ docs,
2468
+ orchestration,
2469
+ alias,
2470
+ aliasProvided
2471
+ }) {
2472
+ const selectedDocs = docs;
2473
+ const selectedOrchestration = orchestration || !docs;
2474
+ if (aliasProvided && !selectedOrchestration) {
2475
+ throw new Error(
2476
+ "--alias applies to orchestration. Add --orchestration or omit --alias."
2477
+ );
2478
+ }
2479
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(alias) || alias === "camunda-docs") {
2480
+ throw new Error(
2481
+ "Use an orchestration alias containing letters, digits, underscores or hyphens, starting with a letter or digit. 'camunda-docs' is reserved."
2482
+ );
2483
+ }
2484
+ return { docs: selectedDocs, orchestration: selectedOrchestration, alias };
2485
+ }
2486
+ function applyPlans({
2487
+ ctx,
2488
+ plans,
2489
+ operation
2490
+ }) {
2491
+ const { logger } = ctx;
2492
+ if (ctx.dryRun) {
2493
+ logger.json({
2494
+ dryRun: true,
2495
+ command: `mcp ${operation}`,
2496
+ changes: plans.flatMap(
2497
+ (plan) => plan.changes.map((change) => ({
2498
+ harness: plan.harness,
2499
+ path: plan.path,
2500
+ ...change
2501
+ }))
2502
+ )
2503
+ });
2504
+ return;
2505
+ }
2506
+ for (const plan of plans) {
2507
+ writeMcpConfig(plan);
2508
+ logger.info(`MCP configuration: ${plan.harness} (${plan.path})`);
2509
+ }
2510
+ if (operation === "install") {
2511
+ logger.info("Restart or reload the selected harnesses to activate MCP.");
2512
+ if (plans.some(
2513
+ (plan) => plan.changes.some((change) => change.server === "camunda-docs")
2514
+ )) {
2515
+ logger.info("The docs server requires sign-in on first use.");
2516
+ }
2517
+ }
2518
+ const items = plans.flatMap(
2519
+ (plan) => plan.changes.map(({ server, status }) => ({
2520
+ harness: plan.harness,
2521
+ server,
2522
+ status,
2523
+ path: plan.path
2524
+ }))
2525
+ );
2526
+ if (items.length > 0) {
2527
+ logger.table(items);
2528
+ } else {
2529
+ logger.info("No MCP entries selected.", { essential: true });
2530
+ }
2531
+ }
2532
+ async function mcpHandler(args, flags, ctx) {
2533
+ if (!ctx) throw new Error("mcp requires the plugin host context");
2534
+ const { logger } = ctx;
2535
+ const operation = args[0];
2536
+ if (operation !== "install" && operation !== "uninstall") {
2537
+ if (operation === void 0) {
2538
+ logger.info(
2539
+ "\nUsage: c8ctl mcp install|uninstall [harness...]\n\nAvailable resources:\n install\n uninstall",
2540
+ { essential: true }
2541
+ );
2542
+ } else {
2543
+ logger.error(`Unknown command: mcp ${args.join(" ")}`);
2544
+ logger.info('Run "c8 help" for usage information', { essential: true });
2545
+ }
2546
+ process.exitCode = 1;
2547
+ return;
2548
+ }
2549
+ try {
2550
+ const rawAlias = flags?.alias;
2551
+ if (rawAlias !== void 0 && (typeof rawAlias !== "string" || rawAlias === "")) {
2552
+ logger.error("Invalid --alias: value must not be empty");
2553
+ process.exitCode = 1;
2554
+ return;
2555
+ }
2556
+ const selected = targets({
2557
+ docs: flags?.docs === true,
2558
+ orchestration: flags?.orchestration === true,
2559
+ alias: rawAlias ?? "camunda",
2560
+ aliasProvided: rawAlias !== void 0
2561
+ });
2562
+ const plans = planMcpConfigs({
2563
+ requested: args.slice(1),
2564
+ operation,
2565
+ ...selected,
2566
+ preserveConflicts: flags?.["preserve-conflicts"] === true,
2567
+ connection: operation === "install" && selected.orchestration ? buildMcpConnection(ctx.profile) : void 0
2568
+ });
2569
+ applyPlans({ ctx, plans, operation });
2570
+ } catch (error) {
2571
+ renderCommandFailure(logger, `Failed to mcp ${operation}`, error, {
2572
+ verbose: ctx.verbose
2573
+ });
2574
+ process.exitCode = 1;
2575
+ }
2576
+ }
2577
+ var commands = {
2578
+ mcp: {
2579
+ flags: {
2580
+ orchestration: {
2581
+ type: "boolean",
2582
+ description: "Select the orchestration MCP server (default when --docs is absent)"
2583
+ },
2584
+ docs: {
2585
+ type: "boolean",
2586
+ description: "Select the Camunda docs MCP server; combine with --orchestration for both"
2587
+ },
2588
+ alias: {
2589
+ type: "string",
2590
+ rejectEmpty: true,
2591
+ description: "Orchestration server entry name (default: camunda)"
2592
+ },
2593
+ "preserve-conflicts": {
2594
+ type: "boolean",
2595
+ description: "On uninstall, leave conflicting foreign entries untouched instead of failing"
2596
+ }
2597
+ },
2598
+ handler: mcpHandler
2599
+ }
2600
+ };
2601
+ export {
2602
+ commands,
2603
+ metadata
2604
+ };