@depup/webpack 5.106.0-depup.0 → 5.109.0-depup.0

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.
Files changed (667) hide show
  1. package/README.md +9 -11
  2. package/changes.json +16 -24
  3. package/hot/dev-server.js +2 -0
  4. package/lib/APIPlugin.js +60 -35
  5. package/lib/AsyncDependenciesBlock.js +3 -0
  6. package/lib/AutomaticPrefetchPlugin.js +6 -1
  7. package/lib/BannerPlugin.js +13 -5
  8. package/lib/Cache.js +27 -5
  9. package/lib/CacheFacade.js +41 -0
  10. package/lib/Chunk.js +71 -25
  11. package/lib/ChunkGraph.js +141 -9
  12. package/lib/ChunkGroup.js +115 -28
  13. package/lib/ChunkTemplate.js +9 -0
  14. package/lib/CircularModulesPlugin.js +190 -0
  15. package/lib/CleanPlugin.js +23 -26
  16. package/lib/CodeGenerationResults.js +19 -0
  17. package/lib/CompatibilityPlugin.js +54 -37
  18. package/lib/Compilation.js +635 -107
  19. package/lib/Compiler.js +93 -31
  20. package/lib/ConcatenationScope.js +34 -4
  21. package/lib/ConditionalInitFragment.js +6 -0
  22. package/lib/ConstPlugin.js +15 -12
  23. package/lib/ContextExclusionPlugin.js +3 -1
  24. package/lib/ContextModule.js +345 -55
  25. package/lib/ContextModuleFactory.js +193 -51
  26. package/lib/ContextReplacementPlugin.js +8 -1
  27. package/lib/DefinePlugin.js +498 -127
  28. package/lib/DependenciesBlock.js +6 -1
  29. package/lib/Dependency.js +159 -11
  30. package/lib/DependencyTemplate.js +7 -1
  31. package/lib/DependencyTemplates.js +4 -0
  32. package/lib/DotenvPlugin.js +3 -0
  33. package/lib/DynamicEntryPlugin.js +3 -1
  34. package/lib/EntryOptionPlugin.js +42 -2
  35. package/lib/EntryPlugin.js +4 -1
  36. package/lib/Entrypoint.js +5 -1
  37. package/lib/EnvironmentPlugin.js +3 -2
  38. package/lib/ErrorHelpers.js +7 -0
  39. package/lib/EvalDevToolModulePlugin.js +3 -1
  40. package/lib/EvalSourceMapDevToolPlugin.js +11 -11
  41. package/lib/ExportsInfo.js +399 -108
  42. package/lib/ExportsInfoApiPlugin.js +4 -3
  43. package/lib/ExternalModule.js +376 -78
  44. package/lib/ExternalModuleFactoryPlugin.js +75 -3
  45. package/lib/ExternalsPlugin.js +3 -1
  46. package/lib/FileSystemInfo.js +575 -149
  47. package/lib/FlagAllModulesAsUsedPlugin.js +3 -6
  48. package/lib/FlagDependencyExportsPlugin.js +82 -9
  49. package/lib/FlagDependencyUsagePlugin.js +92 -6
  50. package/lib/FlagEntryExportAsUsedPlugin.js +4 -1
  51. package/lib/Generator.js +24 -3
  52. package/lib/HotModuleReplacementPlugin.js +110 -44
  53. package/lib/IgnorePlugin.js +5 -2
  54. package/lib/IgnoreWarningsPlugin.js +2 -1
  55. package/lib/InitFragment.js +15 -0
  56. package/lib/JavascriptMetaInfoPlugin.js +9 -6
  57. package/lib/LazyBarrel.js +389 -0
  58. package/lib/LibraryTemplatePlugin.js +2 -1
  59. package/lib/LoaderOptionsPlugin.js +3 -1
  60. package/lib/LoaderTargetPlugin.js +3 -1
  61. package/lib/MainTemplate.js +15 -0
  62. package/lib/ManifestPlugin.js +9 -2
  63. package/lib/Module.js +121 -60
  64. package/lib/ModuleFactory.js +6 -1
  65. package/lib/ModuleFilenameHelpers.js +5 -2
  66. package/lib/ModuleGraph.js +69 -2
  67. package/lib/ModuleGraphConnection.js +9 -0
  68. package/lib/ModuleInfoHeaderPlugin.js +5 -0
  69. package/lib/ModuleNotFoundError.js +3 -83
  70. package/lib/ModuleProfile.js +27 -1
  71. package/lib/ModuleSourceTypeConstants.js +52 -19
  72. package/lib/ModuleTemplate.js +10 -0
  73. package/lib/ModuleTypeConstants.js +20 -4
  74. package/lib/MultiCompiler.js +59 -4
  75. package/lib/MultiStats.js +9 -0
  76. package/lib/MultiWatching.js +6 -0
  77. package/lib/NoEmitOnErrorsPlugin.js +1 -1
  78. package/lib/NodeStuffPlugin.js +78 -46
  79. package/lib/NormalModule.js +485 -181
  80. package/lib/NormalModuleFactory.js +148 -29
  81. package/lib/NormalModuleReplacementPlugin.js +3 -1
  82. package/lib/NullFactory.js +1 -0
  83. package/lib/OptionsApply.js +1 -0
  84. package/lib/Parser.js +3 -1
  85. package/lib/PlatformPlugin.js +2 -1
  86. package/lib/PrefetchPlugin.js +4 -1
  87. package/lib/ProgressPlugin.js +351 -161
  88. package/lib/ProvidePlugin.js +6 -3
  89. package/lib/RawModule.js +32 -16
  90. package/lib/RecordIdsPlugin.js +9 -0
  91. package/lib/RequestShortener.js +8 -0
  92. package/lib/ResolverFactory.js +5 -0
  93. package/lib/RuntimeGlobals.js +58 -5
  94. package/lib/RuntimeModule.js +22 -7
  95. package/lib/RuntimePlugin.js +104 -26
  96. package/lib/RuntimeTemplate.js +616 -37
  97. package/lib/SelfModuleFactory.js +3 -0
  98. package/lib/SourceMapDevToolModuleOptionsPlugin.js +2 -0
  99. package/lib/SourceMapDevToolPlugin.js +341 -63
  100. package/lib/Stats.js +6 -0
  101. package/lib/Template.js +29 -3
  102. package/lib/TemplatedPathPlugin.js +505 -138
  103. package/lib/UseStrictPlugin.js +3 -2
  104. package/lib/WarnCaseSensitiveModulesPlugin.js +72 -3
  105. package/lib/WarnDeprecatedOptionPlugin.js +6 -2
  106. package/lib/WarnNoModeSetPlugin.js +18 -2
  107. package/lib/WatchIgnorePlugin.js +5 -1
  108. package/lib/Watching.js +25 -3
  109. package/lib/WebpackError.js +3 -74
  110. package/lib/WebpackIsIncludedPlugin.js +4 -2
  111. package/lib/WebpackOptionsApply.js +88 -25
  112. package/lib/WebpackOptionsDefaulter.js +1 -0
  113. package/lib/asset/AssetBytesGenerator.js +28 -10
  114. package/lib/asset/AssetBytesParser.js +1 -0
  115. package/lib/asset/AssetGenerator.js +199 -60
  116. package/lib/asset/AssetModule.js +47 -0
  117. package/lib/asset/AssetModulesPlugin.js +115 -24
  118. package/lib/asset/AssetParser.js +4 -2
  119. package/lib/asset/AssetSourceGenerator.js +26 -8
  120. package/lib/asset/AssetSourceParser.js +1 -0
  121. package/lib/asset/RawDataUrlModule.js +23 -13
  122. package/lib/asset/WebManifestGenerator.js +164 -0
  123. package/lib/asset/WebManifestParser.js +130 -0
  124. package/lib/async-modules/AsyncModuleHelpers.js +1 -0
  125. package/lib/async-modules/AwaitDependenciesInitFragment.js +18 -4
  126. package/lib/async-modules/InferAsyncModulesPlugin.js +1 -1
  127. package/lib/async-modules/isGeneratorLowered.js +26 -0
  128. package/lib/buildChunkGraph.js +107 -15
  129. package/lib/bun/BunTargetPlugin.js +42 -0
  130. package/lib/cache/AddBuildDependenciesPlugin.js +3 -1
  131. package/lib/cache/AddManagedPathsPlugin.js +5 -1
  132. package/lib/cache/IdleFileCachePlugin.js +6 -1
  133. package/lib/cache/MemoryCachePlugin.js +1 -1
  134. package/lib/cache/MemoryWithGcCachePlugin.js +4 -1
  135. package/lib/cache/PackFileCacheStrategy.js +43 -7
  136. package/lib/cache/ResolverCachePlugin.js +12 -1
  137. package/lib/cache/getLazyHashedEtag.js +13 -2
  138. package/lib/cache/mergeEtags.js +4 -0
  139. package/lib/cli.js +142 -20
  140. package/lib/config/browserslistTargetHandler.js +141 -0
  141. package/lib/config/defaults.js +591 -41
  142. package/lib/config/defineConfig.js +31 -0
  143. package/lib/config/normalization.js +46 -1
  144. package/lib/config/target.js +200 -2
  145. package/lib/container/ContainerEntryDependency.js +2 -0
  146. package/lib/container/ContainerEntryModule.js +27 -14
  147. package/lib/container/ContainerEntryModuleFactory.js +1 -0
  148. package/lib/container/ContainerExposedDependency.js +6 -2
  149. package/lib/container/ContainerPlugin.js +2 -1
  150. package/lib/container/ContainerReferencePlugin.js +3 -2
  151. package/lib/container/FallbackDependency.js +9 -7
  152. package/lib/container/FallbackItemDependency.js +1 -0
  153. package/lib/container/FallbackModule.js +22 -9
  154. package/lib/container/FallbackModuleFactory.js +1 -0
  155. package/lib/container/ModuleFederationPlugin.js +12 -26
  156. package/lib/container/RemoteModule.js +33 -10
  157. package/lib/container/RemoteRuntimeModule.js +15 -12
  158. package/lib/container/RemoteToExternalDependency.js +1 -0
  159. package/lib/container/options.js +7 -0
  160. package/lib/css/CssGenerator.js +534 -272
  161. package/lib/css/CssInjectStyleRuntimeModule.js +86 -70
  162. package/lib/css/CssLoadingRuntimeModule.js +156 -77
  163. package/lib/{CssModule.js → css/CssModule.js} +72 -37
  164. package/lib/css/CssModulesPlugin.js +356 -204
  165. package/lib/css/CssParser.js +3452 -1950
  166. package/lib/css/syntax.js +4058 -0
  167. package/lib/debug/ProfilingPlugin.js +33 -2
  168. package/lib/deno/DenoTargetPlugin.js +41 -0
  169. package/lib/dependencies/AMDDefineDependency.js +29 -17
  170. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +19 -6
  171. package/lib/dependencies/AMDPlugin.js +6 -3
  172. package/lib/dependencies/AMDRequireArrayDependency.js +13 -11
  173. package/lib/dependencies/AMDRequireContextDependency.js +10 -11
  174. package/lib/dependencies/AMDRequireDependenciesBlock.js +1 -0
  175. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +28 -14
  176. package/lib/dependencies/AMDRequireDependency.js +28 -20
  177. package/lib/dependencies/AMDRequireItemDependency.js +1 -0
  178. package/lib/dependencies/AMDRuntimeModules.js +3 -0
  179. package/lib/dependencies/CachedConstDependency.js +9 -1
  180. package/lib/dependencies/CommonJsDependencyHelpers.js +104 -0
  181. package/lib/dependencies/CommonJsExportRequireDependency.js +138 -38
  182. package/lib/dependencies/CommonJsExportsDependency.js +74 -20
  183. package/lib/dependencies/CommonJsExportsParserPlugin.js +246 -15
  184. package/lib/dependencies/CommonJsFullRequireDependency.js +62 -27
  185. package/lib/dependencies/CommonJsImportsParserPlugin.js +187 -24
  186. package/lib/dependencies/CommonJsPlugin.js +7 -4
  187. package/lib/dependencies/CommonJsRequireContextDependency.js +13 -13
  188. package/lib/dependencies/CommonJsRequireDependency.js +135 -13
  189. package/lib/dependencies/CommonJsSelfReferenceDependency.js +60 -16
  190. package/lib/dependencies/ConstDependency.js +22 -12
  191. package/lib/dependencies/ContextDependency.js +13 -2
  192. package/lib/dependencies/ContextDependencyHelpers.js +7 -4
  193. package/lib/dependencies/ContextDependencyTemplateAsId.js +2 -1
  194. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +1 -0
  195. package/lib/dependencies/ContextElementDependency.js +27 -14
  196. package/lib/dependencies/CreateRequireParserPlugin.js +14 -7
  197. package/lib/dependencies/CreateScriptUrlDependency.js +9 -7
  198. package/lib/dependencies/CriticalDependencyWarning.js +3 -1
  199. package/lib/dependencies/CssIcssExportDependency.js +682 -368
  200. package/lib/dependencies/CssIcssImportDependency.js +62 -17
  201. package/lib/dependencies/CssIcssSymbolDependency.js +36 -17
  202. package/lib/dependencies/CssImportDependency.js +37 -1
  203. package/lib/dependencies/CssUrlDependency.js +87 -14
  204. package/lib/dependencies/DelegatedSourceDependency.js +1 -0
  205. package/lib/dependencies/DllEntryDependency.js +12 -13
  206. package/lib/dependencies/DynamicExports.js +5 -0
  207. package/lib/dependencies/EntryDependency.js +1 -0
  208. package/lib/dependencies/ExportBindingInitFragment.js +164 -0
  209. package/lib/dependencies/ExportsInfoDependency.js +18 -12
  210. package/lib/dependencies/ExternalModuleDependency.js +13 -5
  211. package/lib/dependencies/ExternalModuleInitFragment.js +10 -5
  212. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +19 -12
  213. package/lib/dependencies/HarmonyAcceptDependency.js +24 -26
  214. package/lib/dependencies/HarmonyAcceptImportDependency.js +2 -0
  215. package/lib/dependencies/HarmonyCompatibilityDependency.js +33 -14
  216. package/lib/dependencies/HarmonyDetectionParserPlugin.js +108 -30
  217. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +32 -2
  218. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +70 -33
  219. package/lib/dependencies/HarmonyExportExpressionDependency.js +140 -46
  220. package/lib/dependencies/HarmonyExportHeaderDependency.js +11 -9
  221. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +253 -37
  222. package/lib/dependencies/HarmonyExportInitFragment.js +28 -20
  223. package/lib/dependencies/HarmonyExportSpecifierDependency.js +88 -18
  224. package/lib/dependencies/HarmonyExports.js +6 -1
  225. package/lib/dependencies/HarmonyImportDependency.js +59 -3
  226. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +139 -146
  227. package/lib/dependencies/HarmonyImportGuard.js +426 -0
  228. package/lib/dependencies/HarmonyImportSideEffectDependency.js +22 -1
  229. package/lib/dependencies/HarmonyImportSpecifierDependency.js +136 -17
  230. package/lib/{HarmonyLinkingError.js → dependencies/HarmonyLinkingError.js} +6 -3
  231. package/lib/dependencies/HarmonyModulesPlugin.js +11 -1
  232. package/lib/dependencies/HarmonyTopLevelThisParserPlugin.js +2 -1
  233. package/lib/dependencies/HtmlEntryDependency.js +1295 -0
  234. package/lib/dependencies/HtmlInlineHtmlDependency.js +107 -0
  235. package/lib/dependencies/HtmlInlineScriptDependency.js +126 -0
  236. package/lib/dependencies/HtmlInlineStyleDependency.js +152 -0
  237. package/lib/dependencies/HtmlSourceDependency.js +172 -0
  238. package/lib/dependencies/ImportContextDependency.js +9 -9
  239. package/lib/dependencies/ImportDependency.js +92 -3
  240. package/lib/dependencies/ImportEagerDependency.js +2 -0
  241. package/lib/dependencies/ImportMetaContextDependency.js +1 -0
  242. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +35 -19
  243. package/lib/dependencies/ImportMetaContextPlugin.js +40 -8
  244. package/lib/dependencies/ImportMetaGlobDependency.js +81 -0
  245. package/lib/dependencies/ImportMetaGlobDependencyParserPlugin.js +78 -0
  246. package/lib/dependencies/ImportMetaGlobHelpers.js +660 -0
  247. package/lib/dependencies/ImportMetaHotAcceptDependency.js +2 -0
  248. package/lib/dependencies/ImportMetaHotDeclineDependency.js +2 -0
  249. package/lib/dependencies/ImportMetaPlugin.js +595 -209
  250. package/lib/dependencies/ImportMetaResolveDependency.js +90 -0
  251. package/lib/dependencies/ImportParserPlugin.js +114 -27
  252. package/lib/dependencies/ImportPhase.js +17 -11
  253. package/lib/dependencies/ImportPlugin.js +2 -1
  254. package/lib/dependencies/ImportWeakDependency.js +3 -0
  255. package/lib/dependencies/JsonExportsDependency.js +15 -10
  256. package/lib/dependencies/LoaderDependency.js +2 -0
  257. package/lib/dependencies/LoaderImportDependency.js +3 -0
  258. package/lib/dependencies/LoaderPlugin.js +9 -2
  259. package/lib/dependencies/LocalModule.js +15 -12
  260. package/lib/dependencies/LocalModuleDependency.js +15 -13
  261. package/lib/dependencies/LocalModulesHelpers.js +3 -0
  262. package/lib/dependencies/ModuleDecoratorDependency.js +16 -10
  263. package/lib/dependencies/ModuleDependency.js +14 -0
  264. package/lib/dependencies/ModuleDependencyTemplateAsId.js +1 -0
  265. package/lib/dependencies/ModuleDependencyTemplateAsRequireId.js +1 -0
  266. package/lib/dependencies/ModuleHotAcceptDependency.js +2 -0
  267. package/lib/dependencies/ModuleHotDeclineDependency.js +2 -0
  268. package/lib/dependencies/ModuleInitFragmentDependency.js +19 -11
  269. package/lib/dependencies/NullDependency.js +2 -0
  270. package/lib/dependencies/PrefetchDependency.js +1 -0
  271. package/lib/dependencies/ProvidedDependency.js +36 -27
  272. package/lib/dependencies/PureExpressionDependency.js +14 -10
  273. package/lib/dependencies/RequireContextDependency.js +1 -0
  274. package/lib/dependencies/RequireContextDependencyParserPlugin.js +2 -1
  275. package/lib/dependencies/RequireContextPlugin.js +2 -1
  276. package/lib/dependencies/RequireEnsureDependenciesBlock.js +1 -0
  277. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +4 -6
  278. package/lib/dependencies/RequireEnsureDependency.js +16 -13
  279. package/lib/dependencies/RequireEnsureItemDependency.js +1 -0
  280. package/lib/dependencies/RequireEnsurePlugin.js +2 -1
  281. package/lib/dependencies/RequireHeaderDependency.js +7 -4
  282. package/lib/dependencies/RequireIncludeDependency.js +2 -0
  283. package/lib/dependencies/RequireIncludeDependencyParserPlugin.js +11 -12
  284. package/lib/dependencies/RequireIncludePlugin.js +2 -1
  285. package/lib/{RequireJsStuffPlugin.js → dependencies/RequireJsStuffPlugin.js} +9 -8
  286. package/lib/dependencies/RequireResolveContextDependency.js +10 -11
  287. package/lib/dependencies/RequireResolveDependency.js +2 -0
  288. package/lib/dependencies/RequireResolveHeaderDependency.js +8 -5
  289. package/lib/dependencies/RuntimeRequirementsDependency.js +11 -8
  290. package/lib/dependencies/StaticExportsDependency.js +13 -10
  291. package/lib/dependencies/SystemPlugin.js +9 -6
  292. package/lib/dependencies/SystemRuntimeModule.js +1 -0
  293. package/lib/dependencies/TopLevelAwaitDependency.js +93 -0
  294. package/lib/dependencies/URLContextDependency.js +8 -7
  295. package/lib/dependencies/URLDependency.js +157 -33
  296. package/lib/dependencies/URLPlugin.js +2 -0
  297. package/lib/dependencies/UnsupportedDependency.js +12 -13
  298. package/lib/dependencies/WebAssemblyExportImportedDependency.js +15 -16
  299. package/lib/dependencies/WebAssemblyImportDependency.js +19 -18
  300. package/lib/dependencies/WebpackIsIncludedDependency.js +3 -0
  301. package/lib/dependencies/{WorkerPlugin.js → WorkerAndWorkletPlugin.js} +364 -114
  302. package/lib/dependencies/WorkerDependency.js +111 -27
  303. package/lib/dependencies/WorkletDependency.js +278 -0
  304. package/lib/dependencies/getFunctionExpression.js +1 -0
  305. package/lib/dependencies/processExportInfo.js +14 -11
  306. package/lib/{DelegatedModule.js → dll/DelegatedModule.js} +71 -44
  307. package/lib/{DelegatedModuleFactoryPlugin.js → dll/DelegatedModuleFactoryPlugin.js} +27 -4
  308. package/lib/{DelegatedPlugin.js → dll/DelegatedPlugin.js} +5 -3
  309. package/lib/{DllEntryPlugin.js → dll/DllEntryPlugin.js} +9 -5
  310. package/lib/{DllModule.js → dll/DllModule.js} +36 -24
  311. package/lib/{DllModuleFactory.js → dll/DllModuleFactory.js} +5 -4
  312. package/lib/{DllPlugin.js → dll/DllPlugin.js} +24 -6
  313. package/lib/{DllReferencePlugin.js → dll/DllReferencePlugin.js} +26 -18
  314. package/lib/{LibManifestPlugin.js → dll/LibManifestPlugin.js} +14 -10
  315. package/lib/electron/ElectronTargetPlugin.js +24 -5
  316. package/lib/{AbstractMethodError.js → errors/AbstractMethodError.js} +10 -1
  317. package/lib/{AsyncDependencyToInitialChunkError.js → errors/AsyncDependencyToInitialChunkError.js} +8 -3
  318. package/lib/errors/BuildCycleError.js +1 -1
  319. package/lib/{ChunkRenderError.js → errors/ChunkRenderError.js} +1 -1
  320. package/lib/{CodeGenerationError.js → errors/CodeGenerationError.js} +1 -1
  321. package/lib/{CommentCompilationWarning.js → errors/CommentCompilationWarning.js} +9 -3
  322. package/lib/{ConcurrentCompilationError.js → errors/ConcurrentCompilationError.js} +5 -2
  323. package/lib/{EnvironmentNotSupportAsyncWarning.js → errors/EnvironmentNotSupportAsyncWarning.js} +5 -5
  324. package/lib/{HookWebpackError.js → errors/HookWebpackError.js} +20 -16
  325. package/lib/{IgnoreErrorModuleFactory.js → errors/IgnoreErrorModuleFactory.js} +7 -4
  326. package/lib/{InvalidDependenciesModuleWarning.js → errors/InvalidDependenciesModuleWarning.js} +6 -3
  327. package/lib/errors/JSONParseError.js +115 -0
  328. package/lib/errors/LoaderLoadingError.js +20 -0
  329. package/lib/{ModuleBuildError.js → errors/ModuleBuildError.js} +22 -16
  330. package/lib/{ModuleDependencyError.js → errors/ModuleDependencyError.js} +10 -3
  331. package/lib/{ModuleDependencyWarning.js → errors/ModuleDependencyWarning.js} +13 -5
  332. package/lib/{ModuleError.js → errors/ModuleError.js} +10 -14
  333. package/lib/{ModuleHashingError.js → errors/ModuleHashingError.js} +5 -1
  334. package/lib/errors/ModuleNotFoundError.js +94 -0
  335. package/lib/errors/ModuleParseError.js +141 -0
  336. package/lib/{ModuleRestoreError.js → errors/ModuleRestoreError.js} +4 -1
  337. package/lib/{ModuleStoreError.js → errors/ModuleStoreError.js} +5 -1
  338. package/lib/{ModuleWarning.js → errors/ModuleWarning.js} +13 -14
  339. package/lib/{NodeStuffInWebError.js → errors/NodeStuffInWebError.js} +7 -5
  340. package/lib/errors/NonErrorEmittedError.js +30 -0
  341. package/lib/{UnhandledSchemeError.js → errors/UnhandledSchemeError.js} +9 -2
  342. package/lib/{UnsupportedFeatureWarning.js → errors/UnsupportedFeatureWarning.js} +4 -3
  343. package/lib/errors/WebpackError.js +84 -0
  344. package/lib/esm/ExportWebpackRequireRuntimeModule.js +2 -0
  345. package/lib/esm/ModuleChunkFormatPlugin.js +52 -15
  346. package/lib/esm/ModuleChunkLoadingPlugin.js +11 -3
  347. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +71 -49
  348. package/lib/hmr/HotModuleReplacement.runtime.js +175 -30
  349. package/lib/hmr/HotModuleReplacementRuntimeModule.js +8 -0
  350. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +173 -26
  351. package/lib/hmr/JavascriptHotModuleReplacementHelper.js +1 -0
  352. package/lib/hmr/LazyCompilationPlugin.js +154 -7
  353. package/lib/hmr/lazyCompilationBackend.js +34 -8
  354. package/lib/html/HtmlGenerator.js +1470 -0
  355. package/lib/html/HtmlModule.js +41 -0
  356. package/lib/html/HtmlModulesPlugin.js +1111 -0
  357. package/lib/html/HtmlParser.js +1970 -0
  358. package/lib/html/favicon.svg +1 -0
  359. package/lib/html/syntax.js +9020 -0
  360. package/lib/ids/ChunkModuleIdRangePlugin.js +3 -1
  361. package/lib/ids/DeterministicChunkIdsPlugin.js +3 -1
  362. package/lib/ids/DeterministicModuleIdsPlugin.js +3 -1
  363. package/lib/ids/HashedModuleIdsPlugin.js +2 -1
  364. package/lib/ids/IdHelpers.js +25 -2
  365. package/lib/ids/NamedChunkIdsPlugin.js +3 -1
  366. package/lib/ids/NamedModuleIdsPlugin.js +3 -1
  367. package/lib/ids/NaturalChunkIdsPlugin.js +1 -1
  368. package/lib/ids/NaturalModuleIdsPlugin.js +1 -1
  369. package/lib/ids/OccurrenceChunkIdsPlugin.js +2 -1
  370. package/lib/ids/OccurrenceModuleIdsPlugin.js +4 -1
  371. package/lib/ids/SyncModuleIdsPlugin.js +3 -1
  372. package/lib/index.js +66 -15
  373. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +5 -6
  374. package/lib/javascript/BasicEvaluatedExpression.js +370 -49
  375. package/lib/javascript/ChunkFormatHelpers.js +2 -1
  376. package/lib/javascript/ChunkHelpers.js +1 -0
  377. package/lib/javascript/CommonJsChunkFormatPlugin.js +1 -1
  378. package/lib/javascript/EnableChunkLoadingPlugin.js +6 -1
  379. package/lib/javascript/JavascriptGenerator.js +213 -51
  380. package/lib/javascript/JavascriptModule.js +54 -0
  381. package/lib/javascript/JavascriptModulesPlugin.js +579 -183
  382. package/lib/javascript/JavascriptParser.js +1289 -462
  383. package/lib/javascript/JavascriptParserHelpers.js +10 -7
  384. package/lib/javascript/StartupHelpers.js +5 -0
  385. package/lib/javascript/syntax.js +4380 -0
  386. package/lib/json/JsonData.js +5 -0
  387. package/lib/json/JsonGenerator.js +21 -0
  388. package/lib/json/JsonModule.js +40 -0
  389. package/lib/json/JsonModulesPlugin.js +8 -1
  390. package/lib/json/JsonParser.js +18 -27
  391. package/lib/library/AbstractLibraryPlugin.js +17 -2
  392. package/lib/library/AmdLibraryPlugin.js +8 -0
  393. package/lib/library/AssignLibraryPlugin.js +21 -3
  394. package/lib/library/EnableLibraryPlugin.js +8 -2
  395. package/lib/library/ExportPropertyLibraryPlugin.js +10 -0
  396. package/lib/{FalseIIFEUmdWarning.js → library/FalseIIFEUmdWarning.js} +2 -1
  397. package/lib/library/JsonpLibraryPlugin.js +8 -0
  398. package/lib/library/ModuleLibraryPlugin.js +154 -7
  399. package/lib/library/SystemLibraryPlugin.js +11 -3
  400. package/lib/library/UmdLibraryPlugin.js +16 -0
  401. package/lib/loaders/LoaderRunner.js +714 -0
  402. package/lib/loaders/loadLoader.js +100 -0
  403. package/lib/logging/Logger.js +17 -0
  404. package/lib/logging/createConsoleLogger.js +7 -0
  405. package/lib/logging/runtime.js +2 -0
  406. package/lib/logging/truncateArgs.js +2 -0
  407. package/lib/node/CommonJsChunkLoadingPlugin.js +5 -1
  408. package/lib/node/NodeEnvironmentPlugin.js +7 -3
  409. package/lib/node/NodeSourcePlugin.js +1 -1
  410. package/lib/node/NodeTargetPlugin.js +4 -63
  411. package/lib/node/NodeTemplatePlugin.js +3 -1
  412. package/lib/node/NodeWatchFileSystem.js +40 -22
  413. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +13 -9
  414. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +23 -1
  415. package/lib/node/ReadFileCompileWasmPlugin.js +18 -1
  416. package/lib/node/RequireChunkLoadingRuntimeModule.js +21 -16
  417. package/lib/node/nodeBuiltins.js +80 -0
  418. package/lib/node/nodeConsole.js +116 -64
  419. package/lib/optimize/AggressiveMergingPlugin.js +3 -1
  420. package/lib/optimize/AggressiveSplittingPlugin.js +6 -1
  421. package/lib/optimize/ConcatenatedModule.js +585 -116
  422. package/lib/optimize/ConstExportsPlugin.js +211 -0
  423. package/lib/optimize/EnsureChunkConditionsPlugin.js +2 -1
  424. package/lib/optimize/FlagIncludedChunksPlugin.js +15 -4
  425. package/lib/optimize/InlineExports.js +178 -0
  426. package/lib/optimize/InnerGraph.js +374 -262
  427. package/lib/optimize/InnerGraphPlugin.js +246 -117
  428. package/lib/optimize/LimitChunkCountPlugin.js +9 -0
  429. package/lib/optimize/MangleExportsPlugin.js +5 -1
  430. package/lib/optimize/MergeDuplicateChunksPlugin.js +2 -0
  431. package/lib/optimize/MinChunkSizePlugin.js +2 -1
  432. package/lib/optimize/MinMaxSizeWarning.js +5 -4
  433. package/lib/optimize/ModuleConcatenationPlugin.js +159 -34
  434. package/lib/optimize/RealContentHashPlugin.js +125 -50
  435. package/lib/optimize/RemoveEmptyChunksPlugin.js +2 -1
  436. package/lib/optimize/RemoveParentModulesPlugin.js +3 -1
  437. package/lib/optimize/RuntimeChunkPlugin.js +2 -1
  438. package/lib/optimize/SideEffectsFlagPlugin.js +381 -55
  439. package/lib/optimize/SplitChunksPlugin.js +54 -6
  440. package/lib/performance/AssetsOverSizeLimitWarning.js +3 -2
  441. package/lib/performance/EntrypointsOverSizeLimitWarning.js +3 -2
  442. package/lib/performance/NoAsyncChunksWarning.js +5 -3
  443. package/lib/performance/SizeLimitsPlugin.js +8 -2
  444. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +1 -0
  445. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +21 -0
  446. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +1 -0
  447. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +5 -1
  448. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +25 -13
  449. package/lib/prefetch/ResourceHintPlugin.js +663 -0
  450. package/lib/prefetch/ResourceHintRuntimeModule.js +149 -0
  451. package/lib/prefetch/StartupAssetHintRuntimeModule.js +210 -0
  452. package/lib/prefetch/parseResourceHintOptions.js +103 -0
  453. package/lib/rules/BasicEffectRulePlugin.js +3 -0
  454. package/lib/rules/BasicMatcherRulePlugin.js +3 -0
  455. package/lib/rules/ObjectMatcherRulePlugin.js +3 -0
  456. package/lib/rules/RuleSetCompiler.js +132 -0
  457. package/lib/rules/UseEffectRulePlugin.js +10 -3
  458. package/lib/runtime/AsyncModuleGeneratorRuntimeModule.js +56 -0
  459. package/lib/runtime/AsyncModuleRuntimeModule.js +52 -33
  460. package/lib/runtime/AutoPublicPathRuntimeModule.js +22 -9
  461. package/lib/runtime/BaseUriRuntimeModule.js +1 -0
  462. package/lib/runtime/ChunkNameRuntimeModule.js +1 -0
  463. package/lib/runtime/CommonJsWrapRuntimeModule.js +37 -0
  464. package/lib/runtime/CompatGetDefaultExportRuntimeModule.js +2 -1
  465. package/lib/runtime/CompatRuntimeModule.js +2 -0
  466. package/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +7 -4
  467. package/lib/runtime/CreateScriptRuntimeModule.js +1 -0
  468. package/lib/runtime/CreateScriptUrlRuntimeModule.js +1 -0
  469. package/lib/runtime/DefinePropertyGettersRuntimeModule.js +34 -4
  470. package/lib/runtime/EnsureChunkRuntimeModule.js +1 -0
  471. package/lib/runtime/GetChunkFilenameRuntimeModule.js +88 -8
  472. package/lib/runtime/GetFullHashRuntimeModule.js +1 -0
  473. package/lib/runtime/GetMainFilenameRuntimeModule.js +1 -0
  474. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +2 -1
  475. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +59 -0
  476. package/lib/runtime/GlobalRuntimeModule.js +1 -0
  477. package/lib/runtime/HasOwnPropertyRuntimeModule.js +2 -1
  478. package/lib/runtime/HelperRuntimeModule.js +5 -0
  479. package/lib/runtime/LoadScriptRuntimeModule.js +28 -37
  480. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +354 -37
  481. package/lib/runtime/MakeNamespaceObjectRuntimeModule.js +2 -1
  482. package/lib/runtime/NonceRuntimeModule.js +1 -0
  483. package/lib/runtime/OnChunksLoadedRuntimeModule.js +5 -4
  484. package/lib/runtime/PublicPathRuntimeModule.js +1 -0
  485. package/lib/runtime/RelativeUrlRuntimeModule.js +4 -2
  486. package/lib/runtime/RuntimeIdRuntimeModule.js +1 -0
  487. package/lib/runtime/SetAnonymousDefaultNameRuntimeModule.js +38 -0
  488. package/lib/runtime/StartupChunkDependenciesPlugin.js +13 -1
  489. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +2 -1
  490. package/lib/runtime/StartupEntrypointRuntimeModule.js +5 -3
  491. package/lib/runtime/SystemContextRuntimeModule.js +1 -0
  492. package/lib/runtime/ToBinaryRuntimeModule.js +1 -0
  493. package/lib/runtime/WorkerRuntimeModule.js +33 -0
  494. package/lib/schemes/DataUriPlugin.js +14 -2
  495. package/lib/schemes/FileUriPlugin.js +1 -1
  496. package/lib/schemes/HttpUriPlugin.js +86 -4
  497. package/lib/schemes/VirtualUrlPlugin.js +8 -4
  498. package/lib/serialization/AggregateErrorSerializer.js +9 -6
  499. package/lib/serialization/ArraySerializer.js +6 -8
  500. package/lib/serialization/BinaryMiddleware.js +552 -463
  501. package/lib/serialization/DateObjectSerializer.js +4 -2
  502. package/lib/serialization/ErrorObjectSerializer.js +10 -6
  503. package/lib/serialization/FileMiddleware.js +50 -3
  504. package/lib/serialization/MapObjectSerializer.js +7 -9
  505. package/lib/serialization/NullPrototypeObjectSerializer.js +9 -9
  506. package/lib/serialization/ObjectMiddleware.js +73 -13
  507. package/lib/serialization/PlainObjectSerializer.js +16 -8
  508. package/lib/serialization/RegExpObjectSerializer.js +4 -2
  509. package/lib/serialization/Serializer.js +6 -0
  510. package/lib/serialization/SerializerMiddleware.js +14 -2
  511. package/lib/serialization/SetObjectSerializer.js +6 -8
  512. package/lib/serialization/SingleItemMiddleware.js +3 -0
  513. package/lib/sharing/ConsumeSharedFallbackDependency.js +1 -0
  514. package/lib/sharing/ConsumeSharedModule.js +21 -7
  515. package/lib/sharing/ConsumeSharedPlugin.js +11 -11
  516. package/lib/sharing/ConsumeSharedRuntimeModule.js +55 -45
  517. package/lib/sharing/ProvideForSharedDependency.js +1 -0
  518. package/lib/sharing/ProvideSharedDependency.js +34 -15
  519. package/lib/sharing/ProvideSharedModule.js +42 -12
  520. package/lib/sharing/ProvideSharedModuleFactory.js +1 -0
  521. package/lib/sharing/ProvideSharedPlugin.js +13 -8
  522. package/lib/sharing/SharePlugin.js +5 -1
  523. package/lib/sharing/ShareRuntimeModule.js +19 -16
  524. package/lib/sharing/resolveMatchedConfigs.js +6 -2
  525. package/lib/sharing/utils.js +9 -1
  526. package/lib/stats/DefaultStatsFactoryPlugin.js +94 -12
  527. package/lib/stats/DefaultStatsPresetPlugin.js +14 -2
  528. package/lib/stats/DefaultStatsPrinterPlugin.js +64 -18
  529. package/lib/stats/StatsFactory.js +39 -18
  530. package/lib/stats/StatsPrinter.js +16 -2
  531. package/lib/typescript/TypeScriptPlugin.js +210 -0
  532. package/lib/url/URLParserPlugin.js +111 -23
  533. package/lib/util/ArrayHelpers.js +1 -0
  534. package/lib/util/ArrayQueue.js +10 -5
  535. package/lib/util/AsyncQueue.js +154 -74
  536. package/lib/util/Hash.js +2 -2
  537. package/lib/util/IterableHelpers.js +3 -0
  538. package/lib/util/LazyBucketSortedSet.js +26 -0
  539. package/lib/util/LazySet.js +45 -4
  540. package/lib/util/LocConverter.js +64 -0
  541. package/lib/util/ParallelismFactorCalculator.js +1 -0
  542. package/lib/util/Queue.js +6 -3
  543. package/lib/util/Semaphore.js +15 -1
  544. package/lib/util/SetHelpers.js +4 -1
  545. package/lib/util/SortableSet.js +7 -1
  546. package/lib/util/SourceProcessor.js +119 -0
  547. package/lib/util/StackedCacheMap.js +20 -3
  548. package/lib/util/StackedMap.js +162 -43
  549. package/lib/util/StringXor.js +1 -1
  550. package/lib/util/TupleQueue.js +7 -3
  551. package/lib/util/TupleSet.js +14 -0
  552. package/lib/util/URLAbsoluteSpecifier.js +1 -0
  553. package/lib/util/WeakTupleMap.js +60 -1
  554. package/lib/util/binarySearchBounds.js +3 -2
  555. package/lib/util/chainedImports.js +3 -3
  556. package/lib/util/cleverMerge.js +19 -2
  557. package/lib/util/comparators.js +35 -4
  558. package/lib/util/compileBooleanMatcher.js +9 -0
  559. package/lib/util/concatenate.js +80 -24
  560. package/lib/util/conventions.js +46 -1
  561. package/lib/util/createHash.js +0 -1
  562. package/lib/util/createHooksRegistry.js +43 -0
  563. package/lib/util/createMappings.js +118 -0
  564. package/lib/util/dataURL.js +3 -2
  565. package/lib/util/deprecation.js +19 -0
  566. package/lib/util/deterministicGrouping.js +46 -17
  567. package/lib/util/extractSourceMap.js +2 -1
  568. package/lib/util/extractUrlAndGlobal.js +1 -0
  569. package/lib/util/findGraphRoots.js +7 -0
  570. package/lib/{formatLocation.js → util/formatLocation.js} +4 -2
  571. package/lib/{SizeFormatHelpers.js → util/formatSize.js} +10 -3
  572. package/lib/util/fs.js +87 -14
  573. package/lib/util/generateDebugId.js +1 -0
  574. package/lib/util/globUtils.js +710 -0
  575. package/lib/util/hash/BatchedHash.js +1 -0
  576. package/lib/util/hash/BulkUpdateHash.js +1 -0
  577. package/lib/util/hash/DebugHash.js +1 -0
  578. package/lib/util/hash/hash-digest.js +32 -15
  579. package/lib/util/hash/md4.js +1 -1
  580. package/lib/util/hash/wasm-hash.js +5 -0
  581. package/lib/util/hash/xxhash64.js +1 -1
  582. package/lib/util/identifier.js +97 -6
  583. package/lib/util/implicitTypeLoaderFallback.js +62 -0
  584. package/lib/util/internalSerializables.js +102 -60
  585. package/lib/util/magicComment.js +149 -7
  586. package/lib/util/makeSerializable.js +7 -0
  587. package/lib/util/memoize.js +2 -0
  588. package/lib/util/mimeTypes.js +176 -0
  589. package/lib/util/nonNumericOnlyHash.js +31 -1
  590. package/lib/util/numberHash.js +2 -2
  591. package/lib/util/parseJson.js +41 -0
  592. package/lib/util/processAsyncTree.js +8 -0
  593. package/lib/util/property.js +9 -2
  594. package/lib/util/publicPathPlaceholder.js +64 -0
  595. package/lib/util/registerExternalSerializer.js +24 -4
  596. package/lib/util/removeBOM.js +1 -0
  597. package/lib/util/runtime.js +32 -0
  598. package/lib/util/semver.js +15 -0
  599. package/lib/util/serialization.js +2 -0
  600. package/lib/util/smartGrouping.js +8 -0
  601. package/lib/util/source.js +23 -0
  602. package/lib/util/topologicalSort.js +69 -0
  603. package/lib/validateSchema.js +1 -0
  604. package/lib/wasm/EnableWasmLoadingPlugin.js +15 -1
  605. package/lib/wasm-async/AsyncWasmCompileRuntimeModule.js +25 -18
  606. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +34 -22
  607. package/lib/wasm-async/AsyncWasmModule.js +77 -0
  608. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +6 -0
  609. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +6 -1
  610. package/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js +22 -126
  611. package/lib/wasm-async/AsyncWebAssemblyParser.js +3 -2
  612. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +13 -2
  613. package/lib/wasm-sync/SyncWasmModule.js +39 -0
  614. package/lib/wasm-sync/UnsupportedWebAssemblyFeatureError.js +7 -3
  615. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +86 -19
  616. package/lib/wasm-sync/WasmFinalizeExportsPlugin.js +4 -3
  617. package/lib/wasm-sync/WebAssemblyGenerator.js +27 -1
  618. package/lib/wasm-sync/WebAssemblyInInitialChunkError.js +9 -3
  619. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +4 -0
  620. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +20 -1
  621. package/lib/wasm-sync/WebAssemblyParser.js +9 -3
  622. package/lib/wasm-sync/WebAssemblyUtils.js +2 -0
  623. package/lib/web/FetchCompileAsyncWasmPlugin.js +29 -1
  624. package/lib/web/FetchCompileWasmPlugin.js +27 -1
  625. package/lib/web/JsonpChunkLoadingPlugin.js +11 -1
  626. package/lib/web/JsonpChunkLoadingRuntimeModule.js +58 -64
  627. package/lib/web/JsonpTemplatePlugin.js +2 -1
  628. package/lib/webpack.js +78 -1
  629. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +10 -1
  630. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +15 -10
  631. package/lib/webworker/WebWorkerTemplatePlugin.js +1 -1
  632. package/module.d.ts +21 -0
  633. package/package.json +79 -77
  634. package/schemas/WebpackOptions.check.js +1 -1
  635. package/schemas/WebpackOptions.json +1117 -79
  636. package/schemas/plugins/{DllPlugin.check.d.ts → HtmlGeneratorOptions.check.d.ts} +1 -1
  637. package/schemas/plugins/HtmlGeneratorOptions.check.js +6 -0
  638. package/schemas/plugins/HtmlGeneratorOptions.json +3 -0
  639. package/schemas/plugins/{DllReferencePlugin.check.d.ts → HtmlParserOptions.check.d.ts} +1 -1
  640. package/schemas/plugins/HtmlParserOptions.check.js +6 -0
  641. package/schemas/plugins/HtmlParserOptions.json +3 -0
  642. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  643. package/schemas/plugins/ProgressPlugin.json +38 -0
  644. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  645. package/schemas/plugins/container/ContainerReferencePlugin.json +2 -0
  646. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  647. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  648. package/schemas/plugins/container/ModuleFederationPlugin.json +2 -0
  649. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.d.ts +7 -0
  650. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.js +6 -0
  651. package/schemas/plugins/css/CssAutoOrModuleParserOptions.json +3 -0
  652. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  653. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  654. package/schemas/plugins/dll/DllPlugin.check.d.ts +7 -0
  655. package/schemas/plugins/dll/DllReferencePlugin.check.d.ts +7 -0
  656. package/types.d.ts +8608 -1159
  657. package/lib/CaseSensitiveModulesWarning.js +0 -72
  658. package/lib/GraphHelpers.js +0 -46
  659. package/lib/ModuleParseError.js +0 -125
  660. package/lib/NoModeWarning.js +0 -23
  661. package/lib/css/CssMergeStyleSheetsRuntimeModule.js +0 -56
  662. package/lib/css/walkCssTokens.js +0 -1843
  663. package/lib/util/AppendOnlyStackedSet.js +0 -78
  664. /package/schemas/plugins/{DllPlugin.check.js → dll/DllPlugin.check.js} +0 -0
  665. /package/schemas/plugins/{DllPlugin.json → dll/DllPlugin.json} +0 -0
  666. /package/schemas/plugins/{DllReferencePlugin.check.js → dll/DllReferencePlugin.check.js} +0 -0
  667. /package/schemas/plugins/{DllReferencePlugin.json → dll/DllReferencePlugin.json} +0 -0
