Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## v1.1.1

- [x] fix validation issues

## v1.1.0

- [x] inline sourcemap
Expand Down
465 changes: 296 additions & 169 deletions dist/index-umd-web.js

Large diffs are not rendered by default.

465 changes: 296 additions & 169 deletions dist/index.cjs

Large diffs are not rendered by default.

31 changes: 24 additions & 7 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,17 @@
* validation level enum
*/
declare enum ValidationLevel {
/**
* disable validation
*/
None = 0,
/**
* validate selectors and at-rules
*/
Default = 1,// selectors + at-rules
/**
* validate selectors, at-rules and declarations
*/
All = 2
}
/**
Expand Down Expand Up @@ -1160,6 +1169,7 @@ interface ValidationOptions {
interface MinifyOptions {

minify?: boolean;
parseColor?: boolean;
nestingRules?: boolean;
expandNestingRules?: boolean;
removeDuplicateDeclarations?: boolean;
Expand All @@ -1179,7 +1189,6 @@ export declare interface ParserOptions extends MinifyOptions, MinifyFeatureOptio
resolveUrls?: boolean;
resolveImport?: boolean;
cwd?: string;
parseColor?: boolean;
removePrefix?: boolean;
load?: (url: string, currentUrl: string) => Promise<string>;
dirname?: (path: string) => string;
Expand Down Expand Up @@ -1248,15 +1257,20 @@ export declare interface TransformOptions extends ParserOptions, RenderOptions {

}

export declare interface ParseResultStats {
src: string;
bytesIn: number;
importedBytesIn: number;
parse: string;
minify: string;
total: string;
imports: ParseResultStats[]
}

export declare interface ParseResult {
ast: AstRuleStyleSheet;
errors: ErrorDescription[];
stats: {
bytesIn: number;
parse: string;
minify: string;
total: string;
}
stats: ParseResultStats
}

export declare interface RenderResult {
Expand All @@ -1271,12 +1285,15 @@ export declare interface RenderResult {
export declare interface TransformResult extends ParseResult, RenderResult {

stats: {
src: string;
bytesIn: number;
bytesOut: number;
importedBytesIn: number;
parse: string;
minify: string;
render: string;
total: string;
imports: ParseResultStats[];
}
}

Expand Down
9 changes: 9 additions & 0 deletions dist/lib/ast/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,17 @@ var SyntaxValidationResult;
*/
var ValidationLevel;
(function (ValidationLevel) {
/**
* disable validation
*/
ValidationLevel[ValidationLevel["None"] = 0] = "None";
/**
* validate selectors and at-rules
*/
ValidationLevel[ValidationLevel["Default"] = 1] = "Default";
/**
* validate selectors, at-rules and declarations
*/
ValidationLevel[ValidationLevel["All"] = 2] = "All"; // selectors + at-rules + declarations
})(ValidationLevel || (ValidationLevel = {}));
/**
Expand Down
104 changes: 104 additions & 0 deletions dist/lib/ast/utils/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { funcLike, ColorKind } from '../../renderer/color/utils/constants.js';
import { EnumToken } from '../types.js';
import '../minify.js';
import '../walk.js';
import '../../parser/parse.js';
import '../../parser/tokenize.js';
import '../../parser/utils/config.js';
import '../../renderer/sourcemap/lib/encode.js';
import { minmax } from '../../renderer/color/color.js';

function reduceNumber(val) {
val = String(+val);
if (val === '0') {
return '0';
}
const chr = val.charAt(0);
if (chr == '-') {
const slice = val.slice(0, 2);
if (slice == '-0') {
return val.length == 2 ? '0' : '-' + val.slice(2);
}
}
if (chr == '0') {
return val.slice(1);
}
return val;
}
/**
* clamp color values
* @param token
*/
function clamp(token) {
if (token.kin == ColorKind.RGB || token.kin == ColorKind.RGBA) {
token.chi.filter((token) => ![EnumToken.LiteralTokenType, EnumToken.CommaTokenType, EnumToken.WhitespaceTokenType].includes(token.typ)).forEach((token, index) => {
if (index <= 2) {
if (token.typ == EnumToken.NumberTokenType) {
token.val = String(minmax(+token.val, 0, 255));
}
else if (token.typ == EnumToken.PercentageTokenType) {
token.val = String(minmax(+token.val, 0, 100));
}
}
else {
if (token.typ == EnumToken.NumberTokenType) {
token.val = String(minmax(+token.val, 0, 1));
}
else if (token.typ == EnumToken.PercentageTokenType) {
token.val = String(minmax(+token.val, 0, 100));
}
}
});
}
return token;
}
function getNumber(token) {
if (token.typ == EnumToken.IdenTokenType && token.val == 'none') {
return 0;
}
// @ts-ignore
return token.typ == EnumToken.PercentageTokenType ? token.val / 100 : +token.val;
}
/**
* convert angle to turn
* @param token
*/
function getAngle(token) {
if (token.typ == EnumToken.IdenTokenType) {
if (token.val == 'none') {
return 0;
}
}
if (token.typ == EnumToken.AngleTokenType) {
switch (token.unit) {
case 'deg':
// @ts-ignore
return token.val / 360;
case 'rad':
// @ts-ignore
return token.val / (2 * Math.PI);
case 'grad':
// @ts-ignore
return token.val / 400;
case 'turn':
// @ts-ignore
return +token.val;
}
}
// @ts-ignore
return token.val / 360;
}
function filterValues(values) {
let i = 0;
for (; i < values.length; i++) {
if (values[i].typ == EnumToken.ImportantTokenType && values[i - 1]?.typ == EnumToken.WhitespaceTokenType) {
values.splice(i - 1, 1);
}
else if (funcLike.includes(values[i].typ) && !['var', 'calc'].includes(values[i].val) && values[i + 1]?.typ == EnumToken.WhitespaceTokenType) {
values.splice(i + 1, 1);
}
}
return values;
}

