This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

16
node_modules/hast-util-to-jsx-runtime/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
export { toJsxRuntime } from "./lib/index.js";
export type Components = import('./lib/components.js').Components;
export type ExtraProps = import('./lib/components.js').ExtraProps;
export type CreateEvaluater = import('./lib/index.js').CreateEvaluater;
export type ElementAttributeNameCase = import('./lib/index.js').ElementAttributeNameCase;
export type EvaluateExpression = import('./lib/index.js').EvaluateExpression;
export type EvaluateProgram = import('./lib/index.js').EvaluateProgram;
export type Evaluater = import('./lib/index.js').Evaluater;
export type Fragment = import('./lib/index.js').Fragment;
export type Jsx = import('./lib/index.js').Jsx;
export type JsxDev = import('./lib/index.js').JsxDev;
export type Options = import('./lib/index.js').Options;
export type Props = import('./lib/index.js').Props;
export type Source = import('./lib/index.js').Source;
export type Space = import('./lib/index.js').Space;
export type StylePropertyNameCase = import('./lib/index.js').StylePropertyNameCase;

19
node_modules/hast-util-to-jsx-runtime/index.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/**
* @typedef {import('./lib/components.js').Components} Components
* @typedef {import('./lib/components.js').ExtraProps} ExtraProps
* @typedef {import('./lib/index.js').CreateEvaluater} CreateEvaluater
* @typedef {import('./lib/index.js').ElementAttributeNameCase} ElementAttributeNameCase
* @typedef {import('./lib/index.js').EvaluateExpression} EvaluateExpression
* @typedef {import('./lib/index.js').EvaluateProgram} EvaluateProgram
* @typedef {import('./lib/index.js').Evaluater} Evaluater
* @typedef {import('./lib/index.js').Fragment} Fragment
* @typedef {import('./lib/index.js').Jsx} Jsx
* @typedef {import('./lib/index.js').JsxDev} JsxDev
* @typedef {import('./lib/index.js').Options} Options
* @typedef {import('./lib/index.js').Props} Props
* @typedef {import('./lib/index.js').Source} Source
* @typedef {import('./lib/index.js').Space} Space
* @typedef {import('./lib/index.js').StylePropertyNameCase} StylePropertyNameCase
*/
export {toJsxRuntime} from './lib/index.js'

View File

@@ -0,0 +1,65 @@
import type {Element} from 'hast'
/**
* Basic functional component: given props, returns an element.
*
* @typeParam ComponentProps
* Props type.
* @param props
* Props.
* @returns
* Result.
*/
export type FunctionComponent<ComponentProps> = (
props: ComponentProps
) => JSX.Element | string | null | undefined
/**
* Class component: given props, returns an instance.
*
* @typeParam ComponentProps
* Props type.
* @param props
* Props.
* @returns
* Instance.
*/
export type ClassComponent<ComponentProps> = new (
props: ComponentProps
) => JSX.ElementClass
/**
* Function or class component.
*
* You can access props at `JSX.IntrinsicElements`.
* For example, to find props for `a`, use `JSX.IntrinsicElements['a']`.
*
* @typeParam ComponentProps
* Props type.
*/
export type Component<ComponentProps> =
| ClassComponent<ComponentProps>
| FunctionComponent<ComponentProps>
/**
* Extra fields we pass.
*/
export type ExtraProps = {node?: Element | undefined}
/**
* Possible components to use.
*
* Each key is a tag name typed in `JSX.IntrinsicElements`.
* Each value is either a different tag name, or a component accepting the
* corresponding props (and an optional `node` prop if `passNode` is on).
*
* You can access props at `JSX.IntrinsicElements`.
* For example, to find props for `a`, use `JSX.IntrinsicElements['a']`.
*/
// Note: this type has to be in `.ts` or `.d.ts`, otherwise TSC hardcodes
// react into the `.d.ts` file.
export type Components = {
[TagName in keyof JSX.IntrinsicElements]:
| Component<JSX.IntrinsicElements[TagName] & ExtraProps>
| keyof JSX.IntrinsicElements
}

View File

@@ -0,0 +1,2 @@
// TypeScript only.
export {}

341
node_modules/hast-util-to-jsx-runtime/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,341 @@
/**
* Transform a hast tree to preact, react, solid, svelte, vue, etc.,
* with an automatic JSX runtime.
*
* @param {Nodes} tree
* Tree to transform.
* @param {Options} options
* Configuration (required).
* @returns {JSX.Element}
* JSX element.
*/
export function toJsxRuntime(tree: Nodes, options: Options): JSX.Element;
export type Identifier = import('estree').Identifier;
export type Literal = import('estree').Literal;
export type MemberExpression = import('estree').MemberExpression;
export type Expression = import('estree').Expression;
export type Program = import('estree').Program;
export type Element = import('hast').Element;
export type Nodes = import('hast').Nodes;
export type Parents = import('hast').Parents;
export type Root = import('hast').Root;
export type Text = import('hast').Text;
export type MdxFlowExpression = import('mdast-util-mdx-expression').MdxFlowExpressionHast;
export type MdxTextExpression = import('mdast-util-mdx-expression').MdxTextExpressionHast;
export type MdxJsxFlowElement = import('mdast-util-mdx-jsx').MdxJsxFlowElementHast;
export type MdxJsxTextElement = import('mdast-util-mdx-jsx').MdxJsxTextElementHast;
export type MdxjsEsm = import('mdast-util-mdxjs-esm').MdxjsEsmHast;
export type Schema = import('property-information').Schema;
export type Position = import('unist').Position;
export type Components = import('./components.js').Components;
/**
* Child.
*/
export type Child = JSX.Element | string | null | undefined;
/**
* Create something in development or production.
*/
export type Create = (node: Nodes, type: unknown, props: Props, key: string | undefined) => JSX.Element;
/**
* Create an evaluator that turns ESTree ASTs from embedded MDX into values.
*/
export type CreateEvaluater = () => Evaluater;
/**
* Casing to use for attribute names.
*
* HTML casing is for example `class`, `stroke-linecap`, `xml:lang`.
* React casing is for example `className`, `strokeLinecap`, `xmlLang`.
*/
export type ElementAttributeNameCase = 'html' | 'react';
/**
* Turn an MDX expression into a value.
*/
export type EvaluateExpression = (expression: Expression) => unknown;
/**
* Turn an MDX program (export/import statements) into a value.
*/
export type EvaluateProgram = (expression: Program) => unknown;
/**
* Evaluator that turns ESTree ASTs from embedded MDX into values.
*/
export type Evaluater = {
/**
* Evaluate an expression.
*/
evaluateExpression: EvaluateExpression;
/**
* Evaluate a program.
*/
evaluateProgram: EvaluateProgram;
};
/**
* Property field.
*/
export type Field = [string, Value];
/**
* Represent the children, typically a symbol.
*/
export type Fragment = unknown;
/**
* Create a production element.
*/
export type Jsx = (type: unknown, props: Props, key?: string | undefined) => JSX.Element;
/**
* Create a development element.
*/
export type JsxDev = (type: unknown, props: Props, key: string | undefined, isStaticChildren: boolean, source: Source, self: undefined) => JSX.Element;
/**
* Properties and children.
*/
export type Props = {
[prop: string]: string | number | boolean | import("hast").Element | import("mdast-util-mdx-jsx").MdxJsxTextElementHast | import("mdast-util-mdx-jsx").MdxJsxFlowElementHast | JSX.Element | Style | Child[] | null | undefined;
children?: Array<Child> | Child;
node?: Element | MdxJsxFlowElement | MdxJsxTextElement | undefined;
};
/**
* Configuration.
*/
export type RegularFields = {
/**
* Components to use (optional).
*/
components?: Partial<Components> | null | undefined;
/**
* Create an evaluator that turns ESTree ASTs into values (optional).
*/
createEvaluater?: CreateEvaluater | null | undefined;
/**
* Specify casing to use for attribute names (default: `'react'`).
*/
elementAttributeNameCase?: ElementAttributeNameCase | null | undefined;
/**
* File path to the original source file (optional).
*
* Passed in source info to `jsxDEV` when using the automatic runtime with
* `development: true`.
*/
filePath?: string | null | undefined;
/**
* Ignore invalid CSS in `style` props (default: `false`);
* the default behavior is to throw an error.
*/
ignoreInvalidStyle?: boolean | null | undefined;
/**
* Generate keys to optimize frameworks that support them (default: `true`).
*
* > 👉 **Note**: Solid currently fails if keys are passed.
*/
passKeys?: boolean | null | undefined;
/**
* Pass the hast element node to components (default: `false`).
*/
passNode?: boolean | null | undefined;
/**
* Whether `tree` is in the `'html'` or `'svg'` space (default: `'html'`).
*
* When an `<svg>` element is found in the HTML space, this package already
* automatically switches to and from the SVG space when entering and exiting
* it.
*/
space?: Space | null | undefined;
/**
* Specify casing to use for property names in `style` objects (default:
* `'dom'`).
*/
stylePropertyNameCase?: StylePropertyNameCase | null | undefined;
/**
* Turn obsolete `align` props on `td` and `th` into CSS `style` props
* (default: `true`).
*/
tableCellAlignToStyle?: boolean | null | undefined;
};
/**
* Runtime fields when development is on.
*/
export type RuntimeDevelopment = {
/**
* Fragment.
*/
Fragment: Fragment;
/**
* Whether to use `jsxDEV` (when on) or `jsx` and `jsxs` (when off).
*/
development: true;
/**
* Dynamic JSX (optional).
*/
jsx?: Jsx | null | undefined;
/**
* Development JSX.
*/
jsxDEV: JsxDev;
/**
* Static JSX (optional).
*/
jsxs?: Jsx | null | undefined;
};
/**
* Runtime fields when development is off.
*/
export type RuntimeProduction = {
/**
* Fragment.
*/
Fragment: Fragment;
/**
* Whether to use `jsxDEV` (when on) or `jsx` and `jsxs` (when off) (optional).
*/
development?: false | null | undefined;
/**
* Dynamic JSX.
*/
jsx: Jsx;
/**
* Development JSX (optional).
*/
jsxDEV?: JsxDev | null | undefined;
/**
* Static JSX.
*/
jsxs: Jsx;
};
/**
* Runtime fields when development might be on or off.
*/
export type RuntimeUnknown = {
/**
* Fragment.
*/
Fragment: Fragment;
/**
* Whether to use `jsxDEV` (when on) or `jsx` and `jsxs` (when off).
*/
development: boolean;
/**
* Dynamic JSX (optional).
*/
jsx?: Jsx | null | undefined;
/**
* Development JSX (optional).
*/
jsxDEV?: JsxDev | null | undefined;
/**
* Static JSX (optional).
*/
jsxs?: Jsx | null | undefined;
};
/**
* Info about source.
*/
export type Source = {
/**
* Column where thing starts (0-indexed).
*/
columnNumber: number | undefined;
/**
* Name of source file.
*/
fileName: string | undefined;
/**
* Line where thing starts (1-indexed).
*/
lineNumber: number | undefined;
};
/**
* Namespace.
*
* > 👉 **Note**: hast is not XML.
* > It supports SVG as embedded in HTML.
* > It does not support the features available in XML.
* > Passing SVG might break but fragments of modern SVG should be fine.
* > Use `xast` if you need to support SVG as XML.
*/
export type Space = 'html' | 'svg';
/**
* Info passed around.
*/
export type State = {
/**
* Fragment symbol.
*/
Fragment: unknown;
/**
* Stack of parents.
*/
ancestors: Array<Parents>;
/**
* Components to swap.
*/
components: Partial<Components>;
/**
* Create something in development or production.
*/
create: Create;
/**
* Casing to use for attribute names.
*/
elementAttributeNameCase: ElementAttributeNameCase;
/**
* Evaluator that turns ESTree ASTs into values.
*/
evaluater: Evaluater | undefined;
/**
* File path.
*/
filePath: string | undefined;
/**
* Ignore invalid CSS in `style` props.
*/
ignoreInvalidStyle: boolean;
/**
* Generate keys to optimize frameworks that support them.
*/
passKeys: boolean;
/**
* Pass `node` to components.
*/
passNode: boolean;
/**
* Current schema.
*/
schema: Schema;
/**
* Casing to use for property names in `style` objects.
*/
stylePropertyNameCase: StylePropertyNameCase;
/**
* Turn obsolete `align` props on `td` and `th` into CSS `style` props.
*/
tableCellAlignToStyle: boolean;
};
/**
* Style map.
*/
export type Style = Record<string, string>;
/**
* Casing to use for property names in `style` objects.
*
* CSS casing is for example `background-color` and `-webkit-line-clamp`.
* DOM casing is for example `backgroundColor` and `WebkitLineClamp`.
*/
export type StylePropertyNameCase = 'css' | 'dom';
/**
* Primitive property value and `Style` map.
*/
export type Value = Style | boolean | number | string;
/**
* Configuration (development).
*/
export type Development = RuntimeDevelopment & RegularFields;
/**
* Configuration.
*/
export type Options = Development | Production | Unknown;
/**
* Configuration (production).
*/
export type Production = RegularFields & RuntimeProduction;
/**
* Configuration (production or development).
*/
export type Unknown = RegularFields & RuntimeUnknown;

