@tsrx/content-mapper 0.1.2 → 0.1.3

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.
@@ -2341,6 +2341,149 @@ function invalidateCompilerResolutionCaches() {
2341
2341
  //#endregion
2342
2342
  //#region ../tsrx/src/diagnostics.js
2343
2343
  /**
2344
+ * TSRX's own error codes, one per mistake only TSRX reports. The TSRX
2345
+ * specification lists each with its message and an example (its appendix,
2346
+ * "Error codes"). A mistake TypeScript also reports has TypeScript's code
2347
+ * instead (`TS1005`), from {@link TS_ERRORS}.
2348
+ *
2349
+ * - `TSRX1xxx`: markup syntax only TSRX has
2350
+ * - `TSRX2xxx`: template rules
2351
+ * - `TSRX3xxx`: `<style>` and CSS
2352
+ * - `TSRX4xxx`: everything else
2353
+ */
2354
+ const DIAGNOSTIC_CODES = {
2355
+ /** An element has no closing tag before the end of its template. */
2356
+ UNCLOSED_TAG: "TSRX1001",
2357
+ /** A closing tag doesn't match the element it closes. */
2358
+ MISMATCHED_CLOSING_TAG: "TSRX1002",
2359
+ /** A closing tag with no element open. */
2360
+ UNEXPECTED_CLOSING_TAG: "TSRX1003",
2361
+ /** A `<\/script` in a `<script>` body that isn't its closing tag, where HTML would end the script. */
2362
+ SCRIPT_END_TAG_IN_BODY: "TSRX1004",
2363
+ /** A namespaced element name (`<foo:bar>`). */
2364
+ NAMESPACED_ELEMENT: "TSRX1005",
2365
+ /** A spread as an attribute's value (`a={...b}`). */
2366
+ ATTRIBUTE_VALUE_SPREAD: "TSRX1006",
2367
+ /** A `;` at the end of an expression container (`{a;}`). */
2368
+ TEMPLATE_EXPRESSION_TRAILING_SEMICOLON: "TSRX1007",
2369
+ /** A directive without its `{ … }` body. */
2370
+ DIRECTIVE_BODY_EXPECTED: "TSRX1008",
2371
+ /** A directive's next branch written without its `@` (`else`, `empty`, `pending`, `catch`). */
2372
+ DIRECTIVE_BRANCH_EXPECTED: "TSRX1009",
2373
+ /** An `@try` with neither `@catch` nor `@pending`. */
2374
+ TRY_HANDLER_MISSING: "TSRX1010",
2375
+ /** An `@for`'s `index` or `key` clause is incomplete or out of order. */
2376
+ FOR_CLAUSE: "TSRX1011",
2377
+ /** A `return` in a template. */
2378
+ TEMPLATE_RETURN_STATEMENT: "TSRX2001",
2379
+ /** A `return` in an `@if` body. */
2380
+ IF_RETURN_STATEMENT: "TSRX2002",
2381
+ /** A `break` in an `@if` body. */
2382
+ IF_BREAK_STATEMENT: "TSRX2003",
2383
+ /** A `continue` in an `@if` body. */
2384
+ IF_CONTINUE_STATEMENT: "TSRX2004",
2385
+ /** A `return` in an `@for` body. */
2386
+ FOR_RETURN_STATEMENT: "TSRX2005",
2387
+ /** A `break` in an `@for` body. */
2388
+ FOR_BREAK_STATEMENT: "TSRX2006",
2389
+ /** A `continue` in an `@for` body. */
2390
+ FOR_CONTINUE_STATEMENT: "TSRX2007",
2391
+ /** A `break` in an `@case` body. */
2392
+ SWITCH_CASE_BREAK_STATEMENT: "TSRX2008",
2393
+ /** A `return` in an `@case` body. */
2394
+ SWITCH_CASE_RETURN_STATEMENT: "TSRX2009",
2395
+ /** Template output nothing renders: not returned, assigned, or part of the output. */
2396
+ FORGOTTEN_STATEMENT_CONTAINER: "TSRX2010",
2397
+ /** A `@{ … }` body with more than one output node. */
2398
+ CODE_BLOCK_SINGLE_OUTPUT: "TSRX2011",
2399
+ /** A statement after a `@{ … }` body's output. */
2400
+ CODE_BLOCK_STATEMENT_AFTER_OUTPUT: "TSRX2012",
2401
+ /** A JSX spread child (`{...items}`), which parses but no target supports. */
2402
+ JSX_SPREAD_CHILD: "TSRX2013",
2403
+ /** A dynamic tag expression (`<{expr}>`) other than an identifier, a member access, or a string literal. */
2404
+ DYNAMIC_TAG_EXPRESSION: "TSRX2014",
2405
+ /** An `@for` over something other than `for…of`. */
2406
+ FOR_OF_ONLY: "TSRX2015",
2407
+ /** An element with more than one `ref` attribute. */
2408
+ MULTIPLE_REFS: "TSRX2016",
2409
+ /** An element nested where HTML doesn't allow it (`<p>` in `<p>`). */
2410
+ INVALID_HTML_NESTING: "TSRX2017",
2411
+ /** A JavaScript `try…finally` in a template. */
2412
+ TEMPLATE_TRY_FINALLY: "TSRX2018",
2413
+ /** A `try` in a template with neither a `pending` nor a `catch` block. */
2414
+ TEMPLATE_TRY_HANDLER: "TSRX2019",
2415
+ /** An `@pending` block on a target without it. */
2416
+ TARGET_PENDING_UNSUPPORTED: "TSRX2020",
2417
+ /** An `await` where the target can't await (in a callback, or in its components). */
2418
+ TARGET_AWAIT_UNSUPPORTED: "TSRX2021",
2419
+ /** A `yield` in a part of the template that runs in a callback. */
2420
+ TARGET_YIELD_UNSUPPORTED: "TSRX2022",
2421
+ /** A `super` in a part of the template that's lowered into a generator function. */
2422
+ TARGET_SUPER_UNSUPPORTED: "TSRX2023",
2423
+ /** A `for await…of` in a template on a target without it. */
2424
+ TARGET_FOR_AWAIT_UNSUPPORTED: "TSRX2024",
2425
+ /** A top-level `await` in a TSRX function without a module-level `"use server"`. */
2426
+ TOP_LEVEL_AWAIT_USE_SERVER: "TSRX2025",
2427
+ /** An `@catch` reset parameter on a target whose error boundary has none. */
2428
+ TARGET_CATCH_RESET_UNSUPPORTED: "TSRX2026",
2429
+ /** An `@for` head that assigns to existing variables, or declares its loop variable with `var` or `using`. */
2430
+ FOR_HEAD: "TSRX2027",
2431
+ /** A component read above its declaration on a target that compiles it to a constant, where moving the declaration up would change what it reads. */
2432
+ TARGET_COMPONENT_READ_BEFORE_DECLARATION: "TSRX2028",
2433
+ /** A destructured prop default the target's component compiler drops. */
2434
+ TARGET_PROP_DEFAULT_UNSUPPORTED: "TSRX2029",
2435
+ /** A `var` declared in a nested `@{ … }` block or an `@if`, `@for`, `@switch` or `@try` body, outside any function or class in it. */
2436
+ DIRECTIVE_BODY_VAR: "TSRX2030",
2437
+ /** A destructured prop key the target's component compiler reads as another prop, or leaves out. */
2438
+ TARGET_PROP_KEY_UNSUPPORTED: "TSRX2031",
2439
+ /** A binding of a name the target's toolchain finds by name: Vue's `defineVaporComponent`. */
2440
+ TARGET_RESERVED_NAME: "TSRX2032",
2441
+ /** Type arguments after a dynamic tag (`<{Tag}<T> />`). */
2442
+ DYNAMIC_TAG_TYPE_ARGUMENTS: "TSRX2033",
2443
+ /** A `yield` in a template value the target's JSX compiler moves into an effect, getter or callback. */
2444
+ TARGET_TEMPLATE_YIELD_UNSUPPORTED: "TSRX2034",
2445
+ /**
2446
+ * A warning: a `@{ … }` with no output whose only statement is an
2447
+ * expression there only for its value, such as `<p>@{user.name}</p>`, so
2448
+ * it renders nothing.
2449
+ */
2450
+ CODE_BLOCK_EXPRESSION_ONLY: "TSRX2035",
2451
+ /** `<style apply>` carries no expression value. */
2452
+ STYLE_APPLY_VALUE: "TSRX3001",
2453
+ /** An `apply` entry is not an identifier, member, or array of those, or does not resolve to a style block. */
2454
+ STYLE_APPLY_TARGET: "TSRX3002",
2455
+ /** An `apply` target is declared after the applying block in source order. */
2456
+ STYLE_APPLY_BEFORE_DECLARATION: "TSRX3003",
2457
+ /** Two `apply` attributes on one `<style>` block. */
2458
+ STYLE_APPLY_DUPLICATE: "TSRX3004",
2459
+ /** `apply` on a `<head>` style or a resource (`href`) style. */
2460
+ STYLE_APPLY_UNSUPPORTED_HOST: "TSRX3005",
2461
+ /** An assigned style block authors a `.$class` class selector. */
2462
+ STYLE_RESERVED_CLASS_KEY: "TSRX3006",
2463
+ /** A standalone `<style>` block at module scope. */
2464
+ STYLE_STANDALONE_AT_MODULE_SCOPE: "TSRX3007",
2465
+ /** A standalone `<style>` block with CSS text outside any `@{ … }` or control-flow body. */
2466
+ STYLE_STANDALONE_OUTSIDE_TEMPLATE: "TSRX3008",
2467
+ /** A standalone `<style>` block in a statement slot: the lone output of a `@{ … }` or control-flow body, or a statement. */
2468
+ STYLE_STANDALONE_NEEDS_FRAGMENT: "TSRX3009",
2469
+ /** A `<style>` attribute other than `ref` and `apply`. */
2470
+ STYLE_UNKNOWN_ATTRIBUTE: "TSRX3010",
2471
+ /** `:global` used where the scoping rules do not allow it. */
2472
+ CSS_GLOBAL_PLACEMENT: "TSRX3011",
2473
+ /** An `@import` rule in a `<style>` block, whose rules would not be scoped. */
2474
+ CSS_IMPORT: "TSRX3012",
2475
+ /** CSS in a `<style>` block that doesn't parse. */
2476
+ CSS_SYNTAX: "TSRX3013",
2477
+ /** A `<style>` block in a child expression container (`{<style>…</style>}`), which renders its class map. */
2478
+ STYLE_IN_EXPRESSION_CONTAINER: "TSRX3014",
2479
+ /** A recognized `import.meta.env.platform.*` flag is used without a selected platform. */
2480
+ PLATFORM_REQUIRED: "TSRX4001",
2481
+ /** A name that starts with the prefix the compiler reserves for its own identifiers. */
2482
+ RESERVED_IDENTIFIER_PREFIX: "TSRX4002",
2483
+ /** JavaScript syntax the parser rejects that TypeScript accepts (an escaped `import.meta`). */
2484
+ JAVASCRIPT_SYNTAX: "TSRX4003"
2485
+ };
2486
+ /**
2344
2487
  * The source TSRX's errors are reported under, in capitals like TypeScript's
2345
2488
  * own `TS2322`: `@tsrx/content-mapper` declares it to TypeScript 7, which shows
2346
2489
  * its errors as `TSRX2002`, and the TSRX language server reports its compile
@@ -2412,10 +2555,13 @@ function ignore_directives(errors, source_ast, mappings, original_length, genera
2412
2555
  const ranges = [];
2413
2556
  for (const error of errors) {
2414
2557
  if (typeof error.pos !== "number") continue;
2415
- const holder = source_ast ? holder_at(source_ast, error.pos) : null;
2558
+ const on_tag = reported_on_tag(error);
2559
+ const position = on_tag ? error.raisedAt - 1 : error.pos;
2560
+ const holder = source_ast ? holder_at(source_ast, position) : null;
2416
2561
  const start = holder ? holder.start : error.pos;
2417
2562
  const end = holder ? holder.end : typeof error.end === "number" && error.end > error.pos ? error.end : error.pos + 1;
2418
- for (const generated of generated_ranges(mappings, start, end)) ranges.push([
2563
+ const own_code = on_tag && !holder;
2564
+ for (const generated of generated_ranges(mappings, start, end, own_code)) ranges.push([
2419
2565
  Math.min(start, original_length),
2420
2566
  Math.min(end, original_length),
2421
2567
  Math.min(generated[0], generated_length),
@@ -2446,6 +2592,23 @@ function ignore_directives(errors, source_ast, mappings, original_length, genera
2446
2592
  };
2447
2593
  }
2448
2594
  /**
2595
+ * Whether `error` is an unclosed tag reported on the tag and found where the
2596
+ * parser stopped, one before `raisedAt`: the end of its template, or the start
2597
+ * of a `<style>` or `<script>` body. Its directive holds there, not at the error:
2598
+ * the closing tag that recovery adds has no mapping, so TypeScript's error on it
2599
+ * could only show at the top of the file, and the tag's own statement can end
2600
+ * before it. At the end of the file nothing holds that place, as the tag's
2601
+ * declaration has stretched around the code that follows, which the directive
2602
+ * must not hide. A compiler from before tags were reported on themselves has its
2603
+ * error where the parser stopped already, with `raisedAt` no further than `end`,
2604
+ * and the mapper runs whichever compiler the project has.
2605
+ * @param {CompileError} error
2606
+ * @returns {boolean}
2607
+ */
2608
+ function reported_on_tag({ code, end, raisedAt }) {
2609
+ return code === DIAGNOSTIC_CODES.UNCLOSED_TAG && typeof raisedAt === "number" && typeof end === "number" && raisedAt > end;
2610
+ }
2611
+ /**
2449
2612
  * The innermost holder node (see {@link HOLDER_TYPE}) that contains `position`,
2450
2613
  * found by descending from the root through the child that contains it.
2451
2614
  * @param {AST.Node} root
@@ -2488,9 +2651,13 @@ function child_at(node, position) {
2488
2651
  * @param {readonly CodeMapping[]} mappings
2489
2652
  * @param {number} start
2490
2653
  * @param {number} end
2654
+ * @param {boolean} [own_code] Count only segments inside the range, and no
2655
+ * error's anchor. A segment that encloses the range doesn't count: a mapping of
2656
+ * the whole file can have the same length on both sides by chance. An anchor
2657
+ * still ends a range, as any code from outside the node does.
2491
2658
  * @returns {Array<[number, number]>}
2492
2659
  */
2493
- function generated_ranges(mappings, start, end) {
2660
+ function generated_ranges(mappings, start, end, own_code = false) {
2494
2661
  /** @type {Array<[generated_start: number, generated_end: number, inside: boolean]>} */
2495
2662
  const segments = [];
2496
2663
  for (const mapping of mappings) for (let i = 0; i < mapping.sourceOffsets.length; i++) {
@@ -2498,12 +2665,17 @@ function generated_ranges(mappings, start, end) {
2498
2665
  const length = mapping.lengths[i];
2499
2666
  const generated = mapping.generatedOffsets[i];
2500
2667
  const generated_length = mapping.generatedLengths?.[i] ?? length;
2501
- if (source >= start && source + length <= end) segments.push([
2668
+ if (own_code && mapping.data?.customData?.diagnosticAnchor) segments.push([
2669
+ generated,
2670
+ generated + generated_length,
2671
+ false
2672
+ ]);
2673
+ else if (source >= start && source + length <= end) segments.push([
2502
2674
  generated,
2503
2675
  generated + generated_length,
2504
2676
  true
2505
2677
  ]);
2506
- else if (source <= start && end <= source + length && generated_length === length) segments.push([
2678
+ else if (!own_code && source <= start && end <= source + length && generated_length === length) segments.push([
2507
2679
  generated + start - source,
2508
2680
  generated + end - source,
2509
2681
  true
@@ -2739,10 +2911,83 @@ function pattern_names(pattern) {
2739
2911
  }
2740
2912
  }
2741
2913
 
2914
+ //#endregion
2915
+ //#region src/platform-globals.js
2916
+ /** @import {CodeMapping} from '@tsrx/core/types' */
2917
+ /**
2918
+ * The editor-only `ImportMetaEnv` / `ImportMeta` globals that `withPlatformTypes`
2919
+ * in `@tsrx/core` appends to the generated TSX of a module that keeps a platform
2920
+ * flag, exactly as it prints them, with the three flag value types captured.
2921
+ */
2922
+ const PLATFORM_GLOBALS = /\ndeclare global \{\n\tinterface ImportMetaEnv \{\n\t\treadonly platform: string & \{\n\t\t\treadonly web: (true|false|boolean);\n\t\t\treadonly ios: (true|false|boolean);\n\t\t\treadonly android: (true|false|boolean);\n\t\t\};\n\t\}\n\tinterface ImportMeta \{\n\t\treadonly \[key: `env\$\{string\}`\]: ImportMetaEnv;\n\t\}\n\}\n/;
2923
+ /** The `platform-globals/` file that declares each set of flag value types. */
2924
+ const PLATFORM_FILES = /* @__PURE__ */ new Map([
2925
+ ["true,false,false", "web"],
2926
+ ["false,true,false", "ios"],
2927
+ ["false,false,true", "android"],
2928
+ ["boolean,boolean,boolean", "unconfigured"]
2929
+ ]);
2930
+ /** @type {Map<string, string | null>} */
2931
+ const files = /* @__PURE__ */ new Map();
2932
+ /**
2933
+ * Replace a module's copy of the platform globals in its generated TSX with a
2934
+ * reference to the shared file that declares the same globals. Native
2935
+ * TypeScript merges every module's copy into one `ImportMeta` and reports the
2936
+ * repeated index signature (TS2374), and declaration output keeps every
2937
+ * `declare global` block. The shared file is in the program once, and
2938
+ * declaration output drops a `/// <reference path>` directive.
2939
+ *
2940
+ * The copy is blanked in place, and the directive goes at the start of the
2941
+ * text, where TypeScript reads it, so every generated offset moves by its
2942
+ * length. A directive is not an import: organize imports and auto-import still
2943
+ * see only the module's own imports, and TypeScript 7 maps their edits only
2944
+ * when the last of them is the module's last import. Text without the exact
2945
+ * copy (another TSRX version, a third-party compiler), or that starts with a
2946
+ * hashbang, comes back unchanged.
2947
+ * @param {string} text
2948
+ * @param {readonly CodeMapping[]} mappings
2949
+ * @returns {{ text: string, mappings: readonly CodeMapping[] }}
2950
+ */
2951
+ function share_platform_globals(text, mappings) {
2952
+ const match = PLATFORM_GLOBALS.exec(text);
2953
+ const name = match && PLATFORM_FILES.get(match.slice(1).join(","));
2954
+ const file = name && !text.startsWith("#!") ? platform_globals_file(name) : null;
2955
+ if (!match || !file) return {
2956
+ text,
2957
+ mappings
2958
+ };
2959
+ const directive = `/// <reference path="${file}" />\n`;
2960
+ const end = match.index + match[0].length;
2961
+ return {
2962
+ text: `${directive}${text.slice(0, match.index)}${match[0].replace(/[^\n]/g, " ")}${text.slice(end)}`,
2963
+ mappings: mappings.map((mapping) => ({
2964
+ ...mapping,
2965
+ generatedOffsets: mapping.generatedOffsets.map((offset) => offset + directive.length)
2966
+ }))
2967
+ };
2968
+ }
2969
+ /**
2970
+ * The path of a `platform-globals/` file, with forward slashes. The directory
2971
+ * sits next to `src/` and `dist/`, so one relative URL serves both. A file
2972
+ * missing from the installed package, or a path a directive cannot quote,
2973
+ * leaves the copy in place.
2974
+ * @param {string} name
2975
+ * @returns {string | null}
2976
+ */
2977
+ function platform_globals_file(name) {
2978
+ let file = files.get(name);
2979
+ if (file === void 0) {
2980
+ const path = fileURLToPath(new URL(`../platform-globals/${name}.d.cts`, import.meta.url));
2981
+ file = fs.existsSync(path) && !/["\r\n]/.test(path) ? path.replace(/\\/g, "/") : null;
2982
+ files.set(name, file);
2983
+ }
2984
+ return file;
2985
+ }
2986
+
2742
2987
  //#endregion
2743
2988
  //#region src/span-mappings.js
2744
2989
  /** @import {CodeMapping} from '@tsrx/core/types' */
2745
- /** @import {SpanMapping} from './protocol.js' */
2990
+ /** @import {SpanMapping, VerificationMapping} from './protocol.js' */
2746
2991
  const semantic_features = SpanMapFeature.Hover | SpanMapFeature.SignatureHelp | SpanMapFeature.InlayHints | SpanMapFeature.SemanticTokens;
2747
2992
  const completion_features = SpanMapFeature.Completion | SpanMapFeature.AutoInsert;
2748
2993
  const navigation_features = SpanMapFeature.Definition | SpanMapFeature.TypeDefinition | SpanMapFeature.Implementation | SpanMapFeature.References | SpanMapFeature.DocumentHighlights | SpanMapFeature.Rename | SpanMapFeature.CallHierarchy | SpanMapFeature.CodeActions | SpanMapFeature.LinkedEditing;
@@ -2756,6 +3001,9 @@ const identifier_pattern = /^[\p{ID_Start}_$][\p{ID_Continue}$‌‍]*$/u;
2756
3001
  * @property {number} originalEnd
2757
3002
  * @property {0 | 1 | 2} kind
2758
3003
  * @property {number} features
3004
+ * @property {boolean} [positionOnly] From a mapping with no Volar feature, not even
3005
+ * `verification`: it only places diagnostics, so coalescing may join it to
3006
+ * its neighbours like an unmapped gap.
2759
3007
  */
2760
3008
  /**
2761
3009
  * Translate a Volar `CodeMapping['data']` into content-mapper feature bits.
@@ -2813,6 +3061,11 @@ function features_from_mapping_data(data) {
2813
3061
  * `import { a } from './x';` is one edit-safe span rather than four tokens
2814
3062
  * with unmapped punctuation between them. TypeScript only applies text edits
2815
3063
  * (auto-import, rename, code actions) that fit inside a single Verbatim span.
3064
+ * A dropped candidate then keeps its uncovered edges (see
3065
+ * {@link map_dropped_edges}), so a diagnostic over a whole container starts and
3066
+ * ends where the container does in the original. Last, identical text left
3067
+ * between spans with different feature bits maps without features (see
3068
+ * {@link map_identical_gaps}).
2816
3069
  * @param {readonly CodeMapping[]} mappings
2817
3070
  * @param {string} generated_text
2818
3071
  * @param {string} original_text
@@ -2848,20 +3101,21 @@ function to_span_mappings(mappings, generated_text, original_text, options = {})
2848
3101
  originalStart: original_start,
2849
3102
  originalEnd: original_end,
2850
3103
  kind,
2851
- features: language_features ? features_from_mapping_data(mapping.data) : SpanMapFeature.None
3104
+ features: language_features ? features_from_mapping_data(mapping.data) : SpanMapFeature.None,
3105
+ positionOnly: is_position_only(mapping.data)
2852
3106
  });
2853
3107
  }
2854
3108
  }
2855
3109
  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);
2856
3110
  /** @type {Candidate[]} */
2857
3111
  const selected = [];
3112
+ /** @type {Candidate[]} */
3113
+ const dropped = [];
2858
3114
  const occupied = new IntervalSet();
2859
- for (const candidate of candidates) {
2860
- if (!occupied.add(candidate.generatedStart, candidate.generatedEnd)) continue;
2861
- selected.push(candidate);
2862
- }
3115
+ for (const candidate of candidates) if (occupied.add(candidate.generatedStart, candidate.generatedEnd)) selected.push(candidate);
3116
+ else dropped.push(candidate);
2863
3117
  selected.sort((left, right) => left.generatedStart - right.generatedStart);
2864
- return extend_verbatim_spans_over_whitespace(coalesce_verbatim_spans(selected, generated_text, original_text), generated_text, original_text).map((candidate) => [
3118
+ return map_identical_gaps(map_dropped_edges(extend_verbatim_spans_over_whitespace(coalesce_verbatim_spans(selected, generated_text, original_text), generated_text, original_text), dropped, generated_text, original_text), generated_text, original_text).map((candidate) => [
2865
3119
  candidate.generatedStart,
2866
3120
  candidate.generatedEnd - candidate.generatedStart,
2867
3121
  candidate.originalStart,
@@ -2871,11 +3125,54 @@ function to_span_mappings(mappings, generated_text, original_text, options = {})
2871
3125
  ]);
2872
3126
  }
2873
3127
  /**
3128
+ * Whether a mapping has no Volar feature at all, not even `verification`. The
3129
+ * transform emits such mappings only to give TypeScript 7 a place for
3130
+ * diagnostics (the brackets of a respaced literal); Volar ignores them.
3131
+ * @param {CodeMapping['data'] | undefined} data
3132
+ * @returns {boolean}
3133
+ */
3134
+ function is_position_only(data) {
3135
+ return !!data && typeof data === "object" && !data.verification && !data.completion && !data.semantic && !data.navigation && !data.structure && !data.format;
3136
+ }
3137
+ /**
3138
+ * The transform's own mappings for diagnostics, for command-line checkers (the
3139
+ * `verificationMappings` mapper option): every mapping whose `data.verification`
3140
+ * is set, in the transform's order, with its offsets and lengths as emitted.
3141
+ * This is what `tsrx-tsc` hands Volar, so Volar's `SourceMap#toSourceRange`
3142
+ * (with `fallbackToAnyMatch`) over it maps a diagnostic exactly as `tsrx-tsc`
3143
+ * does. The grouping matters: Volar maps a range through one mapping that holds
3144
+ * both of its ends, such as the start and end points of a literal, and tries
3145
+ * mappings in this order, narrower first. When any mapping's verification is a
3146
+ * `shouldReport` callback, the result is empty: the callback depends on the
3147
+ * diagnostic and doesn't serialize, and leaving out only that mapping could
3148
+ * let an overlapping one map a diagnostic somewhere else.
3149
+ * @param {readonly CodeMapping[]} mappings
3150
+ * @returns {VerificationMapping[]}
3151
+ */
3152
+ function to_verification_mappings(mappings) {
3153
+ /** @type {VerificationMapping[]} */
3154
+ const result = [];
3155
+ for (const mapping of mappings) {
3156
+ const verification = mapping.data?.verification;
3157
+ if (!verification) continue;
3158
+ if (typeof verification === "object" && typeof verification.shouldReport === "function") return [];
3159
+ result.push({
3160
+ sourceOffsets: [...mapping.sourceOffsets],
3161
+ generatedOffsets: [...mapping.generatedOffsets],
3162
+ lengths: [...mapping.lengths],
3163
+ generatedLengths: [...mapping.generatedLengths ?? mapping.lengths],
3164
+ data: { verification: true }
3165
+ });
3166
+ }
3167
+ return result;
3168
+ }
3169
+ /**
2874
3170
  * Merge runs of Verbatim spans, sorted by generated start, when the two spans
2875
3171
  * carry the same feature bits and the text between them is identical (and of
2876
3172
  * equal length) in the generated and the original file. The merged span is
2877
3173
  * Verbatim by construction: every position inside it maps with the same
2878
- * offset and the same text.
3174
+ * offset and the same text. A position-only span joins a neighbour whatever
3175
+ * its features, and takes them, as the unmapped text it covers would.
2879
3176
  * @param {Candidate[]} spans
2880
3177
  * @param {string} generated_text
2881
3178
  * @param {string} original_text
@@ -2886,9 +3183,13 @@ function coalesce_verbatim_spans(spans, generated_text, original_text) {
2886
3183
  const merged = [];
2887
3184
  for (const span of spans) {
2888
3185
  const previous = merged[merged.length - 1];
2889
- 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)) {
3186
+ if (previous && previous.kind === SpanMapKind.Verbatim && span.kind === SpanMapKind.Verbatim && (previous.features === span.features || previous.positionOnly || span.positionOnly) && 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)) {
2890
3187
  previous.generatedEnd = span.generatedEnd;
2891
3188
  previous.originalEnd = span.originalEnd;
3189
+ if (previous.positionOnly && !span.positionOnly) {
3190
+ previous.features = span.features;
3191
+ previous.positionOnly = false;
3192
+ }
2892
3193
  continue;
2893
3194
  }
2894
3195
  merged.push({ ...span });
@@ -2924,6 +3225,219 @@ function extend_verbatim_spans_over_whitespace(spans, generated_text, original_t
2924
3225
  }
2925
3226
  return spans;
2926
3227
  }
3228
+ /**
3229
+ * Map the uncovered edges of each candidate that lost to the spans it
3230
+ * overlaps: the part before its first span and the part after its last.
3231
+ *
3232
+ * A container (a whole import type, a statement) encloses the token spans that
3233
+ * beat it, and TypeScript reports some diagnostics over the whole container.
3234
+ * When the printed text differs from the source (`import( './x' )` printed
3235
+ * as `import('./x')`), the container's start lies in unmapped text, and
3236
+ * TypeScript would report the diagnostic at the nearest earlier mapped
3237
+ * position instead. An edge runs from the container's boundary to the
3238
+ * neighbouring span, in both files, so it maps only when that span's original
3239
+ * range starts (or ends) inside the container's. Each edge is split by
3240
+ * {@link split_edge} so that a node inside it without a span of its own keeps
3241
+ * its position. Edges carry no feature bits: they place diagnostics and change
3242
+ * no editor feature. Gaps between a container's spans get no edge;
3243
+ * {@link map_identical_gaps} maps the ones whose text is identical.
3244
+ * Candidates are visited shortest first, so a nested container's edge bounds
3245
+ * the edge of the one around it.
3246
+ * @param {Candidate[]} spans Sorted by generated start, non-overlapping.
3247
+ * @param {readonly Candidate[]} dropped
3248
+ * @param {string} generated_text
3249
+ * @param {string} original_text
3250
+ * @returns {Candidate[]}
3251
+ */
3252
+ function map_dropped_edges(spans, dropped, generated_text, original_text) {
3253
+ const result = spans.slice();
3254
+ /**
3255
+ * @param {Candidate | null} edge
3256
+ * @param {boolean} trailing
3257
+ */
3258
+ const add = (edge, trailing) => {
3259
+ if (!edge) return;
3260
+ for (const span of split_edge(edge, generated_text, original_text, trailing)) {
3261
+ if (span.kind === SpanMapKind.Atom && is_partial_identifier(original_text, span.originalStart, span.originalEnd)) continue;
3262
+ result.splice(last_span_at_or_before(result, span.generatedStart) + 1, 0, span);
3263
+ }
3264
+ };
3265
+ for (const candidate of dropped) {
3266
+ add(leading_edge(result, candidate), false);
3267
+ add(trailing_edge(result, candidate), true);
3268
+ }
3269
+ return result;
3270
+ }
3271
+ /**
3272
+ * @param {readonly Candidate[]} spans
3273
+ * @param {Candidate} candidate
3274
+ * @returns {Candidate | null}
3275
+ */
3276
+ function leading_edge(spans, candidate) {
3277
+ const index = last_span_at_or_before(spans, candidate.generatedStart);
3278
+ if (index >= 0 && spans[index].generatedEnd > candidate.generatedStart) return null;
3279
+ const next = spans[index + 1];
3280
+ if (!next || next.generatedStart >= candidate.generatedEnd || next.originalStart <= candidate.originalStart || next.originalStart > candidate.originalEnd) return null;
3281
+ return edge(candidate.generatedStart, next.generatedStart, candidate.originalStart, next.originalStart, SpanMapKind.Atom);
3282
+ }
3283
+ /**
3284
+ * @param {readonly Candidate[]} spans
3285
+ * @param {Candidate} candidate
3286
+ * @returns {Candidate | null}
3287
+ */
3288
+ function trailing_edge(spans, candidate) {
3289
+ const previous = spans[last_span_at_or_before(spans, candidate.generatedEnd - 1)];
3290
+ if (!previous || previous.generatedEnd >= candidate.generatedEnd || previous.generatedEnd <= candidate.generatedStart || previous.originalEnd < candidate.originalStart || previous.originalEnd >= candidate.originalEnd) return null;
3291
+ return edge(previous.generatedEnd, candidate.generatedEnd, previous.originalEnd, candidate.originalEnd, SpanMapKind.Atom);
3292
+ }
3293
+ /**
3294
+ * Split an edge into `Verbatim` runs of the text it shares with the source,
3295
+ * matched from the container's boundary (the start of a leading edge, the end
3296
+ * of a trailing one) with whitespace that only one side has skipped, and one
3297
+ * `Atom` for whatever follows the first other difference. The printer mostly
3298
+ * changes spacing: in `Record< {}, 1 >`, printed `Record<{ }, 1>`, the `{` of
3299
+ * the `{}` that has no span of its own then maps to itself instead of to the
3300
+ * container's `<`. An edge whose boundary character differs stays one `Atom`,
3301
+ * and no run starts or ends inside an identifier.
3302
+ * @param {Candidate} whole
3303
+ * @param {string} generated_text
3304
+ * @param {string} original_text
3305
+ * @param {boolean} from_end
3306
+ * @returns {Candidate[]}
3307
+ */
3308
+ function split_edge(whole, generated_text, original_text, from_end) {
3309
+ const generated = generated_text.slice(whole.generatedStart, whole.generatedEnd);
3310
+ const original = original_text.slice(whole.originalStart, whole.originalEnd);
3311
+ /**
3312
+ * The character `index` steps from the boundary.
3313
+ * @param {string} text
3314
+ * @param {number} index
3315
+ */
3316
+ const at = (text, index) => text[from_end ? text.length - 1 - index : index];
3317
+ if (at(generated, 0) !== at(original, 0)) return [whole];
3318
+ /** Runs as `[generated step, original step, length]`, in steps from the boundary. */
3319
+ /** @type {Array<[number, number, number]>} */
3320
+ const runs = [];
3321
+ let i = 0;
3322
+ let j = 0;
3323
+ while (i < generated.length && j < original.length) {
3324
+ const g = at(generated, i);
3325
+ const o = at(original, j);
3326
+ if (g === o) {
3327
+ const run = runs.at(-1);
3328
+ if (run && run[0] + run[2] === i && run[1] + run[2] === j) run[2]++;
3329
+ else runs.push([
3330
+ i,
3331
+ j,
3332
+ 1
3333
+ ]);
3334
+ i++;
3335
+ j++;
3336
+ } else if (/\s/.test(g)) i++;
3337
+ else if (/\s/.test(o)) j++;
3338
+ else break;
3339
+ }
3340
+ /** @param {string} text @param {number} index */
3341
+ const splits = (text, index) => identifier_part.test(at(text, index - 1) ?? "") && identifier_part.test(at(text, index) ?? "");
3342
+ /** @type {Array<[number, number, number]>} */
3343
+ const kept = [];
3344
+ for (const [g, o, length] of runs) {
3345
+ if (splits(generated, g) || splits(original, o)) break;
3346
+ let end = length;
3347
+ while (end > 0 && (splits(generated, g + end) || splits(original, o + end))) end--;
3348
+ if (end > 0) kept.push([
3349
+ g,
3350
+ o,
3351
+ end
3352
+ ]);
3353
+ if (end < length) break;
3354
+ }
3355
+ const last = kept.at(-1);
3356
+ if (!last) return [whole];
3357
+ i = last[0] + last[2];
3358
+ j = last[1] + last[2];
3359
+ /** @type {Candidate[]} */
3360
+ const spans = kept.map(([g, o, length]) => from_end ? edge_span(whole.generatedEnd - g - length, whole.originalEnd - o - length, length) : edge_span(whole.generatedStart + g, whole.originalStart + o, length));
3361
+ if (i < generated.length && j < original.length) spans.push(from_end ? edge(whole.generatedStart, whole.generatedEnd - i, whole.originalStart, whole.originalEnd - j, SpanMapKind.Atom) : edge(whole.generatedStart + i, whole.generatedEnd, whole.originalStart + j, whole.originalEnd, SpanMapKind.Atom));
3362
+ return spans;
3363
+ }
3364
+ /**
3365
+ * @param {number} generated_start
3366
+ * @param {number} original_start
3367
+ * @param {number} length
3368
+ * @returns {Candidate}
3369
+ */
3370
+ function edge_span(generated_start, original_start, length) {
3371
+ return edge(generated_start, generated_start + length, original_start, original_start + length, SpanMapKind.Verbatim);
3372
+ }
3373
+ /**
3374
+ * @param {number} generated_start
3375
+ * @param {number} generated_end
3376
+ * @param {number} original_start
3377
+ * @param {number} original_end
3378
+ * @param {0 | 1 | 2} kind
3379
+ * @returns {Candidate}
3380
+ */
3381
+ function edge(generated_start, generated_end, original_start, original_end, kind) {
3382
+ return {
3383
+ generatedStart: generated_start,
3384
+ generatedEnd: generated_end,
3385
+ originalStart: original_start,
3386
+ originalEnd: original_end,
3387
+ kind,
3388
+ features: SpanMapFeature.None
3389
+ };
3390
+ }
3391
+ /**
3392
+ * The index of the last span that starts at or before `position`, or -1.
3393
+ * @param {readonly Candidate[]} spans Sorted by generated start.
3394
+ * @param {number} position
3395
+ */
3396
+ function last_span_at_or_before(spans, position) {
3397
+ let low = 0;
3398
+ let high = spans.length;
3399
+ while (low < high) {
3400
+ const middle = low + high >>> 1;
3401
+ if (spans[middle].generatedStart <= position) low = middle + 1;
3402
+ else high = middle;
3403
+ }
3404
+ return low - 1;
3405
+ }
3406
+ /**
3407
+ * Give the text that follows a Verbatim span, and is identical in the generated
3408
+ * and the original file up to the next span in either file, a Verbatim span of
3409
+ * its own with no feature bits. TypeScript 7 offers no auto-import completion at
3410
+ * the end of a span that unmapped text separates from the next span, such as at
3411
+ * `helperB` in `{helperB()}<Button />`: the `<` of a tag maps with other features
3412
+ * than `helperB`, so `()}` joins neither span (#1028). The text keeps no features
3413
+ * of its neighbours, as when it was unmapped.
3414
+ * @param {Candidate[]} spans Sorted by generated start, non-overlapping.
3415
+ * @param {string} generated_text
3416
+ * @param {string} original_text
3417
+ * @returns {Candidate[]}
3418
+ */
3419
+ function map_identical_gaps(spans, generated_text, original_text) {
3420
+ /** @type {Candidate[]} */
3421
+ const result = [];
3422
+ for (let index = 0; index < spans.length; index++) {
3423
+ const span = spans[index];
3424
+ result.push(span);
3425
+ const next = spans[index + 1];
3426
+ if (span.kind !== SpanMapKind.Verbatim || !next) continue;
3427
+ let length = 0;
3428
+ while (span.generatedEnd + length < next.generatedStart && span.originalEnd + length < next.originalStart && generated_text[span.generatedEnd + length] === original_text[span.originalEnd + length]) length++;
3429
+ if (length === 0) continue;
3430
+ result.push({
3431
+ generatedStart: span.generatedEnd,
3432
+ generatedEnd: span.generatedEnd + length,
3433
+ originalStart: span.originalEnd,
3434
+ originalEnd: span.originalEnd + length,
3435
+ kind: SpanMapKind.Verbatim,
3436
+ features: SpanMapFeature.None
3437
+ });
3438
+ }
3439
+ return result;
3440
+ }
2927
3441
  const identifier_part = /[\p{ID_Continue}$\u200c\u200d]/u;
2928
3442
  const token_part = /[\p{ID_Continue}$#@\u200c\u200d]/u;
2929
3443
  /**
@@ -3006,6 +3520,7 @@ const bare_package_specifier_pattern = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a
3006
3520
  * @property {string} [compiler] Bare package specifier of the TSRX compiler. Takes precedence over `tsrx.compiler` in the tsconfig chain.
3007
3521
  * @property {'web' | 'ios' | 'android'} [platform] Platform for `import.meta.env.platform` flags. Takes precedence over `tsrx.platform`.
3008
3522
  * @property {boolean} [languageFeatures] `false` clears every editor feature bit while keeping spans for diagnostics (CLI-only projects).
3523
+ * @property {boolean} [verificationMappings] `true` adds `verificationMappings` to each transform result: the transform's own diagnostics mappings, in Volar's shape and order, for command-line checkers. Off by default; TypeScript ignores the field.
3009
3524
  */
3010
3525
  /**
3011
3526
  * @typedef {object} ProjectState
@@ -3117,16 +3632,19 @@ function create_tsrx_content_mapper(context = {}) {
3117
3632
  const result = transform_tsrx(compiler, file_name, content, { platform });
3118
3633
  if (result.fatalError) return failure(state, file_name, content, to_diagnostic(result.fatalError, content.length, MAPPER_CODES.COMPILE_ERROR));
3119
3634
  if (result.sourceAst) state.lastGood.set(file_name, result.sourceAst);
3635
+ const generated = share_platform_globals(result.text, result.mappings);
3120
3636
  const language_features = state.options.languageFeatures !== false;
3121
- const mappings = to_span_mappings(result.mappings, result.text, content, { languageFeatures: language_features });
3122
- const diagnostics = result.errors.map((error) => to_diagnostic(error, content.length, MAPPER_CODES.USAGE_ERROR));
3123
- const diagnosticDirectives = ignore_directives(result.errors, result.sourceAst, result.mappings, content.length, result.text.length);
3637
+ const mappings = to_span_mappings(generated.mappings, generated.text, content, { languageFeatures: language_features });
3638
+ const errors = result.errors.filter((error) => error.severity !== "warning");
3639
+ const diagnostics = errors.map((error) => to_diagnostic(error, content.length, MAPPER_CODES.USAGE_ERROR));
3640
+ const diagnosticDirectives = ignore_directives(errors, result.sourceAst, generated.mappings, content.length, generated.text.length);
3124
3641
  return {
3125
- text: result.text,
3642
+ text: generated.text,
3126
3643
  extension: ".tsx",
3127
3644
  mappings,
3128
3645
  ...diagnostics.length > 0 ? { diagnostics } : null,
3129
- ...diagnosticDirectives ? { diagnosticDirectives } : null
3646
+ ...diagnosticDirectives ? { diagnosticDirectives } : null,
3647
+ ...state.options.verificationMappings ? { verificationMappings: to_verification_mappings(generated.mappings) } : null
3130
3648
  };
3131
3649
  }
3132
3650
  /**
@@ -3220,7 +3738,8 @@ function create_tsrx_content_mapper(context = {}) {
3220
3738
  text: build_export_stub(state.lastGood.get(file_name)),
3221
3739
  extension: ".ts",
3222
3740
  mappings: [],
3223
- diagnostics: [clamp_diagnostic(diagnostic, content.length)]
3741
+ diagnostics: [clamp_diagnostic(diagnostic, content.length)],
3742
+ ...state.options.verificationMappings ? { verificationMappings: [] } : null
3224
3743
  };
3225
3744
  }
3226
3745
  return {
@@ -3275,10 +3794,11 @@ function validate_options(raw) {
3275
3794
  });
3276
3795
  break;
3277
3796
  case "languageFeatures":
3278
- if (typeof value === "boolean") options.languageFeatures = value;
3797
+ case "verificationMappings":
3798
+ if (typeof value === "boolean") options[key] = value;
3279
3799
  else optionDiagnostics.push({
3280
3800
  path: [key],
3281
- messageText: "\"languageFeatures\" must be a boolean.",
3801
+ messageText: `"${key}" must be a boolean.`,
3282
3802
  code: MAPPER_CODES.INVALID_CONFIG
3283
3803
  });
3284
3804
  break;
@@ -3363,4 +3883,4 @@ function nearest_package_manifest(entry) {
3363
3883
 
3364
3884
  //#endregion
3365
3885
  export { validate_options as i, require$1 as n, to_diagnostic as r, create_tsrx_content_mapper as t };
3366
- //# sourceMappingURL=mapper-B4f--1ac.js.map
3886
+ //# sourceMappingURL=mapper-Gc2yuGNf.js.map