export { clamp, filterValues, getAngle, getNumber, reduceNumber };
65 changes: 24 additions & 41 deletions dist/lib/parser/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,13 @@ async function doParse(iterator, options = {}) {
const src = options.src;
const stack = [];
const stats = {
src: options.src ?? '',
bytesIn: 0,
importedBytesIn: 0,
parse: `0ms`,
minify: `0ms`,
total: `0ms`
total: `0ms`,
imports: []
};
let ast = {
typ: EnumToken.StyleSheetNodeType,
Expand Down Expand Up @@ -133,7 +135,7 @@ async function doParse(iterator, options = {}) {
ast.loc.end = item.end;
}
if (item.token == ';' || item.token == '{') {
node = parseNode(tokens, context, stats, options, errors, src, map, rawTokens);
node = parseNode(tokens, context, options, errors, src, map, rawTokens);
rawTokens.length = 0;
if (node != null) {
if ('chi' in node) {
Expand Down Expand Up @@ -172,7 +174,7 @@ async function doParse(iterator, options = {}) {
map = new Map;
}
else if (item.token == '}') {
parseNode(tokens, context, stats, options, errors, src, map, rawTokens);
parseNode(tokens, context, options, errors, src, map, rawTokens);
rawTokens.length = 0;
if (context.loc != null) {
context.loc.end = item.end;
Expand All @@ -193,7 +195,7 @@ async function doParse(iterator, options = {}) {
}
}
if (tokens.length > 0) {
node = parseNode(tokens, context, stats, options, errors, src, map, rawTokens);
node = parseNode(tokens, context, options, errors, src, map, rawTokens);
rawTokens.length = 0;
if (node != null) {
if (node.typ == EnumToken.AtRuleNodeType && node.nam == 'import') {
Expand All @@ -218,14 +220,14 @@ async function doParse(iterator, options = {}) {
const url = token.typ == EnumToken.StringTokenType ? token.val.slice(1, -1) : token.val;
try {
const root = await options.load(url, options.src).then((src) => {
// console.error({url, src: options.src, resolved: options.resolve!(url, options.src as string)})
return doParse(src, Object.assign({}, options, {
minify: false,
setParent: false,
src: options.resolve(url, options.src).absolute
}));
});
stats.importedBytesIn += root.stats.bytesIn;
stats.imports.push(root.stats);
node.parent.chi.splice(node.parent.chi.indexOf(node), 1, ...root.ast.chi);
if (root.errors.length > 0) {
errors.push(...root.errors);
Expand Down Expand Up @@ -317,7 +319,7 @@ function getLastNode(context) {
}
return null;
}
function parseNode(results, context, stats, options, errors, src, map, rawTokens) {
function parseNode(results, context, options, errors, src, map, rawTokens) {
let tokens = [];
for (const t of results) {
const node = getTokenType(t.token, t.hint);
Expand Down Expand Up @@ -545,9 +547,11 @@ function parseNode(results, context, stats, options, errors, src, map, rawTokens
removeComments: true
}), '');
}
// }
context.chi.push(node);
Object.defineProperties(node, { parent: { ...definedPropertySettings, value: context }, validSyntax: { ...definedPropertySettings, value: valid.valid == SyntaxValidationResult.Valid } });
Object.defineProperties(node, {
parent: { ...definedPropertySettings, value: context },
validSyntax: { ...definedPropertySettings, value: valid.valid == SyntaxValidationResult.Valid }
});
return node;
}
else {
Expand Down Expand Up @@ -585,11 +589,9 @@ function parseNode(results, context, stats, options, errors, src, map, rawTokens
let t = renderToken(curr, { minify: false });
if (t == ',') {
acc.push([]);
// uniqTokens.push([]);
}
else {
acc[acc.length - 1].push(t);
// uniqTokens[uniqTokens.length - 1].push(curr);
}
return acc;
}, [[]]).reduce((acc, curr) => {
Expand Down Expand Up @@ -621,7 +623,6 @@ function parseNode(results, context, stats, options, errors, src, map, rawTokens
// @ts-ignore
context.chi.push(node);
Object.defineProperty(node, 'parent', { ...definedPropertySettings, value: context });
// if (options.validation) {
// @ts-ignore
const valid = options.validation == ValidationLevel.None ? {
valid: SyntaxValidationResult.Valid,
Expand All @@ -638,24 +639,10 @@ function parseNode(results, context, stats, options, errors, src, map, rawTokens
location
});
}
// } else {
//
// Object.defineProperty(node, 'tokens', {
// ...definedPropertySettings,
// enumerable: false,
// value: tokens.slice()
// });
//
// let raw: string[][] = [...uniq.values()];
//
// Object.defineProperty(node, 'raw', {
// enumerable: false,
// configurable: true,
// writable: true,
// value: raw
// });
// }
Object.defineProperty(node, 'validSyntax', { ...definedPropertySettings, value: valid.valid == SyntaxValidationResult.Valid });
Object.defineProperty(node, 'validSyntax', {
...definedPropertySettings,
value: valid.valid == SyntaxValidationResult.Valid
});
return node;
}
else {
Expand Down Expand Up @@ -705,9 +692,7 @@ function parseNode(results, context, stats, options, errors, src, map, rawTokens
parseColor(tokens[i]);
}
}
tokens.splice(i, 0, { typ: EnumToken.ColonTokenType });
// i++;
i--;
tokens.splice(i--, 0, { typ: EnumToken.ColonTokenType });
continue;
}
if ('chi' in tokens[i]) {
Expand Down Expand Up @@ -792,11 +777,15 @@ function parseNode(results, context, stats, options, errors, src, map, rawTokens
const result = parseDeclarationNode(node, errors, location);
Object.defineProperty(result, 'parent', { ...definedPropertySettings, value: context });
if (result != null) {
// console.error(doRender(result), result.val, location);
if (options.validation == ValidationLevel.All) {
const valid = evaluateSyntax(result, options);
Object.defineProperty(result, 'validSyntax', { ...definedPropertySettings, value: valid.valid == SyntaxValidationResult.Valid });
Object.defineProperty(result, 'validSyntax', {
...definedPropertySettings,
value: valid.valid == SyntaxValidationResult.Valid
});
if (valid.valid == SyntaxValidationResult.Drop) {
// console.error({result, valid});
// console.error(JSON.stringify({result, options, valid}, null, 1));
errors.push({
action: 'drop',
message: valid.error,
Expand Down Expand Up @@ -1590,12 +1579,6 @@ function parseTokens(tokens, options = {}) {
if (t.chi[0].val.slice(1, 5) != 'data:' && urlTokenMatcher.test(value)) {
// @ts-ignore
t.chi[0].typ = EnumToken.UrlTokenTokenType;
// console.error({t, v: t.chi[0], value,
// src: options.src,
// resolved: options.src !== '' && options.resolveUrls ? options.resolve(value, options.src).absolute : null,
// val2: options.src !== '' && options.resolveUrls ? options.resolve(value, options.src).absolute : value});
//
// console.error(new Error('resolved'));
// @ts-ignore
t.chi[0].val = options.src !== '' && options.resolveUrls ? options.resolve(value, options.src).absolute : value;
}
Expand Down Expand Up @@ -1648,4 +1631,4 @@ function parseTokens(tokens, options = {}) {
return tokens;
}

export { doParse, parseAtRulePrelude, parseSelector, parseString, parseTokens, urlTokenMatcher };
export { doParse, getTokenType, parseAtRulePrelude, parseSelector, parseString, parseTokens, urlTokenMatcher };
Loading