@@ -0,0 +1,4058 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Tobias Koppers @sokra
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const LocConverter = require("../util/LocConverter");
9
+ const GenericSourceProcessor = require("../util/SourceProcessor");
10
+ const { makeCacheable } = require("../util/identifier");
11
+
12
+ // spec: https://drafts.csswg.org/css-syntax/
13
+
14
+ /**
15
+ * @typedef {object} CssWhitespaceToken
16
+ * @property {number} type
17
+ * @property {number} start byte offset of the first whitespace code point
18
+ * @property {number} end byte offset just past the last whitespace code point
19
+ */
20
+ /**
21
+ * @typedef {object} CssCommentToken
22
+ * @property {number} type
23
+ * @property {number} start byte offset of the opening `/`
24
+ * @property {number} end byte offset just past the closing `/`
25
+ */
26
+ /**
27
+ * @typedef {object} CssStringToken
28
+ * @property {number} type
29
+ * @property {number} start byte offset of the opening quote
30
+ * @property {number} end byte offset just past the closing quote (or EOF for unterminated strings)
31
+ */
32
+ /**
33
+ * @typedef {object} CssBadStringToken
34
+ * @property {number} type
35
+ * @property {number} start byte offset of the opening quote
36
+ * @property {number} end byte offset where parsing gave up (typically the newline that broke the string)
37
+ */
38
+ /**
39
+ * @typedef {object} CssLeftCurlyBracketToken
40
+ * @property {number} type
41
+ * @property {number} start byte offset of `{`
42
+ * @property {number} end `start + 1`
43
+ */
44
+ /**
45
+ * @typedef {object} CssRightCurlyBracketToken
46
+ * @property {number} type
47
+ * @property {number} start byte offset of `}`
48
+ * @property {number} end `start + 1`
49
+ */
50
+ /**
51
+ * @typedef {object} CssLeftSquareBracketToken
52
+ * @property {number} type
53
+ * @property {number} start byte offset of `[`
54
+ * @property {number} end `start + 1`
55
+ */
56
+ /**
57
+ * @typedef {object} CssRightSquareBracketToken
58
+ * @property {number} type
59
+ * @property {number} start byte offset of `]`
60
+ * @property {number} end `start + 1`
61
+ */
62
+ /**
63
+ * @typedef {object} CssLeftParenthesisToken
64
+ * @property {number} type
65
+ * @property {number} start byte offset of `(`
66
+ * @property {number} end `start + 1`
67
+ */
68
+ /**
69
+ * @typedef {object} CssRightParenthesisToken
70
+ * @property {number} type
71
+ * @property {number} start byte offset of `)`
72
+ * @property {number} end `start + 1`
73
+ */
74
+ /**
75
+ * @typedef {object} CssFunctionToken
76
+ * @property {number} type
77
+ * @property {number} start byte offset of the function name's first code point
78
+ * @property {number} end byte offset just past the `(` that closes the function token
79
+ */
80
+ /**
81
+ * @typedef {object} CssUrlToken
82
+ * @property {number} type
83
+ * @property {number} start byte offset of the `url(` keyword (i.e. the `u`)
84
+ * @property {number} end byte offset just past the closing `)` (or EOF)
85
+ * @property {number} contentStart byte offset of the first code point of the unquoted URL content (post leading whitespace)
86
+ * @property {number} contentEnd byte offset just past the last code point of the unquoted URL content (pre trailing whitespace / `)` / EOF)
87
+ */
88
+ /**
89
+ * @typedef {object} CssBadUrlToken
90
+ * @property {number} type
91
+ * @property {number} start byte offset of the `url(` keyword
92
+ * @property {number} end byte offset where parsing gave up (past the recovery `)` or EOF)
93
+ */
94
+ /**
95
+ * @typedef {object} CssColonToken
96
+ * @property {number} type
97
+ * @property {number} start byte offset of `:`
98
+ * @property {number} end `start + 1`
99
+ */
100
+ /**
101
+ * @typedef {object} CssAtKeywordToken
102
+ * @property {number} type
103
+ * @property {number} start byte offset of `@`
104
+ * @property {number} end byte offset just past the last ident-sequence code point
105
+ */
106
+ /**
107
+ * @typedef {object} CssDelimToken
108
+ * @property {number} type
109
+ * @property {number} start byte offset of the delim code point
110
+ * @property {number} end `start + 1`
111
+ */
112
+ /**
113
+ * @typedef {object} CssIdentToken
114
+ * @property {number} type
115
+ * @property {number} start byte offset of the first ident code point
116
+ * @property {number} end byte offset just past the last ident-sequence code point
117
+ */
118
+ /**
119
+ * @typedef {object} CssPercentageToken
120
+ * @property {number} type
121
+ * @property {number} start byte offset of the first numeric code point
122
+ * @property {number} end byte offset just past the `%`
123
+ */
124
+ /**
125
+ * @typedef {object} CssNumberToken
126
+ * @property {number} type
127
+ * @property {number} start byte offset of the first numeric code point
128
+ * @property {number} end byte offset just past the last numeric code point
129
+ */
130
+ /**
131
+ * @typedef {object} CssDimensionToken
132
+ * @property {number} type
133
+ * @property {number} start byte offset of the first numeric code point
134
+ * @property {number} end byte offset just past the last unit ident code point
135
+ * @property {number} unitStart byte offset of the first unit-ident code point (== end of the numeric run)
136
+ */
137
+ /**
138
+ * @typedef {object} CssHashToken
139
+ * @property {number} type
140
+ * @property {number} start byte offset of `#`
141
+ * @property {number} end byte offset just past the last ident-sequence code point
142
+ * @property {boolean} isId true when the hash starts an ident sequence (`#foo`), false for non-ident hashes (`#1abc`)
143
+ */
144
+ /**
145
+ * @typedef {object} CssSemicolonToken
146
+ * @property {number} type
147
+ * @property {number} start byte offset of `;`
148
+ * @property {number} end `start + 1`
149
+ */
150
+ /**
151
+ * @typedef {object} CssCommaToken
152
+ * @property {number} type
153
+ * @property {number} start byte offset of `,`
154
+ * @property {number} end `start + 1`
155
+ */
156
+ /**
157
+ * @typedef {object} CssCdoToken
158
+ * @property {number} type
159
+ * @property {number} start byte offset of `<`
160
+ * @property {number} end byte offset just past `<!--`
161
+ */
162
+ /**
163
+ * @typedef {object} CssCdcToken
164
+ * @property {number} type
165
+ * @property {number} start byte offset of `-`
166
+ * @property {number} end byte offset just past `-->`
167
+ */
168
+ /**
169
+ * @typedef {CssWhitespaceToken | CssCommentToken | CssStringToken | CssBadStringToken | CssLeftCurlyBracketToken | CssRightCurlyBracketToken | CssLeftSquareBracketToken | CssRightSquareBracketToken | CssLeftParenthesisToken | CssRightParenthesisToken | CssFunctionToken | CssUrlToken | CssBadUrlToken | CssColonToken | CssAtKeywordToken | CssDelimToken | CssIdentToken | CssPercentageToken | CssNumberToken | CssDimensionToken | CssHashToken | CssSemicolonToken | CssCommaToken | CssCdoToken | CssCdcToken} CssToken
170
+ */
171
+
172
+ const CC_LINE_FEED = "\n".charCodeAt(0);
173
+ const CC_CARRIAGE_RETURN = "\r".charCodeAt(0);
174
+ const CC_FORM_FEED = "\f".charCodeAt(0);
175
+
176
+ const CC_TAB = "\t".charCodeAt(0);
177
+ const CC_SPACE = " ".charCodeAt(0);
178
+
179
+ const CC_SOLIDUS = "/".charCodeAt(0);
180
+ const CC_REVERSE_SOLIDUS = "\\".charCodeAt(0);
181
+ const CC_ASTERISK = "*".charCodeAt(0);
182
+
183
+ const CC_LEFT_PARENTHESIS = "(".charCodeAt(0);
184
+ const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0);
185
+ const CC_LEFT_CURLY = "{".charCodeAt(0);
186
+ const CC_RIGHT_CURLY = "}".charCodeAt(0);
187
+ const CC_LEFT_SQUARE = "[".charCodeAt(0);
188
+ const CC_RIGHT_SQUARE = "]".charCodeAt(0);
189
+
190
+ const CC_QUOTATION_MARK = '"'.charCodeAt(0);
191
+ const CC_APOSTROPHE = "'".charCodeAt(0);
192
+
193
+ const CC_FULL_STOP = ".".charCodeAt(0);
194
+ const CC_COLON = ":".charCodeAt(0);
195
+ const CC_SEMICOLON = ";".charCodeAt(0);
196
+ const CC_COMMA = ",".charCodeAt(0);
197
+ const CC_PERCENTAGE = "%".charCodeAt(0);
198
+ const CC_AT_SIGN = "@".charCodeAt(0);
199
+
200
+ const CC_LOW_LINE = "_".charCodeAt(0);
201
+ const CC_LOWER_A = "a".charCodeAt(0);
202
+ const CC_LOWER_D = "d".charCodeAt(0);
203
+ const CC_LOWER_F = "f".charCodeAt(0);
204
+ const CC_LOWER_E = "e".charCodeAt(0);
205
+ const CC_LOWER_U = "u".charCodeAt(0);
206
+ const CC_LOWER_R = "r".charCodeAt(0);
207
+ const CC_LOWER_L = "l".charCodeAt(0);
208
+ const CC_LOWER_Z = "z".charCodeAt(0);
209
+ const CC_EXCLAMATION = "!".charCodeAt(0);
210
+ const CC_UPPER_A = "A".charCodeAt(0);
211
+ const CC_UPPER_F = "F".charCodeAt(0);
212
+ const CC_UPPER_E = "E".charCodeAt(0);
213
+ const CC_UPPER_Z = "Z".charCodeAt(0);
214
+ const CC_0 = "0".charCodeAt(0);
215
+ const CC_9 = "9".charCodeAt(0);
216
+
217
+ const CC_NUMBER_SIGN = "#".charCodeAt(0);
218
+ const CC_PLUS_SIGN = "+".charCodeAt(0);
219
+ const CC_HYPHEN_MINUS = "-".charCodeAt(0);
220
+
221
+ const CC_LESS_THAN_SIGN = "<".charCodeAt(0);
222
+ const CC_GREATER_THAN_SIGN = ">".charCodeAt(0);
223
+
224
+ // Lexer token types (CSS Syntax Level 3 §4) plus the `<eof-token>`. Numeric so
225
+ // the per-token `type` slot stays compact and `next` / `consume` / the consume
226
+ // algorithms dispatch on integer `===` instead of string comparison. Exported
227
+ // alongside `readToken` (the per-token lexer primitive) for the unit test.
228
+ const TT_COMMENT = 1;
229
+ const TT_WHITESPACE = 2;
230
+ const TT_STRING = 3;
231
+ const TT_BAD_STRING_TOKEN = 4;
232
+ const TT_HASH = 5;
233
+ const TT_DELIM = 6;
234
+ // The three opening brackets are kept contiguous (7..9) so "is this an opening
235
+ // bracket?" is a single range check (`>= TT_LEFT_PARENTHESIS && <= TT_LEFT_CURLY_BRACKET`).
236
+ const TT_LEFT_PARENTHESIS = 7;
237
+ const TT_LEFT_SQUARE_BRACKET = 8;
238
+ const TT_LEFT_CURLY_BRACKET = 9;
239
+ const TT_RIGHT_PARENTHESIS = 10;
240
+ const TT_RIGHT_SQUARE_BRACKET = 11;
241
+ const TT_RIGHT_CURLY_BRACKET = 12;
242
+ const TT_COMMA = 13;
243
+ const TT_COLON = 14;
244
+ const TT_SEMICOLON = 15;
245
+ const TT_AT_KEYWORD = 16;
246
+ const TT_FUNCTION = 17;
247
+ const TT_URL = 18;
248
+ const TT_BAD_URL_TOKEN = 19;
249
+ const TT_IDENTIFIER = 20;
250
+ const TT_NUMBER = 21;
251
+ const TT_PERCENTAGE = 22;
252
+ const TT_DIMENSION = 23;
253
+ const TT_CDO = 24;
254
+ const TT_CDC = 25;
255
+ const TT_EOF = 26;
256
+
257
+ // The opening bracket types (7..9) and their mirror closers (10..12) are laid
258
+ // out so a closer is always `opener + 3`; `consumeASimpleBlock` uses that
259
+ // directly. The associated block char is a dense array indexed by the opener's
260
+ // offset from `TT_LEFT_PARENTHESIS` — a plain element load instead of a numeric
261
+ // object-key lookup.
262
+ /** @type {SimpleBlockToken[]} */
263
+ const BLOCK_TOKEN_CHAR = ["(", "[", "{"];
264
+
265
+ /**
266
+ * @param {number} cc char code
267
+ * @returns {boolean} true, if cc is a newline (per the spec: LF, CR, or FF)
268
+ */
269
+ const _isNewline = (cc) =>
270
+ cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED;
271
+
272
+ /**
273
+ * If the source had a CR followed by an LF, advance past the LF —
274
+ * the spec normalises CRLF to LF during preprocessing.
275
+ * @param {number} cc char code already consumed (the CR)
276
+ * @param {string} input input
277
+ * @param {number} pos position just past `cc`
278
+ * @returns {number} position past the CRLF pair (or unchanged for bare CR)
279
+ */
280
+ const consumeExtraNewline = (cc, input, pos) => {
281
+ if (cc === CC_CARRIAGE_RETURN && input.charCodeAt(pos) === CC_LINE_FEED) {
282
+ pos++;
283
+ }
284
+ return pos;
285
+ };
286
+
287
+ /**
288
+ * @param {number} cc char code
289
+ * @returns {boolean} true, if cc is space or tab
290
+ */
291
+ const _isSpace = (cc) => cc === CC_SPACE || cc === CC_TAB;
292
+
293
+ /**
294
+ * @param {number} cc char code
295
+ * @returns {boolean} true, if cc is whitespace (space/tab/newline)
296
+ */
297
+ // Space-first: U+0020 is the common case, so it short-circuits before the
298
+ // rarer tab / newline tests.
299
+ const _isWhiteSpace = (cc) => _isSpace(cc) || _isNewline(cc);
300
+
301
+ // Whitespace membership table for the run-consumption loop — one load instead
302
+ // of up to five compares per char. EOF (NaN) / non-ASCII index to undefined.
303
+ const _wsTable = new Uint8Array(128);
304
+ _wsTable[CC_SPACE] = 1;
305
+ _wsTable[CC_TAB] = 1;
306
+ _wsTable[CC_LINE_FEED] = 1;
307
+ _wsTable[CC_CARRIAGE_RETURN] = 1;
308
+ _wsTable[CC_FORM_FEED] = 1;
309
+
310
+ /**
311
+ * @param {number} cc char code
312
+ * @returns {boolean} true, if cc is a digit
313
+ */
314
+ const _isDigit = (cc) => cc >= CC_0 && cc <= CC_9;
315
+
316
+ /**
317
+ * @param {number} cc char code
318
+ * @returns {boolean} true, if cc is a hex digit
319
+ */
320
+ const _isHexDigit = (cc) =>
321
+ _isDigit(cc) ||
322
+ (cc >= CC_UPPER_A && cc <= CC_UPPER_F) ||
323
+ (cc >= CC_LOWER_A && cc <= CC_LOWER_F);
324
+
325
+ /**
326
+ * @param {number} cc char code
327
+ * @returns {boolean} is letter (a-z / A-Z)
328
+ */
329
+ const _isLetter = (cc) =>
330
+ (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) ||
331
+ (cc >= CC_UPPER_A && cc <= CC_UPPER_Z);
332
+
333
+ /**
334
+ * Spec: ident-start = letter / non-ASCII / `_`. Internal helper that
335
+ * accepts an explicit char code (lookahead).
336
+ * @param {number} cc char code
337
+ * @returns {boolean} true, if cc is an ident-start code point
338
+ */
339
+ const _isIdentStartCodePointCC = (cc) =>
340
+ _isLetter(cc) || cc >= 0x80 || cc === CC_LOW_LINE;
341
+
342
+ /**
343
+ * Spec: ident-code = ident-start / digit / hyphen-minus.
344
+ */
345
+ // Full `charCodeAt` range (0..0xFFFF) so the per-code-point ident test is one
346
+ // table load with no `cc < 128` branch — `_consumeAnIdentSequence` runs this on
347
+ // every character of every ident / class / property name (the tokenizer's
348
+ // hottest loop). Every non-ASCII code unit (>= 0x80) is an ident code point per
349
+ // spec, so those default to 1; only the ASCII rows carry real classification.
350
+ // Callers must index with `cc | 0`: EOF (`charCodeAt` → NaN) becomes 0 (NUL,
351
+ // not an ident) — a raw NaN index is an out-of-range access that permanently
352
+ // degrades the load site's IC.
353
+ const _identCharTable = new Uint8Array(0x10000).fill(1);
354
+ for (let i = 0; i < 128; i++) {
355
+ _identCharTable[i] =
356
+ _isLetter(i) || i === CC_LOW_LINE || _isDigit(i) || i === CC_HYPHEN_MINUS
357
+ ? 1
358
+ : 0;
359
+ }
360
+ /**
361
+ * @param {number} cc char code
362
+ * @returns {boolean} true, if cc is an ident-sequence code point
363
+ */
364
+ const _isIdentCodePoint = (cc) => _identCharTable[cc | 0] === 1;
365
+
366
+ /**
367
+ * ASCII case-insensitive equality against a lowercase literal — avoids the
368
+ * `toLowerCase()` allocation and matches CSS's ASCII case-insensitive keyword
369
+ * matching. `lit` must be lowercase ASCII.
370
+ * @param {string} s string to test
371
+ * @param {string} lit lowercase ASCII literal to match
372
+ * @returns {boolean} true, if `s` equals `lit` ignoring ASCII case
373
+ */
374
+ const equalsLowerCase = (s, lit) => {
375
+ if (s.length !== lit.length) return false;
376
+ for (let i = 0; i < lit.length; i++) {
377
+ let c = s.charCodeAt(i);
378
+ if (c >= CC_UPPER_A && c <= CC_UPPER_Z) c |= 0x20;
379
+ if (c !== lit.charCodeAt(i)) return false;
380
+ }
381
+ return true;
382
+ };
383
+
384
+ /**
385
+ * Case-sensitive equality of a source range against a literal — no slice.
386
+ * @param {string} input source
387
+ * @param {number} start range start
388
+ * @param {number} end range end (exclusive)
389
+ * @param {string} lit literal to match
390
+ * @returns {boolean} true when the range equals `lit`
391
+ */
392
+ const rangeEquals = (input, start, end, lit) =>
393
+ end - start === lit.length && input.startsWith(lit, start);
394
+
395
+ /**
396
+ * ASCII case-insensitive equality of a source range against a lowercase ASCII literal — no slice.
397
+ * @param {string} input source
398
+ * @param {number} start range start
399
+ * @param {number} end range end (exclusive)
400
+ * @param {string} lit lowercase ASCII literal to match
401
+ * @returns {boolean} true when the range equals `lit` ignoring ASCII case
402
+ */
403
+ const rangeEqualsLowerCase = (input, start, end, lit) => {
404
+ if (end - start !== lit.length) return false;
405
+ for (let i = 0; i < lit.length; i++) {
406
+ let c = input.charCodeAt(start + i);
407
+ if (c >= CC_UPPER_A && c <= CC_UPPER_Z) c |= 0x20;
408
+ if (c !== lit.charCodeAt(i)) return false;
409
+ }
410
+ return true;
411
+ };
412
+
413
+ /**
414
+ * `s.toLowerCase()` that returns `s` itself (no allocation) when it can't
415
+ * change — no ASCII uppercase and no non-ASCII (whose Unicode case mapping is
416
+ * left to the real `toLowerCase`).
417
+ * @param {string} s string
418
+ * @returns {string} lowercased string
419
+ */
420
+ const toLowerCaseIfNeeded = (s) => {
421
+ for (let i = 0; i < s.length; i++) {
422
+ const c = s.charCodeAt(i);
423
+ if ((c >= CC_UPPER_A && c <= CC_UPPER_Z) || c > 127) return s.toLowerCase();
424
+ }
425
+ return s;
426
+ };
427
+
428
+ /**
429
+ * A custom property name (`<dashed-ident>`): a `--`-prefixed identifier other than bare `--`.
430
+ * @param {string} identifier identifier
431
+ * @returns {boolean} true when identifier is dashed, otherwise false
432
+ */
433
+ const isDashedIdentifier = (identifier) =>
434
+ identifier.startsWith("--") && identifier.length >= 3;
435
+
436
+ /**
437
+ * Consume an escaped code point.
438
+ * @param {string} input input
439
+ * @param {number} pos position just past the `\`
440
+ * @returns {number} position past the escape sequence
441
+ */
442
+ const _consumeAnEscapedCodePoint = (input, pos) => {
443
+ // Caller has verified the `\` and the next code point form a valid
444
+ // escape. Hex digits: consume up to 6 hex digits, then one optional
445
+ // whitespace. Non-hex: consume one code point.
446
+ // `\` at EOF: nothing to consume; return pos so callers don't overrun.
447
+ if (pos >= input.length) return pos;
448
+ const cc = input.charCodeAt(pos);
449
+ pos++;
450
+ if (pos === input.length) return pos;
451
+ if (_isHexDigit(cc)) {
452
+ for (let i = 0; i < 5; i++) {
453
+ if (!_isHexDigit(input.charCodeAt(pos))) break;
454
+ pos++;
455
+ }
456
+ const trail = input.charCodeAt(pos);
457
+ if (_isWhiteSpace(trail)) {
458
+ pos++;
459
+ pos = consumeExtraNewline(trail, input, pos);
460
+ }
461
+ }
462
+ return pos;
463
+ };
464
+
465
+ /**
466
+ * Spec: "two code points are a valid escape" — first is `\`, second is
467
+ * not a newline.
468
+ * @param {string} input input
469
+ * @param {number} pos position of the second code point
470
+ * @param {number=} f first code point (defaults to `input.charCodeAt(pos - 1)`)
471
+ * @param {number=} s second code point (defaults to `input.charCodeAt(pos)`)
472
+ * @returns {boolean} true, if the two code points form a valid escape
473
+ */
474
+ const _ifTwoCodePointsAreValidEscape = (input, pos, f, s) => {
475
+ const first = f || input.charCodeAt(pos - 1);
476
+ const second = s || input.charCodeAt(pos);
477
+ if (first !== CC_REVERSE_SOLIDUS) return false;
478
+ if (_isNewline(second)) return false;
479
+ return true;
480
+ };
481
+
482
+ /**
483
+ * Spec: "three code points would start an ident sequence".
484
+ * @param {string} input input
485
+ * @param {number} pos position
486
+ * @param {number=} f first code point (defaults to `input.charCodeAt(pos - 1)`)
487
+ * @param {number=} s second code point (defaults to `input.charCodeAt(pos)`)
488
+ * @param {number=} t third code point (defaults to `input.charCodeAt(pos + 1)`)
489
+ * @returns {boolean} true, if the three code points start an ident sequence
490
+ */
491
+ const _ifThreeCodePointsWouldStartAnIdentSequence = (input, pos, f, s, t) => {
492
+ const first = f || input.charCodeAt(pos - 1);
493
+ const second = s || input.charCodeAt(pos);
494
+ const third = t || input.charCodeAt(pos + 1);
495
+ if (first === CC_HYPHEN_MINUS) {
496
+ return (
497
+ _isIdentStartCodePointCC(second) ||
498
+ second === CC_HYPHEN_MINUS ||
499
+ _ifTwoCodePointsAreValidEscape(input, pos, second, third)
500
+ );
501
+ }
502
+ if (_isIdentStartCodePointCC(first)) return true;
503
+ if (first === CC_REVERSE_SOLIDUS) {
504
+ return _ifTwoCodePointsAreValidEscape(input, pos, first, second);
505
+ }
506
+ return false;
507
+ };
508
+
509
+ /**
510
+ * Spec: "three code points would start a number".
511
+ * @param {string} input input
512
+ * @param {number} pos position
513
+ * @param {number=} f first code point
514
+ * @param {number=} s second code point
515
+ * @param {number=} t third code point
516
+ * @returns {boolean} true, if the three code points start a number
517
+ */
518
+ const _ifThreeCodePointsWouldStartANumber = (input, pos, f, s, t) => {
519
+ const first = f || input.charCodeAt(pos - 1);
520
+ const second = s || input.charCodeAt(pos);
521
+ const third = t || input.charCodeAt(pos + 1);
522
+ if (first === CC_PLUS_SIGN || first === CC_HYPHEN_MINUS) {
523
+ if (_isDigit(second)) return true;
524
+ return second === CC_FULL_STOP && _isDigit(third);
525
+ }
526
+ if (first === CC_FULL_STOP) return _isDigit(second);
527
+ /* istanbul ignore next -- @preserve: spec-general; every caller passes `pos` just past a +/-/. so `first` is never a bare digit here */
528
+ return _isDigit(first);
529
+ };
530
+
531
+ /**
532
+ * Consume an ident sequence (no validation of the first code points).
533
+ * @param {string} input input
534
+ * @param {number} pos position
535
+ * @returns {number} position just past the last ident-sequence code point
536
+ */
537
+ const _consumeAnIdentSequence = (input, pos) => {
538
+ // Hot loop (every ident, at-keyword, hash, function name, unit). Both checks
539
+ // are inlined from `_isIdentCodePoint` / `_ifTwoCodePointsAreValidEscape`: the
540
+ // ident test is a single full-range table load (no `cc < 128` branch), and the
541
+ // escape test reads the following code point only when `cc` is a `\` (rare)
542
+ // instead of eagerly.
543
+ for (;;) {
544
+ const cc = input.charCodeAt(pos) | 0;
545
+ pos++;
546
+ if (_identCharTable[cc] === 1) {
547
+ continue;
548
+ }
549
+ if (cc === CC_REVERSE_SOLIDUS && !_isNewline(input.charCodeAt(pos))) {
550
+ pos = _consumeAnEscapedCodePoint(input, pos);
551
+ continue;
552
+ }
553
+ return pos - 1;
554
+ }
555
+ };
556
+
557
+ /**
558
+ * @param {number} cc char code
559
+ * @returns {boolean} true, if cc is a non-printable code point
560
+ */
561
+ const _isNonPrintableCodePoint = (cc) =>
562
+ (cc >= 0x00 && cc <= 0x08) ||
563
+ cc === 0x0b ||
564
+ (cc >= 0x0e && cc <= 0x1f) ||
565
+ cc === 0x7f;
566
+
567
+ /**
568
+ * Consume the body of a number per the spec (does not classify integer
569
+ * vs number — caller / token type handles that).
570
+ * @param {string} input input
571
+ * @param {number} pos position at the first numeric / sign code point
572
+ * @returns {number} position just past the number
573
+ */
574
+ const _consumeANumber = (input, pos) => {
575
+ let cc = input.charCodeAt(pos);
576
+ if (cc === CC_HYPHEN_MINUS || cc === CC_PLUS_SIGN) {
577
+ pos++;
578
+ }
579
+ while (_isDigit(input.charCodeAt(pos))) pos++;
580
+ if (
581
+ input.charCodeAt(pos) === CC_FULL_STOP &&
582
+ _isDigit(input.charCodeAt(pos + 1))
583
+ ) {
584
+ pos++;
585
+ while (_isDigit(input.charCodeAt(pos))) pos++;
586
+ }
587
+ cc = input.charCodeAt(pos);
588
+ if (
589
+ (cc === CC_LOWER_E || cc === CC_UPPER_E) &&
590
+ (((input.charCodeAt(pos + 1) === CC_HYPHEN_MINUS ||
591
+ input.charCodeAt(pos + 1) === CC_PLUS_SIGN) &&
592
+ _isDigit(input.charCodeAt(pos + 2))) ||
593
+ _isDigit(input.charCodeAt(pos + 1)))
594
+ ) {
595
+ pos++;
596
+ cc = input.charCodeAt(pos);
597
+ if (cc === CC_PLUS_SIGN || cc === CC_HYPHEN_MINUS) {
598
+ pos++;
599
+ }
600
+ while (_isDigit(input.charCodeAt(pos))) pos++;
601
+ }
602
+ return pos;
603
+ };
604
+
605
+ /**
606
+ * Spec recovery: when the tokenizer realises it's mid-bad-url, consume
607
+ * until `)` or EOF.
608
+ * @param {string} input input
609
+ * @param {number} pos position
610
+ * @returns {number} position past the recovery `)` or EOF
611
+ */
612
+ const _consumeTheRemnantsOfABadUrl = (input, pos) => {
613
+ for (;;) {
614
+ if (pos === input.length) return pos;
615
+ const cc = input.charCodeAt(pos);
616
+ pos++;
617
+ if (cc === CC_RIGHT_PARENTHESIS) return pos;
618
+ if (_ifTwoCodePointsAreValidEscape(input, pos)) {
619
+ pos = _consumeAnEscapedCodePoint(input, pos);
620
+ }
621
+ }
622
+ };
623
+
624
+ /**
625
+ * A mutable lexer token. The `next` / `consume` hot path reuses a single
626
+ * instance per `TokenStream` (the lexer writes into it instead of allocating
627
+ * one object per token), which also keeps the parser's `t.type` reads
628
+ * monomorphic. All fields are present from construction so the shape never
629
+ * transitions; type-specific fields (`isId` / `contentStart` / `contentEnd` /
630
+ * `unitStart`) carry stale values for unrelated token types and are only read
631
+ * by `tokenToNode` for the matching type. Pass a fresh one per `readToken` call
632
+ * to collect the raw token list (e.g. tests).
633
+ * @typedef {object} MutableToken
634
+ * @property {number} type one of the `TT_*` constants
635
+ * @property {number} start byte offset of the token's first code point
636
+ * @property {number} end byte offset just past the token's last code point
637
+ * @property {boolean} isId hash tokens: starts an ident sequence
638
+ * @property {number} contentStart url tokens: first content code point
639
+ * @property {number} contentEnd url tokens: just past the last content code point
640
+ * @property {number} unitStart dimension tokens: first unit-ident code point
641
+ */
642
+
643
+ /**
644
+ * @returns {MutableToken} a fresh lexer token with the canonical shape
645
+ */
646
+ const createToken = () => ({
647
+ type: TT_EOF,
648
+ start: 0,
649
+ end: 0,
650
+ isId: false,
651
+ contentStart: 0,
652
+ contentEnd: 0,
653
+ unitStart: 0
654
+ });
655
+
656
+ /**
657
+ * Populate `out`'s common fields and return it — the lexer functions' return
658
+ * statement (kept tiny so V8 can inline it).
659
+ * @param {MutableToken} out token to populate
660
+ * @param {number} type one of the `TT_*` constants
661
+ * @param {number} start byte offset of the token's first code point
662
+ * @param {number} end byte offset just past the token's last code point
663
+ * @returns {MutableToken} `out`
664
+ */
665
+ const fill = (out, type, start, end) => {
666
+ out.type = type;
667
+ out.start = start;
668
+ out.end = end;
669
+ return out;
670
+ };
671
+
672
+ /**
673
+ * Whitespace token. Caller advances past the leading code point so
674
+ * `start = pos - 1`.
675
+ * @param {string} input input
676
+ * @param {number} pos position just past the first whitespace code point
677
+ * @param {MutableToken} out token to populate
678
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
679
+ */
680
+ function consumeSpace(input, pos, out) {
681
+ const start = pos - 1;
682
+ while (_wsTable[input.charCodeAt(pos)] === 1) pos++;
683
+ return fill(out, TT_WHITESPACE, start, pos);
684
+ }
685
+
686
+ /**
687
+ * Consume a string token. Caller advanced past the opening quote so
688
+ * `pos - 1` holds the ending code point and `pos - 1` is the start.
689
+ * @param {string} input input
690
+ * @param {number} pos position just past the opening quote
691
+ * @param {MutableToken} out token to populate
692
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
693
+ */
694
+ function consumeAStringToken(input, pos, out) {
695
+ const start = pos - 1;
696
+ const endingCodePoint = input.charCodeAt(pos - 1);
697
+ for (;;) {
698
+ if (pos === input.length) {
699
+ return fill(out, TT_STRING, start, pos);
700
+ }
701
+ const cc = input.charCodeAt(pos);
702
+ pos++;
703
+ if (cc === endingCodePoint) {
704
+ return fill(out, TT_STRING, start, pos);
705
+ }
706
+ if (_isNewline(cc)) {
707
+ pos--;
708
+ return fill(out, TT_BAD_STRING_TOKEN, start, pos);
709
+ }
710
+ if (cc === CC_REVERSE_SOLIDUS) {
711
+ // `\` at EOF: string ends here; emit the token so ranges cover all input.
712
+ if (pos === input.length) return fill(out, TT_STRING, start, pos);
713
+ if (_isNewline(input.charCodeAt(pos))) {
714
+ const ccNl = input.charCodeAt(pos);
715
+ pos++;
716
+ pos = consumeExtraNewline(ccNl, input, pos);
717
+ } else if (_ifTwoCodePointsAreValidEscape(input, pos)) {
718
+ pos = _consumeAnEscapedCodePoint(input, pos);
719
+ }
720
+ }
721
+ }
722
+ }
723
+
724
+ /**
725
+ * `#` — hash or delim.
726
+ * @param {string} input input
727
+ * @param {number} pos position just past `#`
728
+ * @param {MutableToken} out token to populate
729
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
730
+ */
731
+ function consumeNumberSign(input, pos, out) {
732
+ const start = pos - 1;
733
+ const first = input.charCodeAt(pos);
734
+ const second = input.charCodeAt(pos + 1);
735
+ if (
736
+ _isIdentCodePoint(first) ||
737
+ _ifTwoCodePointsAreValidEscape(input, pos, first, second)
738
+ ) {
739
+ const third = input.charCodeAt(pos + 2);
740
+ out.isId = _ifThreeCodePointsWouldStartAnIdentSequence(
741
+ input,
742
+ pos,
743
+ first,
744
+ second,
745
+ third
746
+ );
747
+ pos = _consumeAnIdentSequence(input, pos);
748
+ return fill(out, TT_HASH, start, pos);
749
+ }
750
+ return fill(out, TT_DELIM, start, pos);
751
+ }
752
+
753
+ /**
754
+ * `-` — number / cdc / ident / delim.
755
+ * @param {string} input input
756
+ * @param {number} pos position just past `-`
757
+ * @param {MutableToken} out token to populate
758
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
759
+ */
760
+ function consumeHyphenMinus(input, pos, out) {
761
+ // Read the two lookahead code points once; the lead is the known `-`.
762
+ const second = input.charCodeAt(pos);
763
+ const third = input.charCodeAt(pos + 1);
764
+ if (
765
+ _ifThreeCodePointsWouldStartANumber(
766
+ input,
767
+ pos,
768
+ CC_HYPHEN_MINUS,
769
+ second,
770
+ third
771
+ )
772
+ ) {
773
+ pos--;
774
+ return consumeANumericToken(input, pos, out);
775
+ }
776
+ if (second === CC_HYPHEN_MINUS && third === CC_GREATER_THAN_SIGN) {
777
+ return fill(out, TT_CDC, pos - 1, pos + 2);
778
+ }
779
+ if (
780
+ _ifThreeCodePointsWouldStartAnIdentSequence(
781
+ input,
782
+ pos,
783
+ CC_HYPHEN_MINUS,
784
+ second,
785
+ third
786
+ )
787
+ ) {
788
+ pos--;
789
+ return consumeAnIdentLikeToken(input, pos, out);
790
+ }
791
+ return fill(out, TT_DELIM, pos - 1, pos);
792
+ }
793
+
794
+ /**
795
+ * `.` — number or delim.
796
+ * @param {string} input input
797
+ * @param {number} pos position just past `.`
798
+ * @param {MutableToken} out token to populate
799
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
800
+ */
801
+ function consumeFullStop(input, pos, out) {
802
+ const start = pos - 1;
803
+ if (_ifThreeCodePointsWouldStartANumber(input, pos)) {
804
+ pos--;
805
+ return consumeANumericToken(input, pos, out);
806
+ }
807
+ return fill(out, TT_DELIM, start, pos);
808
+ }
809
+
810
+ /**
811
+ * `+` — number or delim.
812
+ * @param {string} input input
813
+ * @param {number} pos position just past `+`
814
+ * @param {MutableToken} out token to populate
815
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
816
+ */
817
+ function consumePlusSign(input, pos, out) {
818
+ const start = pos - 1;
819
+ if (_ifThreeCodePointsWouldStartANumber(input, pos)) {
820
+ pos--;
821
+ return consumeANumericToken(input, pos, out);
822
+ }
823
+ return fill(out, TT_DELIM, start, pos);
824
+ }
825
+
826
+ /**
827
+ * Numeric token: number / percentage / dimension.
828
+ * @param {string} input input
829
+ * @param {number} pos position at the first numeric/sign code point
830
+ * @param {MutableToken} out token to populate
831
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
832
+ */
833
+ function consumeANumericToken(input, pos, out) {
834
+ const start = pos;
835
+ pos = _consumeANumber(input, pos);
836
+ const first = input.charCodeAt(pos);
837
+ // A unit can only begin with `-`, `\`, or an ident-start code point — exactly
838
+ // the cases where the §4 "would start an ident sequence" check can be true. For
839
+ // a plain number (next char is whitespace / `;` / `,` / `)` / EOF, the common
840
+ // case) skip the two lookahead reads and the call entirely.
841
+ if (
842
+ (first === CC_HYPHEN_MINUS ||
843
+ first === CC_REVERSE_SOLIDUS ||
844
+ _isIdentStartCodePointCC(first)) &&
845
+ _ifThreeCodePointsWouldStartAnIdentSequence(
846
+ input,
847
+ pos,
848
+ first,
849
+ input.charCodeAt(pos + 1),
850
+ input.charCodeAt(pos + 2)
851
+ )
852
+ ) {
853
+ out.unitStart = pos;
854
+ pos = _consumeAnIdentSequence(input, pos);
855
+ return fill(out, TT_DIMENSION, start, pos);
856
+ }
857
+ if (first === CC_PERCENTAGE) {
858
+ return fill(out, TT_PERCENTAGE, start, pos + 1);
859
+ }
860
+ return fill(out, TT_NUMBER, start, pos);
861
+ }
862
+
863
+ /**
864
+ * Consume an unquoted url token. Caller has already eaten `url(` and
865
+ * any leading whitespace.
866
+ * @param {string} input input
867
+ * @param {number} pos position at the first content code point
868
+ * @param {number} fnStart byte offset of the `u` in `url(`
869
+ * @param {MutableToken} out token to populate
870
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
871
+ */
872
+ function consumeAUrlToken(input, pos, fnStart, out) {
873
+ while (_isWhiteSpace(input.charCodeAt(pos))) pos++;
874
+ const contentStart = pos;
875
+ out.contentStart = contentStart;
876
+ for (;;) {
877
+ if (pos === input.length) {
878
+ out.contentEnd = pos;
879
+ return fill(out, TT_URL, fnStart, pos);
880
+ }
881
+ const cc = input.charCodeAt(pos);
882
+ pos++;
883
+ if (cc === CC_RIGHT_PARENTHESIS) {
884
+ out.contentEnd = pos - 1;
885
+ return fill(out, TT_URL, fnStart, pos);
886
+ }
887
+ if (_isWhiteSpace(cc)) {
888
+ const end = pos - 1;
889
+ while (_isWhiteSpace(input.charCodeAt(pos))) pos++;
890
+ if (pos === input.length) {
891
+ out.contentEnd = end;
892
+ return fill(out, TT_URL, fnStart, pos);
893
+ }
894
+ if (input.charCodeAt(pos) === CC_RIGHT_PARENTHESIS) {
895
+ pos++;
896
+ out.contentEnd = end;
897
+ return fill(out, TT_URL, fnStart, pos);
898
+ }
899
+ pos = _consumeTheRemnantsOfABadUrl(input, pos);
900
+ return fill(out, TT_BAD_URL_TOKEN, fnStart, pos);
901
+ }
902
+ if (
903
+ cc === CC_QUOTATION_MARK ||
904
+ cc === CC_APOSTROPHE ||
905
+ cc === CC_LEFT_PARENTHESIS ||
906
+ _isNonPrintableCodePoint(cc)
907
+ ) {
908
+ pos = _consumeTheRemnantsOfABadUrl(input, pos);
909
+ return fill(out, TT_BAD_URL_TOKEN, fnStart, pos);
910
+ }
911
+ if (cc === CC_REVERSE_SOLIDUS) {
912
+ if (_ifTwoCodePointsAreValidEscape(input, pos)) {
913
+ pos = _consumeAnEscapedCodePoint(input, pos);
914
+ } else {
915
+ pos = _consumeTheRemnantsOfABadUrl(input, pos);
916
+ return fill(out, TT_BAD_URL_TOKEN, fnStart, pos);
917
+ }
918
+ }
919
+ }
920
+ }
921
+
922
+ /**
923
+ * Consume an ident-like token: ident / function / url / bad-url.
924
+ * @param {string} input input
925
+ * @param {number} pos position at the first ident-start code point
926
+ * @param {MutableToken} out token to populate
927
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
928
+ */
929
+ function consumeAnIdentLikeToken(input, pos, out) {
930
+ const start = pos;
931
+ pos = _consumeAnIdentSequence(input, pos);
932
+ // `url` case-insensitively (ASCII lower via `| 0x20`) without a
933
+ // `slice().toLowerCase()` allocation per identifier; an escaped ident can't
934
+ // be exactly 3 raw chars, so the length gate keeps this equivalent.
935
+ if (
936
+ pos - start === 3 &&
937
+ (input.charCodeAt(start) | 0x20) === CC_LOWER_U &&
938
+ (input.charCodeAt(start + 1) | 0x20) === CC_LOWER_R &&
939
+ (input.charCodeAt(start + 2) | 0x20) === CC_LOWER_L &&
940
+ input.charCodeAt(pos) === CC_LEFT_PARENTHESIS
941
+ ) {
942
+ pos++;
943
+ const end = pos;
944
+ while (
945
+ _isWhiteSpace(input.charCodeAt(pos)) &&
946
+ _isWhiteSpace(input.charCodeAt(pos + 1))
947
+ ) {
948
+ pos++;
949
+ }
950
+ if (
951
+ input.charCodeAt(pos) === CC_QUOTATION_MARK ||
952
+ input.charCodeAt(pos) === CC_APOSTROPHE ||
953
+ (_isWhiteSpace(input.charCodeAt(pos)) &&
954
+ (input.charCodeAt(pos + 1) === CC_QUOTATION_MARK ||
955
+ input.charCodeAt(pos + 1) === CC_APOSTROPHE))
956
+ ) {
957
+ // End at `end` (the `(`'s closer position), not `pos` — the
958
+ // lookahead-eaten whitespace must be re-tokenized as a whitespace
959
+ // token rather than swallowed silently. The reader resumes at
960
+ // `token.end`, so returning `end` here does that.
961
+ return fill(out, TT_FUNCTION, start, end);
962
+ }
963
+ return consumeAUrlToken(input, pos, start, out);
964
+ }
965
+ if (input.charCodeAt(pos) === CC_LEFT_PARENTHESIS) {
966
+ pos++;
967
+ return fill(out, TT_FUNCTION, start, pos);
968
+ }
969
+ return fill(out, TT_IDENTIFIER, start, pos);
970
+ }
971
+
972
+ /**
973
+ * `<` — CDO or delim.
974
+ * @param {string} input input
975
+ * @param {number} pos position just past `<`
976
+ * @param {MutableToken} out token to populate
977
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
978
+ */
979
+ function consumeLessThan(input, pos, out) {
980
+ if (
981
+ input.charCodeAt(pos) === CC_EXCLAMATION &&
982
+ input.charCodeAt(pos + 1) === CC_HYPHEN_MINUS &&
983
+ input.charCodeAt(pos + 2) === CC_HYPHEN_MINUS
984
+ ) {
985
+ return fill(out, TT_CDO, pos - 1, pos + 3);
986
+ }
987
+ return fill(out, TT_DELIM, pos - 1, pos);
988
+ }
989
+
990
+ /**
991
+ * `@` — at-keyword or delim.
992
+ * @param {string} input input
993
+ * @param {number} pos position just past `@`
994
+ * @param {MutableToken} out token to populate
995
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
996
+ */
997
+ function consumeCommercialAt(input, pos, out) {
998
+ const start = pos - 1;
999
+ if (
1000
+ _ifThreeCodePointsWouldStartAnIdentSequence(
1001
+ input,
1002
+ pos,
1003
+ input.charCodeAt(pos),
1004
+ input.charCodeAt(pos + 1),
1005
+ input.charCodeAt(pos + 2)
1006
+ )
1007
+ ) {
1008
+ pos = _consumeAnIdentSequence(input, pos);
1009
+ return fill(out, TT_AT_KEYWORD, start, pos);
1010
+ }
1011
+ return fill(out, TT_DELIM, start, pos);
1012
+ }
1013
+
1014
+ /**
1015
+ * `\` — escape starts an ident-like token, otherwise it's a delim.
1016
+ * @param {string} input input
1017
+ * @param {number} pos position just past `\`
1018
+ * @param {MutableToken} out token to populate
1019
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
1020
+ */
1021
+ function consumeReverseSolidus(input, pos, out) {
1022
+ if (_ifTwoCodePointsAreValidEscape(input, pos)) {
1023
+ pos--;
1024
+ return consumeAnIdentLikeToken(input, pos, out);
1025
+ }
1026
+ return fill(out, TT_DELIM, pos - 1, pos);
1027
+ }
1028
+
1029
+ // `consumeAToken` dispatch: the §4 token rules keyed by the lead code point are
1030
+ // === Tokenizer lead-character dispatch (CSS Syntax Level 3 §4 "consume a token") ===
1031
+ //
1032
+ // `consumeAToken` selects a sub-routine from the first ("lead") code point of each
1033
+ // token. The §4 rules are keyed on specific code points (`"` `#` `(` digit
1034
+ // ident-start …) that sit SPARSELY across the ASCII range, so a plain `switch (cc)`
1035
+ // compiles to a jump table spanning U+0009..U+007D in which the most common lead —
1036
+ // an ident-start letter — is not a case and reaches its handler only after the
1037
+ // digit/whitespace tests miss. `_charClass` precomputes, for every ASCII code
1038
+ // point, a dense handler id (`HC_*`, 0..12) so `consumeAToken` is one array load +
1039
+ // a compact 13-entry jump table and idents dispatch directly. Non-ASCII
1040
+ // (cc >= 128) is always ident-start per §4, so it skips the table.
1041
+ //
1042
+ // Extending for a spec change: repoint the code point in the build loop below; if
1043
+ // it needs a new sub-routine, add an `HC_*` id, a `case` in `consumeAToken`, and a
1044
+ // row here. This list is the authoritative "which lead code point dispatches
1045
+ // where" map (§4 "consume a token", step by lead code point):
1046
+ //
1047
+ // HC_WHITESPACE whitespace U+0009 TAB U+000A LF U+000C FF U+000D CR U+0020 SPACE
1048
+ // HC_STRING string start U+0022 " U+0027 '
1049
+ // HC_SINGLE one-char token ( ) , : ; [ ] { } (its token type comes from `_singleTT`)
1050
+ // HC_NUMBER_SIGN hash / delim U+0023 #
1051
+ // HC_PLUS_SIGN number / delim U+002B +
1052
+ // HC_HYPHEN_MINUS number / CDC / ident / delim U+002D -
1053
+ // HC_FULL_STOP number / delim U+002E .
1054
+ // HC_LESS_THAN CDO / delim U+003C <
1055
+ // HC_AT_SIGN at-keyword / delim U+0040 @
1056
+ // HC_REVERSE_SOLIDUS escape / delim U+005C \
1057
+ // HC_DIGIT number U+0030..U+0039 0-9
1058
+ // HC_IDENT ident-like U+0041..U+005A A-Z U+0061..U+007A a-z U+005F _ (plus cc >= 128)
1059
+ // HC_DELIM anything else -> a single <delim-token>
1060
+ //
1061
+ // `_singleTT[cc]` is the token type for the HC_SINGLE code points (a second table
1062
+ // so they share one handler instead of one `case` each). The default class 0 is
1063
+ // the delim handler (anything not matched below), so it needs no named constant.
1064
+ const HC_WHITESPACE = 1;
1065
+ const HC_STRING = 2;
1066
+ const HC_SINGLE = 3;
1067
+ const HC_NUMBER_SIGN = 4;
1068
+ const HC_PLUS_SIGN = 5;
1069
+ const HC_HYPHEN_MINUS = 6;
1070
+ const HC_FULL_STOP = 7;
1071
+ const HC_LESS_THAN = 8;
1072
+ const HC_AT_SIGN = 9;
1073
+ const HC_REVERSE_SOLIDUS = 10;
1074
+ const HC_DIGIT = 11;
1075
+ const HC_IDENT = 12;
1076
+ // Full `charCodeAt` range so `consumeAToken` dispatches with one table load and
1077
+ // no `cc < 128` branch. Every non-ASCII code point (>= 0x80) is an ident-start
1078
+ // lead per §4, so those rows are seeded to `HC_IDENT`; the ASCII rows below
1079
+ // overwrite 0..127 with their real class.
1080
+ const _charClass = new Uint8Array(0x10000).fill(HC_IDENT, 128);
1081
+ const _singleTT = new Uint8Array(128);
1082
+ _singleTT[CC_LEFT_PARENTHESIS] = TT_LEFT_PARENTHESIS;
1083
+ _singleTT[CC_RIGHT_PARENTHESIS] = TT_RIGHT_PARENTHESIS;
1084
+ _singleTT[CC_COMMA] = TT_COMMA;
1085
+ _singleTT[CC_COLON] = TT_COLON;
1086
+ _singleTT[CC_SEMICOLON] = TT_SEMICOLON;
1087
+ _singleTT[CC_LEFT_SQUARE] = TT_LEFT_SQUARE_BRACKET;
1088
+ _singleTT[CC_RIGHT_SQUARE] = TT_RIGHT_SQUARE_BRACKET;
1089
+ _singleTT[CC_LEFT_CURLY] = TT_LEFT_CURLY_BRACKET;
1090
+ _singleTT[CC_RIGHT_CURLY] = TT_RIGHT_CURLY_BRACKET;
1091
+ // Each ASCII code point belongs to exactly one class; HC_SINGLE is seeded from
1092
+ // `_singleTT` above, the rest follow §4's lead-code-point rules, and everything
1093
+ // unmatched stays the delim class (0). Keep this in sync with the table above.
1094
+ for (let i = 0; i < 128; i++) {
1095
+ if (_singleTT[i] !== 0) {
1096
+ _charClass[i] = HC_SINGLE;
1097
+ } else if (_isWhiteSpace(i)) {
1098
+ _charClass[i] = HC_WHITESPACE;
1099
+ } else if (i === CC_QUOTATION_MARK || i === CC_APOSTROPHE) {
1100
+ _charClass[i] = HC_STRING;
1101
+ } else if (i === CC_NUMBER_SIGN) {
1102
+ _charClass[i] = HC_NUMBER_SIGN;
1103
+ } else if (i === CC_PLUS_SIGN) {
1104
+ _charClass[i] = HC_PLUS_SIGN;
1105
+ } else if (i === CC_HYPHEN_MINUS) {
1106
+ _charClass[i] = HC_HYPHEN_MINUS;
1107
+ } else if (i === CC_FULL_STOP) {
1108
+ _charClass[i] = HC_FULL_STOP;
1109
+ } else if (i === CC_LESS_THAN_SIGN) {
1110
+ _charClass[i] = HC_LESS_THAN;
1111
+ } else if (i === CC_AT_SIGN) {
1112
+ _charClass[i] = HC_AT_SIGN;
1113
+ } else if (i === CC_REVERSE_SOLIDUS) {
1114
+ _charClass[i] = HC_REVERSE_SOLIDUS;
1115
+ } else if (_isDigit(i)) {
1116
+ _charClass[i] = HC_DIGIT;
1117
+ } else if (_isIdentStartCodePointCC(i)) {
1118
+ _charClass[i] = HC_IDENT;
1119
+ }
1120
+ // else stays the delim class (0)
1121
+ }
1122
+
1123
+ /**
1124
+ * Per-character dispatcher. The outer loop has already advanced past
1125
+ * the lead code point (`pos - 1` is the lead).
1126
+ * @param {string} input input
1127
+ * @param {number} pos position just past the lead code point
1128
+ * @param {number} cc the lead code point (`input.charCodeAt(pos - 1)`, already read by the caller)
1129
+ * @param {MutableToken} out token to populate
1130
+ * @returns {MutableToken | undefined} the resulting token, or undefined at EOF
1131
+ */
1132
+ function consumeAToken(input, pos, cc, out) {
1133
+ // `u` / `U` would start a unicode-range token in the spec; those are not
1134
+ // produced, so they map to HC_IDENT and fall through to ident-like.
1135
+ switch (_charClass[cc]) {
1136
+ // Run of whitespace → one <whitespace-token>.
1137
+ case HC_WHITESPACE:
1138
+ return consumeSpace(input, pos, out);
1139
+ // `"` / `'` → <string-token> (or <bad-string-token> on a raw newline).
1140
+ case HC_STRING:
1141
+ return consumeAStringToken(input, pos, out);
1142
+ // One-code-point token: its type is looked up in `_singleTT` (the `(` `)`
1143
+ // `,` `:` `;` `[` `]` `{` `}` set), so all of them share this arm.
1144
+ case HC_SINGLE:
1145
+ return fill(out, _singleTT[cc], pos - 1, pos);
1146
+ // `#` → <hash-token> if an ident/escape follows, else a <delim-token>.
1147
+ case HC_NUMBER_SIGN:
1148
+ return consumeNumberSign(input, pos, out);
1149
+ // `+` → <number-token> if it starts a number, else a <delim-token>.
1150
+ case HC_PLUS_SIGN:
1151
+ return consumePlusSign(input, pos, out);
1152
+ // `-` → number / <CDC-token> (`-->`) / ident / <delim-token>.
1153
+ case HC_HYPHEN_MINUS:
1154
+ return consumeHyphenMinus(input, pos, out);
1155
+ // `.` → <number-token> if a digit follows, else a <delim-token>.
1156
+ case HC_FULL_STOP:
1157
+ return consumeFullStop(input, pos, out);
1158
+ // `<` → <CDO-token> (`<!--`), else a <delim-token>.
1159
+ case HC_LESS_THAN:
1160
+ return consumeLessThan(input, pos, out);
1161
+ // `@` → <at-keyword-token> if an ident follows, else a <delim-token>.
1162
+ case HC_AT_SIGN:
1163
+ return consumeCommercialAt(input, pos, out);
1164
+ // `\` → ident-like token if it's a valid escape, else a <delim-token>.
1165
+ case HC_REVERSE_SOLIDUS:
1166
+ return consumeReverseSolidus(input, pos, out);
1167
+ // Digit → numeric token; `pos - 1` re-includes the digit the caller passed.
1168
+ case HC_DIGIT:
1169
+ return consumeANumericToken(input, pos - 1, out);
1170
+ // Ident-start (letter / `_` / non-ASCII, incl. `u`/`U`) → ident / function /
1171
+ // url token; `pos - 1` re-includes the lead code point.
1172
+ case HC_IDENT:
1173
+ return consumeAnIdentLikeToken(input, pos - 1, out);
1174
+ default:
1175
+ // HC_DELIM. EOF is impossible here (caller guarded with the outer
1176
+ // loop's `pos < input.length` check). Anything else: a <delim-token>.
1177
+ return fill(out, TT_DELIM, pos - 1, pos);
1178
+ }
1179
+ }
1180
+
1181
+ /**
1182
+ * Read one raw token (comment / whitespace / value token) starting at byte
1183
+ * `pos`, writing it into the caller-supplied `out` and returning `out`. The
1184
+ * token's `end` is the next read position. Returns `undefined` at end-of-input —
1185
+ * `pos >= length`, an unterminated comment, or a string ending on a trailing
1186
+ * escape. This is the shared lexer core: `next` reuses one `out` across calls so
1187
+ * the parse hot path allocates no per-token object; loop over it with a fresh
1188
+ * `out` per call to collect the raw token list (e.g. tests). Comment tokens are
1189
+ * returned here; `next` filters them.
1190
+ * @param {string} input input
1191
+ * @param {number} pos byte offset to read from
1192
+ * @param {MutableToken} out token to populate
1193
+ * @returns {MutableToken | undefined} the token, or undefined at EOF
1194
+ */
1195
+ function readToken(input, pos, out) {
1196
+ if (pos >= input.length) return undefined;
1197
+ const cc = input.charCodeAt(pos);
1198
+ // Comment: `/*…*/` is yielded as a token (filtered by `next`).
1199
+ if (cc === CC_SOLIDUS && input.charCodeAt(pos + 1) === CC_ASTERISK) {
1200
+ const start = pos;
1201
+ // Jump to the closing `*/` in one native scan instead of a per-character
1202
+ // loop — comment bodies (license banners, source comments) can be long.
1203
+ // No close: unterminated comment runs to EOF so ranges cover all input.
1204
+ const close = input.indexOf("*/", pos + 2);
1205
+ return fill(
1206
+ out,
1207
+ TT_COMMENT,
1208
+ start,
1209
+ close === -1 ? input.length : close + 2
1210
+ );
1211
+ }
1212
+ // `consumeAToken` dispatches on the lead code point at `pos` (it expects the
1213
+ // position just past the lead and the already-read lead code point).
1214
+ return consumeAToken(input, pos + 1, cc, out);
1215
+ }
1216
+
1217
+ // AST shape mirrors tabatkins/parse-css (the CSS Syntax Level 3 reference), with two deviations: nodes carry a `range` byte offset pair + a lazy `loc` getter, and have no methods beyond it.
1218
+
1219
+ /**
1220
+ * AST node / leaf-token `type` discriminators (spec name where it has one, else
1221
+ * parse-css's PascalCase). Numeric for the same reasons as the `TT_*` token
1222
+ * constants: a compact `Node#type` slot and integer `===` / `Map` keys on the
1223
+ * visitor hot path. Kept as a `NodeType` namespace (not bare constants) because
1224
+ * consumers reference members as `NodeType.AtRule`; exported so visitor maps
1225
+ * (`SourceProcessor#use`) and `CssParser` name nodes instead of a string
1226
+ * literal. A lexer token type never reaches a `Node#type`.
1227
+ * @enum {number}
1228
+ */
1229
+ const NodeType = {
1230
+ Ident: 1,
1231
+ Function: 2,
1232
+ AtKeyword: 3,
1233
+ Hash: 4,
1234
+ String: 5,
1235
+ BadString: 6,
1236
+ Url: 7,
1237
+ BadUrl: 8,
1238
+ Delim: 9,
1239
+ Number: 10,
1240
+ Percentage: 11,
1241
+ Dimension: 12,
1242
+ Whitespace: 13,
1243
+ Colon: 14,
1244
+ Semicolon: 15,
1245
+ Comma: 16,
1246
+ // Preserved tokens for stray closers / CDO / CDC (kept as component values per §5.4.8 "consume a token and return it").
1247
+ RightParenthesis: 17,
1248
+ RightSquareBracket: 18,
1249
+ RightCurlyBracket: 19,
1250
+ CDO: 20,
1251
+ CDC: 21,
1252
+ SimpleBlock: 22,
1253
+ Declaration: 23,
1254
+ AtRule: 24,
1255
+ QualifiedRule: 25,
1256
+ Stylesheet: 26,
1257
+ // Comments are never tree nodes; this type exists only so a `NodeType.Comment`
1258
+ // visitor can be registered (fired during tokenization — see `grammar`).
1259
+ Comment: 27
1260
+ };
1261
+ const {
1262
+ Ident: T_IDENT,
1263
+ Function: T_FUNCTION,
1264
+ AtKeyword: T_AT_KEYWORD,
1265
+ Hash: T_HASH,
1266
+ String: T_STRING,
1267
+ BadString: T_BAD_STRING,
1268
+ Url: T_URL,
1269
+ BadUrl: T_BAD_URL,
1270
+ Delim: T_DELIM,
1271
+ Number: T_NUMBER,
1272
+ Percentage: T_PERCENTAGE,
1273
+ Dimension: T_DIMENSION,
1274
+ Whitespace: T_WHITESPACE,
1275
+ Colon: T_COLON,
1276
+ Semicolon: T_SEMICOLON,
1277
+ Comma: T_COMMA,
1278
+ RightParenthesis: T_RIGHT_PARENTHESIS,
1279
+ RightSquareBracket: T_RIGHT_SQUARE_BRACKET,
1280
+ RightCurlyBracket: T_RIGHT_CURLY_BRACKET,
1281
+ CDO: T_CDO,
1282
+ CDC: T_CDC,
1283
+ SimpleBlock: T_SIMPLE_BLOCK,
1284
+ Declaration: T_DECLARATION,
1285
+ AtRule: T_AT_RULE,
1286
+ QualifiedRule: T_QUALIFIED_RULE,
1287
+ Stylesheet: T_STYLESHEET,
1288
+ Comment: T_COMMENT
1289
+ } = NodeType;
1290
+
1291
+ /**
1292
+ * Base AST node. All concrete nodes (tokens, simple blocks, functions,
1293
+ * declarations) inherit from this and carry the `[start, end)` byte `range`
1294
+ * of the source slice they cover. `loc` is computed on demand from a
1295
+ * shared `LocConverter` so we don't pay for line/column conversion until
1296
+ * a consumer (warning, error, dependency) actually needs it.
1297
+ */
1298
+ class Node {
1299
+ /**
1300
+ * @param {number} type node type discriminator
1301
+ * @param {number} start byte offset of the node's first code point
1302
+ * @param {number} end byte offset just past the node's last code point
1303
+ * @param {LocConverter} locConverter shared loc converter
1304
+ */
1305
+ constructor(type, start, end, locConverter) {
1306
+ /** @type {number} */
1307
+ this.type = type;
1308
+ // Byte range as two inline fields rather than a `[start, end]` array —
1309
+ // one fewer allocation per node and ~56 bytes lighter (×100k+ nodes).
1310
+ /** @type {number} */
1311
+ this.start = start;
1312
+ /** @type {number} */
1313
+ this.end = end;
1314
+ /** @type {LocConverter} */
1315
+ this._locConverter = locConverter;
1316
+ }
1317
+
1318
+ /**
1319
+ * The `[start, end)` byte range as a tuple — compatibility view over
1320
+ * `start` / `end` (builds the array lazily; hot code reads the
1321
+ * fields directly).
1322
+ * @returns {[number, number]} the byte range
1323
+ */
1324
+ get range() {
1325
+ return [this.start, this.end];
1326
+ }
1327
+
1328
+ get loc() {
1329
+ const lc = this._locConverter;
1330
+ // `LocConverter#get` mutates and returns the converter itself, so we
1331
+ // must snapshot `line`/`column` between the two calls.
1332
+ const s = lc.get(this.start);
1333
+ const sl = s.line;
1334
+ const sc = s.column;
1335
+ const e = lc.get(this.end);
1336
+ return {
1337
+ start: { line: sl, column: sc },
1338
+ end: { line: e.line, column: e.column }
1339
+ };
1340
+ }
1341
+
1342
+ /**
1343
+ * Serialize back to source — re-slices the original input (zero-alloc for
1344
+ * untouched nodes).
1345
+ * @returns {string} the source slice for this node
1346
+ */
1347
+ toString() {
1348
+ return this._locConverter._input.slice(this.start, this.end);
1349
+ }
1350
+
1351
+ /**
1352
+ * For name-bearing nodes (function / at-rule): the `name` with CSS escapes
1353
+ * resolved, for case-insensitive keyword matching (`\75 rl` → `url`). Computed
1354
+ * on read via `unescapeIdentifier`'s no-escape fast path. Callers without a
1355
+ * `name` must not read this.
1356
+ * @returns {string} the unescaped name
1357
+ */
1358
+ get unescapedName() {
1359
+ return unescapeIdentifier(
1360
+ /** @type {{ name: string }} */ (/** @type {unknown} */ (this)).name
1361
+ );
1362
+ }
1363
+ }
1364
+
1365
+ /**
1366
+ * @param {string} s numeric text
1367
+ * @returns {"+" | "-" | ""} the spec sign ("" when unsigned)
1368
+ */
1369
+ const _signOf = (s) => {
1370
+ const c = s.charCodeAt(0);
1371
+ return c === CC_PLUS_SIGN ? "+" : c === CC_HYPHEN_MINUS ? "-" : "";
1372
+ };
1373
+
1374
+ /**
1375
+ * @param {string} s numeric text (no unit / `%`)
1376
+ * @returns {"integer" | "number"} the spec type flag
1377
+ */
1378
+ const _typeFlagOf = (s) =>
1379
+ s.includes(".") || s.includes("e") || s.includes("E") ? "number" : "integer";
1380
+
1381
+ /**
1382
+ * Leaf token node — the only `Node` subclass. `value` is the raw source slice
1383
+ * (identifier text, quoted string including quotes, a dimension's full `123px`,
1384
+ * …). Token-specific extras are named by the `HashToken` / `UrlToken` /
1385
+ * `NumberToken` / `DimensionToken` shape typedefs below.
1386
+ *
1387
+ * The numeric accessors (`numericValue` / `typeFlag` / `sign` / `unit`) are
1388
+ * getters, not stored fields: a number / dimension / percentage token costs
1389
+ * nothing beyond the base node unless a consumer reads them, and every leaf
1390
+ * token keeps a single object shape so the walker's `node.type` dispatch stays
1391
+ * monomorphic. They are only meaningful on the matching token type.
1392
+ */
1393
+ class Token extends Node {
1394
+ /**
1395
+ * @param {number} type node type
1396
+ * @param {number} start byte offset of the token's first code point
1397
+ * @param {number} end byte offset just past the token's last code point
1398
+ * @param {LocConverter} locConverter shared loc converter
1399
+ */
1400
+ // No own fields: a leaf token is exactly a `Node` plus the value getters
1401
+ // below. `value` is derived from the byte range on read instead of cached in
1402
+ // a `_value` slot — most tokens (whitespace, punctuation) never read it, and
1403
+ // dropping the slot is ~8 bytes saved on every token (the bulk of all nodes).
1404
+ // hash / at-keyword strip their `#` / `@` prefix; url uses its content range
1405
+ // (`contentStart` / `contentEnd`, the token's only own fields).
1406
+
1407
+ /**
1408
+ * @returns {string} the token's value (raw source slice unless overridden)
1409
+ */
1410
+ get value() {
1411
+ const input = this._locConverter._input;
1412
+ const type = this.type;
1413
+ // hash (`#name` → `name`) and at-keyword (`@name` → `name`) drop one char.
1414
+ if (type === T_HASH || type === T_AT_KEYWORD) {
1415
+ return input.slice(this.start + 1, this.end);
1416
+ }
1417
+ if (type === T_URL) {
1418
+ const u = /** @type {UrlToken} */ (/** @type {unknown} */ (this));
1419
+ return input.slice(u.contentStart, u.contentEnd);
1420
+ }
1421
+ return input.slice(this.start, this.end);
1422
+ }
1423
+
1424
+ /**
1425
+ * The token's value with CSS escapes resolved (`\2d` → `-`, `\75 rl` → `url`),
1426
+ * per https://www.w3.org/TR/css-syntax-3/#consume-escaped-code-point — the
1427
+ * form to match keywords / export as a CSS-Modules name against. For a string
1428
+ * token it is the content between the quotes (the spec string value). Computed
1429
+ * on read; `unescapeIdentifier` fast-returns the value unchanged when it has no
1430
+ * escapes (the common case), so nothing is stored per token.
1431
+ * @returns {string} the unescaped value
1432
+ */
1433
+ get unescaped() {
1434
+ const v = this.value;
1435
+ // A string token's `value` carries its delimiting quotes; its value is the content between them.
1436
+ return this.type === T_STRING
1437
+ ? unescapeIdentifier(v.slice(1, -1))
1438
+ : unescapeIdentifier(v);
1439
+ }
1440
+
1441
+ /**
1442
+ * Parsed numeric value (number / percentage / dimension tokens). Derived from
1443
+ * `value` on access — the `%` is dropped for percentages and the unit for
1444
+ * dimensions (split with `_consumeANumber`, recomputed here so nothing is
1445
+ * stored per token).
1446
+ * @returns {number} the parsed numeric value
1447
+ */
1448
+ get numericValue() {
1449
+ const v = this.value;
1450
+ if (this.type === T_DIMENSION) {
1451
+ return Number(v.slice(0, _consumeANumber(v, 0)));
1452
+ }
1453
+ if (this.type === T_PERCENTAGE) return Number(v.slice(0, -1));
1454
+ return Number(v);
1455
+ }
1456
+
1457
+ /**
1458
+ * Spec type flag. For number / dimension tokens it's "integer" / "number"
1459
+ * (derived from `value`); for hash tokens it's "id" / "unrestricted" (re-derived
1460
+ * from the source). The two senses share the name in the spec; both are computed
1461
+ * on read so every leaf token keeps the same object shape (no own `typeFlag`).
1462
+ * @returns {"integer" | "number" | "id" | "unrestricted"} the spec type flag
1463
+ */
1464
+ get typeFlag() {
1465
+ if (this.type === T_HASH) {
1466
+ // Re-derive id-ness from the source (whether the name after `#` starts an
1467
+ // ident sequence) rather than storing an `_isId` slot — keeps hash tokens
1468
+ // the same shape as every other leaf token. Matches the lexer's
1469
+ // `consumeNumberSign`, which sets `isId` from the same check.
1470
+ const input = this._locConverter._input;
1471
+ const p = this.start + 1;
1472
+ return _ifThreeCodePointsWouldStartAnIdentSequence(
1473
+ input,
1474
+ p,
1475
+ input.charCodeAt(p),
1476
+ input.charCodeAt(p + 1),
1477
+ input.charCodeAt(p + 2)
1478
+ )
1479
+ ? "id"
1480
+ : "unrestricted";
1481
+ }
1482
+ const v = this.value;
1483
+ return _typeFlagOf(
1484
+ this.type === T_DIMENSION ? v.slice(0, _consumeANumber(v, 0)) : v
1485
+ );
1486
+ }
1487
+
1488
+ /**
1489
+ * @returns {"+" | "-" | ""} the spec sign (number / percentage / dimension tokens)
1490
+ */
1491
+ get sign() {
1492
+ return _signOf(this.value);
1493
+ }
1494
+
1495
+ /**
1496
+ * @returns {string} the unit, lower-cased per spec (dimension tokens)
1497
+ */
1498
+ get unit() {
1499
+ const v = this.value;
1500
+ return v.slice(_consumeANumber(v, 0)).toLowerCase();
1501
+ }
1502
+ }
1503
+
1504
+ /**
1505
+ * The non-leaf `Node` subclass: functions, simple blocks, declarations, at-rules
1506
+ * and qualified rules. It declares the union of every container field up front so
1507
+ * all five share **one** hidden class — the consume algorithms only overwrite the
1508
+ * slots relevant to their type, never adding a property, so the shape never
1509
+ * transitions. This caps the shape count: the walker's hot `.type` / `.value` /
1510
+ * `.prelude` loads otherwise see eight distinct node maps (five container types
1511
+ * plus the token / hash / url token maps), tipping V8's inline cache into the
1512
+ * slow megamorphic path; folding the five containers into one leaves four maps
1513
+ * (token, hash, url, container) — within the polymorphic limit, so those loads
1514
+ * stay inline-cached. Unused-for-the-type slots keep their defaults (the field
1515
+ * typedefs below document which fields each type uses). The stylesheet node is
1516
+ * rare (one per parse) and stays a bare `Node`.
1517
+ */
1518
+ class Container extends Node {
1519
+ /**
1520
+ * @param {number} type node type
1521
+ * @param {number} start byte offset of the node's first code point
1522
+ * @param {number} end byte offset just past the node's last code point
1523
+ * @param {LocConverter} locConverter shared loc converter
1524
+ */
1525
+ constructor(type, start, end, locConverter) {
1526
+ super(type, start, end, locConverter);
1527
+ /** @type {string} name (function / at-rule / declaration) */
1528
+ this.name = "";
1529
+ /** @type {number} */
1530
+ this.nameStart = start;
1531
+ /** @type {number} */
1532
+ this.nameEnd = start;
1533
+ /** @type {ComponentValue[] | null} component values (function / block / declaration) */
1534
+ this.value = null;
1535
+ /** @type {ComponentValue[] | null} prelude (at-rule / qualified rule) */
1536
+ this.prelude = null;
1537
+ /** @type {Declaration[] | null} */
1538
+ this.declarations = null;
1539
+ /** @type {Rule[] | null} */
1540
+ this.childRules = null;
1541
+ /** @type {number} `{` start offset, or -1 (at-rule / qualified rule) */
1542
+ this.blockStart = -1;
1543
+ /** @type {number} `}` end offset, or -1 (at-rule / qualified rule) */
1544
+ this.blockEnd = -1;
1545
+ /** @type {boolean} stripped `!important` (declaration) */
1546
+ this.important = false;
1547
+ /** @type {SimpleBlockToken | undefined} opening char (simple block) */
1548
+ this.token = undefined;
1549
+ }
1550
+ }
1551
+
1552
+ /**
1553
+ * Number token (`123`, `-1.5`, `+2e3`). `value` is the raw source slice (the spec's "value"); `numericValue` / `typeFlag` / `sign` are lazy getters derived from it (see `Token`).
1554
+ * @typedef {Token & { numericValue: number, typeFlag: "integer" | "number", sign: "+" | "-" | "" }} NumberToken
1555
+ */
1556
+
1557
+ /**
1558
+ * Percentage token (`50%`). `value` is the raw slice including `%`; `numericValue` (without `%`) and `sign` are lazy getters.
1559
+ * @typedef {Token & { numericValue: number, sign: "+" | "-" | "" }} PercentageToken
1560
+ */
1561
+
1562
+ /**
1563
+ * Dimension token (`100px`, `1.5em`). `value` is the raw slice (number + unit); `numericValue` / `typeFlag` / `sign` (of the numeric part) and `unit` (lower-cased) are lazy getters.
1564
+ * @typedef {Token & { numericValue: number, typeFlag: "integer" | "number", sign: "+" | "-" | "", unit: string }} DimensionToken
1565
+ */
1566
+
1567
+ // Spec "Assert: …" preconditions are comments only (callers satisfy them); a future `strict` option could reinstate them as throws.
1568
+
1569
+ /**
1570
+ * Hash token (`#foo`). `value` is the name without the leading `#`; `typeFlag` is the spec type flag ("id" when the name forms a valid `<id>` selector, "unrestricted" otherwise).
1571
+ * @typedef {Token & { typeFlag: "id" | "unrestricted" }} HashToken
1572
+ */
1573
+
1574
+ /**
1575
+ * Old-style unquoted URL token (`url(unquoted)`). `value` is the unquoted body;
1576
+ * `contentStart` / `contentEnd` mark the inner content range in the source.
1577
+ * @typedef {Token & { contentStart: number, contentEnd: number }} UrlToken
1578
+ */
1579
+
1580
+ /**
1581
+ * Function node: `name(component-values...)`. `name` is the raw source slice
1582
+ * before the `(` (callers lowercase / unescape as needed); `nameStart` / `nameEnd`
1583
+ * are its `[start, end)` byte offsets; `value` is the component values inside the parentheses.
1584
+ * @typedef {Node & { name: string, nameStart: number, nameEnd: number, value: ComponentValue[] }} FunctionNode
1585
+ */
1586
+
1587
+ /** @typedef {"[" | "(" | "{"} SimpleBlockToken */
1588
+
1589
+ /**
1590
+ * Simple block (`[...]`, `(...)` not preceded by an ident, `{...}`). `token` is
1591
+ * the opening character. `value` is the component values inside. This shape is
1592
+ * produced by `consumeASimpleBlock` (§5.4.9) and appears in preludes.
1593
+ *
1594
+ * Note: `consumeABlock` (§5.4.4) returns the parsed block's separate `decls` /
1595
+ * `rules` lists (per §5.4.5), not a SimpleBlock wrapper — see
1596
+ * `AtRule` / `QualifiedRule`'s `declarations` and `childRules` fields.
1597
+ * @typedef {Node & { token: SimpleBlockToken, value: ComponentValue[] }} SimpleBlock
1598
+ */
1599
+
1600
+ /**
1601
+ * A CSS component value (CSS Syntax §5.4.8): a preserved token, a function, or
1602
+ * a simple block (`Token` also covers `HashToken` / `UrlToken`).
1603
+ * @typedef {Token | FunctionNode | SimpleBlock} ComponentValue
1604
+ */
1605
+
1606
+ /**
1607
+ * A CSS rule — an at-rule or a qualified rule.
1608
+ * @typedef {AtRule | QualifiedRule} Rule
1609
+ */
1610
+
1611
+ /**
1612
+ * Declaration: `name: value [!important][;]`. `name` is the raw property-name
1613
+ * slice; `value` is the trimmed component-value list (whitespace stripped from
1614
+ * both ends); `important` records a stripped `!important`.
1615
+ * @typedef {Node & { name: string, nameStart: number, nameEnd: number, value: ComponentValue[], important: boolean }} Declaration
1616
+ */
1617
+
1618
+ /**
1619
+ * At-rule: `@name <prelude> ;` or `@name <prelude> { ... }`. `name` is the
1620
+ * at-keyword without the leading `@`; `prelude` is the component values up to
1621
+ * the at-rule's `;` / block / enclosing `}`. Per §5.4.2 the block is consumed
1622
+ * into separate `declarations` (a `Declaration[]`) and `childRules` (a `Rule[]`,
1623
+ * each an at-rule or qualified rule); both are `null` for a `;`-terminated
1624
+ * at-rule. `blockStart` / `blockEnd` are the `{` start / `}` end offsets
1625
+ * (webpack extension, not in spec; the spec doesn't track brace positions), or
1626
+ * `-1` / `-1` when there is no block. `range[1]` points past `}` for a block, or
1627
+ * at the `;` / `}` / EOF position otherwise (callers check the byte at `range[1]`
1628
+ * to tell them apart).
1629
+ * @typedef {Node & { name: string, nameStart: number, nameEnd: number, prelude: ComponentValue[], declarations: Declaration[] | null, childRules: Rule[] | null, blockStart: number, blockEnd: number }} AtRule
1630
+ */
1631
+
1632
+ /**
1633
+ * Qualified rule: `<prelude> { <block> }`. `prelude` is the component values
1634
+ * before the `{` (selectors, keyframe parameters, …); `declarations` and
1635
+ * `childRules` are the parsed `{ ... }` body (split per tabatkins/parse-css.js
1636
+ * reference impl), or both `null` when EOF was hit before `{`. `blockStart` /
1637
+ * `blockEnd` are the `{` start / `}` end offsets (webpack extension), or `-1` /
1638
+ * `-1` when there is no block.
1639
+ * @typedef {Node & { prelude: ComponentValue[], declarations: Declaration[] | null, childRules: Rule[] | null, blockStart: number, blockEnd: number }} QualifiedRule
1640
+ */
1641
+
1642
+ /**
1643
+ * Stylesheet (CSS Syntax §5.3.4): the result of `parseAStylesheet`. `rules`
1644
+ * holds the top-level at-rules / qualified rules (top-level declarations are
1645
+ * parse errors and never produced).
1646
+ * @typedef {Node & { rules: Rule[] }} Stylesheet
1647
+ */
1648
+
1649
+ // Lexer-token-type → AST-node-type map. A single \`new Token\` construct site
1650
+ // (vs a ~20-case switch with a \`new Token\` in each arm) keeps V8 on the fast
1651
+ // monomorphic allocation path — the switch form showed up as generic construct
1652
+ // stubs in profiles. URL is the one type with extra own state, handled first.
1653
+ const _ttToNodeType = new Uint8Array(27);
1654
+ _ttToNodeType[TT_WHITESPACE] = T_WHITESPACE;
1655
+ _ttToNodeType[TT_IDENTIFIER] = T_IDENT;
1656
+ _ttToNodeType[TT_STRING] = T_STRING;
1657
+ _ttToNodeType[TT_DELIM] = T_DELIM;
1658
+ _ttToNodeType[TT_NUMBER] = T_NUMBER;
1659
+ _ttToNodeType[TT_PERCENTAGE] = T_PERCENTAGE;
1660
+ _ttToNodeType[TT_DIMENSION] = T_DIMENSION;
1661
+ _ttToNodeType[TT_HASH] = T_HASH;
1662
+ _ttToNodeType[TT_AT_KEYWORD] = T_AT_KEYWORD;
1663
+ _ttToNodeType[TT_BAD_STRING_TOKEN] = T_BAD_STRING;
1664
+ _ttToNodeType[TT_BAD_URL_TOKEN] = T_BAD_URL;
1665
+ _ttToNodeType[TT_COLON] = T_COLON;
1666
+ _ttToNodeType[TT_COMMA] = T_COMMA;
1667
+ _ttToNodeType[TT_SEMICOLON] = T_SEMICOLON;
1668
+ _ttToNodeType[TT_RIGHT_PARENTHESIS] = T_RIGHT_PARENTHESIS;
1669
+ _ttToNodeType[TT_RIGHT_SQUARE_BRACKET] = T_RIGHT_SQUARE_BRACKET;
1670
+ _ttToNodeType[TT_RIGHT_CURLY_BRACKET] = T_RIGHT_CURLY_BRACKET;
1671
+ _ttToNodeType[TT_CDO] = T_CDO;
1672
+ _ttToNodeType[TT_CDC] = T_CDC;
1673
+
1674
+ // === AST construction backend ===
1675
+ // The consume algorithms build nodes through these module-level primitives
1676
+ // rather than `new Token` / `new Container` directly, so the node
1677
+ // representation can be swapped under the parser. The object backend below
1678
+ // builds the retainable `Node` / `Token` / `Container` tree the `parseA*`
1679
+ // entry points return; the Struct-of-Arrays backend (added separately) writes
1680
+ // the same nodes into reused typed arrays for the streaming `grammar`, where
1681
+ // per-node allocation dominates cost. Child lists are plain arrays in both
1682
+ // backends (a node ref is an object or an integer index); only node creation /
1683
+ // field access differs, so only those ops are swapped.
1684
+
1685
+ // Current loc converter for the active parse (object backend reads it).
1686
+ let _objLocConverter = /** @type {LocConverter} */ (
1687
+ /** @type {unknown} */ (null)
1688
+ );
1689
+
1690
+ // Active skip state (from `CssProcessOptions.skip`), applied by the grammar.
1691
+ // `_skipTypes` is indexed by `NodeType` (1 = skip): drop that component-value
1692
+ // leaf / container from declaration value and function-arg lists. The two
1693
+ // prelude flags scan a rule's prelude without materializing its tree (url tokens
1694
+ // / functions kept, so `url()` in a selector or `@import url(…)` still resolves).
1695
+ // A skipped node is still tokenized (positions stay correct) but never pushed,
1696
+ // so it is never walked or read — the caller must only skip what nothing reads.
1697
+ // `useObjectBackend` restores the defaults so `parseA*` build the full tree.
1698
+ const _NO_SKIP_TYPES = new Uint8Array(32);
1699
+ // Shared frozen empty list for block bodies with no decls / no child rules (the
1700
+ // common case — most rules carry only declarations). Every consumer reads these
1701
+ // lists read-only and null-guards, so one immutable instance replaces ~one empty
1702
+ // array allocation per rule; frozen so any errant push fails loud.
1703
+ const _EMPTY_LIST = /** @type {Rule[]} */ (
1704
+ /** @type {unknown} */ (Object.freeze([]))
1705
+ );
1706
+ /** @type {Uint8Array} */
1707
+ let _skipTypes = _NO_SKIP_TYPES;
1708
+ // Fast-path flag: true only when a real skip set is active, so the (dominant)
1709
+ // no-skip parses pay one boolean test instead of a node-type lookup per value.
1710
+ let _skipActive = false;
1711
+ let _skipSelectorPrelude = false;
1712
+ let _skipAtRulePrelude = false;
1713
+
1714
+ /** @type {(type: number, start: number, end: number) => Node} */
1715
+ let _makeLeaf;
1716
+ /** @type {(start: number, end: number, contentStart: number, contentEnd: number) => Node} */
1717
+ let _makeUrl;
1718
+ /** @type {(type: number, start: number, end: number) => Node} */
1719
+ let _makeContainer;
1720
+ /** @type {(start: number) => Node} */
1721
+ let _makeStylesheet;
1722
+ // Offsets only — the object backend derives the name string itself (an
1723
+ // at-rule's name skips its `@`), so the SoA backend never pays for a slice
1724
+ // it would immediately discard (it re-derives names from offsets on read).
1725
+ /** @type {(r: Node, nameStart: number, nameEnd: number) => void} */
1726
+ let _setName;
1727
+ /** @type {(r: Node, v: number) => void} */
1728
+ let _setEnd;
1729
+ /** @type {(r: Node, blockStart: number, blockEnd: number) => void} */
1730
+ let _setBlock;
1731
+ /** @type {(r: Node) => void} */
1732
+ let _setImportant;
1733
+ /** @type {(r: Node, ch: SimpleBlockToken) => void} */
1734
+ let _setToken;
1735
+ /** @type {(r: Node, list: Node[]) => void} */
1736
+ let _setValue;
1737
+ /** @type {(r: Node, list: Node[]) => void} */
1738
+ let _setPrelude;
1739
+ /** @type {(r: Node, decls: Node[], childRules: Node[]) => void} */
1740
+ let _setBody;
1741
+ /** @type {(r: Node, list: Node[]) => void} */
1742
+ let _setRules;
1743
+ /** @type {(r: Node) => number} */
1744
+ let _nodeTypeOf;
1745
+ /** @type {(r: Node) => number} */
1746
+ let _nodeStartOf;
1747
+ /** @type {(r: Node) => string} */
1748
+ let _nodeValueOf;
1749
+ /** @type {(r: Node) => SimpleBlockToken} */
1750
+ let _nodeTokenOf;
1751
+
1752
+ // Child lists are plain arrays in every backend; refs are pushed by value.
1753
+ // Content-list allocation: the object backend uses a per-site `[]` literal
1754
+ // (each site keeps its own V8 allocation site — a shared helper collapses them
1755
+ // and defeats escape analysis / pretenuring), the SoA backend recycles scratch
1756
+ // arrays through a pool — a sealed list is copied into the flat value buffer
1757
+ // and its array returned to the pool by `_soaSetValue`, so the streaming parse
1758
+ // allocates no per-list array. An abandoned (never-sealed) list simply falls
1759
+ // out of the pool. `_soaActive` gates the pool at each site.
1760
+ let _soaActive = false;
1761
+ /** @type {Node[][]} */
1762
+ const _listPool = [];
1763
+ const _soaList = () =>
1764
+ _listPool.length > 0
1765
+ ? /** @type {Node[]} */ (_listPool.pop())
1766
+ : /** @type {Node[]} */ ([]);
1767
+
1768
+ // -- object backend: builds the retainable class-instance tree --
1769
+ /** @type {typeof _makeLeaf} */
1770
+ const _objLeaf = (type, start, end) =>
1771
+ new Token(type, start, end, _objLocConverter);
1772
+ /** @type {typeof _makeUrl} */
1773
+ const _objUrl = (start, end, cs, ce) => {
1774
+ const u = /** @type {UrlToken} */ (
1775
+ new Token(T_URL, start, end, _objLocConverter)
1776
+ );
1777
+ u.contentStart = cs;
1778
+ u.contentEnd = ce;
1779
+ return u;
1780
+ };
1781
+ /** @type {typeof _makeContainer} */
1782
+ const _objContainer = (type, start, end) =>
1783
+ new Container(type, start, end, _objLocConverter);
1784
+ /** @type {typeof _makeStylesheet} */
1785
+ const _objStylesheet = (start) => {
1786
+ const s = /** @type {Stylesheet} */ (
1787
+ new Node(T_STYLESHEET, start, start, _objLocConverter)
1788
+ );
1789
+ s.rules = [];
1790
+ return s;
1791
+ };
1792
+ // The backend function sets are module-level constants (not closures rebuilt
1793
+ // per parse): the dispatch slots keep one function identity forever, so the
1794
+ // per-node call sites in the consume algorithms stay monomorphic instead of
1795
+ // seeing a fresh closure per parse. They capture only module-level state.
1796
+ /** @type {typeof _setName} */
1797
+ const _objSetName = (r, ns, ne) => {
1798
+ const c = /** @type {Container} */ (r);
1799
+ // An at-rule's `nameStart` points at its `@`, which the name excludes.
1800
+ c.name = _objLocConverter._input.slice(
1801
+ r.type === T_AT_RULE ? ns + 1 : ns,
1802
+ ne
1803
+ );
1804
+ c.nameStart = ns;
1805
+ c.nameEnd = ne;
1806
+ };
1807
+ /** @type {typeof _setEnd} */
1808
+ const _objSetEnd = (r, v) => {
1809
+ r.end = v;
1810
+ };
1811
+ /** @type {typeof _setBlock} */
1812
+ const _objSetBlock = (r, bs, be) => {
1813
+ const c = /** @type {Container} */ (r);
1814
+ c.blockStart = bs;
1815
+ c.blockEnd = be;
1816
+ };
1817
+ /** @type {typeof _setImportant} */
1818
+ const _objSetImportant = (r) => {
1819
+ /** @type {Container} */ (r).important = true;
1820
+ };
1821
+ /** @type {typeof _setToken} */
1822
+ const _objSetToken = (r, ch) => {
1823
+ /** @type {Container} */ (r).token = ch;
1824
+ };
1825
+ /** @type {typeof _setValue} */
1826
+ const _objSetValue = (r, list) => {
1827
+ /** @type {Container} */ (r).value = /** @type {ComponentValue[]} */ (list);
1828
+ };
1829
+ /** @type {typeof _setPrelude} */
1830
+ const _objSetPrelude = (r, list) => {
1831
+ /** @type {Container} */ (r).prelude = /** @type {ComponentValue[]} */ (list);
1832
+ };
1833
+ /** @type {typeof _setBody} */
1834
+ const _objSetBody = (r, decls, childRules) => {
1835
+ const c = /** @type {Container} */ (r);
1836
+ c.declarations = /** @type {Declaration[]} */ (decls);
1837
+ c.childRules = /** @type {Rule[]} */ (childRules);
1838
+ };
1839
+ /** @type {typeof _setRules} */
1840
+ const _objSetRules = (r, list) => {
1841
+ /** @type {Stylesheet} */ (r).rules = /** @type {Rule[]} */ (list);
1842
+ };
1843
+ /** @type {typeof _nodeTypeOf} */
1844
+ const _objNodeTypeOf = (r) => r.type;
1845
+ /** @type {typeof _nodeStartOf} */
1846
+ const _objNodeStartOf = (r) => r.start;
1847
+ /** @type {typeof _nodeValueOf} */
1848
+ const _objNodeValueOf = (r) => /** @type {Token} */ (r).value;
1849
+ /** @type {typeof _nodeTokenOf} */
1850
+ const _objNodeTokenOf = (r) =>
1851
+ /** @type {SimpleBlockToken} */ (/** @type {Container} */ (r).token);
1852
+ /** @param {LocConverter} lc loc converter for this parse */
1853
+ const useObjectBackend = (lc) => {
1854
+ _objLocConverter = lc;
1855
+ _soaActive = false;
1856
+ // `parseA*` return the full tree, so nothing is skipped.
1857
+ _skipTypes = _NO_SKIP_TYPES;
1858
+ _skipActive = false;
1859
+ _skipSelectorPrelude = false;
1860
+ _skipAtRulePrelude = false;
1861
+ _makeLeaf = _objLeaf;
1862
+ _makeUrl = _objUrl;
1863
+ _makeContainer = _objContainer;
1864
+ _makeStylesheet = _objStylesheet;
1865
+ _setName = _objSetName;
1866
+ _setEnd = _objSetEnd;
1867
+ _setBlock = _objSetBlock;
1868
+ _setImportant = _objSetImportant;
1869
+ _setToken = _objSetToken;
1870
+ _setValue = _objSetValue;
1871
+ _setPrelude = _objSetPrelude;
1872
+ _setBody = _objSetBody;
1873
+ _setRules = _objSetRules;
1874
+ _nodeTypeOf = _objNodeTypeOf;
1875
+ _nodeStartOf = _objNodeStartOf;
1876
+ _nodeValueOf = _objNodeValueOf;
1877
+ _nodeTokenOf = _objNodeTokenOf;
1878
+ };
1879
+
1880
+ // -- struct-of-arrays backend: writes nodes into reused typed arrays --
1881
+ // A node ref is its integer id; fields live in parallel arrays indexed by id.
1882
+ // Three reused int slots (`_soaAux0/1/2`) plus a flags byte carry the per-type
1883
+ // extras; child lists hang off three object arrays. Aux slot meaning by type:
1884
+ // url: aux0 contentStart, aux1 contentEnd
1885
+ // function: aux0 nameEnd
1886
+ // declaration: aux0 nameEnd, flags bit0 important
1887
+ // at-rule: aux0 nameEnd, aux1 blockStart, aux2 blockEnd
1888
+ // qualified: aux1 blockStart, aux2 blockEnd
1889
+ // `name` / `nameStart` / a simple block's `token` are derived from the source
1890
+ // on read (see the SoA accessors), so they need no slot. A node's main content
1891
+ // (value | prelude | stylesheet rules) is a `_soaFlat` span (see below).
1892
+ // `grammar` resets `_soaNodeCount` to 0 after each top-level rule's walk, so the
1893
+ // buffers are reused across rules and the parse allocates almost nothing.
1894
+ let _soaCapacity = 0;
1895
+ let _soaNodeCount = 0;
1896
+ let _soaTypes = new Uint8Array(0);
1897
+ let _soaStarts = new Int32Array(0);
1898
+ let _soaEnds = new Int32Array(0);
1899
+ let _soaAux0 = new Int32Array(0);
1900
+ let _soaAux1 = new Int32Array(0);
1901
+ let _soaAux2 = new Int32Array(0);
1902
+ let _soaFlags = new Uint8Array(0);
1903
+ // Content-list spans: a container's value / prelude is `_soaFlat[start, start+len)`
1904
+ // (node refs), recycled per top-level rule like the node columns.
1905
+ let _soaListStarts = new Int32Array(0);
1906
+ let _soaListLens = new Int32Array(0);
1907
+ let _soaFlat = new Int32Array(0);
1908
+ let _soaFlatTop = 0;
1909
+ // Peak usage of the current parse, and use-once regrow hints: after an
1910
+ // over-capacity shrink the next grow jumps straight back to the previous
1911
+ // parse's peak (one exact-fit allocation instead of re-doubling up).
1912
+ let _soaPeak = 0;
1913
+ let _soaFlatPeak = 0;
1914
+ let _soaGrowHint = 0;
1915
+ let _soaFlatGrowHint = 0;
1916
+
1917
+ /** @param {number} need minimum flat-buffer capacity */
1918
+ const _soaFlatGrow = (need) => {
1919
+ let cap = _soaFlat.length || 4096;
1920
+ if (_soaFlatGrowHint > cap) cap = _soaFlatGrowHint;
1921
+ _soaFlatGrowHint = 0;
1922
+ while (cap < need) cap *= 2;
1923
+ const next = new Int32Array(cap);
1924
+ next.set(_soaFlat);
1925
+ _soaFlat = next;
1926
+ };
1927
+ /** @type {(Node[] | null)[]} */
1928
+ const _soaDeclarationLists = [];
1929
+ /** @type {(Node[] | null)[]} */
1930
+ const _soaChildRuleLists = [];
1931
+ let _soaInput = "";
1932
+ let _soaLocConverter = /** @type {LocConverter} */ (
1933
+ /** @type {unknown} */ (null)
1934
+ );
1935
+
1936
+ // Node refs are integers here but typed `Node` across the parser; these are
1937
+ // identity casts that just satisfy the type system at the boundary.
1938
+ /** @type {(n: Node) => number} */
1939
+ const _nodeIndex = (n) => /** @type {number} */ (/** @type {unknown} */ (n));
1940
+ /** @type {(i: number) => Node} */
1941
+ const _nodeRef = (i) => /** @type {Node} */ (/** @type {unknown} */ (i));
1942
+
1943
+ /** @param {number} need minimum capacity */
1944
+ const _soaGrow = (need) => {
1945
+ let cap = _soaCapacity || 4096;
1946
+ if (_soaGrowHint > cap) cap = _soaGrowHint;
1947
+ _soaGrowHint = 0;
1948
+ while (cap < need) cap *= 2;
1949
+ const ty = new Uint8Array(cap);
1950
+ ty.set(_soaTypes);
1951
+ _soaTypes = ty;
1952
+ const st = new Int32Array(cap);
1953
+ st.set(_soaStarts);
1954
+ _soaStarts = st;
1955
+ const en = new Int32Array(cap);
1956
+ en.set(_soaEnds);
1957
+ _soaEnds = en;
1958
+ const a0 = new Int32Array(cap);
1959
+ a0.set(_soaAux0);
1960
+ _soaAux0 = a0;
1961
+ const a1 = new Int32Array(cap);
1962
+ a1.set(_soaAux1);
1963
+ _soaAux1 = a1;
1964
+ const a2 = new Int32Array(cap);
1965
+ a2.set(_soaAux2);
1966
+ _soaAux2 = a2;
1967
+ const fl = new Uint8Array(cap);
1968
+ fl.set(_soaFlags);
1969
+ _soaFlags = fl;
1970
+ const ls = new Int32Array(cap);
1971
+ ls.set(_soaListStarts);
1972
+ _soaListStarts = ls;
1973
+ const ll = new Int32Array(cap);
1974
+ ll.set(_soaListLens);
1975
+ _soaListLens = ll;
1976
+ _soaCapacity = cap;
1977
+ };
1978
+ /** @type {(type: number, start: number, end: number) => Node} */
1979
+ const _soaAllocNode = (type, start, end) => {
1980
+ // Ids are 1-based: a node ref is used in truthiness checks (`if (!parent)`),
1981
+ // so 0 must stay reserved for "no node".
1982
+ // Leaves never read the flag / list slots — `_soaAllocContainer` clears
1983
+ // them instead, keeping the dominant leaf allocation at three writes.
1984
+ const i = _soaNodeCount + 1;
1985
+ if (i >= _soaCapacity) _soaGrow(i + 1);
1986
+ _soaTypes[i] = type;
1987
+ _soaStarts[i] = start;
1988
+ _soaEnds[i] = end;
1989
+ _soaNodeCount = i;
1990
+ return _nodeRef(i);
1991
+ };
1992
+ /** @type {(type: number, start: number, end: number) => Node} */
1993
+ const _soaAllocContainer = (type, start, end) => {
1994
+ const r = _soaAllocNode(type, start, end);
1995
+ const i = _nodeIndex(r);
1996
+ _soaFlags[i] = 0;
1997
+ // Clear list slots so a reused id never exposes a previous node's children
1998
+ // (content lists are flat spans, so zeroing the length suffices).
1999
+ _soaListLens[i] = 0;
2000
+ _soaDeclarationLists[i] = null;
2001
+ _soaChildRuleLists[i] = null;
2002
+ return r;
2003
+ };
2004
+ // Raw token value (the lazy `Token.value` form): hash / at-keyword drop their
2005
+ // one-char prefix, url uses its content range. Shared by the parser's
2006
+ // mid-parse reads and the SoA accessor.
2007
+ /**
2008
+ * @param {number} i node id
2009
+ * @returns {string} raw token value
2010
+ */
2011
+ const _soaValueOf = (i) => {
2012
+ const ty = _soaTypes[i];
2013
+ if (ty === T_HASH || ty === T_AT_KEYWORD) {
2014
+ return _soaInput.slice(_soaStarts[i] + 1, _soaEnds[i]);
2015
+ }
2016
+ if (ty === T_URL) return _soaInput.slice(_soaAux0[i], _soaAux1[i]);
2017
+ return _soaInput.slice(_soaStarts[i], _soaEnds[i]);
2018
+ };
2019
+ // Module-level constants for the same reason as the `_objSet*` set above.
2020
+ /** @type {typeof _makeUrl} */
2021
+ const _soaMakeUrl = (start, end, cs, ce) => {
2022
+ const r = _soaAllocNode(T_URL, start, end);
2023
+ _soaAux0[_nodeIndex(r)] = cs;
2024
+ _soaAux1[_nodeIndex(r)] = ce;
2025
+ return r;
2026
+ };
2027
+ /** @type {typeof _makeStylesheet} */
2028
+ const _soaMakeStylesheet = (start) =>
2029
+ _soaAllocContainer(T_STYLESHEET, start, start);
2030
+ // name / nameStart are derived from start + nameEnd; only nameEnd is stored.
2031
+ /** @type {typeof _setName} */
2032
+ const _soaSetName = (r, ns, ne) => {
2033
+ _soaAux0[_nodeIndex(r)] = ne;
2034
+ };
2035
+ /** @type {typeof _setEnd} */
2036
+ const _soaSetEnd = (r, v) => {
2037
+ _soaEnds[_nodeIndex(r)] = v;
2038
+ };
2039
+ /** @type {typeof _setBlock} */
2040
+ const _soaSetBlock = (r, bs, be) => {
2041
+ const i = _nodeIndex(r);
2042
+ _soaAux1[i] = bs;
2043
+ _soaAux2[i] = be;
2044
+ };
2045
+ /** @type {typeof _setImportant} */
2046
+ const _soaSetImportant = (r) => {
2047
+ _soaFlags[_nodeIndex(r)] |= 1;
2048
+ };
2049
+ // A simple block's token is derived from its opening char on read.
2050
+ /** @type {typeof _setToken} */
2051
+ const _soaSetToken = (r, ch) => {};
2052
+ /** @type {typeof _setValue} */
2053
+ const _soaSetValue = (r, list) => {
2054
+ // Seal the finished list: copy its refs into the flat buffer and hand the
2055
+ // scratch array back to the pool. The caller never touches `list` again.
2056
+ const i = _nodeIndex(r);
2057
+ const len = list.length;
2058
+ const start = _soaFlatTop;
2059
+ if (start + len > _soaFlat.length) _soaFlatGrow(start + len);
2060
+ for (let k = 0; k < len; k++) {
2061
+ _soaFlat[start + k] = _nodeIndex(list[k]);
2062
+ }
2063
+ _soaFlatTop = start + len;
2064
+ _soaListStarts[i] = start;
2065
+ _soaListLens[i] = len;
2066
+ list.length = 0;
2067
+ _listPool.push(list);
2068
+ };
2069
+ /** @type {typeof _setBody} */
2070
+ const _soaSetBody = (r, decls, childRules) => {
2071
+ const i = _nodeIndex(r);
2072
+ _soaDeclarationLists[i] = decls;
2073
+ _soaChildRuleLists[i] = childRules;
2074
+ };
2075
+ /** @type {typeof _nodeTypeOf} */
2076
+ const _soaNodeTypeOf = (r) => _soaTypes[_nodeIndex(r)];
2077
+ /** @type {typeof _nodeStartOf} */
2078
+ const _soaNodeStartOf = (r) => _soaStarts[_nodeIndex(r)];
2079
+ /** @type {typeof _nodeValueOf} */
2080
+ const _soaNodeValueOf = (r) => _soaValueOf(_nodeIndex(r));
2081
+ /** @type {typeof _nodeTokenOf} */
2082
+ const _soaNodeTokenOf = (r) =>
2083
+ /** @type {SimpleBlockToken} */ (_soaInput[_soaStarts[_nodeIndex(r)]]);
2084
+ /**
2085
+ * @param {string} input source
2086
+ * @param {LocConverter} lc loc converter
2087
+ */
2088
+ const useSoaBackend = (input, lc) => {
2089
+ _soaInput = input;
2090
+ _soaLocConverter = lc;
2091
+ _soaNodeCount = 0;
2092
+ _soaFlatTop = 0;
2093
+ _soaActive = true;
2094
+ // The alloc primitives are the slot functions directly — no wrapper hop.
2095
+ _makeLeaf = _soaAllocNode;
2096
+ _makeUrl = _soaMakeUrl;
2097
+ _makeContainer = _soaAllocContainer;
2098
+ _makeStylesheet = _soaMakeStylesheet;
2099
+ _setName = _soaSetName;
2100
+ _setEnd = _soaSetEnd;
2101
+ _setBlock = _soaSetBlock;
2102
+ _setImportant = _soaSetImportant;
2103
+ _setToken = _soaSetToken;
2104
+ _setValue = _soaSetValue;
2105
+ // value / prelude / rules all land in the one content-list slot.
2106
+ _setPrelude = _soaSetValue;
2107
+ _setBody = _soaSetBody;
2108
+ _setRules = _soaSetValue;
2109
+ _nodeTypeOf = _soaNodeTypeOf;
2110
+ _nodeStartOf = _soaNodeStartOf;
2111
+ _nodeValueOf = _soaNodeValueOf;
2112
+ _nodeTokenOf = _soaNodeTokenOf;
2113
+ };
2114
+
2115
+ /**
2116
+ * Materialize a single non-block, non-function lexer token as its leaf AST node — the spec's "consume a token" result (§5.4.8 "anything else"), preserving stray closers / CDO / CDC.
2117
+ * @param {MutableToken} t token from the lexer
2118
+ * @returns {Node} the leaf token node
2119
+ */
2120
+ const tokenToNode = (t) => {
2121
+ const tt = t.type;
2122
+ // URL is the only leaf with own state (its content range); all others are a
2123
+ // plain leaf whose node type comes from the map.
2124
+ if (tt === TT_URL) {
2125
+ const ut = /** @type {CssUrlToken} */ (t);
2126
+ return _makeUrl(t.start, t.end, ut.contentStart, ut.contentEnd);
2127
+ }
2128
+ return _makeLeaf(_ttToNodeType[tt], t.start, t.end);
2129
+ };
2130
+
2131
+ /**
2132
+ * Position-based view over the lexer — webpack's stand-in for the spec's
2133
+ * "normalize into a token stream" (CSS Syntax §9). It unifies the lexer and the
2134
+ * stream in one class: the `readToken` primitive lexes one token (the CSS
2135
+ * tokenizer), and the spec token-stream operations `next` / `consume` /
2136
+ * `discard` / `mark` / `restoreMark` / `discardMark` drive it from a byte
2137
+ * cursor. `parse*` entry points wrap a source string in one of these and every
2138
+ * `consume*` algorithm reads tokens from it.
2139
+ *
2140
+ * No token buffer is kept: the cursor is a byte offset and the only state is
2141
+ * the next token (lazily tokenized once and cached until consumed). The
2142
+ * declaration-vs-qualified-rule backtracking in `consumeABlocksContents`
2143
+ * rewinds by `mark`ing / `restoreMark`ing that byte offset, which simply
2144
+ * re-tokenizes the rewound span — comment tokens are filtered here and fire
2145
+ * `onComment` once each, tracked by a monotonic high-water mark so a
2146
+ * re-tokenized span never re-fires them.
2147
+ *
2148
+ * `SourceProcessor` is handed this class (not an instance) and threads it to
2149
+ * the grammar, so a different language can drive the same visitor machinery by
2150
+ * swapping the tokenizer — the per-token `readToken` primitive — for its own.
2151
+ */
2152
+ class TokenStream {
2153
+ /**
2154
+ * @param {string} input source
2155
+ * @param {number=} pos start byte offset (default `0`)
2156
+ * @param {LocConverter=} locConverter shared loc converter (default a fresh one over `input`)
2157
+ * @param {((input: string, start: number, end: number) => number)=} onComment comment-token callback
2158
+ */
2159
+ constructor(
2160
+ input,
2161
+ pos = 0,
2162
+ locConverter = new LocConverter(input),
2163
+ onComment = undefined
2164
+ ) {
2165
+ /** @type {string} */
2166
+ this.input = input;
2167
+ /** @type {LocConverter} */
2168
+ this.locConverter = locConverter;
2169
+ this._onComment = onComment;
2170
+ // Byte offset where the next token is tokenized from.
2171
+ /** @type {number} */
2172
+ this._pos = pos;
2173
+ // Comments before this offset have already fired `onComment`; a
2174
+ // re-tokenized (backtracked) span never re-fires them.
2175
+ /** @type {number} */
2176
+ this._commentHigh = pos;
2177
+ // Single reused token the lexer writes into on the `next` path — see
2178
+ // `MutableToken`. `_hasNext` marks it cached — a boolean instead of an
2179
+ // object slot, so caching a token never pays a GC write barrier.
2180
+ /** @type {MutableToken} */
2181
+ this._tok = createToken();
2182
+ /** @type {boolean} whether `_tok` holds the (lazily tokenized) next token */
2183
+ this._hasNext = false;
2184
+ /** @type {number[]} byte offsets to rewind to */
2185
+ this._marks = [];
2186
+ }
2187
+
2188
+ /**
2189
+ * The next token (CSS Syntax §3 "next token") — the upcoming token without
2190
+ * consuming it; the `<eof-token>` once the source is exhausted. This is the
2191
+ * token the consume algorithms dispatch on (the spec's "process"). Tokenized
2192
+ * from `_pos` on first use and cached until consumed; comment tokens are
2193
+ * skipped here, firing `onComment` once each.
2194
+ * @returns {MutableToken} the next token
2195
+ */
2196
+ next() {
2197
+ if (!this._hasNext) {
2198
+ const input = this.input;
2199
+ const tok = this._tok;
2200
+ let pos = this._pos;
2201
+ for (;;) {
2202
+ const t = readToken(input, pos, tok);
2203
+ if (t === undefined) {
2204
+ fill(tok, TT_EOF, input.length, input.length);
2205
+ break;
2206
+ }
2207
+ if (t.type === TT_COMMENT) {
2208
+ if (t.start >= this._commentHigh) {
2209
+ if (this._onComment) this._onComment(input, t.start, t.end);
2210
+ this._commentHigh = t.end;
2211
+ }
2212
+ pos = t.end;
2213
+ continue;
2214
+ }
2215
+ break;
2216
+ }
2217
+ this._hasNext = true;
2218
+ }
2219
+ return this._tok;
2220
+ }
2221
+
2222
+ /**
2223
+ * Consume a token (CSS Syntax §3 "consume a token") — return the next token
2224
+ * and advance the cursor past it. The returned token is valid until the next
2225
+ * `next` re-tokenizes (the reused instance is not cleared by advancing).
2226
+ * @returns {MutableToken} the consumed token
2227
+ */
2228
+ consume() {
2229
+ const t = this.next();
2230
+ if (t.type !== TT_EOF) {
2231
+ this._pos = t.end;
2232
+ this._hasNext = false;
2233
+ }
2234
+ return t;
2235
+ }
2236
+
2237
+ /**
2238
+ * Discard a token (CSS Syntax §3 "discard a token") — advance the cursor past
2239
+ * the next token without returning it.
2240
+ * @returns {void}
2241
+ */
2242
+ discard() {
2243
+ const t = this.next();
2244
+ if (t.type !== TT_EOF) {
2245
+ this._pos = t.end;
2246
+ this._hasNext = false;
2247
+ }
2248
+ }
2249
+
2250
+ /**
2251
+ * Mark (CSS Syntax §3 "mark") — push the current cursor position.
2252
+ * @returns {void}
2253
+ */
2254
+ mark() {
2255
+ this._marks.push(this._pos);
2256
+ }
2257
+
2258
+ /**
2259
+ * Restore a mark (CSS Syntax §3 "restore a mark") — pop the last mark and
2260
+ * rewind the cursor to it. The rewound span is re-tokenized on the next read;
2261
+ * already-fired comments are not re-fired (`_commentHigh`).
2262
+ * @returns {void}
2263
+ */
2264
+ restoreMark() {
2265
+ this._pos = /** @type {number} */ (this._marks.pop());
2266
+ this._hasNext = false;
2267
+ }
2268
+
2269
+ /**
2270
+ * Discard a mark (CSS Syntax §3 "discard a mark") — pop without rewinding.
2271
+ * @returns {void}
2272
+ */
2273
+ discardMark() {
2274
+ this._marks.pop();
2275
+ }
2276
+ }
2277
+
2278
+ /**
2279
+ * Normalize a `parse*` entry point's first argument into a `TokenStream`
2280
+ * (CSS Syntax §9 "normalize into a token stream"). An existing `TokenStream`
2281
+ * is returned as-is (consumed from its current position — it already carries
2282
+ * the shared `LocConverter` and comment hook), so `pos` / `onComment` are
2283
+ * ignored. A raw source string is tokenized from `pos` with a fresh
2284
+ * `LocConverter`; pass a `TokenStream` instead to share one converter across
2285
+ * sub-parses.
2286
+ * @param {string | TokenStream} input source string or an existing stream
2287
+ * @param {number=} pos start byte offset (string input only; default `0`)
2288
+ * @param {((input: string, start: number, end: number) => number)=} onComment comment callback (string input only)
2289
+ * @returns {TokenStream} the stream to consume from
2290
+ */
2291
+ const normalizeIntoTokenStream = (input, pos, onComment) =>
2292
+ input instanceof TokenStream
2293
+ ? input
2294
+ : new TokenStream(input, pos || 0, new LocConverter(input), onComment);
2295
+
2296
+ // === Parser entry points (CSS Syntax Level 3 §5.3) ===
2297
+ // Each `parseA*` is a thin public wrapper over a `consumeA*` algorithm
2298
+ // (§5.4): it takes raw source + a start position (webpack's stand-in for
2299
+ // the spec's "normalize into a token stream") and runs the matching
2300
+ // consume algorithm. The split mirrors tabatkins/parse-css — `parse*`
2301
+ // are the documented entry points, `consume*` are the internal
2302
+ // algorithms that drive the tokenizer.
2303
+
2304
+ /**
2305
+ * @typedef {object} ParseOptions
2306
+ * @property {((input: string, start: number, end: number) => number)=} comment optional comment-token callback; the public `parse*` entry points use it to build the `TokenStream` so the outer parser's comment tracker still sees magic comments inside the consumed range
2307
+ */
2308
+
2309
+ /**
2310
+ * Parse a stylesheet, CSS Syntax Level 3
2311
+ * [§5.3.4](https://drafts.csswg.org/css-syntax/#parse-stylesheet).
2312
+ * @param {string | TokenStream} input source string or an existing token stream
2313
+ * @param {number=} pos start position (string input only)
2314
+ * @param {ParseOptions=} options optional comment-token callback (string input only)
2315
+ * @returns {Stylesheet} the parsed stylesheet
2316
+ */
2317
+ const parseAStylesheet = (input, pos = 0, options = {}) => {
2318
+ // 1. If input is a byte stream for a stylesheet, decode bytes from input, and set input to the result.
2319
+ // 2. Normalize input, and set input to the result.
2320
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2321
+ useObjectBackend(ts.locConverter);
2322
+ // 3. Create a new stylesheet, with its location set to location (or null, if location was not passed).
2323
+ const start = ts.next().start;
2324
+ const stylesheet = /** @type {Stylesheet} */ (_makeStylesheet(start));
2325
+ // 4. Consume a stylesheet's contents from input, and set the stylesheet's rules to the result.
2326
+ _setRules(stylesheet, consumeAStylesheetsContents(ts));
2327
+ _setEnd(stylesheet, ts.next().start);
2328
+ // 5. Return the stylesheet.
2329
+ return stylesheet;
2330
+ };
2331
+
2332
+ /**
2333
+ * Parse a stylesheet's contents, CSS Syntax Level 3
2334
+ * [§5.3.5](https://drafts.csswg.org/css-syntax/#parse-stylesheets-contents) —
2335
+ * the top-level rule list via `consumeAStylesheetsContents` (§5.4.1): top-level
2336
+ * declarations are parse errors (never produced) and top-level CDO (`<!--`) /
2337
+ * CDC (`-->`) tokens are discarded.
2338
+ * @param {string | TokenStream} input source string or an existing token stream
2339
+ * @param {number=} pos start position (string input only)
2340
+ * @param {ParseOptions=} options optional comment-token callback (string input only)
2341
+ * @returns {Rule[]} top-level rules
2342
+ */
2343
+ const parseAStylesheetsContents = (input, pos = 0, options = {}) => {
2344
+ // 1. Normalize input, and set input to the result.
2345
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2346
+ useObjectBackend(ts.locConverter);
2347
+ // 2. Consume a stylesheet’s contents from input, and return the result.
2348
+ return consumeAStylesheetsContents(ts);
2349
+ };
2350
+
2351
+ /**
2352
+ * Parse a block's contents, CSS Syntax Level 3
2353
+ * [§5.3.6](https://drafts.csswg.org/css-syntax/#parse-block-contents).
2354
+ * @param {string | TokenStream} input source string or an existing token stream
2355
+ * @param {number=} pos start position (string input only; just past the opening `{`, or 0)
2356
+ * @param {ParseOptions=} options optional comment-token callback (string input only)
2357
+ * @returns {{ decls: Declaration[], rules: Rule[] }} block decls + rules
2358
+ */
2359
+ const parseABlocksContents = (input, pos = 0, options = {}) => {
2360
+ // 1. Normalize input, and set input to the result.
2361
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2362
+ useObjectBackend(ts.locConverter);
2363
+ // 2. Consume a block’s contents from input, and return the result.
2364
+ return consumeABlocksContents(ts);
2365
+ };
2366
+
2367
+ /**
2368
+ * Parse a rule, CSS Syntax Level 3
2369
+ * [§5.3.7](https://drafts.csswg.org/css-syntax/#parse-rule) — discards leading
2370
+ * whitespace, consumes one at-rule / qualified rule, and requires only trailing
2371
+ * whitespace; `undefined` (syntax error) otherwise.
2372
+ * @param {string | TokenStream} input source string or an existing token stream
2373
+ * @param {number=} pos start position (string input only)
2374
+ * @param {ParseOptions=} options optional comment-token callback (string input only)
2375
+ * @returns {Rule | undefined} the parsed rule
2376
+ */
2377
+ const parseARule = (input, pos = 0, options = {}) => {
2378
+ // 1. Normalize input, and set input to the result.
2379
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2380
+ useObjectBackend(ts.locConverter);
2381
+ // 2. Discard whitespace from input.
2382
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2383
+ // 3. If the next token from input is an <EOF-token>, return a syntax error.
2384
+ // Otherwise, if the next token from input is an <at-keyword-token>, consume an at-rule from input, and let rule be the return value.
2385
+ // Otherwise, consume a qualified rule from input and let rule be the return value.
2386
+ // If nothing or an invalid rule error was returned, return a syntax error.
2387
+ const head = ts.next();
2388
+ if (head.type === TT_EOF) return undefined;
2389
+ const rule =
2390
+ head.type === TT_AT_KEYWORD
2391
+ ? consumeAnAtRule(ts)
2392
+ : consumeAQualifiedRule(ts);
2393
+ if (!rule) return undefined;
2394
+ // 4. Discard whitespace from input.
2395
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2396
+ // 5. If the next token from input is an <EOF-token>, return rule. Otherwise, return a syntax error.
2397
+ return ts.next().type === TT_EOF ? rule : undefined;
2398
+ };
2399
+
2400
+ /**
2401
+ * Parse a declaration, CSS Syntax Level 3
2402
+ * [§5.3.8](https://drafts.csswg.org/css-syntax/#parse-declaration).
2403
+ * @param {string | TokenStream} input source string or an existing token stream
2404
+ * @param {number=} pos start position (string input only)
2405
+ * @param {ParseOptions=} options optional comment-token callback (string input only)
2406
+ * @returns {Declaration | undefined} the parsed declaration, or undefined
2407
+ */
2408
+ const parseADeclaration = (input, pos = 0, options = {}) => {
2409
+ // 1. Normalize input, and set input to the result.
2410
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2411
+ useObjectBackend(ts.locConverter);
2412
+ // 2. Discard whitespace from input.
2413
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2414
+ // 3. Consume a declaration from input. If anything was returned, return it. Otherwise, return a syntax error.
2415
+ return consumeADeclaration(ts);
2416
+ };
2417
+
2418
+ /**
2419
+ * Parse a component value, CSS Syntax Level 3 [§5.3.9](https://drafts.csswg.org/css-syntax/#parse-component-value) — strict entry point that consumes one value and returns `undefined` if non-whitespace input trails (use `consumeAComponentValue` for "one value, ignore the rest").
2420
+ * @param {string | TokenStream} input source string or an existing token stream
2421
+ * @param {number=} pos start position (string input only)
2422
+ * @param {ParseOptions=} options optional comment-token callback (string input only)
2423
+ * @returns {ComponentValue | undefined} the parsed component value, or `undefined` on empty / trailing-garbage input
2424
+ */
2425
+ const parseAComponentValue = (input, pos = 0, options = {}) => {
2426
+ // 1. Normalize input, and set input to the result.
2427
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2428
+ useObjectBackend(ts.locConverter);
2429
+ // 2. Discard whitespace from input.
2430
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2431
+ // 3. If input is empty, return a syntax error.
2432
+ if (ts.next().type === TT_EOF) return undefined;
2433
+ // 4. Consume a component value from input and let value be the return value.
2434
+ const result = consumeAComponentValue(ts);
2435
+ // 5. Discard whitespace from input.
2436
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2437
+ // 6. If input is empty, return value. Otherwise, return a syntax error.
2438
+ if (ts.next().type === TT_EOF) return result;
2439
+ return undefined;
2440
+ };
2441
+
2442
+ /**
2443
+ * Parse a list of component values, CSS Syntax Level 3
2444
+ * [§5.3.10](https://drafts.csswg.org/css-syntax/#parse-list-of-components).
2445
+ * @param {string | TokenStream} input source string or an existing token stream
2446
+ * @param {number=} pos start position (string input only)
2447
+ * @param {ParseOptions=} options comment callback
2448
+ * @returns {ComponentValue[]} component values
2449
+ */
2450
+ const parseAListOfComponentValues = (input, pos = 0, options = {}) => {
2451
+ // 1. Normalize input, and set input to the result.
2452
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2453
+ useObjectBackend(ts.locConverter);
2454
+ // 2. Consume a list of component values from input, and return the result.
2455
+ // (`null` needs `bailOnCurly`, which is not passed here.)
2456
+ return /** @type {ComponentValue[]} */ (consumeAListOfComponentValues(ts));
2457
+ };
2458
+
2459
+ /**
2460
+ * Parse a comma-separated list of component values, CSS Syntax Level 3 [§5.3.11](https://drafts.csswg.org/css-syntax/#parse-comma-list) — consumes one `<comma-token>`-stopped group of component values per iteration until EOF.
2461
+ * @param {string | TokenStream} input source string or an existing token stream
2462
+ * @param {number=} pos start position (string input only)
2463
+ * @param {ParseOptions=} options comment callback
2464
+ * @returns {ComponentValue[][]} comma-separated groups of component values
2465
+ */
2466
+ const parseACommaSeparatedListOfComponentValues = (
2467
+ input,
2468
+ pos = 0,
2469
+ options = {}
2470
+ ) => {
2471
+ // 1. Normalize input, and set input to the result.
2472
+ const ts = normalizeIntoTokenStream(input, pos, options.comment);
2473
+ useObjectBackend(ts.locConverter);
2474
+ // 2. Let groups be an empty list.
2475
+ /** @type {ComponentValue[][]} */
2476
+ const groups = [];
2477
+ // 3. While input is not empty:
2478
+ while (ts.next().type !== TT_EOF) {
2479
+ // 3.1. Consume a list of component values from input, with <comma-token> as the stop token, and append the result to groups.
2480
+ groups.push(
2481
+ /** @type {ComponentValue[]} */ (
2482
+ consumeAListOfComponentValues(ts, TT_COMMA)
2483
+ )
2484
+ );
2485
+ // 3.2 Discard a token from input.
2486
+ ts.discard();
2487
+ }
2488
+ // 4. Return groups.
2489
+ return groups;
2490
+ };
2491
+
2492
+ // === Parser algorithms (CSS Syntax Level 3 §5.4) ===
2493
+ // The mutually-recursive consume algorithms the `parse*` entry points drive:
2494
+ // each reads tokens from a `TokenStream` and reuses `consumeAComponentValue`
2495
+ // for nested values, mirroring tabatkins/parse-css.
2496
+
2497
+ /**
2498
+ * Consume a stylesheet's contents, CSS Syntax Level 3 [§5.4.1](https://drafts.csswg.org/css-syntax/#consume-stylesheet-contents) — the top-level rule list: whitespace and CDO (`<!--`) / CDC (`-->`) tokens are discarded, an at-keyword starts an at-rule, and anything else starts a qualified rule (so top-level declarations are parse errors and never produced).
2499
+ *
2500
+ * `onRule` is a webpack extension to the algorithm's output: when given, each
2501
+ * consumed rule is handed to it immediately and not collected, so the walker can
2502
+ * process one top-level rule at a time without materializing the whole
2503
+ * stylesheet (the returned list is then empty). When omitted the rules are
2504
+ * collected and returned as the spec specifies.
2505
+ * @param {TokenStream} ts token stream
2506
+ * @param {((rule: Rule) => void)=} onRule optional per-rule sink (streaming); rules are not collected when given
2507
+ * @returns {Rule[]} top-level rules (empty when `onRule` is given)
2508
+ */
2509
+ const consumeAStylesheetsContents = (ts, onRule) => {
2510
+ // Let rules be an initially empty list of rules.
2511
+ /** @type {Rule[]} */
2512
+ const rules = [];
2513
+
2514
+ // Process input
2515
+ for (;;) {
2516
+ const t = ts.next();
2517
+ // <whitespace-token> / <CDO-token> / <CDC-token>
2518
+ // Discard a token from input.
2519
+ if (t.type === TT_WHITESPACE || t.type === TT_CDO || t.type === TT_CDC) {
2520
+ ts.discard();
2521
+ }
2522
+ // <EOF-token>
2523
+ // Return rules.
2524
+ else if (t.type === TT_EOF) {
2525
+ return rules;
2526
+ }
2527
+ // <at-keyword-token>
2528
+ // Consume an at-rule from input. If anything is returned, append it to rules.
2529
+ else if (t.type === TT_AT_KEYWORD) {
2530
+ const at = consumeAnAtRule(ts);
2531
+ if (at) {
2532
+ if (onRule) onRule(at);
2533
+ else rules.push(at);
2534
+ }
2535
+ }
2536
+ // anything else
2537
+ // Consume a qualified rule from input. If a rule is returned, append it to rules.
2538
+ else {
2539
+ const rule = consumeAQualifiedRule(ts);
2540
+ if (rule) {
2541
+ if (onRule) onRule(rule);
2542
+ else rules.push(rule);
2543
+ }
2544
+ }
2545
+ }
2546
+ };
2547
+
2548
+ /**
2549
+ * Consume an at-rule, CSS Syntax Level 3 [§5.4.2](https://drafts.csswg.org/css-syntax/#consume-at-rule) — the next token must be an <at-keyword-token> (asserted); consumes the prelude up to `;` / `{` / `}` / EOF; `{` consumes the block (§5.4.4) onto `.block`, `;` / EOF is discarded, a top-level `}` (when not `nested`) is appended via `consumeAComponentValue`.
2550
+ * @param {TokenStream} ts token stream
2551
+ * @param {boolean=} nested true inside a `{}` block — a top-level `}` ends the at-rule (left for the caller)
2552
+ * @returns {AtRule | undefined} the parsed at-rule
2553
+ */
2554
+ const consumeAnAtRule = (ts, nested = false) => {
2555
+ // Assert (spec): the next token is an <at-keyword-token>.
2556
+ // Consume a token from input, and let rule be a new at-rule with its name set to the returned token’s value, its prelude initially set to an empty list, and no declarations or child rules.
2557
+ const head = ts.consume();
2558
+ const rule = /** @type {AtRule} */ (
2559
+ _makeContainer(T_AT_RULE, head.start, head.end)
2560
+ );
2561
+ _setName(rule, head.start, head.end);
2562
+ // Sealed (`_setPrelude`) at each return — the SoA backend consumes the
2563
+ // scratch array when sealing, so it must be complete by then.
2564
+ const prelude = _soaActive ? _soaList() : [];
2565
+ // declarations / childRules / blockStart (-1) / blockEnd (-1) keep their
2566
+ // defaults (no block: the `;` / EOF / nested-`}` at-rule forms).
2567
+
2568
+ // Like `consumeAQualifiedRule`: skip mode scans the prelude without
2569
+ // materializing it (url tokens / functions kept so `@import url(…)` still
2570
+ // resolves); the block boundary is found by scanning, not the prelude nodes.
2571
+ const skip = _skipAtRulePrelude;
2572
+
2573
+ // Process input
2574
+ for (;;) {
2575
+ const t = ts.next();
2576
+
2577
+ // <semicolon-token>
2578
+ // <EOF-token>
2579
+ // Discard a token from input. If rule is valid in the current context, return it; otherwise return nothing.
2580
+ if (t.type === TT_SEMICOLON || t.type === TT_EOF) {
2581
+ ts.discard();
2582
+ _setPrelude(rule, prelude);
2583
+ _setEnd(rule, t.start);
2584
+ return rule;
2585
+ }
2586
+ // <}-token>
2587
+ // If nested is true: if rule is valid in the current context, return it; otherwise return nothing.
2588
+ // Otherwise, consume a token and append the result to rule’s prelude.
2589
+ else if (t.type === TT_RIGHT_CURLY_BRACKET) {
2590
+ if (nested) {
2591
+ _setPrelude(rule, prelude);
2592
+ _setEnd(rule, t.start);
2593
+ return rule;
2594
+ }
2595
+ const node = consumeATokenAsNode(ts);
2596
+ if (!skip) prelude.push(node);
2597
+ continue;
2598
+ }
2599
+ // <{-token>
2600
+ // Consume a block from input, and assign the result to rule's declarations and child rules.
2601
+ else if (t.type === TT_LEFT_CURLY_BRACKET) {
2602
+ _setPrelude(rule, prelude);
2603
+ const block = consumeABlock(ts);
2604
+ _setBody(rule, block.decls, block.rules);
2605
+ _setBlock(rule, block.blockStart, block.blockEnd);
2606
+ _setEnd(rule, block.blockEnd);
2607
+ return rule;
2608
+ }
2609
+
2610
+ // anything else
2611
+ // Consume a component value from input and append the returned value to rule’s prelude.
2612
+ const node = consumeAComponentValue(ts, t);
2613
+ if (!skip) {
2614
+ prelude.push(node);
2615
+ } else if (
2616
+ _nodeTypeOf(node) === T_FUNCTION ||
2617
+ _nodeTypeOf(node) === T_URL
2618
+ ) {
2619
+ prelude.push(node);
2620
+ }
2621
+ }
2622
+ };
2623
+
2624
+ /**
2625
+ * Consume a token (CSS Syntax §3 "consume a token"): advance past the next
2626
+ * token and return it as a leaf AST node. Used directly where the spec says
2627
+ * "consume a token from input" (e.g. the parse-error branches in §5.4.7 /
2628
+ * §5.4.2 / §5.4.3), distinct from `consumeAComponentValue` which would recurse
2629
+ * into a simple block / function.
2630
+ * @param {TokenStream} ts token stream
2631
+ * @returns {Token} the consumed token as a leaf node
2632
+ */
2633
+ const consumeATokenAsNode = (ts) => {
2634
+ const t = ts.consume();
2635
+ return /** @type {Token} */ (tokenToNode(t));
2636
+ };
2637
+
2638
+ /**
2639
+ * Consume a qualified rule, CSS Syntax Level 3 [§5.4.3](https://drafts.csswg.org/css-syntax/#consume-qualified-rule) — consumes the prelude (each component value via `consumeAComponentValue`) up to its `{` block; EOF, the optional `stopToken`, or a nested top-level `}` is a parse error returning nothing (the block-less prelude is dropped), while a non-nested top-level `}` is consumed as a parse error and the prelude continues. A returned rule always has a block.
2640
+ * @param {TokenStream} ts token stream
2641
+ * @param {number=} stopToken token type that ends the prelude (parse error → nothing)
2642
+ * @param {boolean=} nested true inside a `{}` block — a top-level `}` ends the rule (left for the caller)
2643
+ * @returns {QualifiedRule | undefined} parsed qualified rule, or `undefined` on a parse error
2644
+ */
2645
+ const consumeAQualifiedRule = (ts, stopToken, nested = false) => {
2646
+ const start = ts.next().start;
2647
+ // Let rule be a new qualified rule with its prelude, declarations, and child rules all initially set to empty lists.
2648
+ const rule = /** @type {QualifiedRule} */ (
2649
+ _makeContainer(T_QUALIFIED_RULE, start, start)
2650
+ );
2651
+ // Sealed (`_setPrelude`) at the `{` exit — the only path that returns the
2652
+ // rule; the parse-error exits abandon the scratch unsealed.
2653
+ const prelude = _soaActive ? _soaList() : [];
2654
+ // declarations / childRules / blockStart (-1) / blockEnd (-1) keep their
2655
+ // defaults (no block until a `{` is reached).
2656
+
2657
+ // Skip mode leaves `prelude` empty (selector text is recovered from the
2658
+ // rule's byte range, not its nodes); `first`/`second` still track the first
2659
+ // two non-whitespace tokens the `--foo: {` disambiguation below needs.
2660
+ const skip = _skipSelectorPrelude;
2661
+ let first = /** @type {Node} */ (/** @type {unknown} */ (0));
2662
+ let second = /** @type {Node} */ (/** @type {unknown} */ (0));
2663
+
2664
+ // Process input
2665
+ for (;;) {
2666
+ const t = ts.next();
2667
+ // <EOF-token>
2668
+ // stop token (if passed)
2669
+ // This is a parse error. Return nothing.
2670
+ if (t.type === TT_EOF || t.type === stopToken) {
2671
+ return undefined;
2672
+ }
2673
+ // <}-token>
2674
+ // This is a parse error. If nested is true, return nothing. Otherwise, consume a token and append the result to rule’s prelude.
2675
+ else if (t.type === TT_RIGHT_CURLY_BRACKET) {
2676
+ if (nested) return undefined;
2677
+ const node = consumeATokenAsNode(ts);
2678
+ if (skip) {
2679
+ if (!first) first = node;
2680
+ else if (!second) second = node;
2681
+ } else {
2682
+ prelude.push(node);
2683
+ }
2684
+ continue;
2685
+ }
2686
+ // <{-token>
2687
+ // If the first two non-<whitespace-token> values of rule's prelude are an <ident-token> whose value starts with "--" followed by a <colon-token>, then:
2688
+ // - If nested is true, consume the remnants of a bad declaration from input, with nested set to true, and return nothing.
2689
+ // - If nested is false, consume a block from input, and return nothing.
2690
+ // (This disambiguates custom-property declarations from nested qualified rules — `--foo: { … }` at top level of a block is a declaration, not a rule.)
2691
+ // Otherwise, consume a block from input, and let child rules be the result.
2692
+ else if (t.type === TT_LEFT_CURLY_BRACKET) {
2693
+ if (!skip) {
2694
+ let firstIdx = 0;
2695
+ /* istanbul ignore next -- @preserve: leading whitespace is discarded before the rule, so the prelude never starts with it */
2696
+ while (
2697
+ firstIdx < prelude.length &&
2698
+ _nodeTypeOf(prelude[firstIdx]) === T_WHITESPACE
2699
+ ) {
2700
+ firstIdx++;
2701
+ }
2702
+ let secondIdx = firstIdx + 1;
2703
+ while (
2704
+ secondIdx < prelude.length &&
2705
+ _nodeTypeOf(prelude[secondIdx]) === T_WHITESPACE
2706
+ ) {
2707
+ secondIdx++;
2708
+ }
2709
+ first = prelude[firstIdx];
2710
+ second = prelude[secondIdx];
2711
+ }
2712
+ if (
2713
+ first &&
2714
+ _nodeTypeOf(first) === T_IDENT &&
2715
+ // Test the source bytes directly — avoids forcing the lazy `value`
2716
+ // slice just to check the `--` custom-property prefix.
2717
+ ts.input.startsWith("--", _nodeStartOf(first)) &&
2718
+ second &&
2719
+ _nodeTypeOf(second) === T_COLON
2720
+ ) {
2721
+ /* istanbul ignore if -- @preserve: when nested, `declarationStartLikely` routes every `--x:` to consumeADeclaration (which accepts custom properties), so this fallthrough is unreachable */
2722
+ if (nested) {
2723
+ consumeTheRemnantsOfABadDeclaration(ts, true);
2724
+ } else {
2725
+ consumeABlock(ts);
2726
+ }
2727
+ return undefined;
2728
+ }
2729
+ _setPrelude(rule, prelude);
2730
+ const block = consumeABlock(ts);
2731
+ _setBody(rule, block.decls, block.rules);
2732
+ _setBlock(rule, block.blockStart, block.blockEnd);
2733
+ _setEnd(rule, block.blockEnd);
2734
+ return rule;
2735
+ }
2736
+
2737
+ // anything else
2738
+ // Consume a component value from input and append the result to rule’s prelude.
2739
+ const node = consumeAComponentValue(ts, t);
2740
+ if (skip) {
2741
+ // Keep only url-bearing nodes (url tokens, or functions that may hold a
2742
+ // url like `:unknown(url(x))`) so the url visitor still rewrites them;
2743
+ // other selector tokens have no non-modules consumer, so drop them.
2744
+ const ty = _nodeTypeOf(node);
2745
+ if (ty === T_FUNCTION || ty === T_URL) prelude.push(node);
2746
+ // Track the first two non-whitespace tokens for the disambiguation above.
2747
+ if (t.type !== TT_WHITESPACE) {
2748
+ if (!first) first = node;
2749
+ else if (!second) second = node;
2750
+ }
2751
+ } else {
2752
+ prelude.push(node);
2753
+ }
2754
+ }
2755
+ };
2756
+
2757
+ /**
2758
+ * Consume a block, CSS Syntax Level 3 [§5.4.4](https://drafts.csswg.org/css-syntax/#consume-block) — the next token must be `<{-token>`; discards it, consumes the block's contents (§5.4.5), discards the closing `}`, and returns its `decls` / `rules` pair. We also return the `[start of {, end of }]` offsets so callers can record the block's source position.
2759
+ * @param {TokenStream} ts token stream
2760
+ * @returns {{ decls: Declaration[], rules: Rule[], blockStart: number, blockEnd: number }} block decls + rules and the `{` start / `}` end offsets
2761
+ */
2762
+ const consumeABlock = (ts) => {
2763
+ // Capture the opening `{`'s start before advancing — the stream reuses one
2764
+ // token instance, so `consumeABlocksContents` below would overwrite it.
2765
+ const blockStart = ts.next().start;
2766
+ // Assert (spec): the next token is <{-token>.
2767
+ // Discard a token from input. Consume a block's contents from input and let result be the result. Discard a token from input.
2768
+ ts.discard();
2769
+ const { decls, rules } = consumeABlocksContents(ts);
2770
+ const close = ts.next();
2771
+ const end = close.type === TT_RIGHT_CURLY_BRACKET ? close.end : close.start;
2772
+ ts.discard();
2773
+ return { decls, rules, blockStart, blockEnd: end };
2774
+ };
2775
+
2776
+ /**
2777
+ * 2-token lookahead: is the next non-whitespace pair `<ident> <colon>`?
2778
+ * Peeks raw code points without advancing; comments still fire `onComment` later.
2779
+ * @param {TokenStream} ts token stream
2780
+ * @returns {boolean} true if consume-a-declaration's step 1 + step 3 would both succeed on the current input
2781
+ */
2782
+ const declarationStartLikely = (ts) => {
2783
+ const t = ts.next();
2784
+ if (t.type !== TT_IDENTIFIER) return false;
2785
+ const input = ts.input;
2786
+ const len = input.length;
2787
+ let pos = t.end;
2788
+ for (;;) {
2789
+ if (pos >= len) return false;
2790
+ const cc = input.charCodeAt(pos);
2791
+ if (_isWhiteSpace(cc)) {
2792
+ pos++;
2793
+ continue;
2794
+ }
2795
+ // Skip a `/* … */` comment (the tokenizer filters comments between tokens).
2796
+ if (cc === CC_SOLIDUS && input.charCodeAt(pos + 1) === CC_ASTERISK) {
2797
+ pos += 2;
2798
+ while (
2799
+ pos < len &&
2800
+ !(
2801
+ input.charCodeAt(pos) === CC_ASTERISK &&
2802
+ input.charCodeAt(pos + 1) === CC_SOLIDUS
2803
+ )
2804
+ ) {
2805
+ pos++;
2806
+ }
2807
+ pos += 2;
2808
+ continue;
2809
+ }
2810
+ // `:` is always a standalone <colon-token>, so the next significant char
2811
+ // being `:` is equivalent to the next token being a <colon-token>.
2812
+ return cc === CC_COLON;
2813
+ }
2814
+ };
2815
+
2816
+ /**
2817
+ * Consume a block's contents, CSS Syntax Level 3 [§5.4.5](https://drafts.csswg.org/css-syntax/#consume-block-contents). Per tabatkins/parse-css.js reference impl: returns separate `decls` and `rules` flat lists, both preserved on EOF / `}` (the spec text's "Return rules" single-list model drops trailing decls because there's no implicit flush before EOF / `}`).
2818
+ *
2819
+ * `onNode` is the same streaming extension `consumeAStylesheetsContents` exposes:
2820
+ * when given, each consumed declaration / rule is handed to it immediately (in
2821
+ * source order) instead of being collected, so the returned lists are empty.
2822
+ * @param {TokenStream} ts token stream
2823
+ * @param {((node: Declaration | Rule) => void)=} onNode optional per-node sink (streaming); nodes are not collected when given
2824
+ * @returns {{ decls: Declaration[], rules: Rule[] }} consumed decls + rules (both empty when `onNode` is given; stops at the enclosing `}` / EOF, left in the stream)
2825
+ */
2826
+ const consumeABlocksContents = (ts, onNode) => {
2827
+ /** @type {Declaration[]} */
2828
+ const decls = [];
2829
+ // Child rules are the common empty case (most rules carry only declarations),
2830
+ // so `rules` is allocated lazily and returned as the shared frozen
2831
+ // `_EMPTY_LIST` when nothing was appended — one fewer array per rule. `decls`
2832
+ // stays eager so the hot declaration append keeps a branch-free `push`.
2833
+ /** @type {Rule[] | null} */
2834
+ let rules = null;
2835
+
2836
+ // Process input:
2837
+ for (;;) {
2838
+ const t = ts.next();
2839
+
2840
+ // <whitespace-token> / <semicolon-token>
2841
+ // Discard a token from input.
2842
+ if (t.type === TT_WHITESPACE || t.type === TT_SEMICOLON) {
2843
+ ts.discard();
2844
+ }
2845
+ // <EOF-token> / <}-token>
2846
+ // Return decls and rules.
2847
+ else if (t.type === TT_EOF || t.type === TT_RIGHT_CURLY_BRACKET) {
2848
+ return { decls, rules: rules || _EMPTY_LIST };
2849
+ }
2850
+ // <at-keyword-token>
2851
+ // Consume an at-rule from input, with nested set to true. If a rule was returned, append it to rules.
2852
+ else if (t.type === TT_AT_KEYWORD) {
2853
+ const atRule = consumeAnAtRule(ts, true);
2854
+ if (atRule) {
2855
+ if (onNode) onNode(atRule);
2856
+ else (rules || (rules = [])).push(atRule);
2857
+ }
2858
+ }
2859
+ // anything else
2860
+ // Mark input. Consume a declaration from input, with nested set to true.
2861
+ // If a declaration was returned, append it to decls, and discard a mark from input.
2862
+ // Otherwise, restore a mark from input, then consume a qualified rule from input, with nested set to true, and <semicolon-token> as the stop token. If a rule was returned, append it to rules.
2863
+ else {
2864
+ // 2-token peek: consume-a-declaration's steps 1 / 3 require `<ident> <colon>`; if absent it would call consume-the-remnants-of-a-bad-declaration (potentially the rest of the enclosing block) only for the restoreMark to undo it (O(N²) on flat blocks of qualified rules). Skip straight to consume-a-qualified-rule — same observable result.
2865
+ if (declarationStartLikely(ts)) {
2866
+ ts.mark();
2867
+ const decl = consumeADeclaration(ts, true);
2868
+ if (decl) {
2869
+ if (onNode) onNode(decl);
2870
+ else decls.push(decl);
2871
+ ts.discardMark();
2872
+ continue;
2873
+ }
2874
+ ts.restoreMark();
2875
+ }
2876
+ const rule = consumeAQualifiedRule(ts, TT_SEMICOLON, true);
2877
+ if (rule) {
2878
+ if (onNode) onNode(rule);
2879
+ else (rules || (rules = [])).push(rule);
2880
+ }
2881
+ }
2882
+ }
2883
+ };
2884
+
2885
+ /**
2886
+ * Consume the remnants of a bad declaration, CSS Syntax Level 3 [§5.4.11](https://drafts.csswg.org/css-syntax/#consume-the-remnants-of-a-bad-declaration). Advances the stream past a malformed declaration's tail so the caller (`consumeABlocksContents`) can resume cleanly.
2887
+ * @param {TokenStream} ts token stream
2888
+ * @param {boolean} nested whether the call originates from inside a `{}` block
2889
+ * @returns {void}
2890
+ */
2891
+ const consumeTheRemnantsOfABadDeclaration = (ts, nested) => {
2892
+ // Process input:
2893
+ for (;;) {
2894
+ const t = ts.next();
2895
+ // <eof-token> / <semicolon-token>
2896
+ // Discard a token from input, and return.
2897
+ if (t.type === TT_EOF || t.type === TT_SEMICOLON) {
2898
+ ts.discard();
2899
+ return;
2900
+ }
2901
+ // <}-token>
2902
+ // If nested is true, return. Otherwise, discard a token.
2903
+ if (t.type === TT_RIGHT_CURLY_BRACKET) {
2904
+ if (nested) return;
2905
+ ts.discard();
2906
+ continue;
2907
+ }
2908
+ // anything else
2909
+ // Consume a component value from input, and do nothing.
2910
+ consumeAComponentValue(ts);
2911
+ }
2912
+ };
2913
+
2914
+ /**
2915
+ * Consume a declaration, CSS Syntax Level 3 [§5.4.6](https://drafts.csswg.org/css-syntax/#consume-declaration).
2916
+ * @param {TokenStream} ts token stream
2917
+ * @param {boolean=} nested true inside a `{}` block — a top-level `}` ends the value
2918
+ * @returns {Declaration | undefined} parsed declaration, or `undefined` on the spec's "return nothing" branches (steps 1, 3, 8)
2919
+ */
2920
+ const consumeADeclaration = (ts, nested = false) => {
2921
+ const { input } = ts;
2922
+ // Let decl be a new declaration, with an initially empty name and a value set to an empty list.
2923
+ const start = ts.next().start;
2924
+ // name "" / nameStart / nameEnd (= start) / important (false) keep their
2925
+ // `Container` defaults; `value` is set unconditionally at step 5 below.
2926
+ const decl = /** @type {Declaration} */ (
2927
+ _makeContainer(T_DECLARATION, start, start)
2928
+ );
2929
+
2930
+ // 1. If the next token is an <ident-token>, consume a token from input and set decl's name to the returned token's value.
2931
+ // Otherwise, consume the remnants of a bad declaration from input, with nested, and return nothing.
2932
+ if (ts.next().type === TT_IDENTIFIER) {
2933
+ const head = ts.consume();
2934
+ _setName(decl, head.start, head.end);
2935
+ } else {
2936
+ consumeTheRemnantsOfABadDeclaration(ts, nested);
2937
+ return undefined;
2938
+ }
2939
+
2940
+ // 2. Discard whitespace from input.
2941
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2942
+
2943
+ // 3. If the next token is a <colon-token>, discard a token from input.
2944
+ // Otherwise, consume the remnants of a bad declaration from input, with nested, and return nothing.
2945
+ if (ts.next().type === TT_COLON) {
2946
+ ts.discard();
2947
+ } else {
2948
+ consumeTheRemnantsOfABadDeclaration(ts, nested);
2949
+ return undefined;
2950
+ }
2951
+
2952
+ // 4. Discard whitespace from input.
2953
+ while (ts.next().type === TT_WHITESPACE) ts.discard();
2954
+
2955
+ // Step 8's custom-property test, computed early so the value parse can bail.
2956
+ const isCustomProperty = input.startsWith("--", start);
2957
+
2958
+ // 5. Consume a list of component values from input, with nested, and with <semicolon-token> as the stop token, and set decl's value to the result.
2959
+ // A nested non-custom declaration bails on a top-level `{` — step 8 would
2960
+ // reject it and the caller restores its mark, so parsing the block (the
2961
+ // entire nested-rule body, re-parsed as a qualified rule after the
2962
+ // restore) would be pure waste.
2963
+ const value = consumeAListOfComponentValues(
2964
+ ts,
2965
+ TT_SEMICOLON,
2966
+ nested,
2967
+ nested && !isCustomProperty
2968
+ );
2969
+ if (value === null) return undefined;
2970
+ // `_setValue` waits until step 9: steps 6-8 still trim / scan the scratch,
2971
+ // and the SoA backend consumes it when sealing.
2972
+ _setEnd(decl, ts.next().start);
2973
+
2974
+ // 6. If the last two non-<whitespace-token>s in decl's value are a <delim-token> with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive match for "important", remove them from decl's value and set decl's important flag.
2975
+ {
2976
+ let last = value.length - 1;
2977
+ while (last >= 0 && _nodeTypeOf(value[last]) === T_WHITESPACE) last--;
2978
+ let prev = last - 1;
2979
+ while (prev >= 0 && _nodeTypeOf(value[prev]) === T_WHITESPACE) prev--;
2980
+ // `!` delim first: it's almost always absent, and `_nodeValueOf` allocates
2981
+ // a slice — this order pays it only for genuine `!important` candidates.
2982
+ if (
2983
+ prev >= 0 &&
2984
+ _nodeTypeOf(value[prev]) === T_DELIM &&
2985
+ input.charCodeAt(_nodeStartOf(value[prev])) === CC_EXCLAMATION &&
2986
+ _nodeTypeOf(value[last]) === T_IDENT &&
2987
+ equalsLowerCase(_nodeValueOf(value[last]), "important")
2988
+ ) {
2989
+ _setImportant(decl);
2990
+ value.length = prev;
2991
+ }
2992
+ }
2993
+
2994
+ // 7. While the last item in decl's value is a <whitespace-token>, remove that token.
2995
+ while (
2996
+ value.length > 0 &&
2997
+ _nodeTypeOf(value[value.length - 1]) === T_WHITESPACE
2998
+ ) {
2999
+ value.pop();
3000
+ }
3001
+
3002
+ // 8. If decl's name starts with "--" (a custom property), it can contain any value (including a top-level `{}` block) — accept it.
3003
+ // Otherwise, if decl's value contains a top-level simple block with an associated token of <{-token>, return nothing.
3004
+ // (That is, a top-level {}-block is only allowed as the entire value of a non-custom property — for CSS Nesting, `consumeABlocksContents`'s `mark` / `restore a mark` will retry the input as a qualified rule.)
3005
+ // Otherwise, accept the declaration. (The spec also checks "contains any non-whitespace-tokens at the top level" → return nothing; we keep empty-value declarations because callers — e.g. `@value name:;` — rely on them.)
3006
+ if (!isCustomProperty) {
3007
+ for (let i = 0; i < value.length; i++) {
3008
+ const v = value[i];
3009
+ if (_nodeTypeOf(v) === T_SIMPLE_BLOCK && _nodeTokenOf(v) === "{") {
3010
+ return undefined;
3011
+ }
3012
+ }
3013
+ }
3014
+
3015
+ // 9. Return decl.
3016
+ _setValue(decl, value);
3017
+ return decl;
3018
+ };
3019
+
3020
+ /**
3021
+ * Consume a list of component values, CSS Syntax Level 3 [§5.4.7](https://drafts.csswg.org/css-syntax/#consume-list-of-components) — consumes component values until EOF, the optional `stopToken`, or — when `nested` — a top-level `}` (left in the stream); a non-nested `}` is a parse error appended as a token.
3022
+ * @param {TokenStream} ts token stream
3023
+ * @param {number=} stopToken token type that terminates the list (left unconsumed)
3024
+ * @param {boolean=} nested true inside a `{}` block — a top-level `}` ends the list (left unconsumed)
3025
+ * @param {boolean=} bailOnCurly abort with `null` on a top-level `{` (left unconsumed) — for callers that would reject the list anyway (consume-a-declaration step 8) and restore a mark
3026
+ * @returns {ComponentValue[] | null} consumed component values, or `null` when `bailOnCurly` hit
3027
+ */
3028
+ const consumeAListOfComponentValues = (
3029
+ ts,
3030
+ stopToken,
3031
+ nested = false,
3032
+ bailOnCurly = false
3033
+ ) => {
3034
+ const values = /** @type {ComponentValue[]} */ (_soaActive ? _soaList() : []);
3035
+ // Process input
3036
+ for (;;) {
3037
+ const t = ts.next();
3038
+
3039
+ // <eof-token>
3040
+ // stop token (if passed)
3041
+ // Return values.
3042
+ if (t.type === TT_EOF || t.type === stopToken) {
3043
+ return values;
3044
+ }
3045
+ // <}-token>
3046
+ // If nested is true, return values.
3047
+ // Otherwise, this is a parse error. Consume a token from input and append the result to values.
3048
+ if (t.type === TT_RIGHT_CURLY_BRACKET) {
3049
+ if (nested) return values;
3050
+ const closer = consumeATokenAsNode(ts);
3051
+ // Keep unless the type is explicitly marked skip (1); an out-of-range
3052
+ // lookup on a short `skip.types` yields `undefined`, which must not drop.
3053
+ if (!_skipActive || _skipTypes[_nodeTypeOf(closer)] !== 1) {
3054
+ values.push(closer);
3055
+ }
3056
+ continue;
3057
+ }
3058
+ // A top-level `{` dooms the list for a bailing caller — stop before the
3059
+ // whole block is parsed only to be thrown away on the caller's restore.
3060
+ if (bailOnCurly && t.type === TT_LEFT_CURLY_BRACKET) return null;
3061
+ // anything else
3062
+ // Consume a component value from input, and append the result to values.
3063
+ // Skipped leaf types short-circuit before materializing: no SoA slot is
3064
+ // written and no node is built (blocks / functions never skip here).
3065
+ const tt = t.type;
3066
+ if (
3067
+ _skipActive &&
3068
+ tt !== TT_FUNCTION &&
3069
+ !(tt >= TT_LEFT_PARENTHESIS && tt <= TT_LEFT_CURLY_BRACKET) &&
3070
+ _skipTypes[_ttToNodeType[tt]] === 1
3071
+ ) {
3072
+ ts.consume();
3073
+ continue;
3074
+ }
3075
+ const node = consumeAComponentValue(ts, t);
3076
+ if (!_skipActive || _skipTypes[_nodeTypeOf(node)] !== 1) values.push(node);
3077
+ }
3078
+ };
3079
+
3080
+ /**
3081
+ * Consume a component value, CSS Syntax Level 3 [§5.4.8](https://drafts.csswg.org/css-syntax/#consume-component-value) — consumes the next value (simple block, function, or single token); callers guard against EOF before calling.
3082
+ * @param {TokenStream} ts token stream
3083
+ * @param {MutableToken=} t the next token, if the caller already peeked it (defaults to `ts.next()`)
3084
+ * @returns {SimpleBlock | FunctionNode | ComponentValue} the consumed component value
3085
+ */
3086
+ const consumeAComponentValue = (ts, t = ts.next()) => {
3087
+ // `t` is the next token; hot callers already peeked it and pass it in to
3088
+ // skip a redundant `ts.next()` per component value.
3089
+ // <{-token> / <[-token> / <(-token> (the three contiguous opening brackets)
3090
+ // Consume a simple block from input and return the result.
3091
+ if (t.type >= TT_LEFT_PARENTHESIS && t.type <= TT_LEFT_CURLY_BRACKET) {
3092
+ return /** @type {SimpleBlock} */ (consumeASimpleBlock(ts));
3093
+ }
3094
+ // <function-token>
3095
+ // Consume a function from input and return the result.
3096
+ if (t.type === TT_FUNCTION) {
3097
+ return /** @type {FunctionNode} */ (consumeAFunction(ts));
3098
+ }
3099
+ // anything else
3100
+ // Consume a token from input and return the result. (Asserted: not EOF.)
3101
+ // Inlined `consumeATokenAsNode`: `t` is already the peeked next token, so
3102
+ // advance past it and materialize it directly — one fewer call per leaf
3103
+ // component value (the bulk of the nodes on a large stylesheet).
3104
+ ts.consume();
3105
+ return /** @type {ComponentValue} */ (tokenToNode(t));
3106
+ };
3107
+
3108
+ /**
3109
+ * Consume a simple block, CSS Syntax Level 3 [§5.4.9](https://drafts.csswg.org/css-syntax/#consume-simple-block) — the next token must be `(`, `[`, or `{` (asserted); consumes component values via `consumeAComponentValue` until the mirror closing token (`)`, `]`, `}`) or EOF, returning the partial block on EOF (parse error).
3110
+ * @param {TokenStream} ts token stream
3111
+ * @returns {SimpleBlock | undefined} the parsed simple block
3112
+ */
3113
+ const consumeASimpleBlock = (ts) => {
3114
+ const open = ts.next();
3115
+ // Assert (spec): the next token of input is <{-token>, <[-token>, or <(-token>.
3116
+ // Mirror closing token (`opener + 3`) and the associated block char.
3117
+ const ending = open.type + 3;
3118
+ const token = BLOCK_TOKEN_CHAR[open.type - TT_LEFT_PARENTHESIS];
3119
+
3120
+ // Let block be a new simple block with its associated token set to the next token and with its value initially set to an empty list.
3121
+ const block = /** @type {SimpleBlock} */ (
3122
+ _makeContainer(T_SIMPLE_BLOCK, open.start, open.end)
3123
+ );
3124
+ _setToken(block, token);
3125
+ // Sealed (`_setValue`) at the return, once complete.
3126
+ const val = _soaActive ? _soaList() : [];
3127
+
3128
+ // Discard a token from input.
3129
+ ts.discard();
3130
+
3131
+ // Process input
3132
+ for (;;) {
3133
+ const t = ts.next();
3134
+
3135
+ // <eof-token>
3136
+ // ending token
3137
+ // Discard a token from input. Return block.
3138
+ if (t.type === TT_EOF || t.type === ending) {
3139
+ ts.discard();
3140
+ _setValue(block, val);
3141
+ _setEnd(block, t.end);
3142
+ return block;
3143
+ }
3144
+
3145
+ // anything else
3146
+ // Consume a component value from input and append the result to block’s value.
3147
+ val.push(consumeAComponentValue(ts, t));
3148
+ }
3149
+ };
3150
+
3151
+ /**
3152
+ * Consume a function, CSS Syntax Level 3 [§5.4.10](https://drafts.csswg.org/css-syntax/#consume-function) — consumes component values up to the matching `)` or EOF (the partial function on EOF is a parse error).
3153
+ * @param {TokenStream} ts token stream
3154
+ * @returns {FunctionNode | undefined} the consumed function node
3155
+ */
3156
+ const consumeAFunction = (ts) => {
3157
+ // Assert (spec): the next token is a <function-token>.
3158
+ // Consume a token from input, and let function be a new function with its name equal the returned token’s value, and a value set to an empty list.
3159
+ const tFn = ts.consume();
3160
+ const fn = /** @type {FunctionNode} */ (
3161
+ _makeContainer(T_FUNCTION, tFn.start, tFn.end)
3162
+ );
3163
+ _setName(fn, tFn.start, tFn.end - 1);
3164
+ // Sealed (`_setValue`) at the return, once complete.
3165
+ const val = _soaActive ? _soaList() : [];
3166
+
3167
+ // Process input
3168
+ for (;;) {
3169
+ const t = ts.next();
3170
+
3171
+ if (t.type === TT_EOF || t.type === TT_RIGHT_PARENTHESIS) {
3172
+ // <eof-token>
3173
+ // <)-token>
3174
+ // Discard a token from input. Return function.
3175
+ ts.discard();
3176
+ _setValue(fn, val);
3177
+ _setEnd(fn, t.end);
3178
+ return fn;
3179
+ }
3180
+
3181
+ // anything else
3182
+ // Consume a component value from input and append the result to function’s value.
3183
+ // Same pre-materialization skip as `consumeAListOfComponentValues`.
3184
+ const tt = t.type;
3185
+ if (
3186
+ _skipActive &&
3187
+ tt !== TT_FUNCTION &&
3188
+ !(tt >= TT_LEFT_PARENTHESIS && tt <= TT_LEFT_CURLY_BRACKET) &&
3189
+ _skipTypes[_ttToNodeType[tt]] === 1
3190
+ ) {
3191
+ ts.consume();
3192
+ continue;
3193
+ }
3194
+ const node = consumeAComponentValue(ts, t);
3195
+ if (!_skipActive || _skipTypes[_nodeTypeOf(node)] !== 1) val.push(node);
3196
+ }
3197
+ };
3198
+
3199
+ // Identifier escape / unescape — operate on the raw text of an
3200
+ // `<ident-token>` (or any source slice that may carry CSS escape sequences).
3201
+ // `escapeIdentifier` produces a CSS-Syntax-3-conformant `<ident-token>` from
3202
+ // an arbitrary string (so the result can be re-tokenized as the same name);
3203
+ // `unescapeIdentifier` reverses tokenizer-time escapes per
3204
+ // https://www.w3.org/TR/css-syntax-3/#consume-escaped-code-point.
3205
+ // Both are pure string functions and have no dependency on the AST; they
3206
+ // live here so the AST module is a one-stop shop for CSS-syntax-level
3207
+ // utilities. `CssParser.js` re-exports them for back-compat with callers
3208
+ // that previously reached them via `getCssParser()`.
3209
+
3210
+ const regexSingleEscape = /[ -,./:-@[\]^`{-~]/;
3211
+ const regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6}) (?![a-fA-F0-9 ])/g;
3212
+ // ASCII escape class per char code: 0 = pass through, 1 = `\<char>` single
3213
+ // escape, 2 = `\HEX ` (control chars). Built from the original predicates so
3214
+ // behaviour is identical; replaces two regex tests per character with one load.
3215
+ const ESCAPE_CLASS_HEX = 2;
3216
+ const ESCAPE_CLASS_SINGLE = 1;
3217
+ const _escapeClassTable = new Uint8Array(128);
3218
+ for (let i = 0; i < 128; i++) {
3219
+ const ch = String.fromCharCode(i);
3220
+ _escapeClassTable[i] = /[\t\n\f\r\v]/.test(ch)
3221
+ ? ESCAPE_CLASS_HEX
3222
+ : ch === "\\" || regexSingleEscape.test(ch)
3223
+ ? ESCAPE_CLASS_SINGLE
3224
+ : 0;
3225
+ }
3226
+
3227
+ /**
3228
+ * Returns escaped identifier.
3229
+ * @param {string} str string
3230
+ * @returns {string} escaped identifier
3231
+ */
3232
+ const _escapeIdentifier = (str) => {
3233
+ let output = "";
3234
+ // Flush safe runs in bulk: only escaped chars break the run, so an
3235
+ // identifier needing no escapes returns `str` unchanged (no allocation).
3236
+ let lastFlush = 0;
3237
+ let needSpaceFix = false;
3238
+ for (let i = 0; i < str.length; i++) {
3239
+ const cc = str.charCodeAt(i);
3240
+ const cls = cc < 128 ? _escapeClassTable[cc] : 0;
3241
+ if (cls === 0) continue;
3242
+ output += str.slice(lastFlush, i);
3243
+ if (cls === ESCAPE_CLASS_SINGLE) {
3244
+ output += `\\${str[i]}`;
3245
+ } else {
3246
+ output += `\\${cc.toString(16).toUpperCase()} `;
3247
+ needSpaceFix = true;
3248
+ }
3249
+ lastFlush = i + 1;
3250
+ }
3251
+ output = lastFlush === 0 ? str : output + str.slice(lastFlush);
3252
+
3253
+ // `-` and digits are class 0 (never escaped above), so testing `str`'s lead
3254
+ // char codes is equivalent to regexes over `output` — and keeps the common
3255
+ // nothing-to-do call regex-free.
3256
+ const first = str.charCodeAt(0);
3257
+ if (
3258
+ first === CC_HYPHEN_MINUS &&
3259
+ (str.charCodeAt(1) === CC_HYPHEN_MINUS || _isDigit(str.charCodeAt(1)))
3260
+ ) {
3261
+ output = `\\-${output.slice(1)}`;
3262
+ } else if (_isDigit(first)) {
3263
+ // A leading digit becomes `\3<digit> `, another `\HEX ` run to clean up.
3264
+ output = `\\3${str.charAt(0)} ${output.slice(1)}`;
3265
+ needSpaceFix = true;
3266
+ }
3267
+
3268
+ // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
3269
+ // since they’re redundant. Only `\HEX ` runs (above) can produce them; plain
3270
+ // single escapes can't, so skip the scan when none were emitted. Note this is
3271
+ // only possible if the escape isn't preceded by an odd number of backslashes.
3272
+ if (needSpaceFix) {
3273
+ output = output.replace(regexExcessiveSpaces, ($0, $1, $2) => {
3274
+ /* istanbul ignore if -- @preserve: this escaper never emits an odd run of backslashes before a `\HEX` escape (literal `\` is doubled) */
3275
+ if ($1 && $1.length % 2) {
3276
+ // It’s not safe to remove the space, so don’t.
3277
+ return $0;
3278
+ }
3279
+
3280
+ // Strip the space.
3281
+ return ($1 || "") + $2;
3282
+ });
3283
+ }
3284
+
3285
+ return output;
3286
+ };
3287
+
3288
+ /**
3289
+ * Returns hex. Reads up to six hex digits from `str` starting at `start` —
3290
+ * indexed rather than sliced, and case-folded inline, so the common
3291
+ * non-hex escape (e.g. `\:` in `focus\:sr-only`) allocates nothing.
3292
+ * @param {string} str string
3293
+ * @param {number} start index just past the `\`
3294
+ * @returns {[string, number] | undefined} hex
3295
+ */
3296
+ const gobbleHex = (str, start) => {
3297
+ let hex = "";
3298
+
3299
+ for (let i = 0; i < 6; i++) {
3300
+ const code = str.charCodeAt(start + i);
3301
+ // valid hex char [0-9 | A-F | a-f]; out-of-range reads NaN -> invalid
3302
+ const valid =
3303
+ (code >= 48 && code <= 57) ||
3304
+ (code >= 65 && code <= 70) ||
3305
+ (code >= 97 && code <= 102);
3306
+ if (!valid) break;
3307
+ // parseInt below is case-insensitive, so keep the original char.
3308
+ hex += str[start + i];
3309
+ }
3310
+
3311
+ if (hex.length === 0) return undefined;
3312
+
3313
+ // One trailing whitespace terminates the escape, matching the tokenizer's
3314
+ // `_consumeAnEscapedCodePoint` — including after a full 6-digit escape, for
3315
+ // any CSS whitespace (not just space), plus the extra LF of a CRLF pair.
3316
+ // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
3317
+ let consumed = hex.length;
3318
+ const trail = str.charCodeAt(start + hex.length);
3319
+ if (_isWhiteSpace(trail)) {
3320
+ consumed = consumeExtraNewline(trail, str, start + hex.length + 1) - start;
3321
+ }
3322
+
3323
+ const codePoint = Number.parseInt(hex, 16);
3324
+ const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
3325
+
3326
+ // Add special case for
3327
+ // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
3328
+ // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
3329
+ if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
3330
+ return ["�", consumed];
3331
+ }
3332
+
3333
+ return [String.fromCodePoint(codePoint), consumed];
3334
+ };
3335
+
3336
+ /**
3337
+ * Unescape identifier.
3338
+ * @param {string} str string
3339
+ * @returns {string} unescaped string
3340
+ */
3341
+ const _unescapeIdentifier = (str) => {
3342
+ // `indexOf` is the no-escape fast path and the start offset in one — the
3343
+ // leading safe run is skipped and an unescaped ident returns as-is.
3344
+ const first = str.indexOf("\\");
3345
+ if (first === -1) return str;
3346
+ let ret = "";
3347
+ // Flush safe runs in bulk instead of appending char by char.
3348
+ let lastFlush = 0;
3349
+ for (let i = first; i < str.length; i++) {
3350
+ if (str[i] !== "\\") continue;
3351
+ ret += str.slice(lastFlush, i);
3352
+ const gobbled = gobbleHex(str, i + 1);
3353
+ if (gobbled !== undefined) {
3354
+ ret += gobbled[0];
3355
+ i += gobbled[1];
3356
+ } else if (str[i + 1] === "\\") {
3357
+ // Retain one `\` of an escaped `\\` pair.
3358
+ // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
3359
+ ret += "\\";
3360
+ i += 1;
3361
+ } else if (str.length === i + 1) {
3362
+ // A trailing lone `\` is retained.
3363
+ // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
3364
+ ret += "\\";
3365
+ }
3366
+ // Otherwise the lone `\` is dropped; the next char flushes with its run.
3367
+ lastFlush = i + 1;
3368
+ }
3369
+ ret += str.slice(lastFlush);
3370
+
3371
+ return ret;
3372
+ };
3373
+
3374
+ // Cacheable per `compiler.root` — CssParser binds once per parse via
3375
+ // `.bindCache(...)` and reuses for every identifier.
3376
+ const escapeIdentifier = makeCacheable(_escapeIdentifier);
3377
+ const unescapeIdentifier = makeCacheable(_unescapeIdentifier);
3378
+
3379
+ // A url-token / url-string value's escaped newlines (`url("im\<newline>g.png")`).
3380
+ const STRING_MULTILINE = /\\[\n\r\f]/g;
3381
+ // Leading / trailing CSS whitespace inside a quoted url value.
3382
+ const TRIM_WHITE_SPACES = /(^[ \t\n\r\f]*|[ \t\n\r\f]*$)/g;
3383
+ // One CSS escape: `\` + up to 6 hex digits (+ optional whitespace) or any char.
3384
+ const UNESCAPE = /\\([0-9a-f]{1,6}[ \t\n\r\f]?|[\s\S])/gi;
3385
+
3386
+ /**
3387
+ * Normalize a url value (a url-token's content or a url string's body) into
3388
+ * the form requests are resolved from: escaped newlines removed (string form),
3389
+ * edge whitespace trimmed, CSS escapes and percent-encoding decoded
3390
+ * (`data:` URIs excepted).
3391
+ * @param {string} str url string
3392
+ * @param {boolean} isString is url wrapped in quotes
3393
+ * @returns {string} normalized url
3394
+ */
3395
+ const normalizeUrl = (str, isString) => {
3396
+ // Fast paths: skip the regex engine for the common URL with no escape and
3397
+ // no edge whitespace (e.g. `./img.png`). Each guard is equivalent to the
3398
+ // regex being a no-op.
3399
+ // Remove escaped newlines from a string-token url like `url("im\<newline>g.png")`.
3400
+ if (isString && str.includes("\\")) {
3401
+ str = str.replace(STRING_MULTILINE, "");
3402
+ }
3403
+
3404
+ // Remove unnecessary spaces from `url(" img.png ")`
3405
+ if (
3406
+ str.length !== 0 &&
3407
+ (_isWhiteSpace(str.charCodeAt(0)) ||
3408
+ _isWhiteSpace(str.charCodeAt(str.length - 1)))
3409
+ ) {
3410
+ str = str.replace(TRIM_WHITE_SPACES, "");
3411
+ }
3412
+
3413
+ // Unescape
3414
+ if (str.includes("\\")) {
3415
+ str = str.replace(UNESCAPE, (match) => {
3416
+ if (match.length > 2) {
3417
+ return String.fromCharCode(Number.parseInt(match.slice(1).trim(), 16));
3418
+ }
3419
+ return match[1];
3420
+ });
3421
+ }
3422
+
3423
+ // Char-code gate so the dominant non-`data:` url skips the regex test.
3424
+ if ((str.charCodeAt(0) | 0x20) === CC_LOWER_D && /^data:/i.test(str)) {
3425
+ return str;
3426
+ }
3427
+
3428
+ if (str.includes("%")) {
3429
+ // Convert `url('%2E/img.png')` -> `url('./img.png')`
3430
+ try {
3431
+ str = decodeURIComponent(str);
3432
+ } catch (_err) {
3433
+ // Ignore
3434
+ }
3435
+ }
3436
+
3437
+ return str;
3438
+ };
3439
+
3440
+ // CSS-typed views over the generic visitor machinery (`util/SourceProcessor`),
3441
+ // re-exported so consumers keep importing them from this module.
3442
+ /**
3443
+ * @typedef {import("../util/SourceProcessor").VisitorFn<CssPath>} VisitorFn
3444
+ * @typedef {import("../util/SourceProcessor").VisitorBucket<CssPath>} VisitorBucket
3445
+ * @typedef {import("../util/SourceProcessor").VisitorMap<CssPath>} VisitorMap
3446
+ * @typedef {import("../util/SourceProcessor").CompiledVisitorMap<CssPath>} CompiledVisitorMap
3447
+ */
3448
+
3449
+ /**
3450
+ * A CSS Syntax §5.4 top-level consumer that streams each top-level node it
3451
+ * produces to `onNode` (in source order) rather than collecting it. Every entry
3452
+ * in `TOP_LEVEL_CONSUMERS` shares this shape, so the walk's `grammar` drives any
3453
+ * `as` mode through one call — a future mode is just another map entry.
3454
+ * @typedef {(ts: TokenStream, onNode: (node: Rule | Declaration) => void) => void} TopLevelConsumer
3455
+ */
3456
+
3457
+ /**
3458
+ * `as` value → the §5.4 consumer that streams its top-level nodes. Keyed by the
3459
+ * public `CssParserOptions.as` enum.
3460
+ * @type {Record<string, TopLevelConsumer>}
3461
+ */
3462
+ const TOP_LEVEL_CONSUMERS = {
3463
+ stylesheet: /** @type {TopLevelConsumer} */ (consumeAStylesheetsContents),
3464
+ "block-contents": consumeABlocksContents
3465
+ };
3466
+
3467
+ /**
3468
+ * @typedef {object} CssProcessOptions
3469
+ * @property {LocConverter=} locConverter shared loc converter (default a fresh one over the input)
3470
+ * @property {boolean=} recurseBlocks walk into block bodies' nested rules (default true)
3471
+ * @property {("stylesheet" | "block-contents")=} as which top-level production to consume the source as (see `TOP_LEVEL_CONSUMERS`): `"stylesheet"` (default) or `"block-contents"` (a block's contents, e.g. an HTML `style` attribute)
3472
+ * @property {SkipOptions=} skip what the grammar may leave un-materialized to go faster — safe only for parts nothing reads in the active parse; default skip nothing
3473
+ */
3474
+
3475
+ /**
3476
+ * `CssProcessOptions.skip`: two independent axes, so each reads unambiguously.
3477
+ * @typedef {object} SkipOptions
3478
+ * @property {Uint8Array=} types component-value node types to drop from declaration value / function-arg lists (indexed by `NodeType`, 1 = skip; build with `buildSkipSet`)
3479
+ * @property {boolean=} selectorPrelude drop qualified-rule (selector) preludes — the rule and its block are still produced (default false)
3480
+ * @property {boolean=} atRulePrelude drop at-rule preludes — the at-rule and its block are still produced (default false)
3481
+ */
3482
+
3483
+ // Per-parse walk state in module slots (same pattern as `_skip*`) so the walk
3484
+ // functions below are module-level constants: one function identity across
3485
+ // parses keeps the recursive per-node call sites monomorphic and drops the
3486
+ // per-parse closure allocations.
3487
+ /** @typedef {import("../util/SourceProcessor").CompiledVisitorBucket<CssPath>} CompiledVisitorBucket */
3488
+ /** @type {CompiledVisitorMap} */
3489
+ let _visitors = /** @type {CompiledVisitorMap} */ (/** @type {unknown} */ ([]));
3490
+ let _recurseBlocks = true;
3491
+ /** @type {CompiledVisitorBucket | undefined} */
3492
+ let _commentBucket;
3493
+
3494
+ // Comments reach the visitor map through `NodeType.Comment` instead of a
3495
+ // side callback. They fire during tokenization — in source order among
3496
+ // comments, not interleaved with the node walk — on a transient SoA node so
3497
+ // `A.start`/`end`/`loc`/`source` work. No comment visitor → no callback →
3498
+ // the tokenizer skips comments with zero overhead.
3499
+ /** @type {(input: string, start: number, end: number) => number} */
3500
+ const _grammarOnComment = (_input, start, end) => {
3501
+ const node = _soaAllocNode(T_COMMENT, start, end);
3502
+ _currentNode = node;
3503
+ _currentParent = null;
3504
+ const bucket = /** @type {CompiledVisitorBucket} */ (_commentBucket);
3505
+ const e = bucket.enter;
3506
+ for (let i = 0; i < e.length; i++) e[i](A);
3507
+ const x = bucket.exit;
3508
+ for (let i = 0; i < x.length; i++) x[i](A);
3509
+ return end;
3510
+ };
3511
+
3512
+ /**
3513
+ * Walk a component-value subtree; children are already materialized. Fetches
3514
+ * the node's visitor bucket once (reused for enter + exit) and uses index
3515
+ * loops — `for…of` would allocate an iterator per node on this hot path.
3516
+ * @param {Node} node component-value root
3517
+ * @param {Node | null} parent enclosing node
3518
+ */
3519
+ const _walkValue = (node, parent) => {
3520
+ const ty = _soaTypes[_nodeIndex(node)];
3521
+ const b = _visitors[ty];
3522
+ let skip = false;
3523
+ if (b !== undefined && b.enter.length !== 0) {
3524
+ _walkSkip = false;
3525
+ _currentNode = node;
3526
+ _currentParent = parent;
3527
+ const e = b.enter;
3528
+ for (let i = 0; i < e.length; i++) e[i](A);
3529
+ skip = _walkSkip;
3530
+ _walkSkip = false;
3531
+ }
3532
+ if (!skip && (ty === T_FUNCTION || ty === T_SIMPLE_BLOCK)) {
3533
+ const i0 = _nodeIndex(node);
3534
+ const vs = _soaListStarts[i0];
3535
+ const ve = vs + _soaListLens[i0];
3536
+ for (let i = vs; i < ve; i++) _walkValue(_nodeRef(_soaFlat[i]), node);
3537
+ }
3538
+ if (b !== undefined) {
3539
+ // Rebind: descending into children moved the path.
3540
+ _currentNode = node;
3541
+ _currentParent = parent;
3542
+ const x = b.exit;
3543
+ for (let i = 0; i < x.length; i++) x[i](A);
3544
+ }
3545
+ };
3546
+
3547
+ /**
3548
+ * Walk a structural subtree; an at-rule / qualified-rule's block was parsed
3549
+ * eagerly (§5.4.4), so its `value` holds the nested rules / declarations.
3550
+ * @param {Node} node structural-tree root
3551
+ * @param {Node | null} parent enclosing node
3552
+ */
3553
+ const _walkRule = (node, parent) => {
3554
+ const i0 = _nodeIndex(node);
3555
+ const ty = _soaTypes[i0];
3556
+ const b = _visitors[ty];
3557
+ let skip = false;
3558
+ if (b !== undefined && b.enter.length !== 0) {
3559
+ _walkSkip = false;
3560
+ _currentNode = node;
3561
+ _currentParent = parent;
3562
+ const e = b.enter;
3563
+ for (let i = 0; i < e.length; i++) e[i](A);
3564
+ skip = _walkSkip;
3565
+ _walkSkip = false;
3566
+ }
3567
+ if (!skip) {
3568
+ if (ty === T_AT_RULE || ty === T_QUALIFIED_RULE) {
3569
+ const ps = _soaListStarts[i0];
3570
+ const pe = ps + _soaListLens[i0];
3571
+ for (let i = ps; i < pe; i++) _walkValue(_nodeRef(_soaFlat[i]), node);
3572
+ if (_recurseBlocks) {
3573
+ // Declarations then child rules — downstream consumers don't need them strictly interleaved in source order.
3574
+ const decls = _soaDeclarationLists[i0];
3575
+ if (decls) {
3576
+ for (let i = 0; i < decls.length; i++) _walkRule(decls[i], node);
3577
+ }
3578
+ const ch = _soaChildRuleLists[i0];
3579
+ if (ch) for (let i = 0; i < ch.length; i++) _walkRule(ch[i], node);
3580
+ }
3581
+ } else if (ty === T_DECLARATION) {
3582
+ const vs = _soaListStarts[i0];
3583
+ const ve = vs + _soaListLens[i0];
3584
+ for (let i = vs; i < ve; i++) _walkValue(_nodeRef(_soaFlat[i]), node);
3585
+ }
3586
+ }
3587
+ if (b !== undefined) {
3588
+ // Rebind: descending into children moved the path.
3589
+ _currentNode = node;
3590
+ _currentParent = parent;
3591
+ const x = b.exit;
3592
+ for (let i = 0; i < x.length; i++) x[i](A);
3593
+ }
3594
+ };
3595
+
3596
+ /**
3597
+ * The `grammar` streaming sink: walk one top-level node, then recycle the SoA
3598
+ * buffers for the next.
3599
+ * @param {Rule | Declaration} node top-level node
3600
+ */
3601
+ const _walkTopLevel = (node) => {
3602
+ _walkRule(node, null);
3603
+ if (_soaNodeCount > _soaPeak) _soaPeak = _soaNodeCount;
3604
+ if (_soaFlatTop > _soaFlatPeak) _soaFlatPeak = _soaFlatTop;
3605
+ _soaNodeCount = 0;
3606
+ _soaFlatTop = 0;
3607
+ };
3608
+
3609
+ // The SoA buffers grow to the largest single top-level rule ever parsed and
3610
+ // live at module level; above this capacity they are re-shrunk after a parse
3611
+ // so one pathological rule can't pin megabytes for the process lifetime.
3612
+ const _SOA_SHRINK_CAPACITY = 65536;
3613
+
3614
+ /**
3615
+ * The CSS `SourceProcessor` grammar: consume top-level rules one at a time
3616
+ * (§5.4.1) and walk each immediately, firing `enter` / `exit` in source order
3617
+ * without building a whole-stylesheet array first. `recurseBlocks: false` skips
3618
+ * walking block bodies' (eagerly parsed) nested rules (caller drives nested
3619
+ * traversal itself).
3620
+ * @param {string} input source text
3621
+ * @param {CompiledVisitorMap} visitors compiled visitor map
3622
+ * @param {CssProcessOptions} options process options
3623
+ */
3624
+ const grammar = (input, visitors, options) => {
3625
+ const locConverter = options.locConverter || new LocConverter(input);
3626
+ useSoaBackend(input, locConverter);
3627
+ const skip = options.skip;
3628
+ _skipTypes = (skip && skip.types) || _NO_SKIP_TYPES;
3629
+ _skipActive = _skipTypes !== _NO_SKIP_TYPES;
3630
+ _skipSelectorPrelude = skip !== undefined && skip.selectorPrelude === true;
3631
+ _skipAtRulePrelude = skip !== undefined && skip.atRulePrelude === true;
3632
+ _recurseBlocks = options.recurseBlocks !== false;
3633
+ _visitors = visitors;
3634
+ _commentBucket = visitors[T_COMMENT];
3635
+
3636
+ // Stream each top-level node (selected by `as`) to the walker the moment it's
3637
+ // consumed, rather than collecting them first — so the whole AST is never
3638
+ // held at once; peak heap is ~one top-level node's subtree.
3639
+ const ts = new TokenStream(
3640
+ input,
3641
+ 0,
3642
+ locConverter,
3643
+ _commentBucket === undefined ? undefined : _grammarOnComment
3644
+ );
3645
+ const consume =
3646
+ TOP_LEVEL_CONSUMERS[options.as || "stylesheet"] ||
3647
+ consumeAStylesheetsContents;
3648
+ try {
3649
+ consume(ts, _walkTopLevel);
3650
+ } finally {
3651
+ // Drop the module-level SoA references so the last parsed source (and
3652
+ // its LocConverter / child lists / visitors) don't stay alive between
3653
+ // parses.
3654
+ _soaInput = "";
3655
+ _soaLocConverter = /** @type {LocConverter} */ (
3656
+ /** @type {unknown} */ (null)
3657
+ );
3658
+ _soaDeclarationLists.length = 0;
3659
+ _soaChildRuleLists.length = 0;
3660
+ _soaFlatTop = 0;
3661
+ _listPool.length = 0;
3662
+ if (_soaFlat.length > _SOA_SHRINK_CAPACITY) {
3663
+ _soaFlatGrowHint = _soaFlatPeak;
3664
+ _soaFlat = new Int32Array(0);
3665
+ }
3666
+ _visitors = /** @type {CompiledVisitorMap} */ (/** @type {unknown} */ ([]));
3667
+ _commentBucket = undefined;
3668
+ if (_soaCapacity > _SOA_SHRINK_CAPACITY) {
3669
+ // +1: node ids are 1-based and grow fires at `id >= capacity`.
3670
+ _soaGrowHint = _soaPeak + 1;
3671
+ _soaCapacity = 0;
3672
+ _soaTypes = new Uint8Array(0);
3673
+ _soaStarts = new Int32Array(0);
3674
+ _soaEnds = new Int32Array(0);
3675
+ _soaAux0 = new Int32Array(0);
3676
+ _soaAux1 = new Int32Array(0);
3677
+ _soaAux2 = new Int32Array(0);
3678
+ _soaFlags = new Uint8Array(0);
3679
+ _soaListStarts = new Int32Array(0);
3680
+ _soaListLens = new Int32Array(0);
3681
+ }
3682
+ _soaPeak = 0;
3683
+ _soaFlatPeak = 0;
3684
+ }
3685
+ };
3686
+
3687
+ /**
3688
+ * The generic visitor coordinator (`util/SourceProcessor`) bound to the CSS
3689
+ * `grammar`. Babel-style usage:
3690
+ *
3691
+ * ```
3692
+ * new SourceProcessor({ skip }).use({ [NodeType.AtRule]: (path) => {} }).process(source);
3693
+ * ```
3694
+ * @extends {GenericSourceProcessor<CssPath, CssProcessOptions>}
3695
+ */
3696
+ class SourceProcessor extends GenericSourceProcessor {
3697
+ /**
3698
+ * @param {CssProcessOptions=} options default process options (`skip`, `as`, …) for every `process` call
3699
+ */
3700
+ constructor(options) {
3701
+ super(grammar, options);
3702
+ }
3703
+ }
3704
+
3705
+ /**
3706
+ * Build a `SkipOptions.types` set (drop these component-value node types from
3707
+ * value / function-arg lists) from a list of `NodeType`s. Preludes are separate
3708
+ * (`SkipOptions.selectorPrelude` / `atRulePrelude`). The caller owns the safety
3709
+ * contract: only pass types nothing reads in the intended parse. Two
3710
+ * grammar-internal caveats beyond consumer needs: dropping both `Delim` and
3711
+ * `Ident` loses `!important` detection, and dropping `SimpleBlock` loses the
3712
+ * custom-property `{}`-value check (and its subtree). Precompute once per
3713
+ * configuration and reuse across parses.
3714
+ * @param {number[]} nodeTypes component-value node types to drop
3715
+ * @returns {Uint8Array} skip-types set indexed by `NodeType`
3716
+ */
3717
+ const buildSkipSet = (nodeTypes) => {
3718
+ const set = new Uint8Array(32);
3719
+ for (let i = 0; i < nodeTypes.length; i++) set[nodeTypes[i]] = 1;
3720
+ return set;
3721
+ };
3722
+
3723
+ /* eslint-disable jsdoc/require-template -- `A` below is the accessor const, not a type parameter */
3724
+ /**
3725
+ * The CSS path (Babel's `path` shape): the AST accessor with the walk's
3726
+ * current position on it — the single argument every visitor receives.
3727
+ * @typedef {typeof A} CssPath
3728
+ */
3729
+ /* eslint-enable jsdoc/require-template */
3730
+
3731
+ // A fresh (safely retainable) array view of a node's flat content span —
3732
+ // visitors that read `A.children` / `A.prelude` may keep the result.
3733
+ /** @type {(n: Node) => Node[]} */
3734
+ const _materializeList = (n) => {
3735
+ const i = _nodeIndex(n);
3736
+ const start = _soaListStarts[i];
3737
+ const len = _soaListLens[i];
3738
+ /** @type {Node[]} */
3739
+ const out = [];
3740
+ for (let k = 0; k < len; k++) out.push(_nodeRef(_soaFlat[start + k]));
3741
+ return out;
3742
+ };
3743
+
3744
+ // Babel's `path.skip()`, children-only: set by `A.skipChildren()` during an
3745
+ // `enter` dispatch, consumed by the walk.
3746
+ let _walkSkip = false;
3747
+ // The walk's current position (`A.node` / `A.parent` read these; module-level
3748
+ // so the accessor methods' defaults avoid self-referential `this` typing).
3749
+ /** @type {Node} */
3750
+ let _currentNode = /** @type {Node} */ (/** @type {unknown} */ (0));
3751
+ /** @type {Node | null} */
3752
+ let _currentParent = null;
3753
+
3754
+ // AST field-access seam. Every AST-node field read by `CssParser` goes through
3755
+ // one of these accessors so the node representation can change underneath the
3756
+ // consumer without touching it. Today they are backed by the `Node` / `Token` /
3757
+ // `Container` objects (`n` is a node); the Struct-of-Arrays migration rewrites
3758
+ // the bodies to index typed arrays (`n` becomes an integer node id) without any
3759
+ // consumer edit. `value` is the leaf-token string; container child lists are
3760
+ // `children` / `prelude` / `declarations` / `childRules`.
3761
+ const A = {
3762
+ // === path position (rebound by the walk before every visitor call) ===
3763
+ /**
3764
+ * @returns {Node} current node — only valid during a visitor callback
3765
+ */
3766
+ get node() {
3767
+ return _currentNode;
3768
+ },
3769
+ /**
3770
+ * @returns {Node | null} enclosing node (null = a top-level node)
3771
+ */
3772
+ get parent() {
3773
+ return _currentParent;
3774
+ },
3775
+ /** Stop the walk descending into the current node (enter only). */
3776
+ skipChildren() {
3777
+ _walkSkip = true;
3778
+ },
3779
+ // === field reads — `n` defaults to the current node ===
3780
+ /**
3781
+ * @param {Node=} n node
3782
+ * @returns {number} node type
3783
+ */
3784
+ type(n = _currentNode) {
3785
+ return _soaTypes[_nodeIndex(n)];
3786
+ },
3787
+ /**
3788
+ * @param {Node=} n node
3789
+ * @returns {number} start offset
3790
+ */
3791
+ start(n = _currentNode) {
3792
+ return _soaStarts[_nodeIndex(n)];
3793
+ },
3794
+ /**
3795
+ * @param {Node=} n node
3796
+ * @returns {number} end offset
3797
+ */
3798
+ end(n = _currentNode) {
3799
+ return _soaEnds[_nodeIndex(n)];
3800
+ },
3801
+ /**
3802
+ * @param {Node=} n node
3803
+ * @returns {[number, number]} start / end offsets
3804
+ */
3805
+ range(n = _currentNode) {
3806
+ const i = _nodeIndex(n);
3807
+ return [_soaStarts[i], _soaEnds[i]];
3808
+ },
3809
+ /**
3810
+ * @param {Node=} n node
3811
+ * @returns {{ start: { line: number, column: number }, end: { line: number, column: number } }} source location
3812
+ */
3813
+ loc(n = _currentNode) {
3814
+ const i = _nodeIndex(n);
3815
+ const lc = _soaLocConverter;
3816
+ const s = lc.get(_soaStarts[i]);
3817
+ const sl = s.line;
3818
+ const sc = s.column;
3819
+ const e = lc.get(_soaEnds[i]);
3820
+ return {
3821
+ start: { line: sl, column: sc },
3822
+ end: { line: e.line, column: e.column }
3823
+ };
3824
+ },
3825
+ /**
3826
+ * @param {Node=} n node
3827
+ * @returns {string} raw source slice
3828
+ */
3829
+ source(n = _currentNode) {
3830
+ const i = _nodeIndex(n);
3831
+ return _soaInput.slice(_soaStarts[i], _soaEnds[i]);
3832
+ },
3833
+ /**
3834
+ * @param {Node=} n node
3835
+ * @returns {string} raw token value
3836
+ */
3837
+ value(n = _currentNode) {
3838
+ return _soaValueOf(_nodeIndex(n));
3839
+ },
3840
+ /**
3841
+ * @param {Node=} n node
3842
+ * @returns {string} unescaped token value
3843
+ */
3844
+ unescaped(n = _currentNode) {
3845
+ const i = _nodeIndex(n);
3846
+ const v = _soaValueOf(i);
3847
+ return _soaTypes[i] === T_STRING
3848
+ ? unescapeIdentifier(v.slice(1, -1))
3849
+ : unescapeIdentifier(v);
3850
+ },
3851
+ /**
3852
+ * @param {Node=} n node
3853
+ * @returns {string} hash / numeric type flag
3854
+ */
3855
+ typeFlag(n = _currentNode) {
3856
+ const i = _nodeIndex(n);
3857
+ if (_soaTypes[i] === T_HASH) {
3858
+ const input = _soaInput;
3859
+ const p = _soaStarts[i] + 1;
3860
+ return _ifThreeCodePointsWouldStartAnIdentSequence(
3861
+ input,
3862
+ p,
3863
+ input.charCodeAt(p),
3864
+ input.charCodeAt(p + 1),
3865
+ input.charCodeAt(p + 2)
3866
+ )
3867
+ ? "id"
3868
+ : "unrestricted";
3869
+ }
3870
+ const v = _soaValueOf(i);
3871
+ return _typeFlagOf(
3872
+ _soaTypes[i] === T_DIMENSION ? v.slice(0, _consumeANumber(v, 0)) : v
3873
+ );
3874
+ },
3875
+ /**
3876
+ * @param {Node=} n node
3877
+ * @returns {number} url content start offset
3878
+ */
3879
+ contentStart(n = _currentNode) {
3880
+ return _soaAux0[_nodeIndex(n)];
3881
+ },
3882
+ /**
3883
+ * @param {Node=} n node
3884
+ * @returns {number} url content end offset
3885
+ */
3886
+ contentEnd(n = _currentNode) {
3887
+ return _soaAux1[_nodeIndex(n)];
3888
+ },
3889
+ /**
3890
+ * @param {Node=} n node
3891
+ * @returns {string} rule / declaration / function name
3892
+ */
3893
+ name(n = _currentNode) {
3894
+ const i = _nodeIndex(n);
3895
+ return _soaTypes[i] === T_AT_RULE
3896
+ ? _soaInput.slice(_soaStarts[i] + 1, _soaAux0[i])
3897
+ : _soaInput.slice(_soaStarts[i], _soaAux0[i]);
3898
+ },
3899
+ /**
3900
+ * @param {Node=} n node
3901
+ * @returns {number} name start offset
3902
+ */
3903
+ nameStart(n = _currentNode) {
3904
+ return _soaStarts[_nodeIndex(n)];
3905
+ },
3906
+ /**
3907
+ * @param {Node=} n node
3908
+ * @returns {number} name end offset
3909
+ */
3910
+ nameEnd(n = _currentNode) {
3911
+ return _soaAux0[_nodeIndex(n)];
3912
+ },
3913
+ /**
3914
+ * @param {Node=} n node
3915
+ * @returns {string} unescaped name
3916
+ */
3917
+ unescapedName(n = _currentNode) {
3918
+ return unescapeIdentifier(A.name(n));
3919
+ },
3920
+ /**
3921
+ * @param {Node=} n node
3922
+ * @returns {ComponentValue[]} function / block children
3923
+ */
3924
+ children(n = _currentNode) {
3925
+ return /** @type {ComponentValue[]} */ (_materializeList(n));
3926
+ },
3927
+ /**
3928
+ * @param {Node=} n node
3929
+ * @returns {ComponentValue[]} rule prelude
3930
+ */
3931
+ prelude(n = _currentNode) {
3932
+ return /** @type {ComponentValue[]} */ (_materializeList(n));
3933
+ },
3934
+ /**
3935
+ * @param {Node=} n node
3936
+ * @returns {Declaration[] | null} block declarations
3937
+ */
3938
+ declarations(n = _currentNode) {
3939
+ return /** @type {Declaration[] | null} */ (
3940
+ _soaDeclarationLists[_nodeIndex(n)]
3941
+ );
3942
+ },
3943
+ /**
3944
+ * @param {Node=} n node
3945
+ * @returns {Rule[] | null} block child rules
3946
+ */
3947
+ childRules(n = _currentNode) {
3948
+ return /** @type {Rule[] | null} */ (_soaChildRuleLists[_nodeIndex(n)]);
3949
+ },
3950
+ /**
3951
+ * @param {Node=} n node
3952
+ * @returns {number} block start offset
3953
+ */
3954
+ blockStart(n = _currentNode) {
3955
+ return _soaAux1[_nodeIndex(n)];
3956
+ },
3957
+ /**
3958
+ * @param {Node=} n node
3959
+ * @returns {number} block end offset
3960
+ */
3961
+ blockEnd(n = _currentNode) {
3962
+ return _soaAux2[_nodeIndex(n)];
3963
+ },
3964
+ /**
3965
+ * @param {Node=} n node
3966
+ * @returns {boolean} `!important` flag
3967
+ */
3968
+ important(n = _currentNode) {
3969
+ return (_soaFlags[_nodeIndex(n)] & 1) !== 0;
3970
+ },
3971
+ /**
3972
+ * @param {Node=} n node
3973
+ * @returns {SimpleBlockToken} block opening token
3974
+ */
3975
+ blockToken(n = _currentNode) {
3976
+ return /** @type {SimpleBlockToken} */ (
3977
+ _soaInput[_soaStarts[_nodeIndex(n)]]
3978
+ );
3979
+ },
3980
+ // Writers — `CssParser` rewrites a rule's end / block-end when it folds an
3981
+ // inline ICSS `:import` / `:export` body into a single dependency. The
3982
+ // node stays explicit here: writes should never be implicit on position.
3983
+ /**
3984
+ * @param {Node} n node
3985
+ * @param {number} v new end offset
3986
+ */
3987
+ setEnd(n, v) {
3988
+ _soaEnds[_nodeIndex(n)] = v;
3989
+ },
3990
+ /**
3991
+ * @param {Node} n node
3992
+ * @param {number} v new block end offset
3993
+ */
3994
+ setBlockEnd(n, v) {
3995
+ _soaAux2[_nodeIndex(n)] = v;
3996
+ }
3997
+ };
3998
+
3999
+ // The two AST runtime classes — `Node` and its sole subclass `Token` (the
4000
+ // other node shapes are `@typedef`s over `Node`, exported as types only). Plus
4001
+ // the full CSS-Syntax-3 §5.3 `parseA*` entry-point surface, `consumeASimpleBlock`
4002
+ // (the one §5.4 algorithm exposed as a byte entry point for `CssParser`), the
4003
+ // `TokenStream` (so callers can pass a pre-built stream to any `parseA*`), and
4004
+ // the `escape` / `unescapeIdentifier` string utils.
4005
+ module.exports.A = A;
4006
+ module.exports.Node = Node;
4007
+ module.exports.NodeType = NodeType;
4008
+ module.exports.SourceProcessor = SourceProcessor;
4009
+ module.exports.TT_AT_KEYWORD = TT_AT_KEYWORD;
4010
+ module.exports.TT_BAD_STRING_TOKEN = TT_BAD_STRING_TOKEN;
4011
+ module.exports.TT_BAD_URL_TOKEN = TT_BAD_URL_TOKEN;
4012
+ module.exports.TT_CDC = TT_CDC;
4013
+ module.exports.TT_CDO = TT_CDO;
4014
+ module.exports.TT_COLON = TT_COLON;
4015
+ module.exports.TT_COMMA = TT_COMMA;
4016
+ module.exports.TT_COMMENT = TT_COMMENT;
4017
+ module.exports.TT_DELIM = TT_DELIM;
4018
+ module.exports.TT_DIMENSION = TT_DIMENSION;
4019
+ module.exports.TT_EOF = TT_EOF;
4020
+ module.exports.TT_FUNCTION = TT_FUNCTION;
4021
+ module.exports.TT_HASH = TT_HASH;
4022
+ module.exports.TT_IDENTIFIER = TT_IDENTIFIER;
4023
+ module.exports.TT_LEFT_CURLY_BRACKET = TT_LEFT_CURLY_BRACKET;
4024
+ module.exports.TT_LEFT_PARENTHESIS = TT_LEFT_PARENTHESIS;
4025
+ module.exports.TT_LEFT_SQUARE_BRACKET = TT_LEFT_SQUARE_BRACKET;
4026
+ module.exports.TT_NUMBER = TT_NUMBER;
4027
+ module.exports.TT_PERCENTAGE = TT_PERCENTAGE;
4028
+ module.exports.TT_RIGHT_CURLY_BRACKET = TT_RIGHT_CURLY_BRACKET;
4029
+ module.exports.TT_RIGHT_PARENTHESIS = TT_RIGHT_PARENTHESIS;
4030
+ module.exports.TT_RIGHT_SQUARE_BRACKET = TT_RIGHT_SQUARE_BRACKET;
4031
+ module.exports.TT_SEMICOLON = TT_SEMICOLON;
4032
+ module.exports.TT_STRING = TT_STRING;
4033
+ module.exports.TT_URL = TT_URL;
4034
+ module.exports.TT_WHITESPACE = TT_WHITESPACE;
4035
+ module.exports.Token = Token;
4036
+ module.exports.TokenStream = TokenStream;
4037
+ module.exports.buildSkipSet = buildSkipSet;
4038
+ module.exports.equalsLowerCase = equalsLowerCase;
4039
+ module.exports.escapeIdentifier = escapeIdentifier;
4040
+ module.exports.isDashedIdentifier = isDashedIdentifier;
4041
+ // CSS Syntax §4.2 "whitespace" (space / tab / newline / CR / FF) — the
4042
+ // tokenizer's whitespace class, exported under the spec's name.
4043
+ module.exports.isWhitespace = _isWhiteSpace;
4044
+ module.exports.normalizeUrl = normalizeUrl;
4045
+ module.exports.parseABlocksContents = parseABlocksContents;
4046
+ module.exports.parseACommaSeparatedListOfComponentValues =
4047
+ parseACommaSeparatedListOfComponentValues;
4048
+ module.exports.parseAComponentValue = parseAComponentValue;
4049
+ module.exports.parseADeclaration = parseADeclaration;
4050
+ module.exports.parseAListOfComponentValues = parseAListOfComponentValues;
4051
+ module.exports.parseARule = parseARule;
4052
+ module.exports.parseAStylesheet = parseAStylesheet;
4053
+ module.exports.parseAStylesheetsContents = parseAStylesheetsContents;
4054
+ module.exports.rangeEquals = rangeEquals;
4055
+ module.exports.rangeEqualsLowerCase = rangeEqualsLowerCase;
4056
+ module.exports.readToken = readToken;
4057
+ module.exports.toLowerCaseIfNeeded = toLowerCaseIfNeeded;
4058
+ module.exports.unescapeIdentifier = unescapeIdentifier;