Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 | 66x 66x 66x 66x 66x 7507x 7507x 7507x 89296x 89100x 81604x 11x 66x 2218x 2218x 66x 45x 45x 66x 4445x 4445x 16653x 4261x 3187x 3174x 4445x 66x 66x 140x 140x 249x 249x 139x 2x 2x 2x 2x 137x 140x 137x 137x 19x 71x 19x 118x 115x 66x 119x 119x 119x 1212x 1212x 1041x 1039x 1015x 991x 111x 111x 111x 928x 6x 66x 66x 1261x 1261x 1262x 1262x 1261x 1261x 66x 2133x 2133x 2133x 107377x 107377x 105334x 105220x 105216x 105183x 100922x 96665x 96659x 1939x 1939x 1939x 66x 66x 103238x 254x 66x 2640x 2640x 2640x 2640x 2640x 2643x 2643x 2643x 2640x 2640x 127894x 127894x 125116x 124977x 124974x 124948x 119717x 114489x 124945x 124945x 2640x 2640x 66x 1184x 1184x 1127x 57x 57x 164x 164x 164x 164x 19x 19x 4x 4x 160x 57x 66x 646x 646x 649x 649x 649x 649x 649x 649x 649x 649x 626x 649x 649x 646x 646x 649x 646x 646x 66x 1212x 1212x 1212x 1212x 1212x 1212x 43263x 43263x 43263x 836x 836x 836x 836x 836x 42427x 303x 303x 303x 303x 42124x 29x 29x 29x 29x 29x 42095x 336x 336x 69x 69x 69x 69x 42026x 5090x 5090x 5090x 646x 646x 646x 646x 646x 646x 646x 646x 4444x 4444x 4444x 125x 125x 125x 125x 125x 125x 125x 125x 41255x 39576x 41255x 38387x 41255x 41255x 1212x 66x 66x 66x 14x 14x 14x 14x 191x 191x 184x 177x 16x 16x 16x 14x 66x 15x 15x 14x 14x 14x 14x 2x 2x 2x 14x 16x 11x 8x 14x 66x 66x 233x 233x 233x 4009x 4009x 3974x 3974x 3972x 3969x 3727x 3739x 3x 66x 3380x 3380x 3380x 25294x 25294x 25294x 25294x 25294x 25294x 25202x 25110x 22585x 671x 66x 286x 286x 286x 286x 286x 4783x 4783x 4742x 4742x 4739x 4735x 4667x 4599x 535x 535x 535x 4735x 286x 66x 3084x 3084x 3084x 3084x 2702x 2702x 66x 260x 260x 176x 176x 173x 173x 278x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 173x 66x 425x 425x 425x 425x 44951x 44951x 44124x 43833x 43827x 43817x 58x 58x 58x 43759x 42136x 43759x 40908x 43759x 367x 66x 66x 66x 425x 425x 58x 58x 58x 58x 58x 58x 56x 56x 56x 1081x 1081x 1075x 1075x 1074x 1073x 958x 1017x 56x 66x 425x 425x 56x 56x 56x 5x 51x 66x 415x 415x 415x 415x 415x 415x 415x 48399x 48399x 48399x 48399x 833x 833x 833x 833x 833x 47566x 306x 306x 306x 306x 47260x 11x 11x 11x 11x 11x 47249x 349x 349x 67x 67x 67x 67x 282x 19x 19x 19x 15x 15x 15x 15x 47167x 46x 46x 46x 46x 46x 46x 46x 46x 47121x 45261x 47121x 43968x 47121x 47121x 415x 66x 66x 66x 66x 66x 2565x 66x 66x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 3296x 3296x 2756x 2752x 2752x 2750x 2642x 7x 7x 61x 61x 54x 6x 6x 6x 86x 86x 86x 6x 6x 8x 6x 48x 7x 7x 7x 2635x 70x 70x 70x 70x 2565x 1798x 8714x 1798x 1798x 1798x 1796x 1517x 1509x 1508x 1508x 1508x 1424x 1424x 1424x 1424x 767x 767x 742x 742x 60x 60x 60x 60x 682x 598x 517x 434x 411x 598x 598x 1293x 1283x 66x 66x 66x 66x 1350x 1350x 1350x 132x 132x 131x 131x 128x 128x 128x 128x 218x 218x 218x 202x 202x 202x 106x 106x 106x 90x 66x 658x 658x 1362x 1362x 1362x 658x 2712x 2712x 2712x 1994x 1994x 1994x 1994x 658x 1362x 658x 658x 658x 1362x 1359x 1359x 1359x 9x 1350x 1350x 1362x 658x | // ---------------------------------------------------------------------------
// :setup script transform
//
// setup scripts are written like Svelte components:
//
// let firstName = null
// $: fullName = `${firstName} ${lastName}`
// fetchUser().then(user => { firstName = user.firstName })
//
// and are executed inside `with ($scope)` against the component's reactive
// store, so plain assignments (even from async callbacks) go through the
// proxy's set trap and re-render whatever depends on them. To make that work
// the source is lightly rewritten - no full JS parser, just a scanner that is
// string/comment-aware and only touches code at brace/paren depth 0:
// - `let/var/const x = ...` at the top level loses its keyword, becoming a
// scope assignment (the name is pre-declared on the store so the `with`
// lookup resolves it)
// - `$: x = expr` becomes `$__effect(() => { x = expr })`, re-running when a
// dependency read inside expr changes ($__effect is deliberately NOT a
// property of the scope, so `with` falls through to the function parameter)
// ---------------------------------------------------------------------------
type SetupTransform = { vars: string[]; code: string }
// a declaration whose target is an identifier (`let x`), an object pattern
// (`let { a }`, space optional) or an array pattern (`let [x]`)
const DECLARATION_START_RE = /(?:let|var|const)(?:\s+(?=[A-Za-z_$])|\s*(?=[{[]))/y
const REACTIVE_LABEL_RE = /\$:\s*/y
const IMPORT_CALL_RE = /import(?=\s*\()/y
const REACTIVE_ASSIGN_RE = /\$:\s*([A-Za-z_$][\w$]*)\s*=(?!=)/y
const skipString = (src: string, start: number): number => {
const quote = src[start]
let i = start + 1
while (i < src.length) {
if (src[i] === "\\") { i += 2; continue }
if (src[i] === quote) return i + 1
i++
}
return src.length
}
const skipLineComment = (src: string, start: number): number => {
const end = src.indexOf("\n", start)
return end === -1 ? src.length : end
}
const skipBlockComment = (src: string, start: number): number => {
const end = src.indexOf("*/", start + 2)
return end === -1 ? src.length : end + 2
}
// index of the next thing that isn't whitespace or a comment
const skipToToken = (src: string, start: number): number => {
let i = start
while (i < src.length) {
if (/\s/.test(src[i])) { i++; continue }
if (src[i] === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
if (src[i] === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
break
}
return i
}
// ---------------------------------------------------------------------------
// regex literals. The scanners walk the source counting bracket depth, and a
// regex walked as if it were code poisons that count: `split(/\//)` puts two
// slashes side by side (a line comment, as far as a scanner knows) and the
// `)` after them is skipped uncounted; `/[(]/` inflates the depth for good.
// So a `/` that opens a regex is consumed whole - and whether it opens one is
// the classic lexer call, made the way every tokenizer makes it: by what came
// before. Division needs a completed expression on its left; everywhere else
// a `/` can only be a regex.
// ---------------------------------------------------------------------------
// reserved words a regex can follow. Reserved only - `of` is not (`const of
// = 4; of / 2` is legal division), so `for (x of /re/)` stays unrescued
// rather than risking real code
const REGEX_AFTER_WORD = new Set([
"return", "typeof", "case", "in", "instanceof", "new", "delete", "void", "do", "else", "yield", "await",
])
// whether a `/` at `at` opens a regex literal rather than a division: looks
// backward past whitespace and block comments for the last meaningful thing.
// A completed expression - identifier, number, closing quote or bracket,
// postfix ++/-- - takes division; a reserved word or any other punctuator
// admits a regex. Only consulted for the rare `/` that is neither `//` nor
// `/*`, so the scanners pay nothing on the common path
const regexAllowed = (src: string, at: number): boolean => {
let i = at - 1
while (i >= 0) {
const ch = src[i]
if (/\s/.test(ch)) { i--; continue }
if (ch === "/" && src[i - 1] === "*") {
const open = src.lastIndexOf("/*", i - 2)
Iif (open === -1) return true // an unopened comment tail: malformed input
i = open - 1
continue
}
break
}
if (i < 0) return true // the start of the source starts an expression
const ch = src[i]
if (/[\w$]/.test(ch)) {
let start = i
while (start > 0 && /[\w$]/.test(src[start - 1])) start--
return REGEX_AFTER_WORD.has(src.slice(start, i + 1))
}
if ((ch === "+" || ch === "-") && src[i - 1] === ch) return false // postfix ++/--
return !")]}\"'`.".includes(ch)
}
// consumes a regex literal (with its flags): backslash escapes, and character
// classes, where an unescaped `/` doesn't close the literal (`/[/]/` is one
// regex). A literal can't contain an unescaped newline, so hitting one means
// the classification was wrong or the input malformed - stop there, bounding
// any damage to a single line
const skipRegex = (src: string, start: number): number => {
let i = start + 1
let inClass = false
while (i < src.length) {
const ch = src[i]
if (ch === "\\") { i += 2; continue }
if (ch === "\n") return i
if (ch === "[") inClass = true
else if (ch === "]") inClass = false
else if (ch === "/" && !inClass) {
i++
while (i < src.length && /[a-z]/i.test(src[i])) i++ // flags
return i
}
i++
}
return src.length
}
// tokens that can't *start* a statement, so a line beginning with one is
// continuing the previous expression rather than opening a new statement -
// the same call JS's automatic semicolon insertion makes. Unary-only forms
// (!, ~, ++, --) are deliberately absent: those do start a statement, and JS
// inserts the semicolon before them
const CONTINUATION_RE = /^(\?\.|\?\?|&&|\|\||\*\*|[.,+\-*/%&|^<>=?:([])/
// the last meaningful character before `at`: walks back past whitespace and
// block comments, the way regexAllowed does. A line comment can't be skipped
// from behind (its start is only findable forwards), so a line ending in one
// reports the comment's text instead - callers treat that as "not the char I
// was looking for", which degrades to ending the statement, exactly as
// before this helper existed
const lastMeaningfulBefore = (src: string, at: number): string => {
let i = at - 1
while (i >= 0) {
const ch = src[i]
if (/\s/.test(ch)) { i--; continue }
Iif (ch === "/" && src[i - 1] === "*") {
const open = src.lastIndexOf("/*", i - 2)
if (open === -1) return ""
i = open - 1
continue
}
return ch
}
return ""
}
// end of a statement starting at `start`: the first `;` or line break that
// isn't inside a string/comment or unbalanced brackets. A line break only
// ends the statement if the next line can't continue it, so leading-dot
// method chains and multi-line operator chains stay in one piece:
//
// $: total = items
// .filter(item => item.active) <- still the same statement
// .length
//
// ...and only if the current line *can* end it: a line whose last meaningful
// character is `,` or `=` left its expression incomplete (a multi-line
// declarator list writes exactly this), so the statement continues - the
// same ASI call as the leading-token check, made from the other side
const findStatementEnd = (src: string, start: number): number => {
let depth = 0
let i = start
while (i < src.length) {
const ch = src[i]
if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); continue }
if (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch)) depth--
else if (depth <= 0 && ch === ";") return i
else if (depth <= 0 && ch === "\n") {
const next = skipToToken(src, i + 1)
const continues =
next < src.length &&
(CONTINUATION_RE.test(src.slice(next, next + 2)) || [",", "="].includes(lastMeaningfulBefore(src, i)))
if (!continues) return i
i = next
continue
}
i++
}
return src.length
}
// ---------------------------------------------------------------------------
// top-level declarations. `let x = 1` loses its keyword and becomes a scope
// assignment (x pre-declared on the store). A destructuring declarator
// becomes an *assignment pattern*: inside `with`, `({ a, b } = obj)` writes
// every binding through the reactive proxy - which is what makes it reactive.
// The parens keep the `{` from opening a block, and a leading `;` keeps the
// `(` from gluing onto the previous line as a call. Multi-declarator
// statements (`let a = 1, b = 2`) register every binding, not just the first.
// These lean on the pattern helpers defined with the props signature below
// (splitTopLevel, indexOfTopLevel, defaultAssignIndex); the scanner only
// runs long after the module evaluates, so the order is cosmetic
// ---------------------------------------------------------------------------
type Declarator = { raw: string; codeEnd: number }
// splits a declarator list at top-level commas, keeping each segment's raw
// text (layout and comments included) and where its last meaningful token
// ends - the spot a closing paren must go, so a trailing comment can't
// swallow it
const splitDeclarators = (src: string): Declarator[] => {
const parts: Declarator[] = []
let depth = 0
let start = 0
let lastEnd = 0
const flush = (end: number) => {
parts.push({ raw: src.slice(start, end), codeEnd: Math.max(0, lastEnd - start) })
start = end + 1
lastEnd = start
}
let i = 0
while (i < src.length) {
const ch = src[i]
if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); lastEnd = i; continue }
if (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); lastEnd = i; continue }
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch)) depth--
else if (ch === "," && depth <= 0) { flush(i); i++; continue }
if (!/\s/.test(ch)) lastEnd = i + 1
i++
}
flush(src.length)
return parts
}
// the *binding* names a destructuring pattern declares - unlike
// parsePropsPattern, which answers "which props" (the keys), this answers
// "which variables": `{ a: x }` binds x, `{ a: { b } }` binds b,
// `[x, ...rest]` binds x and rest. Defaults are stripped; what remains is a
// nested pattern (recurse) or the bound identifier
const patternBindings = (src: string): string[] => {
const pattern = src.trim()
if (!pattern.startsWith("{") && !pattern.startsWith("[")) {
return IDENTIFIER_RE.test(pattern) ? [pattern] : []
}
const names: string[] = []
for (let part of splitTopLevel(pattern.slice(1, patternCloseIndex(pattern)))) {
if (part.startsWith("...")) part = part.slice(3).trim()
const assign = defaultAssignIndex(part)
if (assign !== -1) part = part.slice(0, assign).trim()
if (pattern.startsWith("{")) {
const colon = indexOfTopLevel(part, ":")
if (colon !== -1) {
names.push(...patternBindings(part.slice(colon + 1)))
continue
}
}
names.push(...patternBindings(part))
}
return names
}
// one `let/var/const` declarator list, rewritten to scope assignments.
// Each segment's initializer is re-scanned so an `import()` inside it is
// rewritten like anywhere else - nothing else can match in there, since a
// nested top-level declaration inside a declarator is a SyntaxError in JS
const rewriteDeclarators = (src: string): SetupTransform => {
const vars: string[] = []
const rewritten = splitDeclarators(src).map(({ raw, codeEnd }) => {
const lead = raw.match(/^\s*/)![0]
Iif (codeEnd <= lead.length) return { text: raw, empty: true }
const body = raw.slice(lead.length, codeEnd)
const tail = raw.slice(codeEnd)
const assign = defaultAssignIndex(body)
const target = (assign === -1 ? body : body.slice(0, assign)).trim()
const isPattern = body[0] === "{" || body[0] === "["
if (isPattern) vars.push(...patternBindings(target))
else if (IDENTIFIER_RE.test(target)) vars.push(target)
const code = transformSetupScript(body).code
return { text: `${lead}${isPattern ? `(${code})` : code}${tail}`, empty: false }
})
// a trailing comment-only segment (`let a = 1, // note` cut at its line
// end) is re-attached without its comma, so the output stays a statement
const tail: string[] = []
while (rewritten.length && rewritten[rewritten.length - 1].empty) tail.unshift(rewritten.pop()!.text)
let code = rewritten.map(part => part.text).join(",") + tail.join("")
if (code.trimStart().startsWith("(")) code = `;${code}`
return { vars, code }
}
export const transformSetupScript = (src: string): SetupTransform => {
const vars: string[] = []
let out = ""
let i = 0
let depth = 0
let atStatementStart = true
while (i < src.length) {
const ch = src[i]
const next = src[i + 1]
if (ch === "'" || ch === '"' || ch === "`") {
const end = skipString(src, i)
out += src.slice(i, end)
i = end
atStatementStart = false
continue
}
if (ch === "/" && (next === "/" || next === "*")) {
const end = next === "/" ? skipLineComment(src, i) : skipBlockComment(src, i)
out += src.slice(i, end)
i = end
continue
}
if (ch === "/" && regexAllowed(src, i)) {
const end = skipRegex(src, i)
out += src.slice(i, end)
i = end
atStatementStart = false
continue
}
// `import(...)` is a keyword form, so it can't be intercepted through the
// scope - rewrite the identifier to the injected $__import (which loads
// .html URLs as components via Component79.fetch and delegates the rest to
// native import). The `(` is left for the scanner so depth stays balanced
if (ch === "i" && (i === 0 || !/[\w$.]/.test(src[i - 1]))) {
IMPORT_CALL_RE.lastIndex = i
if (IMPORT_CALL_RE.test(src)) {
out += "$__import"
i += "import".length
atStatementStart = false
continue
}
}
if (depth === 0 && atStatementStart) {
DECLARATION_START_RE.lastIndex = i
const decl = DECLARATION_START_RE.exec(src)
if (decl) {
const start = i + decl[0].length
const end = findStatementEnd(src, start)
const { vars: names, code } = rewriteDeclarators(src.slice(start, end))
vars.push(...names)
out += code
i = end
atStatementStart = false
continue
}
REACTIVE_LABEL_RE.lastIndex = i
const label = REACTIVE_LABEL_RE.exec(src)
if (label) {
REACTIVE_ASSIGN_RE.lastIndex = i
const assign = REACTIVE_ASSIGN_RE.exec(src)
if (assign) vars.push(assign[1])
const start = i + label[0].length
const end = findStatementEnd(src, start)
// the body is re-scanned rather than sliced raw, so an `import()`
// inside it gets the $__import rewrite like anywhere else. Safe to
// recurse: strings/comments/regexes copy through unchanged, and a
// depth-0 declaration inside a labeled statement is a SyntaxError
// in JS anyway, so nothing else can rewrite
out += `$__effect(() => { ${transformSetupScript(src.slice(start, end)).code} });`
i = end
continue
}
}
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch)) depth = Math.max(0, depth - 1)
if (ch === "\n" || ch === ";" || ch === "}") atStatementStart = true
else if (!/\s/.test(ch)) atStatementStart = false
out += ch
i++
}
return { vars, code: out }
}
// ---------------------------------------------------------------------------
// factory scripts - a <script> whose top level has `export default` runs as a
// plain lexical module instead of a `with`-scoped setup script: no implicit
// reactivity, no `$:` labels - standard JS that editors and type-checkers
// understand. The default export is called with the instance context
// ({ $data, $effect, $emit, $mounted, $destroyed, $attached, $detached, $computed, $self, $$self }) and a returned object
// is merged into the reactive store for the template to use.
// Detection is backwards-safe: `export default` is a SyntaxError inside a
// setup script, so no previously-working component can change behavior.
// The same scanner rewrites the module-only syntax into a Function body:
// - `export default X` -> `$__exports.default = X`
// - `import d from "m"` -> `const d = $__default(await $__import("m"))`
// (and the other static clause forms), so imports resolve through the same
// $__import as setup scripts: bundler map first, then fetch/native import
// ---------------------------------------------------------------------------
const EXPORT_DEFAULT_RE = /export\s+default(?![\w$])/y
// clause (default/namespace/named, no quotes or parens) + specifier; the
// no-clause alternative requires the specifier right away, so dynamic
// `import(...)` and `import.meta` never match
const STATIC_IMPORT_RE = /import\s*(?:([\w$\s,{}*]+?)\s*from\s*)?(["'])([^"'\n]+)\2/y
// splits an import clause on top-level commas: `d, { a, b as c }` keeps the
// braced group together
const splitImportClause = (clause: string): string[] => {
const parts: string[] = []
let depth = 0
let start = 0
for (let i = 0; i <= clause.length; i++) {
const ch = clause[i]
if (ch === "{") depth++
else if (ch === "}") depth--
else if (i === clause.length || (ch === "," && depth === 0)) {
const part = clause.slice(start, i).trim()
Eif (part) parts.push(part)
start = i + 1
}
}
return parts
}
// one static import statement -> const bindings from the awaited module
const staticImportToAwait = (clause: string | undefined, spec: string, n: number): string => {
const source = `await $__import(${JSON.stringify(spec)})`
if (clause === undefined) return source // side-effect import
const parts = splitImportClause(clause)
const bindings: string[] = []
let ref = source
if (parts.length > 1) {
const tmp = `$__mod${n}`
bindings.push(`${tmp} = ${source}`)
ref = tmp
}
for (const part of parts) {
if (part.startsWith("{")) bindings.push(`${part.replace(/\s+as\s+/g, ": ")} = ${ref}`)
else if (part.startsWith("*")) bindings.push(`${part.replace(/^\*\s*as\s+/, "")} = ${ref}`)
else bindings.push(`${part} = $__default(${ref})`)
}
return `const ${bindings.join(", ")}`
}
// ---------------------------------------------------------------------------
// the component's prop signature
//
// A component declares the props it takes as a destructuring pattern, in the
// place each script mode already puts its inputs: the `:setup` attribute's
// value, or the factory's *first* parameter (the ctx moved to the second).
// Position is fixed, so the signature is read straight from the source string -
// no parser, no execution - and the runtime can seed the defaults on the store
// before the first render, which is what makes them reach the template even in
// factory mode (where JS would only apply them inside the function body).
//
// <script :setup="{ label = 'Total', step = 1 }">
// export default ({ label = "Total" }, { $data }) => {}
//
// An object pattern *is* the declaration; anything else (`_`, a plain
// identifier, no attribute at all) declares nothing and stays permissive.
// ---------------------------------------------------------------------------
// `as` is the local name the pattern binds the key to, when it isn't the key
// itself (`{ item: row }`). A prop signature has no use for it - what the
// store holds is the key - but the slot binder (`:slot="{ item: row }"`) is
// the same pattern read for the other half: which names the content uses
export type PropDecl = { name: string; default?: string; as?: string }
const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/
// index of the bracket that closes the one opening at src[0], skipping
// strings, comments and regex literals; src.length when unbalanced
const patternCloseIndex = (src: string): number => {
let depth = 0
let i = 0
while (i < src.length) {
const ch = src[i]
if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); continue }
Iif (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch) && --depth === 0) return i
i++
}
return src.length
}
// index of the first `ch` at bracket depth 0, skipping strings and comments
const indexOfTopLevel = (src: string, ch: string): number => {
let depth = 0
let i = 0
while (i < src.length) {
const c = src[i]
Iif (c === "'" || c === '"' || c === "`") { i = skipString(src, i); continue }
Iif (c === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
Iif (c === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
Iif (c === "/" && c !== ch && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
if ("([{".includes(c)) depth++
else if (")]}".includes(c)) depth--
else if (depth === 0 && c === ch) return i
i++
}
return -1
}
const splitTopLevel = (src: string): string[] => {
const parts: string[] = []
let depth = 0
let start = 0
let i = 0
while (i <= src.length) {
const ch = src[i]
if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); continue }
Iif (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
if (ch !== undefined && "([{".includes(ch)) depth++
else if (ch !== undefined && ")]}".includes(ch)) depth--
else if (i === src.length || (ch === "," && depth === 0)) {
const part = src.slice(start, i).trim()
if (part) parts.push(part)
start = i + 1
}
i++
}
return parts
}
// the `=` that opens a default value: the first one at depth 0 that isn't part
// of `==`/`===` or an arrow's `=>` (so `{ format = a => a }` keeps its default)
const defaultAssignIndex = (src: string): number => {
let from = 0
while (from < src.length) {
const at = indexOfTopLevel(src.slice(from), "=")
if (at === -1) return -1
const i = from + at
Eif (src[i + 1] !== "=" && src[i + 1] !== ">" && src[i - 1] !== "=" && src[i - 1] !== "!") return i
from = i + 1
}
return -1
}
// a destructuring pattern -> the props it declares. null means "no signature":
// the pattern isn't an object one (`_`, `props`, nothing at all), so the
// component declares nothing and keeps the permissive, undeclared behavior.
// `{}` parses to [] - a closed signature that declares zero props
export const parsePropsPattern = (pattern: string | undefined): PropDecl[] | null => {
const src = (pattern ?? "").trim()
if (!src.startsWith("{")) return null
// to the `}` that closes the pattern, so a parameter's own default value
// (`({ label } = {})`) is left out of it
const close = patternCloseIndex(src)
if (close >= src.length) return null // unbalanced: not a pattern we can read
const props: PropDecl[] = []
for (const part of splitTopLevel(src.slice(1, close))) {
if (part.startsWith("...")) continue // a rest element names no prop
const assign = defaultAssignIndex(part)
const named = assign === -1 ? part : part.slice(0, assign)
const fallback = assign === -1 ? undefined : part.slice(assign + 1).trim()
// `{ user: { id } }` and `{ user: renamed }` both declare `user`: what the
// store holds is the key, whatever the pattern binds it to
const colon = indexOfTopLevel(named, ":")
const name = (colon === -1 ? named : named.slice(0, colon)).trim()
Iif (!IDENTIFIER_RE.test(name)) continue
const decl: PropDecl = { name }
if (fallback !== undefined) decl.default = fallback
// only a plain rename is kept: `{ user: { id } }` binds no single name, so
// there is nothing to record - the prop is still declared under its key
const local = colon === -1 ? "" : named.slice(colon + 1).trim()
if (IDENTIFIER_RE.test(local)) decl.as = local
props.push(decl)
}
return props
}
// index just past a top-level `export default`, or -1
const findExportDefault = (src: string): number => {
let i = 0
let depth = 0
let atStatementStart = true
while (i < src.length) {
const ch = src[i]
if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); atStatementStart = false; continue }
if (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); atStatementStart = false; continue }
if (ch === "e" && depth === 0 && atStatementStart && (i === 0 || !/[\w$.]/.test(src[i - 1]))) {
EXPORT_DEFAULT_RE.lastIndex = i
const found = EXPORT_DEFAULT_RE.exec(src)
Eif (found) return i + found[0].length
}
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch)) depth = Math.max(0, depth - 1)
if (ch === "\n" || ch === ";" || ch === "}") atStatementStart = true
else if (!/\s/.test(ch)) atStatementStart = false
i++
}
return -1
}
const ASYNC_RE = /^async(?![\w$])/
const FUNCTION_RE = /^function(?![\w$])\s*\*?\s*[A-Za-z_$][\w$]*|^function(?![\w$])\s*\*?/
// source text of the exported function's first parameter, or null when there
// is no parameter list to read (`export default Factory`, `export default
// props => ...`, an exported object) - all of which declare nothing
const firstParameterSource = (src: string): string | null => {
const start = findExportDefault(src)
if (start === -1) return null
let i = skipToToken(src, start)
const rest = src.slice(i)
if (ASYNC_RE.test(rest)) i = skipToToken(src, i + "async".length)
const fn = FUNCTION_RE.exec(src.slice(i))
if (fn) i = skipToToken(src, i + fn[0].length)
if (src[i] !== "(") return null
// the parameter list runs to the `)` that closes this `(`
let depth = 0
let end = i
while (end < src.length) {
const ch = src[end]
if (ch === "'" || ch === '"' || ch === "`") { end = skipString(src, end); continue }
Iif (ch === "/" && src[end + 1] === "/") { end = skipLineComment(src, end); continue }
if (ch === "/" && src[end + 1] === "*") { end = skipBlockComment(src, end); continue }
if (ch === "/" && regexAllowed(src, end)) { end = skipRegex(src, end); continue }
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch) && --depth === 0) break
end++
}
return splitTopLevel(src.slice(i + 1, end))[0] ?? ""
}
// the props declared by a factory script's first parameter. Throws the
// migration error when it finds the pre-0.4 signature there - the ctx used to
// be the first parameter, and the change is silent otherwise ($data would just
// come back undefined). `$` is what tells them apart: what carries one comes
// from the library, what doesn't comes from the parent, everywhere in jq79
export const parseFactoryProps = (src: string): PropDecl[] | null => {
const first = firstParameterSource(src)
if (first === null) return null
const props = parsePropsPattern(first)
const ctxName = props?.find(prop => prop.name.startsWith("$"))?.name
if (ctxName) {
throw new Error(
`jq79: the factory signature is (props, ctx), so \`${ctxName}\` can't be destructured from the first parameter. ` +
`Write \`export default (props, { ${ctxName} }) => …\`, or \`_\` in place of props if the component takes none.`
)
}
return props
}
// rewrites a factory script into a Function body, or returns null when the
// script has no top-level `export default` (i.e. it's a regular setup script)
export const transformFactoryScript = (src: string): string | null => {
let out = ""
let i = 0
let depth = 0
let atStatementStart = true
let isFactory = false
let modCount = 0
while (i < src.length) {
const ch = src[i]
const next = src[i + 1]
const atWordBoundary = i === 0 || !/[\w$.]/.test(src[i - 1])
if (ch === "'" || ch === '"' || ch === "`") {
const end = skipString(src, i)
out += src.slice(i, end)
i = end
atStatementStart = false
continue
}
if (ch === "/" && (next === "/" || next === "*")) {
const end = next === "/" ? skipLineComment(src, i) : skipBlockComment(src, i)
out += src.slice(i, end)
i = end
continue
}
if (ch === "/" && regexAllowed(src, i)) {
const end = skipRegex(src, i)
out += src.slice(i, end)
i = end
atStatementStart = false
continue
}
if (ch === "i" && atWordBoundary) {
// dynamic import() -> $__import, same rewrite as setup scripts
IMPORT_CALL_RE.lastIndex = i
if (IMPORT_CALL_RE.test(src)) {
out += "$__import"
i += "import".length
atStatementStart = false
continue
}
if (depth === 0 && atStatementStart) {
STATIC_IMPORT_RE.lastIndex = i
const staticImport = STATIC_IMPORT_RE.exec(src)
if (staticImport) {
out += staticImportToAwait(staticImport[1], staticImport[3], modCount++)
i += staticImport[0].length
atStatementStart = false
continue
}
}
}
if (ch === "e" && atWordBoundary && depth === 0 && atStatementStart) {
EXPORT_DEFAULT_RE.lastIndex = i
const exportDefault = EXPORT_DEFAULT_RE.exec(src)
Eif (exportDefault) {
isFactory = true
out += "$__exports.default ="
i += exportDefault[0].length
atStatementStart = false
continue
}
}
if ("([{".includes(ch)) depth++
else if (")]}".includes(ch)) depth = Math.max(0, depth - 1)
if (ch === "\n" || ch === ";" || ch === "}") atStatementStart = true
else if (!/\s/.test(ch)) atStatementStart = false
out += ch
i++
}
return isFactory ? out : null
}
// ---------------------------------------------------------------------------
// free identifiers in a template expression
//
// What a compiled expression reads from the scope, so it can be resolved by
// name instead of by `with ($scope)` - which is 60% of an evaluation over a
// store proxy, because it resolves every mention through [[HasProperty]] (the
// proxy's `has` trap as well as its `get`) and consults Symbol.unscopables
// besides. See RECORD/2026-08-27.name-resolution-without-with.md
//
// This is a scanner, not a parser, and it is deliberately conservative: `null`
// means "keep `with`", and every shape that binds a name, assigns to one or
// resolves one dynamically returns it. The caller falls back rather than
// guesses, so a name this misses costs a slower evaluation, never a wrong one.
// ---------------------------------------------------------------------------
// words that scan as an identifier and are never a free variable read
const NOT_A_FREE_NAME = new Set([
"true", "false", "null", "undefined", "this", "typeof", "instanceof", "in", "new", "void",
"delete", "of", "await", "yield", "NaN", "Infinity", "arguments", "case", "do", "else", "return",
])
// anything that introduces a binding or reaches the scope by another route.
// A dynamic `import(...)` is absent deliberately: naming it here would put the
// word next to a quote in the bundle, which is what tests/no-bundle.test.ts
// greps for. It needs no entry - `import` is collected as a free name, the
// prologue's `const import = …` will not compile, and compileScoped falls back
const BINDS_A_NAME = new Set(["function", "class", "let", "const", "var", "eval", "with"])
// the compiled function's own parameters and temporary: an expression that
// mentions one would be reading the codegen's variable, not the author's
const CODEGEN_NAMES = new Set(["$scope", "$r", "$t"])
// operators that write, or bind - any of them and the expression keeps `with`
const WRITES_RE = /^(?:\+\+|--|=>|\*\*=|<<=|>>>=|>>=|&&=|\|\|=|\?\?=|[+\-*/%&|^]=(?!=))/
// operators that merely read, longest first so `===` is never read as `==` + `=`
const READS_RE = /^(?:>>>|===|!==|\*\*|<<|>>|==|!=|<=|>=|&&|\|\||\?\?|\?\.)/
const isIdentifierStart = (ch: string): boolean => /[A-Za-z_$]/.test(ch)
// a numeric literal, consumed whole so `1e5` does not scan as the name `e5`
const NUMBER_RE = /^(?:0[xXbBoO][\da-fA-F_]+|\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d+)?)n?/
export const freeIdentifiers = (expr: string): string[] | null => {
const names = new Set<string>()
// one entry per open bracket, counting the `?`s waiting for their `:` at that
// depth - which is what tells `{ danger: x }`'s key from `a ? b : c`'s colon
const ternaries: number[] = [0]
const brackets: string[] = []
let shortCircuits = false
let prev = "" // the last meaningful token: "name", "value", "." or "?." or a punctuator
let i = 0
while (i < expr.length) {
const ch = expr[i]
if (/\s/.test(ch)) { i++; continue }
if (ch === "/" && expr[i + 1] === "/") { i = skipLineComment(expr, i); continue }
Iif (ch === "/" && expr[i + 1] === "*") { i = skipBlockComment(expr, i); continue }
if (ch === "/" && regexAllowed(expr, i)) { i = skipRegex(expr, i); prev = "value"; continue }
if (ch === '"' || ch === "'") { i = skipString(expr, i); prev = "value"; continue }
if (ch === "`") {
// a template literal reads names inside every ${...}, and nothing else
let j = i + 1
while (j < expr.length) {
Iif (expr[j] === "\\") { j += 2; continue }
if (expr[j] === "`") { j++; break }
if (expr[j] === "$" && expr[j + 1] === "{") {
let depth = 1
const start = (j += 2)
while (j < expr.length && depth > 0) {
Iif (expr[j] === "{") depth++
else if (expr[j] === "}") depth--
j++
}
const inner = freeIdentifiers(expr.slice(start, j - 1))
Iif (inner === null) return null
inner.forEach(name => names.add(name))
continue
}
j++
}
i = j
prev = "value"
continue
}
if (/\d/.test(ch) && prev !== "." && prev !== "?.") {
const match = NUMBER_RE.exec(expr.slice(i))
i += match ? match[0].length : 1
prev = "value"
continue
}
if (isIdentifierStart(ch)) {
let end = i
while (end < expr.length && /[\w$]/.test(expr[end])) end++
const word = expr.slice(i, end)
i = end
if (BINDS_A_NAME.has(word)) return null
if (prev === "." || prev === "?.") { prev = "value"; continue } // a property, not a name
if (NOT_A_FREE_NAME.has(word)) { prev = word === "this" ? "value" : "op"; continue }
if (CODEGEN_NAMES.has(word)) return null
let after = i
while (after < expr.length && /\s/.test(expr[after])) after++
// A free name that is CALLED is called with the with-object as its
// receiver: `add()` inside `with ($scope)` runs with `this === $scope`,
// and a factory component's `{ items: [], add() { this.items… } }`
// depends on it. A `const` cannot reproduce that - the call would get
// `undefined` - so a called name keeps `with`. Measured at 11 of this
// repository's 239 resolvable expressions, and 8 of those are handlers
if (expr[after] === "(") return null
// `{ danger: … }` names a key; `a ? b : c` names a value
const isKey = expr[after] === ":" && expr[after + 1] !== ":" &&
brackets[brackets.length - 1] === "{" && ternaries[ternaries.length - 1] === 0
if (!isKey) names.add(word)
prev = "value"
continue
}
const rest = expr.slice(i)
if (WRITES_RE.test(rest)) return null
const reads = READS_RE.exec(rest)
if (reads) {
if (reads[0] === "&&" || reads[0] === "||" || reads[0] === "??") shortCircuits = true
prev = reads[0] === "?." ? "?." : "op"
i += reads[0].length
continue
}
if (ch === "=") return null // a bare `=` left after READS_RE is an assignment
if (ch === "(" || ch === "[" || ch === "{") { brackets.push(ch); ternaries.push(0) }
else if (ch === ")" || ch === "]" || ch === "}") { brackets.pop(); if (ternaries.length > 1) ternaries.pop() }
else if (ch === "?") { ternaries[ternaries.length - 1]++; shortCircuits = true }
else if (ch === ":" && ternaries[ternaries.length - 1] > 0) ternaries[ternaries.length - 1]--
prev = ch
i++
}
// every name is resolved before the expression runs, so a branch that would
// not have been taken is read anyway: one more dep than `with` would track,
// and a ReferenceError for a name only the dead branch mentions. With one
// name there is no branch to be wrong about
if (shortCircuits && names.size > 1) return null
return [...names]
}
// ---------------------------------------------------------------------------
// the preload scanner (RECORD/2026-11-05.a-preload-scanner.md): the literal
// specifiers a script asks for in top-level statements that run whatever
// happens, so the runtime can start every download before the script's first
// line and let the script take them in its own order. What might not run is
// left alone - a function's body, a block, a branch, a loop, a handler - and
// so is anything the scanner can't read whole: a missed preload costs what it
// costs today, a wrong one an extra download of a file
// ---------------------------------------------------------------------------
// how a specifier resolves - the way the call that names it does:
// - "component": import(), $importAll and a static import, against the
// component's file and through its modules map; .html is a component,
// anything else a module
// - "page": C79.importAll, the same against the page
// - "fetch": C79.fetch / fetchAll, always a component, against the page
// (no kind is spelled "import": dist/jq79.js is held to having no import
// statement in it, and the test can't tell one from a string that ends so)
export type Preload = { spec: string; kind: "component" | "page" | "fetch" }
// where a statement or an initializer starts with a call that downloads:
// an optional await, then the call up to its opening bracket(s)
const PRELOAD_CALL_RE = /(?:await\s+)?(?:import\s*\(|(\$importAll)\s*\(\s*\[|(C79|Component79)\s*\.\s*(fetch|fetchAll|importAll)\s*\(\s*(\[)?)/y
const PRELOAD_LITERAL_RE = /(["'])([^"'\n\\]+)\1/y
// a statement that guards the next one without braces - `if (x)`, a loop's
// header, `else`, `do` - so that one may not run
const GUARD_RE = /^(?:(?:if|for|while|with)\b[\s\S]*\)|[\s\S]*\b(?:else|do))$/
// the literal specifiers of the call `text` starts with: an array's entries
// up to the first that isn't a literal on its own (`"./a" + x` is not one)
const preloadCall = (text: string, own: Set<string>): Preload[] => {
PRELOAD_CALL_RE.lastIndex = 0
const call = PRELOAD_CALL_RE.exec(text)
if (!call) return []
const [, importAll, library, method, bracket] = call
if (own.has(importAll ?? library ?? "")) return [] // the script's own, not jq79's
const list = importAll !== undefined || bracket !== undefined
// fetch takes one URL, its plurals an array: anything else throws
if (method !== undefined && (method === "fetch") === list) return []
const kind: Preload["kind"] = library === undefined ? "component" : method === "importAll" ? "page" : "fetch"
const found: Preload[] = []
let i = skipToToken(text, PRELOAD_CALL_RE.lastIndex)
for (;;) {
PRELOAD_LITERAL_RE.lastIndex = i
const literal = PRELOAD_LITERAL_RE.exec(text)
if (!literal) return found
const end = skipToToken(text, PRELOAD_LITERAL_RE.lastIndex)
const next = text[end]
if (!list) return next === ")" || next === "," ? [{ spec: literal[2], kind }] : []
Iif (next !== "," && next !== "]") return found
found.push({ spec: literal[2], kind })
if (next === "]") return found
i = skipToToken(text, end + 1)
}
}
export const preloadSpecifiers = (src: string): Preload[] => {
const statements: string[] = []
for (let i = skipToToken(src, 0); i < src.length; i = skipToToken(src, i + 1)) {
const end = findStatementEnd(src, i)
statements.push(src.slice(i, end).trim().replace(/^export\s+(?!default\b)/, ""))
i = end
}
// a declaration's initializers, or null for a statement that isn't one
const initializers = (statement: string): { target: string; init: string }[] | null => {
DECLARATION_START_RE.lastIndex = 0
const declaration = DECLARATION_START_RE.exec(statement)
if (!declaration) return null
return splitDeclarators(statement.slice(declaration[0].length)).map(({ raw }) => {
const body = raw.trim()
const assign = defaultAssignIndex(body)
return assign === -1 ? { target: body, init: "" } : { target: body.slice(0, assign).trim(), init: body.slice(assign + 1).trim() }
})
}
// a script that declares its own C79, Component79 or $importAll calls
// that, not the library's
const own = new Set<string>()
statements.forEach(statement => initializers(statement)?.forEach(({ target }) => patternBindings(target).forEach(name => own.add(name))))
const found: Preload[] = []
let guarded = false
for (const statement of statements) {
if (!guarded) {
STATIC_IMPORT_RE.lastIndex = 0
const staticImport = STATIC_IMPORT_RE.exec(statement)
if (staticImport) {
if (!/^type\s/.test(staticImport[1] ?? "")) found.push({ spec: staticImport[3], kind: "component" })
} else {
const declared = initializers(statement)
for (const text of declared ? declared.map(({ init }) => init) : [statement]) found.push(...preloadCall(text, own))
}
}
guarded = GUARD_RE.test(statement)
}
return found
}
|