@tsrx/content-mapper 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,3320 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
- import { createHash } from "node:crypto";
4
- import fs from "node:fs";
5
- import path from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { createRequire as createRequire$1 } from "module";
8
- import path$1 from "path";
9
- import { parse, printParseErrorCode } from "jsonc-parser";
10
- import fs$1 from "fs";
11
- import { fileURLToPath as fileURLToPath$1 } from "url";
2
+ import { t as create_tsrx_content_mapper } from "./mapper-DATqGboo.js";
3
+ import { redirect_console_to_stderr, run_mapper_server } from "./rpc.js";
12
4
 
13
- //#region \0rolldown/runtime.js
14
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
15
-
16
- //#endregion
17
- //#region ../typescript-plugin/src/config-host.js
18
- /**
19
- * The file-system host the TSRX tooling reads `tsconfig.json` files and
20
- * package manifests through when no TypeScript `sys` is supplied. It covers
21
- * the subset of `ts.sys` that `tsconfig-resolution.js` and
22
- * `consumer-compiler.js` use, on `node:fs`, so the native TypeScript 7 path
23
- * (whose `typescript` package has no JavaScript API) needs no TypeScript at
24
- * all. `ts.sys` still satisfies the same interface for the classic path.
25
- */
26
- /**
27
- * @typedef {object} ConfigHost
28
- * @property {(file_name: string) => boolean} fileExists
29
- * @property {(file_name: string) => string | undefined} readFile
30
- * @property {(directory_name: string) => boolean} [directoryExists]
31
- * @property {boolean | (() => boolean)} useCaseSensitiveFileNames
32
- * @property {(file_name: string) => Date | undefined} [getModifiedTime]
33
- * @property {(path_name: string) => string} [realpath]
34
- */
35
- /**
36
- * Whether the file system distinguishes letter case, probed the way
37
- * TypeScript's `sys` does: this module's own path with its case swapped exists
38
- * only on a case-insensitive file system.
39
- * @returns {boolean}
40
- */
41
- function detect_case_sensitive_file_names() {
42
- const own_path = fileURLToPath(import.meta.url);
43
- const swapped = own_path.replace(/[a-zA-Z]/g, (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase());
44
- if (swapped === own_path) return true;
45
- return !fs.existsSync(swapped);
46
- }
47
- /** @type {boolean | undefined} */
48
- let case_sensitive_file_names;
49
- /** @returns {boolean} */
50
- function use_case_sensitive_file_names() {
51
- case_sensitive_file_names ??= detect_case_sensitive_file_names();
52
- return case_sensitive_file_names;
53
- }
54
- /**
55
- * @param {string} file_name
56
- * @returns {fs.Stats | undefined}
57
- */
58
- function stat(file_name) {
59
- try {
60
- return fs.statSync(file_name, { throwIfNoEntry: false });
61
- } catch {
62
- return;
63
- }
64
- }
65
- /** @returns {ConfigHost} */
66
- function create_config_host() {
67
- return {
68
- fileExists: (file_name) => stat(file_name)?.isFile() === true,
69
- directoryExists: (directory_name) => stat(directory_name)?.isDirectory() === true,
70
- readFile: (file_name) => {
71
- try {
72
- return fs.readFileSync(file_name, "utf8");
73
- } catch {
74
- return;
75
- }
76
- },
77
- useCaseSensitiveFileNames: use_case_sensitive_file_names,
78
- getModifiedTime: (file_name) => stat(file_name)?.mtime,
79
- realpath: (path_name) => {
80
- try {
81
- return fs.realpathSync(path_name);
82
- } catch {
83
- return path_name;
84
- }
85
- }
86
- };
87
- }
88
- /** The shared default host; one instance so per-host caches are reused. */
89
- const NODE_CONFIG_HOST = create_config_host();
90
-
91
- //#endregion
92
- //#region ../../node_modules/.pnpm/resolve-pkg-maps@1.0.0/node_modules/resolve-pkg-maps/dist/index.mjs
93
- const A = (r) => r !== null && typeof r == "object";
94
- const a = (r, t) => Object.assign(/* @__PURE__ */ new Error(`[${r}]: ${t}`), { code: r });
95
- const _ = "ERR_INVALID_PACKAGE_CONFIG";
96
- const E = "ERR_INVALID_PACKAGE_TARGET";
97
- const I = "ERR_PACKAGE_PATH_NOT_EXPORTED";
98
- const R = /^\d+$/;
99
- const O = /^(\.{1,2}|node_modules)$/i;
100
- const w = /\/|\\/;
101
- var h = ((r) => (r.Export = "exports", r.Import = "imports", r))(h || {});
102
- const f = (r, t, e, o, c) => {
103
- if (t == null) return [];
104
- if (typeof t == "string") {
105
- const [n, ...i] = t.split(w);
106
- if (n === ".." || i.some((l) => O.test(l))) throw a(E, `Invalid "${r}" target "${t}" defined in the package config`);
107
- return [c ? t.replace(/\*/g, c) : t];
108
- }
109
- if (Array.isArray(t)) return t.flatMap((n) => f(r, n, e, o, c));
110
- if (A(t)) {
111
- for (const n of Object.keys(t)) {
112
- if (R.test(n)) throw a(_, "Cannot contain numeric property keys");
113
- if (n === "default" || o.includes(n)) return f(r, t[n], e, o, c);
114
- }
115
- return [];
116
- }
117
- throw a(E, `Invalid "${r}" target "${t}"`);
118
- };
119
- const s = "*";
120
- const m = (r, t) => {
121
- const e = r.indexOf(s), o = t.indexOf(s);
122
- return e === o ? t.length > r.length : o > e;
123
- };
124
- function d(r, t) {
125
- if (!t.includes(s) && r.hasOwnProperty(t)) return [t];
126
- let e, o;
127
- for (const c of Object.keys(r)) if (c.includes(s)) {
128
- const [n, i, l] = c.split(s);
129
- if (l === void 0 && t.startsWith(n) && t.endsWith(i)) {
130
- const g = t.slice(n.length, -i.length || void 0);
131
- g && (!e || m(e, c)) && (e = c, o = g);
132
- }
133
- }
134
- return [e, o];
135
- }
136
- const p = (r) => Object.keys(r).reduce((t, e) => {
137
- const o = e === "" || e[0] !== ".";
138
- if (t === void 0 || t === o) return o;
139
- throw a(_, "\"exports\" cannot contain some keys starting with \".\" and some not");
140
- }, void 0);
141
- const u = /^\w+:/;
142
- const v = (r, t, e) => {
143
- if (!r) throw new Error("\"exports\" is required");
144
- t = t === "" ? "." : `./${t}`, (typeof r == "string" || Array.isArray(r) || A(r) && p(r)) && (r = { ".": r });
145
- const [o, c] = d(r, t), n = f(h.Export, r[o], t, e, c);
146
- if (n.length === 0) throw a(I, t === "." ? "No \"exports\" main defined" : `Package subpath '${t}' is not defined by "exports"`);
147
- for (const i of n) if (!i.startsWith("./") && !u.test(i)) throw a(E, `Invalid "exports" target "${i}" defined in the package config`);
148
- return n;
149
- };
150
-
151
- //#endregion
152
- //#region ../typescript-plugin/src/package-resolution.js
153
- /**
154
- * Package lookups without TypeScript's module resolver: the runtime entry of a
155
- * TSRX compiler package, and the file a `tsconfig.json` `extends` entry names.
156
- * Both walk `node_modules` directories upwards from a starting directory and
157
- * read every `package.json` fresh, so they also serve as the retry path when
158
- * Node's own `require.resolve` keeps a negative lookup after a package is
159
- * installed.
160
- */
161
- /** @typedef {import('./config-host.js').ConfigHost} ConfigHost */
162
- /**
163
- * @typedef {object} ParsedSpecifier
164
- * @property {string} name `pkg` or `@scope/pkg`.
165
- * @property {string} subpath The part after the package name, without a leading slash; empty for the package root.
166
- */
167
- /**
168
- * @param {string} specifier
169
- * @returns {ParsedSpecifier | undefined} `undefined` for relative, absolute or empty specifiers.
170
- */
171
- function parse_bare_specifier(specifier) {
172
- if (specifier === "" || specifier.startsWith(".") || path.isAbsolute(specifier)) return;
173
- const segments = specifier.split("/");
174
- const name_segments = specifier.startsWith("@") ? 2 : 1;
175
- if (segments.length < name_segments || segments.slice(0, name_segments).some((s) => s === "")) return;
176
- return {
177
- name: segments.slice(0, name_segments).join("/"),
178
- subpath: segments.slice(name_segments).join("/")
179
- };
180
- }
181
- /**
182
- * A directory exists when the host says so, or (for hosts without
183
- * `directoryExists`) when it holds a `package.json`.
184
- * @param {ConfigHost} host
185
- * @param {string} directory_name
186
- * @returns {boolean}
187
- */
188
- function is_directory(host, directory_name) {
189
- return host.directoryExists ? host.directoryExists(directory_name) : host.fileExists(path.join(directory_name, "package.json"));
190
- }
191
- /**
192
- * Read a package manifest through the host, never through Node's cached reader.
193
- * @param {ConfigHost} host
194
- * @param {string} package_dir
195
- * @returns {Record<string, unknown> | undefined}
196
- */
197
- function read_package_manifest(host, package_dir) {
198
- const text = host.readFile(path.join(package_dir, "package.json"));
199
- if (text === void 0) return;
200
- try {
201
- const parsed = JSON.parse(text);
202
- return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
203
- } catch {
204
- return;
205
- }
206
- }
207
- /**
208
- * Every `node_modules/<name>` directory that exists on the way up from `from_dir`.
209
- * @param {ConfigHost} host
210
- * @param {string} from_dir
211
- * @param {string} name
212
- * @returns {string[]}
213
- */
214
- function package_directories(host, from_dir, name) {
215
- /** @type {string[]} */
216
- const directories = [];
217
- let current = path.resolve(from_dir);
218
- while (true) {
219
- if (path.basename(current) !== "node_modules") {
220
- const candidate = path.join(current, "node_modules", name);
221
- if (is_directory(host, candidate)) directories.push(candidate);
222
- }
223
- const parent = path.dirname(current);
224
- if (parent === current) return directories;
225
- current = parent;
226
- }
227
- }
228
- /**
229
- * Targets of `exports` for a subpath under the given conditions, in order;
230
- * empty when the package has no `exports` or does not export the subpath.
231
- * @param {Record<string, unknown> | undefined} manifest
232
- * @param {string} subpath
233
- * @param {readonly string[]} conditions
234
- * @returns {string[]}
235
- */
236
- function exports_targets(manifest, subpath, conditions) {
237
- const exports = manifest?.exports;
238
- if (exports === void 0 || exports === null) return [];
239
- try {
240
- return v(exports, subpath, conditions);
241
- } catch {
242
- return [];
243
- }
244
- }
245
- /**
246
- * The file a bare specifier loads at runtime: the package's `exports` (under
247
- * `conditions`), else its `main`, else `index.js`, with the extension probing
248
- * Node's CommonJS loader applies; a subpath is resolved the same way.
249
- * @param {string} specifier
250
- * @param {string} from_dir
251
- * @param {{ conditions?: readonly string[], host?: ConfigHost }} [options]
252
- * @returns {string | undefined}
253
- */
254
- function resolve_package_entry(specifier, from_dir, options = {}) {
255
- const parsed = parse_bare_specifier(specifier);
256
- if (!parsed) return;
257
- const host = options.host ?? NODE_CONFIG_HOST;
258
- const conditions = options.conditions ?? [
259
- "node",
260
- "require",
261
- "default"
262
- ];
263
- for (const package_dir of package_directories(host, from_dir, parsed.name)) {
264
- const manifest = read_package_manifest(host, package_dir);
265
- for (const target of exports_targets(manifest, parsed.subpath, conditions)) {
266
- const resolved = path.resolve(package_dir, target);
267
- if (host.fileExists(resolved)) return resolved;
268
- }
269
- if (manifest?.exports !== void 0 && manifest.exports !== null) continue;
270
- const main = typeof manifest?.main === "string" ? manifest.main : void 0;
271
- const targets = parsed.subpath !== "" ? [parsed.subpath] : main !== void 0 ? [main, "index"] : ["index"];
272
- for (const target of targets) {
273
- const base = path.resolve(package_dir, target);
274
- for (const candidate of [
275
- base,
276
- `${base}.js`,
277
- `${base}.cjs`,
278
- `${base}.mjs`,
279
- `${base}.json`,
280
- path.join(base, "index.js")
281
- ]) if (host.fileExists(candidate)) return candidate;
282
- }
283
- }
284
- }
285
- /**
286
- * The config a package directory stands for: its `package.json` `tsconfig`
287
- * field (with `.json` appended when the file is missing without it, as
288
- * TypeScript's file loader does) or its `tsconfig.json`.
289
- * @param {ConfigHost} host
290
- * @param {string} directory
291
- * @param {Record<string, unknown> | undefined} manifest
292
- * @returns {string | undefined}
293
- */
294
- function tsconfig_field_target(host, directory, manifest) {
295
- const field = typeof manifest?.tsconfig === "string" ? manifest.tsconfig : "tsconfig.json";
296
- let resolved = path.resolve(directory, field);
297
- if (!host.fileExists(resolved) && !resolved.endsWith(".json")) resolved = `${resolved}.json`;
298
- return host.fileExists(resolved) ? resolved : void 0;
299
- }
300
- /**
301
- * The JSON file a `tsconfig.json` `extends` entry names. The rules and their
302
- * order are those of get-tsconfig's `resolveExtendsPath` (MIT, privatenumber),
303
- * which are tested against `tsc`:
304
- *
305
- * 1. `..` means `../tsconfig.json`; an entry starting with `.` is relative to
306
- * the config's directory; an absolute path is used as is. A missing path
307
- * without a `.json` extension gets one appended.
308
- * 2. Otherwise the entry names a package (`name` or `@scope/name`, plus an
309
- * optional subpath) found by walking `node_modules` upwards. A package with
310
- * `exports` is resolved only through them (conditions `require`, `types`);
311
- * an unexported subpath is a hard stop. Without `exports`, the package
312
- * root's `tsconfig` field or its `tsconfig.json` is used; a subpath is tried
313
- * with `.json` appended, as a `.json` file, then as a directory whose
314
- * `package.json` `tsconfig` field or `tsconfig.json` is the target.
315
- *
316
- * @param {string} extends_value
317
- * @param {string} config_dir
318
- * @param {ConfigHost} [host]
319
- * @returns {{ path: string, candidate?: string } | { path?: undefined, candidate?: string }}
320
- * `path` when found; `candidate` is the location TypeScript would have read
321
- * for a path entry, whether or not it exists (so a watcher can wait for it).
322
- */
323
- function resolve_extends_target(extends_value, config_dir, host = NODE_CONFIG_HOST) {
324
- let file_path = extends_value === ".." ? path.join("..", "tsconfig.json") : extends_value;
325
- if (file_path.startsWith(".")) file_path = path.resolve(config_dir, file_path);
326
- if (path.isAbsolute(file_path)) {
327
- if (host.fileExists(file_path)) return {
328
- path: file_path,
329
- candidate: file_path
330
- };
331
- const candidate = file_path.endsWith(".json") ? file_path : `${file_path}.json`;
332
- return host.fileExists(candidate) ? {
333
- path: candidate,
334
- candidate
335
- } : { candidate };
336
- }
337
- const parsed = parse_bare_specifier(extends_value);
338
- if (!parsed) return {};
339
- for (const found_dir of package_directories(host, config_dir, parsed.name)) {
340
- const package_dir = host.realpath ? host.realpath(found_dir) : found_dir;
341
- const manifest = read_package_manifest(host, package_dir);
342
- if (manifest?.exports !== void 0 && manifest.exports !== null) {
343
- const [target] = exports_targets(manifest, parsed.subpath, ["require", "types"]);
344
- if (target === void 0) return {};
345
- const resolved = path.resolve(package_dir, target);
346
- return host.fileExists(resolved) ? { path: resolved } : {};
347
- }
348
- if (parsed.subpath === "") {
349
- const resolved = tsconfig_field_target(host, package_dir, manifest);
350
- if (resolved !== void 0) return { path: resolved };
351
- }
352
- const full_path = path.join(package_dir, parsed.subpath);
353
- if (!full_path.endsWith(".json") && host.fileExists(`${full_path}.json`)) return { path: `${full_path}.json` };
354
- if (is_directory(host, full_path)) {
355
- const resolved = tsconfig_field_target(host, full_path, read_package_manifest(host, full_path));
356
- if (resolved !== void 0) return { path: resolved };
357
- } else if (full_path.endsWith(".json") && host.fileExists(full_path)) return { path: full_path };
358
- }
359
- return {};
360
- }
361
-
362
- //#endregion
363
- //#region ../typescript-plugin/src/jsonc.js
364
- /**
365
- * A JSON-with-comments reader for `tsconfig.json` and package manifests:
366
- * comments and trailing commas are allowed, as TypeScript allows them. The
367
- * parsing is Microsoft's `jsonc-parser` (the same scanner VS Code and
368
- * get-tsconfig use), so what parses here parses there.
369
- */
370
- /**
371
- * @typedef {object} JsoncParseResult
372
- * @property {unknown} value `undefined` when the text does not parse.
373
- * @property {{ message: string, offset: number }} [error] The first parse error.
374
- */
375
- /**
376
- * @param {string} text
377
- * @returns {JsoncParseResult}
378
- */
379
- function parse_jsonc(text) {
380
- const source = text.charCodeAt(0) === 65279 ? text.slice(1) : text;
381
- if (source.trim() === "") return { value: {} };
382
- /** @type {import('jsonc-parser').ParseError[]} */
383
- const errors = [];
384
- const value = parse(source, errors, {
385
- allowTrailingComma: true,
386
- disallowComments: false
387
- });
388
- if (errors.length > 0) {
389
- const [first] = errors;
390
- return {
391
- value: void 0,
392
- error: {
393
- message: `${printParseErrorCode(first.error)} at offset ${first.offset}`,
394
- offset: first.offset
395
- }
396
- };
397
- }
398
- return { value };
399
- }
400
-
401
- //#endregion
402
- //#region ../typescript-plugin/src/tsconfig-resolution.js
403
- /**
404
- * What the tooling needs from a file system to read tsconfig files: the
405
- * subset of TypeScript's `sys` that `config-host.js` also provides on
406
- * `node:fs`, so no TypeScript is needed to resolve a config chain.
407
- * @typedef {object} TsconfigHost
408
- * @property {(file_name: string) => boolean} fileExists
409
- * @property {(file_name: string) => string | undefined} readFile
410
- * @property {boolean | (() => boolean)} useCaseSensitiveFileNames
411
- * @property {(file_name: string) => Date | undefined} [getModifiedTime]
412
- */
413
- /**
414
- * A problem reading or resolving a config file. `code` follows TypeScript's
415
- * numbering for the cases it has one for (5024 invalid `extends` entry,
416
- * 6053 file not found, 18000 circular `extends`), so callers that filter on
417
- * codes keep working on both paths.
418
- * @typedef {object} TsconfigDiagnostic
419
- * @property {number} code
420
- * @property {string} message
421
- * @property {string} [file] The config file the problem is in.
422
- */
423
- /**
424
- * @typedef {object} TsconfigLayer
425
- * @property {string} path
426
- * @property {string} dir
427
- * @property {Record<string, unknown>} config
428
- * @property {string | undefined} raw_source
429
- * @property {TsconfigDiagnostic[]} parse_diagnostics
430
- */
431
- /** @typedef {TsconfigLayer & { extends_values: unknown[] }} ParsedTsconfigLayer */
432
- /**
433
- * @typedef {object} TsconfigExtendsFailure
434
- * @property {string} config_path
435
- * @property {unknown} extends_value
436
- * @property {string | undefined} resolved_path
437
- * @property {TsconfigDiagnostic[]} diagnostics
438
- */
439
- /**
440
- * @typedef {object} ResolvedTsconfigLayers
441
- * @property {TsconfigLayer[]} layers
442
- * @property {string[]} dependencies
443
- * @property {TsconfigDiagnostic[]} diagnostics
444
- * @property {TsconfigExtendsFailure[]} extends_failures
445
- */
446
- /**
447
- * @template TValue
448
- * @typedef {{state: 'absent'} | {state: 'found', value: TValue}} ConfigValueResult
449
- */
450
- /** @typedef {{config_path: string, config_dir: string}} TsconfigValueOrigin */
451
- const INVALID_EXTENDS_DIAGNOSTIC_CODE = 5024;
452
- const FILE_NOT_FOUND_DIAGNOSTIC_CODE = 6053;
453
- const CIRCULARITY_DIAGNOSTIC_CODE = 18e3;
454
- const PARSE_ERROR_DIAGNOSTIC_CODE = 1005;
455
- /**
456
- * Load a tsconfig and its explicit inheritance graph from lowest to highest
457
- * precedence. Parsed files are cached, but traversal intentionally does not
458
- * deduplicate layers because a shared base must be reapplied in every branch.
459
- * `extends` entries follow TypeScript's rules (see `resolve_extends_target`).
460
- *
461
- * @param {TsconfigHost} host
462
- * @param {string} config_file_name
463
- * @returns {ResolvedTsconfigLayers}
464
- */
465
- function load_tsconfig_layers(host, config_file_name) {
466
- /** @type {Map<string, ParsedTsconfigLayer>} */
467
- const parsed_file_cache = /* @__PURE__ */ new Map();
468
- /** @type {TsconfigLayer[]} */
469
- const layers = [];
470
- /** @type {string[]} */
471
- const dependencies = [];
472
- const dependency_keys = /* @__PURE__ */ new Set();
473
- /** @type {TsconfigDiagnostic[]} */
474
- const diagnostics = [];
475
- /** @type {TsconfigExtendsFailure[]} */
476
- const extends_failures = [];
477
- const diagnostic_keys = /* @__PURE__ */ new Set();
478
- /** The chain of configs being visited, root first, for cycle reporting. */
479
- /** @type {string[]} */
480
- const active_stack = [];
481
- const active_keys = /* @__PURE__ */ new Set();
482
- const use_case_sensitive_file_names = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
483
- /** @param {string} file_name */
484
- function normalize_path(file_name) {
485
- return path.normalize(path.resolve(file_name));
486
- }
487
- /** @param {string} file_name */
488
- function get_path_key(file_name) {
489
- const normalized_path = normalize_path(file_name);
490
- return use_case_sensitive_file_names ? normalized_path : normalized_path.toLowerCase();
491
- }
492
- /** @param {TsconfigDiagnostic[]} next_diagnostics */
493
- function add_diagnostics(next_diagnostics) {
494
- for (const diagnostic of next_diagnostics) {
495
- const key = `${diagnostic.code}\0${diagnostic.file ?? ""}\0${diagnostic.message}`;
496
- if (!diagnostic_keys.has(key)) {
497
- diagnostic_keys.add(key);
498
- diagnostics.push(diagnostic);
499
- }
500
- }
501
- }
502
- /** @param {string} file_name */
503
- function add_dependency(file_name) {
504
- const normalized_path = normalize_path(file_name);
505
- const key = get_path_key(normalized_path);
506
- if (!dependency_keys.has(key)) {
507
- dependency_keys.add(key);
508
- dependencies.push(normalized_path);
509
- }
510
- }
511
- /** @param {string} file_name */
512
- function parse_file(file_name) {
513
- const normalized_path = normalize_path(file_name);
514
- const key = get_path_key(normalized_path);
515
- const cached = parsed_file_cache.get(key);
516
- if (cached) return cached;
517
- const raw_source = host.readFile(normalized_path);
518
- /** @type {TsconfigDiagnostic[]} */
519
- const parse_diagnostics = [];
520
- /** @type {Record<string, unknown>} */
521
- let config = {};
522
- if (raw_source !== void 0) {
523
- const parsed = parse_jsonc(raw_source);
524
- if (parsed.error) parse_diagnostics.push({
525
- code: PARSE_ERROR_DIAGNOSTIC_CODE,
526
- message: `Failed to parse ${normalized_path}: ${parsed.error.message}`,
527
- file: normalized_path
528
- });
529
- else if (parsed.value !== null && typeof parsed.value === "object" && !Array.isArray(parsed.value)) config = parsed.value;
530
- else parse_diagnostics.push({
531
- code: PARSE_ERROR_DIAGNOSTIC_CODE,
532
- message: `The root value of ${normalized_path} must be an object.`,
533
- file: normalized_path
534
- });
535
- }
536
- const extends_value = config.extends;
537
- const extends_values = Array.isArray(extends_value) ? extends_value : extends_value !== void 0 ? [extends_value] : [];
538
- const parsed = {
539
- path: normalized_path,
540
- dir: path.dirname(normalized_path),
541
- config,
542
- raw_source,
543
- parse_diagnostics,
544
- extends_values
545
- };
546
- parsed_file_cache.set(key, parsed);
547
- add_diagnostics(parse_diagnostics);
548
- return parsed;
549
- }
550
- /**
551
- * Resolve one immediate extends entry. The conventional JSON candidate of an
552
- * unresolved relative entry is still recorded as a dependency so creating it
553
- * later invalidates caches and language-server projects.
554
- * @param {ParsedTsconfigLayer} parsed
555
- * @param {unknown} extends_value
556
- */
557
- function resolve_extends_path(parsed, extends_value) {
558
- if (typeof extends_value !== "string") {
559
- const diagnostic = {
560
- code: INVALID_EXTENDS_DIAGNOSTIC_CODE,
561
- message: `Compiler option 'extends' requires a value of type string.`,
562
- file: parsed.path
563
- };
564
- add_diagnostics([diagnostic]);
565
- extends_failures.push({
566
- config_path: parsed.path,
567
- extends_value,
568
- resolved_path: void 0,
569
- diagnostics: [diagnostic]
570
- });
571
- return;
572
- }
573
- const target = resolve_extends_target(extends_value, parsed.dir, host);
574
- const dependency_path = target.path ?? target.candidate;
575
- if (dependency_path !== void 0) add_dependency(dependency_path);
576
- if (target.path === void 0) {
577
- const diagnostic = {
578
- code: FILE_NOT_FOUND_DIAGNOSTIC_CODE,
579
- message: `File '${target.candidate ?? extends_value}' not found.`,
580
- file: parsed.path
581
- };
582
- add_diagnostics([diagnostic]);
583
- extends_failures.push({
584
- config_path: parsed.path,
585
- extends_value,
586
- resolved_path: dependency_path,
587
- diagnostics: [diagnostic]
588
- });
589
- return;
590
- }
591
- if (active_keys.has(get_path_key(target.path))) {
592
- const chain = [...active_stack, normalize_path(target.path)];
593
- const diagnostic = {
594
- code: CIRCULARITY_DIAGNOSTIC_CODE,
595
- message: `Circularity detected while resolving configuration: ${chain.join(" -> ")}`,
596
- file: parsed.path
597
- };
598
- add_diagnostics([diagnostic]);
599
- extends_failures.push({
600
- config_path: parsed.path,
601
- extends_value,
602
- resolved_path: dependency_path,
603
- diagnostics: [diagnostic]
604
- });
605
- return;
606
- }
607
- return target.path;
608
- }
609
- /** @param {string} file_name */
610
- function visit(file_name) {
611
- const normalized_path = normalize_path(file_name);
612
- const key = get_path_key(normalized_path);
613
- active_keys.add(key);
614
- active_stack.push(normalized_path);
615
- add_dependency(normalized_path);
616
- const parsed = parse_file(normalized_path);
617
- for (const extends_value of parsed.extends_values) {
618
- const extended_path = resolve_extends_path(parsed, extends_value);
619
- if (extended_path !== void 0) visit(extended_path);
620
- }
621
- layers.push({
622
- path: parsed.path,
623
- dir: parsed.dir,
624
- config: parsed.config,
625
- raw_source: parsed.raw_source,
626
- parse_diagnostics: parsed.parse_diagnostics
627
- });
628
- active_stack.pop();
629
- active_keys.delete(key);
630
- }
631
- visit(config_file_name);
632
- return {
633
- layers,
634
- dependencies,
635
- diagnostics,
636
- extends_failures
637
- };
638
- }
639
- /**
640
- * Read a nested config value only when every segment is an own property.
641
- *
642
- * @param {unknown} config
643
- * @param {readonly PropertyKey[]} path_parts
644
- * @returns {ConfigValueResult<unknown>}
645
- */
646
- function get_own_config_value(config, path_parts) {
647
- let current = config;
648
- for (const path_part of path_parts) {
649
- if (current === null || typeof current !== "object" && typeof current !== "function" || !Object.prototype.hasOwnProperty.call(current, path_part)) return { state: "absent" };
650
- current = current[path_part];
651
- }
652
- return {
653
- state: "found",
654
- value: current
655
- };
656
- }
657
- /**
658
- * Resolve a caller-defined value across layers. The last result whose state is
659
- * not absent wins and is annotated with the config that declared it.
660
- *
661
- * @template {{state: string}} TResult
662
- * @param {readonly TsconfigLayer[]} layers
663
- * @param {(layer: TsconfigLayer) => TResult} read_layer
664
- * @returns {{state: 'absent'} | (TResult & TsconfigValueOrigin)}
665
- */
666
- function resolve_inherited_config_value(layers, read_layer) {
667
- /** @type {{state: 'absent'} | (TResult & TsconfigValueOrigin)} */
668
- let resolved = { state: "absent" };
669
- for (const layer of layers) {
670
- const value = read_layer(layer);
671
- if (value.state !== "absent") resolved = {
672
- ...value,
673
- config_path: layer.path,
674
- config_dir: layer.dir
675
- };
676
- }
677
- return resolved;
678
- }
679
-
680
- //#endregion
681
- //#region ../typescript-plugin/src/utils.js
682
- const DEBUG = process.env.TSRX_DEBUG === "true";
683
- /**
684
- * Create a logging utility with a specific label
685
- * @param {string} label
686
- * @returns {{
687
- * log: (...args: unknown[]) => void,
688
- * logError: (...args: unknown[]) => void,
689
- * logWarning: (...args: unknown[]) => void,
690
- * }}
691
- */
692
- function createLogging(label) {
693
- return {
694
- log(...args) {
695
- if (DEBUG) console.log(label, ...args);
696
- },
697
- logError(...args) {
698
- if (DEBUG) console.error(label, ...args);
699
- },
700
- logWarning(...args) {
701
- if (DEBUG) console.warn(label, ...args);
702
- }
703
- };
704
- }
705
-
706
- //#endregion
707
- //#region ../typescript-plugin/src/consumer-compiler.js
708
- /** @typedef {{actual_type: string, actual_value: string}} InvalidConfigValueDetails */
709
- /** @typedef {'web' | 'ios' | 'android'} Platform */
710
- /**
711
- * @typedef {
712
- * | {state: 'absent'}
713
- * | {state: 'declared', value: string}
714
- * | ({state: 'invalid', target: 'tsrx' | 'compiler'} & InvalidConfigValueDetails)
715
- * } CompilerDeclaration
716
- */
717
- /**
718
- * @typedef {
719
- * | {state: 'absent'}
720
- * | {state: 'declared', value: Platform}
721
- * | ({state: 'invalid', target: 'tsrx' | 'platform'} & InvalidConfigValueDetails)
722
- * } PlatformDeclaration
723
- */
724
- /**
725
- * @typedef {object} CompilerResolutionOptions
726
- * @property {typeof import('typescript')} [ts] Accepted for the classic callers; config resolution no longer uses it.
727
- * @property {string} [configFileName]
728
- * @property {import('./tsconfig-resolution.js').TsconfigHost} [configHost]
729
- * @property {Set<string>} [dependencies]
730
- * @property {boolean} [requirePlatformResolution]
731
- */
732
- /**
733
- * @typedef {object} ConfigHostResolutionCache
734
- * @property {Map<string, string | null>} nearest_config_paths
735
- * @property {Map<string, CachedTsconfigLayers>} resolved_config_layers
736
- */
737
- /**
738
- * @typedef {object} CachedTsconfigLayers
739
- * @property {import('./tsconfig-resolution.js').ResolvedTsconfigLayers} value
740
- * @property {Map<string, number | undefined> | undefined} dependency_modified_times
741
- */
742
- const { log: log$1, logError: logError$1, logWarning: logWarning$1 } = createLogging("[TSRX Language]");
743
- const bare_package_specifier_pattern$1 = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/;
744
- const tsrx_key_pattern = /["']tsrx["']\s*:/;
745
- /** @type {WeakMap<object, ConfigHostResolutionCache>} */
746
- let config_host_to_resolution_cache = /* @__PURE__ */ new WeakMap();
747
- /** @type {Map<string, string | null>} */
748
- const declared_compiler_path_map = /* @__PURE__ */ new Map();
749
- /**
750
- * @param {unknown} value
751
- * @returns {{ actual_type: string, actual_value: string }}
752
- */
753
- function describe_config_value(value) {
754
- return {
755
- actual_type: value === null ? "null" : Array.isArray(value) ? "array" : typeof value,
756
- actual_value: JSON.stringify(value) ?? String(value)
757
- };
758
- }
759
- /**
760
- * Keep filesystem-derived config caches isolated per TypeScript/Volar host.
761
- * Different hosts can expose different snapshots for the same absolute path.
762
- * @param {import('./tsconfig-resolution.js').TsconfigHost} host
763
- */
764
- function get_config_host_cache(host) {
765
- let cache = config_host_to_resolution_cache.get(host);
766
- if (!cache) {
767
- cache = {
768
- nearest_config_paths: /* @__PURE__ */ new Map(),
769
- resolved_config_layers: /* @__PURE__ */ new Map()
770
- };
771
- config_host_to_resolution_cache.set(host, cache);
772
- }
773
- return cache;
774
- }
775
- /**
776
- * @param {string} file_name
777
- * @param {import('./tsconfig-resolution.js').TsconfigHost} host
778
- */
779
- function get_config_cache_key(file_name, host) {
780
- const normalized_path = path$1.normalize(path$1.resolve(file_name));
781
- return (typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames) ? normalized_path : normalized_path.toLowerCase();
782
- }
783
- /**
784
- * @param {unknown} config
785
- * @returns {CompilerDeclaration}
786
- */
787
- function get_compiler_declaration(config) {
788
- const tsrx_result = get_own_config_value(config, ["tsrx"]);
789
- if (tsrx_result.state === "absent") return { state: "absent" };
790
- const tsrx_value = tsrx_result.value;
791
- if (tsrx_value === null || typeof tsrx_value !== "object" || Array.isArray(tsrx_value)) return {
792
- state: "invalid",
793
- target: "tsrx",
794
- ...describe_config_value(tsrx_value)
795
- };
796
- const compiler_result = get_own_config_value(tsrx_value, ["compiler"]);
797
- if (compiler_result.state === "absent") return { state: "absent" };
798
- const compiler = compiler_result.value;
799
- if (typeof compiler === "string" && compiler.trim() !== "") return {
800
- state: "declared",
801
- value: compiler.trim()
802
- };
803
- return {
804
- state: "invalid",
805
- target: "compiler",
806
- ...describe_config_value(compiler)
807
- };
808
- }
809
- /**
810
- * @param {unknown} config
811
- * @returns {PlatformDeclaration}
812
- */
813
- function get_platform_declaration(config) {
814
- const tsrx_result = get_own_config_value(config, ["tsrx"]);
815
- if (tsrx_result.state === "absent") return { state: "absent" };
816
- const tsrx_value = tsrx_result.value;
817
- if (tsrx_value === null || typeof tsrx_value !== "object" || Array.isArray(tsrx_value)) return {
818
- state: "invalid",
819
- target: "tsrx",
820
- ...describe_config_value(tsrx_value)
821
- };
822
- const platform_result = get_own_config_value(tsrx_value, ["platform"]);
823
- if (platform_result.state === "absent") return { state: "absent" };
824
- const platform = platform_result.value;
825
- if (platform === "web" || platform === "ios" || platform === "android") return {
826
- state: "declared",
827
- value: platform
828
- };
829
- return {
830
- state: "invalid",
831
- target: "platform",
832
- ...describe_config_value(platform)
833
- };
834
- }
835
- /**
836
- * Find the nearest tsconfig.json to use as the root of inheritance resolution.
837
- * @param {string} start_dir
838
- * @param {import('./tsconfig-resolution.js').TsconfigHost} host
839
- * @param {ConfigHostResolutionCache} cache
840
- * @returns {string | null}
841
- */
842
- function get_nearest_root_tsconfig(start_dir, host, cache) {
843
- let current_dir = start_dir;
844
- /** @type {string[]} */
845
- const visited_dir_keys = [];
846
- while (current_dir) {
847
- const current_dir_key = get_config_cache_key(current_dir, host);
848
- if (cache.nearest_config_paths.has(current_dir_key)) {
849
- const cached_tsconfig = cache.nearest_config_paths.get(current_dir_key) ?? null;
850
- for (const visited_dir_key of visited_dir_keys) cache.nearest_config_paths.set(visited_dir_key, cached_tsconfig);
851
- return cached_tsconfig;
852
- }
853
- visited_dir_keys.push(current_dir_key);
854
- const tsconfig_path = path$1.join(current_dir, "tsconfig.json");
855
- if (host.fileExists(tsconfig_path)) {
856
- for (const visited_dir_key of visited_dir_keys) cache.nearest_config_paths.set(visited_dir_key, tsconfig_path);
857
- return tsconfig_path;
858
- }
859
- const parent_dir = path$1.dirname(current_dir);
860
- if (parent_dir === current_dir) break;
861
- current_dir = parent_dir;
862
- }
863
- for (const visited_dir_key of visited_dir_keys) cache.nearest_config_paths.set(visited_dir_key, null);
864
- return null;
865
- }
866
- /**
867
- * @param {import('./tsconfig-resolution.js').TsconfigHost} host
868
- * @param {string} root_config_path
869
- * @param {ConfigHostResolutionCache} cache
870
- */
871
- function get_tsconfig_layers(host, root_config_path, cache) {
872
- const cache_key = get_config_cache_key(root_config_path, host);
873
- const cached = cache.resolved_config_layers.get(cache_key);
874
- if (cached && (cached.dependency_modified_times === void 0 || [...cached.dependency_modified_times].every(([dependency, modified_time]) => host.getModifiedTime?.(dependency)?.valueOf() === modified_time))) return cached.value;
875
- const value = load_tsconfig_layers(host, root_config_path);
876
- const dependency_modified_times = host.getModifiedTime ? new Map(value.dependencies.map((dependency) => [dependency, host.getModifiedTime?.(dependency)?.valueOf()])) : void 0;
877
- cache.resolved_config_layers.set(cache_key, {
878
- value,
879
- dependency_modified_times
880
- });
881
- return value;
882
- }
883
- /**
884
- * A declaration in the config that owns a failed extends entry, or in a child
885
- * config above it, has higher precedence than anything the missing base could
886
- * have declared and therefore makes that failure irrelevant to this value.
887
- * @param {readonly import('./tsconfig-resolution.js').TsconfigLayer[]} layers
888
- * @param {import('./tsconfig-resolution.js').TsconfigExtendsFailure} failure
889
- * @param {string} declaration_config_path
890
- */
891
- function is_extends_failure_overridden(layers, failure, declaration_config_path) {
892
- const failure_owner_index = layers.findLastIndex((layer) => layer.path === failure.config_path);
893
- const declaration_index = layers.findLastIndex((layer) => layer.path === declaration_config_path);
894
- return failure_owner_index >= 0 && declaration_index >= failure_owner_index;
895
- }
896
- /**
897
- * Resolve without a module-resolution cache. This is the recovery path when
898
- * Node retains a negative package lookup after a dependency is installed: the
899
- * package walk reads every manifest fresh and resolves the runtime entry.
900
- * @param {import('./tsconfig-resolution.js').TsconfigHost} host
901
- * @param {string} config_path
902
- * @param {string} specifier
903
- */
904
- function resolve_uncached_declared_compiler(host, config_path, specifier) {
905
- return resolve_package_entry(specifier, path$1.dirname(config_path), { host });
906
- }
907
- /**
908
- * Resolve the compiler explicitly selected by a consumer tsconfig. Invalid
909
- * specifiers are stable and cached, while missing packages are retried so
910
- * tsserver can recover after the dependency is installed.
911
- * @param {import('./tsconfig-resolution.js').TsconfigHost} host
912
- * @param {string} config_path
913
- * @param {string} specifier
914
- * @returns {string | null}
915
- */
916
- function resolve_declared_compiler(host, config_path, specifier) {
917
- const cache_key = `${config_path}\0${specifier}`;
918
- if (declared_compiler_path_map.has(cache_key)) return declared_compiler_path_map.get(cache_key) ?? null;
919
- if (!bare_package_specifier_pattern$1.test(specifier)) {
920
- declared_compiler_path_map.set(cache_key, null);
921
- logError$1("Declared TSRX compiler must be a bare package specifier:", specifier, `in ${config_path}`);
922
- return null;
923
- }
924
- try {
925
- const compiler_path = createRequire$1(config_path).resolve(specifier);
926
- declared_compiler_path_map.set(cache_key, compiler_path);
927
- log$1("Found declared tsrx compiler at:", compiler_path, "from tsconfig:", config_path);
928
- return compiler_path;
929
- } catch {
930
- const compiler_path = resolve_uncached_declared_compiler(host, config_path, specifier);
931
- if (compiler_path !== void 0) {
932
- declared_compiler_path_map.set(cache_key, compiler_path);
933
- log$1("Found declared tsrx compiler after uncached retry at:", compiler_path, "from tsconfig:", config_path);
934
- return compiler_path;
935
- }
936
- logError$1(`Unable to resolve declared TSRX compiler "${specifier}" from tsconfig`, config_path);
937
- return null;
938
- }
939
- }
940
- /**
941
- * Return undefined when there is no consumer declaration, null for a declared
942
- * hard stop, or the resolved compiler path for a valid declaration.
943
- * @param {string} normalized_file_name
944
- * @param {CompilerResolutionOptions} [options]
945
- * @returns {string | null | undefined}
946
- */
947
- function resolve_consumer_compiler_for_file(normalized_file_name, options = {}) {
948
- const config_host = options.configHost ?? NODE_CONFIG_HOST;
949
- const host_cache = get_config_host_cache(config_host);
950
- const root_config_path = options.configFileName ?? get_nearest_root_tsconfig(path$1.dirname(normalized_file_name), config_host, host_cache);
951
- if (root_config_path === null) return;
952
- const resolved_layers = get_tsconfig_layers(config_host, root_config_path, host_cache);
953
- for (const dependency of resolved_layers.dependencies) options.dependencies?.add(dependency);
954
- const unreadable_layers = resolved_layers.layers.filter((layer) => layer.raw_source === void 0);
955
- if (unreadable_layers.length > 0) {
956
- for (const layer of unreadable_layers) logError$1("Unable to read tsconfig layer:", layer.path);
957
- return null;
958
- }
959
- const malformed_layers = resolved_layers.layers.filter((layer) => layer.parse_diagnostics.length > 0);
960
- if (malformed_layers.length > 0) {
961
- const has_tsrx_intent = resolved_layers.layers.some((layer) => {
962
- if (get_own_config_value(layer.config, ["tsrx"]).state === "found") return true;
963
- if (layer.parse_diagnostics.length === 0 || layer.raw_source === void 0) return false;
964
- return tsrx_key_pattern.test(layer.raw_source);
965
- });
966
- const log_parse_error = has_tsrx_intent ? logError$1 : logWarning$1;
967
- for (const layer of malformed_layers) for (const diagnostic of layer.parse_diagnostics) log_parse_error("Unable to parse tsconfig layer:", layer.path, diagnostic.message);
968
- return has_tsrx_intent ? null : void 0;
969
- }
970
- const declaration = resolve_inherited_config_value(resolved_layers.layers, (layer) => get_compiler_declaration(layer.config));
971
- if (declaration.state === "invalid") {
972
- logError$1(`Invalid TSRX ${declaration.target} declaration:`, declaration.actual_type, declaration.actual_value, `in ${declaration.config_path}`);
973
- return null;
974
- }
975
- const effective_extends_failures = resolved_layers.extends_failures.filter((failure) => declaration.state !== "declared" || !is_extends_failure_overridden(resolved_layers.layers, failure, declaration.config_path));
976
- if (effective_extends_failures.length > 0) {
977
- for (const failure of effective_extends_failures) {
978
- if (failure.diagnostics.length === 0) {
979
- logError$1("Unable to resolve tsconfig extends entry:", JSON.stringify(failure.extends_value), `in ${failure.config_path}`);
980
- continue;
981
- }
982
- for (const diagnostic of failure.diagnostics) logError$1("Unable to resolve tsconfig extends entry:", JSON.stringify(failure.extends_value), `in ${failure.config_path}`, diagnostic.message);
983
- }
984
- return null;
985
- }
986
- if (declaration.state === "declared") return resolve_declared_compiler(config_host, declaration.config_path, declaration.value);
987
- }
988
- /**
989
- * Resolve the compile-time platform selected by the active TypeScript project.
990
- * The same inheritance graph and dependency tracking as compiler selection are
991
- * used so nested projects and config edits cannot silently drift.
992
- *
993
- * @param {string} normalized_file_name
994
- * @param {CompilerResolutionOptions} [options]
995
- * @returns {Platform | undefined}
996
- */
997
- function resolve_consumer_platform_for_file(normalized_file_name, options = {}) {
998
- const config_host = options.configHost ?? NODE_CONFIG_HOST;
999
- const host_cache = get_config_host_cache(config_host);
1000
- const root_config_path = options.configFileName ?? get_nearest_root_tsconfig(path$1.dirname(normalized_file_name), config_host, host_cache);
1001
- if (root_config_path === null) return;
1002
- const resolved_layers = get_tsconfig_layers(config_host, root_config_path, host_cache);
1003
- for (const dependency of resolved_layers.dependencies) options.dependencies?.add(dependency);
1004
- const unreadable_layer = resolved_layers.layers.find((layer) => layer.raw_source === void 0);
1005
- if (unreadable_layer) {
1006
- const message = `Unable to read tsconfig layer while resolving TSRX platform: ${unreadable_layer.path}`;
1007
- logError$1(message);
1008
- throw new Error(message);
1009
- }
1010
- const malformed_layers = resolved_layers.layers.filter((layer) => layer.parse_diagnostics.length > 0);
1011
- if (malformed_layers.length > 0) {
1012
- if (!resolved_layers.layers.some((layer) => {
1013
- if (get_own_config_value(layer.config, ["tsrx"]).state === "found") return true;
1014
- return layer.parse_diagnostics.length > 0 && layer.raw_source !== void 0 && tsrx_key_pattern.test(layer.raw_source);
1015
- })) return void 0;
1016
- const layer = malformed_layers[0];
1017
- const detail = layer.parse_diagnostics[0].message;
1018
- const message = `Unable to parse tsconfig layer while resolving TSRX platform: ${layer.path}: ${detail}`;
1019
- logError$1(message);
1020
- throw new Error(message);
1021
- }
1022
- const declaration = resolve_inherited_config_value(resolved_layers.layers, (layer) => get_platform_declaration(layer.config));
1023
- if (declaration.state === "invalid") {
1024
- const expected = declaration.target === "platform" ? " Expected \"web\", \"ios\", or \"android\"." : "";
1025
- const message = `Invalid TSRX ${declaration.target} declaration: ${declaration.actual_type} ${declaration.actual_value} in ${declaration.config_path}.${expected}`;
1026
- logError$1(message);
1027
- throw new TypeError(message);
1028
- }
1029
- const effective_extends_failures = resolved_layers.extends_failures.filter((failure) => declaration.state !== "declared" || !is_extends_failure_overridden(resolved_layers.layers, failure, declaration.config_path));
1030
- if (effective_extends_failures.length > 0) {
1031
- if (!options.requirePlatformResolution) return declaration.state === "declared" ? declaration.value : void 0;
1032
- const failure = effective_extends_failures[0];
1033
- const detail = failure.diagnostics.length > 0 ? `: ${failure.diagnostics[0].message}` : "";
1034
- const message = `Unable to resolve tsconfig extends entry ${JSON.stringify(failure.extends_value)} in ${failure.config_path} while resolving TSRX platform${detail}`;
1035
- logError$1(message);
1036
- throw new Error(message);
1037
- }
1038
- return declaration.state === "declared" ? declaration.value : void 0;
1039
- }
1040
- /** Drop all filesystem-derived consumer compiler resolution state. */
1041
- function reset_consumer_compiler_resolution_caches() {
1042
- config_host_to_resolution_cache = /* @__PURE__ */ new WeakMap();
1043
- declared_compiler_path_map.clear();
1044
- }
1045
-
1046
- //#endregion
1047
- //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/lib/binarySearch.js
1048
- var require_binarySearch = /* @__PURE__ */ __commonJSMin(((exports) => {
1049
- Object.defineProperty(exports, "__esModule", { value: true });
1050
- exports.binarySearch = binarySearch;
1051
- function binarySearch(values, searchValue) {
1052
- let low = 0;
1053
- let high = values.length - 1;
1054
- let match;
1055
- while (low <= high) {
1056
- const mid = Math.floor((low + high) / 2);
1057
- const midValue = values[mid];
1058
- if (midValue < searchValue) low = mid + 1;
1059
- else if (midValue > searchValue) high = mid - 1;
1060
- else {
1061
- low = mid;
1062
- high = mid;
1063
- match = mid;
1064
- break;
1065
- }
1066
- }
1067
- return {
1068
- low: Math.max(Math.min(low, high, values.length - 1), 0),
1069
- high: Math.min(Math.max(low, high, 0), values.length - 1),
1070
- match
1071
- };
1072
- }
1073
- }));
1074
-
1075
- //#endregion
1076
- //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/lib/translateOffset.js
1077
- var require_translateOffset = /* @__PURE__ */ __commonJSMin(((exports) => {
1078
- Object.defineProperty(exports, "__esModule", { value: true });
1079
- exports.translateOffset = translateOffset;
1080
- let warned = false;
1081
- function translateOffset(start, fromOffsets, toOffsets, fromLengths, toLengths = fromLengths, preferEnd = false) {
1082
- if (!fromOffsets.every((value, index) => index === 0 || fromOffsets[index - 1] <= value)) {
1083
- for (let i = 0; i < fromOffsets.length; i++) {
1084
- const fromOffset = fromOffsets[i];
1085
- const fromLength = fromLengths[i];
1086
- if (start >= fromOffset && start <= fromOffset + fromLength) {
1087
- const toLength = toLengths[i];
1088
- const toOffset = toOffsets[i];
1089
- let rangeOffset;
1090
- const relativePos = start - fromOffset;
1091
- if (preferEnd && toLength > fromLength && relativePos === fromLength) rangeOffset = toLength;
1092
- else rangeOffset = Math.min(relativePos, toLength);
1093
- return toOffset + rangeOffset;
1094
- }
1095
- }
1096
- if (!warned) {
1097
- warned = true;
1098
- console.warn("fromOffsets should be sorted in ascending order");
1099
- }
1100
- }
1101
- let low = 0;
1102
- let high = fromOffsets.length - 1;
1103
- while (low <= high) {
1104
- const mid = Math.floor((low + high) / 2);
1105
- const fromOffset = fromOffsets[mid];
1106
- const fromLength = fromLengths[mid];
1107
- if (start >= fromOffset && start <= fromOffset + fromLength) {
1108
- const toLength = toLengths[mid];
1109
- const toOffset = toOffsets[mid];
1110
- let rangeOffset;
1111
- const relativePos = start - fromOffset;
1112
- if (preferEnd && toLength > fromLength && relativePos === fromLength) rangeOffset = toLength;
1113
- else rangeOffset = Math.min(relativePos, toLength);
1114
- return toOffset + rangeOffset;
1115
- } else if (start < fromOffset) high = mid - 1;
1116
- else low = mid + 1;
1117
- }
1118
- }
1119
- }));
1120
-
1121
- //#endregion
1122
- //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/lib/sourceMap.js
1123
- var require_sourceMap = /* @__PURE__ */ __commonJSMin(((exports) => {
1124
- Object.defineProperty(exports, "__esModule", { value: true });
1125
- exports.SourceMap = void 0;
1126
- const binarySearch_1 = require_binarySearch();
1127
- const translateOffset_1 = require_translateOffset();
1128
- var SourceMap = class {
1129
- constructor(mappings) {
1130
- this.mappings = mappings;
1131
- }
1132
- toSourceRange(generatedStart, generatedEnd, fallbackToAnyMatch, filter) {
1133
- return this.findMatchingStartEnd(generatedStart, generatedEnd, fallbackToAnyMatch, "generatedOffsets", filter);
1134
- }
1135
- toGeneratedRange(sourceStart, sourceEnd, fallbackToAnyMatch, filter) {
1136
- return this.findMatchingStartEnd(sourceStart, sourceEnd, fallbackToAnyMatch, "sourceOffsets", filter);
1137
- }
1138
- toSourceLocation(generatedOffset, filter) {
1139
- return this.findMatchingOffsets(generatedOffset, "generatedOffsets", filter);
1140
- }
1141
- toGeneratedLocation(sourceOffset, filter) {
1142
- return this.findMatchingOffsets(sourceOffset, "sourceOffsets", filter);
1143
- }
1144
- *findMatchingOffsets(offset, fromRange, filter, preferEnd = false) {
1145
- const memo = this.getMemoBasedOnRange(fromRange);
1146
- if (memo.offsets.length === 0) return;
1147
- const { low: start, high: end } = (0, binarySearch_1.binarySearch)(memo.offsets, offset);
1148
- const skip = /* @__PURE__ */ new Set();
1149
- const toRange = fromRange === "sourceOffsets" ? "generatedOffsets" : "sourceOffsets";
1150
- for (let i = start; i <= end; i++) for (const mapping of memo.mappings[i]) {
1151
- if (skip.has(mapping)) continue;
1152
- skip.add(mapping);
1153
- if (filter && !filter(mapping.data)) continue;
1154
- const mapped = (0, translateOffset_1.translateOffset)(offset, mapping[fromRange], mapping[toRange], getLengths(mapping, fromRange), getLengths(mapping, toRange), preferEnd);
1155
- if (mapped !== void 0) yield [mapped, mapping];
1156
- }
1157
- }
1158
- *findMatchingStartEnd(start, end, fallbackToAnyMatch, fromRange, filter) {
1159
- const toRange = fromRange === "sourceOffsets" ? "generatedOffsets" : "sourceOffsets";
1160
- const preferEnd = toRange === "sourceOffsets";
1161
- const mappedStarts = [];
1162
- let hadMatch = false;
1163
- for (const [mappedStart, mapping] of this.findMatchingOffsets(start, fromRange)) {
1164
- if (filter && !filter(mapping.data)) continue;
1165
- mappedStarts.push([mappedStart, mapping]);
1166
- const mappedEnd = (0, translateOffset_1.translateOffset)(end, mapping[fromRange], mapping[toRange], getLengths(mapping, fromRange), getLengths(mapping, toRange), preferEnd);
1167
- if (mappedEnd !== void 0) {
1168
- hadMatch = true;
1169
- yield [
1170
- mappedStart,
1171
- mappedEnd,
1172
- mapping,
1173
- mapping
1174
- ];
1175
- }
1176
- }
1177
- if (!hadMatch && fallbackToAnyMatch) for (const [mappedStart, mappingStart] of mappedStarts) for (const [mappedEnd, mappingEnd] of this.findMatchingOffsets(end, fromRange, void 0, preferEnd)) {
1178
- if (filter && !filter(mappingEnd.data) || mappedEnd < mappedStart) continue;
1179
- yield [
1180
- mappedStart,
1181
- mappedEnd,
1182
- mappingStart,
1183
- mappingEnd
1184
- ];
1185
- break;
1186
- }
1187
- }
1188
- getMemoBasedOnRange(fromRange) {
1189
- return fromRange === "sourceOffsets" ? this.sourceCodeOffsetsMemo ??= this.createMemo("sourceOffsets") : this.generatedCodeOffsetsMemo ??= this.createMemo("generatedOffsets");
1190
- }
1191
- createMemo(key) {
1192
- const offsetsSet = /* @__PURE__ */ new Set();
1193
- for (const mapping of this.mappings) for (let i = 0; i < mapping[key].length; i++) {
1194
- offsetsSet.add(mapping[key][i]);
1195
- offsetsSet.add(mapping[key][i] + getLengths(mapping, key)[i]);
1196
- }
1197
- const offsets = [...offsetsSet].sort((a, b) => a - b);
1198
- const mappings = offsets.map(() => /* @__PURE__ */ new Set());
1199
- for (const mapping of this.mappings) for (let i = 0; i < mapping[key].length; i++) {
1200
- const startIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i]).match;
1201
- const endIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i] + getLengths(mapping, key)[i]).match;
1202
- for (let i = startIndex; i <= endIndex; i++) mappings[i].add(mapping);
1203
- }
1204
- return {
1205
- offsets,
1206
- mappings
1207
- };
1208
- }
1209
- };
1210
- exports.SourceMap = SourceMap;
1211
- function getLengths(mapping, key) {
1212
- return key === "sourceOffsets" ? mapping.lengths : mapping.generatedLengths ?? mapping.lengths;
1213
- }
1214
- }));
1215
-
1216
- //#endregion
1217
- //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/index.js
1218
- var require_source_map = /* @__PURE__ */ __commonJSMin(((exports) => {
1219
- var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
1220
- if (k2 === void 0) k2 = k;
1221
- var desc = Object.getOwnPropertyDescriptor(m, k);
1222
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
1223
- enumerable: true,
1224
- get: function() {
1225
- return m[k];
1226
- }
1227
- };
1228
- Object.defineProperty(o, k2, desc);
1229
- }) : (function(o, m, k, k2) {
1230
- if (k2 === void 0) k2 = k;
1231
- o[k2] = m[k];
1232
- }));
1233
- var __exportStar = exports && exports.__exportStar || function(m, exports$2) {
1234
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$2, p)) __createBinding(exports$2, m, p);
1235
- };
1236
- Object.defineProperty(exports, "__esModule", { value: true });
1237
- __exportStar(require_sourceMap(), exports);
1238
- __exportStar(require_translateOffset(), exports);
1239
- }));
1240
-
1241
- //#endregion
1242
- //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/editor.js
1243
- var require_editor = /* @__PURE__ */ __commonJSMin(((exports) => {
1244
- Object.defineProperty(exports, "__esModule", { value: true });
1245
- exports.isHoverEnabled = isHoverEnabled;
1246
- exports.isInlayHintsEnabled = isInlayHintsEnabled;
1247
- exports.isCodeLensEnabled = isCodeLensEnabled;
1248
- exports.isMonikerEnabled = isMonikerEnabled;
1249
- exports.isInlineValueEnabled = isInlineValueEnabled;
1250
- exports.isSemanticTokensEnabled = isSemanticTokensEnabled;
1251
- exports.isCallHierarchyEnabled = isCallHierarchyEnabled;
1252
- exports.isTypeHierarchyEnabled = isTypeHierarchyEnabled;
1253
- exports.isRenameEnabled = isRenameEnabled;
1254
- exports.isDefinitionEnabled = isDefinitionEnabled;
1255
- exports.isTypeDefinitionEnabled = isTypeDefinitionEnabled;
1256
- exports.isReferencesEnabled = isReferencesEnabled;
1257
- exports.isImplementationEnabled = isImplementationEnabled;
1258
- exports.isHighlightEnabled = isHighlightEnabled;
1259
- exports.isSymbolsEnabled = isSymbolsEnabled;
1260
- exports.isFoldingRangesEnabled = isFoldingRangesEnabled;
1261
- exports.isSelectionRangesEnabled = isSelectionRangesEnabled;
1262
- exports.isLinkedEditingEnabled = isLinkedEditingEnabled;
1263
- exports.isColorEnabled = isColorEnabled;
1264
- exports.isDocumentLinkEnabled = isDocumentLinkEnabled;
1265
- exports.isDiagnosticsEnabled = isDiagnosticsEnabled;
1266
- exports.isCodeActionsEnabled = isCodeActionsEnabled;
1267
- exports.isFormattingEnabled = isFormattingEnabled;
1268
- exports.isCompletionEnabled = isCompletionEnabled;
1269
- exports.isAutoInsertEnabled = isAutoInsertEnabled;
1270
- exports.isSignatureHelpEnabled = isSignatureHelpEnabled;
1271
- exports.shouldReportDiagnostics = shouldReportDiagnostics;
1272
- exports.resolveRenameNewName = resolveRenameNewName;
1273
- exports.resolveRenameEditText = resolveRenameEditText;
1274
- exports.findOverlapCodeRange = findOverlapCodeRange;
1275
- function isHoverEnabled(info) {
1276
- return !!info.semantic;
1277
- }
1278
- function isInlayHintsEnabled(info) {
1279
- return !!info.semantic;
1280
- }
1281
- function isCodeLensEnabled(info) {
1282
- return !!info.semantic;
1283
- }
1284
- function isMonikerEnabled(info) {
1285
- return !!info.semantic;
1286
- }
1287
- function isInlineValueEnabled(info) {
1288
- return !!info.semantic;
1289
- }
1290
- function isSemanticTokensEnabled(info) {
1291
- return typeof info.semantic === "object" ? info.semantic.shouldHighlight?.() ?? true : !!info.semantic;
1292
- }
1293
- function isCallHierarchyEnabled(info) {
1294
- return !!info.navigation;
1295
- }
1296
- function isTypeHierarchyEnabled(info) {
1297
- return !!info.navigation;
1298
- }
1299
- function isRenameEnabled(info) {
1300
- return typeof info.navigation === "object" ? info.navigation.shouldRename?.() ?? true : !!info.navigation;
1301
- }
1302
- function isDefinitionEnabled(info) {
1303
- return !!info.navigation;
1304
- }
1305
- function isTypeDefinitionEnabled(info) {
1306
- return !!info.navigation;
1307
- }
1308
- function isReferencesEnabled(info) {
1309
- return !!info.navigation;
1310
- }
1311
- function isImplementationEnabled(info) {
1312
- return !!info.navigation;
1313
- }
1314
- function isHighlightEnabled(info) {
1315
- return typeof info.navigation === "object" ? info.navigation.shouldHighlight?.() ?? true : !!info.navigation;
1316
- }
1317
- function isSymbolsEnabled(info) {
1318
- return !!info.structure;
1319
- }
1320
- function isFoldingRangesEnabled(info) {
1321
- return !!info.structure;
1322
- }
1323
- function isSelectionRangesEnabled(info) {
1324
- return !!info.structure;
1325
- }
1326
- function isLinkedEditingEnabled(info) {
1327
- return !!info.structure;
1328
- }
1329
- function isColorEnabled(info) {
1330
- return !!info.structure;
1331
- }
1332
- function isDocumentLinkEnabled(info) {
1333
- return !!info.structure;
1334
- }
1335
- function isDiagnosticsEnabled(info) {
1336
- return !!info.verification;
1337
- }
1338
- function isCodeActionsEnabled(info) {
1339
- return !!info.verification;
1340
- }
1341
- function isFormattingEnabled(info) {
1342
- return !!info.format;
1343
- }
1344
- function isCompletionEnabled(info) {
1345
- return !!info.completion;
1346
- }
1347
- function isAutoInsertEnabled(info) {
1348
- return !!info.completion;
1349
- }
1350
- function isSignatureHelpEnabled(info) {
1351
- return !!info.completion;
1352
- }
1353
- function shouldReportDiagnostics(info, source, code) {
1354
- return typeof info.verification === "object" ? info.verification.shouldReport?.(source, code) ?? true : !!info.verification;
1355
- }
1356
- function resolveRenameNewName(newName, info) {
1357
- return typeof info.navigation === "object" ? info.navigation.resolveRenameNewName?.(newName) ?? newName : newName;
1358
- }
1359
- function resolveRenameEditText(text, info) {
1360
- return typeof info.navigation === "object" ? info.navigation.resolveRenameEditText?.(text) ?? text : text;
1361
- }
1362
- function findOverlapCodeRange(start, end, map, filter) {
1363
- let mappedStart;
1364
- let mappedEnd;
1365
- for (const [mapped, mapping] of map.toGeneratedLocation(start)) if (filter(mapping.data)) {
1366
- mappedStart = mapped;
1367
- break;
1368
- }
1369
- for (const [mapped, mapping] of map.toGeneratedLocation(end)) if (filter(mapping.data)) {
1370
- mappedEnd = mapped;
1371
- break;
1372
- }
1373
- if (mappedStart === void 0 || mappedEnd === void 0) {
1374
- for (const mapping of map.mappings) if (filter(mapping.data)) {
1375
- const mappingStart = mapping.sourceOffsets[0];
1376
- const overlap = getOverlapRange(start, end, mappingStart, mapping.sourceOffsets[mapping.sourceOffsets.length - 1] + mapping.lengths[mapping.lengths.length - 1]);
1377
- if (overlap) {
1378
- const curMappedStart = overlap.start - mappingStart + mapping.generatedOffsets[0];
1379
- const lastGeneratedLength = (mapping.generatedLengths ?? mapping.lengths)[mapping.generatedOffsets.length - 1];
1380
- const curMappedEndOffset = Math.min(overlap.end - mapping.sourceOffsets[mapping.sourceOffsets.length - 1], lastGeneratedLength);
1381
- const curMappedEnd = mapping.generatedOffsets[mapping.generatedOffsets.length - 1] + curMappedEndOffset;
1382
- mappedStart = mappedStart === void 0 ? curMappedStart : Math.min(mappedStart, curMappedStart);
1383
- mappedEnd = mappedEnd === void 0 ? curMappedEnd : Math.max(mappedEnd, curMappedEnd);
1384
- }
1385
- }
1386
- }
1387
- if (mappedStart !== void 0 && mappedEnd !== void 0) return {
1388
- start: mappedStart,
1389
- end: mappedEnd
1390
- };
1391
- }
1392
- function getOverlapRange(range1Start, range1End, range2Start, range2End) {
1393
- const start = Math.max(range1Start, range2Start);
1394
- const end = Math.min(range1End, range2End);
1395
- if (start > end) return;
1396
- return {
1397
- start,
1398
- end
1399
- };
1400
- }
1401
- }));
1402
-
1403
- //#endregion
1404
- //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/linkedCodeMap.js
1405
- var require_linkedCodeMap = /* @__PURE__ */ __commonJSMin(((exports) => {
1406
- Object.defineProperty(exports, "__esModule", { value: true });
1407
- exports.LinkedCodeMap = void 0;
1408
- const source_map_1 = require_source_map();
1409
- var LinkedCodeMap = class extends source_map_1.SourceMap {
1410
- *getLinkedOffsets(start) {
1411
- for (const mapped of this.toGeneratedLocation(start)) yield mapped[0];
1412
- for (const mapped of this.toSourceLocation(start)) yield mapped[0];
1413
- }
1414
- };
1415
- exports.LinkedCodeMap = LinkedCodeMap;
1416
- }));
1417
-
1418
- //#endregion
1419
- //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/types.js
1420
- var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
1421
- Object.defineProperty(exports, "__esModule", { value: true });
1422
- }));
1423
-
1424
- //#endregion
1425
- //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/utils.js
1426
- var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
1427
- Object.defineProperty(exports, "__esModule", { value: true });
1428
- exports.FileMap = void 0;
1429
- var FileMap = class extends Map {
1430
- constructor(caseSensitive) {
1431
- super();
1432
- this.caseSensitive = caseSensitive;
1433
- this.originalFileNames = /* @__PURE__ */ new Map();
1434
- }
1435
- keys() {
1436
- return this.originalFileNames.values();
1437
- }
1438
- get(key) {
1439
- return super.get(this.normalizeId(key));
1440
- }
1441
- has(key) {
1442
- return super.has(this.normalizeId(key));
1443
- }
1444
- set(key, value) {
1445
- this.originalFileNames.set(this.normalizeId(key), key);
1446
- return super.set(this.normalizeId(key), value);
1447
- }
1448
- delete(key) {
1449
- this.originalFileNames.delete(this.normalizeId(key));
1450
- return super.delete(this.normalizeId(key));
1451
- }
1452
- clear() {
1453
- this.originalFileNames.clear();
1454
- return super.clear();
1455
- }
1456
- normalizeId(id) {
1457
- return this.caseSensitive ? id : id.toLowerCase();
1458
- }
1459
- };
1460
- exports.FileMap = FileMap;
1461
- }));
1462
-
1463
- //#endregion
1464
- //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/index.js
1465
- var require_language_core = /* @__PURE__ */ __commonJSMin(((exports) => {
1466
- var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
1467
- if (k2 === void 0) k2 = k;
1468
- var desc = Object.getOwnPropertyDescriptor(m, k);
1469
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
1470
- enumerable: true,
1471
- get: function() {
1472
- return m[k];
1473
- }
1474
- };
1475
- Object.defineProperty(o, k2, desc);
1476
- }) : (function(o, m, k, k2) {
1477
- if (k2 === void 0) k2 = k;
1478
- o[k2] = m[k];
1479
- }));
1480
- var __exportStar = exports && exports.__exportStar || function(m, exports$1) {
1481
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
1482
- };
1483
- Object.defineProperty(exports, "__esModule", { value: true });
1484
- exports.defaultMapperFactory = exports.SourceMap = void 0;
1485
- exports.createLanguage = createLanguage;
1486
- exports.forEachEmbeddedCode = forEachEmbeddedCode;
1487
- var source_map_1 = require_source_map();
1488
- Object.defineProperty(exports, "SourceMap", {
1489
- enumerable: true,
1490
- get: function() {
1491
- return source_map_1.SourceMap;
1492
- }
1493
- });
1494
- __exportStar(require_editor(), exports);
1495
- __exportStar(require_linkedCodeMap(), exports);
1496
- __exportStar(require_types(), exports);
1497
- __exportStar(require_utils(), exports);
1498
- const source_map_2 = require_source_map();
1499
- const linkedCodeMap_1 = require_linkedCodeMap();
1500
- const defaultMapperFactory = (mappings) => new source_map_2.SourceMap(mappings);
1501
- exports.defaultMapperFactory = defaultMapperFactory;
1502
- function createLanguage(plugins, scriptRegistry, sync, onAssociationDirty) {
1503
- const virtualCodeToSourceScriptMap = /* @__PURE__ */ new WeakMap();
1504
- const virtualCodeToSourceMap = /* @__PURE__ */ new WeakMap();
1505
- const virtualCodeToLinkedCodeMap = /* @__PURE__ */ new WeakMap();
1506
- const language = {
1507
- mapperFactory: exports.defaultMapperFactory,
1508
- plugins,
1509
- scripts: {
1510
- fromVirtualCode(virtualCode) {
1511
- return virtualCodeToSourceScriptMap.get(virtualCode);
1512
- },
1513
- get(id, includeFsFiles = true, shouldRegister = false) {
1514
- sync(id, includeFsFiles, shouldRegister);
1515
- const result = scriptRegistry.get(id);
1516
- if (result?.isAssociationDirty) this.set(id, result.snapshot, result.languageId);
1517
- return scriptRegistry.get(id);
1518
- },
1519
- set(id, snapshot, languageId, _plugins = plugins) {
1520
- if (!languageId) for (const plugin of plugins) {
1521
- languageId = plugin.getLanguageId?.(id);
1522
- if (languageId) break;
1523
- }
1524
- if (!languageId) {
1525
- console.warn(`languageId not found for ${String(id)}`);
1526
- return;
1527
- }
1528
- let associatedOnly = false;
1529
- for (const plugin of plugins) if (plugin.isAssociatedFileOnly?.(id, languageId)) {
1530
- associatedOnly = true;
1531
- break;
1532
- }
1533
- if (scriptRegistry.has(id)) {
1534
- const sourceScript = scriptRegistry.get(id);
1535
- if (sourceScript.languageId !== languageId || sourceScript.associatedOnly !== associatedOnly) {
1536
- this.delete(id);
1537
- triggerTargetsDirty(sourceScript);
1538
- return this.set(id, snapshot, languageId);
1539
- } else if (associatedOnly) {
1540
- if (sourceScript.snapshot !== snapshot) {
1541
- sourceScript.snapshot = snapshot;
1542
- triggerTargetsDirty(sourceScript);
1543
- }
1544
- } else if (sourceScript.isAssociationDirty || sourceScript.snapshot !== snapshot) {
1545
- if (sourceScript.snapshot !== snapshot) {
1546
- sourceScript.snapshot = snapshot;
1547
- triggerTargetsDirty(sourceScript);
1548
- }
1549
- const codegenCtx = prepareCreateVirtualCode(sourceScript);
1550
- if (sourceScript.generated) {
1551
- const { updateVirtualCode, createVirtualCode } = sourceScript.generated.languagePlugin;
1552
- const newVirtualCode = updateVirtualCode ? updateVirtualCode(id, sourceScript.generated.root, snapshot, codegenCtx) : createVirtualCode?.(id, languageId, snapshot, codegenCtx);
1553
- if (newVirtualCode) {
1554
- sourceScript.generated.root = newVirtualCode;
1555
- sourceScript.generated.embeddedCodes.clear();
1556
- for (const code of forEachEmbeddedCode(sourceScript.generated.root)) {
1557
- virtualCodeToSourceScriptMap.set(code, sourceScript);
1558
- sourceScript.generated.embeddedCodes.set(code.id, code);
1559
- }
1560
- return sourceScript;
1561
- } else {
1562
- this.delete(id);
1563
- return;
1564
- }
1565
- }
1566
- } else return sourceScript;
1567
- } else {
1568
- const sourceScript = {
1569
- id,
1570
- languageId,
1571
- snapshot,
1572
- associatedIds: /* @__PURE__ */ new Set(),
1573
- targetIds: /* @__PURE__ */ new Set(),
1574
- associatedOnly
1575
- };
1576
- scriptRegistry.set(id, sourceScript);
1577
- if (associatedOnly) return sourceScript;
1578
- for (const languagePlugin of _plugins) {
1579
- const virtualCode = languagePlugin.createVirtualCode?.(id, languageId, snapshot, prepareCreateVirtualCode(sourceScript));
1580
- if (virtualCode) {
1581
- sourceScript.generated = {
1582
- root: virtualCode,
1583
- languagePlugin,
1584
- embeddedCodes: /* @__PURE__ */ new Map()
1585
- };
1586
- for (const code of forEachEmbeddedCode(virtualCode)) {
1587
- virtualCodeToSourceScriptMap.set(code, sourceScript);
1588
- sourceScript.generated.embeddedCodes.set(code.id, code);
1589
- }
1590
- break;
1591
- }
1592
- }
1593
- return sourceScript;
1594
- }
1595
- },
1596
- delete(id) {
1597
- const sourceScript = scriptRegistry.get(id);
1598
- if (sourceScript) {
1599
- sourceScript.generated?.languagePlugin.disposeVirtualCode?.(id, sourceScript.generated.root);
1600
- scriptRegistry.delete(id);
1601
- triggerTargetsDirty(sourceScript);
1602
- }
1603
- }
1604
- },
1605
- maps: {
1606
- get(virtualCode, sourceScript) {
1607
- let mapCache = virtualCodeToSourceMap.get(virtualCode.snapshot);
1608
- if (!mapCache) virtualCodeToSourceMap.set(virtualCode.snapshot, mapCache = /* @__PURE__ */ new WeakMap());
1609
- if (!mapCache.has(sourceScript.snapshot)) {
1610
- const mappings = virtualCode.associatedScriptMappings?.get(sourceScript.id) ?? virtualCode.mappings;
1611
- mapCache.set(sourceScript.snapshot, language.mapperFactory(mappings));
1612
- }
1613
- return mapCache.get(sourceScript.snapshot);
1614
- },
1615
- *forEach(virtualCode) {
1616
- const sourceScript = virtualCodeToSourceScriptMap.get(virtualCode);
1617
- yield [sourceScript, this.get(virtualCode, sourceScript)];
1618
- if (virtualCode.associatedScriptMappings) for (const [relatedScriptId] of virtualCode.associatedScriptMappings) {
1619
- const relatedSourceScript = scriptRegistry.get(relatedScriptId);
1620
- if (relatedSourceScript) yield [relatedSourceScript, this.get(virtualCode, relatedSourceScript)];
1621
- }
1622
- }
1623
- },
1624
- linkedCodeMaps: { get(virtualCode) {
1625
- const sourceScript = virtualCodeToSourceScriptMap.get(virtualCode);
1626
- let mapCache = virtualCodeToLinkedCodeMap.get(virtualCode.snapshot);
1627
- if (mapCache?.[0] !== sourceScript.snapshot) virtualCodeToLinkedCodeMap.set(virtualCode.snapshot, mapCache = [sourceScript.snapshot, virtualCode.linkedCodeMappings ? new linkedCodeMap_1.LinkedCodeMap(virtualCode.linkedCodeMappings) : void 0]);
1628
- return mapCache[1];
1629
- } }
1630
- };
1631
- return language;
1632
- function triggerTargetsDirty(sourceScript) {
1633
- sourceScript.targetIds.forEach((id) => {
1634
- const sourceScript = scriptRegistry.get(id);
1635
- if (sourceScript) {
1636
- sourceScript.isAssociationDirty = true;
1637
- onAssociationDirty?.(sourceScript.id);
1638
- }
1639
- });
1640
- }
1641
- function prepareCreateVirtualCode(sourceScript) {
1642
- for (const id of sourceScript.associatedIds) scriptRegistry.get(id)?.targetIds.delete(sourceScript.id);
1643
- sourceScript.associatedIds.clear();
1644
- sourceScript.isAssociationDirty = false;
1645
- return { getAssociatedScript(id) {
1646
- sync(id, true, true);
1647
- const relatedSourceScript = scriptRegistry.get(id);
1648
- if (relatedSourceScript) {
1649
- relatedSourceScript.targetIds.add(sourceScript.id);
1650
- sourceScript.associatedIds.add(relatedSourceScript.id);
1651
- }
1652
- return relatedSourceScript;
1653
- } };
1654
- }
1655
- }
1656
- function* forEachEmbeddedCode(virtualCode) {
1657
- yield virtualCode;
1658
- if (virtualCode.embeddedCodes) for (const embeddedCode of virtualCode.embeddedCodes) yield* forEachEmbeddedCode(embeddedCode);
1659
- }
1660
- }));
1661
-
1662
- //#endregion
1663
- //#region ../typescript-plugin/src/transform.js
1664
- var import_language_core = require_language_core();
1665
- /** @import * as AST from 'estree'; */
1666
- /** @import {CompileError, VolarMappingsResult, CodeMapping} from '@tsrx/core/types' */
1667
- /**
1668
- * The compiler contract every TSRX target exposes for editor tooling. Octane
1669
- * and consumer-declared modules may spell the entry `compileToVolarMappings`;
1670
- * see `normalize_tsrx_compiler_module` in `language.js`.
1671
- * @typedef {{
1672
- * compile?: (source: string, filename: string, options?: TsrxTransformOptions) => { code?: string, errors?: CompileError[] },
1673
- * compile_to_volar_mappings(source: string, filename: string, options?: { loose?: boolean } & TsrxTransformOptions): VolarMappingsResult,
1674
- * }} TSRXCompilerModule
1675
- */
1676
- /**
1677
- * @typedef {object} TsrxTransformOptions
1678
- * @property {'web' | 'ios' | 'android'} [platform] Platform selected for `import.meta.env.platform` flags.
1679
- */
1680
- /**
1681
- * A `<style>` or `<script>` body inside a `.tsrx` file, located by source
1682
- * offset. Both region kinds map 1:1 onto their source text.
1683
- * @typedef {object} EmbeddedRegion
1684
- * @property {string} id Stable id, e.g. `style_0` / `script_0`.
1685
- * @property {number} start Source offset of the first character of the body.
1686
- * @property {number} length Body length in UTF-16 code units.
1687
- * @property {string} content The body text.
1688
- */
1689
- /**
1690
- * The type-only transform of one `.tsrx` file, free of any Volar or
1691
- * TypeScript-host types so that both the classic Volar language plugin and the
1692
- * TypeScript 7 content mapper can consume it.
1693
- *
1694
- * `fatalError` is set when the compiler threw: `text` is then `''`,
1695
- * `mappings` is empty and `sourceAst` is `null`. Otherwise `text` is the
1696
- * generated TSX, `mappings` maps it back to the source, `errors` holds the
1697
- * non-fatal (usage) diagnostics and the regions describe the embedded
1698
- * `<style>` / `<script>` bodies.
1699
- * @typedef {object} TsrxTransformResult
1700
- * @property {string} text
1701
- * @property {CodeMapping[]} mappings
1702
- * @property {EmbeddedRegion[]} cssRegions
1703
- * @property {EmbeddedRegion[]} scriptRegions
1704
- * @property {CompileError[]} errors
1705
- * @property {CompileError | null} fatalError
1706
- * @property {AST.Program | null} sourceAst
1707
- */
1708
- /**
1709
- * Run a TSRX compiler's type-only transform in loose mode.
1710
- *
1711
- * Pure with respect to its inputs: the compiler module is the only
1712
- * collaborator, no caches are consulted and nothing is logged.
1713
- * @param {TSRXCompilerModule} compiler
1714
- * @param {string} file_name
1715
- * @param {string} content
1716
- * @param {TsrxTransformOptions} [options]
1717
- * @returns {TsrxTransformResult}
1718
- */
1719
- function transform_tsrx(compiler, file_name, content, options = {}) {
1720
- /** @type {VolarMappingsResult} */
1721
- let transpiled;
1722
- try {
1723
- transpiled = compiler.compile_to_volar_mappings(content, file_name, {
1724
- loose: true,
1725
- platform: options.platform
1726
- });
1727
- } catch (e) {
1728
- const error = e;
1729
- error.type = "fatal";
1730
- return {
1731
- text: "",
1732
- mappings: [],
1733
- cssRegions: [],
1734
- scriptRegions: [],
1735
- errors: [],
1736
- fatalError: error,
1737
- sourceAst: null
1738
- };
1739
- }
1740
- const scriptRegions = regions_from_mappings(transpiled.scriptMappings ?? []);
1741
- const embedded = embed_script_bodies(blank_script_bodies(transpiled.code ?? "", scriptRegions), transpiled.mappings ?? [], scriptRegions);
1742
- return {
1743
- text: embedded.text,
1744
- mappings: embedded.mappings,
1745
- cssRegions: regions_from_mappings(transpiled.cssMappings ?? []),
1746
- scriptRegions,
1747
- errors: transpiled.errors ?? [],
1748
- fatalError: null,
1749
- sourceAst: transpiled.sourceAst ?? null
1750
- };
1751
- }
1752
- /**
1753
- * The mapping data of a `<script>` body embedded in the generated TSX: every
1754
- * language feature except formatting, exactly like the compiler's own spans.
1755
- */
1756
- const SCRIPT_BODY_MAPPING_DATA = {
1757
- verification: true,
1758
- completion: true,
1759
- semantic: true,
1760
- navigation: true,
1761
- structure: true,
1762
- format: false,
1763
- customData: {}
1764
- };
1765
- /**
1766
- * `import` declarations at the top level of a `<script>` body, by offset. A
1767
- * conservative statement scanner (a line starting with `import`, up to the
1768
- * module specifier and optional attributes) rather than a parser: the body is
1769
- * plain TypeScript and the transform has no TypeScript parser of its own.
1770
- */
1771
- const IMPORT_DECLARATION = /^[ \t]*import\s+(?:type\s+)?(?:(?:[\w$]+\s*,\s*)?(?:\{[^}]*\}|\*\s+as\s+[\w$]+|[\w$]+)\s+from\s+)?(['"])[^'"\n]*\1(?:\s+with\s*\{[^}]*\})?[ \t]*;?/gm;
1772
- /**
1773
- * Whole export statements that carry no declaration: re-exports
1774
- * (`export ... from '...'`), local export lists (`export { a as b };`),
1775
- * `export type { T };` and `export = x;`. Module-level syntax with nothing to
1776
- * export from an inline script, blanked entirely.
1777
- */
1778
- const EXPORT_STATEMENT = /^[ \t]*export\s+(?:type\s+)?(?:(?:\{[^}]*\}|\*(?:\s+as\s+[\w$]+)?)(?:\s+from\s+(['"])[^'"\n]*\1(?:\s+with\s*\{[^}]*\})?)?|=\s*[^;\n]*)[ \t]*;?/gm;
1779
- /**
1780
- * `export default` in front of a named function or class declaration: only the
1781
- * keywords are blanked, so the declaration keeps its name in the block's scope.
1782
- */
1783
- const EXPORT_DEFAULT_NAMED = /^([ \t]*)(export[ \t]+default[ \t]+)(?=(?:async[ \t]+)?function[ \t]*\*?[ \t]*[A-Za-z_$]|(?:abstract[ \t]+)?class[ \t]+(?!(?:extends|implements)\b)[A-Za-z_$])/gm;
1784
- /**
1785
- * `export default` in front of an expression, an anonymous function or an
1786
- * anonymous class: replaced by a same-length `const <name>=` so the rest stays
1787
- * a valid, checked initializer (an anonymous `function () {}` or `class {}` is
1788
- * only valid as an expression).
1789
- */
1790
- const EXPORT_DEFAULT = /^([ \t]*)(export[ \t]+default[ \t]+)(?=\S)/gm;
1791
- /** The `export` keyword in front of a declaration. */
1792
- const EXPORT_KEYWORD = /^([ \t]*)(export[ \t]+)(?=(?:async[ \t]+)?(?:const|let|var|function|class|type|interface|enum|abstract|declare|namespace|module)\b)/gm;
1793
- /**
1794
- * A `<script type="module">` body may `export`, but nothing can import an inline
1795
- * script, so its exports are dead and a block cannot hold them: statements that
1796
- * only export are blanked, `export default` becomes a same-length `const`
1797
- * binding, and the keyword in front of a declaration is blanked, keeping every
1798
- * length so the body's mapping stays one to one.
1799
- * @param {string} body
1800
- * @returns {string}
1801
- */
1802
- function blank_export_syntax(body) {
1803
- return body.replace(EXPORT_STATEMENT, (statement) => statement.replace(/[^\r\n]/g, " ")).replace(EXPORT_DEFAULT_NAMED, (_match, indent, keywords) => indent + " ".repeat(keywords.length)).replace(EXPORT_DEFAULT, (_match, indent, keywords) => {
1804
- return `${indent}const ${"_default".padEnd(keywords.length - 6 - 1, "_")}=`;
1805
- }).replace(EXPORT_KEYWORD, (_match, indent, keyword) => indent + " ".repeat(keyword.length));
1806
- }
1807
- /**
1808
- * @param {string} body
1809
- * @returns {Array<{ start: number, end: number }>}
1810
- */
1811
- function find_import_declarations(body) {
1812
- /** @type {Array<{ start: number, end: number }>} */
1813
- const imports = [];
1814
- for (const match of body.matchAll(IMPORT_DECLARATION)) {
1815
- const start = match.index + match[0].length - match[0].trimStart().length;
1816
- imports.push({
1817
- start,
1818
- end: match.index + match[0].length
1819
- });
1820
- }
1821
- return imports;
1822
- }
1823
- /**
1824
- * Append every `<script>` body to the generated TSX as a block statement, so
1825
- * TypeScript checks it in the same file as the component, on every path that
1826
- * consumes the transform (the language server, tsserver through the plugin, and
1827
- * the content mapper), with ordinary mappings back to the source. A block keeps
1828
- * one body's declarations from colliding with another's or with the
1829
- * component's, and contributes nothing to declaration output.
1830
- *
1831
- * `import` declarations cannot live in a block, so each body's imports are
1832
- * hoisted verbatim in front of its block, at module level, where TypeScript
1833
- * resolves them like any other import (a browser-only URL in a
1834
- * `<script type="module">` yields a mapped "cannot find module"); their place
1835
- * in the block is blanked. `export` syntax is blanked in place
1836
- * ({@link blank_export_syntax}). Top-level `await` is legal inside a block of a
1837
- * module and stays as written. Each body maps in one multi-segment mapping.
1838
- * @param {string} text
1839
- * @param {CodeMapping[]} mappings
1840
- * @param {EmbeddedRegion[]} script_regions
1841
- * @returns {{ text: string, mappings: CodeMapping[] }}
1842
- */
1843
- function embed_script_bodies(text, mappings, script_regions) {
1844
- const result_mappings = [...mappings];
1845
- for (const region of script_regions) {
1846
- if (region.length === 0 || region.content.length !== region.length) continue;
1847
- const imports = find_import_declarations(region.content);
1848
- /** @type {number[]} */
1849
- const sourceOffsets = [];
1850
- /** @type {number[]} */
1851
- const generatedOffsets = [];
1852
- /** @type {number[]} */
1853
- const lengths = [];
1854
- let hoisted = "";
1855
- let body = blank_export_syntax(region.content);
1856
- for (const { start, end } of imports) {
1857
- sourceOffsets.push(region.start + start);
1858
- generatedOffsets.push(text.length + 1 + hoisted.length);
1859
- lengths.push(end - start);
1860
- hoisted += region.content.slice(start, end) + "\n";
1861
- body = body.slice(0, start) + " ".repeat(end - start) + body.slice(end);
1862
- }
1863
- const block_prefix = `\n${hoisted};{\n`;
1864
- const body_offset = text.length + block_prefix.length;
1865
- let cursor = 0;
1866
- for (const { start, end } of [...imports, {
1867
- start: region.length,
1868
- end: region.length
1869
- }]) {
1870
- if (start > cursor) {
1871
- sourceOffsets.push(region.start + cursor);
1872
- generatedOffsets.push(body_offset + cursor);
1873
- lengths.push(start - cursor);
1874
- }
1875
- cursor = end;
1876
- }
1877
- text += `${block_prefix}${body}\n}\n`;
1878
- if (sourceOffsets.length > 0) result_mappings.push({
1879
- sourceOffsets,
1880
- generatedOffsets,
1881
- lengths,
1882
- generatedLengths: [...lengths],
1883
- data: {
1884
- ...SCRIPT_BODY_MAPPING_DATA,
1885
- customData: { embeddedId: region.id }
1886
- }
1887
- });
1888
- }
1889
- return {
1890
- text,
1891
- mappings: result_mappings
1892
- };
1893
- }
1894
- /**
1895
- * Blank every `<script>` body in the generated TSX, keeping its length and
1896
- * line breaks. The compilers copy the body verbatim into the JSX text of the
1897
- * `<script>` element, where a `<` (as in `1 < 2`) parses as a tag and yields a
1898
- * syntax error that only the Volar path used to hide (it drops diagnostics
1899
- * with no source mapping; the content-mapper protocol reports them). The body
1900
- * is type-checked as a block appended by {@link embed_script_bodies}, and no
1901
- * mapping of the generated TSX points into the copy in the JSX text
1902
- * (`regions_from_mappings`), so blanking it loses nothing. A body is located by its text followed by the closing tag; a body
1903
- * that is not found unchanged in the output is left alone.
1904
- * @param {string} text
1905
- * @param {EmbeddedRegion[]} script_regions
1906
- * @returns {string}
1907
- */
1908
- function blank_script_bodies(text, script_regions) {
1909
- let cursor = 0;
1910
- for (const region of script_regions) {
1911
- if (region.length === 0) continue;
1912
- const needle = `${region.content}<\/script>`;
1913
- const index = text.indexOf(needle, cursor);
1914
- if (index < 0) continue;
1915
- const blank = region.content.replace(/[^\r\n]/g, " ");
1916
- text = text.slice(0, index) + blank + text.slice(index + region.content.length);
1917
- cursor = index + needle.length;
1918
- }
1919
- return text;
1920
- }
1921
- /**
1922
- * @param {CodeMapping[]} mappings
1923
- * @returns {EmbeddedRegion[]}
1924
- */
1925
- function regions_from_mappings(mappings) {
1926
- return mappings.map((mapping) => ({
1927
- id: String(mapping.data?.customData?.embeddedId ?? ""),
1928
- start: mapping.sourceOffsets[0],
1929
- length: mapping.lengths[0],
1930
- content: String(mapping.data?.customData?.content ?? "")
1931
- }));
1932
- }
1933
-
1934
- //#endregion
1935
- //#region ../typescript-plugin/src/language.js
1936
- /** @import * as AST from 'estree'; */
1937
- /** @import {CompileError, CodeMapping} from '@tsrx/core/types' */
1938
- /** @typedef {import('./transform.js').TSRXCompilerModule} TSRXCompilerModule */
1939
- /** @typedef {import('./transform.js').TsrxTransformResult} TsrxTransformResult */
1940
- /** @typedef {import('./transform.js').EmbeddedRegion} EmbeddedRegion */
1941
- /** @typedef {Map<string, CodeMapping>} CachedMappings */
1942
- /** @typedef {import('typescript').CompilerOptions} CompilerOptions */
1943
- /** @typedef {import('@volar/language-core').IScriptSnapshot} IScriptSnapshot */
1944
- /** @typedef {import('@volar/language-core').VirtualCode} VirtualCode */
1945
- /** @typedef {string | { fsPath: string }} ScriptId */
1946
- /** @typedef {typeof import('@volar/typescript')} _VolarTypeScriptAugmentation */
1947
- /** @typedef {import('./consumer-compiler.js').CompilerResolutionOptions} CompilerResolutionOptions */
1948
- /** @typedef {import('@volar/language-core').LanguagePlugin<ScriptId, VirtualCode>} TsrxLanguagePlugin */
1949
- /** @typedef {InstanceType<typeof import('./language.js')["TSRXVirtualCode"]>} TSRXVirtualCodeInstance */
1950
- const require$2 = createRequire$1(import.meta.url);
1951
- const root_dirname = path$1.dirname(fileURLToPath$1(import.meta.url));
1952
- const { log, logWarning, logError } = createLogging("[TSRX Language]");
1953
- /** @type {Set<string>} */
1954
- const loggedCompilationFailures = /* @__PURE__ */ new Set();
1955
- /**
1956
- * `[package name, package directory parts, supported extensions, package hints, entry candidates?]`.
1957
- * Entry candidates are relative to the package directory and are probed in order,
1958
- * so a package that ships both a build output and its sources lists the published
1959
- * layout first.
1960
- * @typedef {[string, string[], string[], string[], string[][]?]} CompilerCandidate
1961
- */
1962
- /** @type {CompilerCandidate[]} */
1963
- const COMPILER_CANDIDATES = [
1964
- [
1965
- "@tsrx/ripple",
1966
- [
1967
- "node_modules",
1968
- "@tsrx",
1969
- "ripple"
1970
- ],
1971
- [".tsrx"],
1972
- [
1973
- "@tsrx/ripple",
1974
- "ripple",
1975
- "@ripple-ts/vite-plugin"
1976
- ]
1977
- ],
1978
- [
1979
- "@tsrx/react",
1980
- [
1981
- "node_modules",
1982
- "@tsrx",
1983
- "react"
1984
- ],
1985
- [".tsrx"],
1986
- ["@tsrx/react", "@tsrx/vite-plugin-react"]
1987
- ],
1988
- [
1989
- "@tsrx/solid",
1990
- [
1991
- "node_modules",
1992
- "@tsrx",
1993
- "solid"
1994
- ],
1995
- [".tsrx"],
1996
- ["@tsrx/solid", "@tsrx/vite-plugin-solid"]
1997
- ],
1998
- [
1999
- "@tsrx/preact",
2000
- [
2001
- "node_modules",
2002
- "@tsrx",
2003
- "preact"
2004
- ],
2005
- [".tsrx"],
2006
- ["@tsrx/preact", "@tsrx/vite-plugin-preact"]
2007
- ],
2008
- [
2009
- "@tsrx/vue",
2010
- [
2011
- "node_modules",
2012
- "@tsrx",
2013
- "vue"
2014
- ],
2015
- [".tsrx"],
2016
- ["@tsrx/vue", "@tsrx/vite-plugin-vue"]
2017
- ],
2018
- [
2019
- "@tsrx/hono",
2020
- [
2021
- "node_modules",
2022
- "@tsrx",
2023
- "hono"
2024
- ],
2025
- [".tsrx"],
2026
- ["@tsrx/hono", "@tsrx/vite-plugin-hono"]
2027
- ],
2028
- [
2029
- "octane",
2030
- ["node_modules", "octane"],
2031
- [".tsrx"],
2032
- ["octane", "@octanejs/vite-plugin"],
2033
- [[
2034
- "dist",
2035
- "compiler",
2036
- "volar.js"
2037
- ], [
2038
- "src",
2039
- "compiler",
2040
- "volar.js"
2041
- ]]
2042
- ]
2043
- ];
2044
- /** @type {string[][]} */
2045
- const DEFAULT_COMPILER_ENTRY_CANDIDATES = [["src", "index.js"]];
2046
- /**
2047
- * Tokenize enough of a source text to find member chains: comments and
2048
- * string literals are skipped, template literals contribute only their
2049
- * `${...}` expressions, and every identifier, `.` and `?.` is a token.
2050
- * It tokenizes independently of any grammar, so partially authored TSRX and
2051
- * template syntax (`@{`, `@if`) are fine.
2052
- * @param {string} source
2053
- * @returns {Array<{ kind: 'word' | 'dot' | 'question-dot' | 'other', text: string }>}
2054
- */
2055
- function tokenize_member_chains(source) {
2056
- /** @type {Array<{ kind: 'word' | 'dot' | 'question-dot' | 'other', text: string }>} */
2057
- const tokens = [];
2058
- const length = source.length;
2059
- let index = 0;
2060
- /** Brace depth at which each open template substitution started, innermost last. */
2061
- /** @type {number[]} */
2062
- const template_braces = [];
2063
- let brace_depth = 0;
2064
- /** Skip template text from `index` to the closing backtick or the next substitution. */
2065
- function skip_template_text() {
2066
- while (index < length && source[index] !== "`") {
2067
- if (source[index] === "\\") {
2068
- index += 2;
2069
- continue;
2070
- }
2071
- if (source[index] === "$" && source[index + 1] === "{") {
2072
- template_braces.push(brace_depth);
2073
- index += 2;
2074
- return;
2075
- }
2076
- index += 1;
2077
- }
2078
- if (index < length) index += 1;
2079
- }
2080
- while (index < length) {
2081
- const char = source[index];
2082
- const next = source[index + 1];
2083
- if (/\s/.test(char)) index += 1;
2084
- else if (char === "/" && next === "/") while (index < length && source[index] !== "\n") index += 1;
2085
- else if (char === "/" && next === "*") {
2086
- const end = source.indexOf("*/", index + 2);
2087
- index = end < 0 ? length : end + 2;
2088
- } else if (char === "\"" || char === "'") {
2089
- index += 1;
2090
- while (index < length && source[index] !== char && source[index] !== "\n") {
2091
- if (source[index] === "\\") index += 1;
2092
- index += 1;
2093
- }
2094
- index += 1;
2095
- } else if (char === "`") {
2096
- index += 1;
2097
- skip_template_text();
2098
- } else if (char === "}" && template_braces.length > 0 && template_braces[template_braces.length - 1] === brace_depth) {
2099
- template_braces.pop();
2100
- index += 1;
2101
- skip_template_text();
2102
- } else if (/[A-Za-z_$]/.test(char)) {
2103
- let end = index + 1;
2104
- while (end < length && /[\w$]/.test(source[end])) end += 1;
2105
- tokens.push({
2106
- kind: "word",
2107
- text: source.slice(index, end)
2108
- });
2109
- index = end;
2110
- } else if (char === "?" && next === ".") {
2111
- tokens.push({
2112
- kind: "question-dot",
2113
- text: "?."
2114
- });
2115
- index += 2;
2116
- } else if (char === ".") {
2117
- tokens.push({
2118
- kind: "dot",
2119
- text: "."
2120
- });
2121
- index += 1;
2122
- } else {
2123
- if (char === "{") brace_depth += 1;
2124
- else if (char === "}") brace_depth -= 1;
2125
- tokens.push({
2126
- kind: "other",
2127
- text: char
2128
- });
2129
- index += 1;
2130
- }
2131
- }
2132
- return tokens;
2133
- }
2134
- /**
2135
- * Detect exact platform property paths (`import.meta.env.platform.web` and
2136
- * the `ios` and `android` twins) without matching comments or string
2137
- * literals, and without TypeScript's scanner so the native path needs no
2138
- * TypeScript.
2139
- *
2140
- * @param {string} source
2141
- * @param {unknown} [_typescript] Accepted for older callers; unused.
2142
- * @returns {boolean}
2143
- */
2144
- function source_uses_platform_flag(source, _typescript) {
2145
- const tokens = tokenize_member_chains(source);
2146
- const prefix = [
2147
- "import",
2148
- ".",
2149
- "meta",
2150
- ".",
2151
- "env",
2152
- ".",
2153
- "platform",
2154
- "."
2155
- ];
2156
- for (let index = 0; index + prefix.length < tokens.length; index += 1) {
2157
- if (index > 0 && (tokens[index - 1].kind === "dot" || tokens[index - 1].kind === "question-dot")) continue;
2158
- if (!prefix.every((text, offset) => tokens[index + offset].text === text)) continue;
2159
- const name = tokens[index + prefix.length].text;
2160
- if (name === "web" || name === "ios" || name === "android") return true;
2161
- }
2162
- return false;
2163
- }
2164
- /** @type {Map<string, string | null>} */
2165
- const path2TsrxCompilerPathMap = /* @__PURE__ */ new Map();
2166
- /** @type {Map<string, { name: string | null, dependencies: Set<string> } | null>} */
2167
- const pathToPackageManifestCache = /* @__PURE__ */ new Map();
2168
- /**
2169
- * @param {string} start_dir
2170
- * @param {(file_path: import('fs').PathLike) => boolean} [exists_sync]
2171
- * @returns {{ name: string | null, dependencies: Set<string> } | null}
2172
- */
2173
- function get_nearest_package_manifest(start_dir, exists_sync = fs$1.existsSync) {
2174
- let current_dir = start_dir;
2175
- /** @type {string[]} */
2176
- const visited_dirs = [];
2177
- while (current_dir) {
2178
- if (pathToPackageManifestCache.has(current_dir)) {
2179
- const cached_manifest = pathToPackageManifestCache.get(current_dir) ?? null;
2180
- for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, cached_manifest);
2181
- return cached_manifest;
2182
- }
2183
- visited_dirs.push(current_dir);
2184
- const package_json_path = path$1.join(current_dir, "package.json");
2185
- if (exists_sync(package_json_path)) try {
2186
- const package_json = JSON.parse(fs$1.readFileSync(package_json_path, "utf8"));
2187
- const dependencies = /* @__PURE__ */ new Set([
2188
- ...Object.keys(package_json.dependencies ?? {}),
2189
- ...Object.keys(package_json.devDependencies ?? {}),
2190
- ...Object.keys(package_json.peerDependencies ?? {}),
2191
- ...Object.keys(package_json.optionalDependencies ?? {})
2192
- ]);
2193
- const package_manifest = {
2194
- name: typeof package_json.name === "string" ? package_json.name : null,
2195
- dependencies
2196
- };
2197
- for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, package_manifest);
2198
- return package_manifest;
2199
- } catch {
2200
- for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, null);
2201
- return null;
2202
- }
2203
- const parent_dir = path$1.dirname(current_dir);
2204
- if (parent_dir === current_dir) break;
2205
- current_dir = parent_dir;
2206
- }
2207
- for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, null);
2208
- return null;
2209
- }
2210
- /**
2211
- * @param {{ name: string | null, dependencies: Set<string> } | null} package_manifest
2212
- * @param {string} compiler_name
2213
- * @param {string[]} package_hints
2214
- * @returns {boolean}
2215
- */
2216
- function package_manifest_matches_compiler(package_manifest, compiler_name, package_hints) {
2217
- if (!package_manifest) return false;
2218
- if (package_manifest.name === compiler_name || package_hints.includes(package_manifest.name ?? "")) return true;
2219
- if (package_manifest.dependencies.has(compiler_name)) return true;
2220
- for (const package_hint of package_hints) if (package_manifest.dependencies.has(package_hint)) return true;
2221
- return false;
2222
- }
2223
- /**
2224
- * Load a resolved compiler entry and normalize its contract.
2225
- * @param {string} compiler_path
2226
- * @returns {TSRXCompilerModule}
2227
- */
2228
- function require_tsrx_compiler(compiler_path) {
2229
- return normalize_tsrx_compiler_module(require$2(compiler_path));
2230
- }
2231
- /**
2232
- * Normalize the compiler contract used by Octane and consumer-declared modules.
2233
- * @param {TSRXCompilerModule & { compileToVolarMappings?: TSRXCompilerModule['compile_to_volar_mappings'] }} compiler_module
2234
- * @returns {TSRXCompilerModule}
2235
- */
2236
- function normalize_tsrx_compiler_module(compiler_module) {
2237
- if (typeof compiler_module?.compile_to_volar_mappings !== "function" && typeof compiler_module?.compileToVolarMappings === "function") return {
2238
- ...compiler_module,
2239
- compile_to_volar_mappings: compiler_module.compileToVolarMappings
2240
- };
2241
- return compiler_module;
2242
- }
2243
- /**
2244
- * @param {string} normalized_file_name
2245
- * @param {(file_path: import('fs').PathLike) => boolean} [exists_sync]
2246
- * @param {Map<string, string | null>} [compiler_path_map]
2247
- * @returns {string | undefined}
2248
- */
2249
- function find_workspace_compiler_entry_for_file(normalized_file_name, exists_sync = fs$1.existsSync, compiler_path_map = path2TsrxCompilerPathMap) {
2250
- const parts = normalized_file_name.split("/");
2251
- const ext = path$1.extname(normalized_file_name);
2252
- for (let i = parts.length - 2; i >= 0; i--) {
2253
- const dir = parts.slice(0, i + 1).join("/");
2254
- const cache_key = dir + "\0" + ext;
2255
- if (!compiler_path_map.has(cache_key)) {
2256
- /** @type {Array<[string, string, string[]]>} */
2257
- const available_candidates = [];
2258
- for (const [compiler_name, compiler_dir_parts, supported_extensions, package_hints, entry_candidates = DEFAULT_COMPILER_ENTRY_CANDIDATES] of COMPILER_CANDIDATES) {
2259
- if (!supported_extensions.includes(ext)) continue;
2260
- for (const entry_parts of entry_candidates) {
2261
- const full_path = [
2262
- dir,
2263
- ...compiler_dir_parts,
2264
- ...entry_parts
2265
- ].join("/");
2266
- if (exists_sync(full_path)) {
2267
- available_candidates.push([
2268
- compiler_name,
2269
- full_path,
2270
- package_hints
2271
- ]);
2272
- break;
2273
- }
2274
- }
2275
- }
2276
- let found_path = null;
2277
- if (available_candidates.length > 0) {
2278
- const package_manifest = get_nearest_package_manifest(dir, exists_sync);
2279
- found_path = available_candidates.find(([compiler_name, , package_hints]) => package_manifest_matches_compiler(package_manifest, compiler_name, package_hints))?.[1] ?? available_candidates[0][1];
2280
- log("Found tsrx compiler at:", found_path, "for extension:", ext);
2281
- }
2282
- compiler_path_map.set(cache_key, found_path);
2283
- }
2284
- const compiler_path = compiler_path_map.get(cache_key);
2285
- if (compiler_path) return compiler_path;
2286
- }
2287
- }
2288
- /**
2289
- * @param {string} normalized_file_name
2290
- * @param {CompilerResolutionOptions} [options]
2291
- * @returns {string | undefined}
2292
- */
2293
- function get_compiler_entry_for_file(normalized_file_name, options) {
2294
- const ext = path$1.extname(normalized_file_name);
2295
- const consumer_compiler_path = resolve_consumer_compiler_for_file(normalized_file_name, options);
2296
- if (consumer_compiler_path !== void 0) return consumer_compiler_path ?? void 0;
2297
- const package_manifest = get_nearest_package_manifest(path$1.dirname(normalized_file_name));
2298
- const workspace_compiler_path = find_workspace_compiler_entry_for_file(normalized_file_name);
2299
- if (workspace_compiler_path) return workspace_compiler_path;
2300
- const warn_message = `No supported tsrx compiler found in workspace for ${normalized_file_name}.`;
2301
- let current_dir = root_dirname;
2302
- while (current_dir) {
2303
- /** @type {Array<[string, string, string[]]>} */
2304
- const available_candidates = [];
2305
- for (const [compiler_name, compiler_dir_parts, supported_extensions, package_hints, entry_candidates = DEFAULT_COMPILER_ENTRY_CANDIDATES] of COMPILER_CANDIDATES) {
2306
- if (!supported_extensions.includes(ext)) continue;
2307
- const full_path = path$1.join(current_dir, ...compiler_dir_parts);
2308
- for (const entry_parts of entry_candidates) {
2309
- const entry_path = path$1.join(full_path, ...entry_parts);
2310
- if (fs$1.existsSync(entry_path)) {
2311
- available_candidates.push([
2312
- compiler_name,
2313
- entry_path,
2314
- package_hints
2315
- ]);
2316
- break;
2317
- }
2318
- }
2319
- }
2320
- if (available_candidates.length > 0) {
2321
- const entry_path = available_candidates.find(([compiler_name, , package_hints]) => package_manifest_matches_compiler(package_manifest, compiler_name, package_hints))?.[1] ?? available_candidates[0][1];
2322
- logWarning(`${warn_message} Using packaged version at ${entry_path}`);
2323
- return entry_path;
2324
- }
2325
- const parent_dir = path$1.dirname(current_dir);
2326
- if (parent_dir === current_dir) break;
2327
- current_dir = parent_dir;
2328
- }
2329
- }
2330
- /**
2331
- * Drop compiler-selection state. Loaded ESM compiler graphs cannot be evicted
2332
- * safely in-process; language-server package watchers restart the process.
2333
- */
2334
- function invalidateCompilerResolutionCaches() {
2335
- path2TsrxCompilerPathMap.clear();
2336
- pathToPackageManifestCache.clear();
2337
- reset_consumer_compiler_resolution_caches();
2338
- loggedCompilationFailures.clear();
2339
- }
2340
-
2341
- //#endregion
2342
- //#region src/export-stub.js
2343
- /** @import * as AST from 'estree' */
2344
- /**
2345
- * Build a TypeScript stub that preserves a module's export surface while the
2346
- * file cannot be compiled.
2347
- *
2348
- * The native content-mapper protocol offers no way to suppress TypeScript's
2349
- * own diagnostics, so feeding raw TSRX (or the last good TSX, which may carry
2350
- * type errors of its own) to the checker would produce noise. Instead every
2351
- * export from the last successful transform's source AST is re-declared as
2352
- * `any` (both as a value and as a type, so `new X()`, `X.y` and `let v: X` all
2353
- * keep resolving), re-exports from other modules are kept as written (including
2354
- * their `type` modifiers, so `isolatedModules` and `verbatimModuleSyntax` do
2355
- * not reject the stub), and the compile error is reported through the mapper's
2356
- * own diagnostics. Importers keep resolving; the author sees one error at the
2357
- * right place.
2358
- * @param {AST.Program | null | undefined} program The last successfully parsed source AST, if any.
2359
- * @returns {string}
2360
- */
2361
- function build_export_stub(program) {
2362
- /** @type {string[]} */
2363
- const lines = [];
2364
- /** @type {Set<string>} */
2365
- const names = /* @__PURE__ */ new Set();
2366
- let has_default = false;
2367
- for (const statement of program?.body ?? []) switch (statement.type) {
2368
- case "ExportAllDeclaration": {
2369
- const exported = statement.exported ? ` as ${export_name(statement.exported)}` : "";
2370
- lines.push(`export ${type_modifier(statement)}*${exported} from ${JSON.stringify(String(statement.source.value))};`);
2371
- break;
2372
- }
2373
- case "ExportDefaultDeclaration":
2374
- has_default = true;
2375
- break;
2376
- case "ExportNamedDeclaration":
2377
- if (statement.source) {
2378
- const statement_is_type = type_modifier(statement) !== "";
2379
- const specifiers = statement.specifiers.map((specifier) => {
2380
- const local = export_name(specifier.local);
2381
- const exported = export_name(specifier.exported);
2382
- return `${statement_is_type ? "" : type_modifier(specifier)}${local === exported ? local : `${local} as ${exported}`}`;
2383
- });
2384
- lines.push(`export ${type_modifier(statement)}{ ${specifiers.join(", ")} } from ${JSON.stringify(String(statement.source.value))};`);
2385
- break;
2386
- }
2387
- for (const specifier of statement.specifiers) {
2388
- const exported = export_name(specifier.exported);
2389
- if (exported === "default") has_default = true;
2390
- else names.add(exported);
2391
- }
2392
- if (statement.declaration) for (const name of declaration_names(statement.declaration)) names.add(name);
2393
- }
2394
- for (const name of names) {
2395
- if (!/^[\p{ID_Start}_$][\p{ID_Continue}$]*$/u.test(name)) continue;
2396
- lines.push(`export declare const ${name}: any;`);
2397
- lines.push(`export type ${name} = any;`);
2398
- }
2399
- if (has_default) {
2400
- lines.push("declare const _default: any;");
2401
- lines.push("export default _default;");
2402
- }
2403
- if (lines.length === 0) lines.push("export {};");
2404
- return lines.join("\n") + "\n";
2405
- }
2406
- /**
2407
- * `type ` for a type-only export statement or specifier (the ESTree-TS
2408
- * `exportKind` field), else the empty string.
2409
- * @param {AST.Node} node
2410
- * @returns {'type ' | ''}
2411
- */
2412
- function type_modifier(node) {
2413
- return node.exportKind === "type" ? "type " : "";
2414
- }
2415
- /**
2416
- * @param {AST.Identifier | AST.Literal | AST.Expression} node
2417
- * @returns {string}
2418
- */
2419
- function export_name(node) {
2420
- if (node.type === "Identifier") return node.name;
2421
- if (node.type === "Literal") return String(node.value);
2422
- return "";
2423
- }
2424
- /**
2425
- * @param {AST.Declaration | AST.Node} declaration
2426
- * @returns {string[]}
2427
- */
2428
- function declaration_names(declaration) {
2429
- switch (declaration.type) {
2430
- case "VariableDeclaration": return declaration.declarations.flatMap((declarator) => pattern_names(declarator.id));
2431
- case "FunctionDeclaration":
2432
- case "ClassDeclaration": return declaration.id ? [declaration.id.name] : [];
2433
- default: {
2434
- const id = declaration.id;
2435
- return id && id.type === "Identifier" ? [id.name] : [];
2436
- }
2437
- }
2438
- }
2439
- /**
2440
- * @param {AST.Pattern} pattern
2441
- * @returns {string[]}
2442
- */
2443
- function pattern_names(pattern) {
2444
- switch (pattern.type) {
2445
- case "Identifier": return [pattern.name];
2446
- case "ObjectPattern": return pattern.properties.flatMap((property) => property.type === "RestElement" ? pattern_names(property.argument) : pattern_names(property.value));
2447
- case "ArrayPattern": return pattern.elements.flatMap((element) => element ? pattern_names(element) : []);
2448
- case "RestElement": return pattern_names(pattern.argument);
2449
- case "AssignmentPattern": return pattern_names(pattern.left);
2450
- default: return [];
2451
- }
2452
- }
2453
-
2454
- //#endregion
2455
- //#region src/protocol.js
2456
- /**
2457
- * Constants of the TypeScript 7 content-mapper protocol, kept in sync with
2458
- * `tsc/internal/contentmapper` and `tsc/internal/spanmap` in microsoft/TypeScript.
2459
- */
2460
- /** Span kinds. */
2461
- const SpanMapKind = {
2462
- /** Same length and identical text; the only kind that supports text edits. */
2463
- Verbatim: 0,
2464
- /** Same entity, different text or length. */
2465
- Atom: 1,
2466
- /** Different text; diagnostics covering the whole span exactly show the original text. */
2467
- Alias: 2
2468
- };
2469
- /** Feature bits a span opts into. Diagnostics ignore them. */
2470
- const SpanMapFeature = {
2471
- Hover: 1,
2472
- SignatureHelp: 2,
2473
- Completion: 4,
2474
- Definition: 8,
2475
- TypeDefinition: 16,
2476
- Implementation: 32,
2477
- References: 64,
2478
- DocumentHighlights: 128,
2479
- Rename: 256,
2480
- CallHierarchy: 512,
2481
- CodeActions: 1024,
2482
- Formatting: 2048,
2483
- InlayHints: 4096,
2484
- SemanticTokens: 8192,
2485
- FoldingRanges: 16384,
2486
- SelectionRanges: 32768,
2487
- LinkedEditing: 65536,
2488
- AutoInsert: 1 << 17,
2489
- DocumentSymbols: 1 << 18,
2490
- CodeLens: 1 << 19,
2491
- None: 0,
2492
- All: (1 << 20) - 1
2493
- };
2494
- /** Prefix for mapper-authored diagnostics: `error tsrx(1000): ...`. */
2495
- const DIAGNOSTIC_SOURCE = "tsrx";
2496
- /** Numeric code for a fatal compile error (the file could not be transformed). */
2497
- const DIAGNOSTIC_CODE_COMPILE_ERROR = 1e3;
2498
- /** Numeric code for a usage error that carries no string code. */
2499
- const DIAGNOSTIC_CODE_USAGE_ERROR = 1001;
2500
- /** Numeric code when no TSRX compiler can be resolved for a file. */
2501
- const DIAGNOSTIC_CODE_NO_COMPILER = 1002;
2502
- /** Numeric code when the project's TSRX configuration is invalid. */
2503
- const DIAGNOSTIC_CODE_INVALID_CONFIG = 1003;
2504
- /**
2505
- * @typedef {[
2506
- * generatedStart: number,
2507
- * generatedLength: number,
2508
- * originalStart: number,
2509
- * originalLength: number,
2510
- * kind: 0 | 1 | 2,
2511
- * features: number,
2512
- * ]} SpanMapping
2513
- */
2514
- /**
2515
- * @typedef {object} MapperDiagnostic
2516
- * @property {number} start Offset into the original text (UTF-16 code units).
2517
- * @property {number} length
2518
- * @property {number} code
2519
- * @property {string} messageText
2520
- */
2521
- /**
2522
- * @typedef {object} MappedOutput
2523
- * @property {string} text
2524
- * @property {'.js' | '.jsx' | '.mjs' | '.cjs' | '.ts' | '.tsx' | '.mts' | '.cts' | '.json'} extension
2525
- * @property {SpanMapping[]} mappings
2526
- */
2527
- /**
2528
- * @typedef {MappedOutput & {
2529
- * diagnostics?: MapperDiagnostic[],
2530
- * supplemental?: MappedOutput[],
2531
- * }} TransformResult
2532
- */
2533
- /**
2534
- * @typedef {object} InitializeParams
2535
- * @property {string} [locale]
2536
- * @property {Array<'utf-8' | 'utf-16'>} positionEncodings
2537
- */
2538
- /**
2539
- * @typedef {object} InitializeResult
2540
- * @property {'utf-8' | 'utf-16'} positionEncoding
2541
- * @property {string} diagnosticSource
2542
- */
2543
- /**
2544
- * @typedef {object} OpenProjectParams
2545
- * @property {string} configFileName Empty for inferred projects.
2546
- * @property {string} projectHandle
2547
- * @property {Record<string, unknown>} [options] The mapper entry's `options` object.
2548
- * @property {Record<string, unknown>} compilerOptions Effective compiler options (wire format).
2549
- */
2550
- /**
2551
- * @typedef {object} OpenProjectResult
2552
- * @property {string} configIdentity
2553
- * @property {string[]} [watchedFiles]
2554
- * @property {Array<{ path: Array<string | number>, messageText: string, code: number }>} [optionDiagnostics]
2555
- */
2556
- /**
2557
- * @typedef {object} TransformParams
2558
- * @property {string} fileName
2559
- * @property {string} content
2560
- * @property {string} [projectHandle]
2561
- */
2562
-
2563
- //#endregion
2564
- //#region src/span-mappings.js
2565
- /** @import {CodeMapping} from '@tsrx/core/types' */
2566
- /** @import {SpanMapping} from './protocol.js' */
2567
- const semantic_features = SpanMapFeature.Hover | SpanMapFeature.SignatureHelp | SpanMapFeature.InlayHints | SpanMapFeature.SemanticTokens;
2568
- const completion_features = SpanMapFeature.Completion | SpanMapFeature.AutoInsert;
2569
- const navigation_features = SpanMapFeature.Definition | SpanMapFeature.TypeDefinition | SpanMapFeature.Implementation | SpanMapFeature.References | SpanMapFeature.DocumentHighlights | SpanMapFeature.Rename | SpanMapFeature.CallHierarchy | SpanMapFeature.CodeActions | SpanMapFeature.LinkedEditing;
2570
- const structure_features = SpanMapFeature.FoldingRanges | SpanMapFeature.SelectionRanges | SpanMapFeature.DocumentSymbols | SpanMapFeature.CodeLens;
2571
- const identifier_pattern = /^[\p{ID_Start}_$][\p{ID_Continue}$‌‍]*$/u;
2572
- /**
2573
- * @typedef {object} Candidate
2574
- * @property {number} generatedStart
2575
- * @property {number} generatedEnd
2576
- * @property {number} originalStart
2577
- * @property {number} originalEnd
2578
- * @property {0 | 1 | 2} kind
2579
- * @property {number} features
2580
- */
2581
- /**
2582
- * Translate a Volar `CodeMapping['data']` into content-mapper feature bits.
2583
- *
2584
- * `verification` has no bit: diagnostics always apply. Spans that carry CSS
2585
- * class hover/definition metadata (`customData.hover` / `customData.definition`)
2586
- * leave Hover and Definition off so the TSRX language server owns those
2587
- * features. `semantic.shouldHighlight()` returning `false` (string-literal
2588
- * spans) drops SemanticTokens.
2589
- * @param {CodeMapping['data'] | undefined} data
2590
- * @returns {number}
2591
- */
2592
- function features_from_mapping_data(data) {
2593
- if (!data || typeof data !== "object") return SpanMapFeature.None;
2594
- let features = SpanMapFeature.None;
2595
- if (data.semantic) {
2596
- features |= semantic_features;
2597
- if (typeof data.semantic === "object" && data.semantic.shouldHighlight?.() === false) features &= ~SpanMapFeature.SemanticTokens;
2598
- }
2599
- if (data.completion) features |= completion_features;
2600
- if (data.navigation) {
2601
- features |= navigation_features;
2602
- if (typeof data.navigation === "object") {
2603
- if (data.navigation.shouldHighlight?.() === false) features &= ~SpanMapFeature.DocumentHighlights;
2604
- if (data.navigation.shouldRename?.() === false) features &= ~SpanMapFeature.Rename;
2605
- }
2606
- }
2607
- if (data.structure) features |= structure_features;
2608
- if (data.format) features |= SpanMapFeature.Formatting;
2609
- const custom = data.customData;
2610
- if (custom && (custom.hover !== void 0 || custom.definition !== void 0)) features &= ~(SpanMapFeature.Hover | SpanMapFeature.Definition);
2611
- return features;
2612
- }
2613
- /**
2614
- * Convert the type-only transform's Volar mappings into a content-mapper span
2615
- * map: an ordered, disjoint (in generated space) list of
2616
- * `[generatedStart, generatedLength, originalStart, originalLength, kind, features]`.
2617
- *
2618
- * - Equal length and identical text → `Verbatim` (the only edit-safe kind).
2619
- * - An identifier whose generated spelling differs (obfuscated `_$_` names,
2620
- * renamed or capitalized identifiers) → `Alias`, so diagnostics that cover
2621
- * the span exactly show the authored name.
2622
- * - Anything else → `Atom`.
2623
- *
2624
- * The transform emits container spans (statements, control-flow bodies) that
2625
- * enclose token spans. TypeScript requires generated spans to be disjoint, so
2626
- * candidates are ranked Verbatim first, then shorter before longer, and a
2627
- * candidate that overlaps an already selected span in generated space is
2628
- * dropped. Overlap in original space is allowed by the protocol (one source
2629
- * range may be projected several times) and is kept.
2630
- *
2631
- * Neighbouring Verbatim spans with equal feature bits whose gap is the same
2632
- * text in both files are then coalesced into one span (see
2633
- * {@link coalesce_verbatim_spans}), so a statement such as
2634
- * `import { a } from './x';` is one edit-safe span rather than four tokens
2635
- * with unmapped punctuation between them. TypeScript only applies text edits
2636
- * (auto-import, rename, code actions) that fit inside a single Verbatim span.
2637
- * @param {readonly CodeMapping[]} mappings
2638
- * @param {string} generated_text
2639
- * @param {string} original_text
2640
- * @param {{ languageFeatures?: boolean }} [options] `languageFeatures: false` clears every feature bit (CLI-only projects).
2641
- * @returns {SpanMapping[]}
2642
- */
2643
- function to_span_mappings(mappings, generated_text, original_text, options = {}) {
2644
- const language_features = options.languageFeatures !== false;
2645
- /** @type {Candidate[]} */
2646
- const candidates = [];
2647
- for (const mapping of mappings) {
2648
- const count = Math.min(mapping.sourceOffsets.length, mapping.generatedOffsets.length);
2649
- for (let index = 0; index < count; index++) {
2650
- const original_start = mapping.sourceOffsets[index];
2651
- const generated_start = mapping.generatedOffsets[index];
2652
- const original_length = mapping.lengths[index] ?? mapping.lengths[0];
2653
- const generated_length = mapping.generatedLengths?.[index] ?? mapping.generatedLengths?.[0] ?? original_length;
2654
- if (!Number.isInteger(original_start) || !Number.isInteger(generated_start) || !Number.isInteger(original_length) || !Number.isInteger(generated_length) || original_start < 0 || generated_start < 0 || original_length <= 0 || generated_length <= 0) continue;
2655
- const generated_end = generated_start + generated_length;
2656
- const original_end = original_start + original_length;
2657
- if (generated_end > generated_text.length || original_end > original_text.length) continue;
2658
- const generated_slice = generated_text.slice(generated_start, generated_end);
2659
- const original_slice = original_text.slice(original_start, original_end);
2660
- /** @type {0 | 1 | 2} */
2661
- let kind;
2662
- if (generated_length === original_length && generated_slice === original_slice) kind = SpanMapKind.Verbatim;
2663
- else if (is_whole_identifier(generated_text, generated_start, generated_end) && is_whole_token(original_text, original_start, original_end)) kind = SpanMapKind.Alias;
2664
- else if (is_partial_identifier(original_text, original_start, original_end)) continue;
2665
- else kind = SpanMapKind.Atom;
2666
- candidates.push({
2667
- generatedStart: generated_start,
2668
- generatedEnd: generated_end,
2669
- originalStart: original_start,
2670
- originalEnd: original_end,
2671
- kind,
2672
- features: language_features ? features_from_mapping_data(mapping.data) : SpanMapFeature.None
2673
- });
2674
- }
2675
- }
2676
- candidates.sort((left, right) => Number(left.kind !== SpanMapKind.Verbatim) - Number(right.kind !== SpanMapKind.Verbatim) || left.generatedEnd - left.generatedStart - (right.generatedEnd - right.generatedStart) || left.generatedStart - right.generatedStart || left.originalStart - right.originalStart);
2677
- /** @type {Candidate[]} */
2678
- const selected = [];
2679
- const occupied = new IntervalSet();
2680
- for (const candidate of candidates) {
2681
- if (!occupied.add(candidate.generatedStart, candidate.generatedEnd)) continue;
2682
- selected.push(candidate);
2683
- }
2684
- selected.sort((left, right) => left.generatedStart - right.generatedStart);
2685
- return extend_verbatim_spans_over_whitespace(coalesce_verbatim_spans(selected, generated_text, original_text), generated_text, original_text).map((candidate) => [
2686
- candidate.generatedStart,
2687
- candidate.generatedEnd - candidate.generatedStart,
2688
- candidate.originalStart,
2689
- candidate.originalEnd - candidate.originalStart,
2690
- candidate.kind,
2691
- candidate.features
2692
- ]);
2693
- }
2694
- /**
2695
- * Merge runs of Verbatim spans, sorted by generated start, when the two spans
2696
- * carry the same feature bits and the text between them is identical (and of
2697
- * equal length) in the generated and the original file. The merged span is
2698
- * Verbatim by construction: every position inside it maps with the same
2699
- * offset and the same text.
2700
- * @param {Candidate[]} spans
2701
- * @param {string} generated_text
2702
- * @param {string} original_text
2703
- * @returns {Candidate[]}
2704
- */
2705
- function coalesce_verbatim_spans(spans, generated_text, original_text) {
2706
- /** @type {Candidate[]} */
2707
- const merged = [];
2708
- for (const span of spans) {
2709
- const previous = merged[merged.length - 1];
2710
- if (previous && previous.kind === SpanMapKind.Verbatim && span.kind === SpanMapKind.Verbatim && previous.features === span.features && span.originalStart >= previous.originalEnd && span.generatedStart - previous.generatedEnd === span.originalStart - previous.originalEnd && generated_text.slice(previous.generatedEnd, span.generatedStart) === original_text.slice(previous.originalEnd, span.originalStart)) {
2711
- previous.generatedEnd = span.generatedEnd;
2712
- previous.originalEnd = span.originalEnd;
2713
- continue;
2714
- }
2715
- merged.push({ ...span });
2716
- }
2717
- return merged;
2718
- }
2719
- /**
2720
- * Extend every Verbatim span forward over whitespace that is identical in the
2721
- * generated and the original file, up to the next span in either file.
2722
- *
2723
- * TypeScript's edits routinely end at the start of the line after a statement
2724
- * (an organize-imports edit for the import block ends after the last import's
2725
- * newline), and TypeScript 7 discards a whole edit when any of its ranges does
2726
- * not map. A span that stops at a statement's last character therefore made
2727
- * "Organize Imports" a no-op on `.tsrx` files; covering the newline that follows
2728
- * fixes that at no cost, since identical whitespace maps verbatim.
2729
- * @param {Candidate[]} spans Sorted by generated start, non-overlapping.
2730
- * @param {string} generated_text
2731
- * @param {string} original_text
2732
- * @returns {Candidate[]}
2733
- */
2734
- function extend_verbatim_spans_over_whitespace(spans, generated_text, original_text) {
2735
- for (let index = 0; index < spans.length; index++) {
2736
- const span = spans[index];
2737
- if (span.kind !== SpanMapKind.Verbatim) continue;
2738
- const next = spans[index + 1];
2739
- const generated_limit = next ? next.generatedStart : generated_text.length;
2740
- const original_limit = next ? next.originalStart : original_text.length;
2741
- while (span.generatedEnd < generated_limit && span.originalEnd < original_limit && generated_text[span.generatedEnd] === original_text[span.originalEnd] && /[ \t\r\n]/.test(generated_text[span.generatedEnd])) {
2742
- span.generatedEnd++;
2743
- span.originalEnd++;
2744
- }
2745
- }
2746
- return spans;
2747
- }
2748
- const identifier_part = /[\p{ID_Continue}$\u200c\u200d]/u;
2749
- const token_part = /[\p{ID_Continue}$#@\u200c\u200d]/u;
2750
- /**
2751
- * Whether `[start, end)` is a complete identifier in `text`: identifier
2752
- * syntax inside and no identifier character touching either edge.
2753
- * @param {string} text
2754
- * @param {number} start
2755
- * @param {number} end
2756
- */
2757
- function is_whole_identifier(text, start, end) {
2758
- return identifier_pattern.test(text.slice(start, end)) && (start === 0 || !identifier_part.test(text[start - 1])) && (end === text.length || !identifier_part.test(text[end]));
2759
- }
2760
- /**
2761
- * Whether `[start, end)` is a piece of a longer identifier in `text`:
2762
- * identifier characters inside and an identifier character touching an edge.
2763
- * @param {string} text
2764
- * @param {number} start
2765
- * @param {number} end
2766
- */
2767
- function is_partial_identifier(text, start, end) {
2768
- const slice = text.slice(start, end);
2769
- return slice.length > 0 && [...slice].every((character) => identifier_part.test(character)) && (start > 0 && identifier_part.test(text[start - 1]) || end < text.length && identifier_part.test(text[end]));
2770
- }
2771
- /**
2772
- * Whether `[start, end)` is a complete authored token: no whitespace inside
2773
- * and no token character (identifier characters plus the TSRX `#`/`@`
2774
- * sigils) touching either edge.
2775
- * @param {string} text
2776
- * @param {number} start
2777
- * @param {number} end
2778
- */
2779
- function is_whole_token(text, start, end) {
2780
- const slice = text.slice(start, end);
2781
- return slice.length > 0 && !/\s/.test(slice) && (start === 0 || !token_part.test(text[start - 1])) && (end === text.length || !token_part.test(text[end]));
2782
- }
2783
- /**
2784
- * Sorted set of half-open intervals supporting an "add if disjoint" query.
2785
- * Intervals are kept sorted by start in a plain array; a binary search finds
2786
- * the neighbours to test, so adding is O(n) in the worst case, which is fine
2787
- * for the few thousand spans a file produces.
2788
- */
2789
- var IntervalSet = class {
2790
- /** @type {number[]} */
2791
- #starts = [];
2792
- /** @type {number[]} */
2793
- #ends = [];
2794
- /**
2795
- * @param {number} start
2796
- * @param {number} end
2797
- * @returns {boolean} Whether the interval was added (it overlapped nothing).
2798
- */
2799
- add(start, end) {
2800
- const starts = this.#starts;
2801
- let low = 0;
2802
- let high = starts.length;
2803
- while (low < high) {
2804
- const middle = low + high >>> 1;
2805
- if (starts[middle] < start) low = middle + 1;
2806
- else high = middle;
2807
- }
2808
- if (low < starts.length && starts[low] < end) return false;
2809
- if (low > 0 && this.#ends[low - 1] > start) return false;
2810
- starts.splice(low, 0, start);
2811
- this.#ends.splice(low, 0, end);
2812
- return true;
2813
- }
2814
- };
2815
-
2816
- //#endregion
2817
- //#region src/mapper.js
2818
- /** @import * as AST from 'estree' */
2819
- /** @import {CompileError} from '@tsrx/core/types' */
2820
- /** @import {InitializeParams, InitializeResult, OpenProjectParams, OpenProjectResult, TransformParams, TransformResult, MapperDiagnostic} from './protocol.js' */
2821
- const require$1 = createRequire(import.meta.url);
2822
- const bare_package_specifier_pattern = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/;
2823
- /**
2824
- * The mapper entry's `options` object in tsconfig (`contentMappers[].options`)
2825
- * or in an inferred-project contribution.
2826
- * @typedef {object} MapperOptions
2827
- * @property {string} [compiler] Bare package specifier of the TSRX compiler. Takes precedence over `tsrx.compiler` in the tsconfig chain.
2828
- * @property {'web' | 'ios' | 'android'} [platform] Platform for `import.meta.env.platform` flags. Takes precedence over `tsrx.platform`.
2829
- * @property {boolean} [languageFeatures] `false` clears every editor feature bit while keeping spans for diagnostics (CLI-only projects).
2830
- */
2831
- /**
2832
- * @typedef {object} ProjectState
2833
- * @property {string | undefined} configFileName
2834
- * @property {MapperOptions} options
2835
- * @property {Set<string>} dependencies Files whose content affects transform output.
2836
- * @property {Map<string, AST.Program>} lastGood Last successfully parsed source AST per file, for the compile-failure stub. Shared by every project state of a mapper (see {@link create_tsrx_content_mapper}).
2837
- */
2838
- /**
2839
- * @typedef {object} ContentMapper
2840
- * @property {(params: InitializeParams) => InitializeResult} initialize
2841
- * @property {(params: OpenProjectParams) => OpenProjectResult} openProject
2842
- * @property {(params: { projectHandle: string }) => void} closeProject
2843
- * @property {(params: TransformParams) => TransformResult} transform
2844
- */
2845
- /**
2846
- * Create the `.tsrx` content mapper. Each `projectHandle` owns its own state;
2847
- * nothing is shared between projects except the process-wide compiler
2848
- * resolution caches, which are keyed by directory and reset on every
2849
- * `openProject`, and the last successfully parsed AST per file. The latter is
2850
- * keyed by file name and independent of the project, and TypeScript reopens a
2851
- * project (same or new handle) whenever its identity or a watched file
2852
- * changes, so keeping it at the mapper level is what lets a file that still
2853
- * fails to compile keep its export stub across a reopen.
2854
- * The mapper needs no TypeScript of its own: tsconfig files are read and
2855
- * compilers resolved through `@tsrx/typescript-plugin`'s own reader and
2856
- * package walk, so the native compiler's `typescript` package (which has no
2857
- * JavaScript API) can be the only TypeScript in a project.
2858
- * @param {{ host?: import('@tsrx/typescript-plugin/src/config-host.js').ConfigHost }} [context]
2859
- * @returns {ContentMapper}
2860
- */
2861
- function create_tsrx_content_mapper(context = {}) {
2862
- const host = context.host ?? NODE_CONFIG_HOST;
2863
- /** @type {Map<string, ProjectState>} */
2864
- const projects = /* @__PURE__ */ new Map();
2865
- /** @type {Map<string, AST.Program>} */
2866
- const last_good = /* @__PURE__ */ new Map();
2867
- /** Transforms that arrive without a project handle. */
2868
- const standalone = create_project_state(void 0, {});
2869
- /** @type {ContentMapper['initialize']} */
2870
- function initialize(params) {
2871
- if (!params.positionEncodings?.includes("utf-16")) throw new Error("@tsrx/content-mapper requires UTF-16 position encoding");
2872
- return {
2873
- positionEncoding: "utf-16",
2874
- diagnosticSource: DIAGNOSTIC_SOURCE
2875
- };
2876
- }
2877
- /** @type {ContentMapper['openProject']} */
2878
- function openProject(params) {
2879
- invalidateCompilerResolutionCaches();
2880
- const { options, optionDiagnostics } = validate_options(params.options);
2881
- const state = create_project_state(params.configFileName || void 0, options);
2882
- projects.set(params.projectHandle, state);
2883
- try {
2884
- resolve_compiler(state, probe_file_name(state));
2885
- } catch {}
2886
- const watchedFiles = [...state.dependencies].sort();
2887
- return {
2888
- configIdentity: compute_identity(state, watchedFiles),
2889
- watchedFiles,
2890
- ...optionDiagnostics.length > 0 ? { optionDiagnostics } : null
2891
- };
2892
- }
2893
- /** @type {ContentMapper['closeProject']} */
2894
- function closeProject(params) {
2895
- projects.delete(params.projectHandle);
2896
- }
2897
- /** @type {ContentMapper['transform']} */
2898
- function transform(params) {
2899
- const state = params.projectHandle ? projects.get(params.projectHandle) : standalone;
2900
- if (!state) throw new Error(`Unknown @tsrx/content-mapper project handle: ${params.projectHandle}`);
2901
- const file_name = params.fileName.replace(/\\/g, "/");
2902
- const content = params.content;
2903
- /** @type {import('@tsrx/typescript-plugin/src/transform.js').TSRXCompilerModule | null} */
2904
- let compiler;
2905
- try {
2906
- compiler = resolve_compiler(state, file_name);
2907
- } catch (error) {
2908
- return failure(state, file_name, content, {
2909
- start: 0,
2910
- length: 0,
2911
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
2912
- messageText: error_message(error)
2913
- });
2914
- }
2915
- if (!compiler) return failure(state, file_name, content, {
2916
- start: 0,
2917
- length: 0,
2918
- code: DIAGNOSTIC_CODE_NO_COMPILER,
2919
- messageText: `No TSRX compiler found for ${file_name}. Install a target compiler (for example @tsrx/react) next to the project, or select one with "tsrx": { "compiler": "<package>" } in tsconfig.json or "options": { "compiler": "<package>" } on the content mapper entry.`
2920
- });
2921
- /** @type {'web' | 'ios' | 'android' | undefined} */
2922
- let platform;
2923
- try {
2924
- platform = state.options.platform ?? resolve_consumer_platform_for_file(file_name, {
2925
- configFileName: state.configFileName,
2926
- configHost: host,
2927
- dependencies: state.dependencies,
2928
- requirePlatformResolution: source_uses_platform_flag(content)
2929
- });
2930
- } catch (error) {
2931
- return failure(state, file_name, content, {
2932
- start: 0,
2933
- length: 0,
2934
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
2935
- messageText: error_message(error)
2936
- });
2937
- }
2938
- const result = transform_tsrx(compiler, file_name, content, { platform });
2939
- if (result.fatalError) return failure(state, file_name, content, to_diagnostic(result.fatalError, content.length, DIAGNOSTIC_CODE_COMPILE_ERROR));
2940
- if (result.sourceAst) state.lastGood.set(file_name, result.sourceAst);
2941
- const language_features = state.options.languageFeatures !== false;
2942
- const mappings = to_span_mappings(result.mappings, result.text, content, { languageFeatures: language_features });
2943
- const diagnostics = result.errors.map((error) => to_diagnostic(error, content.length, DIAGNOSTIC_CODE_USAGE_ERROR));
2944
- return {
2945
- text: result.text,
2946
- extension: ".tsx",
2947
- mappings,
2948
- ...diagnostics.length > 0 ? { diagnostics } : null
2949
- };
2950
- }
2951
- /**
2952
- * @param {string | undefined} config_file_name
2953
- * @param {MapperOptions} options
2954
- * @returns {ProjectState}
2955
- */
2956
- function create_project_state(config_file_name, options) {
2957
- return {
2958
- configFileName: config_file_name ? path.normalize(config_file_name) : void 0,
2959
- options,
2960
- dependencies: /* @__PURE__ */ new Set(),
2961
- lastGood: last_good
2962
- };
2963
- }
2964
- /**
2965
- * A `.tsrx` path inside the project directory, used to drive compiler
2966
- * resolution before any real file is transformed.
2967
- * @param {ProjectState} state
2968
- */
2969
- function probe_file_name(state) {
2970
- const dir = state.configFileName ? path.dirname(state.configFileName) : process.cwd();
2971
- return path.join(dir, "__tsrx_content_mapper_probe__.tsrx").replace(/\\/g, "/");
2972
- }
2973
- /**
2974
- * Precedence: the mapper entry's `options.compiler` wins over `tsrx.compiler`
2975
- * in the tsconfig chain, which wins over auto-detection of an installed
2976
- * target compiler. Whatever is found, its `package.json` joins the watched
2977
- * files so a compiler upgrade invalidates the project.
2978
- * @param {ProjectState} state
2979
- * @param {string} file_name
2980
- * @returns {import('@tsrx/typescript-plugin/src/transform.js').TSRXCompilerModule | null}
2981
- */
2982
- function resolve_compiler(state, file_name) {
2983
- /** @type {string | undefined} */
2984
- let entry;
2985
- if (state.options.compiler !== void 0) entry = resolve_declared_compiler(state, file_name, state.options.compiler);
2986
- else entry = get_compiler_entry_for_file(file_name, {
2987
- configFileName: state.configFileName,
2988
- configHost: host,
2989
- dependencies: state.dependencies
2990
- });
2991
- if (!entry) return null;
2992
- const manifest = nearest_package_manifest(entry);
2993
- if (manifest) state.dependencies.add(manifest);
2994
- return require_tsrx_compiler(entry);
2995
- }
2996
- /**
2997
- * @param {ProjectState} state
2998
- * @param {string} file_name
2999
- * @param {string} specifier
3000
- * @returns {string}
3001
- */
3002
- function resolve_declared_compiler(state, file_name, specifier) {
3003
- if (!bare_package_specifier_pattern.test(specifier)) throw new Error(`The content mapper option "compiler" must be a bare package specifier, got ${JSON.stringify(specifier)}.`);
3004
- const anchor = state.configFileName ?? file_name;
3005
- try {
3006
- return createRequire(anchor).resolve(specifier);
3007
- } catch {
3008
- const resolved = resolve_package_entry(specifier, path.dirname(anchor), { host });
3009
- if (!resolved) throw new Error(`Unable to resolve the TSRX compiler ${JSON.stringify(specifier)} declared in the content mapper options from ${anchor}.`);
3010
- return resolved;
3011
- }
3012
- }
3013
- /**
3014
- * @param {ProjectState} state
3015
- * @param {string[]} watched_files
3016
- * @returns {string}
3017
- */
3018
- function compute_identity(state, watched_files) {
3019
- const hash = createHash("sha256");
3020
- hash.update(JSON.stringify(state.options));
3021
- hash.update("\0");
3022
- for (const file of watched_files) {
3023
- hash.update(file);
3024
- hash.update("\0");
3025
- hash.update(host.readFile(file) ?? "");
3026
- hash.update("\0");
3027
- }
3028
- return hash.digest("hex");
3029
- }
3030
- /**
3031
- * @param {ProjectState} state
3032
- * @param {string} file_name
3033
- * @param {string} content
3034
- * @param {MapperDiagnostic} diagnostic
3035
- * @returns {TransformResult}
3036
- */
3037
- function failure(state, file_name, content, diagnostic) {
3038
- return {
3039
- text: build_export_stub(state.lastGood.get(file_name)),
3040
- extension: ".ts",
3041
- mappings: [],
3042
- diagnostics: [clamp_diagnostic(diagnostic, content.length)]
3043
- };
3044
- }
3045
- return {
3046
- initialize,
3047
- openProject,
3048
- closeProject,
3049
- transform
3050
- };
3051
- }
3052
- /**
3053
- * @param {unknown} raw
3054
- * @returns {{ options: MapperOptions, optionDiagnostics: NonNullable<OpenProjectResult['optionDiagnostics']> }}
3055
- */
3056
- function validate_options(raw) {
3057
- /** @type {MapperOptions} */
3058
- const options = {};
3059
- /** @type {NonNullable<OpenProjectResult['optionDiagnostics']>} */
3060
- const optionDiagnostics = [];
3061
- if (raw === void 0 || raw === null) return {
3062
- options,
3063
- optionDiagnostics
3064
- };
3065
- if (typeof raw !== "object" || Array.isArray(raw)) {
3066
- optionDiagnostics.push({
3067
- path: [],
3068
- messageText: "Content mapper options must be an object.",
3069
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3070
- });
3071
- return {
3072
- options,
3073
- optionDiagnostics
3074
- };
3075
- }
3076
- const record = raw;
3077
- for (const key of Object.keys(record)) {
3078
- const value = record[key];
3079
- switch (key) {
3080
- case "compiler":
3081
- if (typeof value === "string" && bare_package_specifier_pattern.test(value.trim())) options.compiler = value.trim();
3082
- else optionDiagnostics.push({
3083
- path: [key],
3084
- messageText: "\"compiler\" must be a bare package specifier such as \"@tsrx/react\".",
3085
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3086
- });
3087
- break;
3088
- case "platform":
3089
- if (value === "web" || value === "ios" || value === "android") options.platform = value;
3090
- else optionDiagnostics.push({
3091
- path: [key],
3092
- messageText: "\"platform\" must be \"web\", \"ios\", or \"android\".",
3093
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3094
- });
3095
- break;
3096
- case "languageFeatures":
3097
- if (typeof value === "boolean") options.languageFeatures = value;
3098
- else optionDiagnostics.push({
3099
- path: [key],
3100
- messageText: "\"languageFeatures\" must be a boolean.",
3101
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3102
- });
3103
- break;
3104
- default: optionDiagnostics.push({
3105
- path: [key],
3106
- messageText: `Unknown content mapper option "${key}".`,
3107
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3108
- });
3109
- }
3110
- }
3111
- return {
3112
- options,
3113
- optionDiagnostics
3114
- };
3115
- }
3116
- /**
3117
- * Translate a compiler `CompileError` into a mapper diagnostic in original
3118
- * offsets. Coded errors keep their string code in the message and derive a
3119
- * stable numeric code from it; uncoded ones use `fallback_code`.
3120
- * @param {CompileError} error
3121
- * @param {number} content_length
3122
- * @param {number} fallback_code
3123
- * @returns {MapperDiagnostic}
3124
- */
3125
- function to_diagnostic(error, content_length, fallback_code) {
3126
- const start = typeof error.pos === "number" ? error.pos : 0;
3127
- const end = typeof error.end === "number" && error.end > start ? error.end : start + 1;
3128
- const code = typeof error.code === "string" && error.code ? numeric_code(error.code) : fallback_code;
3129
- const message = String(error.message ?? error);
3130
- return clamp_diagnostic({
3131
- start,
3132
- length: end - start,
3133
- code,
3134
- messageText: typeof error.code === "string" && error.code ? `${message} [${error.code}]` : message
3135
- }, content_length);
3136
- }
3137
- /**
3138
- * Stable numeric code for a TSRX string diagnostic code (FNV-1a 32-bit,
3139
- * folded into the 10000..99999 range so it never collides with the fixed
3140
- * codes below 10000).
3141
- * @param {string} code
3142
- * @returns {number}
3143
- */
3144
- function numeric_code(code) {
3145
- let hash = 2166136261;
3146
- for (let index = 0; index < code.length; index++) {
3147
- hash ^= code.charCodeAt(index);
3148
- hash = Math.imul(hash, 16777619);
3149
- }
3150
- return 1e4 + (hash >>> 0) % 9e4;
3151
- }
3152
- /**
3153
- * @param {MapperDiagnostic} diagnostic
3154
- * @param {number} content_length
3155
- * @returns {MapperDiagnostic}
3156
- */
3157
- function clamp_diagnostic(diagnostic, content_length) {
3158
- const start = Math.max(0, Math.min(diagnostic.start, content_length));
3159
- const end = Math.max(start, Math.min(diagnostic.start + diagnostic.length, content_length));
3160
- return {
3161
- ...diagnostic,
3162
- start,
3163
- length: end - start
3164
- };
3165
- }
3166
- /**
3167
- * @param {unknown} error
3168
- * @returns {string}
3169
- */
3170
- function error_message(error) {
3171
- return error instanceof Error ? error.message : String(error);
3172
- }
3173
- /**
3174
- * The `package.json` that owns a compiler entry file, stopping at a
3175
- * `node_modules` boundary.
3176
- * @param {string} entry
3177
- * @returns {string | undefined}
3178
- */
3179
- function nearest_package_manifest(entry) {
3180
- let dir = path.dirname(entry);
3181
- while (dir) {
3182
- const candidate = path.join(dir, "package.json");
3183
- if (fs.existsSync(candidate)) return candidate;
3184
- if (path.basename(dir) === "node_modules") return void 0;
3185
- const parent = path.dirname(dir);
3186
- if (parent === dir) return void 0;
3187
- dir = parent;
3188
- }
3189
- }
3190
-
3191
- //#endregion
3192
- //#region src/rpc.js
3193
- /**
3194
- * Content-mapper transport: `Content-Length`-framed JSON-RPC 2.0 over stdio.
3195
- * TypeScript is the only requester; the mapper never sends requests or
3196
- * notifications. stdout is reserved for protocol messages, so everything
3197
- * else (including `console.log`) goes to stderr.
3198
- *
3199
- * Kept separate from the executable entry (`server.js`) so hosts that bundle
3200
- * the mapper (the VS Code extension ships it for inferred projects) can start
3201
- * it from their own entry file.
3202
- */
3203
- /**
3204
- * @typedef {{ jsonrpc: '2.0', id?: number | string | null, method: string, params?: unknown }} RequestMessage
3205
- */
3206
- /**
3207
- * Run the mapper server on the given streams. Installs the stream handlers
3208
- * and returns; the process exits (with `process.exitCode`) once the input
3209
- * stream ends, which is how TypeScript shuts a mapper down.
3210
- * @param {import('./mapper.js').ContentMapper} mapper
3211
- * @param {{ input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream }} [streams]
3212
- */
3213
- function run_mapper_server(mapper, streams = {}) {
3214
- const input = streams.input ?? process.stdin;
3215
- const output = streams.output ?? process.stdout;
3216
- let buffered = Buffer.alloc(0);
3217
- input.on("data", (chunk) => {
3218
- buffered = Buffer.concat([buffered, typeof chunk === "string" ? Buffer.from(chunk) : chunk]);
3219
- read_messages();
3220
- });
3221
- input.on("error", (error) => {
3222
- console.error(error);
3223
- process.exitCode = 1;
3224
- });
3225
- input.on("end", () => {
3226
- process.exit(process.exitCode ?? 0);
3227
- });
3228
- function read_messages() {
3229
- while (true) {
3230
- const header_end = buffered.indexOf("\r\n\r\n");
3231
- if (header_end < 0) return;
3232
- const header = buffered.subarray(0, header_end).toString("ascii");
3233
- const length_match = /^Content-Length:\s*(\d+)\s*$/im.exec(header);
3234
- if (!length_match) {
3235
- console.error("@tsrx/content-mapper: missing Content-Length header");
3236
- process.exit(1);
3237
- }
3238
- const content_length = Number(length_match[1]);
3239
- const message_start = header_end + 4;
3240
- const message_end = message_start + content_length;
3241
- if (buffered.length < message_end) return;
3242
- const body = buffered.subarray(message_start, message_end).toString("utf8");
3243
- buffered = buffered.subarray(message_end);
3244
- /** @type {RequestMessage} */
3245
- let message;
3246
- try {
3247
- message = JSON.parse(body);
3248
- } catch (error) {
3249
- console.error("@tsrx/content-mapper: invalid JSON-RPC message", error);
3250
- continue;
3251
- }
3252
- handle_message(message);
3253
- }
3254
- }
3255
- /** @param {RequestMessage} message */
3256
- function handle_message(message) {
3257
- if (message.id === void 0 || message.id === null) return;
3258
- try {
3259
- /** @type {unknown} */
3260
- let result;
3261
- switch (message.method) {
3262
- case "initialize":
3263
- result = mapper.initialize(message.params);
3264
- break;
3265
- case "openProject":
3266
- result = mapper.openProject(message.params);
3267
- break;
3268
- case "closeProject":
3269
- mapper.closeProject(message.params);
3270
- result = null;
3271
- break;
3272
- case "transform":
3273
- result = mapper.transform(message.params);
3274
- break;
3275
- default:
3276
- write({
3277
- jsonrpc: "2.0",
3278
- id: message.id,
3279
- error: {
3280
- code: -32601,
3281
- message: `Unknown method ${message.method}`
3282
- }
3283
- });
3284
- return;
3285
- }
3286
- write({
3287
- jsonrpc: "2.0",
3288
- id: message.id,
3289
- result
3290
- });
3291
- } catch (error) {
3292
- write({
3293
- jsonrpc: "2.0",
3294
- id: message.id,
3295
- error: {
3296
- code: -32603,
3297
- message: error instanceof Error ? error.stack ?? error.message : String(error)
3298
- }
3299
- });
3300
- }
3301
- }
3302
- /** @param {unknown} message */
3303
- function write(message) {
3304
- const body = Buffer.from(JSON.stringify(message), "utf8");
3305
- output.write(`Content-Length: ${body.length}\r\n\r\n`);
3306
- output.write(body);
3307
- }
3308
- }
3309
- /**
3310
- * Route every console method to stderr so stray logging (from a target
3311
- * compiler, for example) can never corrupt the protocol stream on stdout.
3312
- */
3313
- function redirect_console_to_stderr() {
3314
- console.log = console.info = console.warn = console.debug = (...args) => console.error(...args);
3315
- }
3316
-
3317
- //#endregion
3318
5
  //#region src/server.js
3319
6
  /**
3320
7
  * Executable entry of the content mapper: TypeScript spawns it through the