what-compiler 0.13.11 → 0.15.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.
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/babel.d.ts +78 -2
- package/dist/babel/auto-selector.min.js +94 -0
- package/dist/babel/common.min.js +2053 -0
- package/dist/babel/dev-metadata.min.js +106 -0
- package/dist/babel/dom.min.js +1669 -0
- package/dist/babel/jsx-root.min.js +13 -0
- package/dist/babel/lists.min.js +492 -0
- package/dist/babel/nesting.min.js +328 -0
- package/dist/babel/reactivity.min.js +1218 -0
- package/dist/babel/server-actions.min.js +85 -0
- package/dist/babel/ssr.min.js +496 -0
- package/dist/babel/types.min.js +9 -0
- package/dist/babel-plugin.min.js +101 -1
- package/dist/file-router.min.js +368 -12
- package/dist/framework-files.min.js +62 -0
- package/dist/hot.min.js +315 -0
- package/dist/index.min.js +13 -414
- package/dist/release.min.js +78 -0
- package/dist/runtime.min.js +9 -1
- package/dist/tables/import-changes.min.js +272 -0
- package/dist/tables/markup-rules.min.js +213 -0
- package/dist/vite-plugin.min.js +432 -399
- package/file-router.d.ts +3 -1
- package/index.d.ts +1 -1
- package/package.json +11 -2
- package/runtime.d.ts +2 -1
- package/src/babel/auto-selector.js +248 -0
- package/src/babel/common.js +3800 -0
- package/src/babel/dev-metadata.js +167 -0
- package/src/babel/dom.js +3386 -0
- package/src/babel/jsx-root.js +27 -0
- package/src/babel/lists.js +704 -0
- package/src/babel/nesting.js +260 -0
- package/src/babel/reactivity.js +1998 -0
- package/src/babel/server-actions.js +144 -0
- package/src/babel/ssr.js +870 -0
- package/src/babel/types.js +10 -0
- package/src/babel-plugin.js +185 -3598
- package/src/file-router.js +58 -38
- package/src/framework-files.js +106 -0
- package/src/hot.js +523 -0
- package/src/release.js +127 -0
- package/src/runtime.js +7 -7
- package/src/tables/import-changes.js +157 -0
- package/src/tables/markup-rules.js +388 -0
- package/src/vite-plugin.js +460 -175
- package/vite.d.ts +47 -3
- package/src/error-overlay.js +0 -428
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Generated from packages/core/src/import-changes.js by scripts/generate-import-changes.mjs: edit that file, then run `npm run docs:imports`.
|
|
2
|
+
// What Framework - Import changes
|
|
3
|
+
//
|
|
4
|
+
// Every name the root entry (`what-framework`, and `what-core` alike) stopped
|
|
5
|
+
// exporting in 0.15.0, and where it went, the names it exports with React's
|
|
6
|
+
// meaning instead of What's, then the internal interfaces new in 0.15 that the
|
|
7
|
+
// root entry never exported. This table is the one list: the docs
|
|
8
|
+
// (docs/UPGRADING.md, generated by scripts/generate-import-changes.mjs),
|
|
9
|
+
// what-compiler's Vite plugin, eslint-plugin-what's no-moved-imports rule,
|
|
10
|
+
// validateImports() and tools reading what-core/internal all take it from
|
|
11
|
+
// here, so agents and people see the same answer.
|
|
12
|
+
//
|
|
13
|
+
// A record is { name, to, as?, note, answer, onRoot?, neverOnRoot? }:
|
|
14
|
+
// name the name as it is imported
|
|
15
|
+
// to the module that exports it now, or null when it is gone
|
|
16
|
+
// as its new name, when it was renamed
|
|
17
|
+
// note why, ending with what to write instead
|
|
18
|
+
// answer what an import of the name from the root entry is told: the
|
|
19
|
+
// note, then the import to write (built from the fields above)
|
|
20
|
+
// onRoot true for a name the root entry exports again, with React's
|
|
21
|
+
// meaning: the record says where What's export of that name
|
|
22
|
+
// went, and only an import of its new name (`as`) from the root
|
|
23
|
+
// entry is answered
|
|
24
|
+
// neverOnRoot true for an internal interface new in 0.15 that the root
|
|
25
|
+
// entry never exported, listed so an import of it is answered
|
|
26
|
+
// A what-framework/<kit> path has a what-core/<kit> twin with the same exports.
|
|
27
|
+
// A row with `names` stands for one record per name.
|
|
28
|
+
|
|
29
|
+
export const IMPORT_CHANGES = /* @__PURE__ */ table([
|
|
30
|
+
// Names that meant something else in React.
|
|
31
|
+
{ name: 'useTransition', to: 'what-framework/motion', as: 'useTween', onRoot: true, note: 'The animation helper formerly named useTransition is useTween. useTransition and startTransition on the root entry are React\'s transition API: const [isPending, start] = useTransition(), where isPending is an accessor, read as isPending().' },
|
|
32
|
+
{ name: 'transition', to: 'what-framework/motion', as: 'transitionClass', note: 'The enter/leave class helper is transitionClass(name, active).' },
|
|
33
|
+
{ name: 'on', to: 'what-framework/render', note: 'on(el, event, handler) is a fine-grained rendering primitive; in components write onClick={...} in JSX.' },
|
|
34
|
+
|
|
35
|
+
// Deleted: duplicates of names that stay.
|
|
36
|
+
{ name: 'each', to: null, note: 'Render lists with .map() and a key prop, or <For>.' },
|
|
37
|
+
{ name: 'atom', to: null, note: 'Use signal(initial).' },
|
|
38
|
+
{ name: 'storeComputed', to: null, note: 'Use derived(fn) in the store definition.' },
|
|
39
|
+
{ name: 'onRootCleanup', to: null, note: 'Use onCleanup(fn): it attaches to the component being rendered, or else to the reactive owner (createRoot, a list row).' },
|
|
40
|
+
{ name: 'signalMemo', to: null, note: 'Use computed(fn), which recomputes only when read and skips readers when the value is unchanged.' },
|
|
41
|
+
{ name: 'getLoaderData', to: null, note: 'Use useLoaderData(), which reads the same payload on the client and the render context on the server.' },
|
|
42
|
+
{ name: '_template', to: null, note: 'Use template() from what-framework/render; compiled output imports _$template from there.' },
|
|
43
|
+
{ name: 'getResource', to: null, note: 'Use createResource(fetcher, { key }), which reads the hydrated value for its key.' },
|
|
44
|
+
|
|
45
|
+
// One island component: the server's. What the compiler lowers client:*
|
|
46
|
+
// directives to is a compiler target.
|
|
47
|
+
{ name: 'Island', to: 'what-framework/server', note: 'The island component is what-framework/server\'s Island({ name, props, mode }), which the client hydrates through the island registry (island(), hydrateIslands()). A JSX client:* directive (<Counter client:idle />) compiles to _$Island from what-framework/render, an island that hydrates itself; code written with h() calls that the same way: h(_$Island, { component: Counter, mode: \'idle\' }).' },
|
|
48
|
+
|
|
49
|
+
// The error collector: the diagnostics channel replaced it.
|
|
50
|
+
{ name: 'collectError', to: null, note: 'Nothing collects errors by hand: the runtime reports its coded diagnostics on one channel (getDiagnostics(), subscribeDiagnostics()), and what-devtools records thrown errors (getErrors()). Both are development-only: a production build reports nothing.' },
|
|
51
|
+
{ name: 'getCollectedErrors', to: null, note: 'Use getDiagnostics({ since }) for the coded diagnostics (since is the seq the previous call returned, not a timestamp), or getErrors() from what-devtools for thrown errors; both are development-only.' },
|
|
52
|
+
{ name: 'clearCollectedErrors', to: null, note: 'Use clearDiagnostics().' },
|
|
53
|
+
|
|
54
|
+
// The agent context (window.__WHAT_AGENT__): what-devtools and
|
|
55
|
+
// what-devtools-mcp replaced it.
|
|
56
|
+
{ name: 'installAgentContext', to: null, note: 'Use installDevTools() from what-devtools, which what-devtools-mcp\'s Vite plugin calls in development: it exposes the app\'s state as window.__WHAT_DEVTOOLS__, which the what_* MCP tools read.' },
|
|
57
|
+
{ to: null, names: ['registerComponent', 'unregisterComponent'], note: 'Delete the call: with what-devtools installed, every component is registered as it mounts and dropped as it unmounts.' },
|
|
58
|
+
{ to: null, names: ['registerSignal', 'unregisterSignal'], note: 'Delete the call: with what-devtools installed, every signal is registered as it is created, and nothing has to unregister it.' },
|
|
59
|
+
{ name: 'getMountedComponents', to: null, note: 'Use getSnapshot().components from what-devtools (development only), or the what_components MCP tool.' },
|
|
60
|
+
{ name: 'getActiveSignals', to: null, note: 'Use getSnapshot().signals from what-devtools (development only), or the what_signals MCP tool.' },
|
|
61
|
+
{ name: 'getHealth', to: null, note: 'Use the what_diagnose MCP tool (diagnostic codes, errors, hot effects, unread signals), or getDiagnostics() for the coded diagnostics alone.' },
|
|
62
|
+
|
|
63
|
+
// Domain kits on subpaths.
|
|
64
|
+
{ to: 'what-framework/a11y', names: [
|
|
65
|
+
'useFocus', 'useFocusRestore', 'useFocusTrap', 'FocusTrap', 'announce', 'announceAssertive',
|
|
66
|
+
'SkipLink', 'useAriaExpanded', 'useAriaSelected', 'useAriaChecked', 'useRovingTabIndex',
|
|
67
|
+
'VisuallyHidden', 'LiveRegion', 'useIds', 'useDescribedBy', 'useLabelledBy', 'Keys', 'onKey', 'onKeys',
|
|
68
|
+
], note: 'Accessibility helpers live in what-framework/a11y.' },
|
|
69
|
+
{ to: 'what-framework/ui', names: [
|
|
70
|
+
'Skeleton', 'SkeletonText', 'SkeletonAvatar', 'SkeletonCard', 'SkeletonTable', 'IslandSkeleton',
|
|
71
|
+
'useSkeleton', 'Placeholder', 'LoadingDots', 'Spinner',
|
|
72
|
+
], note: 'Skeletons and loading placeholders live in what-framework/ui.' },
|
|
73
|
+
{ to: 'what-framework/motion', names: [
|
|
74
|
+
'spring', 'tween', 'easings', 'useGesture', 'useAnimatedValue', 'createTransitionClasses', 'cssTransition',
|
|
75
|
+
], note: 'Animation lives in what-framework/motion.' },
|
|
76
|
+
{ to: 'what-framework/dom', names: [
|
|
77
|
+
'scheduleRead', 'scheduleWrite', 'flushScheduler', 'measure', 'mutate', 'useScheduledEffect',
|
|
78
|
+
'nextFrame', 'raf', 'onResize', 'onIntersect', 'smoothScrollTo',
|
|
79
|
+
], note: 'The DOM read/write scheduler lives in what-framework/dom.' },
|
|
80
|
+
{ to: 'what-framework/dom', names: [
|
|
81
|
+
'cls', 'style', 'debounce', 'throttle', 'useMediaQuery', 'useLocalStorage', 'useClickOutside', 'clearHead',
|
|
82
|
+
], note: 'DOM utilities live in what-framework/dom.' },
|
|
83
|
+
{ to: 'what-framework/form', names: [
|
|
84
|
+
'useForm', 'useField', 'rules', 'simpleResolver', 'zodResolver', 'yupResolver',
|
|
85
|
+
'Input', 'Textarea', 'Select', 'Checkbox', 'Radio', 'ErrorMessage',
|
|
86
|
+
], note: 'Forms live in what-framework/form.' },
|
|
87
|
+
{ to: 'what-framework/data', names: [
|
|
88
|
+
'useFetch', 'useSWR', 'useQuery', 'useInfiniteQuery', 'invalidateQueries', 'prefetchQuery',
|
|
89
|
+
'setQueryData', 'getQueryData', 'clearCache',
|
|
90
|
+
], note: 'The query, SWR and fetch hooks live in what-framework/data.' },
|
|
91
|
+
|
|
92
|
+
// Fine-grained rendering primitives: the compiler's runtime, for code
|
|
93
|
+
// written without JSX.
|
|
94
|
+
{ to: 'what-framework/render', names: [
|
|
95
|
+
'template', 'svgTemplate', 'insert', 'mapArray', 'spread', 'setProp', 'delegateEvents',
|
|
96
|
+
'classList', 'isHydrating', '_$template', '_$createComponent',
|
|
97
|
+
], note: 'Fine-grained rendering primitives live in what-framework/render, beside the rest of the compiled-JSX runtime.' },
|
|
98
|
+
{ name: '_setTextInsertHook', to: 'what-core/render', note: 'Text engines register their insert hook through what-core/render.' },
|
|
99
|
+
|
|
100
|
+
// The contract between what-core and its sibling packages and tools.
|
|
101
|
+
{ to: 'what-core/internal', names: [
|
|
102
|
+
'__setDevToolsHooks', '__drainPreinstallBuffer', '__getCacheSnapshot', 'configureGuardrails', 'getGuardrailConfig',
|
|
103
|
+
'validateImports', 'ERROR_CODES', 'createWhatError', 'classifyError',
|
|
104
|
+
], note: 'Devtools hooks, guardrails and the error catalogue are tool interfaces in what-core/internal.' },
|
|
105
|
+
{ name: 'checkComponentName', to: null, note: 'Removed: a function that reaches the runtime is already being called as a component, so its name cannot reveal the lowercase JSX tag (rendered as an unknown element) the check was meant to catch. Name components in PascalCase.' },
|
|
106
|
+
{ name: 'installSignalReadGuardrail', to: null, note: 'Nothing to install: in development every signal and computed reports ERR_MISSING_SIGNAL_READ when it is converted to a string or a number, with or without what-devtools.' },
|
|
107
|
+
{ to: 'what-core/internal', names: [
|
|
108
|
+
'getServerContext', 'setServerContext', 'runWithServerContext', '__installServerContextStorage',
|
|
109
|
+
'beginHeadCollection', 'endHeadCollection', '_isAriaAttr', '_beginComponentSSR', '_endComponentSSR',
|
|
110
|
+
'_mapArrayToArray', '__readHydrationData', '__resetHydrationData',
|
|
111
|
+
], note: 'Server-rendering internals are what-server\'s interface in what-core/internal; apps use getResponse() and useLoaderData().' },
|
|
112
|
+
|
|
113
|
+
// New in 0.15, never on the root entry.
|
|
114
|
+
{ to: 'what-core/internal', neverOnRoot: true, names: [
|
|
115
|
+
'__depsOf', '__subsOf', '__currentEffect', '__ownerOf', '__ownerPath', 'reportDiagnostic', '_thrownMessage', 'IMPORT_CHANGES', 'SUBPATH_ONLY',
|
|
116
|
+
], note: 'Devtools hooks, guardrails and the error catalogue are tool interfaces in what-core/internal.' },
|
|
117
|
+
{ to: 'what-core/internal', neverOnRoot: true, names: [
|
|
118
|
+
'_escapeHtml', '_runInComponentSSR', '_assignOwnerPath', '_ownerCounter', '_currentOwnerPath', '_actionStateKey', '_actionKeySalt', '_currentRowPath', '_enterRow', '_installRowKeys', '_leaveRow', '_renderSalt', '_tracksRows', '__flushOutsideServerContext', '__outsideServerContext', '__markServerProcess',
|
|
119
|
+
'_rowKeyDigest', '_engine', '_runComponentAsync', '_runComponentSync', '_symbolChild', '_loadedQueries',
|
|
120
|
+
], note: 'Server-rendering internals are what-server\'s interface in what-core/internal; apps use getResponse() and useLoaderData().' },
|
|
121
|
+
{ to: 'what-core/internal', neverOnRoot: true, names: [
|
|
122
|
+
'__invalidateFromDevtools', '_tagQueries', '_formStatus', '_formStatusContext', '_resetForm', '_formMember', '_devAction', '__DEV__', '_urgent', '_currentTransition', '_onCommit', '_pathLoaded',
|
|
123
|
+
'_contextOf', '_provide', '_isServerProcess', '_devNewContent', '_devDropped', '_hotKeep',
|
|
124
|
+
], note: 'The query cache\'s devtools and router hooks, the status <Form> provides and its reset, the engine hooks a navigation uses and the development flag are what-devtools\', what-router\'s and what-server\'s interface in what-core/internal; apps use what-framework/data, useFormStatus(), <Form> and useTransition().' },
|
|
125
|
+
{ name: 'isVNode', to: 'what-core/internal', neverOnRoot: true, note: 'Whether a value is a vnode, by the brand only what-core\'s producers (h(), the JSX runtime, the boundaries) give: for libraries that make or inspect elements, such as what-react. Apps make elements with h() or JSX.' },
|
|
126
|
+
{ name: '_signalKeyed', to: 'what-core/internal', neverOnRoot: true, note: 'A vnode whose key is a signal, as the reactive child that builds it again when the key\'s value changes: what-server renders it with it. Apps write the key (`h(Editor, { key: id })`).' },
|
|
127
|
+
{ to: 'what-core/internal', neverOnRoot: true, names: ['_claimRegion', '_afterWalk', '_devHoldsState'], note: 'Hooks for what-react\'s islands: an island takes the server\'s HTML for it whole and renders after the walk, and in development says it holds state (ERR_REBUILT_COMPONENT). Apps use hydrate().' },
|
|
128
|
+
{ to: 'what-core/internal', neverOnRoot: true, names: ['_errorSource', '_errorFromRecord'], note: 'Whether an error is what a read of a failed async value threw, and the Error a hydrating client makes of a server error record: what-server shows an <ErrorBoundary>\'s fallback for a value that failed as the client does. Apps use <ErrorBoundary>.' },
|
|
129
|
+
{ name: '_mountPortal', to: 'what-core/internal', neverOnRoot: true, note: 'The client renderer a portal\'s vnode carries: what-react\'s createPortal attaches it, so its portal also renders where it reaches a native What tree. Apps use <Portal>.' },
|
|
130
|
+
{ to: 'what-core/internal', neverOnRoot: true, names: ['_placedNamespace', '_svgOnlyTag'], note: 'What a React tree native code places is created in, for what-react\'s mixed mode: the namespace compiled JSX placed the native code in, and the tags only SVG has. Apps write the <svg>.' },
|
|
131
|
+
]);
|
|
132
|
+
|
|
133
|
+
// Names a subpath exports that the root entry never did, imported from the
|
|
134
|
+
// root entry by someone who guessed (`import { Router, Link } from
|
|
135
|
+
// 'what-framework'`, the way react-router's names are swapped for React's).
|
|
136
|
+
// They are not changes, so the upgrade guide does not list them; what-compiler's
|
|
137
|
+
// Vite plugin and eslint-plugin-what's no-moved-imports rule answer such an
|
|
138
|
+
// import with where the name lives, as they answer a moved one. Records have
|
|
139
|
+
// the shape of IMPORT_CHANGES' ({ name, to, note, answer }).
|
|
140
|
+
export const SUBPATH_ONLY = /* @__PURE__ */ table([
|
|
141
|
+
{ to: 'what-framework/router', names: [
|
|
142
|
+
'Router', 'FileRouter', 'Link', 'NavLink', 'Outlet', 'Redirect', 'navigate', 'redirect', 'route',
|
|
143
|
+
'useRoute', 'useParams', 'useSearch', 'useNavigate', 'defineRoutes', 'nestedRoutes', 'routeGroup',
|
|
144
|
+
'matchRoute', 'compilePath', 'parseQuery', 'isSafeUrl', 'setBase', 'guard', 'asyncGuard',
|
|
145
|
+
'beforeNavigate', 'afterNavigate', 'prefetch', 'prefetchRoute', 'enableScrollRestoration',
|
|
146
|
+
'setViewTransition', 'viewTransitionName',
|
|
147
|
+
], note: 'The router lives in what-framework/router.' },
|
|
148
|
+
]);
|
|
149
|
+
|
|
150
|
+
function table(rows) {
|
|
151
|
+
const records = rows.flatMap(({ names, ...row }) => (names ? names.map((name) => ({ name, ...row })) : [row]));
|
|
152
|
+
return Object.freeze(records.map((change) => Object.freeze({ ...change, answer: answerFor(change) })));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function answerFor({ name, to, as, note }) {
|
|
156
|
+
return to ? `${note} Import it with: import { ${as || name} } from '${to}'.` : `It was removed in 0.15. ${note}`;
|
|
157
|
+
}
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// Generated from packages/core/src/markup-rules.js by scripts/generate-import-changes.mjs: edit that file, then run `npm run docs:imports`.
|
|
2
|
+
// What Framework - the markup rules every renderer applies.
|
|
3
|
+
//
|
|
4
|
+
// One copy of each rule a value has to pass before it is written as HTML or
|
|
5
|
+
// set as an attribute: which tag and attribute names can be emitted verbatim,
|
|
6
|
+
// which attributes hold URLs and which URL schemes are refused, which props
|
|
7
|
+
// are never applied, how a prop name maps to its attribute, which attributes
|
|
8
|
+
// are enumerated, which elements are void, and how the text of <script> and
|
|
9
|
+
// <style> is kept from ending its element. what-compiler applies them to
|
|
10
|
+
// static markup when a module is compiled, what-server to every value it
|
|
11
|
+
// renders (compiled or h()), and the client to every attribute it sets, so a
|
|
12
|
+
// rule cannot hold on one path and lapse on another
|
|
13
|
+
// (packages/server/test/markup-rules-parity.test.js).
|
|
14
|
+
//
|
|
15
|
+
// Import-free, because what-compiler loads it into the build.
|
|
16
|
+
|
|
17
|
+
// Names are emitted verbatim (values are escaped, names cannot be), so anything
|
|
18
|
+
// outside these patterns could inject markup:
|
|
19
|
+
// h('div', { 'x" onload="alert(1)': '' }) -> <div x" onload="alert(1)>
|
|
20
|
+
// They allow data-*, aria-*, xlink:href, SVG names such as stroke-width and
|
|
21
|
+
// clipPath, custom elements, and the internal '__suspense' marker tag.
|
|
22
|
+
export const SAFE_ATTR_NAME = /^[a-zA-Z_:][a-zA-Z0-9:._-]*$/;
|
|
23
|
+
export const SAFE_TAG_NAME = /^[a-zA-Z_][a-zA-Z0-9._:-]*$/;
|
|
24
|
+
|
|
25
|
+
// Attributes whose value is a URL the browser follows, fetches or executes:
|
|
26
|
+
// xlink:href because SVG <a> executes it, ping and object[data] because they
|
|
27
|
+
// are fetched, and the SVG animation values (values, to, from, by), which
|
|
28
|
+
// <animate> or <set> with attributeName="href" sets as the href after the
|
|
29
|
+
// element's own attributes were checked. Compared in lower case, so the
|
|
30
|
+
// camelCase props (formAction, xlinkHref) are covered too.
|
|
31
|
+
export const URL_ATTRS = /* @__PURE__ */ new Set(['href', 'src', 'action', 'formaction', 'data', 'ping', 'xlink:href', 'xlinkhref', 'values', 'to', 'from', 'by']);
|
|
32
|
+
|
|
33
|
+
export function isUrlAttr(name) {
|
|
34
|
+
return URL_ATTRS.has(name.toLowerCase());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// A URL with a javascript:, vbscript: or data: scheme, after whitespace and
|
|
38
|
+
// control characters (a superset of what a browser ignores) are removed, or
|
|
39
|
+
// a `;`-separated list (an animation's `values`) with one among its items. A
|
|
40
|
+
// value with no usable toString (Object.create(null), { toString: null }, both
|
|
41
|
+
// reachable from JSON) is refused rather than allowed to throw mid-render.
|
|
42
|
+
export function isUnsafeUrl(value) {
|
|
43
|
+
if (value == null) return false;
|
|
44
|
+
let normalized;
|
|
45
|
+
try {
|
|
46
|
+
normalized = String(value).replace(/[\p{Cc}\s]+/gu, '').toLowerCase();
|
|
47
|
+
} catch {
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
return normalized.split(';').some((url) => url.startsWith('javascript:') || url.startsWith('vbscript:') || url.startsWith('data:'));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Props whose value the browser parses as markup, so escaping is no defense:
|
|
54
|
+
// srcdoc is entity-decoded and parsed as a whole document, and outerHTML
|
|
55
|
+
// replaces the element with its value parsed as markup. Refused outright, in
|
|
56
|
+
// any letter case, on every path. innerHTML and dangerouslySetInnerHTML are the
|
|
57
|
+
// other two; they are accepted only as { __html: trustedString }.
|
|
58
|
+
export const REFUSED_ATTRS = /* @__PURE__ */ new Set(['srcdoc', 'outerhtml']);
|
|
59
|
+
|
|
60
|
+
export function isRefusedAttr(name) {
|
|
61
|
+
return REFUSED_ATTRS.has(name.toLowerCase());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const INNER_HTML_PROPS = /* @__PURE__ */ new Set(['innerHTML', 'dangerouslySetInnerHTML']);
|
|
65
|
+
|
|
66
|
+
// Prop names whose HTML attribute is not just the prop name in another case.
|
|
67
|
+
// The client reaches the right attribute through the element's reflected DOM
|
|
68
|
+
// property (`label.htmlFor = x` writes `for`); markup has no properties, so
|
|
69
|
+
// static templates and server markup rename them: an unrenamed `htmlFor="x"`
|
|
70
|
+
// parses as a meaningless `htmlfor` attribute, and hydration never corrects a
|
|
71
|
+
// static attribute. Names that differ from their attribute only by case
|
|
72
|
+
// (tabIndex, readOnly) need no entry: the parser lowercases attribute names.
|
|
73
|
+
export const ATTRIBUTE_ALIASES = /* @__PURE__ */ new Map([
|
|
74
|
+
['className', 'class'],
|
|
75
|
+
['htmlFor', 'for'],
|
|
76
|
+
['httpEquiv', 'http-equiv'],
|
|
77
|
+
['acceptCharset', 'accept-charset'],
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
export function attributeName(prop) {
|
|
81
|
+
return ATTRIBUTE_ALIASES.get(prop) || prop;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The props whose value lives in markup under another attribute: a field's
|
|
85
|
+
// default is its content attribute (an <input>'s defaultValue is its `value`
|
|
86
|
+
// attribute, what a form reset restores), so markup writes it there. A client
|
|
87
|
+
// writes these props as properties, which reflect to the same attributes.
|
|
88
|
+
const DEFAULT_ATTRIBUTES = /* @__PURE__ */ new Map([
|
|
89
|
+
['defaultValue', 'value'],
|
|
90
|
+
['defaultChecked', 'checked'],
|
|
91
|
+
['defaultSelected', 'selected'],
|
|
92
|
+
]);
|
|
93
|
+
|
|
94
|
+
// SVG's XLink and XML attributes in React's spelling (`xlinkHref`, `xmlLang`):
|
|
95
|
+
// markup writes them under their qualified names (`xlink:href`, `xml:lang`),
|
|
96
|
+
// which the HTML parser places in their namespaces inside <svg>. Written as
|
|
97
|
+
// they are, they parse as `xlinkhref`, which no browser reads. `xmlns` and
|
|
98
|
+
// `xmlnsXlink` are declarations, not one of these.
|
|
99
|
+
const XML_PROP = /^(xlink|xml)([A-Z])/;
|
|
100
|
+
|
|
101
|
+
/** The attribute `prop` is written as in markup (server HTML, a compiled template). */
|
|
102
|
+
export function markupName(prop) {
|
|
103
|
+
return DEFAULT_ATTRIBUTES.get(prop) || attributeName(prop).replace(XML_PROP, (_, prefix, first) => prefix + ':' + first.toLowerCase());
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// --- Form fields ---
|
|
107
|
+
//
|
|
108
|
+
// The props of a form field that hold its state: `value` (an <input> whose
|
|
109
|
+
// value is its own, a <textarea>, a <select>) and `checked` control what it
|
|
110
|
+
// shows; `defaultValue` and `defaultChecked` are its default, what a form
|
|
111
|
+
// reset restores. A server shows the value (else the default) in the one
|
|
112
|
+
// place markup has for both; a client writes the value as a property and the
|
|
113
|
+
// default as the attribute (what-core's dom.js, what-server's html.js).
|
|
114
|
+
export const FIELD_PROPS = /* @__PURE__ */ new Set(['value', 'defaultValue', 'checked', 'defaultChecked']);
|
|
115
|
+
export const FIELD_TAGS = /* @__PURE__ */ new Set(['input', 'textarea', 'select']);
|
|
116
|
+
|
|
117
|
+
// <input> types whose `value` is the attribute it submits or shows on a
|
|
118
|
+
// button, not a value the user edits: for them `value` is an attribute.
|
|
119
|
+
export const ATTRIBUTE_VALUE_TYPES = /* @__PURE__ */ new Set(['checkbox', 'radio', 'hidden', 'submit', 'reset', 'button', 'image']);
|
|
120
|
+
|
|
121
|
+
/** A string with ASCII whitespace stripped from both ends and collapsed to single spaces. */
|
|
122
|
+
export function stripAndCollapse(text) {
|
|
123
|
+
return text.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '').replace(/[\t\n\f\r ]+/g, ' ');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The options a <select> value selects, as one boolean per option value in
|
|
128
|
+
* `values`: an array selects every option whose value it holds, any other
|
|
129
|
+
* value the first option with its string, a value no option has none. The
|
|
130
|
+
* client writes it (`select.value =` picks the first match, in a multiple
|
|
131
|
+
* select too) and a server marks it.
|
|
132
|
+
*/
|
|
133
|
+
export function selectedOptions(values, value) {
|
|
134
|
+
if (Array.isArray(value)) {
|
|
135
|
+
const wanted = value.map(String);
|
|
136
|
+
return values.map((v) => wanted.includes(v));
|
|
137
|
+
}
|
|
138
|
+
const at = values.indexOf(String(value));
|
|
139
|
+
return values.map((_, i) => i === at);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ARIA attributes and `role` take enumerated string values, never HTML boolean
|
|
143
|
+
// syntax: an absent aria-expanded means "unsupported" and aria-expanded="false"
|
|
144
|
+
// means "collapsed". data-* attributes are strings too, so `[data-open="false"]`
|
|
145
|
+
// keeps matching. HTML's own "true"/"false" attributes are enumerated as well:
|
|
146
|
+
// draggable="" is the auto state (a <div> is not draggable), and an absent
|
|
147
|
+
// spellcheck or contenteditable inherits from the parent, so `false` has to be
|
|
148
|
+
// written out. Everything else follows HTML boolean semantics: true writes the
|
|
149
|
+
// bare name, false omits it.
|
|
150
|
+
export function isAriaAttr(name) {
|
|
151
|
+
return name === 'role' || name.startsWith('aria-');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function isEnumeratedAttr(name) {
|
|
155
|
+
return isAriaAttr(name) || name.startsWith('data-') || /^(draggable|spellcheck|contenteditable)$/i.test(name);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export const VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
159
|
+
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
|
|
160
|
+
'link', 'meta', 'param', 'source', 'track', 'wbr',
|
|
161
|
+
]);
|
|
162
|
+
|
|
163
|
+
// --- Namespaces ---
|
|
164
|
+
//
|
|
165
|
+
// The parser builds <svg> and <math> content in the SVG and MathML namespaces,
|
|
166
|
+
// except where it switches back to HTML (its integration points): the
|
|
167
|
+
// children of SVG <foreignObject>, <desc> and <title>; of the MathML token
|
|
168
|
+
// elements <mi>, <mo>, <mn>, <ms> and <mtext>, apart from <mglyph> and
|
|
169
|
+
// <malignmark>, which stay MathML; and of MathML <annotation-xml> whose
|
|
170
|
+
// encoding is text/html or application/xhtml+xml.
|
|
171
|
+
export const SVG_HTML_INTEGRATION_POINTS = /* @__PURE__ */ new Set(['foreignObject', 'desc', 'title']);
|
|
172
|
+
export const MATHML_TEXT_INTEGRATION_POINTS = /* @__PURE__ */ new Set(['mi', 'mo', 'mn', 'ms', 'mtext']);
|
|
173
|
+
export const MATHML_IN_TEXT_POINTS = /* @__PURE__ */ new Set(['mglyph', 'malignmark']);
|
|
174
|
+
export const HTML_ENCODINGS = /* @__PURE__ */ new Set(['text/html', 'application/xhtml+xml']);
|
|
175
|
+
|
|
176
|
+
// The namespace the children of `tag` are parsed in, given the namespace `tag`
|
|
177
|
+
// itself is in: null for HTML, 'svg', 'math', or 'foreign' for SVG or MathML
|
|
178
|
+
// content whose exact namespace a renderer does not know, which never switches
|
|
179
|
+
// back to HTML. `encoding` is the element's encoding attribute (it decides
|
|
180
|
+
// <annotation-xml>).
|
|
181
|
+
export function childNamespace(ns, tag, encoding) {
|
|
182
|
+
if (ns === null) {
|
|
183
|
+
if (tag === 'svg') return 'svg';
|
|
184
|
+
return tag === 'math' || MATHML_IN_TEXT_POINTS.has(tag) ? 'math' : null;
|
|
185
|
+
}
|
|
186
|
+
if (ns === 'svg') return SVG_HTML_INTEGRATION_POINTS.has(tag) ? null : 'svg';
|
|
187
|
+
if (ns === 'math') {
|
|
188
|
+
if (MATHML_TEXT_INTEGRATION_POINTS.has(tag)) return null;
|
|
189
|
+
return tag === 'annotation-xml' && typeof encoding === 'string' && HTML_ENCODINGS.has(encoding.toLowerCase()) ? null : 'math';
|
|
190
|
+
}
|
|
191
|
+
return ns;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Elements whose content the HTML parser reads as raw text: nothing in it is
|
|
195
|
+
// decoded, so HTML-escaping corrupts it (`a && b` is not JavaScript),
|
|
196
|
+
// and only the closing sequence ends it. Its text is written as it is, apart
|
|
197
|
+
// from the sequences encodeRawText replaces. In SVG or MathML they are
|
|
198
|
+
// ordinary elements whose content is parsed as markup, so there their text is
|
|
199
|
+
// escaped (rawTextContent).
|
|
200
|
+
export const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(['script', 'style']);
|
|
201
|
+
|
|
202
|
+
// Elements whose content the HTML parser reads as text that it decodes:
|
|
203
|
+
// <textarea> and <title> in HTML. Nothing in it is markup, a comment included,
|
|
204
|
+
// so a server writes their children as escaped text with no hydration
|
|
205
|
+
// markers, and the client hydrates that text as one text node.
|
|
206
|
+
export const TEXT_ONLY_ELEMENTS = /* @__PURE__ */ new Set(['textarea', 'title']);
|
|
207
|
+
|
|
208
|
+
// The HTML parser drops a newline that comes right after one of these start
|
|
209
|
+
// tags, so a server writes one there: the parser drops that one, and content
|
|
210
|
+
// that begins with a newline keeps its own.
|
|
211
|
+
export const LEADING_NEWLINE_ELEMENTS = /* @__PURE__ */ new Set(['pre', 'textarea', 'listing']);
|
|
212
|
+
|
|
213
|
+
// The sequences that could end a raw-text element or change how the parser
|
|
214
|
+
// reads it: `</` (which starts every closing tag, in any letter case) and, in
|
|
215
|
+
// a script, `<!--`, which can switch the parser into a state where the real
|
|
216
|
+
// closing tag no longer closes the element.
|
|
217
|
+
export function rawTextHazard(tag, text) {
|
|
218
|
+
return text.includes('</') || (tag === 'script' && text.includes('<!--'));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Raw text, encoded so it cannot end its element. `<\/` means `</` inside a
|
|
222
|
+
// CSS or JavaScript string and in JSON; `<!--` means `<!--` inside a
|
|
223
|
+
// JavaScript or JSON string. Text without either sequence is unchanged, so
|
|
224
|
+
// static text that passed rawTextHazard encodes to itself.
|
|
225
|
+
export function encodeRawText(tag, text) {
|
|
226
|
+
if (!rawTextHazard(tag, text)) return text;
|
|
227
|
+
const out = text.replace(/<\//g, '<\\/');
|
|
228
|
+
return tag === 'script' ? out.replace(/<!--/g, '\\u003C!--') : out;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// The content of a <script> or <style> whose text is `text`, written in
|
|
232
|
+
// namespace `ns`. In HTML it is raw text (encodeRawText); in SVG or MathML it
|
|
233
|
+
// is parsed as markup, so `&` and `<` are escaped, and nothing else, so text
|
|
234
|
+
// that holds neither is the same bytes in every namespace.
|
|
235
|
+
export function rawTextContent(tag, text, ns) {
|
|
236
|
+
if (ns === null) return encodeRawText(tag, text);
|
|
237
|
+
return text.replace(/&/g, '&').replace(/</g, '<');
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Text a compiler can write into a raw-text element as it is, whatever
|
|
241
|
+
// namespace the element ends up in: no `&` and no `<`.
|
|
242
|
+
export function isNamespaceNeutralText(text) {
|
|
243
|
+
return !/[&<]/.test(text);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// The five-character HTML escape every server renderer and what-compiler use
|
|
247
|
+
// for text and attribute values. A test() for any character that needs
|
|
248
|
+
// escaping, an early return for the common clean string (test() is cheaper
|
|
249
|
+
// than search(), which saves and restores the expression's lastIndex), then a
|
|
250
|
+
// search for the first one and one pass from there: the same output as five
|
|
251
|
+
// chained replace() calls without scanning the string five times.
|
|
252
|
+
const NEEDS_ESCAPE = /[&<>"']/;
|
|
253
|
+
|
|
254
|
+
export function escapeHtml(str) {
|
|
255
|
+
if (!NEEDS_ESCAPE.test(str)) return str;
|
|
256
|
+
const first = str.search(NEEDS_ESCAPE);
|
|
257
|
+
let out = '';
|
|
258
|
+
let last = 0;
|
|
259
|
+
for (let i = first; i < str.length; i++) {
|
|
260
|
+
let replacement;
|
|
261
|
+
switch (str.charCodeAt(i)) {
|
|
262
|
+
case 38: replacement = '&'; break;
|
|
263
|
+
case 60: replacement = '<'; break;
|
|
264
|
+
case 62: replacement = '>'; break;
|
|
265
|
+
case 34: replacement = '"'; break;
|
|
266
|
+
case 39: replacement = '''; break;
|
|
267
|
+
default: continue;
|
|
268
|
+
}
|
|
269
|
+
if (last < i) out += str.slice(last, i);
|
|
270
|
+
out += replacement;
|
|
271
|
+
last = i + 1;
|
|
272
|
+
}
|
|
273
|
+
return last < str.length ? out + str.slice(last) : out;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// A style object as CSS text, as what-server writes a style prop and
|
|
277
|
+
// what-framework/dom's style() returns it: camelCase properties in
|
|
278
|
+
// kebab-case, custom properties (--x) as they are. A property whose value is
|
|
279
|
+
// null, undefined, a boolean or empty is left out, as the client sets none
|
|
280
|
+
// for it (React leaves out the same values). A declaration the client's
|
|
281
|
+
// CSSOM would refuse (a name that is not a property or a custom property, a
|
|
282
|
+
// value that ends the declaration or opens a block) is left out, as the
|
|
283
|
+
// client leaves it out: the server must not write
|
|
284
|
+
// `color: red; background: url(//tracker)` from one value.
|
|
285
|
+
const CSS_PROPERTY = /^(?:--[\w-]+|-?[a-zA-Z][\w-]*)$/;
|
|
286
|
+
|
|
287
|
+
// Control characters other than CSS whitespace: tab, LF, FF, CR.
|
|
288
|
+
const isControl = (code) => (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0c && code !== 0x0d) || code === 0x7f;
|
|
289
|
+
|
|
290
|
+
// Whether `text` is a value in a conservative CSS grammar, which a CSS parser
|
|
291
|
+
// reads as one declaration's value whatever it does with it:
|
|
292
|
+
// - no control characters;
|
|
293
|
+
// - outside strings, no `\` (an escape makes the next character, a quote or
|
|
294
|
+
// a parenthesis, part of an identifier), no comment (`/*`, which can hide a
|
|
295
|
+
// quote or a parenthesis from a reader that knows no comments) and no braces;
|
|
296
|
+
// - strings close on their own line (`\` escapes the next character in them);
|
|
297
|
+
// - parentheses and brackets nest and match, and a `;` is allowed only inside
|
|
298
|
+
// them (`url(data:image/png;base64,…)`);
|
|
299
|
+
// - an unquoted `url(` holds one url token: a CSS parser reads it to the
|
|
300
|
+
// first `)` whatever it holds, and one with a quote, a `(` or inner
|
|
301
|
+
// whitespace is a bad url, which also ends at the first `)`, so the `;`
|
|
302
|
+
// after that `)` would end the declaration (`url(a(b);x:y)`).
|
|
303
|
+
// A value outside the grammar is dropped, even one a browser would accept
|
|
304
|
+
// (`red /* note */`): style objects never need one.
|
|
305
|
+
export function oneDeclaration(text) {
|
|
306
|
+
const open = [];
|
|
307
|
+
let quote = '';
|
|
308
|
+
for (let i = 0; i < text.length; i++) {
|
|
309
|
+
const c = text[i];
|
|
310
|
+
if (isControl(text.charCodeAt(i))) return false;
|
|
311
|
+
if (quote !== '') {
|
|
312
|
+
if (c === '\\') i++;
|
|
313
|
+
else if (c === quote) quote = '';
|
|
314
|
+
else if (c === '\n' || c === '\r' || c === '\f') return false;
|
|
315
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
316
|
+
else if (c === '(' && isUrlFunction(text, i)) {
|
|
317
|
+
const end = urlTokenEnd(text, i + 1);
|
|
318
|
+
if (end === -1) return false;
|
|
319
|
+
if (end > i) i = end;
|
|
320
|
+
else open.push(')');
|
|
321
|
+
} else if (c === '(' || c === '[') open.push(c === '(' ? ')' : ']');
|
|
322
|
+
else if (c === ')' || c === ']') {
|
|
323
|
+
if (open.pop() !== c) return false;
|
|
324
|
+
} else if (c === '\\' || c === '{' || c === '}' || (c === '/' && text[i + 1] === '*') || (c === ';' && open.length === 0)) return false;
|
|
325
|
+
}
|
|
326
|
+
return open.length === 0 && quote === '';
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Whether the `(` at `at` opens `url(`: the identifier before it is `url`, in
|
|
330
|
+
// any case.
|
|
331
|
+
function isUrlFunction(text, at) {
|
|
332
|
+
return at >= 3 && text.slice(at - 3, at).toLowerCase() === 'url' && (at === 3 || !/[\w\u0080-\uffff-]/.test(text[at - 4]));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Where the url token that starts at `from` (after `url(`) ends: the index of
|
|
336
|
+
// its `)`; `from - 1` when the argument is a string instead (a quote after
|
|
337
|
+
// any whitespace), read as one; -1 when it is a bad url or never closes.
|
|
338
|
+
function urlTokenEnd(text, from) {
|
|
339
|
+
let i = from;
|
|
340
|
+
while (i < text.length && /[ \t\n\r\f]/.test(text[i])) i++;
|
|
341
|
+
if (text[i] === '"' || text[i] === "'") return from - 1;
|
|
342
|
+
for (; i < text.length; i++) {
|
|
343
|
+
const c = text[i];
|
|
344
|
+
if (c === ')') return i;
|
|
345
|
+
if (c === '"' || c === "'" || c === '(' || c === '\\') return -1;
|
|
346
|
+
if (/[ \t\n\r\f]/.test(c)) {
|
|
347
|
+
while (i < text.length && /[ \t\n\r\f]/.test(text[i])) i++;
|
|
348
|
+
return text[i] === ')' ? i : -1;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return -1;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// A property name as it is written (kebab-case; a custom property as it is),
|
|
355
|
+
// or null for a name that is no property: decided once per name. Bounded,
|
|
356
|
+
// because a style object's keys can come from data.
|
|
357
|
+
export const _cssNames = new Map();
|
|
358
|
+
export const CSS_NAME_CACHE_SIZE = 1024;
|
|
359
|
+
|
|
360
|
+
function cssName(property) {
|
|
361
|
+
let name = _cssNames.get(property);
|
|
362
|
+
if (name === undefined) {
|
|
363
|
+
name = !CSS_PROPERTY.test(property) ? null
|
|
364
|
+
: property.startsWith('--') ? property : property.replace(/([A-Z])/g, '-$1').toLowerCase();
|
|
365
|
+
if (_cssNames.size < CSS_NAME_CACHE_SIZE) _cssNames.set(property, name);
|
|
366
|
+
}
|
|
367
|
+
return name;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Values that are one declaration's value by their characters alone: letters,
|
|
371
|
+
// digits, `_`, `#`, `%`, `.`, `,`, `-`, `+` and spaces, none of which
|
|
372
|
+
// oneDeclaration gives a meaning to. Every other value is read by it.
|
|
373
|
+
export const PLAIN_CSS_VALUE = /^[\w#%.,+ -]*$/;
|
|
374
|
+
|
|
375
|
+
export function styleText(style) {
|
|
376
|
+
let css = '';
|
|
377
|
+
const properties = Object.keys(style);
|
|
378
|
+
for (let i = 0; i < properties.length; i++) {
|
|
379
|
+
const property = properties[i];
|
|
380
|
+
const value = style[property];
|
|
381
|
+
if (value == null || value === '' || typeof value === 'boolean') continue;
|
|
382
|
+
const text = String(value);
|
|
383
|
+
const name = cssName(property);
|
|
384
|
+
if (name === null || !(PLAIN_CSS_VALUE.test(text) || oneDeclaration(text))) continue;
|
|
385
|
+
css += (css ? ';' : '') + name + ':' + text;
|
|
386
|
+
}
|
|
387
|
+
return css;
|
|
388
|
+
}
|