1084
node_modules/hast-util-to-jsx-runtime/lib/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

22
node_modules/hast-util-to-jsx-runtime/license generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2023 Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,228 @@
# inline-style-parser
[![NPM](https://nodei.co/npm/inline-style-parser.png)](https://nodei.co/npm/inline-style-parser/)
[![NPM version](https://badgen.net/npm/v/inline-style-parser)](https://www.npmjs.com/package/inline-style-parser)
[![Bundlephobia minified + gzip](https://badgen.net/bundlephobia/minzip/inline-style-parser)](https://bundlephobia.com/package/inline-style-parser)
[![build](https://github.com/remarkablemark/inline-style-parser/actions/workflows/build.yml/badge.svg)](https://github.com/remarkablemark/inline-style-parser/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/remarkablemark/inline-style-parser/branch/master/graph/badge.svg?token=B8EEK5709W)](https://codecov.io/gh/remarkablemark/inline-style-parser)
[![NPM downloads](https://badgen.net/npm/dm/inline-style-parser)](https://www.npmjs.com/package/inline-style-parser)
An inline style parser copied from [`css/lib/parse/index.js`](https://github.com/reworkcss/css/blob/v2.2.4/lib/parse/index.js):
```
InlineStyleParser(string)
```
Example:
```js
var parse = require('inline-style-parser');
parse('color: #BADA55;');
```
Output:
```js
[ { type: 'declaration',
property: 'color',
value: '#BADA55',
position: Position { start: [Object], end: [Object], source: undefined } } ]
```
[JSFiddle](https://jsfiddle.net/remarkablemark/hcxbpwq8/) | [Replit](https://replit.com/@remarkablemark/inline-style-parser)
See [usage](#usage) and [examples](https://github.com/remarkablemark/inline-style-parser/tree/master/examples).
## Installation
[NPM](https://www.npmjs.com/package/inline-style-parser):
```sh
npm install inline-style-parser --save
```
[Yarn](https://yarnpkg.com/package/inline-style-parser):
```sh
yarn add inline-style-parser
```
[CDN](https://unpkg.com/inline-style-parser/):
```html
<script src="https://unpkg.com/inline-style-parser@latest/dist/inline-style-parser.min.js"></script>
<script>
window.InlineStyleParser(/* string */);
</script>
```
## Usage
Import the module:
```js
// CommonJS
const parse = require('inline-style-parser');
// ES Modules
import parse from 'inline-style-parser';
```
Parse single declaration:
```js
parse('left: 0');
```
Output:
```js
[
{
type: 'declaration',
property: 'left',
value: '0',
position: {
start: { line: 1, column: 1 },
end: { line: 1, column: 8 },
source: undefined
}
}
]
```
Parse multiple declarations:
```js
parse('left: 0; right: 100px;');
```
Output:
```js
[
{
type: 'declaration',
property: 'left',
value: '0',
position: {
start: { line: 1, column: 1 },
end: { line: 1, column: 8 },
source: undefined
}
},
{
type: 'declaration',
property: 'right',
value: '100px',
position: {
start: { line: 1, column: 10 },
end: { line: 1, column: 22 },
source: undefined
}
}
]
```
Parse declaration with missing value:
```js
parse('top:');
```
Output:
```js
[
{
type: 'declaration',
property: 'top',
value: '',
position: {
start: { line: 1, column: 1 },
end: { line: 1, column: 5 },
source: undefined
}
}
]
```
Parse unknown declaration:
```js
parse('answer: 42;');
```
Output:
```js
[
{
type: 'declaration',
property: 'answer',
value: '42',
position: {
start: { line: 1, column: 1 },
end: { line: 1, column: 11 },
source: undefined
}
}
]
```
Invalid declarations:
```js
parse(''); // []
parse(); // throws TypeError
parse(1); // throws TypeError
parse('width'); // throws Error
parse('/*'); // throws Error
```
## Testing
Run tests:
```sh
npm test
```
Run tests in watch mode:
```sh
npm run test:watch
```
Run tests with coverage:
```sh
npm run test:coverage
```
Run tests in CI mode:
```sh
npm run test:ci
```
Lint files:
```sh
npm run lint
```
Fix lint errors:
```sh
npm run lint:fix
```
## Release
Release and publish are automated by [Release Please](https://github.com/googleapis/release-please).
## License
MIT. See [license](https://github.com/reworkcss/css/blob/v2.2.4/LICENSE) from original project.

View File

@@ -0,0 +1,274 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.InlineStyleParser = factory());
})(this, (function () { 'use strict';
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
// http://www.w3.org/TR/CSS21/grammar.html
// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
var NEWLINE_REGEX = /\n/g;
var WHITESPACE_REGEX = /^\s*/;
// declaration
var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/;
var COLON_REGEX = /^:\s*/;
var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/;
var SEMICOLON_REGEX = /^[;\s]*/;
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
var TRIM_REGEX = /^\s+|\s+$/g;
// strings
var NEWLINE = '\n';
var FORWARD_SLASH = '/';
var ASTERISK = '*';
var EMPTY_STRING = '';
// types
var TYPE_COMMENT = 'comment';
var TYPE_DECLARATION = 'declaration';
/**
* @param {String} style
* @param {Object} [options]
* @return {Object[]}
* @throws {TypeError}
* @throws {Error}
*/
var inlineStyleParser = function (style, options) {
if (typeof style !== 'string') {
throw new TypeError('First argument must be a string');
}
if (!style) return [];
options = options || {};
/**
* Positional.
*/
var lineno = 1;
var column = 1;
/**
* Update lineno and column based on `str`.
*
* @param {String} str
*/
function updatePosition(str) {
var lines = str.match(NEWLINE_REGEX);
if (lines) lineno += lines.length;
var i = str.lastIndexOf(NEWLINE);
column = ~i ? str.length - i : column + str.length;
}
/**
* Mark position and patch `node.position`.
*
* @return {Function}
*/
function position() {
var start = { line: lineno, column: column };
return function (node) {
node.position = new Position(start);
whitespace();
return node;
};
}
/**
* Store position information for a node.
*
* @constructor
* @property {Object} start
* @property {Object} end
* @property {undefined|String} source
*/
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
/**
* Non-enumerable source string.
*/
Position.prototype.content = style;
/**
* Error `msg`.
*
* @param {String} msg
* @throws {Error}
*/
function error(msg) {
var err = new Error(
options.source + ':' + lineno + ':' + column + ': ' + msg
);
err.reason = msg;
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = style;
if (options.silent) ; else {
throw err;
}
}
/**
* Match `re` and return captures.
*
* @param {RegExp} re
* @return {undefined|Array}
*/
function match(re) {
var m = re.exec(style);
if (!m) return;
var str = m[0];
updatePosition(str);
style = style.slice(str.length);
return m;
}
/**
* Parse whitespace.
*/
function whitespace() {
match(WHITESPACE_REGEX);
}
/**
* Parse comments.
*
* @param {Object[]} [rules]
* @return {Object[]}
*/
function comments(rules) {
var c;
rules = rules || [];
while ((c = comment())) {
if (c !== false) {
rules.push(c);
}
}
return rules;
}
/**
* Parse comment.
*
* @return {Object}
* @throws {Error}
*/
function comment() {
var pos = position();
if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;
var i = 2;
while (
EMPTY_STRING != style.charAt(i) &&
(ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))
) {
++i;
}
i += 2;
if (EMPTY_STRING === style.charAt(i - 1)) {
return error('End of comment missing');
}
var str = style.slice(2, i - 2);
column += 2;
updatePosition(str);
style = style.slice(i);
column += 2;
return pos({
type: TYPE_COMMENT,
comment: str
});
}
/**
* Parse declaration.
*
* @return {Object}
* @throws {Error}
*/
function declaration() {
var pos = position();
// prop
var prop = match(PROPERTY_REGEX);
if (!prop) return;
comment();
// :
if (!match(COLON_REGEX)) return error("property missing ':'");
// val
var val = match(VALUE_REGEX);
var ret = pos({
type: TYPE_DECLARATION,
property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),
value: val
? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))
: EMPTY_STRING
});
// ;
match(SEMICOLON_REGEX);
return ret;
}
/**
* Parse declarations.
*
* @return {Object[]}
*/
function declarations() {
var decls = [];
comments(decls);
// declarations
var decl;
while ((decl = declaration())) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
return decls;
}
whitespace();
return declarations();
};
/**
* Trim `str`.
*
* @param {String} str
* @return {String}
*/
function trim(str) {
return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;
}
var index = /*@__PURE__*/getDefaultExportFromCjs(inlineStyleParser);
return index;
}));
//# sourceMappingURL=inline-style-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).InlineStyleParser=n()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,t=/^\s*/,o=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,u=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,f=/^\s+|\s+$/g,a="";function s(e){return e?e.replace(f,a):a}return e((function(e,f){if("string"!=typeof e)throw new TypeError("First argument must be a string");if(!e)return[];f=f||{};var l=1,p=1;function h(e){var n=e.match(r);n&&(l+=n.length);var t=e.lastIndexOf("\n");p=~t?e.length-t:p+e.length}function m(){var e={line:l,column:p};return function(n){return n.position=new d(e),y(),n}}function d(e){this.start=e,this.end={line:l,column:p},this.source=f.source}function v(n){var r=new Error(f.source+":"+l+":"+p+": "+n);if(r.reason=n,r.filename=f.source,r.line=l,r.column=p,r.source=e,!f.silent)throw r}function g(n){var r=n.exec(e);if(r){var t=r[0];return h(t),e=e.slice(t.length),r}}function y(){g(t)}function w(e){var n;for(e=e||[];n=A();)!1!==n&&e.push(n);return e}function A(){var n=m();if("/"==e.charAt(0)&&"*"==e.charAt(1)){for(var r=2;a!=e.charAt(r)&&("*"!=e.charAt(r)||"/"!=e.charAt(r+1));)++r;if(r+=2,a===e.charAt(r-1))return v("End of comment missing");var t=e.slice(2,r-2);return p+=2,h(t),e=e.slice(r),p+=2,n({type:"comment",comment:t})}}function b(){var e=m(),r=g(o);if(r){if(A(),!g(i))return v("property missing ':'");var t=g(u),f=e({type:"declaration",property:s(r[0].replace(n,a)),value:t?s(t[0].replace(n,a)):a});return g(c),f}}return d.prototype.content=e,y(),function(){var e,n=[];for(w(n);e=b();)!1!==e&&(n.push(e),w(n));return n}()}))}));
//# sourceMappingURL=inline-style-parser.min.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
interface Position {
start: {
line: number;
column: number;
};
end: {
line: number;
column: number;
};
source?: string;
}
export interface Declaration {
type: 'declaration';
property: string;
value: string;
position: Position;
}
export interface Comment {
type: 'comment';
comment: string;
position: Position;
}
interface Options {
source?: string;
silent?: boolean;
}
export default function InlineStyleParser(
style: string,
options?: Options
): (Declaration | Comment)[];

View File

@@ -0,0 +1,261 @@
// http://www.w3.org/TR/CSS21/grammar.html
// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
var NEWLINE_REGEX = /\n/g;
var WHITESPACE_REGEX = /^\s*/;
// declaration
var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/;
var COLON_REGEX = /^:\s*/;
var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/;
var SEMICOLON_REGEX = /^[;\s]*/;
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
var TRIM_REGEX = /^\s+|\s+$/g;
// strings
var NEWLINE = '\n';
var FORWARD_SLASH = '/';
var ASTERISK = '*';
var EMPTY_STRING = '';
// types
var TYPE_COMMENT = 'comment';
var TYPE_DECLARATION = 'declaration';
/**
* @param {String} style
* @param {Object} [options]
* @return {Object[]}
* @throws {TypeError}
* @throws {Error}
*/
module.exports = function (style, options) {
if (typeof style !== 'string') {
throw new TypeError('First argument must be a string');
}
if (!style) return [];
options = options || {};
/**
* Positional.
*/
var lineno = 1;
var column = 1;
/**
* Update lineno and column based on `str`.
*
* @param {String} str
*/
function updatePosition(str) {
var lines = str.match(NEWLINE_REGEX);
if (lines) lineno += lines.length;
var i = str.lastIndexOf(NEWLINE);
column = ~i ? str.length - i : column + str.length;
}
/**
* Mark position and patch `node.position`.
*
* @return {Function}
*/
function position() {
var start = { line: lineno, column: column };
return function (node) {
node.position = new Position(start);
whitespace();
return node;
};
}
/**
* Store position information for a node.
*
* @constructor
* @property {Object} start
* @property {Object} end
* @property {undefined|String} source
*/
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
/**
* Non-enumerable source string.
*/
Position.prototype.content = style;
var errorsList = [];
/**
* Error `msg`.
*
* @param {String} msg
* @throws {Error}
*/
function error(msg) {
var err = new Error(
options.source + ':' + lineno + ':' + column + ': ' + msg
);
err.reason = msg;
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = style;
if (options.silent) {
errorsList.push(err);
} else {
throw err;
}
}
/**
* Match `re` and return captures.
*
* @param {RegExp} re
* @return {undefined|Array}
*/
function match(re) {
var m = re.exec(style);
if (!m) return;
var str = m[0];
updatePosition(str);
style = style.slice(str.length);
return m;
}
/**
* Parse whitespace.
*/
function whitespace() {
match(WHITESPACE_REGEX);
}
/**
* Parse comments.
*
* @param {Object[]} [rules]
* @return {Object[]}
*/
function comments(rules) {
var c;
rules = rules || [];
while ((c = comment())) {
if (c !== false) {
rules.push(c);
}
}
return rules;
}
/**
* Parse comment.
*
* @return {Object}
* @throws {Error}
*/
function comment() {
var pos = position();
if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;
var i = 2;
while (
EMPTY_STRING != style.charAt(i) &&
(ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))
) {
++i;
}
i += 2;
if (EMPTY_STRING === style.charAt(i - 1)) {
return error('End of comment missing');
}
var str = style.slice(2, i - 2);
column += 2;
updatePosition(str);
style = style.slice(i);
column += 2;
return pos({
type: TYPE_COMMENT,
comment: str
});
}
/**
* Parse declaration.
*
* @return {Object}
* @throws {Error}
*/
function declaration() {
var pos = position();
// prop
var prop = match(PROPERTY_REGEX);
if (!prop) return;
comment();
// :
if (!match(COLON_REGEX)) return error("property missing ':'");
// val
var val = match(VALUE_REGEX);
var ret = pos({
type: TYPE_DECLARATION,
property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),
value: val
? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))
: EMPTY_STRING
});
// ;
match(SEMICOLON_REGEX);
return ret;
}
/**
* Parse declarations.
*
* @return {Object[]}
*/
function declarations() {
var decls = [];
comments(decls);
// declarations
var decl;
while ((decl = declaration())) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
return decls;
}
whitespace();
return declarations();
};
/**
* Trim `str`.
*
* @param {String} str
* @return {String}
*/
function trim(str) {
return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;
}

View File

@@ -0,0 +1,53 @@
{
"name": "inline-style-parser",
"version": "0.2.2",
"description": "An inline style parser.",
"main": "index.js",
"scripts": {
"build": "rollup --config --failAfterWarnings",
"clean": "rm -rf dist",
"lint": "eslint --ignore-path .gitignore .",
"lint:fix": "npm run lint -- --fix",
"prepublishOnly": "pinst --disable && npm run lint && npm test && npm run build",
"test": "jest",
"test:ci": "CI=true jest --ci --colors --coverage --collectCoverageFrom=index.js",
"test:esm": "node --test test/index.test.mjs",
"test:watch": "jest --watch",
"_postinstall": "husky install",
"postpublish": "pinst --enable"
},
"repository": {
"type": "git",
"url": "https://github.com/remarkablemark/inline-style-parser"
},
"bugs": {
"url": "https://github.com/remarkablemark/inline-style-parser/issues"
},
"keywords": [
"inline-style-parser",
"inline-style",
"style",
"parser",
"css"
],
"devDependencies": {
"@commitlint/cli": "17.8.0",
"@commitlint/config-conventional": "17.8.0",
"@rollup/plugin-commonjs": "25.0.5",
"@rollup/plugin-terser": "0.4.4",
"css": "3.0.0",
"eslint": "8.51.0",
"eslint-plugin-prettier": "5.0.1",
"husky": "8.0.3",
"jest": "29.7.0",
"lint-staged": "14.0.0",
"pinst": "3.0.0",
"prettier": "3.0.3",
"rollup": "4.1.0"
},
"files": [
"/dist",
"/index.d.ts"
],
"license": "MIT"
}

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2017 Menglin "Mark" Xu <mark@remarkablemark.org>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,188 @@
# style-to-object
[![NPM](https://nodei.co/npm/style-to-object.png)](https://nodei.co/npm/style-to-object/)
[![NPM version](https://badgen.net/npm/v/style-to-object)](https://www.npmjs.com/package/style-to-object)
[![Bundlephobia minified + gzip](https://badgen.net/bundlephobia/minzip/style-to-object)](https://bundlephobia.com/package/style-to-object)
[![build](https://github.com/remarkablemark/style-to-object/actions/workflows/build.yml/badge.svg)](https://github.com/remarkablemark/style-to-object/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/remarkablemark/style-to-object/branch/master/graph/badge.svg?token=XWxph9dpa4)](https://codecov.io/gh/remarkablemark/style-to-object)
[![NPM downloads](https://badgen.net/npm/dm/style-to-object)](https://www.npmjs.com/package/style-to-object)
Parses inline style to object:
```js
import parse from 'style-to-object';
parse('color: #C0FFEE; background: #BADA55;');
```
Output:
```js
{ color: '#C0FFEE', background: '#BADA55' }
```
[JSFiddle](https://jsfiddle.net/remarkablemark/ykz2meot/) | [Replit](https://replit.com/@remarkablemark/style-to-object) | [Examples](https://github.com/remarkablemark/style-to-object/tree/master/examples)
## Installation
[NPM](https://www.npmjs.com/package/style-to-object):
```sh
npm install style-to-object --save
```
[Yarn](https://yarn.fyi/style-to-object):
```sh
yarn add style-to-object
```
[CDN](https://unpkg.com/style-to-object/):
```html
<script src="https://unpkg.com/style-to-object@latest/dist/style-to-object.min.js"></script>
<script>
window.StyleToObject(/* string */);
</script>
```
## Usage
Import with ES Modules:
```js
import parse from 'style-to-object';
```
Require with CommonJS:
```js
const parse = require('style-to-object').default;
```
Parse single declaration:
```js
parse('line-height: 42');
```
Output:
```js
{ 'line-height': '42' }
```
Parse multiple declarations:
```js
parse(`
border-color: #ACE;
z-index: 1337;
`);
```
Output:
```js
{ 'border-color': '#ACE', 'z-index': '1337' }
```
Parse unknown declarations:
```js
parse('answer: 42;');
```
Output:
```js
{ 'answer': '42' }
```
Invalid declarations/arguments:
<!-- prettier-ignore-start -->
```js
parse(`
top: ;
right: 1em;
`); // { right: '1em' }
parse(); // null
parse(null); // null
parse(1); // null
parse(true); // null
parse('top:'); // null
parse(':12px'); // null
parse(':'); // null
parse(';'); // null
parse('top'); // throws Error
parse('/*'); // throws Error
```
<!-- prettier-ignore-end -->
### Iterator
If the 2nd argument is a function, then the parser will return `null`:
```js
parse('color: #f00', () => {}); // null
```
But the function will iterate through each declaration:
<!-- prettier-ignore-start -->
```js
parse('color: #f00', (name, value, declaration) => {
console.log(name); // 'color'
console.log(value); // '#f00'
console.log(declaration); // { type: 'declaration', property: 'color', value: '#f00' }
});
```
<!-- prettier-ignore-end -->
This makes it easy to customize the output:
```js
const style = `
color: red;
background: blue;
`;
const output = [];
function iterator(name, value) {
output.push([name, value]);
}
parse(style, iterator);
console.log(output); // [['color', 'red'], ['background', 'blue']]
```
## Migration
### v1
Migrated to TypeScript. Iterator excludes `Comment`. CommonJS requires the `.default` key:
```js
const parse = require('style-to-object').default;
```
## Release
Release and publish are automated by [Release Please](https://github.com/googleapis/release-please).
## Special Thanks
- [inline-style-parser](https://github.com/remarkablemark/inline-style-parser)
- [Contributors](https://github.com/remarkablemark/style-to-object/graphs/contributors)
## License
[MIT](https://github.com/remarkablemark/style-to-object/blob/master/LICENSE)

View File

@@ -0,0 +1,22 @@
import type { Declaration } from 'inline-style-parser';
export { Declaration };
interface StyleObject {
[name: string]: string;
}
type Iterator = (property: string, value: string, declaration: Declaration) => void;
/**
* Parses inline style to object.
*
* @param style - Inline style.
* @param iterator - Iterator.
* @returns - Style object or null.
*
* @example Parsing inline style to object:
*
* ```js
* import parse from 'style-to-object';
* parse('line-height: 42;'); // { 'line-height': '42' }
* ```
*/
export default function StyleToObject(style: string, iterator?: Iterator): StyleObject | null;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,WAAW,EAAE,CAAC;AAEvB,UAAU,WAAW;IACnB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;CACxB;AAED,KAAK,QAAQ,GAAG,CACd,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,WAAW,KACrB,IAAI,CAAC;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACnC,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,QAAQ,GAClB,WAAW,GAAG,IAAI,CA0BpB"}

View File

@@ -0,0 +1,44 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var inline_style_parser_1 = __importDefault(require("inline-style-parser"));
/**
* Parses inline style to object.
*
* @param style - Inline style.
* @param iterator - Iterator.
* @returns - Style object or null.
*
* @example Parsing inline style to object:
*
* ```js
* import parse from 'style-to-object';
* parse('line-height: 42;'); // { 'line-height': '42' }
* ```
*/
function StyleToObject(style, iterator) {
var styleObject = null;
if (!style || typeof style !== 'string') {
return styleObject;
}
var declarations = (0, inline_style_parser_1.default)(style);
var hasIterator = typeof iterator === 'function';
declarations.forEach(function (declaration) {
if (declaration.type !== 'declaration') {
return;
}
var property = declaration.property, value = declaration.value;
if (hasIterator) {
iterator(property, value, declaration);
}
else if (value) {
styleObject = styleObject || {};
styleObject[property] = value;
}
});
return styleObject;
}
exports.default = StyleToObject;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,4EAAwC;AAexC;;;;;;;;;;;;;GAaG;AACH,SAAwB,aAAa,CACnC,KAAa,EACb,QAAmB;IAEnB,IAAI,WAAW,GAAuB,IAAI,CAAC;IAE3C,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,IAAM,YAAY,GAAG,IAAA,6BAAK,EAAC,KAAK,CAAC,CAAC;IAClC,IAAM,WAAW,GAAG,OAAO,QAAQ,KAAK,UAAU,CAAC;IAEnD,YAAY,CAAC,OAAO,CAAC,UAAC,WAAW;QAC/B,IAAI,WAAW,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;YACvC,OAAO;QACT,CAAC;QAEO,IAAA,QAAQ,GAAY,WAAW,SAAvB,EAAE,KAAK,GAAK,WAAW,MAAhB,CAAiB;QAExC,IAAI,WAAW,EAAE,CAAC;YAChB,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,KAAK,EAAE,CAAC;YACjB,WAAW,GAAG,WAAW,IAAI,EAAE,CAAC;YAChC,WAAW,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;QAChC,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC;AA7BD,gCA6BC"}

View File

@@ -0,0 +1,311 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.StyleToObject = factory());
})(this, (function () { 'use strict';
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
// http://www.w3.org/TR/CSS21/grammar.html
// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
var NEWLINE_REGEX = /\n/g;
var WHITESPACE_REGEX = /^\s*/;
// declaration
var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/;
var COLON_REGEX = /^:\s*/;
var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/;
var SEMICOLON_REGEX = /^[;\s]*/;
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
var TRIM_REGEX = /^\s+|\s+$/g;
// strings
var NEWLINE = '\n';
var FORWARD_SLASH = '/';
var ASTERISK = '*';
var EMPTY_STRING = '';
// types
var TYPE_COMMENT = 'comment';
var TYPE_DECLARATION = 'declaration';
/**
* @param {String} style
* @param {Object} [options]
* @return {Object[]}
* @throws {TypeError}
* @throws {Error}
*/
var inlineStyleParser = function (style, options) {
if (typeof style !== 'string') {
throw new TypeError('First argument must be a string');
}
if (!style) return [];
options = options || {};
/**
* Positional.
*/
var lineno = 1;
var column = 1;
/**
* Update lineno and column based on `str`.
*
* @param {String} str
*/
function updatePosition(str) {
var lines = str.match(NEWLINE_REGEX);
if (lines) lineno += lines.length;
var i = str.lastIndexOf(NEWLINE);
column = ~i ? str.length - i : column + str.length;
}
/**
* Mark position and patch `node.position`.
*
* @return {Function}
*/
function position() {
var start = { line: lineno, column: column };
return function (node) {
node.position = new Position(start);
whitespace();
return node;
};
}
/**
* Store position information for a node.
*
* @constructor
* @property {Object} start
* @property {Object} end
* @property {undefined|String} source
*/
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
/**
* Non-enumerable source string.
*/
Position.prototype.content = style;
/**
* Error `msg`.
*
* @param {String} msg
* @throws {Error}
*/
function error(msg) {
var err = new Error(
options.source + ':' + lineno + ':' + column + ': ' + msg
);
err.reason = msg;
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = style;
if (options.silent) ; else {
throw err;
}
}
/**
* Match `re` and return captures.
*
* @param {RegExp} re
* @return {undefined|Array}
*/
function match(re) {
var m = re.exec(style);
if (!m) return;
var str = m[0];
updatePosition(str);
style = style.slice(str.length);
return m;
}
/**
* Parse whitespace.
*/
function whitespace() {
match(WHITESPACE_REGEX);
}
/**
* Parse comments.
*
* @param {Object[]} [rules]
* @return {Object[]}
*/
function comments(rules) {
var c;
rules = rules || [];
while ((c = comment())) {
if (c !== false) {
rules.push(c);
}
}
return rules;
}
/**
* Parse comment.
*
* @return {Object}
* @throws {Error}
*/
function comment() {
var pos = position();
if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;
var i = 2;
while (
EMPTY_STRING != style.charAt(i) &&
(ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))
) {
++i;
}
i += 2;
if (EMPTY_STRING === style.charAt(i - 1)) {
return error('End of comment missing');
}
var str = style.slice(2, i - 2);
column += 2;
updatePosition(str);
style = style.slice(i);
column += 2;
return pos({
type: TYPE_COMMENT,
comment: str
});
}
/**
* Parse declaration.
*
* @return {Object}
* @throws {Error}
*/
function declaration() {
var pos = position();
// prop
var prop = match(PROPERTY_REGEX);
if (!prop) return;
comment();
// :
if (!match(COLON_REGEX)) return error("property missing ':'");
// val
var val = match(VALUE_REGEX);
var ret = pos({
type: TYPE_DECLARATION,
property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),
value: val
? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))
: EMPTY_STRING
});
// ;
match(SEMICOLON_REGEX);
return ret;
}
/**
* Parse declarations.
*
* @return {Object[]}
*/
function declarations() {
var decls = [];
comments(decls);
// declarations
var decl;
while ((decl = declaration())) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
return decls;
}
whitespace();
return declarations();
};
/**
* Trim `str`.
*
* @param {String} str
* @return {String}
*/
function trim(str) {
return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;
}
var parse = /*@__PURE__*/getDefaultExportFromCjs(inlineStyleParser);
/**
* Parses inline style to object.
*
* @param style - Inline style.
* @param iterator - Iterator.
* @returns - Style object or null.
*
* @example Parsing inline style to object:
*
* ```js
* import parse from 'style-to-object';
* parse('line-height: 42;'); // { 'line-height': '42' }
* ```
*/
function StyleToObject(style, iterator) {
var styleObject = null;
if (!style || typeof style !== 'string') {
return styleObject;
}
var declarations = parse(style);
var hasIterator = typeof iterator === 'function';
declarations.forEach(function (declaration) {
if (declaration.type !== 'declaration') {
return;
}
var property = declaration.property, value = declaration.value;
if (hasIterator) {
iterator(property, value, declaration);
}
else if (value) {
styleObject = styleObject || {};
styleObject[property] = value;
}
});
return styleObject;
}
return StyleToObject;
}));
//# sourceMappingURL=style-to-object.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
!function(n,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(n="undefined"!=typeof globalThis?globalThis:n||self).StyleToObject=e()}(this,(function(){"use strict";function n(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,t=/^\s*/,o=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,u=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,f=/^\s+|\s+$/g,a="";function s(n){return n?n.replace(f,a):a}var l=n((function(n,f){if("string"!=typeof n)throw new TypeError("First argument must be a string");if(!n)return[];f=f||{};var l=1,p=1;function h(n){var e=n.match(r);e&&(l+=e.length);var t=n.lastIndexOf("\n");p=~t?n.length-t:p+n.length}function v(){var n={line:l,column:p};return function(e){return e.position=new d(n),g(),e}}function d(n){this.start=n,this.end={line:l,column:p},this.source=f.source}function m(e){var r=new Error(f.source+":"+l+":"+p+": "+e);if(r.reason=e,r.filename=f.source,r.line=l,r.column=p,r.source=n,!f.silent)throw r}function y(e){var r=e.exec(n);if(r){var t=r[0];return h(t),n=n.slice(t.length),r}}function g(){y(t)}function w(n){var e;for(n=n||[];e=b();)!1!==e&&n.push(e);return n}function b(){var e=v();if("/"==n.charAt(0)&&"*"==n.charAt(1)){for(var r=2;a!=n.charAt(r)&&("*"!=n.charAt(r)||"/"!=n.charAt(r+1));)++r;if(r+=2,a===n.charAt(r-1))return m("End of comment missing");var t=n.slice(2,r-2);return p+=2,h(t),n=n.slice(r),p+=2,e({type:"comment",comment:t})}}function A(){var n=v(),r=y(o);if(r){if(b(),!y(i))return m("property missing ':'");var t=y(u),f=n({type:"declaration",property:s(r[0].replace(e,a)),value:t?s(t[0].replace(e,a)):a});return y(c),f}}return d.prototype.content=n,g(),function(){var n,e=[];for(w(e);n=A();)!1!==n&&(e.push(n),w(e));return e}()}));return function(n,e){var r=null;if(!n||"string"!=typeof n)return r;var t=l(n),o="function"==typeof e;return t.forEach((function(n){if("declaration"===n.type){var t=n.property,i=n.value;o?e(t,i,n):i&&((r=r||{})[t]=i)}})),r}}));
//# sourceMappingURL=style-to-object.min.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import type { Declaration } from 'inline-style-parser';
export { Declaration };
interface StyleObject {
[name: string]: string;
}
type Iterator = (property: string, value: string, declaration: Declaration) => void;
/**
* Parses inline style to object.
*
* @param style - Inline style.
* @param iterator - Iterator.
* @returns - Style object or null.
*
* @example Parsing inline style to object:
*
* ```js
* import parse from 'style-to-object';
* parse('line-height: 42;'); // { 'line-height': '42' }
* ```
*/
export default function StyleToObject(style: string, iterator?: Iterator): StyleObject | null;

View File

@@ -0,0 +1,4 @@
import StyleToObject from '../cjs/index.js';
// ensure compatibility with rollup umd build
export default StyleToObject.default || StyleToObject;

View File

@@ -0,0 +1,77 @@
{
"name": "style-to-object",
"version": "1.0.5",
"description": "Converts inline style to object.",
"author": "Mark <mark@remarkablemark.org>",
"main": "./cjs/index.js",
"module": "./esm/index.mjs",
"exports": {
"import": "./esm/index.mjs",
"require": "./cjs/index.js"
},
"scripts": {
"build": "run-s build:*",
"build:cjs": "tsc",
"build:esm": "awk '!/sourceMappingURL/' cjs/index.d.ts > esm/index.d.mts",
"build:umd": "rollup --config --failAfterWarnings",
"clean": "rm -rf cjs coverage dist",
"lint": "eslint --ignore-path .gitignore .",
"lint:fix": "npm run lint -- --fix",
"lint:tsc": "tsc --noEmit",
"_postinstall": "husky install",
"postpublish": "pinst --enable",
"prepublishOnly": "pinst --disable && run-s lint lint:tsc test clean build",
"test": "jest",
"test:ci": "CI=true jest --ci --colors --coverage",
"test:esm": "npm run build:cjs && node --test __tests__",
"test:watch": "npm run test -- --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/remarkablemark/style-to-object"
},
"bugs": {
"url": "https://github.com/remarkablemark/style-to-object/issues"
},
"keywords": [
"style-to-object",
"inline",
"style",
"parser",
"css",
"object",
"pojo"
],
"dependencies": {
"inline-style-parser": "0.2.2"
},
"devDependencies": {
"@commitlint/cli": "18.4.3",
"@commitlint/config-conventional": "18.4.3",
"@rollup/plugin-commonjs": "25.0.7",
"@rollup/plugin-node-resolve": "15.2.3",
"@rollup/plugin-terser": "0.4.4",
"@rollup/plugin-typescript": "11.1.5",
"@types/jest": "29.5.10",
"@typescript-eslint/eslint-plugin": "6.13.1",
"@typescript-eslint/parser": "6.13.1",
"eslint": "8.54.0",
"eslint-plugin-prettier": "5.0.1",
"husky": "8.0.3",
"jest": "29.7.0",
"lint-staged": "15.1.0",
"npm-run-all": "4.1.5",
"pinst": "3.0.0",
"prettier": "3.1.0",
"rollup": "4.6.1",
"ts-jest": "29.1.1",
"typescript": "5.3.2"
},
"files": [
"/cjs",
"/dist",
"/esm",
"/src"
],
"license": "MIT"
}

View File

@@ -0,0 +1,59 @@
import parse from 'inline-style-parser';
import type { Declaration } from 'inline-style-parser';
export { Declaration };
interface StyleObject {
[name: string]: string;
}
type Iterator = (
property: string,
value: string,
declaration: Declaration,
) => void;
/**
* Parses inline style to object.
*
* @param style - Inline style.
* @param iterator - Iterator.
* @returns - Style object or null.
*
* @example Parsing inline style to object:
*
* ```js
* import parse from 'style-to-object';
* parse('line-height: 42;'); // { 'line-height': '42' }
* ```
*/
export default function StyleToObject(
style: string,
iterator?: Iterator,
): StyleObject | null {
let styleObject: StyleObject | null = null;
if (!style || typeof style !== 'string') {
return styleObject;
}
const declarations = parse(style);
const hasIterator = typeof iterator === 'function';
declarations.forEach((declaration) => {
if (declaration.type !== 'declaration') {
return;
}
const { property, value } = declaration;
if (hasIterator) {
iterator(property, value, declaration);
} else if (value) {
styleObject = styleObject || {};
styleObject[property] = value;
}
});
return styleObject;
}

128
node_modules/hast-util-to-jsx-runtime/package.json generated vendored Normal file
View File

@@ -0,0 +1,128 @@
{
"name": "hast-util-to-jsx-runtime",
"version": "2.3.0",
"description": "hast utility to transform to preact, react, solid, svelte, vue, etc",
"license": "MIT",
"keywords": [
"unist",
"hast",
"hast-util",
"util",
"utility",
"html",
"preact",
"react",
"solid",
"svelte",
"vue"
],
"repository": "syntax-tree/hast-util-to-jsx-runtime",
"bugs": "https://github.com/syntax-tree/hast-util-to-jsx-runtime/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"sideEffects": false,
"type": "module",
"exports": "./index.js",
"files": [
"lib/",
"index.d.ts",
"index.js"
],
"dependencies": {
"@types/estree": "^1.0.0",
"@types/hast": "^3.0.0",
"@types/unist": "^3.0.0",
"comma-separated-tokens": "^2.0.0",
"devlop": "^1.0.0",
"estree-util-is-identifier-name": "^3.0.0",
"hast-util-whitespace": "^3.0.0",
"mdast-util-mdx-expression": "^2.0.0",
"mdast-util-mdx-jsx": "^3.0.0",
"mdast-util-mdxjs-esm": "^2.0.0",
"property-information": "^6.0.0",
"space-separated-tokens": "^2.0.0",
"style-to-object": "^1.0.0",
"unist-util-position": "^5.0.0",
"vfile-message": "^4.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"c8": "^8.0.0",
"esbuild": "^0.19.0",
"estree-util-visit": "^2.0.0",
"hastscript": "^8.0.0",
"prettier": "^3.0.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"remark-cli": "^12.0.0",
"remark-gfm": "^4.0.0",
"remark-preset-wooorm": "^9.0.0",
"sval": "^0.4.0",
"type-coverage": "^2.0.0",
"typescript": "^5.0.0",
"xo": "^0.56.0"
},
"scripts": {
"prepack": "npm run build && npm run format",
"generate": "esbuild . --bundle --minify --target=es2020 --format=esm --outfile=example/hast-util-to-jsx-runtime.min.js",
"build": "tsc --build --clean && tsc --build && type-coverage",
"format": "remark . -qfo && prettier . -w --log-level warn && xo --fix",
"test-api": "node --conditions development test/index.js",
"test-coverage": "c8 --100 --reporter lcov npm run test-api",
"test": "npm run generate && npm run build && npm run format && npm run test-coverage"
},
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"remark-preset-wooorm",
[
"remark-lint-list-item-indent",
"space"
],
[
"remark-preset-wooorm/node_modules/remark-gfm/index.js",
false
],
"remark-gfm"
]
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"ignoreCatch": true,
"ignoreFiles": [
"example/**/*.js"
],
"strict": true
},
"xo": {
"overrides": [
{
"files": "**/*.ts",
"rules": {
"@typescript-eslint/ban-types": "off"
}
}
],
"prettier": true,
"rules": {
"unicorn/prefer-at": "off",
"unicorn/prefer-string-replace-all": "off"
}
}
}

772
node_modules/hast-util-to-jsx-runtime/readme.md generated vendored Normal file
View File

@@ -0,0 +1,772 @@
# hast-util-to-jsx-runtime
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
hast utility to transform a tree to preact, react, solid, svelte, vue, etc.,
with an automatic JSX runtime.
## Contents
* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`toJsxRuntime(tree, options)`](#tojsxruntimetree-options)
* [`Components`](#components)
* [`CreateEvaluater`](#createevaluater)
* [`ElementAttributeNameCase`](#elementattributenamecase)
* [`EvaluateExpression`](#evaluateexpression)
* [`EvaluateProgram`](#evaluateprogram)
* [`Evaluater`](#evaluater)
* [`ExtraProps`](#extraprops)
* [`Fragment`](#fragment)
* [`Jsx`](#jsx)
* [`JsxDev`](#jsxdev)
* [`Options`](#options)
* [`Props`](#props)
* [`Source`](#source)
* [`Space`](#space)
* [`StylePropertyNameCase`](#stylepropertynamecase)
* [Errors](#errors)
* [Examples](#examples)
* [Example: Preact](#example-preact)
* [Example: Solid](#example-solid)
* [Example: Svelte](#example-svelte)
* [Example: Vue](#example-vue)
* [Syntax](#syntax)
* [Compatibility](#compatibility)
* [Security](#security)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This package is a utility that takes a [hast][] tree and an
[automatic JSX runtime][jsx-runtime] and turns the tree into anything you
wish.
## When should I use this?
You can use this package when you have a hast syntax tree and want to use it
with whatever framework.
This package uses an automatic JSX runtime, which is a sort of lingua franca
for frameworks to support JSX.
Notably, automatic runtimes have support for passing extra information in
development, and have guaranteed support for fragments.
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install hast-util-to-jsx-runtime
```
In Deno with [`esm.sh`][esmsh]:
```js
import {toJsxRuntime} from 'https://esm.sh/hast-util-to-jsx-runtime@2'
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {toJsxRuntime} from 'https://esm.sh/hast-util-to-jsx-runtime@2?bundle'
</script>
```
## Use
```js
import {h} from 'hastscript'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {Fragment, jsx, jsxs} from 'react/jsx-runtime'
import {renderToStaticMarkup} from 'react-dom/server'
const tree = h('h1', 'Hello, world!')
const doc = renderToStaticMarkup(toJsxRuntime(tree, {Fragment, jsx, jsxs}))
console.log(doc)
```
Yields:
```html
<h1>Hello, world!</h1>
```
## API
This package exports the identifier [`toJsxRuntime`][api-to-jsx-runtime].
It exports the [TypeScript][] types
[`Components`][api-components],
[`CreateEvaluater`][api-create-evaluater],
[`ElementAttributeNameCase`][api-element-attribute-name-case],
[`EvaluateExpression`][api-evaluate-expression],
[`EvaluateProgram`][api-evaluate-program],
[`Evaluater`][api-evaluater],
[`ExtraProps`][api-extra-props],
[`Fragment`][api-fragment],
[`Jsx`][api-jsx],
[`JsxDev`][api-jsx-dev],
[`Options`][api-options],
[`Props`][api-props],
[`Source`][api-source],
[`Space`][api-Space], and
[`StylePropertyNameCase`][api-style-property-name-case].
There is no default export.
### `toJsxRuntime(tree, options)`
Transform a hast tree to preact, react, solid, svelte, vue, etc., with an
automatic JSX runtime.
##### Parameters
* `tree` ([`Node`][node])
— tree to transform
* `options` ([`Options`][api-options], required)
— configuration
##### Returns
Result from your configured JSX runtime (`JSX.Element`).
### `Components`
Possible components to use (TypeScript type).
Each key is a tag name typed in `JSX.IntrinsicElements`.
Each value is either a different tag name, or a component accepting the
corresponding props (and an optional `node` prop if `passNode` is on).
You can access props at `JSX.IntrinsicElements`.
For example, to find props for `a`, use `JSX.IntrinsicElements['a']`.
###### Type
```ts
import type {Element} from 'hast'
type Components = {
[TagName in keyof JSX.IntrinsicElements]:
| Component<JSX.IntrinsicElements[TagName] & ExtraProps>
| keyof JSX.IntrinsicElements
}
type ExtraProps = {node?: Element | undefined}
type Component<ComponentProps> =
// Class component:
| (new (props: ComponentProps) => JSX.ElementClass)
// Function component:
| ((props: ComponentProps) => JSX.Element | string | null | undefined)
```
### `CreateEvaluater`
Create an evaluator that turns ESTree ASTs from embedded MDX into values
(TypeScript type).
###### Parameters
There are no parameters.
###### Returns
Evaluater ([`Evaluater`][api-evaluater]).
### `ElementAttributeNameCase`
Casing to use for attribute names (TypeScript type).
HTML casing is for example `class`, `stroke-linecap`, `xml:lang`.
React casing is for example `className`, `strokeLinecap`, `xmlLang`.
###### Type
```ts
type ElementAttributeNameCase = 'html' | 'react'
```
### `EvaluateExpression`
Turn an MDX expression into a value (TypeScript type).
###### Parameters
* `expression` (`Expression` from `@types/estree`)
— estree expression
###### Returns
Result of expression (`unknown`).
### `EvaluateProgram`
Turn an MDX program (export/import statements) into a value (TypeScript type).
###### Parameters
* `program` (`Program` from `@types/estree`)
— estree program
###### Returns
Result of program (`unknown`);
should likely be `undefined` as ESM changes the scope but doesnt yield
something.
### `Evaluater`
Evaluator that turns ESTree ASTs from embedded MDX into values (TypeScript
type).
###### Fields
* `evaluateExpression` ([`EvaluateExpression`][api-evaluate-expression])
— evaluate an expression
* `evaluateProgram` ([`EvaluateProgram`][api-evaluate-program])
— evaluate a program
### `ExtraProps`
Extra fields we pass (TypeScript type).
###### Type
```ts
type ExtraProps = {node?: Element | undefined}
```
### `Fragment`
Represent the children, typically a symbol (TypeScript type).
###### Type
```ts
type Fragment = unknown
```
### `Jsx`
Create a production element (TypeScript type).
###### Parameters
* `type` (`unknown`)
— element type: `Fragment` symbol, tag name (`string`), component
* `props` ([`Props`][api-props])
— element props, `children`, and maybe `node`
* `key` (`string` or `undefined`)
— dynamicly generated key to use
###### Returns
Element from your framework (`JSX.Element`).
### `JsxDev`
Create a development element (TypeScript type).
###### Parameters
* `type` (`unknown`)
— element type: `Fragment` symbol, tag name (`string`), component
* `props` ([`Props`][api-props])
— element props, `children`, and maybe `node`
* `key` (`string` or `undefined`)
— dynamicly generated key to use
* `isStaticChildren` (`boolean`)
— whether two or more children are passed (in an array), which is whether
`jsxs` or `jsx` would be used
* `source` ([`Source`][api-source])
— info about source
* `self` (`undefined`)
— nothing (this is used by frameworks that have components, we dont)
###### Returns
Element from your framework (`JSX.Element`).
### `Options`
Configuration (TypeScript type).
###### Fields
* `Fragment` ([`Fragment`][api-fragment], required)
— fragment
* `jsx` ([`Jsx`][api-jsx], required in production)
— dynamic JSX
* `jsxs` ([`Jsx`][api-jsx], required in production)
— static JSX
* `jsxDEV` ([`JsxDev`][api-jsx-dev], required in development)
— development JSX
* `components` ([`Partial<Components>`][api-components], optional)
— components to use
* `createEvaluater` ([`CreateEvaluater`][api-create-evaluater], optional)
— create an evaluator that turns ESTree ASTs into values
* `development` (`boolean`, default: `false`)
— whether to use `jsxDEV` when on or `jsx` and `jsxs` when off
* `elementAttributeNameCase`
([`ElementAttributeNameCase`][api-element-attribute-name-case],
default: `'react'`)
— specify casing to use for attribute names
* `filePath` (`string`, optional)
— file path to the original source file, passed in source info to `jsxDEV`
when using the automatic runtime with `development: true`
* `passNode` (`boolean`, default: `false`)
— pass the hast element node to components
* `space` ([`Space`][api-space], default: `'html'`)
— whether `tree` is in the `'html'` or `'svg'` space, when an `<svg>`
element is found in the HTML space, this package already automatically
switches to and from the SVG space when entering and exiting it
* `stylePropertyNameCase`
([`StylePropertyNameCase`][api-style-property-name-case],
default: `'dom'`)
— specify casing to use for property names in `style` objects
* `tableCellAlignToStyle`
(`boolean`, default: `true`)
— turn obsolete `align` props on `td` and `th` into CSS `style` props
### `Props`
Properties and children (TypeScript type).
###### Type
```ts
import type {Element} from 'hast'
type Props = {
[prop: string]:
| Array<JSX.Element | string | null | undefined> // For `children`.
| Record<string, string> // For `style`.
| Element // For `node`.
| boolean
| number
| string
| undefined
children: Array<JSX.Element | string | null | undefined> | undefined
node?: Element | undefined
}
```
### `Source`
Info about source (TypeScript type).
###### Fields
* `columnNumber` (`number` or `undefined`)
— column where thing starts (0-indexed)
* `fileName` (`string` or `undefined`)
— name of source file
* `lineNumber` (`number` or `undefined`)
— line where thing starts (1-indexed)
### `Space`
Namespace (TypeScript type).
> 👉 **Note**: hast is not XML.
> It supports SVG as embedded in HTML.
> It does not support the features available in XML.
> Passing SVG might break but fragments of modern SVG should be fine.
> Use `xast` if you need to support SVG as XML.
###### Type
```ts
type Space = 'html' | 'svg'
```
### `StylePropertyNameCase`
Casing to use for property names in `style` objects (TypeScript type).
CSS casing is for example `background-color` and `-webkit-line-clamp`.
DOM casing is for example `backgroundColor` and `WebkitLineClamp`.
###### Type
```ts
type StylePropertyNameCase = 'css' | 'dom'
```
## Errors
The following errors are thrown:
###### ``Expected `Fragment` in options``
This error is thrown when either `options` is not passed at all or
when `options.Fragment` is `undefined`.
The automatic JSX runtime needs a symbol for a fragment to work.
To solve the error, make sure you are passing the correct fragment symbol from
your framework.
###### `` Expected `jsxDEV` in options when `development: true` ``
This error is thrown when `options.development` is turned on (`true`), but when
`options.jsxDEV` is not a function.
The automatic JSX runtime, in development, needs this function.
To solve the error, make sure you are importing the correct runtime functions
(for example, `'react/jsx-dev-runtime'`), and pass `jsxDEV`.
###### ``Expected `jsx` in production options``
###### ``Expected `jsxs` in production options``
These errors are thrown when `options.development` is *not* turned on (`false`
or not defined), and when `options.jsx` or `options.jsxs` are not functions.
The automatic JSX runtime, in production, needs these functions.
To solve the error, make sure you are importing the correct runtime functions
(for example, `'react/jsx-runtime'`), and pass `jsx` and `jsxs`.
###### `` Cannot handle MDX estrees without `createEvaluater` ``
This error is thrown when MDX nodes are passed that represent JavaScript
programs or expressions.
Supporting JavaScript can be unsafe and requires a different project.
To support JavaScript, pass a `createEvaluater` function in `options`.
###### ``Cannot parse `style` attribute``
This error is thrown when a `style` attribute is found on an element, which
cannot be parsed as CSS.
Most frameworks dont accept `style` as a string, so we need to parse it as
CSS, and pass it as an object.
But when broken CSS is used, such as `style="color:red; /*"`, we crash.
To solve the error, make sure authors write valid CSS.
Alternatively, pass `options.ignoreInvalidStyle: true` to swallow these
errors.
## Examples
### Example: Preact
> 👉 **Note**: you must set `elementAttributeNameCase: 'html'` for preact.
In Node.js, do:
```js
import {h} from 'hastscript'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {Fragment, jsx, jsxs} from 'preact/jsx-runtime'
import {render} from 'preact-render-to-string'
const result = render(
toJsxRuntime(h('h1', 'hi!'), {
Fragment,
jsx,
jsxs,
elementAttributeNameCase: 'html'
})
)
console.log(result)
```
Yields:
```html
<h1>hi!</h1>
```
In a browser, do:
```js
import {h} from 'https://esm.sh/hastscript@8'
import {toJsxRuntime} from 'https://esm.sh/hast-util-to-jsx-runtime@2'
import {Fragment, jsx, jsxs} from 'https://esm.sh/preact@10/jsx-runtime'
import {render} from 'https://esm.sh/preact@10'
render(
toJsxRuntime(h('h1', 'hi!'), {
Fragment,
jsx,
jsxs,
elementAttributeNameCase: 'html'
}),
document.getElementById('root')
)
```
### Example: Solid
> 👉 **Note**: you must set `elementAttributeNameCase: 'html'` and
> `stylePropertyNameCase: 'css'` for Solid.
In Node.js, do:
```js
import {h} from 'hastscript'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {Fragment, jsx, jsxs} from 'solid-jsx/jsx-runtime'
console.log(
toJsxRuntime(h('h1', 'hi!'), {
Fragment,
jsx,
jsxs,
elementAttributeNameCase: 'html',
stylePropertyNameCase: 'css'
}).t
)
```
Yields:
```html
<h1 >hi!</h1>
```
In a browser, do:
```js
import {h} from 'https://esm.sh/hastscript@8'
import {toJsxRuntime} from 'https://esm.sh/hast-util-to-jsx-runtime@2'
import {Fragment, jsx, jsxs} from 'https://esm.sh/solid-js@1/h/jsx-runtime'
import {render} from 'https://esm.sh/solid-js@1/web'
render(Component, document.getElementById('root'))
function Component() {
return toJsxRuntime(h('h1', 'hi!'), {
Fragment,
jsx,
jsxs,
elementAttributeNameCase: 'html',
stylePropertyNameCase: 'css'
})
}
```
### Example: Svelte
<!-- To do: improve svelte when it fixes a bunch of bugs. -->
I have no clue how to render a Svelte component in Node, but you can get that
component with:
```js
import {h} from 'hastscript'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {Fragment, jsx, jsxs} from 'svelte-jsx'
const svelteComponent = toJsxRuntime(h('h1', 'hi!'), {Fragment, jsx, jsxs})
console.log(svelteComponent)
```
Yields:
```text
[class Component extends SvelteComponent]
```
### Example: Vue
> 👉 **Note**: you must set `elementAttributeNameCase: 'html'` for Vue.
In Node.js, do:
```js
import serverRenderer from '@vue/server-renderer'
import {h} from 'hastscript'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {Fragment, jsx, jsxs} from 'vue/jsx-runtime' // Available since `vue@^3.3.0-alpha.6`.
console.log(
await serverRenderer.renderToString(
toJsxRuntime(h('h1', 'hi!'), {
Fragment,
jsx,
jsxs,
elementAttributeNameCase: 'html'
})
)
)
```
Yields:
```html
<h1>hi!</h1>
```
In a browser, do:
```js
import {h} from 'https://esm.sh/hastscript@8'
import {toJsxRuntime} from 'https://esm.sh/hast-util-to-jsx-runtime@2'
import {createApp} from 'https://esm.sh/vue@3'
import {Fragment, jsx, jsxs} from 'https://esm.sh/vue@3/jsx-runtime'
createApp(Component).mount('#root')
function Component() {
return toJsxRuntime(h('h1', 'hi!'), {
Fragment,
jsx,
jsxs,
elementAttributeNameCase: 'html'
})
}
```
## Syntax
HTML is parsed according to WHATWG HTML (the living standard), which is also
followed by browsers such as Chrome, Firefox, and Safari.
## Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line,
`hast-util-to-jsx-runtime@^2`, compatible with Node.js 16.
## Security
Be careful with user input in your hast tree.
Use [`hast-util-santize`][hast-util-sanitize] to make hast trees safe.
## Related
* [`hastscript`](https://github.com/syntax-tree/hastscript)
— build hast trees
* [`hast-util-to-html`](https://github.com/syntax-tree/hast-util-to-html)
— serialize hast as HTML
* [`hast-util-sanitize`](https://github.com/syntax-tree/hast-util-sanitize)
— sanitize hast
## Contribute
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
ways to get started.
See [`support.md`][support] for ways to get help.
This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
## License
[MIT][license] © [Titus Wormer][author]
<!-- Definitions -->
[build-badge]: https://github.com/syntax-tree/hast-util-to-jsx-runtime/workflows/main/badge.svg
[build]: https://github.com/syntax-tree/hast-util-to-jsx-runtime/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/hast-util-to-jsx-runtime.svg
[coverage]: https://codecov.io/github/syntax-tree/hast-util-to-jsx-runtime
[downloads-badge]: https://img.shields.io/npm/dm/hast-util-to-jsx-runtime.svg
[downloads]: https://www.npmjs.com/package/hast-util-to-jsx-runtime
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=hast-util-to-jsx-runtime
[size]: https://bundlejs.com/?q=hast-util-to-jsx-runtime
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[collective]: https://opencollective.com/unified
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[chat]: https://github.com/syntax-tree/unist/discussions
[npm]: https://docs.npmjs.com/cli/install
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[esmsh]: https://esm.sh
[typescript]: https://www.typescriptlang.org
[license]: license
[author]: https://wooorm.com
[health]: https://github.com/syntax-tree/.github
[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
[support]: https://github.com/syntax-tree/.github/blob/main/support.md
[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
[hast]: https://github.com/syntax-tree/hast
[node]: https://github.com/syntax-tree/hast#nodes
[hast-util-sanitize]: https://github.com/syntax-tree/hast-util-sanitize
[jsx-runtime]: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
[api-to-jsx-runtime]: #tojsxruntimetree-options
[api-components]: #components
[api-create-evaluater]: #createevaluater
[api-element-attribute-name-case]: #elementattributenamecase
[api-evaluate-expression]: #evaluateexpression
[api-evaluate-program]: #evaluateprogram
[api-evaluater]: #evaluater
[api-extra-props]: #extraprops
[api-fragment]: #fragment
[api-jsx]: #jsx
[api-jsx-dev]: #jsxdev
[api-options]: #options
[api-props]: #props
[api-source]: #source
[api-space]: #space
[api-style-property-name-case]: #stylepropertynamecase