gdharness 1.1.30 → 1.1.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -10236,17 +10236,17 @@ import {
10236
10236
  closeSync as closeSync2,
10237
10237
  constants,
10238
10238
  copyFileSync,
10239
- existsSync as existsSync14,
10239
+ existsSync as existsSync16,
10240
10240
  fstatSync,
10241
- mkdirSync as mkdirSync10,
10241
+ mkdirSync as mkdirSync11,
10242
10242
  openSync as openSync3,
10243
10243
  readdirSync as readdirSync8,
10244
- readFileSync as readFileSync18,
10244
+ readFileSync as readFileSync19,
10245
10245
  readSync as readSync2,
10246
10246
  rmdirSync as rmdirSync2,
10247
10247
  statSync as statSync8
10248
10248
  } from "node:fs";
10249
- import { basename as basename4, dirname as dirname12, extname as extname2, isAbsolute as isAbsolute3, join as join19, normalize as normalize2, relative as relative3 } from "node:path";
10249
+ import { basename as basename5, dirname as dirname14, extname as extname2, isAbsolute as isAbsolute3, join as join20, normalize as normalize2, relative as relative4 } from "node:path";
10250
10250
  import { setTimeout as delay3 } from "node:timers/promises";
10251
10251
  import { fileURLToPath as fileURLToPath4 } from "node:url";
10252
10252
  import { promisify as promisify5 } from "node:util";
@@ -25284,6 +25284,27 @@ function ancestorsIn(tree, pid, root) {
25284
25284
  }
25285
25285
  return chain;
25286
25286
  }
25287
+ var ONE_SHOT_OPTIONS = [
25288
+ "--import",
25289
+ "--quit",
25290
+ "--quit-after",
25291
+ "--export-release",
25292
+ "--export-debug",
25293
+ "--export-pack",
25294
+ "--export-patch",
25295
+ "--doctool",
25296
+ "--gdscript-docs",
25297
+ "--script",
25298
+ "-s",
25299
+ "--check-only",
25300
+ "--build-solutions",
25301
+ "--dump-gdextension-interface",
25302
+ "--dump-extension-api",
25303
+ "--dump-extension-api-with-docs",
25304
+ "--validate-extension-api",
25305
+ "--convert-3to4",
25306
+ "--validate-conversion-3to4"
25307
+ ];
25287
25308
  function readCommandLine(command) {
25288
25309
  const all = commandWords(command);
25289
25310
  const separator = all.findIndex((word) => word === "--" || word === "++");
@@ -25304,9 +25325,18 @@ function readCommandLine(command) {
25304
25325
  return {
25305
25326
  executable,
25306
25327
  projectPath,
25307
- editor: words.some((word) => word === "-e" || word === "--editor")
25328
+ editor: words.some((word) => word === "-e" || word === "--editor"),
25329
+ oneShot: words.find((word) => ONE_SHOT_OPTIONS.includes(word)) ?? null
25308
25330
  };
25309
25331
  }
25332
+ async function oneShotOptionOf(pid) {
25333
+ const tree = await processTree();
25334
+ const listed = tree?.get(pid);
25335
+ if (listed === undefined || listed.command === "") {
25336
+ return;
25337
+ }
25338
+ return readCommandLine(listed.command).oneShot;
25339
+ }
25310
25340
  function commandWords(command) {
25311
25341
  const words = [];
25312
25342
  let word = "";
@@ -26075,6 +26105,397 @@ function callSignal() {
26075
26105
  // src/class-cache.ts
26076
26106
  import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync7, statSync as statSync2 } from "node:fs";
26077
26107
  import { join as join6 } from "node:path";
26108
+
26109
+ // src/gdscript-source.ts
26110
+ var IDENTIFIER_START = /[\p{L}_]/u;
26111
+ var IDENTIFIER_PART = /[\p{L}\p{N}_]/u;
26112
+ function isIdentifierStart(character) {
26113
+ return character !== undefined && IDENTIFIER_START.test(character);
26114
+ }
26115
+ function isIdentifierPart(character) {
26116
+ return character !== undefined && IDENTIFIER_PART.test(character);
26117
+ }
26118
+ function percentIsUniqueNode(source, at) {
26119
+ const next = source[at + 1];
26120
+ if (!isIdentifierStart(next) && next !== '"' && next !== "'") {
26121
+ return false;
26122
+ }
26123
+ let back = at - 1;
26124
+ while (back >= 0 && (source[back] === " " || source[back] === "\t")) {
26125
+ back -= 1;
26126
+ }
26127
+ const before = source[back];
26128
+ if (before === undefined || before === `
26129
+ `) {
26130
+ return true;
26131
+ }
26132
+ if (isIdentifierPart(before) || before === ")" || before === "]" || before === '"' || before === "'") {
26133
+ let wordStart = back;
26134
+ while (wordStart > 0 && isIdentifierPart(source[wordStart - 1])) {
26135
+ wordStart -= 1;
26136
+ }
26137
+ const word = source.slice(wordStart, back + 1);
26138
+ return ["return", "and", "or", "not", "in", "is", "as", "if", "elif", "else", "while", "await"].includes(word);
26139
+ }
26140
+ return true;
26141
+ }
26142
+ function stringEnd(source, at) {
26143
+ const quote = source[at] ?? '"';
26144
+ const fence = source.startsWith(quote.repeat(3), at) ? quote.repeat(3) : quote;
26145
+ let end = at + fence.length;
26146
+ while (end < source.length && !source.startsWith(fence, end)) {
26147
+ if (fence.length === 1 && source[end] === `
26148
+ `) {
26149
+ return end;
26150
+ }
26151
+ end += source[end] === "\\" ? 2 : 1;
26152
+ }
26153
+ return Math.min(end + fence.length, source.length);
26154
+ }
26155
+ function regionsOf(source) {
26156
+ const regions = [];
26157
+ let codeStart = 0;
26158
+ let at = 0;
26159
+ const close = (kind, start, end) => {
26160
+ if (codeStart < start) {
26161
+ regions.push({ kind: "code", start: codeStart, end: start });
26162
+ }
26163
+ regions.push({ kind, start, end });
26164
+ codeStart = end;
26165
+ at = end;
26166
+ };
26167
+ while (at < source.length) {
26168
+ const here = source[at];
26169
+ if (here === "#") {
26170
+ const lineEnd = source.indexOf(`
26171
+ `, at);
26172
+ const end = lineEnd === -1 ? source.length : lineEnd;
26173
+ const lineStart = source.lastIndexOf(`
26174
+ `, at - 1) + 1;
26175
+ const alone = source.slice(lineStart, at).trim() === "";
26176
+ close(alone && source.startsWith("##", at) ? "doc" : "comment", at, end);
26177
+ continue;
26178
+ }
26179
+ if (here === '"' || here === "'") {
26180
+ const prefixed = at > 0 && ["r", "&", "^"].includes(source[at - 1] ?? "") && !isIdentifierPart(source[at - 2]);
26181
+ const start = prefixed ? at - 1 : at;
26182
+ const dollar = source[start - 1] === "$" || source[start - 1] === "%" && percentIsUniqueNode(source, start - 1);
26183
+ close(dollar ? "nodePath" : "string", dollar ? start - 1 : start, stringEnd(source, at));
26184
+ continue;
26185
+ }
26186
+ if (here === "$" || here === "%" && percentIsUniqueNode(source, at)) {
26187
+ if (source[at + 1] === '"' || source[at + 1] === "'") {
26188
+ at += 1;
26189
+ continue;
26190
+ }
26191
+ let end = at + 1;
26192
+ while (end < source.length && (isIdentifierPart(source[end]) || source[end] === "/" || source[end] === "%")) {
26193
+ end += 1;
26194
+ }
26195
+ if (end > at + 1) {
26196
+ close("nodePath", at, end);
26197
+ continue;
26198
+ }
26199
+ }
26200
+ if (isIdentifierStart(here)) {
26201
+ while (at < source.length && isIdentifierPart(source[at])) {
26202
+ at += 1;
26203
+ }
26204
+ continue;
26205
+ }
26206
+ at += 1;
26207
+ }
26208
+ if (codeStart < source.length) {
26209
+ regions.push({ kind: "code", start: codeStart, end: source.length });
26210
+ }
26211
+ return regions;
26212
+ }
26213
+ function codeOf(source, regions = regionsOf(source)) {
26214
+ let code = "";
26215
+ for (const region of regions) {
26216
+ const text = source.slice(region.start, region.end);
26217
+ code += region.kind === "code" ? text : text.replace(/[^\n]/g, " ");
26218
+ }
26219
+ return code;
26220
+ }
26221
+
26222
+ class Lines {
26223
+ starts = [0];
26224
+ text;
26225
+ constructor(text) {
26226
+ this.text = text;
26227
+ for (let at = text.indexOf(`
26228
+ `);at !== -1; at = text.indexOf(`
26229
+ `, at + 1)) {
26230
+ this.starts.push(at + 1);
26231
+ }
26232
+ }
26233
+ positionOf(offset) {
26234
+ let low = 0;
26235
+ let high = this.starts.length - 1;
26236
+ while (low < high) {
26237
+ const middle = low + high + 1 >> 1;
26238
+ if ((this.starts[middle] ?? 0) <= offset) {
26239
+ low = middle;
26240
+ } else {
26241
+ high = middle - 1;
26242
+ }
26243
+ }
26244
+ return { line: low, character: offset - (this.starts[low] ?? 0) };
26245
+ }
26246
+ offsetOf(position) {
26247
+ const start = this.starts[position.line];
26248
+ if (start === undefined) {
26249
+ return null;
26250
+ }
26251
+ const offset = start + position.character;
26252
+ return offset > this.text.length ? null : offset;
26253
+ }
26254
+ lineAt(offset) {
26255
+ const { line } = this.positionOf(offset);
26256
+ const start = this.starts[line] ?? 0;
26257
+ const end = this.starts[line + 1] ?? this.text.length + 1;
26258
+ return this.text.slice(start, end - 1).replace(/\r$/, "");
26259
+ }
26260
+ }
26261
+ var DECLARING = new Set(["var", "const", "func", "signal", "enum", "class", "for", "class_name"]);
26262
+ function escapedForPattern(text) {
26263
+ return text.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
26264
+ }
26265
+ function wholeWord(name, flags = "gu") {
26266
+ return new RegExp(`(?<![\\p{L}\\p{N}_])${escapedForPattern(name)}(?![\\p{L}\\p{N}_])`, flags);
26267
+ }
26268
+ function occurrencesOf(source, name, regions = regionsOf(source)) {
26269
+ const found = [];
26270
+ let index = 0;
26271
+ for (const match of source.matchAll(wholeWord(name))) {
26272
+ const offset = match.index;
26273
+ while (index < regions.length - 1 && (regions[index]?.end ?? 0) <= offset) {
26274
+ index += 1;
26275
+ }
26276
+ const kind = regions[index]?.kind ?? "code";
26277
+ let afterDot = false;
26278
+ let declaredAs = null;
26279
+ if (kind === "code") {
26280
+ let back = offset - 1;
26281
+ while (back >= 0 && /[\s\\]/.test(source[back] ?? "")) {
26282
+ back -= 1;
26283
+ }
26284
+ afterDot = source[back] === "." && source[back - 1] !== ".";
26285
+ let wordStart = back + 1;
26286
+ while (wordStart > 0 && isIdentifierPart(source[wordStart - 1])) {
26287
+ wordStart -= 1;
26288
+ }
26289
+ const word = source.slice(wordStart, back + 1);
26290
+ declaredAs = DECLARING.has(word) ? word : null;
26291
+ }
26292
+ found.push({ offset, kind, afterDot, declaredAs });
26293
+ }
26294
+ return found;
26295
+ }
26296
+ var NAME = "[\\p{L}_][\\p{L}\\p{N}_]*";
26297
+ var ANNOTATIONS = "(?:@[\\p{L}_][\\p{L}\\p{N}_]*(?:\\([^)]*\\))?\\s+)*";
26298
+ var DECLARATION_LINE = new RegExp(`^(${ANNOTATIONS})(static\\s+)?(func|var|const|signal|enum|class)\\s+(${NAME})`, "u");
26299
+ var CLASS_NAME_LINE = new RegExp(`^${ANNOTATIONS}class_name\\s+(${NAME})`, "u");
26300
+ var EXTENDS_LINE = new RegExp(`^${ANNOTATIONS}(?:class_name\\s+${NAME}\\s+)?extends\\s`, "u");
26301
+ var EXTENDS_CLAUSE = /\bextends(?=\s)/u;
26302
+ function extendsTarget(source, code, after) {
26303
+ let from = after;
26304
+ while (source[from] === " " || source[from] === "\t") {
26305
+ from += 1;
26306
+ }
26307
+ const quote = source[from];
26308
+ if (quote === '"' || quote === "'") {
26309
+ const end = source.indexOf(quote, from + 1);
26310
+ return end === -1 ? null : source.slice(from, end + 1);
26311
+ }
26312
+ const dotted = new RegExp(`^${NAME}(?:\\.${NAME})*`, "u").exec(code.slice(from));
26313
+ return dotted?.[0] ?? null;
26314
+ }
26315
+ function shapeOf(source) {
26316
+ const regions = regionsOf(source);
26317
+ const code = codeOf(source, regions);
26318
+ const lines = [];
26319
+ let start = 0;
26320
+ for (const text of code.split(`
26321
+ `)) {
26322
+ const indent = /^[ \t]*/.exec(text)?.[0].length ?? 0;
26323
+ lines.push({ start, text, indent });
26324
+ start += text.length + 1;
26325
+ }
26326
+ let className = null;
26327
+ const parseBody = (name, extendsAs, from, indent, bodyStart) => {
26328
+ const declarations = [];
26329
+ const inner = [];
26330
+ let index = from;
26331
+ let openEnum = null;
26332
+ let topExtends = extendsAs;
26333
+ while (index < lines.length) {
26334
+ const line = lines[index];
26335
+ if (line === undefined) {
26336
+ break;
26337
+ }
26338
+ if (openEnum !== null) {
26339
+ openEnum.text += `
26340
+ ${line.text}`;
26341
+ if (line.text.includes("}")) {
26342
+ collectEnumValues(openEnum.text, openEnum.from, declarations);
26343
+ openEnum = null;
26344
+ }
26345
+ index += 1;
26346
+ continue;
26347
+ }
26348
+ if (line.text.trim() === "") {
26349
+ index += 1;
26350
+ continue;
26351
+ }
26352
+ if (line.indent < indent) {
26353
+ break;
26354
+ }
26355
+ if (line.indent > indent) {
26356
+ index += 1;
26357
+ continue;
26358
+ }
26359
+ const body = line.text.slice(line.indent);
26360
+ const at = line.start + line.indent;
26361
+ if (name === null) {
26362
+ const declared = CLASS_NAME_LINE.exec(body);
26363
+ if (declared?.[1] !== undefined) {
26364
+ className = { name: declared[1], offset: at + declared[0].length - declared[1].length };
26365
+ }
26366
+ if (EXTENDS_LINE.test(body) || CLASS_NAME_LINE.test(body)) {
26367
+ const clause = EXTENDS_CLAUSE.exec(body);
26368
+ if (clause !== null && topExtends === null) {
26369
+ topExtends = extendsTarget(source, code, at + clause.index + clause[0].length);
26370
+ }
26371
+ }
26372
+ }
26373
+ const declared = DECLARATION_LINE.exec(body);
26374
+ if (declared !== null) {
26375
+ const [whole, , isStatic, keyword, declaredName] = declared;
26376
+ if (keyword !== undefined && declaredName !== undefined) {
26377
+ const offset = at + whole.length - declaredName.length;
26378
+ const kind = keyword;
26379
+ declarations.push({ name: declaredName, kind, offset, isStatic: isStatic !== undefined });
26380
+ if (kind === "enum") {
26381
+ const brace = body.indexOf("{");
26382
+ if (brace !== -1) {
26383
+ openEnum = { from: at + brace, text: body.slice(brace) };
26384
+ if (body.includes("}", brace)) {
26385
+ collectEnumValues(openEnum.text, openEnum.from, declarations);
26386
+ openEnum = null;
26387
+ }
26388
+ }
26389
+ }
26390
+ if (kind === "class") {
26391
+ const rest = body.slice(whole.length);
26392
+ const clause = EXTENDS_CLAUSE.exec(rest);
26393
+ const innerExtends = clause === null ? null : extendsTarget(source, code, at + whole.length + clause.index + clause[0].length);
26394
+ const childIndent = lines.slice(index + 1).find((next) => next.text.trim() !== "")?.indent ?? indent + 1;
26395
+ if (childIndent > indent) {
26396
+ const parsed = parseBody(declaredName, innerExtends, index + 1, childIndent, line.start);
26397
+ inner.push(parsed.body);
26398
+ index = parsed.next;
26399
+ continue;
26400
+ }
26401
+ inner.push({
26402
+ name: declaredName,
26403
+ extendsAs: innerExtends,
26404
+ declarations: [],
26405
+ inner: [],
26406
+ start: line.start,
26407
+ end: line.start + line.text.length
26408
+ });
26409
+ }
26410
+ }
26411
+ } else if (/^enum\s*\{/u.test(body)) {
26412
+ const brace = body.indexOf("{");
26413
+ openEnum = { from: at + brace, text: body.slice(brace) };
26414
+ if (body.includes("}", brace)) {
26415
+ collectEnumValues(openEnum.text, openEnum.from, declarations);
26416
+ openEnum = null;
26417
+ }
26418
+ }
26419
+ index += 1;
26420
+ }
26421
+ const last = lines[index - 1];
26422
+ return {
26423
+ body: {
26424
+ name,
26425
+ extendsAs: topExtends,
26426
+ declarations,
26427
+ inner,
26428
+ start: bodyStart,
26429
+ end: last === undefined ? bodyStart : last.start + last.text.length
26430
+ },
26431
+ next: index
26432
+ };
26433
+ };
26434
+ const { body } = parseBody(null, null, 0, 0, 0);
26435
+ return { className, body };
26436
+ }
26437
+ function collectEnumValues(text, from, into) {
26438
+ const close = text.indexOf("}");
26439
+ const inside = text.slice(1, close === -1 ? text.length : close);
26440
+ for (const match of inside.matchAll(new RegExp(`(^|,)\\s*(${NAME})`, "gu"))) {
26441
+ const valueName = match[2];
26442
+ if (valueName === undefined) {
26443
+ continue;
26444
+ }
26445
+ const offset = from + 1 + match.index + match[0].length - valueName.length;
26446
+ into.push({ name: valueName, kind: "enumValue", offset, isStatic: true });
26447
+ }
26448
+ }
26449
+ var KEYWORDS = new Set([
26450
+ "and",
26451
+ "as",
26452
+ "assert",
26453
+ "await",
26454
+ "break",
26455
+ "breakpoint",
26456
+ "class",
26457
+ "class_name",
26458
+ "const",
26459
+ "continue",
26460
+ "elif",
26461
+ "else",
26462
+ "enum",
26463
+ "extends",
26464
+ "false",
26465
+ "for",
26466
+ "func",
26467
+ "if",
26468
+ "in",
26469
+ "is",
26470
+ "match",
26471
+ "namespace",
26472
+ "not",
26473
+ "null",
26474
+ "or",
26475
+ "pass",
26476
+ "preload",
26477
+ "return",
26478
+ "self",
26479
+ "signal",
26480
+ "static",
26481
+ "super",
26482
+ "trait",
26483
+ "true",
26484
+ "var",
26485
+ "void",
26486
+ "when",
26487
+ "while",
26488
+ "yield",
26489
+ "INF",
26490
+ "NAN",
26491
+ "PI",
26492
+ "TAU"
26493
+ ]);
26494
+ function isIdentifier(name) {
26495
+ return new RegExp(`^${NAME}$`, "u").test(name) && !KEYWORDS.has(name);
26496
+ }
26497
+
26498
+ // src/class-cache.ts
26078
26499
  var DECLARATION = /^(?:@[a-z_]+(?:\([^)\n]*\))?\s+)*class_name\s+([A-Za-z_][A-Za-z0-9_]*)/m;
26079
26500
  var TOOL = /^[ \t]*(?:@[a-z_]+(?:\([^)\n]*\))?[ \t]+)*@tool\b/m;
26080
26501
  function isToolScript(source) {
@@ -26124,33 +26545,6 @@ function scriptsNaming(projectPath, classes) {
26124
26545
  });
26125
26546
  return naming.sort((a, b) => a.script.localeCompare(b.script));
26126
26547
  }
