Skip to content

Commit af2b787

Browse files
alexander-akaitclaude
authored andcommitted
feat(javascript): read an event handler's body as one, with import phases
`sourceType: "event-handler"` reads a source as the function body HTML compiles an event handler attribute into, for `parseProgram`, `process` and the printer's `minify`. `jsMinify` minifies a handler through it instead of wrapping its text, so the answer now maps. `parseProgram` and `process` read import phases, and the parse-error code table loads with the first error reported. Claude-Session: https://claude.ai/code/session_015gdnghKbLJ7VvJ5nNCNHhH
1 parent 9831760 commit af2b787

13 files changed

Lines changed: 618 additions & 354 deletions

File tree

‎.changeset/041-syntax-parse-error-option.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": minor
33
---
44

5-
Add `parseErrors` to CSS and HTML parsers, and `parseError` and `parseProgram`.
5+
Add CSS and HTML `parseErrors`, `parseProgram`, and event handler `sourceType`.

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ Produced by `yarn fix:special` — never edit by hand:
218218
- `types.d.ts` — from JSDoc + schemas.
219219
- `schemas/**/*.check.{js,d.ts}` — precompiled schema validators.
220220
- Generated runtime code under `lib/` (`tooling/generate-runtime-code.js`).
221-
- `lib/css/data.js`, `lib/html/data.js`, `lib/javascript/data.js`, `lib/javascript/syntax-printer-data.js` — every lookup table the CSS minifier, HTML parser/minifier and JS parser and printer read, by `tooling/generate-css-data.js`, `generate-html-data.js` and `generate-js-data.js`; `generate-html-data.js` also writes the `// #region html entities` block in `lib/html/syntax-parser.js`. Sources and contents: [docs/syntax.md](docs/syntax.md#generated-tables).
221+
- `lib/css/data.js`, `lib/html/data.js`, `lib/javascript/data.js`, `lib/javascript/syntax-printer-data.js`, `lib/javascript/parse-error-codes.js` — every lookup table the CSS minifier, HTML parser/minifier and JS parser and printer read, by `tooling/generate-css-data.js`, `generate-html-data.js` and `generate-js-data.js`; `generate-html-data.js` also writes the `// #region html entities` block in `lib/html/syntax-parser.js`. Sources and contents: [docs/syntax.md](docs/syntax.md#generated-tables).
222222

223223
A `syntax-parser.js` or `syntax-printer.js` is algorithm only — a new lookup table belongs in the matching generator. Generator-written regions such as `// #region html entities` are the exception; `syntax.js` is a facade, neither.
224224

‎cspell.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,7 @@
651651
"test/unitCases/JavascriptParser.unittest.js",
652652
"lib/javascript/data.js",
653653
"lib/javascript/syntax-printer-data.js",
654+
"lib/javascript/parse-error-codes.js",
654655
"tooling/html-entities.json",
655656
"test/external/test262-cases/**",
656657
"test/external/wpt/**",

‎docs/syntax.md‎

Lines changed: 2 additions & 0 deletions
Large diffs are not rendered by default.

‎lib/javascript/data.js‎

Lines changed: 1 addition & 245 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
*/
55

66
// GENERATED by tooling/generate-js-data.js — do not edit.
7-
// Sources: acorn 8.19.0, terser 5.51.2, @babel/parser 8.0.7. The tables read from terser are under its
7+
// Sources: acorn 8.19.0, terser 5.51.2. The tables read from terser are under its
88
// license, quoted in full in syntax-printer.js.
99

1010
"use strict";
@@ -564,249 +564,6 @@ const NODE_FIELDS = {
564564
MetaProperty: "meta:node:0 property:node:1"
565565
};
566566

567-
// Each parse error message, `*` for its variable parts, with its code: Babel's
568-
// `reasonCode` for the same error kebab-cased, where Babel has one.
569-
/** @type {[string, string][]} */
570-
const PARSE_ERROR_CODES = [
571-
[
572-
"'import defer' can only be used with namespace imports ('import defer * as identifierName from ...').",
573-
"defer-import-requires-namespace"
574-
],
575-
[
576-
"'import source' can only be used with direct identifier specifier imports ('import source identifierName from ...').",
577-
"source-phase-import-requires-default"
578-
],
579-
[
580-
"'import source' can only be used with direct identifier specifier imports.",
581-
"source-phase-import-requires-default"
582-
],
583-
[
584-
"'import' and 'export' may appear only with 'sourceType: module'",
585-
"import-outside-module"
586-
],
587-
[
588-
"'import' and 'export' may only appear at the top level",
589-
"unexpected-import-export"
590-
],
591-
["'import.*' can only be used in a dynamic import.", "unexpected-token"],
592-
[
593-
"'import.*' must not contain escaped characters",
594-
"unsupported-meta-property"
595-
],
596-
[
597-
"'new.target' can only be used in functions and class static block",
598-
"unexpected-new-target"
599-
],
600-
[
601-
"'new.target' must not contain escaped characters",
602-
"unsupported-meta-property"
603-
],
604-
["'return' outside of function", "illegal-return"],
605-
["'super' keyword outside a method", "unexpected-super"],
606-
["'with' in strict mode", "strict-with"],
607-
[
608-
"* loop variable declaration may not have an initializer",
609-
"for-in-of-loop-initializer"
610-
],
611-
[
612-
"A string literal cannot be used as an exported binding without `from`.",
613-
"export-binding-is-string"
614-
],
615-
[
616-
"An export name cannot include a lone surrogate.",
617-
"module-export-name-has-lone-surrogate"
618-
],
619-
["Argument name clash", "param-dupe"],
620-
["Assigning to * in strict mode", "strict-eval-arguments"],
621-
["Binding * in strict mode", "strict-eval-arguments-binding"],
622-
["Assigning to rvalue", "invalid-lhs"],
623-
["Binding rvalue", "invalid-lhs-binding"],
624-
[
625-
"Await expression cannot be a default value",
626-
"await-expression-formal-parameter"
627-
],
628-
[
629-
"Await using cannot appear outside of async function",
630-
"await-using-not-in-async-context"
631-
],
632-
["Bad character escape sequence", "invalid-escape-sequence"],
633-
[
634-
"Bad escape sequence in untagged template literal",
635-
"invalid-escape-sequence-template"
636-
],
637-
["Binding member expression", "invalid-property-binding-pattern"],
638-
["Binding parenthesized expression", "invalid-parenthesized-assignment"],
639-
["Parenthesized pattern", "invalid-parenthesized-assignment"],
640-
["Cannot use 'arguments' in class field initializer", "arguments-in-class"],
641-
[
642-
"Cannot use 'await' as identifier inside an async function",
643-
"await-binding-identifier"
644-
],
645-
["Cannot use 'import.meta' outside a module", "import-meta-outside-module"],
646-
[
647-
"Cannot use 'yield' as identifier inside a generator",
648-
"yield-binding-identifier"
649-
],
650-
["Cannot use * in class static initialization block", "arguments-in-class"],
651-
[
652-
"Cannot use keyword 'await' outside an async function",
653-
"await-not-in-async-context"
654-
],
655-
["Classes can't have a field named 'constructor'", "constructor-class-field"],
656-
["Classes can't have a static field named 'prototype'", "static-prototype"],
657-
[
658-
"Classes can't have an element named '#constructor'",
659-
"constructor-class-private-field"
660-
],
661-
[
662-
"Classes may not have a static property named prototype",
663-
"static-prototype"
664-
],
665-
["Code point out of bounds", "invalid-code-point"],
666-
["Comma is not permitted after the rest element", "rest-trailing-comma"],
667-
[
668-
"Complex binding patterns require an initialization value",
669-
"declaration-missing-initializer"
670-
],
671-
["Constructor can't be a generator", "constructor-is-generator"],
672-
["Constructor can't be an async method", "constructor-is-async"],
673-
["Constructor can't have get/set modifier", "constructor-is-accessor"],
674-
["Deleting local variable in strict mode", "strict-delete"],
675-
["Duplicate attribute key '*'", "module-attributes-with-duplicate-keys"],
676-
["Duplicate constructor in the same class", "duplicate-constructor"],
677-
["Duplicate export 'default'", "duplicate-default-export"],
678-
["Duplicate export '*'", "duplicate-export"],
679-
["Duplicate regular expression flag", "duplicate-reg-exp-flags"],
680-
["Escape sequence in keyword *", "invalid-escaped-reserved-word"],
681-
["Expected number in radix *", "invalid-digit"],
682-
["Expecting Unicode escape sequence \\uXXXX", "missing-unicode-escape"],
683-
["Export '*' is not defined", "module-export-undefined"],
684-
["Identifier '#*' has already been declared", "private-name-redeclaration"],
685-
["Identifier '*' has already been declared", "var-redeclaration"],
686-
["Identifier directly after number", "number-identifier"],
687-
[
688-
"Illegal 'use strict' directive in function with non-simple parameter list",
689-
"illegal-language-mode-directive"
690-
],
691-
["Illegal newline after throw", "newline-after-throw"],
692-
["Invalid Unicode escape", "escaped-char-not-an-identifier"],
693-
["Invalid escape sequence", "strict-numeric-escape"],
694-
[
695-
"Invalid escape sequence in template string",
696-
"invalid-escape-sequence-template"
697-
],
698-
["Octal literal in strict mode", "strict-numeric-escape"],
699-
["Octal literal in template string", "invalid-escape-sequence-template"],
700-
["Invalid number", "invalid-or-missing-exponent"],
701-
["Invalid regular expression flag", "malformed-reg-exp-flags"],
702-
["Invalid regular expression: /*/: *", "invalid-regular-expression"],
703-
["Invalid use of 'super'", "unsupported-super"],
704-
["Label '*' is already declared", "label-redeclaration"],
705-
[
706-
"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses",
707-
"mixing-coalesce-with-logical"
708-
],
709-
["Missing catch or finally clause", "no-catch-or-finally"],
710-
["Missing initializer in * declaration", "declaration-missing-initializer"],
711-
["Multiple default clauses", "multiple-defaults-in-switch"],
712-
["Not enough stack space to parse input", "not-enough-stack-space"],
713-
[
714-
"Numeric separator is not allowed at the first of digits",
715-
"unexpected-numeric-separator"
716-
],
717-
[
718-
"Numeric separator is not allowed at the last of digits",
719-
"unexpected-numeric-separator"
720-
],
721-
[
722-
"Numeric separator is not allowed in legacy octal numeric literals",
723-
"zero-digit-numeric-separator"
724-
],
725-
[
726-
"Numeric separator must be exactly one underscore",
727-
"unexpected-numeric-separator"
728-
],
729-
["Object pattern can't contain getter or setter", "pattern-has-accessor"],
730-
[
731-
"Only '=' operator can be used for specifying default value.",
732-
"missing-eq-in-assignment"
733-
],
734-
[
735-
"Optional chaining cannot appear in left-hand side",
736-
"invalid-lhs-optional-chaining"
737-
],
738-
[
739-
"Optional chaining cannot appear in the callee of new expressions",
740-
"optional-chaining-no-new"
741-
],
742-
[
743-
"Optional chaining cannot appear in the tag of tagged template expressions",
744-
"optional-chaining-no-template"
745-
],
746-
[
747-
"Private field '#*' must be declared in an enclosing class",
748-
"invalid-private-field-resolution"
749-
],
750-
["Private fields can not be deleted", "delete-private-field"],
751-
[
752-
"Private identifier can only be left side of binary expression",
753-
"private-in-expected-in"
754-
],
755-
["Redefinition of __proto__ property", "duplicate-proto"],
756-
["Redefinition of property", "redefinition-of-property"],
757-
[
758-
"Rest elements cannot have a default value",
759-
"invalid-rest-assignment-pattern"
760-
],
761-
["Setter cannot use rest params", "bad-setter-rest-parameter"],
762-
[
763-
"Shorthand property assignments are valid only in destructuring patterns",
764-
"invalid-cover-initialized-name"
765-
],
766-
["The keyword '*' is reserved", "unexpected-reserved-word"],
767-
[
768-
"The left-hand side of a for-of loop may not start with 'let'.",
769-
"for-of-let"
770-
],
771-
[
772-
"The only valid meta property for import is 'import.meta'",
773-
"unsupported-meta-property"
774-
],
775-
[
776-
"The only valid meta property for new is 'new.target'",
777-
"unsupported-meta-property"
778-
],
779-
["Trailing comma is not allowed in import()", "import-call-arity"],
780-
["Unexpected character '*'", "invalid-or-unexpected-token"],
781-
["Unexpected keyword '*'", "unexpected-keyword"],
782-
["Unexpected token", "unexpected-token"],
783-
["Unsyntactic *", "illegal-break-continue"],
784-
["Unterminated comment", "unterminated-comment"],
785-
["Unterminated regular expression", "unterminated-reg-exp"],
786-
["Unterminated string constant", "unterminated-string"],
787-
["Unterminated template", "unterminated-template"],
788-
["Unterminated template literal", "unterminated-template"],
789-
[
790-
"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement",
791-
"unexpected-using-declaration"
792-
],
793-
["Using declaration is not allowed in for-in loops", "for-in-using"],
794-
[
795-
"Using declaration is not allowed in single-statement positions",
796-
"unexpected-lexical-declaration"
797-
],
798-
["Yield expression cannot be a default value", "yield-in-parameter"],
799-
["getter should have no params", "bad-getter-arity"],
800-
[
801-
"import call cannot be the target of `new`",
802-
"import-call-not-new-expression"
803-
],
804-
["let is disallowed as a lexically bound name", "let-in-lexical-binding"],
805-
["setter should have exactly one param", "bad-setter-arity"],
806-
["super() call outside constructor of a subclass", "super-not-allowed"],
807-
["*", "syntax-error"]
808-
];
809-
810567
module.exports.ASTRAL_IDENTIFIER_PART_RANGES = ASTRAL_IDENTIFIER_PART_RANGES;
811568
module.exports.ASTRAL_IDENTIFIER_START_RANGES = ASTRAL_IDENTIFIER_START_RANGES;
812569
module.exports.IDENTIFIER_PART_RANGES = IDENTIFIER_PART_RANGES;
@@ -817,7 +574,6 @@ module.exports.Field = Field;
817574
module.exports.Flag = Flag;
818575
module.exports.NODE_FIELDS = NODE_FIELDS;
819576
module.exports.NodeType = NodeType;
820-
module.exports.PARSE_ERROR_CODES = PARSE_ERROR_CODES;
821577
module.exports.Part = Part;
822578
module.exports.UNICODE_BINARY_PROPERTIES = UNICODE_BINARY_PROPERTIES;
823579
module.exports.UNICODE_BINARY_PROPERTIES_OF_STRINGS =

‎lib/javascript/jsMinify.js‎

Lines changed: 4 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,7 @@
1010
/** @typedef {import("./syntax-printer").Minify} Minify */
1111
/** @typedef {import("./syntax-printer").PrintNode} PrintNode */
1212

13-
/**
14-
* Which production of JavaScript the source is: a classic script, a module, or
15-
* the body of an event handler, which is a function body and nothing the
16-
* minifier parses on its own.
17-
* @typedef {"script" | "module" | "event-handler"} JavascriptProduction
18-
*/
13+
/** @typedef {import("./syntax-parser").JavascriptSourceType} JavascriptSourceType */
1914

2015
/** @typedef {import("minimizer-webpack-plugin").ExtractCommentsFunction} CommentCondition */
2116
/** @typedef {import("minimizer-webpack-plugin").ExtractCommentsOptions} ExtractCommentsOption */
@@ -38,7 +33,7 @@
3833
* where this module's own scope is gone.
3934
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
4035
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
41-
* @param {(MinifyOptions & { as?: JavascriptProduction })=} minimizerOptions `optimization.minimize.javascript`; `as` names the production the source is written in, which is the source's own rather than the configuration's
36+
* @param {(MinifyOptions & { as?: JavascriptSourceType })=} minimizerOptions `optimization.minimize.javascript`; `as` names the production the source is written in, which is the source's own rather than the configuration's
4237
* @param {ExtractCommentsOption=} extractComments which comments to move into a separate file
4338
* @returns {Promise<{ code: string, map?: MinifyOutput["map"], extractedComments?: string[], errors?: Error[] }>} the minified code, its input->output source map, and the comments taken out of it
4439
*/
@@ -64,30 +59,6 @@ const jsMinify = async (
6459
return { code: "", errors: [/** @type {Error} */ (err)] };
6560
}
6661

67-
// A handler body is minified as the function it belongs to: named past any
68-
// run of `_` the body holds, so nothing in it resolves to that function, and
69-
// opened on a new line so a line comment cannot close the body.
70-
const asFunction = (/** @type {string} */ body) => {
71-
const runs = body.match(/_+/g);
72-
const longest = runs
73-
? runs.reduce((widest, run) => Math.max(widest, run.length), 0)
74-
: 0;
75-
return `function ${"_".repeat(longest + 1)}(){${body}\n}`;
76-
};
77-
// The body back out of that function. `undefined` where the answer is not
78-
// that function — it held something else, or was dropped whole as the unused
79-
// declaration it is.
80-
const functionBody = (/** @type {string | undefined} */ answered) => {
81-
if (typeof answered !== "string") return undefined;
82-
const written = answered.trim().replace(/;$/, "");
83-
const opened = written.indexOf("{");
84-
return opened !== -1 &&
85-
written.endsWith("}") &&
86-
/^function\s+[^\s(]+\s*\(\s*\)\s*$/.test(written.slice(0, opened))
87-
? written.slice(opened + 1, -1).trim()
88-
: undefined;
89-
};
90-
9162
/**
9263
* One comment condition, whatever shape it was written in. A string other
9364
* than `all` or `some` is a pattern, as the minifier reads it.
@@ -199,7 +170,7 @@ const jsMinify = async (
199170
/** @type {MinifyOptions} */
200171
const minifyOptions = {
201172
...options,
202-
...(as === undefined ? undefined : { module: as === "module" }),
173+
...(as === undefined ? undefined : { sourceType: as }),
203174
compress,
204175
mangle:
205176
options.mangle === undefined || options.mangle === null
@@ -219,21 +190,7 @@ const jsMinify = async (
219190

220191
const [[file, given]] = Object.entries(input);
221192
const code = typeof given === "string" ? given : given.toString("utf8");
222-
const handler = as === "event-handler";
223-
const result = await minifier.minify(
224-
{ [file]: handler ? asFunction(code) : code },
225-
minifyOptions
226-
);
227-
228-
if (handler) {
229-
const body = functionBody(result.code);
230-
// A wrap moves every position, so the map written describes a script
231-
// that is not what comes back.
232-
return {
233-
code: body === undefined ? code : body,
234-
extractedComments: extracted
235-
};
236-
}
193+
const result = await minifier.minify({ [file]: code }, minifyOptions);
237194

238195
return {
239196
code: /** @type {string} */ (result.code),

0 commit comments

Comments
 (0)