26127
- function codeOf(source) {
26128
- let code = "";
26129
- let at = 0;
26130
- while (at < source.length) {
26131
- const here = source[at] ?? "";
26132
- if (here === "#") {
26133
- const end = source.indexOf(`
26134
- `, at);
26135
- at = end === -1 ? source.length : end;
26136
- continue;
26137
- }
26138
- if (here === '"' || here === "'") {
26139
- const fence = source.startsWith(here.repeat(3), at) ? here.repeat(3) : here;
26140
- let end = at + fence.length;
26141
- while (end < source.length && !source.startsWith(fence, end)) {
26142
- end += source[end] === "\\" ? 2 : 1;
26143
- }
26144
- const literal = source.slice(at, Math.min(end + fence.length, source.length));
26145
- code += literal.replace(/[^\n]/g, " ");
26146
- at = end + fence.length;
26147
- continue;
26148
- }
26149
- code += here;
26150
- at += 1;
26151
- }
26152
- return code;
26153
- }
26154
26548
  function cachedClasses(projectPath) {
26155
26549
  const cache = join6(projectPath, ".godot", "global_script_class_cache.cfg");
26156
26550
  if (!existsSync3(cache)) {
@@ -27463,7 +27857,7 @@ function theFirstOf(path) {
27463
27857
  var NAMED_VALUES = 6;
27464
27858
  var WALK_BACK_LIMIT = 500;
27465
27859
  var SLOTS = [/"[^"]*"/g, /'[^']*'/g, /\b(?:res|user):\/\/\S+/g, /(?<=\.gd|\.tscn|\.cs):\d+(?::\d+)?/g];
27466
- function shapeOf(text) {
27860
+ function shapeOf2(text) {
27467
27861
  const values = [];
27468
27862
  let shape = "";
27469
27863
  let at = 0;
@@ -27493,7 +27887,7 @@ function shapeOf(text) {
27493
27887
  }
27494
27888
  function bursts(entries, before, keep) {
27495
27889
  const shapes = new Map;
27496
- const shaped = entries.map((entry) => shapeOf(entry.text));
27890
+ const shaped = entries.map((entry) => shapeOf2(entry.text));
27497
27891
  for (const [at, entry] of entries.entries()) {
27498
27892
  const key = `${entry.severity}\x00${shaped[at]?.shape ?? entry.text}`;
27499
27893
  const group = shapes.get(key) ?? { indices: [], values: [] };
@@ -27664,6 +28058,7 @@ var DEFAULT_TIMEOUT_MS = 30000;
27664
28058
  var KEEPALIVE_INTERVAL_MS = 1e4;
27665
28059
  var SECOND_CONNECTION_CLOSE_CODE = 4000;
27666
28060
  var OTHER_PROJECT_CLOSE_CODE = 4001;
28061
+ var ONE_SHOT_CLOSE_CODE = 4002;
27667
28062
  function resolveDefaultBridgePort() {
27668
28063
  return portFromEnv("GDHARNESS_BRIDGE_PORT", DEFAULT_PORT);
27669
28064
  }
@@ -27695,6 +28090,9 @@ class GodotBridge extends EventEmitter {
27695
28090
  socket = null;
27696
28091
  pingInterval = null;
27697
28092
  connectionInfo = null;
28093
+ oneShotReader = null;
28094
+ oneShots = new Map;
28095
+ turnedAway = null;
27698
28096
  pendingRequests = new Map;
27699
28097
  resourceQueues = new Map;
27700
28098
  wantedPort;
@@ -27709,6 +28107,9 @@ class GodotBridge extends EventEmitter {
27709
28107
  this.timeoutMs = timeoutMs;
27710
28108
  this.ownProject = ownProject;
27711
28109
  }
28110
+ identifyEditorsWith(reader) {
28111
+ this.oneShotReader = reader;
28112
+ }
27712
28113
  get mayMove() {
27713
28114
  return this.ownProject !== null;
27714
28115
  }
@@ -27815,25 +28216,33 @@ class GodotBridge extends EventEmitter {
27815
28216
  this.log("info", "WebSocket bridge stopped");
27816
28217
  }
27817
28218
  isConnected() {
27818
- return this.socket?.readyState === import_websocket.default.OPEN;
28219
+ return this.socket?.readyState === import_websocket.default.OPEN && this.connectionInfo?.identifying !== true;
28220
+ }
28221
+ isArriving() {
28222
+ const info = this.connectionInfo;
28223
+ return this.socket?.readyState === import_websocket.default.OPEN && info !== null && (info.greeted !== true || info.identifying === true);
27819
28224
  }
27820
28225
  getStatus() {
28226
+ const identifying = this.connectionInfo?.identifying === true;
28227
+ const editor = identifying ? null : this.connectionInfo;
27821
28228
  return {
27822
28229
  host: this.host,
27823
28230
  port: this.port,
27824
28231
  connected: this.isConnected(),
27825
- projectPath: this.connectionInfo?.projectPath,
27826
- connectedAt: this.connectionInfo?.connectedAt,
27827
- lastPongAt: this.connectionInfo?.lastPongAt,
27828
- addonVersion: this.connectionInfo?.addonVersion,
27829
- addonDigest: this.connectionInfo?.addonDigest,
27830
- editorPid: this.connectionInfo?.editorPid,
27831
- lspPort: this.connectionInfo?.lspPort,
27832
- dapPort: this.connectionInfo?.dapPort,
27833
- debugPort: this.connectionInfo?.debugPort,
27834
- openedByAServer: this.connectionInfo?.openedByAServer,
27835
- startedByAnEditor: this.connectionInfo?.startedByAnEditor,
27836
- syncsBreakpoints: this.connectionInfo?.syncsBreakpoints,
28232
+ projectPath: editor?.projectPath,
28233
+ connectedAt: editor?.connectedAt,
28234
+ lastPongAt: editor?.lastPongAt,
28235
+ addonVersion: editor?.addonVersion,
28236
+ addonDigest: editor?.addonDigest,
28237
+ editorPid: editor?.editorPid,
28238
+ lspPort: editor?.lspPort,
28239
+ dapPort: editor?.dapPort,
28240
+ debugPort: editor?.debugPort,
28241
+ openedByAServer: editor?.openedByAServer,
28242
+ startedByAnEditor: editor?.startedByAnEditor,
28243
+ syncsBreakpoints: editor?.syncsBreakpoints,
28244
+ turnedAway: this.turnedAway ?? undefined,
28245
+ identifying: identifying ? true : undefined,
27837
28246
  pendingRequests: this.pendingRequests.size,
27838
28247
  queuedResources: this.resourceQueues.size,
27839
28248
  listeningSince: this.listeningSince ?? undefined,
@@ -27981,6 +28390,12 @@ class GodotBridge extends EventEmitter {
27981
28390
  this.connectionInfo.startedByAnEditor = typeof message.started_by_an_editor === "boolean" ? message.started_by_an_editor : undefined;
27982
28391
  this.connectionInfo.syncsBreakpoints = typeof message.syncs_breakpoints === "boolean" ? message.syncs_breakpoints : undefined;
27983
28392
  this.log("info", `Godot ready: ${message.project_path}`);
28393
+ this.connectionInfo.greeted = true;
28394
+ const pid = this.connectionInfo.editorPid;
28395
+ if (!this.connectionInfo.openedByAServer && pid !== undefined && this.oneShotReader !== null) {
28396
+ this.identify(pid);
28397
+ return;
28398
+ }
27984
28399
  this.emitBridgeEvent("godot_connected", { projectPath: message.project_path });
27985
28400
  }
27986
28401
  return;
@@ -28071,6 +28486,45 @@ class GodotBridge extends EventEmitter {
28071
28486
  this.stopKeepalive();
28072
28487
  stranger?.close(OTHER_PROJECT_CLOSE_CODE, said);
28073
28488
  }
28489
+ identify(pid) {
28490
+ const known = this.oneShots.get(pid);
28491
+ if (known !== undefined) {
28492
+ this.turnAway(pid, known);
28493
+ return;
28494
+ }
28495
+ const info = this.connectionInfo;
28496
+ const socket = this.socket;
28497
+ const reader = this.oneShotReader;
28498
+ if (info === null || reader === null) {
28499
+ return;
28500
+ }
28501
+ info.identifying = true;
28502
+ reader(pid).catch(() => {
28503
+ return;
28504
+ }).then((option) => {
28505
+ if (this.socket !== socket || this.connectionInfo !== info) {
28506
+ return;
28507
+ }
28508
+ if (typeof option === "string") {
28509
+ this.oneShots.set(pid, option);
28510
+ this.turnAway(pid, option);
28511
+ return;
28512
+ }
28513
+ info.identifying = false;
28514
+ this.log("info", `Godot editor identified: pid ${pid}`);
28515
+ this.emitBridgeEvent("godot_connected", { projectPath: info.projectPath });
28516
+ });
28517
+ }
28518
+ turnAway(pid, option) {
28519
+ const said = `pid ${pid} was started with ${option}, which does one job and quits, so it is not an editor`;
28520
+ this.log("info", `Turning away an engine run: ${said}`);
28521
+ this.turnedAway = { pid, option, at: new Date };
28522
+ const run = this.socket;
28523
+ this.socket = null;
28524
+ this.connectionInfo = null;
28525
+ this.stopKeepalive();
28526
+ run?.close(ONE_SHOT_CLOSE_CODE, said);
28527
+ }
28074
28528
  handleDisconnect(disconnectedSocket, reason) {
28075
28529
  if (disconnectedSocket && this.socket && disconnectedSocket !== this.socket) {
28076
28530
  this.log("debug", "Ignoring stale Godot socket disconnect event");
@@ -29539,6 +29993,39 @@ class GodotLSPClient {
29539
29993
  }
29540
29994
  });
29541
29995
  }
29996
+ async getReferences(filePath, content, line, character) {
29997
+ await this.ensureConnected();
29998
+ await this.ensureInitializedForFile(filePath);
29999
+ const result = await this.withDocument(filePath, async () => {
30000
+ const uri = this.syncDocument(filePath, content);
30001
+ try {
30002
+ return await this.sendRequest("textDocument/references", {
30003
+ textDocument: { uri },
30004
+ position: { line, character },
30005
+ context: { includeDeclaration: true }
30006
+ });
30007
+ } finally {
30008
+ this.closeDocument(uri);
30009
+ }
30010
+ });
30011
+ return locationsIn(result);
30012
+ }
30013
+ async getDefinitions(filePath, content, line, character) {
30014
+ await this.ensureConnected();
30015
+ await this.ensureInitializedForFile(filePath);
30016
+ const result = await this.withDocument(filePath, async () => {
30017
+ const uri = this.syncDocument(filePath, content);
30018
+ try {
30019
+ return await this.sendRequest("textDocument/definition", {
30020
+ textDocument: { uri },
30021
+ position: { line, character }
30022
+ });
30023
+ } finally {
30024
+ this.closeDocument(uri);
30025
+ }
30026
+ });
30027
+ return locationsIn(result);
30028
+ }
29542
30029
  async getDocumentSymbols(filePath, content) {
29543
30030
  await this.ensureConnected();
29544
30031
  await this.ensureInitializedForFile(filePath);
@@ -29558,6 +30045,22 @@ class GodotLSPClient {
29558
30045
  return this.connected;
29559
30046
  }
29560
30047
  }
30048
+ function locationsIn(result) {
30049
+ const entries = Array.isArray(result) ? result : result === null || result === undefined ? [] : [result];
30050
+ const found = [];
30051
+ for (const entry of entries) {
30052
+ const location = entry;
30053
+ const uri = location.uri ?? location.targetUri;
30054
+ const start = location.range?.start ?? location.targetSelectionRange?.start;
30055
+ if (typeof uri !== "string" || typeof start?.line !== "number" || typeof start.character !== "number") {
30056
+ continue;
30057
+ }
30058
+ try {
30059
+ found.push({ file: fileURLToPath(uri), line: start.line, character: start.character });
30060
+ } catch {}
30061
+ }
30062
+ return found;
30063
+ }
29561
30064
  function asToolResponse(payload) {
29562
30065
  return {
29563
30066
  content: [
@@ -29862,6 +30365,46 @@ function scriptsWithoutUid(projectPath) {
29862
30365
  function isBinary(bytes) {
29863
30366
  return bytes.subarray(0, 8000).includes(0);
29864
30367
  }
30368
+ var BINARY_EXTENSIONS = new Set([
30369
+ ...[...ASSET_EXTENSIONS].filter((extension) => !["svg", "gltf", "gdshader", "shader", "fnt"].includes(extension)),
30370
+ "scn",
30371
+ "res",
30372
+ "zip",
30373
+ "pck",
30374
+ "exe",
30375
+ "dll",
30376
+ "so",
30377
+ "dylib"
30378
+ ]);
30379
+ function projectTexts(projectPath) {
30380
+ const found = [];
30381
+ const visit = (directory, prefix) => {
30382
+ if (steppedOver(directory)) {
30383
+ return;
30384
+ }
30385
+ for (const entry of readdirSync5(directory, { withFileTypes: true })) {
30386
+ if (skipped(entry.name)) {
30387
+ continue;
30388
+ }
30389
+ const absolute = join15(directory, entry.name);
30390
+ const spelled = `${prefix}${entry.name}`;
30391
+ if (entry.isDirectory()) {
30392
+ visit(absolute, `${spelled}/`);
30393
+ continue;
30394
+ }
30395
+ const extension = entry.name.includes(".") ? entry.name.split(".").pop()?.toLowerCase() ?? "" : "";
30396
+ if (!entry.isFile() || BINARY_EXTENSIONS.has(extension)) {
30397
+ continue;
30398
+ }
30399
+ const bytes = readFileSync13(absolute);
30400
+ if (!isBinary(bytes)) {
30401
+ found.push({ path: `res://${spelled}`, absolute, text: bytes.toString("utf8") });
30402
+ }
30403
+ }
30404
+ };
30405
+ visit(projectPath, "");
30406
+ return found;
30407
+ }
29865
30408
  function searchProject(projectPath, options) {
29866
30409
  const extensions = options.fileTypes === undefined ? null : new Set(options.fileTypes.map((ext) => ext.replace(/^\./, "").toLowerCase()).filter(Boolean));
29867
30410
  const result = {
@@ -29921,53 +30464,716 @@ function searchProject(projectPath, options) {
29921
30464
  return result;
29922
30465
  }
29923
30466
 
29924
- // src/resources.ts
29925
- import { readFileSync as readFileSync14, realpathSync as realpathSync4 } from "node:fs";
29926
- import { extname, resolve as resolve4 } from "node:path";
29927
- var STATIC_RESOURCES = [
29928
- {
29929
- uri: "godot://project/info",
29930
- name: "Project Info",
29931
- description: "Parsed Godot project.godot metadata as JSON.",
29932
- mimeType: "application/json"
30467
+ // src/rename.ts
30468
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync14, renameSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "node:fs";
30469
+ import { dirname as dirname9, posix } from "node:path";
30470
+ class Script {
30471
+ path;
30472
+ text;
30473
+ regions;
30474
+ shape;
30475
+ lines;
30476
+ constructor(path, text) {
30477
+ this.path = path;
30478
+ this.text = text;
30479
+ this.regions = regionsOf(text);
30480
+ this.shape = shapeOf(text);
30481
+ this.lines = new Lines(text);
30482
+ }
30483
+ occurrences(name) {
30484
+ return occurrencesOf(this.text, name, this.regions);
30485
+ }
30486
+ }
30487
+ function classId(file, inner) {
30488
+ return `${file}#${inner.join(".")}`;
30489
+ }
30490
+ function fileOf(id) {
30491
+ return id.slice(0, id.lastIndexOf("#"));
30492
+ }
30493
+
30494
+ class ClassGraph {
30495
+ nodes = new Map;
30496
+ declared;
30497
+ constructor(scripts, declared) {
30498
+ this.declared = declared;
30499
+ for (const script of scripts.values()) {
30500
+ const add = (body, inner) => {
30501
+ const id = classId(script.path, inner);
30502
+ this.nodes.set(id, { id, file: script.path, inner, body, parent: null, native: null });
30503
+ for (const child of body.inner) {
30504
+ if (child.name !== null) {
30505
+ add(child, [...inner, child.name]);
30506
+ }
30507
+ }
30508
+ };
30509
+ add(script.shape.body, []);
30510
+ }
30511
+ for (const node of this.nodes.values()) {
30512
+ const resolved = this.resolve(node, node.body.extendsAs);
30513
+ node.parent = resolved.id;
30514
+ node.native = resolved.native;
30515
+ }
29933
30516
  }
29934
- ];
29935
- var RESOURCE_TEMPLATES = [
29936
- {
29937
- uriTemplate: "godot://scene/{path}",
29938
- name: "Scene File",
29939
- description: "Read a Godot scene (.tscn) file from the current project.",
29940
- mimeType: "text/plain"
29941
- },
29942
- {
29943
- uriTemplate: "godot://script/{path}",
29944
- name: "GDScript File",
29945
- description: "Read a GDScript (.gd) file from the current project.",
29946
- mimeType: "text/x-gdscript"
29947
- },
29948
- {
29949
- uriTemplate: "godot://resource/{path}",
29950
- name: "Resource File",
29951
- description: "Read a project resource file (.tres, .tscn, .gd).",
29952
- mimeType: "text/plain"
30517
+ resolve(node, written) {
30518
+ if (written === null) {
30519
+ return { id: null, native: "RefCounted" };
30520
+ }
30521
+ if (written.startsWith('"') || written.startsWith("'")) {
30522
+ const path = resolvedPath(written.slice(1, -1), node.file);
30523
+ const id = classId(path, []);
30524
+ return this.nodes.has(id) ? { id, native: null } : { id: null, native: null };
30525
+ }
30526
+ const [first = "", ...rest] = written.split(".");
30527
+ for (let depth = node.inner.length;depth >= 0; depth -= 1) {
30528
+ const scope = this.nodes.get(classId(node.file, node.inner.slice(0, depth)));
30529
+ if (scope?.body.inner.some((child) => child.name === first) === true) {
30530
+ const id = classId(node.file, [...node.inner.slice(0, depth), first, ...rest]);
30531
+ return this.nodes.has(id) ? { id, native: null } : { id: null, native: null };
30532
+ }
30533
+ }
30534
+ const globalFile = this.declared.get(first);
30535
+ if (globalFile !== undefined) {
30536
+ const id = classId(globalFile, rest);
30537
+ return this.nodes.has(id) ? { id, native: null } : { id: null, native: null };
30538
+ }
30539
+ return { id: null, native: rest.length === 0 ? first : null };
29953
30540
  }
29954
- ];
29955
- var RESOURCE_COUNT = STATIC_RESOURCES.length + RESOURCE_TEMPLATES.length;
29956
- function ensureProjectPath(getProjectPath) {
29957
- const projectPath = getProjectPath();
29958
- if (!projectPath) {
29959
- throw new Refusal("This server knows no project to read from: start it with GDHARNESS_PROJECT, connect an editor, or make any tool call naming a projectPath that holds project.godot.");
30541
+ ancestors(id) {
30542
+ const found = [];
30543
+ let at = this.nodes.get(id)?.parent ?? null;
30544
+ while (at !== null && !found.includes(at)) {
30545
+ found.push(at);
30546
+ at = this.nodes.get(at)?.parent ?? null;
30547
+ }
30548
+ return found;
29960
30549
  }
29961
- return resolve4(projectPath);
29962
- }
29963
- function uriPathToProjectPath(inputPath) {
29964
- const normalized = inputPath.replace(/\\/g, "/").trim();
29965
- if (normalized.replace(/\//g, "") === "") {
29966
- throw new Refusal("Resource path is empty.");
30550
+ nativeBase(id) {
30551
+ const chain = [id, ...this.ancestors(id)];
30552
+ return this.nodes.get(chain[chain.length - 1] ?? id)?.native ?? null;
29967
30553
  }
29968
- return normalized.replace(/^\/+/, "");
29969
- }
29970
- function resolveProjectFile(projectPath, resourcePath) {
30554
+ descendants(id) {
30555
+ const found = new Set([id]);
30556
+ for (const node of this.nodes.values()) {
30557
+ if (this.ancestors(node.id).includes(id)) {
30558
+ found.add(node.id);
30559
+ }
30560
+ }
30561
+ return found;
30562
+ }
30563
+ bodyAt(file, offset) {
30564
+ let best = classId(file, []);
30565
+ let depth = 0;
30566
+ for (const node of this.nodes.values()) {
30567
+ if (node.file === file && node.inner.length > depth && node.body.start <= offset && offset <= node.body.end) {
30568
+ best = node.id;
30569
+ depth = node.inner.length;
30570
+ }
30571
+ }
30572
+ return best;
30573
+ }
30574
+ declaration(id, name) {
30575
+ const found = this.nodes.get(id)?.body.declarations.find((one) => one.name === name);
30576
+ return found === undefined ? undefined : { kind: found.kind, offset: found.offset };
30577
+ }
30578
+ }
30579
+ function resolvedPath(written, from) {
30580
+ if (written.startsWith("res://")) {
30581
+ return `res://${posix.normalize(written.slice("res://".length))}`;
30582
+ }
30583
+ const directory = posix.dirname(from.slice("res://".length));
30584
+ return `res://${posix.normalize(posix.join(directory, written))}`;
30585
+ }
30586
+ function relativeTo(target, from) {
30587
+ return posix.relative(posix.dirname(from.slice("res://".length)), target.slice("res://".length));
30588
+ }
30589
+ function scriptsOf(texts) {
30590
+ const scripts = new Map;
30591
+ for (const file of texts) {
30592
+ if (file.path.endsWith(".gd")) {
30593
+ scripts.set(file.path, new Script(file.path, file.text));
30594
+ }
30595
+ }
30596
+ return scripts;
30597
+ }
30598
+ function declaredIn(scripts) {
30599
+ const declared = new Map;
30600
+ for (const script of scripts.values()) {
30601
+ if (script.shape.className !== null) {
30602
+ declared.set(script.shape.className.name, script.path);
30603
+ }
30604
+ }
30605
+ return declared;
30606
+ }
30607
+ var DOC_LINK_KINDS = new Set([
30608
+ "method",
30609
+ "member",
30610
+ "signal",
30611
+ "constant",
30612
+ "enum",
30613
+ "annotation",
30614
+ "theme_item"
30615
+ ]);
30616
+ function docLinkAt(text, offset) {
30617
+ const lineStart = text.lastIndexOf(`
30618
+ `, offset - 1) + 1;
30619
+ const nextBreak = text.indexOf(`
30620
+ `, offset);
30621
+ const lineEnd = nextBreak < 0 ? text.length : nextBreak;
30622
+ const open = text.lastIndexOf("[", offset);
30623
+ const close = text.indexOf("]", offset);
30624
+ if (open < lineStart || close === -1 || close > lineEnd) {
30625
+ return null;
30626
+ }
30627
+ const inside = text.slice(open + 1, close);
30628
+ if (inside.includes("[") || inside.includes("]")) {
30629
+ return null;
30630
+ }
30631
+ const match = /^(?:([a-z_]+)\s+)?([\p{L}_][\p{L}\p{N}_]*(?:\.[\p{L}_][\p{L}\p{N}_]*)*)$/u.exec(inside);
30632
+ if (match === null || match[1] !== undefined && !DOC_LINK_KINDS.has(match[1])) {
30633
+ return null;
30634
+ }
30635
+ const parts = (match[2] ?? "").split(".");
30636
+ const pathStart = open + 1 + inside.length - (match[2] ?? "").length;
30637
+ let at = pathStart;
30638
+ for (const [index, part] of parts.entries()) {
30639
+ if (at === offset) {
30640
+ return { kind: match[1] ?? null, parts, index };
30641
+ }
30642
+ at += part.length + 1;
30643
+ }
30644
+ return null;
30645
+ }
30646
+ var DOC_KIND = {
30647
+ func: "method",
30648
+ var: "member",
30649
+ signal: "signal",
30650
+ const: "constant",
30651
+ enumValue: "constant",
30652
+ enum: "enum",
30653
+ class: null
30654
+ };
30655
+
30656
+ class PlanBuilder {
30657
+ edits = new Map;
30658
+ mentions = [];
30659
+ oldName;
30660
+ newName;
30661
+ constructor(oldName, newName) {
30662
+ this.oldName = oldName;
30663
+ this.newName = newName;
30664
+ }
30665
+ edit(file, offset, kind, length = this.oldName.length, replacement = this.newName) {
30666
+ const key = `${file}:${offset}`;
30667
+ if (!this.edits.has(key)) {
30668
+ this.edits.set(key, { file, offset, length, replacement, kind });
30669
+ }
30670
+ }
30671
+ edited(file, offset) {
30672
+ return this.edits.has(`${file}:${offset}`);
30673
+ }
30674
+ mention(file, lines, offset, kind, why) {
30675
+ this.mentions.push({
30676
+ file,
30677
+ line: lines.positionOf(offset).line + 1,
30678
+ kind,
30679
+ text: lines.lineAt(offset).trim(),
30680
+ ...why === undefined ? {} : { why }
30681
+ });
30682
+ }
30683
+ mentionTheRest(texts, scripts, whyFor) {
30684
+ const already = new Set(this.mentions.map((one) => `${one.file}:${one.line}:${one.kind}:${one.text}`));
30685
+ for (const file of texts) {
30686
+ const script = scripts.get(file.path);
30687
+ const lines = script?.lines ?? new Lines(file.text);
30688
+ const occurrences = script?.occurrences(this.oldName) ?? occurrencesOf(file.text, this.oldName, [{ kind: "code", start: 0, end: file.text.length }]);
30689
+ for (const occurrence of occurrences) {
30690
+ if (this.edited(file.path, occurrence.offset)) {
30691
+ continue;
30692
+ }
30693
+ const kind = script !== undefined ? occurrence.kind : /\.(tscn|tres)$/.test(file.path) ? "scene" : "text";
30694
+ const why = whyFor(file.path, occurrence, kind);
30695
+ const key = `${file.path}:${lines.positionOf(occurrence.offset).line + 1}:${kind}:${lines.lineAt(occurrence.offset).trim()}`;
30696
+ if (already.has(key)) {
30697
+ continue;
30698
+ }
30699
+ already.add(key);
30700
+ this.mention(file.path, lines, occurrence.offset, kind, why);
30701
+ }
30702
+ }
30703
+ }
30704
+ build() {
30705
+ const edits = [...this.edits.values()].sort((a, b) => a.file.localeCompare(b.file) || a.offset - b.offset);
30706
+ const mentions = [...this.mentions].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
30707
+ return { edits, mentions };
30708
+ }
30709
+ }
30710
+ function declaresItsOwn(script, name, except) {
30711
+ return script.occurrences(name).some((occurrence) => occurrence.kind === "code" && occurrence.offset !== except && occurrence.declaredAs !== null && occurrence.declaredAs !== "class_name");
30712
+ }
30713
+ function planClassRename(args) {
30714
+ const { texts, scripts, declaring, oldName, newName } = args;
30715
+ const plan = new PlanBuilder(oldName, newName);
30716
+ const declarationAt = declaring.shape.className?.offset ?? null;
30717
+ for (const script of scripts.values()) {
30718
+ const ownDeclaration = script.path === declaring.path ? declarationAt : null;
30719
+ const shadowed = declaresItsOwn(script, oldName, ownDeclaration);
30720
+ for (const occurrence of script.occurrences(oldName)) {
30721
+ if (occurrence.kind === "code") {
30722
+ if (occurrence.offset === ownDeclaration) {
30723
+ plan.edit(script.path, occurrence.offset, "declaration");
30724
+ } else if (!shadowed && !occurrence.afterDot && occurrence.declaredAs === null) {
30725
+ plan.edit(script.path, occurrence.offset, "code");
30726
+ }
30727
+ } else if (occurrence.kind === "doc") {
30728
+ const link = docLinkAt(script.text, occurrence.offset);
30729
+ if (link?.index === 0 && !shadowed) {
30730
+ plan.edit(script.path, occurrence.offset, "doc link");
30731
+ }
30732
+ }
30733
+ }
30734
+ }
30735
+ for (const file of texts) {
30736
+ if (!/\.(tscn|tres)$/.test(file.path)) {
30737
+ continue;
30738
+ }
30739
+ for (const section of sectionsOf(file.text)) {
30740
+ if (section.kind === "gd_resource" || section.kind === "gd_scene") {
30741
+ const recorded = section.attributes.get("script_class");
30742
+ if (recorded?.value === oldName) {
30743
+ plan.edit(file.path, recorded.offset, "resource class");
30744
+ }
30745
+ }
30746
+ }
30747
+ }
30748
+ plan.mentionTheRest(texts, scripts, (file, occurrence, kind) => {
30749
+ const script = scripts.get(file);
30750
+ if (kind !== "code" || script === undefined) {
30751
+ return;
30752
+ }
30753
+ if (occurrence.declaredAs === "class_name") {
30754
+ return `this script declares a class of the same name`;
30755
+ }
30756
+ if (occurrence.declaredAs !== null || declaresItsOwn(script, oldName, null)) {
30757
+ return `this script declares something of its own named ${oldName}, so which uses mean the class cannot be told from the text`;
30758
+ }
30759
+ if (occurrence.afterDot) {
30760
+ return `after a dot, a member of something else rather than the class`;
30761
+ }
30762
+ return;
30763
+ });
30764
+ return plan.build();
30765
+ }
30766
+ function planMemberRename(args) {
30767
+ const { texts, scripts, graph, root, family, kind, oldName, newName, resolved } = args;
30768
+ const plan = new PlanBuilder(oldName, newName);
30769
+ const heirs = graph.descendants(root);
30770
+ const docKind = DOC_KIND[kind];
30771
+ const familyAt = new Set(family.map((one) => `${one.file}:${one.offset}`));
30772
+ for (const one of family) {
30773
+ plan.edit(one.file, one.offset, "declaration");
30774
+ }
30775
+ for (const one of resolved) {
30776
+ const script = scripts.get(one.file);
30777
+ if (script === undefined || script.text.slice(one.offset, one.offset + oldName.length) !== oldName) {
30778
+ continue;
30779
+ }
30780
+ const occurrence = script.occurrences(oldName).find((each) => each.offset === one.offset);
30781
+ if (occurrence === undefined) {
30782
+ continue;
30783
+ }
30784
+ if (occurrence.kind === "code") {
30785
+ plan.edit(one.file, one.offset, familyAt.has(`${one.file}:${one.offset}`) ? "declaration" : "code");
30786
+ } else if (occurrence.kind === "doc" && docLinkAt(script.text, one.offset) !== null) {
30787
+ plan.edit(one.file, one.offset, "doc link");
30788
+ } else {
30789
+ plan.mention(one.file, script.lines, one.offset, occurrence.kind, `the language server resolved this to the ${kind === "func" ? "method" : "member"}, and it is inside ${occurrence.kind === "string" ? "a string" : occurrence.kind === "nodePath" ? "a node path" : "a comment"}, so it is left for you`);
30790
+ }
30791
+ }
30792
+ for (const script of scripts.values()) {
30793
+ for (const occurrence of script.occurrences(oldName)) {
30794
+ if (occurrence.kind !== "doc") {
30795
+ continue;
30796
+ }
30797
+ const link = docLinkAt(script.text, occurrence.offset);
30798
+ if (link === null || link.index !== link.parts.length - 1 || link.kind !== docKind || docKind === null) {
30799
+ continue;
30800
+ }
30801
+ const qualifiers = link.parts.slice(0, -1);
30802
+ let owner = null;
30803
+ if (qualifiers.length === 0) {
30804
+ owner = graph.bodyAt(script.path, occurrence.offset);
30805
+ } else {
30806
+ const [first = "", ...rest] = qualifiers;
30807
+ const file = graph.declared.get(first);
30808
+ owner = file === undefined ? null : `${file}#${rest.join(".")}`;
30809
+ }
30810
+ if (owner !== null && heirs.has(owner)) {
30811
+ plan.edit(script.path, occurrence.offset, "doc link");
30812
+ }
30813
+ }
30814
+ }
30815
+ planScenes(texts, heirs, kind, oldName, plan);
30816
+ plan.mentionTheRest(texts, scripts, (_file, occurrence, mentionKind) => mentionKind === "code" ? occurrence.afterDot ? "not resolved to this member by the language server: another class with a member of the same name, or a value whose type the analyser could not tell" : "not resolved to this member by the language server" : undefined);
30817
+ return plan.build();
30818
+ }
30819
+ function sectionsOf(text) {
30820
+ const sections = [];
30821
+ let current = null;
30822
+ let depth = 0;
30823
+ let inString = false;
30824
+ let offset = 0;
30825
+ for (const line of text.split(`
30826
+ `)) {
30827
+ const atTop = depth === 0 && !inString;
30828
+ const header = atTop ? /^\[([a-z_]+)(.*)\]\s*$/.exec(line.replace(/\r$/, "")) : null;
30829
+ if (header !== null) {
30830
+ const attributes = new Map;
30831
+ const rest = header[2] ?? "";
30832
+ const restAt = offset + 1 + (header[1]?.length ?? 0);
30833
+ for (const attribute of rest.matchAll(/([a-z_]+)=("(?:[^"\\]|\\.)*"|[A-Za-z]+\("(?:[^"\\]|\\.)*"\)|[^\s\]]+)/g)) {
30834
+ const raw = attribute[2] ?? "";
30835
+ const quoted = raw.startsWith('"');
30836
+ attributes.set(attribute[1] ?? "", {
30837
+ value: quoted ? raw.slice(1, -1) : raw,
30838
+ offset: restAt + attribute.index + (attribute[1]?.length ?? 0) + 1 + (quoted ? 1 : 0)
30839
+ });
30840
+ }
30841
+ current = { kind: header[1] ?? "", attributes, properties: [] };
30842
+ sections.push(current);
30843
+ } else if (atTop && current !== null) {
30844
+ const property = /^([A-Za-z_][\w/:]*) = (.*)$/.exec(line.replace(/\r$/, ""));
30845
+ if (property !== null) {
30846
+ current.properties.push({ key: property[1] ?? "", offset, value: property[2] ?? "" });
30847
+ }
30848
+ }
30849
+ for (let at = 0;at < line.length; at += 1) {
30850
+ const character = line[at];
30851
+ if (inString) {
30852
+ if (character === "\\") {
30853
+ at += 1;
30854
+ } else if (character === '"') {
30855
+ inString = false;
30856
+ }
30857
+ } else if (character === '"') {
30858
+ inString = true;
30859
+ } else if (character === "[" || character === "{" || character === "(") {
30860
+ depth += 1;
30861
+ } else if (character === "]" || character === "}" || character === ")") {
30862
+ depth = Math.max(0, depth - 1);
30863
+ }
30864
+ }
30865
+ if (header !== null) {
30866
+ depth = 0;
30867
+ }
30868
+ offset += line.length + 1;
30869
+ }
30870
+ return sections;
30871
+ }
30872
+ function resourceReference(value) {
30873
+ const match = /^(Ext|Sub)Resource\(\s*"([^"]*)"\s*\)$/.exec(value.trim());
30874
+ return match === null ? null : { external: match[1] === "Ext", id: match[2] ?? "" };
30875
+ }
30876
+
30877
+ class SceneReader {
30878
+ cache = new Map;
30879
+ texts;
30880
+ uids;
30881
+ constructor(texts, uids) {
30882
+ this.texts = texts;
30883
+ this.uids = uids;
30884
+ }
30885
+ sections(path) {
30886
+ let found = this.cache.get(path);
30887
+ if (found === undefined) {
30888
+ const text = this.texts.get(path);
30889
+ found = text === undefined ? [] : sectionsOf(text);
30890
+ this.cache.set(path, found);
30891
+ }
30892
+ return found;
30893
+ }
30894
+ external(path, id) {
30895
+ const entry = this.sections(path).find((section) => section.kind === "ext_resource" && section.attributes.get("id")?.value === id);
30896
+ if (entry === undefined) {
30897
+ return null;
30898
+ }
30899
+ const written = entry.attributes.get("path")?.value;
30900
+ if (written !== undefined) {
30901
+ return resolvedPath(written, path);
30902
+ }
30903
+ const uid = entry.attributes.get("uid")?.value;
30904
+ return uid === undefined ? null : this.uids.get(uid) ?? null;
30905
+ }
30906
+ scriptOf(path, section, depth = 0) {
30907
+ const script = section.properties.find((property) => property.key === "script");
30908
+ if (script !== undefined) {
30909
+ const reference = resourceReference(script.value);
30910
+ return reference?.external === true ? this.external(path, reference.id) : null;
30911
+ }
30912
+ const instance = section.attributes.get("instance")?.value;
30913
+ const reference = instance === undefined ? null : resourceReference(instance);
30914
+ if (reference?.external !== true || depth > 8) {
30915
+ return null;
30916
+ }
30917
+ const scene = this.external(path, reference.id);
30918
+ if (scene === null) {
30919
+ return null;
30920
+ }
30921
+ const rootNode = this.sections(scene).find((candidate) => candidate.kind === "node" && !candidate.attributes.has("parent"));
30922
+ return rootNode === undefined ? null : this.scriptOf(scene, rootNode, depth + 1);
30923
+ }
30924
+ nodesByPath(path) {
30925
+ const nodes = new Map;
30926
+ for (const section of this.sections(path)) {
30927
+ if (section.kind !== "node") {
30928
+ continue;
30929
+ }
30930
+ const name = section.attributes.get("name")?.value ?? "";
30931
+ const parent = section.attributes.get("parent")?.value;
30932
+ nodes.set(parent === undefined ? "." : parent === "." ? name : `${parent}/${name}`, section);
30933
+ }
30934
+ return nodes;
30935
+ }
30936
+ }
30937
+ function planScenes(texts, heirs, kind, oldName, plan) {
30938
+ const byPath = new Map(texts.map((file) => [file.path, file.text]));
30939
+ const uids = new Map;
30940
+ for (const file of texts) {
30941
+ if (file.path.endsWith(".uid")) {
30942
+ uids.set(file.text.trim(), file.path.slice(0, -".uid".length));
30943
+ }
30944
+ }
30945
+ const reader = new SceneReader(byPath, uids);
30946
+ const inherits = (script) => script !== null && heirs.has(`${script}#`);
30947
+ for (const file of texts) {
30948
+ if (!/\.(tscn|tres)$/.test(file.path) || !file.text.includes(oldName)) {
30949
+ continue;
30950
+ }
30951
+ const sections = reader.sections(file.path);
30952
+ if (kind === "var") {
30953
+ for (const section of sections) {
30954
+ if (!["node", "resource", "sub_resource"].includes(section.kind)) {
30955
+ continue;
30956
+ }
30957
+ const property = section.properties.find((one) => one.key === oldName);
30958
+ if (property !== undefined && inherits(reader.scriptOf(file.path, section))) {
30959
+ plan.edit(file.path, property.offset, "scene property");
30960
+ }
30961
+ }
30962
+ }
30963
+ if (kind === "signal" || kind === "func") {
30964
+ const nodes = reader.nodesByPath(file.path);
30965
+ for (const section of sections) {
30966
+ if (section.kind !== "connection") {
30967
+ continue;
30968
+ }
30969
+ const attribute = section.attributes.get(kind === "signal" ? "signal" : "method");
30970
+ const node = nodes.get(section.attributes.get(kind === "signal" ? "from" : "to")?.value ?? "");
30971
+ if (attribute?.value === oldName && node !== undefined && inherits(reader.scriptOf(file.path, node))) {
30972
+ plan.edit(file.path, attribute.offset, "scene connection");
30973
+ }
30974
+ }
30975
+ }
30976
+ }
30977
+ }
30978
+ function literalsOf(file, script) {
30979
+ const found = [];
30980
+ if (script !== undefined) {
30981
+ for (const region of script.regions) {
30982
+ if (region.kind !== "string") {
30983
+ continue;
30984
+ }
30985
+ const literal = file.text.slice(region.start, region.end);
30986
+ const quote = /["']/.exec(literal);
30987
+ if (quote === null || literal.startsWith('"""', quote.index) || literal.startsWith("'''", quote.index)) {
30988
+ continue;
30989
+ }
30990
+ found.push({ offset: region.start + quote.index + 1, value: literal.slice(quote.index + 1, -1) });
30991
+ }
30992
+ return found;
30993
+ }
30994
+ for (const match of file.text.matchAll(/"((?:[^"\\\n]|\\.)*)"/g)) {
30995
+ found.push({ offset: match.index + 1, value: match[1] ?? "" });
30996
+ }
30997
+ return found;
30998
+ }
30999
+ function planMove(args, plan) {
31000
+ const { texts, scripts, from, to, exists } = args;
31001
+ const edits = [...plan.edits];
31002
+ const mentions = [...plan.mentions];
31003
+ const editedAt = new Set(edits.map((one) => `${one.file}:${one.offset}`));
31004
+ const add = (file, offset, length, replacement) => {
31005
+ if (!editedAt.has(`${file}:${offset}`)) {
31006
+ editedAt.add(`${file}:${offset}`);
31007
+ edits.push({ file, offset, length, replacement, kind: "path" });
31008
+ }
31009
+ };
31010
+ for (const file of texts) {
31011
+ const script = scripts.get(file.path);
31012
+ for (const literal of literalsOf(file, script)) {
31013
+ const autoload = literal.value.startsWith("*") ? "*" : "";
31014
+ const written = literal.value.slice(autoload.length);
31015
+ if (written === "" || written.startsWith("uid://") || written.includes(`
31016
+ `)) {
31017
+ continue;
31018
+ }
31019
+ const isAbsolute = written.startsWith("res://");
31020
+ const target = resolvedPath(written, file.path);
31021
+ if (target === from) {
31022
+ const replacement = isAbsolute ? to : relativeTo(to, file.path === from ? to : file.path);
31023
+ add(file.path, literal.offset + autoload.length, written.length, replacement);
31024
+ } else if (file.path === from && !isAbsolute && /\.[a-z0-9]+$/i.test(written) && exists(target)) {
31025
+ add(file.path, literal.offset, written.length, relativeTo(target, to));
31026
+ }
31027
+ }
31028
+ const lines = script?.lines ?? new Lines(file.text);
31029
+ for (const match of file.text.matchAll(new RegExp(from.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"), "g"))) {
31030
+ const offset = match.index;
31031
+ const covered = edits.some((one) => one.file === file.path && one.offset <= offset && offset < one.offset + one.length);
31032
+ if (!covered) {
31033
+ const region = script?.regions.find((one) => one.start <= offset && offset < one.end);
31034
+ mentions.push({
31035
+ file: file.path,
31036
+ line: lines.positionOf(offset).line + 1,
31037
+ kind: region !== undefined ? region.kind : /\.(tscn|tres)$/.test(file.path) ? "scene" : "text",
31038
+ text: lines.lineAt(offset).trim(),
31039
+ why: `names ${from} outside a string the engine reads as a path`
31040
+ });
31041
+ }
31042
+ }
31043
+ }
31044
+ return {
31045
+ edits: edits.sort((a, b) => a.file.localeCompare(b.file) || a.offset - b.offset),
31046
+ mentions: mentions.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line)
31047
+ };
31048
+ }
31049
+ function rewritesOf(plan, texts, move) {
31050
+ const byPath = new Map(texts.map((file) => [file.path, file]));
31051
+ const byFile = new Map;
31052
+ for (const edit of plan.edits) {
31053
+ byFile.set(edit.file, [...byFile.get(edit.file) ?? [], edit]);
31054
+ }
31055
+ if (move !== null && !byFile.has(move.from)) {
31056
+ byFile.set(move.from, []);
31057
+ }
31058
+ const rewrites = [];
31059
+ for (const [path, edits] of byFile) {
31060
+ const file = byPath.get(path);
31061
+ if (file === undefined) {
31062
+ continue;
31063
+ }
31064
+ let after = file.text;
31065
+ let lastStart = Number.POSITIVE_INFINITY;
31066
+ for (const edit of [...edits].sort((a, b) => b.offset - a.offset)) {
31067
+ if (edit.offset + edit.length > lastStart) {
31068
+ throw new Error(`two edits overlap in ${path} at offset ${edit.offset}`);
31069
+ }
31070
+ after = after.slice(0, edit.offset) + edit.replacement + after.slice(edit.offset + edit.length);
31071
+ lastStart = edit.offset;
31072
+ }
31073
+ rewrites.push({
31074
+ path,
31075
+ absolute: file.absolute,
31076
+ before: file.text,
31077
+ after,
31078
+ writeTo: move?.from === path ? move.absoluteTo : file.absolute
31079
+ });
31080
+ }
31081
+ return rewrites.sort((a, b) => a.path.localeCompare(b.path));
31082
+ }
31083
+ function applyRewrites(rewrites) {
31084
+ for (const rewrite of rewrites) {
31085
+ const now = readFileSync14(rewrite.absolute, "utf8");
31086
+ if (now !== rewrite.before) {
31087
+ throw new Error(`${rewrite.path} changed on disk while the rename was being worked out; nothing was written`);
31088
+ }
31089
+ if (rewrite.writeTo !== rewrite.absolute && existsSync13(rewrite.writeTo)) {
31090
+ throw new Error(`${rewrite.writeTo} already exists; nothing was written`);
31091
+ }
31092
+ }
31093
+ const done = [];
31094
+ try {
31095
+ for (const rewrite of rewrites) {
31096
+ mkdirSync7(dirname9(rewrite.writeTo), { recursive: true });
31097
+ const staging = `${rewrite.writeTo}.gdharness-rename`;
31098
+ writeFileSync9(staging, rewrite.after, "utf8");
31099
+ renameSync(staging, rewrite.writeTo);
31100
+ let movedUid = false;
31101
+ if (rewrite.writeTo !== rewrite.absolute) {
31102
+ unlinkSync2(rewrite.absolute);
31103
+ if (existsSync13(`${rewrite.absolute}.uid`)) {
31104
+ renameSync(`${rewrite.absolute}.uid`, `${rewrite.writeTo}.uid`);
31105
+ movedUid = true;
31106
+ }
31107
+ }
31108
+ done.push({ rewrite, movedUid });
31109
+ }
31110
+ } catch (error) {
31111
+ for (const { rewrite, movedUid } of done.reverse()) {
31112
+ try {
31113
+ writeFileSync9(rewrite.absolute, rewrite.before, "utf8");
31114
+ if (rewrite.writeTo !== rewrite.absolute) {
31115
+ unlinkSync2(rewrite.writeTo);
31116
+ if (movedUid) {
31117
+ renameSync(`${rewrite.writeTo}.uid`, `${rewrite.absolute}.uid`);
31118
+ }
31119
+ }
31120
+ } catch {}
31121
+ }
31122
+ throw error;
31123
+ }
31124
+ }
31125
+
31126
+ // src/rename-symbol.ts
31127
+ import { existsSync as existsSync14, realpathSync as realpathSync5 } from "node:fs";
31128
+ import { basename as basename3, dirname as dirname10, join as join16, relative as relative3, resolve as resolve5 } from "node:path";
31129
+
31130
+ // src/resources.ts
31131
+ import { readFileSync as readFileSync15, realpathSync as realpathSync4 } from "node:fs";
31132
+ import { extname, resolve as resolve4 } from "node:path";
31133
+ var STATIC_RESOURCES = [
31134
+ {
31135
+ uri: "godot://project/info",
31136
+ name: "Project Info",
31137
+ description: "Parsed Godot project.godot metadata as JSON.",
31138
+ mimeType: "application/json"
31139
+ }
31140
+ ];
31141
+ var RESOURCE_TEMPLATES = [
31142
+ {
31143
+ uriTemplate: "godot://scene/{path}",
31144
+ name: "Scene File",
31145
+ description: "Read a Godot scene (.tscn) file from the current project.",
31146
+ mimeType: "text/plain"
31147
+ },
31148
+ {
31149
+ uriTemplate: "godot://script/{path}",
31150
+ name: "GDScript File",
31151
+ description: "Read a GDScript (.gd) file from the current project.",
31152
+ mimeType: "text/x-gdscript"
31153
+ },
31154
+ {
31155
+ uriTemplate: "godot://resource/{path}",
31156
+ name: "Resource File",
31157
+ description: "Read a project resource file (.tres, .tscn, .gd).",
31158
+ mimeType: "text/plain"
31159
+ }
31160
+ ];
31161
+ var RESOURCE_COUNT = STATIC_RESOURCES.length + RESOURCE_TEMPLATES.length;
31162
+ function ensureProjectPath(getProjectPath) {
31163
+ const projectPath = getProjectPath();
31164
+ if (!projectPath) {
31165
+ throw new Refusal("This server knows no project to read from: start it with GDHARNESS_PROJECT, connect an editor, or make any tool call naming a projectPath that holds project.godot.");
31166
+ }
31167
+ return resolve4(projectPath);
31168
+ }
31169
+ function uriPathToProjectPath(inputPath) {
31170
+ const normalized = inputPath.replace(/\\/g, "/").trim();
31171
+ if (normalized.replace(/\//g, "") === "") {
31172
+ throw new Refusal("Resource path is empty.");
31173
+ }
31174
+ return normalized.replace(/^\/+/, "");
31175
+ }
31176
+ function resolveProjectFile(projectPath, resourcePath) {
29971
31177
  const contained = resolveWithinProject(projectPath, resourcePath);
29972
31178
  if (!contained.ok) {
29973
31179
  throw new Refusal(contained.reason);
@@ -30132,7 +31338,7 @@ function readResourceText(uri, getProjectPath) {
30132
31338
  const parsedUri = parseGodotUri(uri);
30133
31339
  if (parsedUri.kind === "project-info") {
30134
31340
  const projectFilePath = resolveProjectFile(projectPath, "project.godot");
30135
- const rawProject = readFileSync14(projectFilePath, "utf-8");
31341
+ const rawProject = readFileSync15(projectFilePath, "utf-8");
30136
31342
  const parsedProject = parseProjectGodot(rawProject);
30137
31343
  return {
30138
31344
  mimeType: "application/json",
@@ -30141,7 +31347,7 @@ function readResourceText(uri, getProjectPath) {
30141
31347
  }
30142
31348
  const filePath = resolveProjectFile(projectPath, parsedUri.resourcePath);
30143
31349
  ensureAllowedExtension(parsedUri.kind, filePath);
30144
- const text = readFileSync14(filePath, "utf-8");
31350
+ const text = readFileSync15(filePath, "utf-8");
30145
31351
  return {
30146
31352
  mimeType: parsedUri.kind === "script" ? "text/x-gdscript" : "text/plain",
30147
31353
  text
@@ -30177,17 +31383,364 @@ function setupResourceHandlers(mcp, getProjectPath) {
30177
31383
  });
30178
31384
  }
30179
31385
 
31386
+ // src/rename-symbol.ts
31387
+ var WHAT = {
31388
+ func: "method",
31389
+ var: "variable",
31390
+ const: "constant",
31391
+ signal: "signal",
31392
+ enum: "enum",
31393
+ class: "inner class",
31394
+ enumValue: "enum value"
31395
+ };
31396
+ function resourcePathOf(projectPath, absolute) {
31397
+ const inside = relative3(onDiskSpelling(projectPath), onDiskSpelling(absolute));
31398
+ if (inside === "" || inside.startsWith("..") || /^[A-Za-z]:/.test(inside)) {
31399
+ return null;
31400
+ }
31401
+ return `res://${inside.replace(/\\/g, "/")}`;
31402
+ }
31403
+ function onDiskSpelling(path) {
31404
+ const missing = [];
31405
+ let at = resolve5(path);
31406
+ for (;; ) {
31407
+ try {
31408
+ return join16(realpathSync5.native(at), ...missing.reverse());
31409
+ } catch {
31410
+ const parent = dirname10(at);
31411
+ if (parent === at) {
31412
+ return resolve5(path);
31413
+ }
31414
+ missing.push(basename3(at));
31415
+ at = parent;
31416
+ }
31417
+ }
31418
+ }
31419
+ function usedAsIdentifier(scripts, name, most) {
31420
+ const found = [];
31421
+ for (const script of scripts.values()) {
31422
+ for (const occurrence of script.occurrences(name)) {
31423
+ if (occurrence.kind === "code" && !occurrence.afterDot) {
31424
+ found.push(`${script.path}:${script.lines.positionOf(occurrence.offset).line + 1}`);
31425
+ if (found.length >= most) {
31426
+ return found;
31427
+ }
31428
+ }
31429
+ }
31430
+ }
31431
+ return found;
31432
+ }
31433
+ function autoloadNames(texts) {
31434
+ const settings = texts.find((file) => file.path === "res://project.godot");
31435
+ return settings === undefined ? [] : Object.keys(parseProjectGodot(settings.text)["autoload"] ?? {});
31436
+ }
31437
+ async function renameSymbol(request, services) {
31438
+ const { projectPath, symbol, newName } = request;
31439
+ if (!isIdentifier(newName)) {
31440
+ return {
31441
+ ok: false,
31442
+ reason: `${newName} is not a name GDScript accepts: a letter or underscore, then letters, digits and underscores, and not a keyword.`
31443
+ };
31444
+ }
31445
+ if (newName === symbol) {
31446
+ return { ok: false, reason: `${symbol} is already called ${newName}; nothing to rename.` };
31447
+ }
31448
+ const declaringPath = resourcePathOf(projectPath, request.scriptPath);
31449
+ if (declaringPath === null) {
31450
+ return { ok: false, reason: `${request.scriptPath} is not inside the project.` };
31451
+ }
31452
+ let moveTo = null;
31453
+ if (request.newScriptPath !== null) {
31454
+ moveTo = resourcePathOf(projectPath, request.newScriptPath);
31455
+ if (moveTo === null || !moveTo.endsWith(".gd")) {
31456
+ return {
31457
+ ok: false,
31458
+ reason: `newScriptPath must be a .gd path inside the project, and ${request.newScriptPath} is not.`
31459
+ };
31460
+ }
31461
+ if (existsSync14(request.newScriptPath)) {
31462
+ return { ok: false, reason: `${moveTo} already exists, so the script cannot be moved there.` };
31463
+ }
31464
+ }
31465
+ const texts = projectTexts(projectPath);
31466
+ const scripts = scriptsOf(texts);
31467
+ const declaring = scripts.get(declaringPath);
31468
+ if (declaring === undefined) {
31469
+ return {
31470
+ ok: false,
31471
+ reason: `${declaringPath} is not among the scripts the engine sees: it is under a directory holding a .gdignore, or one spelled with a dot.`
31472
+ };
31473
+ }
31474
+ const declared = declaredIn(scripts);
31475
+ const isClass = declaring.shape.className?.name === symbol;
31476
+ let plan;
31477
+ let what;
31478
+ let resolvedBy;
31479
+ let overrides = [];
31480
+ let declaringFiles = [declaringPath];
31481
+ if (isClass) {
31482
+ what = "class";
31483
+ resolvedBy = "the files";
31484
+ const conflicts = [];
31485
+ const holder = declared.get(newName);
31486
+ if (holder !== undefined) {
31487
+ conflicts.push(`${newName} is already the class_name of ${holder}`);
31488
+ }
31489
+ if (autoloadNames(texts).includes(newName)) {
31490
+ conflicts.push(`${newName} is already an autoload in project.godot`);
31491
+ }
31492
+ for (const place of usedAsIdentifier(scripts, newName, 10)) {
31493
+ conflicts.push(`${newName} is already an identifier at ${place}`);
31494
+ }
31495
+ const taken = (await services.namesTaken([newName], null))[newName];
31496
+ if (taken !== undefined && taken.as.length > 0) {
31497
+ conflicts.push(`${newName} is ${taken.as.join(" and ")}`);
31498
+ }
31499
+ if (conflicts.length > 0) {
31500
+ return {
31501
+ ok: false,
31502
+ reason: `${symbol} cannot be renamed to ${newName}: the name is taken.`,
31503
+ conflicts
31504
+ };
31505
+ }
31506
+ plan = planClassRename({ texts, scripts, declaring, oldName: symbol, newName });
31507
+ } else {
31508
+ const declaration = declaring.shape.body.declarations.find((one) => one.name === symbol);
31509
+ if (declaration === undefined) {
31510
+ const names = [
31511
+ ...declaring.shape.className === null ? [] : [declaring.shape.className.name],
31512
+ ...declaring.shape.body.declarations.map((one) => one.name)
31513
+ ];
31514
+ return {
31515
+ ok: false,
31516
+ reason: `${declaringPath} declares no ${symbol} at its top level. What it declares there: ${names.join(", ") || "nothing"}. A local variable or a member of an inner class is not renamed by this call.`
31517
+ };
31518
+ }
31519
+ const kind = declaration.kind;
31520
+ what = WHAT[kind];
31521
+ resolvedBy = "the editor's language server";
31522
+ const graph = new ClassGraph(scripts, declared);
31523
+ const own = `${declaringPath}#`;
31524
+ let root = own;
31525
+ if (kind === "func") {
31526
+ for (const ancestor of graph.ancestors(own)) {
31527
+ if (graph.declaration(ancestor, symbol)?.kind === "func") {
31528
+ root = ancestor;
31529
+ }
31530
+ }
31531
+ }
31532
+ const native = graph.nativeBase(root);
31533
+ const taken = await services.namesTaken([symbol, newName], native);
31534
+ const engineOwned = taken[symbol]?.declaredBy ?? null;
31535
+ if (engineOwned !== null) {
31536
+ return {
31537
+ ok: false,
31538
+ reason: `${symbol} is declared by the engine's ${engineOwned}, which ${root === own ? declaringPath : fileOf(root)} inherits from, so the script ${kind === "func" ? "overrides" : "shadows"} an engine name rather than declaring its own, and the engine calls it by that name.`
31539
+ };
31540
+ }
31541
+ const conflicts = [];
31542
+ const newOwner = taken[newName]?.declaredBy ?? null;
31543
+ if (newOwner !== null) {
31544
+ conflicts.push(`${newName} is declared by the engine's ${newOwner}, which this class inherits from`);
31545
+ }
31546
+ for (const id of new Set([root, ...graph.ancestors(root), ...graph.descendants(root)])) {
31547
+ if (graph.declaration(id, newName) !== undefined) {
31548
+ conflicts.push(`${newName} is already declared in ${id.endsWith("#") ? fileOf(id) : `${fileOf(id)}, class ${id.slice(id.lastIndexOf("#") + 1)}`}`);
31549
+ }
31550
+ }
31551
+ if (conflicts.length > 0) {
31552
+ return {
31553
+ ok: false,
31554
+ reason: `${symbol} cannot be renamed to ${newName}: the name is taken.`,
31555
+ conflicts
31556
+ };
31557
+ }
31558
+ const family = [];
31559
+ if (kind === "func") {
31560
+ for (const id of graph.descendants(root)) {
31561
+ const found = graph.declaration(id, symbol);
31562
+ if (found?.kind === "func") {
31563
+ family.push({ file: fileOf(id), offset: found.offset });
31564
+ }
31565
+ }
31566
+ } else {
31567
+ family.push({ file: declaringPath, offset: declaration.offset });
31568
+ }
31569
+ overrides = family.map((one) => one.file).filter((file) => file !== fileOf(root));
31570
+ declaringFiles = family.map((one) => one.file);
31571
+ const resolved = await resolveMember(projectPath, texts, scripts, family, symbol, services);
31572
+ if (resolved === null) {
31573
+ const first = family[0];
31574
+ const script = first === undefined ? undefined : scripts.get(first.file);
31575
+ const line = first === undefined || script === undefined ? 0 : script.lines.positionOf(first.offset).line + 1;
31576
+ return {
31577
+ ok: false,
31578
+ reason: `The language server resolved nothing at ${first?.file ?? declaringPath}:${line}, where ${symbol} is declared, not even the declaration, so it is not analysing that script and its answer would rename nothing.`,
31579
+ advice: [
31580
+ "script_diagnostics on that script says whether the editor can parse it",
31581
+ "editor_status says whether the editor connected is this project's"
31582
+ ]
31583
+ };
31584
+ }
31585
+ plan = planMemberRename({
31586
+ texts,
31587
+ scripts,
31588
+ graph,
31589
+ root,
31590
+ family,
31591
+ kind,
31592
+ oldName: symbol,
31593
+ newName,
31594
+ resolved
31595
+ });
31596
+ }
31597
+ if (moveTo !== null) {
31598
+ plan = planMove({
31599
+ texts,
31600
+ scripts,
31601
+ from: declaringPath,
31602
+ to: moveTo,
31603
+ exists: (path) => existsSync14(`${projectPath}/${path.slice("res://".length)}`)
31604
+ }, plan);
31605
+ }
31606
+ const rewrites = rewritesOf(plan, texts, moveTo === null || request.newScriptPath === null ? null : { from: declaringPath, to: moveTo, absoluteTo: request.newScriptPath });
31607
+ const graph = new ClassGraph(scripts, declared);
31608
+ const rank = (path) => (declaringFiles.includes(path) ? 0 : 1000) + graph.ancestors(`${path}#`).length;
31609
+ const scriptsInOrder = rewrites.map((rewrite) => rewrite.path).filter((path) => path.endsWith(".gd")).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b)).map((path) => path === declaringPath && moveTo !== null ? moveTo : path);
31610
+ return {
31611
+ ok: true,
31612
+ isClass,
31613
+ moved: moveTo === null ? null : { from: declaringPath, to: moveTo },
31614
+ scriptsInOrder,
31615
+ rewrites,
31616
+ report: {
31617
+ renamed: { what, from: symbol, to: newName, declaredIn: declaringPath, resolvedBy },
31618
+ ...overrides.length > 0 ? { overridesRenamed: overrides } : {},
31619
+ ...moveTo === null ? {} : { moved: { from: declaringPath, to: moveTo } },
31620
+ changed: changedReport(plan.edits, rewrites),
31621
+ leftAlone: plan.mentions,
31622
+ summary: summaryOf(plan.edits, plan.mentions, rewrites)
31623
+ }
31624
+ };
31625
+ }
31626
+ async function resolveMember(projectPath, texts, scripts, family, name, services) {
31627
+ const absoluteOf = new Map(texts.map((file) => [file.path, file.absolute]));
31628
+ const key = (place) => `${place.file}:${place.offset}`;
31629
+ const toResolved = (located) => {
31630
+ const file = resourcePathOf(projectPath, located.file);
31631
+ const offset = file === null ? null : scripts.get(file)?.lines.offsetOf(located);
31632
+ return file === null || offset === null || offset === undefined ? null : { file, offset };
31633
+ };
31634
+ const ask = async (question, place) => {
31635
+ const script = scripts.get(place.file);
31636
+ const absolute = absoluteOf.get(place.file);
31637
+ if (script === undefined || absolute === undefined) {
31638
+ return [];
31639
+ }
31640
+ const answered = await services[question](absolute, script.text, script.lines.positionOf(place.offset));
31641
+ return answered.map(toResolved).filter((one) => one !== null);
31642
+ };
31643
+ const ours = new Map;
31644
+ const settled = new Set;
31645
+ const root = family[0];
31646
+ if (root === undefined) {
31647
+ return [];
31648
+ }
31649
+ const seeded = await ask("references", root);
31650
+ if (seeded.length === 0) {
31651
+ return null;
31652
+ }
31653
+ for (const place of seeded) {
31654
+ ours.set(key(place), place);
31655
+ }
31656
+ const declarations = new Set(family.map(key));
31657
+ for (const script of scripts.values()) {
31658
+ for (const occurrence of script.occurrences(name)) {
31659
+ const place = { file: script.path, offset: occurrence.offset };
31660
+ if (occurrence.kind !== "code" || ours.has(key(place)) || settled.has(key(place))) {
31661
+ continue;
31662
+ }
31663
+ const declared = await ask("definitions", place);
31664
+ const only = declared.length === 1 ? declared[0] : undefined;
31665
+ if (only === undefined) {
31666
+ settled.add(key(place));
31667
+ continue;
31668
+ }
31669
+ const isOurs = declarations.has(key(only));
31670
+ const same = [place, ...await ask("references", place)];
31671
+ for (const one of same) {
31672
+ if (isOurs) {
31673
+ ours.set(key(one), one);
31674
+ } else {
31675
+ settled.add(key(one));
31676
+ }
31677
+ }
31678
+ }
31679
+ }
31680
+ return [...ours.values()];
31681
+ }
31682
+ function changedReport(edits, rewrites) {
31683
+ return rewrites.map((rewrite) => {
31684
+ const lines = rewrite.after.split(`
31685
+ `);
31686
+ const byLine = new Map;
31687
+ const starts = [0];
31688
+ for (let at = rewrite.before.indexOf(`
31689
+ `);at !== -1; at = rewrite.before.indexOf(`
31690
+ `, at + 1)) {
31691
+ starts.push(at + 1);
31692
+ }
31693
+ let count = 0;
31694
+ for (const edit of edits) {
31695
+ if (edit.file !== rewrite.path) {
31696
+ continue;
31697
+ }
31698
+ count += 1;
31699
+ let line = 0;
31700
+ while (line + 1 < starts.length && (starts[line + 1] ?? 0) <= edit.offset) {
31701
+ line += 1;
31702
+ }
31703
+ byLine.set(line, (byLine.get(line) ?? new Set).add(edit.kind));
31704
+ }
31705
+ return {
31706
+ file: rewrite.path,
31707
+ edits: count,
31708
+ lines: [...byLine.entries()].sort(([a], [b]) => a - b).map(([line, kinds]) => ({
31709
+ line: line + 1,
31710
+ kinds: [...kinds],
31711
+ text: (lines[line] ?? "").replace(/\r$/, "").trim()
31712
+ }))
31713
+ };
31714
+ });
31715
+ }
31716
+ function summaryOf(edits, mentions, rewrites) {
31717
+ const count = (values) => {
31718
+ const counted = {};
31719
+ for (const value of values) {
31720
+ counted[value] = (counted[value] ?? 0) + 1;
31721
+ }
31722
+ return counted;
31723
+ };
31724
+ return {
31725
+ filesChanged: rewrites.length,
31726
+ edits: edits.length,
31727
+ editsByKind: count(edits.map((edit) => edit.kind)),
31728
+ leftAlone: mentions.length,
31729
+ leftAloneByKind: count(mentions.map((mention) => mention.kind))
31730
+ };
31731
+ }
31732
+
30180
31733
  // src/restart-note.ts
30181
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync15, rmSync as rmSync6, writeFileSync as writeFileSync9 } from "node:fs";
30182
- import { dirname as dirname9, join as join16 } from "node:path";
31734
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync16, rmSync as rmSync6, writeFileSync as writeFileSync10 } from "node:fs";
31735
+ import { dirname as dirname11, join as join17 } from "node:path";
30183
31736
  function restartNotePath(projectPath) {
30184
- return join16(projectPath, ".godot", "gdharness-restart.json");
31737
+ return join17(projectPath, ".godot", "gdharness-restart.json");
30185
31738
  }
30186
31739
  function noteRestartBegun(note) {
30187
31740
  const path = restartNotePath(note.projectPath);
30188
31741
  try {
30189
- mkdirSync7(dirname9(path), { recursive: true });
30190
- writeFileSync9(path, `${JSON.stringify(note, null, 2)}
31742
+ mkdirSync8(dirname11(path), { recursive: true });
31743
+ writeFileSync10(path, `${JSON.stringify(note, null, 2)}
30191
31744
  `, "utf8");
30192
31745
  } catch (error) {
30193
31746
  console.error(`[SERVER] Could not record the restart at ${path}: ${errorMessage(error)}`);
@@ -30195,7 +31748,7 @@ function noteRestartBegun(note) {
30195
31748
  }
30196
31749
  function restartOwed(projectPath) {
30197
31750
  try {
30198
- const parsed = JSON.parse(readFileSync15(restartNotePath(projectPath), "utf8"));
31751
+ const parsed = JSON.parse(readFileSync16(restartNotePath(projectPath), "utf8"));
30199
31752
  if (typeof parsed !== "object" || parsed === null) {
30200
31753
  return null;
30201
31754
  }
@@ -30220,64 +31773,64 @@ function restartSettled(projectPath) {
30220
31773
  import { execFile as execFile4 } from "node:child_process";
30221
31774
  import { createHash as createHash3 } from "node:crypto";
30222
31775
  import {
30223
- mkdirSync as mkdirSync8,
31776
+ mkdirSync as mkdirSync9,
30224
31777
  openSync as openSync2,
30225
31778
  readdirSync as readdirSync6,
30226
- readFileSync as readFileSync16,
30227
- realpathSync as realpathSync5,
31779
+ readFileSync as readFileSync17,
31780
+ realpathSync as realpathSync6,
30228
31781
  rmSync as rmSync7,
30229
31782
  statSync as statSync6,
30230
- writeFileSync as writeFileSync10
31783
+ writeFileSync as writeFileSync11
30231
31784
  } from "node:fs";
30232
- import { basename as basename3, dirname as dirname10, join as join17, resolve as resolve5 } from "node:path";
31785
+ import { basename as basename4, dirname as dirname12, join as join18, resolve as resolve6 } from "node:path";
30233
31786
  import { promisify as promisify4 } from "node:util";
30234
31787
  var execFileAsync = promisify4(execFile4);
30235
31788
  function runsDirectory() {
30236
- return join17(runtimeDirectory(), "runs");
31789
+ return join18(runtimeDirectory(), "runs");
30237
31790
  }
30238
31791
  function realAsFarAsItExists(path) {
30239
31792
  const missing = [];
30240
31793
  let at = path;
30241
31794
  for (;; ) {
30242
31795
  try {
30243
- return join17(realpathSync5.native(at), ...missing);
31796
+ return join18(realpathSync6.native(at), ...missing);
30244
31797
  } catch {
30245
- const parent = dirname10(at);
31798
+ const parent = dirname12(at);
30246
31799
  if (parent === at) {
30247
31800
  return path;
30248
31801
  }
30249
- missing.unshift(basename3(at));
31802
+ missing.unshift(basename4(at));
30250
31803
  at = parent;
30251
31804
  }
30252
31805
  }
30253
31806
  }
30254
31807
  function projectKey(projectPath) {
30255
- const real = realAsFarAsItExists(resolve5(projectPath)).replace(/[\\/]+$/, "");
31808
+ const real = realAsFarAsItExists(resolve6(projectPath)).replace(/[\\/]+$/, "");
30256
31809
  const folded = process.platform === "win32" || process.platform === "darwin" ? real.toLowerCase() : real;
30257
31810
  return createHash3("sha256").update(folded.replaceAll("\\", "/")).digest("hex").slice(0, 16);
30258
31811
  }
30259
31812
  function runRecordPath(projectPath, directory = runtimeDirectory()) {
30260
- return join17(directory, "runs", `note-${projectKey(projectPath)}.json`);
31813
+ return join18(directory, "runs", `note-${projectKey(projectPath)}.json`);
30261
31814
  }
30262
31815
  var SHARED_NOTE = "run.json";
30263
31816
  function openTranscript(startedAt) {
30264
- mkdirSync8(runsDirectory(), { recursive: true });
30265
- const path = join17(runsDirectory(), `run-${startedAt}.log`);
31817
+ mkdirSync9(runsDirectory(), { recursive: true });
31818
+ const path = join18(runsDirectory(), `run-${startedAt}.log`);
30266
31819
  return { path, fd: openSync2(path, "a") };
30267
31820
  }
30268
31821
  function noteIsAbout(note, playing) {
30269
31822
  return note.play !== undefined && playing !== null && note.play.play === playing.play && note.play.editorPid === playing.editorPid;
30270
31823
  }
30271
31824
  function editorNotePath(projectPath, directory = runtimeDirectory()) {
30272
- return join17(directory, "runs", `editor-${projectKey(projectPath)}.json`);
31825
+ return join18(directory, "runs", `editor-${projectKey(projectPath)}.json`);
30273
31826
  }
30274
31827
  function writeEditorRunNote(note) {
30275
- mkdirSync8(runsDirectory(), { recursive: true });
30276
- writeFileSync10(editorNotePath(note.projectPath), JSON.stringify(note, null, 2), "utf8");
31828
+ mkdirSync9(runsDirectory(), { recursive: true });
31829
+ writeFileSync11(editorNotePath(note.projectPath), JSON.stringify(note, null, 2), "utf8");
30277
31830
  }
30278
31831
  function readEditorRunNote(projectPath) {
30279
31832
  for (const directory of runtimeDirectories()) {
30280
- const note = editorNoteAt(editorNotePath(projectPath, directory)) ?? editorNoteAt(join17(directory, "runs", "editor-run.json"));
31833
+ const note = editorNoteAt(editorNotePath(projectPath, directory)) ?? editorNoteAt(join18(directory, "runs", "editor-run.json"));
30281
31834
  if (note !== null && isSameDirectory(note.projectPath, projectPath)) {
30282
31835
  return note;
30283
31836
  }
@@ -30287,7 +31840,7 @@ function readEditorRunNote(projectPath) {
30287
31840
  function editorNoteAt(path) {
30288
31841
  let parsed;
30289
31842
  try {
30290
- parsed = JSON.parse(readFileSync16(path, "utf8"));
31843
+ parsed = JSON.parse(readFileSync17(path, "utf8"));
30291
31844
  } catch {
30292
31845
  return null;
30293
31846
  }
@@ -30311,7 +31864,7 @@ function readRunRecord(projectPath) {
30311
31864
  if (own !== null) {
30312
31865
  return own;
30313
31866
  }
30314
- const shared = recordAt(join17(directory, "runs", SHARED_NOTE));
31867
+ const shared = recordAt(join18(directory, "runs", SHARED_NOTE));
30315
31868
  if (shared !== null && shared.projectPath !== "" && isSameDirectory(shared.projectPath, projectPath)) {
30316
31869
  return shared;
30317
31870
  }
@@ -30323,13 +31876,13 @@ function everyRunRecord() {
30323
31876
  for (const directory of runtimeDirectories()) {
30324
31877
  let entries;
30325
31878
  try {
30326
- entries = readdirSync6(join17(directory, "runs"));
31879
+ entries = readdirSync6(join18(directory, "runs"));
30327
31880
  } catch {
30328
31881
  continue;
30329
31882
  }
30330
31883
  for (const entry of entries) {
30331
31884
  if (entry === SHARED_NOTE || entry.startsWith("note-") && entry.endsWith(".json")) {
30332
- const record = recordAt(join17(directory, "runs", entry));
31885
+ const record = recordAt(join18(directory, "runs", entry));
30333
31886
  if (record !== null) {
30334
31887
  found.push(record);
30335
31888
  }
@@ -30341,7 +31894,7 @@ function everyRunRecord() {
30341
31894
  function recordAt(path) {
30342
31895
  let parsed;
30343
31896
  try {
30344
- parsed = JSON.parse(readFileSync16(path, "utf8"));
31897
+ parsed = JSON.parse(readFileSync17(path, "utf8"));
30345
31898
  } catch {
30346
31899
  return null;
30347
31900
  }
@@ -30392,7 +31945,7 @@ async function runningAs(pid) {
30392
31945
  const began = await startedAt(pid, null);
30393
31946
  const when = began === null ? {} : { startedAt: began };
30394
31947
  if (process.platform === "linux") {
30395
- const raw = readFileSync16(`/proc/${pid}/cmdline`, "utf8").replaceAll("\x00", " ").trim();
31948
+ const raw = readFileSync17(`/proc/${pid}/cmdline`, "utf8").replaceAll("\x00", " ").trim();
30396
31949
  return raw === "" ? null : { kind: "commandLine", text: raw, ...when };
30397
31950
  }
30398
31951
  const args = (await execFileAsync("ps", ["-p", String(pid), "-o", "args="], { encoding: "utf8", timeout: 15000 })).stdout.trim();
@@ -30499,7 +32052,7 @@ function whyNotTheRun(record, running, needed) {
30499
32052
  if (after > SAME_RUN_WINDOW_MS) {
30500
32053
  return `that process started ${Math.round(after / 1000)} seconds after the run had`;
30501
32054
  }
30502
- const engine = record.command === undefined ? null : basename3(record.command);
32055
+ const engine = record.command === undefined ? null : basename4(record.command);
30503
32056
  const said = process.platform === "win32" ? running.text.toLowerCase() : running.text;
30504
32057
  const wanted = engine === null || process.platform !== "win32" ? engine : engine.toLowerCase();
30505
32058
  if (wanted !== null && !said.includes(wanted)) {
@@ -30538,7 +32091,7 @@ function judgeAnnouncedGame(running, projectPath, announcedAt) {
30538
32091
  }
30539
32092
  function clearRunRecord(projectPath) {
30540
32093
  for (const directory of runtimeDirectories()) {
30541
- const shared = join17(directory, "runs", SHARED_NOTE);
32094
+ const shared = join18(directory, "runs", SHARED_NOTE);
30542
32095
  const sharedRecord = recordAt(shared);
30543
32096
  const ours = sharedRecord !== null && sharedRecord.projectPath !== "" && isSameDirectory(sharedRecord.projectPath, projectPath);
30544
32097
  for (const path of [runRecordPath(projectPath, directory), ...ours ? [shared] : []]) {
@@ -30568,7 +32121,7 @@ function sweepTranscripts(keepMs = 24 * 60 * 60 * 1000, now = Date.now()) {
30568
32121
  if (!entry.startsWith("run-") || !entry.endsWith(".log")) {
30569
32122
  continue;
30570
32123
  }
30571
- const path = join17(directory, entry);
32124
+ const path = join18(directory, entry);
30572
32125
  if (kept.has(path) || ageMs(path, now) < keepMs) {
30573
32126
  continue;
30574
32127
  }
@@ -30583,16 +32136,16 @@ import { spawnSync } from "node:child_process";
30583
32136
  import { createHash as createHash4 } from "node:crypto";
30584
32137
  import {
30585
32138
  cpSync,
30586
- existsSync as existsSync13,
30587
- mkdirSync as mkdirSync9,
32139
+ existsSync as existsSync15,
32140
+ mkdirSync as mkdirSync10,
30588
32141
  readdirSync as readdirSync7,
30589
- readFileSync as readFileSync17,
32142
+ readFileSync as readFileSync18,
30590
32143
  rmdirSync,
30591
32144
  rmSync as rmSync8,
30592
32145
  statSync as statSync7,
30593
- writeFileSync as writeFileSync11
32146
+ writeFileSync as writeFileSync12
30594
32147
  } from "node:fs";
30595
- import { dirname as dirname11, join as join18 } from "node:path";
32148
+ import { dirname as dirname13, join as join19 } from "node:path";
30596
32149
  import { fileURLToPath as fileURLToPath3 } from "node:url";
30597
32150
  var ADDONS = ["gdharness_editor", "gdharness_runtime", "auto_reload"];
30598
32151
  var EDITOR_PLUGINS = ["gdharness_editor", "auto_reload"];
@@ -30616,21 +32169,21 @@ function addonsDigest(names, from) {
30616
32169
  if (name === VERSION_MARKER || name === DIGEST_MARKER) {
30617
32170
  continue;
30618
32171
  }
30619
- const path = join18(directory, name);
32172
+ const path = join19(directory, name);
30620
32173
  const inside = `${relative}/${name}`;
30621
32174
  if (statSync7(path).isDirectory()) {
30622
32175
  walk(path, inside);
30623
32176
  } else {
30624
32177
  hash.update(`${inside}
30625
32178
  `);
30626
- hash.update(readFileSync17(path));
32179
+ hash.update(readFileSync18(path));
30627
32180
  hash.update(`
30628
32181
  `);
30629
32182
  }
30630
32183
  }
30631
32184
  };
30632
32185
  for (const name of names) {
30633
- walk(join18(from, name), name);
32186
+ walk(join19(from, name), name);
30634
32187
  }
30635
32188
  return hash.digest("hex");
30636
32189
  }
@@ -30663,22 +32216,22 @@ function installedRuntimeDigest(projectPath) {
30663
32216
  return digestMarker(projectPath, RUNTIME_ADDON);
30664
32217
  }
30665
32218
  function digestMarker(projectPath, addon) {
30666
- const marker = join18(projectPath, "addons", addon, DIGEST_MARKER);
30667
- if (!existsSync13(marker)) {
32219
+ const marker = join19(projectPath, "addons", addon, DIGEST_MARKER);
32220
+ if (!existsSync15(marker)) {
30668
32221
  return null;
30669
32222
  }
30670
- const said = readFileSync17(marker, "utf8").trim();
32223
+ const said = readFileSync18(marker, "utf8").trim();
30671
32224
  return said === "" ? null : said;
30672
32225
  }
30673
32226
  function shippedAddonsDirectory() {
30674
- return join18(dirname11(fileURLToPath3(import.meta.url)), "godot", "addons");
32227
+ return join19(dirname13(fileURLToPath3(import.meta.url)), "godot", "addons");
30675
32228
  }
30676
32229
  function installedAddonVersion(projectPath) {
30677
- const marker = join18(projectPath, "addons", ADDONS[0], VERSION_MARKER);
30678
- if (!existsSync13(marker)) {
32230
+ const marker = join19(projectPath, "addons", ADDONS[0], VERSION_MARKER);
32231
+ if (!existsSync15(marker)) {
30679
32232
  return null;
30680
32233
  }
30681
- const said = readFileSync17(marker, "utf8").trim();
32234
+ const said = readFileSync18(marker, "utf8").trim();
30682
32235
  return said === "" ? null : said;
30683
32236
  }
30684
32237
  function loaderAmong(projectPath, named) {
@@ -30689,7 +32242,7 @@ function loaderAmong(projectPath, named) {
30689
32242
  }
30690
32243
  let source = null;
30691
32244
  try {
30692
- source = readFileSync17(join18(projectPath, path), "utf8");
32245
+ source = readFileSync18(join19(projectPath, path), "utf8");
30693
32246
  } catch {}
30694
32247
  if (source?.includes(RUNTIME_AUTOLOAD.path)) {
30695
32248
  return { name: entry, path, exists: true };
@@ -30731,10 +32284,10 @@ function enabledPlugins(settings) {
30731
32284
  function inspectProject(projectPath) {
30732
32285
  const problems = [];
30733
32286
  const addons = ADDONS.map((name) => {
30734
- const directory = join18(projectPath, "addons", name);
30735
- const marker = join18(directory, VERSION_MARKER);
30736
- const installed = existsSync13(directory);
30737
- const version = existsSync13(marker) ? readFileSync17(marker, "utf8").trim() : null;
32287
+ const directory = join19(projectPath, "addons", name);
32288
+ const marker = join19(directory, VERSION_MARKER);
32289
+ const installed = existsSync15(directory);
32290
+ const version = existsSync15(marker) ? readFileSync18(marker, "utf8").trim() : null;
30738
32291
  const current = version === SERVER_VERSION;
30739
32292
  if (!installed) {
30740
32293
  problems.push(`addons/${name} is not installed; run gdharness setup`);
@@ -30743,7 +32296,7 @@ function inspectProject(projectPath) {
30743
32296
  }
30744
32297
  return { name, installed, version, current };
30745
32298
  });
30746
- const settings = parseProjectGodot(readFileSync17(join18(projectPath, "project.godot"), "utf8"));
32299
+ const settings = parseProjectGodot(readFileSync18(join19(projectPath, "project.godot"), "utf8"));
30747
32300
  const pluginsEnabled = enabledPlugins(settings);
30748
32301
  for (const name of EDITOR_PLUGINS) {
30749
32302
  if (!pluginsEnabled.includes(name)) {
@@ -30759,7 +32312,7 @@ function inspectProject(projectPath) {
30759
32312
  const tracked = trackedByGit(projectPath, [...named.values()]);
30760
32313
  const addonMissing = (path) => addons.some((addon) => !addon.installed && path.startsWith(`addons/${addon.name}/`));
30761
32314
  for (const [name, path] of named) {
30762
- if (!existsSync13(join18(projectPath, path))) {
32315
+ if (!existsSync15(join19(projectPath, path))) {
30763
32316
  if (!addonMissing(path)) {
30764
32317
  problems.push(`the ${name} autoload names res://${path}, which is not in this project, so it boots with a missing script; restore that file, or point the autoload at one that is here`);
30765
32318
  }
@@ -31128,7 +32681,7 @@ var TOOL_SPECS = [
31128
32681
  requires: ["resourcePath", "options"]
31129
32682
  },
31130
32683
  reimport: {
31131
- summary: "reimport what status says is outdated or failed, one resource with resourcePath, or what is current as well with force. Through the open editor when one serves the project, so it reloads what it holds, waiting for it to finish; otherwise through the engine's own import pass. Answered from a second status read: reimported lists what is current now, notReimported what is not, with its status and reason, and via says which of the two did the work. A whole-project reimport also answers missingSource, the .import files whose source is not beside them, empty when there are none, whether or not anything needed reimporting; one resourcePath is not a walk of the project and leaves it out. stillImporting is an editor that had not finished within timeoutMs",
32684
+ summary: "reimport what status says is outdated or failed, one resource with resourcePath, or what is current as well with force. Through the open editor when one serves the project, so it reloads what it holds, waiting for it to finish; otherwise through the engine's own import pass. The editor scans first, since its reimport passes over a file it has not taken in, such as one an installer has just written; what that scan imported is named under importedByTheScan and is not imported again unless force asks. Answered from a second status read: reimported lists what is current now, notReimported what is not, one entry per status and reason with the paths sharing them, and via says which of the two did the work. A whole-project reimport also answers missingSource, the .import files whose source is not beside them, empty when there are none, whether or not anything needed reimporting; one resourcePath is not a walk of the project and leaves it out. stillImporting is an editor that had not finished within timeoutMs",
31132
32685
  requires: []
31133
32686
  },
31134
32687
  uid: {
@@ -31346,7 +32899,7 @@ var TOOL_SPECS = [
31346
32899
  },
31347
32900
  {
31348
32901
  name: "script_edit",
31349
- description: "Creates a GDScript file, or adds functions, variables and signals to one. Every declaration written carries a type. Both load what they wrote under the project's own warning settings and answer with parses; the engine's reasons for a refusal come back under engine_messages. create answers with the extends and class_name the engine read, and a script declaring a class_name is put in the project's class list, with registered saying whether it is there. modify makes every addition or none, and answers with the line each one is on in the file written.",
32902
+ description: "Creates a GDScript file, or adds functions, variables and signals to one. Every declaration written carries a type. Both load what they wrote under the project's own warning settings and answer with parses; the engine's reasons for a refusal come back under engine_messages. create answers with the extends and class_name the engine read, and a script declaring a class_name is put in the project's class list, with registered saying whether it is there. modify makes every addition or none, and answers with the line each one is on in the file written. rename renames a class or a member wherever the engine uses it and writes every file or none: changed lists each file with its changed lines as they now read, and leftAlone lists every other whole-word occurrence of the old name with what the tokenizer makes of it (code, string, comment, doc, nodePath, scene or text) and, where it is not plain, why: a find_children string, a word in a comment, a node named like the class, a call on a value whose type the analyser could not tell. Read leftAlone before calling the rename done; nothing in it was changed. Afterwards an open editor scans the changed files and reloads every changed script, which is also the compile check, and its answer comes back under editor; with no editor the class cache is rebuilt and the changed scripts are compiled in a fresh engine, under classCache and compiled.",
31350
32903
  parameters: {
31351
32904
  projectPath: PROJECT_PATH,
31352
32905
  scriptPath: SCRIPT_PATH,
@@ -31361,12 +32914,32 @@ var TOOL_SPECS = [
31361
32914
  enum: ["singleton", "state_machine", "component", "resource"],
31362
32915
  description: "create: a starting shape."
31363
32916
  },
31364
- modifications: SCRIPT_MODIFICATIONS
32917
+ modifications: SCRIPT_MODIFICATIONS,
32918
+ symbol: {
32919
+ type: "string",
32920
+ ops: ["rename"],
32921
+ description: "rename: what to rename, declared by the script at scriptPath: its class_name, or a method, variable, constant, signal, enum, enum value or inner class at its top level. A class is renamed from the files and needs no editor: every bare use in code, the declaration, doc links such as [Told] and [method Told.say], and the script_class a .tres records. A script that declares something of its own by the old name, and a use after a dot, are left alone, since which of those mean the class cannot be told from the text. A member is renamed from what the editor's language server resolves to it, so it needs the editor open on this project; a method is renamed together with every override of it in the classes inheriting it, and from the topmost class declaring it when scriptPath's is itself an override. Doc links naming the member through any class inheriting it are renamed too, and so are a scene's or resource's saved value of a variable on a node or resource whose script inherits it, and a connection naming the signal on its emitter or the method on its receiver. A name the engine itself declares on the native base, such as _ready, is refused, as is a new name already taken: by a class, an autoload, an identifier in code, a native class or built-in type, or a member anywhere in the class's chain."
32922
+ },
32923
+ newName: { type: "string", ops: ["rename"], description: "rename: the new name." },
32924
+ newScriptPath: {
32925
+ type: "string",
32926
+ ops: ["rename"],
32927
+ description: "rename: also move the declaring script here, with its .uid beside it, rewriting every string that names it by path in the same style it was written (res:// or relative), and the relative paths in the moved script itself."
32928
+ },
32929
+ preview: {
32930
+ type: "boolean",
32931
+ ops: ["rename"],
32932
+ description: "rename: answer with what would change and what would be left alone, and write nothing. Default false."
32933
+ }
31365
32934
  },
31366
32935
  requires: ["projectPath", "scriptPath"],
31367
32936
  operations: {
31368
32937
  create: { summary: "a new script file", requires: [] },
31369
- modify: { summary: "add to an existing script", requires: ["modifications"] }
32938
+ modify: { summary: "add to an existing script", requires: ["modifications"] },
32939
+ rename: {
32940
+ summary: "rename a class or a member wherever the engine uses it, across the project",
32941
+ requires: ["symbol", "newName"]
32942
+ }
31370
32943
  }
31371
32944
  },
31372
32945
  {
@@ -31601,7 +33174,7 @@ var TOOL_SPECS = [
31601
33174
  },
31602
33175
  {
31603
33176
  name: "editor_status",
31604
- description: "Whether the editor addon is connected, which Godot answers, whether the editor is playing something, and whether a game with the runtime addon is reachable: runtimeConnected counts the games of the project this server serves, and runtimes lists every game on the machine with ofThisProject saying which is which, since a game of another project is reached only by naming its projectPath. playingInEditor is null when the editor was not asked or did not answer, which is not the same as a no: with no editor connected there is nobody to ask, and an editor that does not serve the question is given a moment and then left. A game can be playing while this is null, so read it as unanswered rather than as nothing playing, and use processActive and runtimes, which come from elsewhere and do not depend on the editor answering. game.run names the run processActive is about, the one editor_output and editor_run stop answer for: its pid, its project, and adopted true when this server read it back from another server rather than starting it; null when there is none. editor.scan says whether the editor is scanning or importing and how many milliseconds ago its last scan finished (finishedMsAgo), or is null when it did not answer: the editor rewrites the class cache just after a scan, and editor_run waits that out before starting a game, saying so under waitedForEditorScanMs. Each game under runtimes is pinged with a short wait, so one held at a breakpoint is listed as unreachable rather than making this call wait out the runtime timeout; for the run this server is reporting on, heldAt says whether that is what it is, with the same three answers editor_output gives. A game the editor played announces the editor under editorPid, and so does whatever that game started for itself; a game some other server started announces none, which is how the two are told apart when both are running from one project. Each game also says which runtime addon it loaded, under addonVersion (null when it cannot say); addonIsStale is true when that code is not what this server ships, and staleNote says whether the project needs gdharness upgrade, the game a restart, or this server a reconnect. A second checkout of a project, such as a git worktree, carries addons of its own and is where this shows. Every runtime_* answer from such a game carries addonIsStale and staleNote too. When connected is false, mayYetConnect says whether that is final: the editor dials this server rather than the other way round and backs off between tries, so for the first half-minute after a server starts, false means \"not reached yet\" as often as it means \"no editor\". True is worth waiting out; false is an editor that is not there. False beside restartInterrupted is one that an editor_launch restart on a previous server asked to quit, where the launch half never ran because that server was ended in between, usually by the reconnect the restart was taken for; editor_launch open finishes it. True beside restartUnderway is a restart still in progress, its server alive and within the wait for the old editor to go: the editor is coming, and opening another would put two on one project. listeningSince is when this server took the bridge port, which is what that window is measured from and what a caller wanting its own window should read. An editor this server opened counts for as long as its process lives, however far past that window the import runs, and awaitingLaunchedEditor names its pid so the two reasons for true are told apart. settingsDropped appears here once when the editor this server opened saved project.godot on its way in, which is the same reading editor_launch restart makes in its own answer. A game that has announced itself in a protocol this server does not speak is listed under unreadable rather than left out, with the protocol it speaks and whether the server or the addon is the older half. This happens during an upgrade that moves the runtime protocol, which most do not: installing replaces the addon on disk as soon as the pin moves, while a server that is already running stays on the version it started with, so the two speak different protocols until the server is reconnected. Those games are real and running, but no tool here can reach them until the halves match, so runtimes stays empty and runtimeConnected stays false. An upgrade that leaves the protocol alone opens no such window and this list stays empty through it. addonIsStale is decided by the code of the editor addons rather than their version, so an editor started before an upgrade that left that code alone reports the older addonVersion, is not stale, and addonNote says so: it needs no restart. port is the one the editor bridge is on; when that is not the one this server was configured with, portWanted names the configured one and portNote says why it moved and, when it was the server this one replaced, which pid kept it. A server replacing another of its project that holds the configured port waits for it to stand down and takes the port over, which takes a few seconds; bridgeHandover says so while it waits, and it moves only if that server has not let go within the wait. An editor that has connected and not yet greeted, which lasts a frame and longer while it imports, reports nothing about itself: greeting says so, addonIsStale is absent rather than guessed, and a restart asked then waits for the greeting to learn who opened it. startedByAnEditor is an editor another editor started, by Godot's own restart or the project manager, which has none of the arguments a server gave the one before it; startedByAnEditorNote says what that costs.",
33177
+ description: "Whether the editor addon is connected, which Godot answers, whether the editor is playing something, and whether a game with the runtime addon is reachable: runtimeConnected counts the games of the project this server serves, and runtimes lists every game on the machine with ofThisProject saying which is which, since a game of another project is reached only by naming its projectPath. playingInEditor is null when the editor was not asked or did not answer, which is not the same as a no: with no editor connected there is nobody to ask, and an editor that does not serve the question is given a moment and then left. A game can be playing while this is null, so read it as unanswered rather than as nothing playing, and use processActive and runtimes, which come from elsewhere and do not depend on the editor answering. game.run names the run processActive is about, the one editor_output and editor_run stop answer for: its pid, its project, and adopted true when this server read it back from another server rather than starting it; null when there is none. editor.scan says whether the editor is scanning or importing and how many milliseconds ago its last scan finished (finishedMsAgo), or is null when it did not answer: the editor rewrites the class cache just after a scan, and editor_run waits that out before starting a game, saying so under waitedForEditorScanMs. Each game under runtimes is pinged with a short wait, so one held at a breakpoint is listed as unreachable rather than making this call wait out the runtime timeout; for the run this server is reporting on, heldAt says whether that is what it is, with the same three answers editor_output gives. A game the editor played announces the editor under editorPid, and so does whatever that game started for itself; a game some other server started announces none, which is how the two are told apart when both are running from one project. Each game also says which runtime addon it loaded, under addonVersion (null when it cannot say); addonIsStale is true when that code is not what this server ships, and staleNote says whether the project needs gdharness upgrade, the game a restart, or this server a reconnect. A second checkout of a project, such as a git worktree, carries addons of its own and is where this shows. Every runtime_* answer from such a game carries addonIsStale and staleNote too. When connected is false, mayYetConnect says whether that is final: the editor dials this server rather than the other way round and backs off between tries, so for the first half-minute after a server starts, false means \"not reached yet\" as often as it means \"no editor\". True is worth waiting out; false is an editor that is not there. False beside restartInterrupted is one that an editor_launch restart on a previous server asked to quit, where the launch half never ran because that server was ended in between, usually by the reconnect the restart was taken for; editor_launch open finishes it. True beside restartUnderway is a restart still in progress, its server alive and within the wait for the old editor to go: the editor is coming, and opening another would put two on one project. listeningSince is when this server took the bridge port, which is what that window is measured from and what a caller wanting its own window should read. An editor this server opened counts for as long as its process lives, however far past that window the import runs, and awaitingLaunchedEditor names its pid so the two reasons for true are told apart. settingsDropped appears here once when the editor this server opened saved project.godot on its way in, which is the same reading editor_launch restart makes in its own answer. A game that has announced itself in a protocol this server does not speak is listed under unreadable rather than left out, with the protocol it speaks and whether the server or the addon is the older half. This happens during an upgrade that moves the runtime protocol, which most do not: installing replaces the addon on disk as soon as the pin moves, while a server that is already running stays on the version it started with, so the two speak different protocols until the server is reconnected. Those games are real and running, but no tool here can reach them until the halves match, so runtimes stays empty and runtimeConnected stays false. An upgrade that leaves the protocol alone opens no such window and this list stays empty through it. addonIsStale is decided by the code of the editor addons rather than their version, so an editor started before an upgrade that left that code alone reports the older addonVersion, is not stale, and addonNote says so: it needs no restart. port is the one the editor bridge is on; when that is not the one this server was configured with, portWanted names the configured one and portNote says why it moved and, when it was the server this one replaced, which pid kept it. A server replacing another of its project that holds the configured port waits for it to stand down and takes the port over, which takes a few seconds; bridgeHandover says so while it waits, and it moves only if that server has not let go within the wait. An editor that has connected and not yet greeted, which lasts a frame and longer while it imports, reports nothing about itself: greeting says so, addonIsStale is absent rather than guessed, and a restart asked then waits for the greeting to learn who opened it. startedByAnEditor is an editor another editor started, by Godot's own restart or the project manager, which has none of the arguments a server gave the one before it; startedByAnEditorNote says what that costs. An engine run that loads the editor addon to do one job and quit, such as a gate's godot --headless --import, an export or a script, is not taken as the editor: a process that greets without a server's mark has its command line read first, and while that is read identifying is true and connected false; one started with such an option is turned away, and turnedAway names the last one, its pid and the option. Every other call made while an editor is arriving, before its greeting or while it is looked up, waits up to ten seconds for it to settle rather than acting on connected as it reads in that window.",
31605
33178
  parameters: {},
31606
33179
  requires: []
31607
33180
  },
@@ -32142,7 +33715,7 @@ function buildToolDefinitions() {
32142
33715
  var UPDATE_NOTICE_EVERY = 500;
32143
33716
  var FEEDBACK_NOTICE_EVERY = 250;
32144
33717
  var run4 = promisify5(execFile5);
32145
- var __dirname2 = dirname12(fileURLToPath4(import.meta.url));
33718
+ var __dirname2 = dirname14(fileURLToPath4(import.meta.url));
32146
33719
  function editorRestartTimeoutMs() {
32147
33720
  const override = Number.parseInt(envValue("GDHARNESS_EDITOR_RESTART_TIMEOUT_MS") ?? "", 10);
32148
33721
  return Number.isInteger(override) && override > 0 ? override : 90000;
@@ -32163,16 +33736,16 @@ function captureDestinationRefusal(outputPath, projects) {
32163
33736
  if (extname2(outputPath).toLowerCase() !== ".png") {
32164
33737
  return `outputPath ${outputPath} does not end in .png, which is what a capture is.`;
32165
33738
  }
32166
- const directory = realPathOr(dirname12(outputPath));
32167
- if (!existsSync14(directory)) {
32168
- return `outputPath's directory ${dirname12(outputPath)} does not exist; a capture creates no directories.`;
33739
+ const directory = realPathOr(dirname14(outputPath));
33740
+ if (!existsSync16(directory)) {
33741
+ return `outputPath's directory ${dirname14(outputPath)} does not exist; a capture creates no directories.`;
32169
33742
  }
32170
- const where = join19(directory, basename4(outputPath));
33743
+ const where = join20(directory, basename5(outputPath));
32171
33744
  const inside = projects.find((project) => project !== "" && isWithinRoot(realPathOr(project), where));
32172
33745
  if (inside !== undefined) {
32173
33746
  return `outputPath ${outputPath} is inside the project at ${inside}; a capture is saved outside it, so it never becomes part of the game.`;
32174
33747
  }
32175
- if (existsSync14(where)) {
33748
+ if (existsSync16(where)) {
32176
33749
  return `outputPath ${outputPath} already exists; a capture is not written over a file. Name a new one.`;
32177
33750
  }
32178
33751
  return null;
@@ -32200,7 +33773,7 @@ function patienceForFrames(frames, atLeast) {
32200
33773
  return Math.max(atLeast, frames / SLOWEST_FRAME_RATE * 1000 + atLeast);
32201
33774
  }
32202
33775
  function projectSpelling(projectPath, absolutePath) {
32203
- return `res://${relative3(realPathOr(projectPath), realPathOr(absolutePath)).replaceAll("\\", "/")}`;
33776
+ return `res://${relative4(realPathOr(projectPath), realPathOr(absolutePath)).replaceAll("\\", "/")}`;
32204
33777
  }
32205
33778
  function whichGame(args) {
32206
33779
  return { projectPath: args["projectPath"], pid: args["pid"] };
@@ -32711,6 +34284,7 @@ var PROJECT_FILE_ARGUMENTS = [
32711
34284
  "scriptPath",
32712
34285
  "resourcePath",
32713
34286
  "newPath",
34287
+ "newScriptPath",
32714
34288
  "path",
32715
34289
  "script"
32716
34290
  ];
@@ -32762,7 +34336,7 @@ function aboveTheRunner(entry) {
32762
34336
  }
32763
34337
  function elsewhereIn(projectPath, asked) {
32764
34338
  const wanted = asked.replace(/^res:\/\//, "").replace(/\/+$/, "");
32765
- if (wanted === "" || existsSync14(join19(projectPath, wanted))) {
34339
+ if (wanted === "" || existsSync16(join20(projectPath, wanted))) {
32766
34340
  return "";
32767
34341
  }
32768
34342
  const root = (wanted.split("/")[0] ?? "").toLowerCase();
@@ -32776,7 +34350,7 @@ function elsewhereIn(projectPath, asked) {
32776
34350
  return near.length === 0 ? "" : ` The project does have ${there}.`;
32777
34351
  }
32778
34352
  function hasMainScene(projectFile) {
32779
- const scene = parseProjectGodot(readFileSync18(projectFile, "utf8"))["application"]?.["run/main_scene"];
34353
+ const scene = parseProjectGodot(readFileSync19(projectFile, "utf8"))["application"]?.["run/main_scene"];
32780
34354
  return typeof scene === "string" && scene !== "";
32781
34355
  }
32782
34356
  function runtimeAddonAnnouncesEditors(projectPath) {
@@ -32784,13 +34358,13 @@ function runtimeAddonAnnouncesEditors(projectPath) {
32784
34358
  return false;
32785
34359
  }
32786
34360
  try {
32787
- return readFileSync18(join19(projectPath, RUNTIME_AUTOLOAD.path), "utf8").includes('"editor_pid"');
34361
+ return readFileSync19(join20(projectPath, RUNTIME_AUTOLOAD.path), "utf8").includes('"editor_pid"');
32788
34362
  } catch {
32789
34363
  return false;
32790
34364
  }
32791
34365
  }
32792
34366
  function editorPlaysHeadless(projectFile) {
32793
- const runArgs = parseProjectGodot(readFileSync18(projectFile, "utf8"))["editor"]?.["run/main_run_args"];
34367
+ const runArgs = parseProjectGodot(readFileSync19(projectFile, "utf8"))["editor"]?.["run/main_run_args"];
32794
34368
  return typeof runArgs === "string" && /(?:^|\s)--headless(?:\s|$)/.test(runArgs);
32795
34369
  }
32796
34370
  function camelCased(params) {
@@ -32809,7 +34383,7 @@ function needsItsOwnProcess(asked) {
32809
34383
  class GodotServer {
32810
34384
  mcp;
32811
34385
  locator = new GodotLocator;
32812
- operationsScript = join19(__dirname2, "godot", "operations", "godot_operations.gd");
34386
+ operationsScript = join20(__dirname2, "godot", "operations", "godot_operations.gd");
32813
34387
  godotBridge;
32814
34388
  tools = buildToolDefinitions();
32815
34389
  activeProcess = null;
@@ -32839,6 +34413,7 @@ class GodotServer {
32839
34413
  constructor() {
32840
34414
  this.ownProject = envValue("GDHARNESS_PROJECT") ?? null;
32841
34415
  this.godotBridge = getDefaultBridge(this.ownProject);
34416
+ this.godotBridge.identifyEditorsWith(oneShotOptionOf);
32842
34417
  this.godotBridge.on("godot_connected", () => {
32843
34418
  this.settleTheLaunchReading();
32844
34419
  });
@@ -33111,7 +34686,7 @@ class GodotServer {
33111
34686
  return checked.response;
33112
34687
  }
33113
34688
  const named = args["projectPath"];
33114
- if (typeof named === "string" && existsSync14(join19(named, "project.godot"))) {
34689
+ if (typeof named === "string" && existsSync16(join20(named, "project.godot"))) {
33115
34690
  this.lastProjectPath = named;
33116
34691
  }
33117
34692
  this.updates.refresh();
@@ -33304,6 +34879,9 @@ class GodotServer {
33304
34879
  return { ok: true, op };
33305
34880
  }
33306
34881
  async dispatch(tool, op, args) {
34882
+ if (tool !== "editor_status" && this.godotBridge.isArriving()) {
34883
+ await this.waitForBridge(() => !this.godotBridge.isArriving(), Date.now() + GREETING_WAIT_MS);
34884
+ }
33307
34885
  if (ENGINE_PASSES[tool]?.[op] !== undefined) {
33308
34886
  return op === "reimport" ? await this.handleReimport(args) : await this.handleRefreshUids(args);
33309
34887
  }
@@ -33404,6 +34982,8 @@ class GodotServer {
33404
34982
  default:
33405
34983
  return await bridge("connect_animation_states");
33406
34984
  }
34985
+ case "script_edit":
34986
+ return await this.handleRenameSymbol(args);
33407
34987
  case "script_info":
33408
34988
  switch (op) {
33409
34989
  case "symbols":
@@ -33579,8 +35159,8 @@ class GodotServer {
33579
35159
  if (path === undefined) {
33580
35160
  return { ok: false, response: this.createErrorResponse("projectPath is required.") };
33581
35161
  }
33582
- const file = join19(path, "project.godot");
33583
- if (!existsSync14(file)) {
35162
+ const file = join20(path, "project.godot");
35163
+ if (!existsSync16(file)) {
33584
35164
  return {
33585
35165
  ok: false,
33586
35166
  response: this.createErrorResponse(`Not a Godot project: ${path}`, [
@@ -34020,8 +35600,39 @@ class GodotServer {
34020
35600
  }
34021
35601
  const viaEditor = this.editorHasOpen(projectPath);
34022
35602
  const extra = {};
35603
+ const statusAsk = resourcePath === undefined ? { includeUpToDate: true } : { resourcePath };
34023
35604
  if (viaEditor) {
34024
- const inEditor = await this.reimportInTheEditor(targets, timeoutMs);
35605
+ const scan = await this.handleRescanFilesystem({ projectPath, timeoutMs });
35606
+ if (scan.isError === true) {
35607
+ return { ok: false, response: scan };
35608
+ }
35609
+ const scanned = asParams(JSON.parse(scan.content[0]?.text ?? "{}"));
35610
+ if (scanned["stillWorking"] === true) {
35611
+ return {
35612
+ ok: true,
35613
+ payload: {
35614
+ via: "editor",
35615
+ stillImporting: true,
35616
+ asked: targets,
35617
+ ...sourceless,
35618
+ note: `The editor's scan of the project had not finished after ${timeoutMs} ms, and the reimport waits for it. project_import status says what it has done so far; pass a longer timeoutMs to wait it out.`
35619
+ }
35620
+ };
35621
+ }
35622
+ let remaining = targets;
35623
+ if (!force) {
35624
+ const between = await this.operation("get_import_status", statusAsk, projectPath);
35625
+ if (!between.ok) {
35626
+ return { ok: false, response: this.answer(between) };
35627
+ }
35628
+ const fresh = new Map(importStatuses(between.payload).map((one) => [one.path, one.status]));
35629
+ const caughtUp = targets.filter((path) => fresh.get(path) === "up_to_date");
35630
+ remaining = targets.filter((path) => !caughtUp.includes(path));
35631
+ if (caughtUp.length > 0) {
35632
+ extra["importedByTheScan"] = caughtUp;
35633
+ }
35634
+ }
35635
+ const inEditor = remaining.length === 0 ? { ok: true, finished: true } : await this.reimportInTheEditor(remaining, timeoutMs);
34025
35636
  if (!inEditor.ok) {
34026
35637
  return inEditor;
34027
35638
  }
@@ -34052,17 +35663,22 @@ class GodotServer {
34052
35663
  extra["extensionNote"] = imported.extensionNote;
34053
35664
  }
34054
35665
  }
34055
- const after = await this.operation("get_import_status", resourcePath === undefined ? { includeUpToDate: true } : { resourcePath }, projectPath);
35666
+ const after = await this.operation("get_import_status", statusAsk, projectPath);
34056
35667
  if (!after.ok) {
34057
35668
  return { ok: false, response: this.answer(after) };
34058
35669
  }
34059
35670
  const now = new Map(importStatuses(after.payload).map((one) => [one.path, one]));
34060
35671
  const reimported = targets.filter((path) => now.get(path)?.status === "up_to_date");
34061
- const notReimported = targets.filter((path) => now.get(path)?.status !== "up_to_date").map((path) => ({
34062
- path,
34063
- status: now.get(path)?.status ?? "unknown",
34064
- ...now.get(path)?.reason === undefined ? {} : { reason: now.get(path)?.reason }
34065
- }));
35672
+ const groups = new Map;
35673
+ for (const path of targets.filter((one) => now.get(one)?.status !== "up_to_date")) {
35674
+ const status = now.get(path)?.status ?? "unknown";
35675
+ const reason = now.get(path)?.reason;
35676
+ const key = `${status}\x00${reason ?? ""}`;
35677
+ const group = groups.get(key) ?? { status, ...reason === undefined ? {} : { reason }, paths: [] };
35678
+ group.paths.push(path);
35679
+ groups.set(key, group);
35680
+ }
35681
+ const notReimported = [...groups.values()];
34066
35682
  return {
34067
35683
  ok: true,
34068
35684
  payload: {
@@ -34154,11 +35770,11 @@ class GodotServer {
34154
35770
  if (!engine.ok) {
34155
35771
  return engine.response;
34156
35772
  }
34157
- const application = parseProjectGodot(readFileSync18(project.value.file, "utf8"))["application"] ?? {};
35773
+ const application = parseProjectGodot(readFileSync19(project.value.file, "utf8"))["application"] ?? {};
34158
35774
  const name = application["config/name"];
34159
35775
  const mainScene = application["run/main_scene"];
34160
35776
  const info = {
34161
- name: typeof name === "string" && name !== "" ? name : basename4(project.value.path),
35777
+ name: typeof name === "string" && name !== "" ? name : basename5(project.value.path),
34162
35778
  path: project.value.path,
34163
35779
  mainScene: typeof mainScene === "string" && mainScene !== "" ? mainScene : null,
34164
35780
  godotVersion: await this.godotVersion(engine.value),
@@ -34210,18 +35826,18 @@ class GodotServer {
34210
35826
  if (!engine.ok) {
34211
35827
  return engine.response;
34212
35828
  }
34213
- const folder = dirname12(output.absolutePath);
35829
+ const folder = dirname14(output.absolutePath);
34214
35830
  try {
34215
- mkdirSync10(folder, { recursive: true });
35831
+ mkdirSync11(folder, { recursive: true });
34216
35832
  } catch (error) {
34217
- return this.createErrorResponse(`Cannot create ${dirname12(output.relativePath)} to export into: ${errorMessage(error)}`);
35833
+ return this.createErrorResponse(`Cannot create ${dirname14(output.relativePath)} to export into: ${errorMessage(error)}`);
34218
35834
  }
34219
35835
  const debug = readBoolean(args, "debug") ?? false;
34220
35836
  const exportLogs = scratchDirectory("export");
34221
35837
  const exportArgs = [
34222
35838
  "--headless",
34223
35839
  "--log-file",
34224
- join19(exportLogs, "engine.log"),
35840
+ join20(exportLogs, "engine.log"),
34225
35841
  "--path",
34226
35842
  project.value.path,
34227
35843
  debug ? "--export-debug" : "--export-release",
@@ -34229,7 +35845,7 @@ class GodotServer {
34229
35845
  output.absolutePath
34230
35846
  ];
34231
35847
  this.logDebug(`Exporting: ${engine.value} ${exportArgs.join(" ")}`);
34232
- const writtenAt = () => existsSync14(output.absolutePath) ? statSync8(output.absolutePath).mtimeMs : null;
35848
+ const writtenAt = () => existsSync16(output.absolutePath) ? statSync8(output.absolutePath).mtimeMs : null;
34233
35849
  const before = writtenAt();
34234
35850
  let ending;
34235
35851
  try {
@@ -34252,7 +35868,7 @@ class GodotServer {
34252
35868
  return contained.response;
34253
35869
  }
34254
35870
  const runner = "addons/gdUnit4/bin/GdUnitCmdTool.gd";
34255
- if (!existsSync14(join19(project.value.path, runner))) {
35871
+ if (!existsSync16(join20(project.value.path, runner))) {
34256
35872
  return this.createErrorResponse(`gdUnit4 is not installed in this project: no ${runner}.`, [
34257
35873
  "Install gdUnit4 under addons/gdUnit4, from https://github.com/godot-gdunit-labs/gdUnit4"
34258
35874
  ]);
@@ -34319,21 +35935,21 @@ class GodotServer {
34319
35935
  await untilGone([run.process.pid]);
34320
35936
  }
34321
35937
  await run.settled;
34322
- const reportsDir = join19(project.value.path, ".godot", ...ours.split("/"));
35938
+ const reportsDir = join20(project.value.path, ".godot", ...ours.split("/"));
34323
35939
  let report = null;
34324
35940
  let reportProblem = null;
34325
35941
  try {
34326
- const written = existsSync14(reportsDir) ? readdirSync8(reportsDir).filter((name) => name.startsWith("report_")).sort((a, b) => Number(a.slice("report_".length)) - Number(b.slice("report_".length))) : [];
35942
+ const written = existsSync16(reportsDir) ? readdirSync8(reportsDir).filter((name) => name.startsWith("report_")).sort((a, b) => Number(a.slice("report_".length)) - Number(b.slice("report_".length))) : [];
34327
35943
  const newest = written.at(-1);
34328
35944
  if (newest !== undefined) {
34329
- report = parseJUnit(readFileSync18(join19(reportsDir, newest, "results.xml"), "utf8"));
35945
+ report = parseJUnit(readFileSync19(join20(reportsDir, newest, "results.xml"), "utf8"));
34330
35946
  }
34331
35947
  } catch (error) {
34332
35948
  reportProblem = errorMessage(error);
34333
35949
  } finally {
34334
35950
  discard(reportsDir, userData);
34335
35951
  try {
34336
- rmdirSync2(dirname12(reportsDir));
35952
+ rmdirSync2(dirname14(reportsDir));
34337
35953
  } catch {}
34338
35954
  }
34339
35955
  const engineEntries = run.log.select({ severity: "warning", sinceLastCall: false, limit: 200 }).entries.map(aboveTheRunner);
@@ -34511,11 +36127,11 @@ class GodotServer {
34511
36127
  const cached = cachedClasses(projectPath);
34512
36128
  const contradicted = cached === null ? [] : contradictedDiagnostics(messages, cached, (resourcePath) => {
34513
36129
  const contained = resolveWithinProject(projectPath, resourcePath);
34514
- if (!contained.ok || !existsSync14(contained.absolutePath)) {
36130
+ if (!contained.ok || !existsSync16(contained.absolutePath)) {
34515
36131
  return null;
34516
36132
  }
34517
36133
  try {
34518
- return readFileSync18(contained.absolutePath, "utf8");
36134
+ return readFileSync19(contained.absolutePath, "utf8");
34519
36135
  } catch {
34520
36136
  return null;
34521
36137
  }
@@ -34571,23 +36187,26 @@ class GodotServer {
34571
36187
  }
34572
36188
  sourceOfClass(projectPath, resourcePath) {
34573
36189
  const contained = resolveWithinProject(projectPath, resourcePath);
34574
- if (!contained.ok || !existsSync14(contained.absolutePath)) {
36190
+ if (!contained.ok || !existsSync16(contained.absolutePath)) {
34575
36191
  return null;
34576
36192
  }
34577
36193
  try {
34578
- return readFileSync18(contained.absolutePath, "utf8");
36194
+ return readFileSync19(contained.absolutePath, "utf8");
34579
36195
  } catch {
34580
36196
  return null;
34581
36197
  }
34582
36198
  }
34583
36199
  async handleLSP(toolName, args) {
36200
+ return handleLSPTool(await this.lsp(), toolName, args);
36201
+ }
36202
+ async lsp() {
34584
36203
  const port = this.editorServes("lspPort", "GDHARNESS_LSP_PORT", DEFAULT_LSP_PORT);
34585
36204
  if (this.lspClient !== null && this.lspClient.port !== port) {
34586
36205
  await this.lspClient.disconnect();
34587
36206
  this.lspClient = null;
34588
36207
  }
34589
36208
  this.lspClient ??= new GodotLSPClient(port);
34590
- return handleLSPTool(this.lspClient, toolName, args);
36209
+ return this.lspClient;
34591
36210
  }
34592
36211
  async handleDAP(toolName, args) {
34593
36212
  return handleDAPTool(this.dap(), toolName, args);
@@ -34883,7 +36502,7 @@ class GodotServer {
34883
36502
  return null;
34884
36503
  }
34885
36504
  try {
34886
- return settingKeys(readFileSync18(join19(projectPath, "project.godot"), "utf8"));
36505
+ return settingKeys(readFileSync19(join20(projectPath, "project.godot"), "utf8"));
34887
36506
  } catch {
34888
36507
  return null;
34889
36508
  }
@@ -34897,14 +36516,7 @@ class GodotServer {
34897
36516
  ]);
34898
36517
  }
34899
36518
  if (!hasSaidWhoItIs(before)) {
34900
- const settled = await this.waitForBridge(() => hasSaidWhoItIs(this.godotBridge.getStatus()) || !this.godotBridge.isConnected(), Date.now() + GREETING_WAIT_MS);
34901
- if (!settled) {
34902
- return this.createErrorResponse(`The editor has connected and has not said who it is within ${GREETING_WAIT_MS / 1000}s, so whether this server or the editor itself restarts it cannot be told.`, [
34903
- "editor_status says when it has, under greeting while it has not",
34904
- "Then ask for the restart again"
34905
- ]);
34906
- }
34907
- return this.handleRestartEditor(args);
36519
+ return this.createErrorResponse(`The editor has connected and has not said who it is within ${GREETING_WAIT_MS / 1000}s, so whether this server or the editor itself restarts it cannot be told.`, ["editor_status says when it has, under greeting while it has not", "Then ask for the restart again"]);
34908
36520
  }
34909
36521
  const mine = before.openedByAServer === true && before.projectPath !== undefined;
34910
36522
  if (!mine && args["hidden"] === true) {
@@ -35098,6 +36710,10 @@ class GodotServer {
35098
36710
  const dap = portFromEnvOrNull("GDHARNESS_DAP_PORT") ?? await freePort(DEFAULT_DAP_PORT);
35099
36711
  return { lsp, dap };
35100
36712
  }
36713
+ editorOnTheBridge() {
36714
+ const pid = this.godotBridge.getStatus().editorPid;
36715
+ return pid === undefined ? "the editor on this bridge" : `the editor on this bridge (pid ${pid})`;
36716
+ }
35101
36717
  async handleRunProject(args, op) {
35102
36718
  const project = this.project(args);
35103
36719
  if (!project.ok) {
@@ -35105,7 +36721,7 @@ class GodotServer {
35105
36721
  }
35106
36722
  const open = this.godotBridge.isConnected() ? this.godotBridge.getStatus().projectPath : undefined;
35107
36723
  if (op !== "check" && open !== undefined && open !== "" && !isSameDirectory(open, project.value.path)) {
35108
- return this.createErrorResponse(`This start names ${project.value.path}, and the editor on this bridge has ${open} open.`, [
36724
+ return this.createErrorResponse(`This start names ${project.value.path}, and ${this.editorOnTheBridge()} has ${open} open.`, [
35109
36725
  "editor_status names the project this server's editor is showing",
35110
36726
  "One server serves one editor: start a second server for the other project"
35111
36727
  ]);
@@ -35208,7 +36824,7 @@ class GodotServer {
35208
36824
  }
35209
36825
  async runtimeUp(projectPath, before, budget, withArgs) {
35210
36826
  const budgetMs = budget.ms;
35211
- if (!existsSync14(join19(projectPath, RUNTIME_AUTOLOAD.path))) {
36827
+ if (!existsSync16(join20(projectPath, RUNTIME_AUTOLOAD.path))) {
35212
36828
  return runtimeVerdict(null, { addon: false, budgetMs, heldAt: null, running: false, withArgs });
35213
36829
  }
35214
36830
  let asking = null;
@@ -35459,7 +37075,7 @@ class GodotServer {
35459
37075
  return 0;
35460
37076
  }
35461
37077
  try {
35462
- return reportAlreadyInTranscript(readFileSync18(game.transcript), readFileSync18(report));
37078
+ return reportAlreadyInTranscript(readFileSync19(game.transcript), readFileSync19(report));
35463
37079
  } catch (error) {
35464
37080
  this.logDebug(`Could not compare a picked-up run's report with its transcript: ${errorMessage(error)}`);
35465
37081
  return 0;
@@ -36217,7 +37833,7 @@ class GodotServer {
36217
37833
  notes.push(endedWithoutACode({
36218
37834
  throughEditor: run.throughEditor,
36219
37835
  announced: announced !== undefined || run.announcedPid !== undefined,
36220
- couldAnnounce: run.projectPath !== null && existsSync14(join19(run.projectPath, RUNTIME_AUTOLOAD.path)),
37836
+ couldAnnounce: run.projectPath !== null && existsSync16(join20(run.projectPath, RUNTIME_AUTOLOAD.path)),
36221
37837
  endedHere: typeof run.endedHere === "string",
36222
37838
  pickedUp: run.pickedUp === true
36223
37839
  }));
@@ -36464,11 +38080,9 @@ class GodotServer {
36464
38080
  const timeoutMs = readPositiveNumber(args, "timeoutMs") ?? 30000;
36465
38081
  const started = Date.now();
36466
38082
  const projectPath = typeof args["projectPath"] === "string" ? args["projectPath"] : "";
36467
- const before = projectPath === "" ? null : cachedClasses(projectPath);
36468
- const writtenBefore = projectPath === "" ? null : cacheWrittenAt(projectPath);
36469
- const blind = await this.classesTheEditorCannotSee(args);
36470
- const atRisk = before === null ? [] : blind.unseen.filter((one) => before.has(one.className));
36471
- const ghosts = blind.stillHeld ?? [];
38083
+ let before = null;
38084
+ let writtenBefore = null;
38085
+ let blind = { unseen: [] };
36472
38086
  let waitedForEditorMs = 0;
36473
38087
  let first;
36474
38088
  let completedBefore;
@@ -36484,6 +38098,9 @@ class GodotServer {
36484
38098
  if (wasBusy) {
36485
38099
  waitedForEditorMs += Date.now() - busySince;
36486
38100
  }
38101
+ before = projectPath === "" ? null : cachedClasses(projectPath);
38102
+ writtenBefore = projectPath === "" ? null : cacheWrittenAt(projectPath);
38103
+ blind = await this.classesTheEditorCannotSee(args);
36487
38104
  first = await this.handleViaBridge("rescan_filesystem", args);
36488
38105
  if (first.isError) {
36489
38106
  return first;
@@ -36500,6 +38117,9 @@ class GodotServer {
36500
38117
  }
36501
38118
  await new Promise((settle) => setTimeout(settle, 100));
36502
38119
  }
38120
+ const held = before;
38121
+ const atRisk = held === null ? [] : blind.unseen.filter((one) => held.has(one.className));
38122
+ const ghosts = blind.stillHeld ?? [];
36503
38123
  let busy = true;
36504
38124
  let idleSince = null;
36505
38125
  while (Date.now() - started < timeoutMs) {
@@ -36637,9 +38257,12 @@ class GodotServer {
36637
38257
  });
36638
38258
  }
36639
38259
  async reloadDependents(projectPath, classes) {
38260
+ return await this.reloadInEditor(scriptsNaming(projectPath, classes));
38261
+ }
38262
+ async reloadInEditor(scripts) {
36640
38263
  const reloaded = [];
36641
38264
  const notReloaded = [];
36642
- for (const { script: scriptPath, tool } of scriptsNaming(projectPath, classes)) {
38265
+ for (const { script: scriptPath, tool } of scripts) {
36643
38266
  if (tool) {
36644
38267
  notReloaded.push({
36645
38268
  scriptPath,
@@ -36756,6 +38379,159 @@ class GodotServer {
36756
38379
  });
36757
38380
  return this.godotBridge.isConnected() ? await this.alsoSayWhatTheEditorCannotSee(answered, args) : answered;
36758
38381
  }
38382
+ async handleRenameSymbol(given) {
38383
+ const project = this.project(given);
38384
+ if (!project.ok) {
38385
+ return project.response;
38386
+ }
38387
+ const contained = this.containProjectFiles(given);
38388
+ if (!contained.ok) {
38389
+ return contained.response;
38390
+ }
38391
+ const args = contained.value;
38392
+ const projectPath = project.value.path;
38393
+ const scriptPath = resolveWithinProject(projectPath, readNonEmptyString(args, "scriptPath") ?? "");
38394
+ if (!scriptPath.ok) {
38395
+ return this.createErrorResponse(scriptPath.reason);
38396
+ }
38397
+ if (!existsSync16(scriptPath.absolutePath)) {
38398
+ return this.createErrorResponse(`Script file does not exist: ${scriptPath.absolutePath}`);
38399
+ }
38400
+ const asked = readNonEmptyString(args, "newScriptPath");
38401
+ const moveTo = asked === undefined ? null : resolveWithinProject(projectPath, asked);
38402
+ if (moveTo !== null && !moveTo.ok) {
38403
+ return this.createErrorResponse(moveTo.reason);
38404
+ }
38405
+ const languageServer = {
38406
+ problem: null,
38407
+ initialized: false
38408
+ };
38409
+ const askTheLanguageServer = async (question) => {
38410
+ const client = await this.lsp();
38411
+ try {
38412
+ if (!languageServer.initialized) {
38413
+ await client.initialize(projectPath);
38414
+ languageServer.initialized = true;
38415
+ }
38416
+ return await question(client);
38417
+ } catch (error) {
38418
+ languageServer.problem = normalizeLSPError(error, client.port);
38419
+ throw error;
38420
+ }
38421
+ };
38422
+ const symbol = readNonEmptyString(args, "symbol") ?? "";
38423
+ const newName = readNonEmptyString(args, "newName") ?? "";
38424
+ const outcome = await renameSymbol({
38425
+ projectPath,
38426
+ scriptPath: scriptPath.absolutePath,
38427
+ symbol,
38428
+ newName,
38429
+ newScriptPath: moveTo === null ? null : moveTo.absolutePath
38430
+ }, {
38431
+ namesTaken: async (names, base) => {
38432
+ const asked = await this.operation("names_taken", { names: [...names], base: base ?? "" }, projectPath);
38433
+ if (!asked.ok) {
38434
+ throw new Error(`the engine could not be asked whether ${names.join(" or ")} is taken: ${asked.message}`);
38435
+ }
38436
+ return asParams(asked.payload["taken"]);
38437
+ },
38438
+ references: async (absolute, text, at) => await askTheLanguageServer((client) => client.getReferences(absolute, text, at.line, at.character)),
38439
+ definitions: async (absolute, text, at) => await askTheLanguageServer((client) => client.getDefinitions(absolute, text, at.line, at.character))
38440
+ }).catch((error) => ({ ok: false, reason: errorMessage(error) }));
38441
+ if (!outcome.ok) {
38442
+ if (languageServer.problem !== null) {
38443
+ return this.createErrorResponse(`Renaming a member needs the editor's language server, because which uses of the name are this class's depends on the types only the engine's analyser knows. ${languageServer.problem}`, [
38444
+ "editor_launch opens the editor, whose language server this uses",
38445
+ "A class_name is renamed from the files and needs no editor"
38446
+ ]);
38447
+ }
38448
+ const said = outcome.conflicts === undefined ? "" : ` ${outcome.conflicts.join("; ")}.`;
38449
+ return this.createErrorResponse(`${outcome.reason}${said}`, outcome.advice ?? []);
38450
+ }
38451
+ if (readBoolean(args, "preview") === true) {
38452
+ return this.jsonTextResponse({ preview: true, ...outcome.report });
38453
+ }
38454
+ try {
38455
+ applyRewrites(outcome.rewrites);
38456
+ } catch (error) {
38457
+ return this.createErrorResponse(`Nothing was renamed: ${errorMessage(error)}`);
38458
+ }
38459
+ const settled = this.godotBridge.isConnected() ? await this.settleRenameInEditor(projectPath, outcome.scriptsInOrder, {
38460
+ gone: outcome.moved === null ? [] : [outcome.moved.from],
38461
+ oldClass: outcome.isClass ? symbol : null,
38462
+ newClass: outcome.isClass ? newName : null
38463
+ }) : await this.settleRenameOnDisk(projectPath, outcome.scriptsInOrder, {
38464
+ rebuildCache: outcome.isClass || outcome.moved !== null,
38465
+ moved: outcome.moved !== null
38466
+ });
38467
+ return this.jsonTextResponse({ ok: settled.ok, ...outcome.report, ...settled.report });
38468
+ }
38469
+ async settleRenameInEditor(projectPath, changed, names) {
38470
+ const { gone, oldClass, newClass } = names;
38471
+ const scanned = asParams(JSON.parse((await this.handleRescanFilesystem({
38472
+ projectPath,
38473
+ timeoutMs: 60000,
38474
+ updateFiles: [...gone, ...changed]
38475
+ })).content[0]?.text ?? "{}"));
38476
+ const reloadedByTheScan = new Set((readArray(scanned, "dependentsReloaded") ?? []).map(String));
38477
+ const toReload = [];
38478
+ for (const script of changed) {
38479
+ if (!reloadedByTheScan.has(script)) {
38480
+ const source = this.sourceOfClass(projectPath, script);
38481
+ toReload.push({ script, tool: source !== null && isToolScript(source) });
38482
+ }
38483
+ }
38484
+ const done = await this.reloadInEditor(toReload);
38485
+ const notReloaded = done.notReloaded;
38486
+ const reloaded = [...reloadedByTheScan, ...done.reloaded].sort();
38487
+ const checked = oldClass === null ? null : await this.classesTheEditorCannotSee({ projectPath });
38488
+ const stillHeld = oldClass !== null && (checked?.stillHeld?.includes(oldClass) === true || (readArray(scanned, "cacheDropped") ?? []).map(String).includes(oldClass) || (readArray(scanned, "cacheAtMissingPaths") ?? []).map(String).includes(oldClass));
38489
+ const unseen = newClass !== null && checked?.unseen.some((one) => one.className === newClass) === true;
38490
+ const notes = [];
38491
+ if (stillHeld) {
38492
+ notes.push(`The editor still holds ${oldClass} after the scan, so it resolves the old name until it is restarted with editor_launch restart, and writes it back into the class cache on every scan until then.`);
38493
+ }
38494
+ if (unseen) {
38495
+ notes.push(`The editor does not hold ${newClass} after the scan, so every use of it reads as an unknown identifier there: editor_rescan on its own, or editor_launch restart.`);
38496
+ }
38497
+ if (scanned["stillWorking"] === true) {
38498
+ notes.push("The editor was still scanning when the wait ran out, so it may not hold the new names yet.");
38499
+ }
38500
+ return {
38501
+ ok: scanned["stillWorking"] !== true && notReloaded.length === 0 && !stillHeld && !unseen,
38502
+ report: {
38503
+ editor: {
38504
+ reloaded,
38505
+ ...notReloaded.length > 0 ? { notReloaded } : {},
38506
+ ...stillHeld ? { stillHolds: oldClass } : {},
38507
+ ...typeof scanned["note"] === "string" ? { scanNote: scanned["note"] } : {}
38508
+ },
38509
+ ...notes.length > 0 ? { note: notes.join(" ") } : {}
38510
+ }
38511
+ };
38512
+ }
38513
+ async settleRenameOnDisk(projectPath, changed, asked) {
38514
+ const report = {};
38515
+ let ok = true;
38516
+ if (asked.moved) {
38517
+ const engine = await this.engine();
38518
+ const imported = engine.ok ? await runImport(engine.value, projectPath) : null;
38519
+ const problem = imported === null ? engine.ok ? "" : engine.response.content.map((block) => block.text).join(" ") : imported.ok ? null : imported.message;
38520
+ report["uidTable"] = problem === null ? "rebuilt by an import pass" : `not rebuilt: ${problem}`;
38521
+ ok &&= problem === null;
38522
+ }
38523
+ if (asked.rebuildCache) {
38524
+ const rebuilt = await this.rebuildClassCache(projectPath);
38525
+ report["classCache"] = rebuilt.ok ? rebuilt.payload : { rebuilt: false, problem: rebuilt.message };
38526
+ ok &&= rebuilt.ok;
38527
+ }
38528
+ if (changed.length > 0) {
38529
+ const compiled = await this.operation("check_scripts", { paths: [...changed] }, projectPath);
38530
+ report["compiled"] = compiled.ok ? { ...compiled.payload, ...engineExtras(compiled) } : { problem: compiled.message };
38531
+ ok &&= compiled.ok && (readArray(compiled.payload, "failed") ?? []).length === 0;
38532
+ }
38533
+ return { ok, report };
38534
+ }
36759
38535
  async alsoSayWhatTheEditorCannotSee(answered, args) {
36760
38536
  const first = answered.content[0];
36761
38537
  if (answered.isError || first?.type !== "text" || typeof first.text !== "string") {
@@ -36822,7 +38598,7 @@ class GodotServer {
36822
38598
  const open = this.godotBridge.getStatus().projectPath;
36823
38599
  const meant = readNonEmptyString(args, "projectPath");
36824
38600
  if (open !== undefined && open !== "" && meant !== undefined && !isSameDirectory(open, meant)) {
36825
- return this.createErrorResponse(`This call names ${meant}, and the editor on this bridge has ${open} open.`, [
38601
+ return this.createErrorResponse(`This call names ${meant}, and ${this.editorOnTheBridge()} has ${open} open.`, [
36826
38602
  "editor_status names the project this server's editor is showing",
36827
38603
  "One server serves one editor: start a second server for the other project"
36828
38604
  ]);
@@ -36884,7 +38660,7 @@ class GodotServer {
36884
38660
  async ownRunOnItsWay(projectPath, budgetMs) {
36885
38661
  const run = await this.currentRun();
36886
38662
  const project = projectPath ?? run?.projectPath ?? null;
36887
- if (run === null || project === null || run.announcedPid !== undefined || run.projectPath !== null && !isSameDirectory(run.projectPath, project) || !existsSync14(join19(project, RUNTIME_AUTOLOAD.path)) || !await this.runStillGoing(run)) {
38663
+ if (run === null || project === null || run.announcedPid !== undefined || run.projectPath !== null && !isSameDirectory(run.projectPath, project) || !existsSync16(join20(project, RUNTIME_AUTOLOAD.path)) || !await this.runStillGoing(run)) {
36888
38664
  return null;
36889
38665
  }
36890
38666
  const already = runtimesAnnounced().running;
@@ -36968,7 +38744,7 @@ class GodotServer {
36968
38744
  }
36969
38745
  }
36970
38746
  const screenshotDir = expectsScreenshot ? scratchDirectory("runtime-screenshot") : null;
36971
- const screenshotPath = screenshotDir ? join19(screenshotDir, "capture.png") : null;
38747
+ const screenshotPath = screenshotDir ? join20(screenshotDir, "capture.png") : null;
36972
38748
  const staleNote = this.runtimeStaleNote(choice.endpoint);
36973
38749
  const stale = staleNote === undefined ? {} : { addonIsStale: true, staleNote };
36974
38750
  const refused = (message) => this.createErrorResponse(staleNote === undefined ? message : `${message}
@@ -37017,7 +38793,7 @@ ${staleNote}`);
37017
38793
 
37018
38794
  ${staleNote}`}`
37019
38795
  },
37020
- { type: "image", data: readFileSync18(screenshotPath).toString("base64"), mimeType: "image/png" }
38796
+ { type: "image", data: readFileSync19(screenshotPath).toString("base64"), mimeType: "image/png" }
37021
38797
  ]
37022
38798
  };
37023
38799
  } finally {