🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@wyw-in-js/processor-utils

Package Overview
Dependencies
Maintainers
2
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@wyw-in-js/processor-utils - npm Package Compare versions

Comparing version
1.1.0
to
2.0.0-alpha.0
+72
esm/ast.js
const stringLiteralCode = (value, quote = "double") => {
const json = JSON.stringify(value);
if (quote === "double") {
return json;
}
return `'${json.slice(1, -1).replace(/'/g, "\\'")}'`;
};
const indent = (level) => " ".repeat(level);
const expressionToCodeWithContext = (expression, context) => {
if (expression.type === "Identifier") {
return expression.name;
}
if (expression.type === "StringLiteral") {
return stringLiteralCode(expression.value, context.quote);
}
if (expression.type === "NumericLiteral" || expression.type === "BooleanLiteral") {
return String(expression.value);
}
if (expression.type === "NullLiteral") {
return "null";
}
if (expression.type === "MemberExpression") {
const memberExpression = expression;
const object = expressionToCodeWithContext(memberExpression.object, context);
const property = expressionToCodeWithContext(memberExpression.property, context);
return memberExpression.computed ? `${object}[${property}]` : `${object}.${property}`;
}
if (expression.type === "CallExpression") {
const callExpression = expression;
const callee = expressionToCodeWithContext(callExpression.callee, context);
const args = callExpression.arguments.map((arg) => expressionToCodeWithContext(arg, {
...context,
quote: arg.type === "StringLiteral" ? "single" : context.quote
}));
return `${callee}(${args.join(", ")})`;
}
if (expression.type === "ArrowFunctionExpression") {
const arrow = expression;
return `(${arrow.params.map((param) => expressionToCodeWithContext(param, context)).join(", ")}) => ${expressionToCodeWithContext(arrow.body, context)}`;
}
if (expression.type === "ArrayExpression") {
return `[${expression.elements.map((item) => item ? expressionToCodeWithContext(item, context) : "").join(", ")}]`;
}
if (expression.type === "BlockStatement") {
return "{ }";
}
if (expression.type === "ObjectExpression") {
const objectExpression = expression;
if (objectExpression.properties.length === 0) {
return "{}";
}
const nextIndent = context.indent + 1;
const properties = objectExpression.properties.map((property) => {
const key = expressionToCodeWithContext(property.key, {
...context,
quote: "double"
});
const value = expressionToCodeWithContext(property.value, {
indent: nextIndent,
quote: "double"
});
return `${indent(nextIndent)}${key}: ${value}`;
}).join(",\n");
return `{\n${properties}\n${indent(context.indent)}}`;
}
return expression.type;
};
export const expressionToCode = (expression) => expressionToCodeWithContext(expression, {
indent: 0,
quote: "double"
});
//# sourceMappingURL=ast.js.map
{"mappings":"AA4HA,MAAM,qBACJ,OACA,QAA6B,aAClB;CACX,MAAM,OAAO,KAAK,UAAU,MAAM;AAClC,KAAI,UAAU,UAAU;AACtB,SAAO;;AAGT,QAAO,IAAI,KAAK,MAAM,GAAG,CAAC,EAAE,CAAC,QAAQ,MAAM,MAAM,CAAC;;AAGpD,MAAM,UAAU,UAA0B,KAAK,OAAO,MAAM;AAE5D,MAAM,+BACJ,YACA,YACW;AACX,KAAI,WAAW,SAAS,cAAc;AACpC,SAAQ,WAA0B;;AAGpC,KAAI,WAAW,SAAS,iBAAiB;AACvC,SAAO,kBAAmB,WAA6B,OAAO,QAAQ,MAAM;;AAG9E,KACE,WAAW,SAAS,oBACpB,WAAW,SAAS,kBACpB;AACA,SAAO,OAAQ,WAA+C,MAAM;;AAGtE,KAAI,WAAW,SAAS,eAAe;AACrC,SAAO;;AAGT,KAAI,WAAW,SAAS,oBAAoB;EAC1C,MAAM,mBAAmB;EACzB,MAAM,SAAS,4BAA4B,iBAAiB,QAAQ,QAAQ;EAC5E,MAAM,WAAW,4BACf,iBAAiB,UACjB,QACD;AACD,SAAO,iBAAiB,WACpB,GAAG,OAAO,GAAG,SAAS,KACtB,GAAG,OAAO,GAAG;;AAGnB,KAAI,WAAW,SAAS,kBAAkB;EACxC,MAAM,iBAAiB;EACvB,MAAM,SAAS,4BAA4B,eAAe,QAAQ,QAAQ;EAC1E,MAAM,OAAO,eAAe,UAAU,KAAK,QACzC,4BAA4B,KAAK;GAC/B,GAAG;GACH,OAAO,IAAI,SAAS,kBAAkB,WAAW,QAAQ;GAC1D,CAAC,CACH;AAED,SAAO,GAAG,OAAO,GAAG,KAAK,KAAK,KAAK,CAAC;;AAGtC,KAAI,WAAW,SAAS,2BAA2B;EACjD,MAAM,QAAQ;AACd,SAAO,IAAI,MAAM,OACd,KAAK,UAAU,4BAA4B,OAAO,QAAQ,CAAC,CAC3D,KAAK,KAAK,CAAC,OAAO,4BAA4B,MAAM,MAAM,QAAQ;;AAGvE,KAAI,WAAW,SAAS,mBAAmB;AACzC,SAAO,IAAK,WAA+B,SACxC,KAAK,SACJ,OAAO,4BAA4B,MAAM,QAAQ,GAAG,GACrD,CACA,KAAK,KAAK,CAAC;;AAGhB,KAAI,WAAW,SAAS,kBAAkB;AACxC,SAAO;;AAGT,KAAI,WAAW,SAAS,oBAAoB;EAC1C,MAAM,mBAAmB;AACzB,MAAI,iBAAiB,WAAW,WAAW,GAAG;AAC5C,UAAO;;EAGT,MAAM,aAAa,QAAQ,SAAS;EACpC,MAAM,aAAa,iBAAiB,WACjC,KAAK,aAAa;GACjB,MAAM,MAAM,4BAA4B,SAAS,KAAK;IACpD,GAAG;IACH,OAAO;IACR,CAAC;GACF,MAAM,QAAQ,4BAA4B,SAAS,OAAO;IACxD,QAAQ;IACR,OAAO;IACR,CAAC;AACF,UAAO,GAAG,OAAO,WAAW,GAAG,IAAI,IAAI;IACvC,CACD,KAAK,MAAM;AAEd,SAAO,MAAM,WAAW,IAAI,OAAO,QAAQ,OAAO,CAAC;;AAGrD,QAAO,WAAW;;AAGpB,OAAO,MAAM,oBAAoB,eAC/B,4BAA4B,YAAY;CACtC,QAAQ;CACR,OAAO;CACR,CAAC","names":[],"sources":["../src/ast.ts"],"version":3,"sourcesContent":["import type { Location } from '@wyw-in-js/shared';\n\nexport type SourceLocation = {\n end: Location;\n filename?: string;\n identifierName?: string | null;\n start: Location;\n};\n\nexport type BaseAstNode = {\n end?: number | null;\n loc?: unknown;\n start?: number | null;\n type: string;\n};\n\nexport type Expression = BaseAstNode;\n\nexport type Identifier = Expression & {\n name: string;\n type: 'Identifier';\n};\n\nexport type StringLiteral = Expression & {\n type: 'StringLiteral';\n value: string;\n};\n\nexport type NumericLiteral = Expression & {\n type: 'NumericLiteral';\n value: number;\n};\n\nexport type BooleanLiteral = Expression & {\n type: 'BooleanLiteral';\n value: boolean;\n};\n\nexport type NullLiteral = Expression & {\n type: 'NullLiteral';\n};\n\nexport type BlockStatement = BaseAstNode & {\n body: BaseAstNode[];\n type: 'BlockStatement';\n};\n\nexport type TemplateElement = BaseAstNode & {\n loc?: SourceLocation | null;\n tail: boolean;\n type: 'TemplateElement';\n value: {\n cooked?: string | null;\n raw: string;\n };\n};\n\nexport type MemberExpression = Expression & {\n computed?: boolean;\n object: Expression;\n property: Expression;\n type: 'MemberExpression';\n};\n\nexport type ObjectProperty = BaseAstNode & {\n computed?: boolean;\n key: Expression;\n shorthand?: boolean;\n type: 'ObjectProperty';\n value: Expression;\n};\n\nexport type ObjectExpression = Expression & {\n properties: ObjectProperty[];\n type: 'ObjectExpression';\n};\n\nexport type ArrayExpression = Expression & {\n elements: (Expression | null)[];\n type: 'ArrayExpression';\n};\n\nexport type CallExpression = Expression & {\n arguments: Expression[];\n callee: Expression;\n type: 'CallExpression';\n};\n\nexport type ArrowFunctionExpression = Expression & {\n async?: boolean;\n body: BlockStatement | Expression;\n params: Identifier[];\n type: 'ArrowFunctionExpression';\n};\n\nexport type AstService = {\n addDefaultImport(source: string, nameHint?: string): Identifier;\n addNamedImport(name: string, source: string, nameHint?: string): Identifier;\n arrayExpression(elements: (Expression | null)[]): ArrayExpression;\n arrowFunctionExpression(\n params: Identifier[],\n body: BlockStatement | Expression\n ): ArrowFunctionExpression;\n blockStatement(body: BaseAstNode[]): BlockStatement;\n booleanLiteral(value: boolean): BooleanLiteral;\n callExpression(callee: Expression, args: Expression[]): CallExpression;\n identifier(name: string): Identifier;\n memberExpression(\n object: Expression,\n property: Expression,\n computed?: boolean\n ): MemberExpression;\n nullLiteral(): NullLiteral;\n numericLiteral(value: number): NumericLiteral;\n objectExpression(properties: ObjectProperty[]): ObjectExpression;\n objectProperty(key: Expression, value: Expression): ObjectProperty;\n stringLiteral(value: string): StringLiteral;\n};\n\ntype PrintContext = {\n indent: number;\n quote?: 'double' | 'single';\n};\n\nconst stringLiteralCode = (\n value: string,\n quote: 'double' | 'single' = 'double'\n): string => {\n const json = JSON.stringify(value);\n if (quote === 'double') {\n return json;\n }\n\n return `'${json.slice(1, -1).replace(/'/g, \"\\\\'\")}'`;\n};\n\nconst indent = (level: number): string => ' '.repeat(level);\n\nconst expressionToCodeWithContext = (\n expression: Expression,\n context: PrintContext\n): string => {\n if (expression.type === 'Identifier') {\n return (expression as Identifier).name;\n }\n\n if (expression.type === 'StringLiteral') {\n return stringLiteralCode((expression as StringLiteral).value, context.quote);\n }\n\n if (\n expression.type === 'NumericLiteral' ||\n expression.type === 'BooleanLiteral'\n ) {\n return String((expression as NumericLiteral | BooleanLiteral).value);\n }\n\n if (expression.type === 'NullLiteral') {\n return 'null';\n }\n\n if (expression.type === 'MemberExpression') {\n const memberExpression = expression as MemberExpression;\n const object = expressionToCodeWithContext(memberExpression.object, context);\n const property = expressionToCodeWithContext(\n memberExpression.property,\n context\n );\n return memberExpression.computed\n ? `${object}[${property}]`\n : `${object}.${property}`;\n }\n\n if (expression.type === 'CallExpression') {\n const callExpression = expression as CallExpression;\n const callee = expressionToCodeWithContext(callExpression.callee, context);\n const args = callExpression.arguments.map((arg) =>\n expressionToCodeWithContext(arg, {\n ...context,\n quote: arg.type === 'StringLiteral' ? 'single' : context.quote,\n })\n );\n\n return `${callee}(${args.join(', ')})`;\n }\n\n if (expression.type === 'ArrowFunctionExpression') {\n const arrow = expression as ArrowFunctionExpression;\n return `(${arrow.params\n .map((param) => expressionToCodeWithContext(param, context))\n .join(', ')}) => ${expressionToCodeWithContext(arrow.body, context)}`;\n }\n\n if (expression.type === 'ArrayExpression') {\n return `[${(expression as ArrayExpression).elements\n .map((item) =>\n item ? expressionToCodeWithContext(item, context) : ''\n )\n .join(', ')}]`;\n }\n\n if (expression.type === 'BlockStatement') {\n return '{ }';\n }\n\n if (expression.type === 'ObjectExpression') {\n const objectExpression = expression as ObjectExpression;\n if (objectExpression.properties.length === 0) {\n return '{}';\n }\n\n const nextIndent = context.indent + 1;\n const properties = objectExpression.properties\n .map((property) => {\n const key = expressionToCodeWithContext(property.key, {\n ...context,\n quote: 'double',\n });\n const value = expressionToCodeWithContext(property.value, {\n indent: nextIndent,\n quote: 'double',\n });\n return `${indent(nextIndent)}${key}: ${value}`;\n })\n .join(',\\n');\n\n return `{\\n${properties}\\n${indent(context.indent)}}`;\n }\n\n return expression.type;\n};\n\nexport const expressionToCode = (expression: Expression): string =>\n expressionToCodeWithContext(expression, {\n indent: 0,\n quote: 'double',\n });\n"],"file":"ast.js"}
import type { Location } from '@wyw-in-js/shared';
export type SourceLocation = {
end: Location;
filename?: string;
identifierName?: string | null;
start: Location;
};
export type BaseAstNode = {
end?: number | null;
loc?: unknown;
start?: number | null;
type: string;
};
export type Expression = BaseAstNode;
export type Identifier = Expression & {
name: string;
type: 'Identifier';
};
export type StringLiteral = Expression & {
type: 'StringLiteral';
value: string;
};
export type NumericLiteral = Expression & {
type: 'NumericLiteral';
value: number;
};
export type BooleanLiteral = Expression & {
type: 'BooleanLiteral';
value: boolean;
};
export type NullLiteral = Expression & {
type: 'NullLiteral';
};
export type BlockStatement = BaseAstNode & {
body: BaseAstNode[];
type: 'BlockStatement';
};
export type TemplateElement = BaseAstNode & {
loc?: SourceLocation | null;
tail: boolean;
type: 'TemplateElement';
value: {
cooked?: string | null;
raw: string;
};
};
export type MemberExpression = Expression & {
computed?: boolean;
object: Expression;
property: Expression;
type: 'MemberExpression';
};
export type ObjectProperty = BaseAstNode & {
computed?: boolean;
key: Expression;
shorthand?: boolean;
type: 'ObjectProperty';
value: Expression;
};
export type ObjectExpression = Expression & {
properties: ObjectProperty[];
type: 'ObjectExpression';
};
export type ArrayExpression = Expression & {
elements: (Expression | null)[];
type: 'ArrayExpression';
};
export type CallExpression = Expression & {
arguments: Expression[];
callee: Expression;
type: 'CallExpression';
};
export type ArrowFunctionExpression = Expression & {
async?: boolean;
body: BlockStatement | Expression;
params: Identifier[];
type: 'ArrowFunctionExpression';
};
export type AstService = {
addDefaultImport(source: string, nameHint?: string): Identifier;
addNamedImport(name: string, source: string, nameHint?: string): Identifier;
arrayExpression(elements: (Expression | null)[]): ArrayExpression;
arrowFunctionExpression(params: Identifier[], body: BlockStatement | Expression): ArrowFunctionExpression;
blockStatement(body: BaseAstNode[]): BlockStatement;
booleanLiteral(value: boolean): BooleanLiteral;
callExpression(callee: Expression, args: Expression[]): CallExpression;
identifier(name: string): Identifier;
memberExpression(object: Expression, property: Expression, computed?: boolean): MemberExpression;
nullLiteral(): NullLiteral;
numericLiteral(value: number): NumericLiteral;
objectExpression(properties: ObjectProperty[]): ObjectExpression;
objectProperty(key: Expression, value: Expression): ObjectProperty;
stringLiteral(value: string): StringLiteral;
};
export declare const expressionToCode: (expression: Expression) => string;
const stringLiteralCode = (value, quote = 'double') => {
const json = JSON.stringify(value);
if (quote === 'double') {
return json;
}
return `'${json.slice(1, -1).replace(/'/g, "\\'")}'`;
};
const indent = (level) => ' '.repeat(level);
const expressionToCodeWithContext = (expression, context) => {
if (expression.type === 'Identifier') {
return expression.name;
}
if (expression.type === 'StringLiteral') {
return stringLiteralCode(expression.value, context.quote);
}
if (expression.type === 'NumericLiteral' ||
expression.type === 'BooleanLiteral') {
return String(expression.value);
}
if (expression.type === 'NullLiteral') {
return 'null';
}
if (expression.type === 'MemberExpression') {
const memberExpression = expression;
const object = expressionToCodeWithContext(memberExpression.object, context);
const property = expressionToCodeWithContext(memberExpression.property, context);
return memberExpression.computed
? `${object}[${property}]`
: `${object}.${property}`;
}
if (expression.type === 'CallExpression') {
const callExpression = expression;
const callee = expressionToCodeWithContext(callExpression.callee, context);
const args = callExpression.arguments.map((arg) => expressionToCodeWithContext(arg, {
...context,
quote: arg.type === 'StringLiteral' ? 'single' : context.quote,
}));
return `${callee}(${args.join(', ')})`;
}
if (expression.type === 'ArrowFunctionExpression') {
const arrow = expression;
return `(${arrow.params
.map((param) => expressionToCodeWithContext(param, context))
.join(', ')}) => ${expressionToCodeWithContext(arrow.body, context)}`;
}
if (expression.type === 'ArrayExpression') {
return `[${expression.elements
.map((item) => item ? expressionToCodeWithContext(item, context) : '')
.join(', ')}]`;
}
if (expression.type === 'BlockStatement') {
return '{ }';
}
if (expression.type === 'ObjectExpression') {
const objectExpression = expression;
if (objectExpression.properties.length === 0) {
return '{}';
}
const nextIndent = context.indent + 1;
const properties = objectExpression.properties
.map((property) => {
const key = expressionToCodeWithContext(property.key, {
...context,
quote: 'double',
});
const value = expressionToCodeWithContext(property.value, {
indent: nextIndent,
quote: 'double',
});
return `${indent(nextIndent)}${key}: ${value}`;
})
.join(',\n');
return `{\n${properties}\n${indent(context.indent)}}`;
}
return expression.type;
};
export const expressionToCode = (expression) => expressionToCodeWithContext(expression, {
indent: 0,
quote: 'double',
});
+47
-76

@@ -1,78 +0,49 @@

/* eslint-disable class-methods-use-this */
import generator from '@babel/generator';
import { hasEvalMeta } from '@wyw-in-js/shared';
import { createProcessorDiagnosticArtifact } from './diagnostics';
import getClassNameAndSlug from './utils/getClassNameAndSlug';
import { isCSSable } from './utils/toCSS';
import { validateParams } from './utils/validateParams';
import { hasEvalMeta } from "@wyw-in-js/shared";
import { expressionToCode } from "./ast.js";
import { createProcessorDiagnosticArtifact } from "./diagnostics.js";
import getClassNameAndSlug from "./utils/getClassNameAndSlug.js";
import { isCSSable } from "./utils/toCSS.js";
import { validateParams } from "./utils/validateParams.js";
export class BaseProcessor {
static SKIP = Symbol('skip');
artifacts = [];
dependencies = [];
interpolations = [];
constructor(params, tagSource, astService, location, replacer, displayName, isReferenced, idx, options, context) {
this.tagSource = tagSource;
this.astService = astService;
this.location = location;
this.replacer = replacer;
this.displayName = displayName;
this.isReferenced = isReferenced;
this.idx = idx;
this.options = options;
this.context = context;
validateParams(params, ['callee'], 'Unknown error: a callee param is not specified');
const {
className,
slug
} = getClassNameAndSlug(this.displayName, this.idx, this.options, this.context);
this.className = className;
this.slug = slug;
[[, this.callee]] = params;
}
/**
* A replacement for tag referenced in a template literal.
*/
/**
* A replacement for the tag in evaluation time.
* For example, `css` tag will be replaced with its className,
* whereas `styled` tag will be replaced with an object with metadata.
*/
addDiagnostic(diagnostic) {
this.artifacts.push(createProcessorDiagnosticArtifact({
...diagnostic,
end: diagnostic.end ?? this.location?.end ?? null,
start: diagnostic.start ?? this.location?.start ?? null
}));
}
isValidValue(value) {
return typeof value === 'function' || isCSSable(value) || hasEvalMeta(value);
}
toString() {
return this.tagSourceCode();
}
tagSourceCode() {
if (this.callee.type === 'Identifier') {
return this.callee.name;
}
return generator(this.callee).code;
}
/**
* Perform a replacement for the tag in evaluation time.
* For example, `css` tag will be replaced with its className,
* whereas `styled` tag will be replaced with an object with metadata.
*/
/**
* Perform a replacement for the tag with its runtime version.
* For example, `css` tag will be replaced with its className,
* whereas `styled` tag will be replaced with a component.
* If some parts require evaluated data for render,
* they will be replaced with placeholders.
*/
static SKIP = Symbol("skip");
artifacts = [];
className;
dependencies = [];
interpolations = [];
slug;
callee;
evaluated;
constructor(params, tagSource, astService, location, replacer, displayName, isReferenced, idx, options, context) {
this.tagSource = tagSource;
this.astService = astService;
this.location = location;
this.replacer = replacer;
this.displayName = displayName;
this.isReferenced = isReferenced;
this.idx = idx;
this.options = options;
this.context = context;
validateParams(params, ["callee"], "Unknown error: a callee param is not specified");
const { className, slug } = getClassNameAndSlug(this.displayName, this.idx, this.options, this.context);
this.className = className;
this.slug = slug;
[[, this.callee]] = params;
}
addDiagnostic(diagnostic) {
this.artifacts.push(createProcessorDiagnosticArtifact({
...diagnostic,
end: diagnostic.end ?? this.location?.end ?? null,
start: diagnostic.start ?? this.location?.start ?? null
}));
}
isValidValue(value) {
return typeof value === "function" || isCSSable(value) || hasEvalMeta(value);
}
toString() {
return this.tagSourceCode();
}
tagSourceCode() {
return expressionToCode(this.callee);
}
}
//# sourceMappingURL=BaseProcessor.js.map
//# sourceMappingURL=BaseProcessor.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"BaseProcessor.js","names":["generator","hasEvalMeta","createProcessorDiagnosticArtifact","getClassNameAndSlug","isCSSable","validateParams","BaseProcessor","SKIP","Symbol","artifacts","dependencies","interpolations","constructor","params","tagSource","astService","location","replacer","displayName","isReferenced","idx","options","context","className","slug","callee","addDiagnostic","diagnostic","push","end","start","isValidValue","value","toString","tagSourceCode","type","name","code"],"sources":["../src/BaseProcessor.ts"],"sourcesContent":["/* eslint-disable class-methods-use-this */\nimport type { NodePath, types as t } from '@babel/core';\nimport generator from '@babel/generator';\nimport type {\n Expression,\n Identifier,\n SourceLocation,\n MemberExpression,\n} from '@babel/types';\n\nimport type { Artifact, ExpressionValue } from '@wyw-in-js/shared';\nimport { hasEvalMeta } from '@wyw-in-js/shared';\n\nimport { createProcessorDiagnosticArtifact } from './diagnostics';\nimport type {\n IInterpolation,\n Params,\n ProcessorDiagnostic,\n Value,\n ValueCache,\n} from './types';\nimport getClassNameAndSlug from './utils/getClassNameAndSlug';\nimport { isCSSable } from './utils/toCSS';\nimport type { IFileContext, IOptions } from './utils/types';\nimport { validateParams } from './utils/validateParams';\n\nexport { Expression };\n\nexport type ProcessorParams = ConstructorParameters<typeof BaseProcessor>;\nexport type TailProcessorParams = ProcessorParams extends [Params, ...infer T]\n ? T\n : never;\n\nexport type TagSource = {\n imported: string;\n source: string;\n};\n\nexport abstract class BaseProcessor {\n public static SKIP = Symbol('skip');\n\n public readonly artifacts: Artifact[] = [];\n\n public readonly className: string;\n\n public readonly dependencies: ExpressionValue[] = [];\n\n public interpolations: IInterpolation[] = [];\n\n public readonly slug: string;\n\n protected callee: Identifier | MemberExpression;\n\n protected evaluated:\n | Record<'dependencies' | 'expression', Value[]>\n | undefined;\n\n public constructor(\n params: Params,\n public tagSource: TagSource,\n protected readonly astService: typeof t & {\n addDefaultImport: (source: string, nameHint?: string) => Identifier;\n addNamedImport: (\n name: string,\n source: string,\n nameHint?: string\n ) => Identifier;\n },\n public readonly location: SourceLocation | null,\n protected readonly replacer: (\n replacement: Expression | ((tagPath: NodePath) => Expression),\n isPure: boolean\n ) => void,\n public readonly displayName: string,\n public readonly isReferenced: boolean,\n protected readonly idx: number,\n protected readonly options: IOptions,\n protected readonly context: IFileContext\n ) {\n validateParams(\n params,\n ['callee'],\n 'Unknown error: a callee param is not specified'\n );\n\n const { className, slug } = getClassNameAndSlug(\n this.displayName,\n this.idx,\n this.options,\n this.context\n );\n\n this.className = className;\n this.slug = slug;\n\n [[, this.callee]] = params;\n }\n\n /**\n * A replacement for tag referenced in a template literal.\n */\n public abstract get asSelector(): string;\n\n /**\n * A replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract get value(): Expression;\n\n public addDiagnostic(diagnostic: ProcessorDiagnostic): void {\n this.artifacts.push(\n createProcessorDiagnosticArtifact({\n ...diagnostic,\n end: diagnostic.end ?? this.location?.end ?? null,\n start: diagnostic.start ?? this.location?.start ?? null,\n })\n );\n }\n\n public isValidValue(value: unknown): value is Value {\n return (\n typeof value === 'function' || isCSSable(value) || hasEvalMeta(value)\n );\n }\n\n public toString(): string {\n return this.tagSourceCode();\n }\n\n protected tagSourceCode(): string {\n if (this.callee.type === 'Identifier') {\n return this.callee.name;\n }\n\n return generator(this.callee).code;\n }\n\n public abstract build(values: ValueCache): void;\n\n /**\n * Perform a replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract doEvaltimeReplacement(): void;\n\n /**\n * Perform a replacement for the tag with its runtime version.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with a component.\n * If some parts require evaluated data for render,\n * they will be replaced with placeholders.\n */\n public abstract doRuntimeReplacement(): void;\n}\n"],"mappings":"AAAA;;AAEA,OAAOA,SAAS,MAAM,kBAAkB;AASxC,SAASC,WAAW,QAA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ACnB,AAAmB,SACnB,AAAmB,SACnB;EAZO;EACY;EACH;EACG;EAIH;EACA;EACG;EACA;EACA;AAEnB,iBACE,QACA,CAAC,SAAS,EACV,iDACD;EAED,MAAM,EAAE,WAAW,SAAS,oBAC1B,KAAK,aACL,KAAK,KACL,KAAK,SACL,KAAK,QACN;AAED,OAAK,YAAY;AACjB,OAAK,OAAO;AAEZ,GAAC,GAAG,KAAK,WAAW;;CAetB,AAAO,cAAc,YAAuC;AAC1D,OAAK,UAAU,KACb,kCAAkC;GAChC,GAAG;GACH,KAAK,WAAW,OAAO,KAAK,UAAU,OAAO;GAC7C,OAAO,WAAW,SAAS,KAAK,UAAU,SAAS;GACpD,CAAC,CACH;;CAGH,AAAO,aAAa,OAAgC;AAClD,SACE,OAAO,UAAU,cAAc,UAAU,MAAM,IAAI,YAAY,MAAM;;CAIzE,AAAO,WAAmB;AACxB,SAAO,KAAK,eAAe;;CAG7B,AAAU,gBAAwB;AAChC,SAAO,iBAAiB,KAAK,OAAO","names":[],"sources":["../src/BaseProcessor.ts"],"version":3,"sourcesContent":["/* eslint-disable class-methods-use-this */\nimport type { Artifact, ExpressionValue } from '@wyw-in-js/shared';\nimport { hasEvalMeta } from '@wyw-in-js/shared';\n\nimport type {\n AstService,\n Expression,\n Identifier,\n MemberExpression,\n SourceLocation,\n} from './ast';\nimport { expressionToCode } from './ast';\nimport { createProcessorDiagnosticArtifact } from './diagnostics';\nimport type {\n IInterpolation,\n Params,\n ProcessorDiagnostic,\n Value,\n ValueCache,\n} from './types';\nimport getClassNameAndSlug from './utils/getClassNameAndSlug';\nimport { isCSSable } from './utils/toCSS';\nimport type { IFileContext, IOptions } from './utils/types';\nimport { validateParams } from './utils/validateParams';\n\nexport type { Expression };\n\nexport type ProcessorParams = ConstructorParameters<typeof BaseProcessor>;\nexport type TailProcessorParams = ProcessorParams extends [Params, ...infer T]\n ? T\n : never;\n\nexport type TagSource = {\n imported: string;\n source: string;\n};\n\nexport abstract class BaseProcessor {\n public static SKIP = Symbol('skip');\n\n public readonly artifacts: Artifact[] = [];\n\n public readonly className: string;\n\n public readonly dependencies: ExpressionValue[] = [];\n\n public interpolations: IInterpolation[] = [];\n\n public readonly slug: string;\n\n protected callee: Identifier | MemberExpression;\n\n protected evaluated:\n | Record<'dependencies' | 'expression', Value[]>\n | undefined;\n\n public constructor(\n params: Params,\n public tagSource: TagSource,\n protected readonly astService: AstService,\n public readonly location: SourceLocation | null,\n protected readonly replacer: (\n replacement: Expression | ((tagPath: unknown) => Expression),\n isPure: boolean\n ) => void,\n public readonly displayName: string,\n public readonly isReferenced: boolean,\n protected readonly idx: number,\n protected readonly options: IOptions,\n protected readonly context: IFileContext\n ) {\n validateParams(\n params,\n ['callee'],\n 'Unknown error: a callee param is not specified'\n );\n\n const { className, slug } = getClassNameAndSlug(\n this.displayName,\n this.idx,\n this.options,\n this.context\n );\n\n this.className = className;\n this.slug = slug;\n\n [[, this.callee]] = params;\n }\n\n /**\n * A replacement for tag referenced in a template literal.\n */\n public abstract get asSelector(): string;\n\n /**\n * A replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract get value(): Expression;\n\n public addDiagnostic(diagnostic: ProcessorDiagnostic): void {\n this.artifacts.push(\n createProcessorDiagnosticArtifact({\n ...diagnostic,\n end: diagnostic.end ?? this.location?.end ?? null,\n start: diagnostic.start ?? this.location?.start ?? null,\n })\n );\n }\n\n public isValidValue(value: unknown): value is Value {\n return (\n typeof value === 'function' || isCSSable(value) || hasEvalMeta(value)\n );\n }\n\n public toString(): string {\n return this.tagSourceCode();\n }\n\n protected tagSourceCode(): string {\n return expressionToCode(this.callee);\n }\n\n public abstract build(values: ValueCache): void;\n\n /**\n * Perform a replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract doEvaltimeReplacement(): void;\n\n /**\n * Perform a replacement for the tag with its runtime version.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with a component.\n * If some parts require evaluated data for render,\n * they will be replaced with placeholders.\n */\n public abstract doRuntimeReplacement(): void;\n}\n"],"file":"BaseProcessor.js"}

@@ -1,4 +0,4 @@

export const PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic';
export const createProcessorDiagnosticArtifact = diagnostic => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];
export const isProcessorDiagnosticArtifact = artifact => artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;
//# sourceMappingURL=diagnostics.js.map
export const PROCESSOR_DIAGNOSTIC_ARTIFACT = "wyw-in-js:diagnostic";
export const createProcessorDiagnosticArtifact = (diagnostic) => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];
export const isProcessorDiagnosticArtifact = (artifact) => artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;
//# sourceMappingURL=diagnostics.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"diagnostics.js","names":["PROCESSOR_DIAGNOSTIC_ARTIFACT","createProcessorDiagnosticArtifact","diagnostic","isProcessorDiagnosticArtifact","artifact"],"sources":["../src/diagnostics.ts"],"sourcesContent":["import type { Artifact } from '@wyw-in-js/shared';\n\nimport type { ProcessorDiagnostic } from './types';\n\nexport const PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic' as const;\n\nexport type ProcessorDiagnosticArtifact = [\n name: typeof PROCESSOR_DIAGNOSTIC_ARTIFACT,\n data: ProcessorDiagnostic,\n];\n\nexport const createProcessorDiagnosticArtifact = (\n diagnostic: ProcessorDiagnostic\n): ProcessorDiagnosticArtifact => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];\n\nexport const isProcessorDiagnosticArtifact = (\n artifact: Artifact\n): artifact is ProcessorDiagnosticArtifact =>\n artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;\n"],"mappings":"AAIA,OAAO,MAAMA,6BAA6B,GAAG,sBAA+B;AAO5E,OAAO,MAAMC,iCAAiC,GAC5CC,UAA+B,IACC,CAACF,6BAA6B,EAAEE,UAAU,CAAC;AAE7E,OAAO,MAAMC,6BAA6B,GACxCC,QAAkB,IAElBA,QAAQ,CAAC,CAAC,CAAC,KAAKJ,6BAA6B","ignoreList":[]}
{"mappings":"AAIA,OAAO,MAAM,gCAAgC;AAO7C,OAAO,MAAM,qCACX,eACgC,CAAC,+BAA+B,WAAW;AAE7E,OAAO,MAAM,iCACX,aAEA,SAAS,OAAO","names":[],"sources":["../src/diagnostics.ts"],"version":3,"sourcesContent":["import type { Artifact } from '@wyw-in-js/shared';\n\nimport type { ProcessorDiagnostic } from './types';\n\nexport const PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic' as const;\n\nexport type ProcessorDiagnosticArtifact = [\n name: typeof PROCESSOR_DIAGNOSTIC_ARTIFACT,\n data: ProcessorDiagnostic,\n];\n\nexport const createProcessorDiagnosticArtifact = (\n diagnostic: ProcessorDiagnostic\n): ProcessorDiagnosticArtifact => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];\n\nexport const isProcessorDiagnosticArtifact = (\n artifact: Artifact\n): artifact is ProcessorDiagnosticArtifact =>\n artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;\n"],"file":"diagnostics.js"}

@@ -1,8 +0,9 @@

export { BaseProcessor } from './BaseProcessor';
export { createProcessorDiagnosticArtifact, isProcessorDiagnosticArtifact, PROCESSOR_DIAGNOSTIC_ARTIFACT } from './diagnostics';
export * from './types';
export { buildSlug } from './utils/buildSlug';
export { isValidParams, validateParams } from './utils/validateParams';
export { TaggedTemplateProcessor } from './TaggedTemplateProcessor';
export { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';
//# sourceMappingURL=index.js.map
export { BaseProcessor } from "./BaseProcessor.js";
export { expressionToCode } from "./ast.js";
export { createProcessorDiagnosticArtifact, isProcessorDiagnosticArtifact, PROCESSOR_DIAGNOSTIC_ARTIFACT } from "./diagnostics.js";
export * from "./types.js";
export { buildSlug } from "./utils/buildSlug.js";
export { isValidParams, validateParams } from "./utils/validateParams.js";
export { TaggedTemplateProcessor } from "./TaggedTemplateProcessor.js";
export { toValidCSSIdentifier } from "./utils/toValidCSSIdentifier.js";
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"index.js","names":["BaseProcessor","createProcessorDiagnosticArtifact","isProcessorDiagnosticArtifact","PROCESSOR_DIAGNOSTIC_ARTIFACT","buildSlug","isValidParams","validateParams","TaggedTemplateProcessor","toValidCSSIdentifier"],"sources":["../src/index.ts"],"sourcesContent":["export { BaseProcessor } from './BaseProcessor';\nexport {\n createProcessorDiagnosticArtifact,\n isProcessorDiagnosticArtifact,\n PROCESSOR_DIAGNOSTIC_ARTIFACT,\n} from './diagnostics';\nexport type { ProcessorDiagnosticArtifact } from './diagnostics';\nexport type {\n Expression,\n TagSource,\n ProcessorParams,\n TailProcessorParams,\n} from './BaseProcessor';\nexport * from './types';\nexport { buildSlug } from './utils/buildSlug';\nexport type { IOptions, IFileContext } from './utils/types';\nexport { isValidParams, validateParams } from './utils/validateParams';\nexport type { MapParams, ParamConstraints } from './utils/validateParams';\nexport { TaggedTemplateProcessor } from './TaggedTemplateProcessor';\nexport { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,iBAAiB;AAC/C,SACEC,iCAAiC,EACjCC,6BAA6B,EAC7BC,6BAA6B,QACxB,eAAe;AAQtB,cAAc,SAAS;AACvB,SAASC,SAAS,QAAQ,mBAAmB;AAE7C,SAASC,aAAa,EAAEC,cAAc,QAAQ,wBAAwB;AAEtE,SAASC,uBAAuB,QAAQ,2BAA2B;AACnE,SAASC,oBAAoB,QAAQ,8BAA8B","ignoreList":[]}
{"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SACE,mCACA,+BACA,qCACK;AA0BP,cAAc;AACd,SAAS,iBAAiB;AAE1B,SAAS,eAAe,sBAAsB;AAE9C,SAAS,+BAA+B;AACxC,SAAS,4BAA4B","names":[],"sources":["../src/index.ts"],"version":3,"sourcesContent":["export { BaseProcessor } from './BaseProcessor';\nexport { expressionToCode } from './ast';\nexport {\n createProcessorDiagnosticArtifact,\n isProcessorDiagnosticArtifact,\n PROCESSOR_DIAGNOSTIC_ARTIFACT,\n} from './diagnostics';\nexport type { ProcessorDiagnosticArtifact } from './diagnostics';\nexport type {\n ArrayExpression,\n ArrowFunctionExpression,\n AstService,\n BaseAstNode,\n BlockStatement,\n BooleanLiteral,\n CallExpression,\n Expression,\n Identifier,\n MemberExpression,\n NullLiteral,\n NumericLiteral,\n ObjectExpression,\n ObjectProperty,\n SourceLocation,\n StringLiteral,\n TemplateElement,\n} from './ast';\nexport type {\n ProcessorParams,\n TagSource,\n TailProcessorParams,\n} from './BaseProcessor';\nexport * from './types';\nexport { buildSlug } from './utils/buildSlug';\nexport type { IOptions, IFileContext } from './utils/types';\nexport { isValidParams, validateParams } from './utils/validateParams';\nexport type { MapParams, ParamConstraints } from './utils/validateParams';\nexport { TaggedTemplateProcessor } from './TaggedTemplateProcessor';\nexport { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';\n"],"file":"index.js"}

@@ -1,43 +0,34 @@

import { ValueType } from '@wyw-in-js/shared';
import { BaseProcessor } from './BaseProcessor';
import templateProcessor from './utils/templateProcessor';
import { validateParams } from './utils/validateParams';
import { ValueType } from "@wyw-in-js/shared";
import { BaseProcessor } from "./BaseProcessor.js";
import templateProcessor from "./utils/templateProcessor.js";
import { validateParams } from "./utils/validateParams.js";
export class TaggedTemplateProcessor extends BaseProcessor {
#template;
constructor(params, ...args) {
// Should have at least two params and the first one should be a callee.
validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
validateParams(params, ['callee', 'template'], 'Invalid usage of template tag');
const [tag, [, template]] = params;
super([tag], ...args);
template.forEach(element => {
if ('kind' in element && element.kind !== ValueType.FUNCTION) {
this.dependencies.push(element);
}
});
this.#template = template;
}
build(values) {
if (this.artifacts.length > 0) {
// FIXME: why it was called twice?
throw new Error('Tag is already built');
}
const artifact = templateProcessor(this, this.#template, values, this.options.variableNameConfig);
if (artifact) {
this.artifacts.push(['css', artifact]);
}
}
toString() {
return `${super.toString()}\`…\``;
}
/**
* It is called for each resolved expression in a template literal.
* @param node
* @param precedingCss
* @param source
* @param unit
* @return chunk of CSS that should be added to extracted CSS
*/
#template;
constructor(params, ...args) {
// Should have at least two params and the first one should be a callee.
validateParams(params, ["callee", "..."], TaggedTemplateProcessor.SKIP);
validateParams(params, ["callee", "template"], "Invalid usage of template tag");
const [tag, [, template]] = params;
super([tag], ...args);
template.forEach((element) => {
if ("kind" in element && element.kind !== ValueType.FUNCTION) {
this.dependencies.push(element);
}
});
this.#template = template;
}
build(values) {
if (this.artifacts.length > 0) {
// FIXME: why it was called twice?
throw new Error("Tag is already built");
}
const artifact = templateProcessor(this, this.#template, values, this.options.variableNameConfig);
if (artifact) {
this.artifacts.push(["css", artifact]);
}
}
toString() {
return `${super.toString()}\`…\``;
}
}
//# sourceMappingURL=TaggedTemplateProcessor.js.map
//# sourceMappingURL=TaggedTemplateProcessor.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"TaggedTemplateProcessor.js","names":["ValueType","BaseProcessor","templateProcessor","validateParams","TaggedTemplateProcessor","template","constructor","params","args","SKIP","tag","forEach","element","kind","FUNCTION","dependencies","push","build","values","artifacts","length","Error","artifact","options","variableNameConfig","toString"],"sources":["../src/TaggedTemplateProcessor.ts"],"sourcesContent":["import type { TemplateElement, Expression, SourceLocation } from '@babel/types';\n\nimport type { ExpressionValue } from '@wyw-in-js/shared';\nimport { ValueType } from '@wyw-in-js/shared';\n\nimport type { TailProcessorParams } from './BaseProcessor';\nimport { BaseProcessor } from './BaseProcessor';\nimport type { ValueCache, Rules, Params } from './types';\nimport templateProcessor from './utils/templateProcessor';\nimport { validateParams } from './utils/validateParams';\n\nexport abstract class TaggedTemplateProcessor extends BaseProcessor {\n readonly #template: (TemplateElement | ExpressionValue)[];\n\n protected constructor(params: Params, ...args: TailProcessorParams) {\n // Should have at least two params and the first one should be a callee.\n validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);\n\n validateParams(\n params,\n ['callee', 'template'],\n 'Invalid usage of template tag'\n );\n const [tag, [, template]] = params;\n\n super([tag], ...args);\n\n template.forEach((element) => {\n if ('kind' in element && element.kind !== ValueType.FUNCTION) {\n this.dependencies.push(element);\n }\n });\n\n this.#template = template;\n }\n\n public override build(values: ValueCache) {\n if (this.artifacts.length > 0) {\n // FIXME: why it was called twice?\n throw new Error('Tag is already built');\n }\n\n const artifact = templateProcessor(\n this,\n this.#template,\n values,\n this.options.variableNameConfig\n );\n if (artifact) {\n this.artifacts.push(['css', artifact]);\n }\n }\n\n public override toString(): string {\n return `${super.toString()}\\`…\\``;\n }\n\n /**\n * It is called for each resolved expression in a template literal.\n * @param node\n * @param precedingCss\n * @param source\n * @param unit\n * @return chunk of CSS that should be added to extracted CSS\n */\n public abstract addInterpolation(\n node: Expression,\n precedingCss: string,\n source: string,\n unit?: string\n ): string;\n\n public abstract extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): Rules;\n}\n"],"mappings":"AAGA,SAASA,SAAS,QAAQ,mBAAmB;AAG7C,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,OAAOC,iBAAiB,MAAM,2BAA2B;AACzD,SAASC,cAAc,QAAQ,wBAAwB;AAEvD,OAAO,MAAeC,uBAAuB,SAASH,aAAa,CAAC;EACzD,CAACI,QAAQ;EAERC,WAAWA,CAACC,MAAc,EAAE,GAAGC,IAAyB,EAAE;IAClE;IACAL,cAAc,CAACI,MAAM,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAEH,uBAAuB,CAACK,IAAI,CAAC;IAEvEN,cAAc,CACZI,MAAM,EACN,CAAC,QAAQ,EAAE,UAAU,CAAC,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WAAW,EACtB,gCACD;EACD,MAAM,CAAC,KAAK,GAAG,aAAa;AAE5B,QAAM,CAAC,IAAI,EAAE,GAAG,KAAK;AAErB,WAAS,SAAS,YAAY;AAC5B,OAAI,UAAU,WAAW,QAAQ,SAAS,UAAU,UAAU;AAC5D,SAAK,aAAa,KAAK,QAAQ;;IAEjC;AAEF,QAAKA,WAAY;;CAGnB,AAAgB,MAAM,QAAoB;AACxC,MAAI,KAAK,UAAU,SAAS,GAAG;;AAE7B,SAAM,IAAI,MAAM,uBAAuB;;EAGzC,MAAM,WAAW,kBACf,MACA,MAAKA,UACL,QACA,KAAK,QAAQ,mBACd;AACD,MAAI,UAAU;AACZ,QAAK,UAAU,KAAK,CAAC,OAAO,SAAS,CAAC;;;CAI1C,AAAgB,WAAmB;AACjC,SAAO,GAAG,MAAM,UAAU,CAAC","names":["#template"],"sources":["../src/TaggedTemplateProcessor.ts"],"version":3,"sourcesContent":["import type { ExpressionValue } from '@wyw-in-js/shared';\nimport { ValueType } from '@wyw-in-js/shared';\n\nimport type { Expression, SourceLocation, TemplateElement } from './ast';\nimport type { TailProcessorParams } from './BaseProcessor';\nimport { BaseProcessor } from './BaseProcessor';\nimport type { ValueCache, Rules, Params } from './types';\nimport templateProcessor from './utils/templateProcessor';\nimport { validateParams } from './utils/validateParams';\n\nexport abstract class TaggedTemplateProcessor extends BaseProcessor {\n readonly #template: (TemplateElement | ExpressionValue)[];\n\n protected constructor(params: Params, ...args: TailProcessorParams) {\n // Should have at least two params and the first one should be a callee.\n validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);\n\n validateParams(\n params,\n ['callee', 'template'],\n 'Invalid usage of template tag'\n );\n const [tag, [, template]] = params;\n\n super([tag], ...args);\n\n template.forEach((element) => {\n if ('kind' in element && element.kind !== ValueType.FUNCTION) {\n this.dependencies.push(element);\n }\n });\n\n this.#template = template;\n }\n\n public override build(values: ValueCache) {\n if (this.artifacts.length > 0) {\n // FIXME: why it was called twice?\n throw new Error('Tag is already built');\n }\n\n const artifact = templateProcessor(\n this,\n this.#template,\n values,\n this.options.variableNameConfig\n );\n if (artifact) {\n this.artifacts.push(['css', artifact]);\n }\n }\n\n public override toString(): string {\n return `${super.toString()}\\`…\\``;\n }\n\n /**\n * It is called for each resolved expression in a template literal.\n * @param node\n * @param precedingCss\n * @param source\n * @param unit\n * @return chunk of CSS that should be added to extracted CSS\n */\n public abstract addInterpolation(\n node: Expression,\n precedingCss: string,\n source: string,\n unit?: string\n ): string;\n\n public abstract extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): Rules;\n}\n"],"file":"TaggedTemplateProcessor.js"}
export {};
//# sourceMappingURL=types.js.map
//# sourceMappingURL=types.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n Expression,\n Identifier,\n TemplateElement,\n MemberExpression,\n} from '@babel/types';\n\nimport type { ExpressionValue, Location, WYWEvalMeta } from '@wyw-in-js/shared';\n\nexport type CSSPropertyValue = string | number;\n\nexport type ObjectWithSelectors = {\n [key: string]:\n | ObjectWithSelectors\n | CSSPropertyValue\n | (ObjectWithSelectors | CSSPropertyValue)[];\n};\n\nexport type CSSable = ObjectWithSelectors[string];\n\nexport type Value = (() => void) | WYWEvalMeta | CSSable;\n\nexport type ValueCache = Map<string | number | boolean | null, unknown>;\n\nexport interface ICSSRule {\n atom?: boolean;\n className: string;\n cssText: string;\n displayName: string;\n start: Location | null | undefined;\n}\n\nexport interface IInterpolation {\n id: string;\n node: Expression;\n source: string;\n unit: string;\n}\n\nexport type ProcessorDiagnosticSeverity = 'error' | 'warning';\n\nexport type ProcessorDiagnostic = {\n category: string;\n end?: Location | null;\n message: string;\n severity: ProcessorDiagnosticSeverity;\n start?: Location | null;\n};\n\nexport type Rules = Record<string, ICSSRule>;\n\nexport type CalleeParam = readonly ['callee', Identifier | MemberExpression];\nexport type CallParam = readonly ['call', ...ExpressionValue[]];\nexport type MemberParam = readonly ['member', string];\nexport type TemplateParam = readonly [\n 'template',\n (TemplateElement | ExpressionValue)[],\n];\n\nexport type Param = CalleeParam | CallParam | MemberParam | TemplateParam;\nexport type Params = readonly Param[];\n"],"mappings":"","ignoreList":[]}
{"mappings":"","names":[],"sources":["../src/types.ts"],"version":3,"sourcesContent":["import type { ExpressionValue, Location, WYWEvalMeta } from '@wyw-in-js/shared';\n\nimport type {\n Expression,\n Identifier,\n MemberExpression,\n TemplateElement,\n} from './ast';\n\nexport type CSSPropertyValue = string | number;\n\nexport type ObjectWithSelectors = {\n [key: string]:\n | ObjectWithSelectors\n | CSSPropertyValue\n | (ObjectWithSelectors | CSSPropertyValue)[];\n};\n\nexport type CSSable = ObjectWithSelectors[string];\n\nexport type Value = (() => void) | WYWEvalMeta | CSSable;\n\nexport type ValueCache = Map<string | number | boolean | null, unknown>;\n\nexport interface ICSSRule {\n atom?: boolean;\n className: string;\n cssText: string;\n displayName: string;\n start: Location | null | undefined;\n}\n\nexport interface IInterpolation {\n id: string;\n node: Expression;\n source: string;\n unit: string;\n}\n\nexport type ProcessorDiagnosticSeverity = 'error' | 'warning';\n\nexport type ProcessorDiagnostic = {\n category: string;\n end?: Location | null;\n message: string;\n severity: ProcessorDiagnosticSeverity;\n start?: Location | null;\n};\n\nexport type Rules = Record<string, ICSSRule>;\n\nexport type CalleeParam = readonly ['callee', Identifier | MemberExpression];\nexport type CallParam = readonly ['call', ...ExpressionValue[]];\nexport type MemberParam = readonly ['member', string];\nexport type TemplateParam = readonly [\n 'template',\n (TemplateElement | ExpressionValue)[],\n];\n\nexport type Param = CalleeParam | CallParam | MemberParam | TemplateParam;\nexport type Params = readonly Param[];\n"],"file":"types.js"}
const PLACEHOLDER = /\[(.*?)]/g;
const isValidArgName = (key, args) => key in args;
export function buildSlug(pattern, args) {
return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : '');
return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : "");
}
//# sourceMappingURL=buildSlug.js.map
//# sourceMappingURL=buildSlug.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"buildSlug.js","names":["PLACEHOLDER","isValidArgName","key","args","buildSlug","pattern","replace","_","name","toString"],"sources":["../../src/utils/buildSlug.ts"],"sourcesContent":["const PLACEHOLDER = /\\[(.*?)]/g;\n\nconst isValidArgName = <TArgs extends Record<string, { toString(): string }>>(\n key: string | number | symbol,\n args: TArgs\n): key is keyof TArgs => key in args;\n\nexport function buildSlug<TArgs extends Record<string, { toString(): string }>>(\n pattern: string,\n args: TArgs\n) {\n return pattern.replace(PLACEHOLDER, (_, name: string) =>\n isValidArgName(name, args) ? args[name].toString() : ''\n );\n}\n"],"mappings":"AAAA,MAAMA,WAAW,GAAG,WAAW;AAE/B,MAAMC,cAAc,GAAGA,CACrBC,GAA6B,EAC7BC,IAAW,KACYD,GAAG,IAAIC,IAAI;AAEpC,OAAO,SAASC,SAASA,CACvBC,OAAe,EACfF,IAAW,EACX;EACA,OAAOE,OAAO,CAACC,OAAO,CAACN,WAAW,EAAE,CAACO,CAAC,EAAEC,IAAY,KAClDP,cAAc,CAACO,IAAI,EAAEL,IAAI,CAAC,GAAGA,IAAI,CAACK,IAAI,CAAC,CAACC,QAAQ,CAAC,CAAC,GAAG,EACvD,CAAC;AACH","ignoreList":[]}
{"mappings":"AAAA,MAAM,cAAc;AAEpB,MAAM,kBACJ,KACA,SACuB,OAAO;AAEhC,OAAO,SAAS,UACd,SACA,MACA;AACA,QAAO,QAAQ,QAAQ,cAAc,GAAG,SACtC,eAAe,MAAM,KAAK,GAAG,KAAK,MAAM,UAAU,GAAG,GACtD","names":[],"sources":["../../src/utils/buildSlug.ts"],"version":3,"sourcesContent":["const PLACEHOLDER = /\\[(.*?)]/g;\n\nconst isValidArgName = <TArgs extends Record<string, { toString(): string }>>(\n key: string | number | symbol,\n args: TArgs\n): key is keyof TArgs => key in args;\n\nexport function buildSlug<TArgs extends Record<string, { toString(): string }>>(\n pattern: string,\n args: TArgs\n) {\n return pattern.replace(PLACEHOLDER, (_, name: string) =>\n isValidArgName(name, args) ? args[name].toString() : ''\n );\n}\n"],"file":"buildSlug.js"}

@@ -1,43 +0,40 @@

import { basename, dirname, extname, relative, sep, posix } from 'path';
import { logger, slugify } from '@wyw-in-js/shared';
import { buildSlug } from './buildSlug';
import { toValidCSSIdentifier } from './toValidCSSIdentifier';
import { basename, dirname, extname, relative, sep, posix } from "path";
import { logger, slugify } from "@wyw-in-js/shared";
import { buildSlug } from "./buildSlug.js";
import { toValidCSSIdentifier } from "./toValidCSSIdentifier.js";
export default function getClassNameAndSlug(displayName, idx, options, context) {
const relativeFilename = (context.root && context.filename ? relative(context.root, context.filename) : context.filename ?? 'unknown').replace(/\\/g, posix.sep);
// Custom properties need to start with a letter, so we prefix the slug
// Also use append the index of the class to the filename for uniqueness in the file
const slug = toValidCSSIdentifier(`${displayName.charAt(0).toLowerCase()}${slugify(`${relativeFilename}:${idx}`)}`);
// Collect some useful replacement patterns from the filename
// Available variables for the square brackets used in `classNameSlug` options
const ext = extname(relativeFilename);
const slugVars = {
hash: slug,
title: displayName,
index: idx,
file: relativeFilename,
ext,
name: basename(relativeFilename, ext),
dir: dirname(relativeFilename).split(sep).pop()
};
let className = options.displayName ? `${toValidCSSIdentifier(displayName)}_${slug}` : slug;
// The className can be defined by the user either as fn or a string
if (typeof options.classNameSlug === 'function') {
try {
className = toValidCSSIdentifier(options.classNameSlug(slug, displayName, slugVars));
} catch {
throw new Error('classNameSlug option must return a string');
}
}
if (typeof options.classNameSlug === 'string') {
className = toValidCSSIdentifier(buildSlug(options.classNameSlug, slugVars));
}
logger.extend('template-parse:generated-meta')(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
return {
className,
slug
};
const relativeFilename = (context.root && context.filename ? relative(context.root, context.filename) : context.filename ?? "unknown").replace(/\\/g, posix.sep);
// Custom properties need to start with a letter, so we prefix the slug
// Also use append the index of the class to the filename for uniqueness in the file
const slug = toValidCSSIdentifier(`${displayName.charAt(0).toLowerCase()}${slugify(`${relativeFilename}:${idx}`)}`);
// Collect some useful replacement patterns from the filename
// Available variables for the square brackets used in `classNameSlug` options
const ext = extname(relativeFilename);
const slugVars = {
hash: slug,
title: displayName,
index: idx,
file: relativeFilename,
ext,
name: basename(relativeFilename, ext),
dir: dirname(relativeFilename).split(sep).pop()
};
let className = options.displayName ? `${toValidCSSIdentifier(displayName)}_${slug}` : slug;
// The className can be defined by the user either as fn or a string
if (typeof options.classNameSlug === "function") {
try {
className = toValidCSSIdentifier(options.classNameSlug(slug, displayName, slugVars));
} catch {
throw new Error("classNameSlug option must return a string");
}
}
if (typeof options.classNameSlug === "string") {
className = toValidCSSIdentifier(buildSlug(options.classNameSlug, slugVars));
}
logger.extend("template-parse:generated-meta")(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
return {
className,
slug
};
}
//# sourceMappingURL=getClassNameAndSlug.js.map
//# sourceMappingURL=getClassNameAndSlug.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"getClassNameAndSlug.js","names":["basename","dirname","extname","relative","sep","posix","logger","slugify","buildSlug","toValidCSSIdentifier","getClassNameAndSlug","displayName","idx","options","context","relativeFilename","root","filename","replace","slug","charAt","toLowerCase","ext","slugVars","hash","title","index","file","name","dir","split","pop","className","classNameSlug","Error","extend"],"sources":["../../src/utils/getClassNameAndSlug.ts"],"sourcesContent":["import { basename, dirname, extname, relative, sep, posix } from 'path';\n\nimport type { ClassNameSlugVars } from '@wyw-in-js/shared';\nimport { logger, slugify } from '@wyw-in-js/shared';\n\nimport { buildSlug } from './buildSlug';\nimport { toValidCSSIdentifier } from './toValidCSSIdentifier';\nimport type { IFileContext, IOptions } from './types';\n\nexport default function getClassNameAndSlug(\n displayName: string,\n idx: number,\n options: IOptions,\n context: IFileContext\n): { className: string; slug: string } {\n const relativeFilename = (\n context.root && context.filename\n ? relative(context.root, context.filename)\n : context.filename ?? 'unknown'\n ).replace(/\\\\/g, posix.sep);\n\n // Custom properties need to start with a letter, so we prefix the slug\n // Also use append the index of the class to the filename for uniqueness in the file\n const slug = toValidCSSIdentifier(\n `${displayName.charAt(0).toLowerCase()}${slugify(\n `${relativeFilename}:${idx}`\n )}`\n );\n\n // Collect some useful replacement patterns from the filename\n // Available variables for the square brackets used in `classNameSlug` options\n const ext = extname(relativeFilename);\n const slugVars: ClassNameSlugVars = {\n hash: slug,\n title: displayName,\n index: idx,\n file: relativeFilename,\n ext,\n name: basename(relativeFilename, ext),\n dir: dirname(relativeFilename).split(sep).pop() as string,\n };\n\n let className = options.displayName\n ? `${toValidCSSIdentifier(displayName!)}_${slug!}`\n : slug!;\n\n // The className can be defined by the user either as fn or a string\n if (typeof options.classNameSlug === 'function') {\n try {\n className = toValidCSSIdentifier(\n options.classNameSlug(slug, displayName, slugVars)\n );\n } catch {\n throw new Error('classNameSlug option must return a string');\n }\n }\n\n if (typeof options.classNameSlug === 'string') {\n className = toValidCSSIdentifier(\n buildSlug(options.classNameSlug, slugVars)\n );\n }\n\n logger.extend('template-parse:generated-meta')(\n `slug: ${slug}, displayName: ${displayName}, className: ${className}`\n );\n\n return { className, slug };\n}\n"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,OAAO,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,GAAG,EAAEC,KAAK,QAAQ,MAAM;AAGvE,SAASC,MAAM,EAAEC,OAAO,QAAQ,mBAAmB;AAEnD,SAASC,SAAS,QAAQ,aAAa;AACvC,SAASC,oBAAoB,QAAQ,wBAAwB;AAG7D,eAAe,SAASC,mBAAmBA,CACzCC,WAAmB,EACnBC,GAAW,EACXC,OAAiB,EACjBC,OAAqB,EACgB;EACrC,MAAMC,gBAAgB,GAAG,CACvBD,OAAO,CAACE,IAAI,IAAIF,OAAO,CAACG,QAAQ,GAC5Bd,QAAQ,CAACW,OAAO,CAACE,IAAI,EAAEF,OAAO,CAACG,QAAQ,CAAC,GACxCH,OAAO,CAACG,QAAQ,IAAI,SAAS,EACjCC,OAAO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IAAI,kBAAkBR,WAAW,gBAAgBqB,SAAS,EACrE,CAAC;EAED,OAAO;IAAEA,SAAS;IAAEb;EAAK,CAAC;AAC5B","ignoreList":[]}
{"mappings":"AAAA,SAAS,UAAU,SAAS,SAAS,UAAU,KAAK,aAAa;AAGjE,SAAS,QAAQ,eAAe;AAEhC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AAGrC,eAAe,SAAS,oBACtB,aACA,KACA,SACA,SACqC;CACrC,MAAM,oBACJ,QAAQ,QAAQ,QAAQ,WACpB,SAAS,QAAQ,MAAM,QAAQ,SAAS,GACxC,QAAQ,YAAY,WACxB,QAAQ,OAAO,MAAM,IAAI;;;CAI3B,MAAM,OAAO,qBACX,GAAG,YAAY,OAAO,EAAE,CAAC,aAAa,GAAG,QACvC,GAAG,iBAAiB,GAAG,MACxB,GACF;;;CAID,MAAM,MAAM,QAAQ,iBAAiB;CACrC,MAAM,WAA8B;EAClC,MAAM;EACN,OAAO;EACP,OAAO;EACP,MAAM;EACN;EACA,MAAM,SAAS,kBAAkB,IAAI;EACrC,KAAK,QAAQ,iBAAiB,CAAC,MAAM,IAAI,CAAC,KAAK;EAChD;CAED,IAAI,YAAY,QAAQ,cACpB,GAAG,qBAAqB,YAAa,CAAC,GAAG,SACzC;;AAGJ,KAAI,OAAO,QAAQ,kBAAkB,YAAY;AAC/C,MAAI;AACF,eAAY,qBACV,QAAQ,cAAc,MAAM,aAAa,SAAS,CACnD;UACK;AACN,SAAM,IAAI,MAAM,4CAA4C;;;AAIhE,KAAI,OAAO,QAAQ,kBAAkB,UAAU;AAC7C,cAAY,qBACV,UAAU,QAAQ,eAAe,SAAS,CAC3C;;AAGH,QAAO,OAAO,gCAAgC,CAC5C,SAAS,KAAK,iBAAiB,YAAY,eAAe,YAC3D;AAED,QAAO;EAAE;EAAW;EAAM","names":[],"sources":["../../src/utils/getClassNameAndSlug.ts"],"version":3,"sourcesContent":["import { basename, dirname, extname, relative, sep, posix } from 'path';\n\nimport type { ClassNameSlugVars } from '@wyw-in-js/shared';\nimport { logger, slugify } from '@wyw-in-js/shared';\n\nimport { buildSlug } from './buildSlug';\nimport { toValidCSSIdentifier } from './toValidCSSIdentifier';\nimport type { IFileContext, IOptions } from './types';\n\nexport default function getClassNameAndSlug(\n displayName: string,\n idx: number,\n options: IOptions,\n context: IFileContext\n): { className: string; slug: string } {\n const relativeFilename = (\n context.root && context.filename\n ? relative(context.root, context.filename)\n : context.filename ?? 'unknown'\n ).replace(/\\\\/g, posix.sep);\n\n // Custom properties need to start with a letter, so we prefix the slug\n // Also use append the index of the class to the filename for uniqueness in the file\n const slug = toValidCSSIdentifier(\n `${displayName.charAt(0).toLowerCase()}${slugify(\n `${relativeFilename}:${idx}`\n )}`\n );\n\n // Collect some useful replacement patterns from the filename\n // Available variables for the square brackets used in `classNameSlug` options\n const ext = extname(relativeFilename);\n const slugVars: ClassNameSlugVars = {\n hash: slug,\n title: displayName,\n index: idx,\n file: relativeFilename,\n ext,\n name: basename(relativeFilename, ext),\n dir: dirname(relativeFilename).split(sep).pop() as string,\n };\n\n let className = options.displayName\n ? `${toValidCSSIdentifier(displayName!)}_${slug!}`\n : slug!;\n\n // The className can be defined by the user either as fn or a string\n if (typeof options.classNameSlug === 'function') {\n try {\n className = toValidCSSIdentifier(\n options.classNameSlug(slug, displayName, slugVars)\n );\n } catch {\n throw new Error('classNameSlug option must return a string');\n }\n }\n\n if (typeof options.classNameSlug === 'string') {\n className = toValidCSSIdentifier(\n buildSlug(options.classNameSlug, slugVars)\n );\n }\n\n logger.extend('template-parse:generated-meta')(\n `slug: ${slug}, displayName: ${displayName}, className: ${className}`\n );\n\n return { className, slug };\n}\n"],"file":"getClassNameAndSlug.js"}
export function getVariableName(varId, rawVariableName) {
switch (rawVariableName) {
case 'raw':
return varId;
case 'dashes':
return `--${varId}`;
case 'var':
default:
return `var(--${varId})`;
}
switch (rawVariableName) {
case "raw": return varId;
case "dashes": return `--${varId}`;
case "var":
default: return `var(--${varId})`;
}
}
//# sourceMappingURL=getVariableName.js.map
//# sourceMappingURL=getVariableName.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"getVariableName.js","names":["getVariableName","varId","rawVariableName"],"sources":["../../src/utils/getVariableName.ts"],"sourcesContent":["import type { IOptions } from './types';\n\nexport function getVariableName(\n varId: string,\n rawVariableName: IOptions['variableNameConfig'] | undefined\n) {\n switch (rawVariableName) {\n case 'raw':\n return varId;\n case 'dashes':\n return `--${varId}`;\n case 'var':\n default:\n return `var(--${varId})`;\n }\n}\n"],"mappings":"AAEA,OAAO,SAASA,eAAeA,CAC7BC,KAAa,EACbC,eAA2D,EAC3D;EACA,QAAQA,eAAe;IACrB,KAAK,KAAK;MACR,OAAOD,KAAK;IACd,KAAK,QAAQ;MACX,OAAO,KAAKA,KAAK,EAAE;IACrB,KAAK,KAAK;IACV;MACE,OAAO,SAASA,KAAK,GAAG;EAC5B;AACF","ignoreList":[]}
{"mappings":"AAEA,OAAO,SAAS,gBACd,OACA,iBACA;AACA,SAAQ,iBAAR;EACE,KAAK,MACH,QAAO;EACT,KAAK,SACH,QAAO,KAAK;EACd,KAAK;EACL,QACE,QAAO,SAAS,MAAM","names":[],"sources":["../../src/utils/getVariableName.ts"],"version":3,"sourcesContent":["import type { IOptions } from './types';\n\nexport function getVariableName(\n varId: string,\n rawVariableName: IOptions['variableNameConfig'] | undefined\n) {\n switch (rawVariableName) {\n case 'raw':\n return varId;\n case 'dashes':\n return `--${varId}`;\n case 'var':\n default:\n return `var(--${varId})`;\n }\n}\n"],"file":"getVariableName.js"}

@@ -5,13 +5,11 @@ // Stripping away the new lines ensures that we preserve line numbers

export default function stripLines(loc, text) {
let result = String(text).replace(/[\r\n]+/g, ' ').trim();
// If the start and end line numbers aren't same, add new lines to span the text across multiple lines
if (loc.start.line !== loc.end.line) {
result += '\n'.repeat(loc.end.line - loc.start.line);
// Add extra spaces to offset the column
result += ' '.repeat(loc.end.column);
}
return result;
let result = String(text).replace(/[\r\n]+/g, " ").trim();
// If the start and end line numbers aren't same, add new lines to span the text across multiple lines
if (loc.start.line !== loc.end.line) {
result += "\n".repeat(loc.end.line - loc.start.line);
// Add extra spaces to offset the column
result += " ".repeat(loc.end.column);
}
return result;
}
//# sourceMappingURL=stripLines.js.map
//# sourceMappingURL=stripLines.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"stripLines.js","names":["stripLines","loc","text","result","String","replace","trim","start","line","end","repeat","column"],"sources":["../../src/utils/stripLines.ts"],"sourcesContent":["import type { Location } from '@wyw-in-js/shared';\n\n// Stripping away the new lines ensures that we preserve line numbers\n// This is useful in case of tools such as the stylelint pre-processor\n// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings\nexport default function stripLines(\n loc: { end: Location; start: Location },\n text: string | number\n) {\n let result = String(text)\n .replace(/[\\r\\n]+/g, ' ')\n .trim();\n\n // If the start and end line numbers aren't same, add new lines to span the text across multiple lines\n if (loc.start.line !== loc.end.line) {\n result += '\\n'.repeat(loc.end.line - loc.start.line);\n\n // Add extra spaces to offset the column\n result += ' '.repeat(loc.end.column);\n }\n\n return result;\n}\n"],"mappings":"AAEA;AACA;AACA;AACA,eAAe,SAASA,UAAUA,CAChCC,GAAuC,EACvCC,IAAqB,EACrB;EACA,IAAIC,MAAM,GAAGC,MAAM,CAACF,IAAI,CAAC,CACtBG,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CACxBC,IAAI,CAAC,CAAC;;EAET;EACA,IAAIL,GAAG,CAACM,KAAK,CAACC,IAAI,KAAKP,GAAG,CAACQ,GAAG,CAACD,IAAI,EAAE;IACnCL,MAAM,IAAI,IAAI,CAACO,MAAM,CAACT,GAAG,CAACQ,GAAG,CAACD,IAAI,GAAGP,GAAG,CAACM,KAAK,CAACC,IAAI,CAAC;;IAEpD;IACAL,MAAM,IAAI,GAAG,CAACO,MAAM,CAACT,GAAG,CAACQ,GAAG,CAACE,MAAM,CAAC;EACtC;EAEA,OAAOR,MAAM;AACf","ignoreList":[]}
{"mappings":";;;AAKA,eAAe,SAAS,WACtB,KACA,MACA;CACA,IAAI,SAAS,OAAO,KAAK,CACtB,QAAQ,YAAY,IAAI,CACxB,MAAM;;AAGT,KAAI,IAAI,MAAM,SAAS,IAAI,IAAI,MAAM;AACnC,YAAU,KAAK,OAAO,IAAI,IAAI,OAAO,IAAI,MAAM,KAAK;;AAGpD,YAAU,IAAI,OAAO,IAAI,IAAI,OAAO;;AAGtC,QAAO","names":[],"sources":["../../src/utils/stripLines.ts"],"version":3,"sourcesContent":["import type { Location } from '@wyw-in-js/shared';\n\n// Stripping away the new lines ensures that we preserve line numbers\n// This is useful in case of tools such as the stylelint pre-processor\n// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings\nexport default function stripLines(\n loc: { end: Location; start: Location },\n text: string | number\n) {\n let result = String(text)\n .replace(/[\\r\\n]+/g, ' ')\n .trim();\n\n // If the start and end line numbers aren't same, add new lines to span the text across multiple lines\n if (loc.start.line !== loc.end.line) {\n result += '\\n'.repeat(loc.end.line - loc.start.line);\n\n // Add extra spaces to offset the column\n result += ' '.repeat(loc.end.column);\n }\n\n return result;\n}\n"],"file":"stripLines.js"}

@@ -1,120 +0,100 @@

/* eslint-disable no-continue */
/**
* This file handles transforming template literals to class names or styled components and generates CSS content.
* It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.
*/
import { hasEvalMeta, ValueType } from '@wyw-in-js/shared';
import { getVariableName } from './getVariableName';
import stripLines from './stripLines';
import throwIfInvalid from './throwIfInvalid';
import toCSS, { isCSSable } from './toCSS';
import { units } from './units';
import { hasEvalMeta, ValueType } from "@wyw-in-js/shared";
import { getVariableName } from "./getVariableName.js";
import stripLines from "./stripLines.js";
import throwIfInvalid from "./throwIfInvalid.js";
import toCSS, { isCSSable } from "./toCSS.js";
import { units } from "./units.js";
// Match any valid CSS unit not immediately followed by an alphanumeric character or underscore.
const unitRegex = new RegExp(`^(?:${units.join('|')})(?![a-zA-Z0-9_])`);
export default function templateProcessor(tagProcessor, [...template], valueCache, variableNameConfig) {
const sourceMapReplacements = [];
// Check if the variable is referenced anywhere for basic DCE
// Only works when it's assigned to a variable
const {
isReferenced
} = tagProcessor;
// Serialize the tagged template literal to a string
let cssText = '';
let item;
// eslint-disable-next-line no-cond-assign
while (item = template.shift()) {
if ('type' in item) {
// It's a template element
cssText += item.value.cooked;
continue;
}
// It's an expression
const {
ex
} = item;
const {
end,
start
} = ex.loc;
const beforeLength = cssText.length;
// The location will be end of the current string to start of next string
const next = template[0]; // template[0] is the next template element
const loc = {
start,
end: next ? {
line: next.loc.start.line,
column: next.loc.start.column
} : {
line: end.line,
column: end.column + 1
}
};
const value = 'value' in item ? item.value : valueCache.get(item.ex.name);
// Is it props based interpolation?
if (item.kind === ValueType.FUNCTION || typeof value === 'function') {
// Check if previous expression was a CSS variable that we replaced
// If it has a unit after it, we need to move the unit into the interpolation
// e.g. `var(--size)px` should actually be `var(--size)`
// So we check if the current text starts with a unit, and add the unit to the previous interpolation
// Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units
// https://bugzilla.mozilla.org/show_bug.cgi?id=956573
const matches = next.value.cooked?.match(unitRegex);
try {
if (matches) {
template.shift();
const [unit] = matches;
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source, unit);
cssText += getVariableName(varId, variableNameConfig);
cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';
} else {
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source);
cssText += getVariableName(varId, variableNameConfig);
}
} catch (e) {
if (e instanceof Error) {
throw item.buildCodeFrameError(e.message);
}
throw e;
}
} else {
throwIfInvalid(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
if (value !== undefined && typeof value !== 'function') {
// Skip the blank string instead of throw ing an error
if (value === '') {
continue;
}
if (hasEvalMeta(value)) {
// If it's a React component wrapped in styled, get the class name
// Useful for interpolating components
cssText += `.${value.__wyw_meta.className}`;
} else if (isCSSable(value)) {
// If it's a plain object or an array, convert it to a CSS string
cssText += stripLines(loc, toCSS(value));
} else {
// For anything else, assume it'll be stringified
cssText += stripLines(loc, value);
}
sourceMapReplacements.push({
original: loc,
length: cssText.length - beforeLength
});
}
}
}
const rules = tagProcessor.extractRules(valueCache, cssText, tagProcessor.location);
// tagProcessor.doRuntimeReplacement(classes);
if (!isReferenced && !cssText.includes(':global')) {
return null;
}
// eslint-disable-next-line no-param-reassign
return [rules, sourceMapReplacements];
const unitRegex = new RegExp(`^(?:${units.join("|")})(?![a-zA-Z0-9_])`);
export default function templateProcessor(tagProcessor, [ ...template], valueCache, variableNameConfig) {
const sourceMapReplacements = [];
// Check if the variable is referenced anywhere for basic DCE
// Only works when it's assigned to a variable
const { isReferenced } = tagProcessor;
// Serialize the tagged template literal to a string
let cssText = "";
let item;
// eslint-disable-next-line no-cond-assign
while (item = template.shift()) {
if ("type" in item) {
// It's a template element
cssText += item.value.cooked;
continue;
}
// It's an expression
const { ex } = item;
const { end, start } = ex.loc;
const beforeLength = cssText.length;
// The location will be end of the current string to start of next string
const next = template[0];
const loc = {
start,
end: next ? {
line: next.loc.start.line,
column: next.loc.start.column
} : {
line: end.line,
column: end.column + 1
}
};
const value = "value" in item ? item.value : valueCache.get(item.ex.name);
// Is it props based interpolation?
if (item.kind === ValueType.FUNCTION || typeof value === "function") {
// Check if previous expression was a CSS variable that we replaced
// If it has a unit after it, we need to move the unit into the interpolation
// e.g. `var(--size)px` should actually be `var(--size)`
// So we check if the current text starts with a unit, and add the unit to the previous interpolation
// Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units
// https://bugzilla.mozilla.org/show_bug.cgi?id=956573
const matches = next.value.cooked?.match(unitRegex);
try {
if (matches) {
template.shift();
const [unit] = matches;
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source, unit);
cssText += getVariableName(varId, variableNameConfig);
cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? "";
} else {
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source);
cssText += getVariableName(varId, variableNameConfig);
}
} catch (e) {
if (e instanceof Error) {
throw item.buildCodeFrameError(e.message);
}
throw e;
}
} else {
throwIfInvalid(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
if (value !== undefined && typeof value !== "function") {
// Skip the blank string instead of throw ing an error
if (value === "") {
continue;
}
if (hasEvalMeta(value)) {
// If it's a React component wrapped in styled, get the class name
// Useful for interpolating components
cssText += `.${value.__wyw_meta.className}`;
} else if (isCSSable(value)) {
// If it's a plain object or an array, convert it to a CSS string
cssText += stripLines(loc, toCSS(value));
} else {
// For anything else, assume it'll be stringified
cssText += stripLines(loc, value);
}
sourceMapReplacements.push({
original: loc,
length: cssText.length - beforeLength
});
}
}
}
const rules = tagProcessor.extractRules(valueCache, cssText, tagProcessor.location);
// tagProcessor.doRuntimeReplacement(classes);
if (!isReferenced && !cssText.includes(":global")) {
return null;
}
// eslint-disable-next-line no-param-reassign
return [rules, sourceMapReplacements];
}
//# sourceMappingURL=templateProcessor.js.map
//# sourceMappingURL=templateProcessor.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"templateProcessor.js","names":["hasEvalMeta","ValueType","getVariableName","stripLines","throwIfInvalid","toCSS","isCSSable","units","unitRegex","RegExp","join","templateProcessor","tagProcessor","template","valueCache","variableNameConfig","sourceMapReplacements","isReferenced","cssText","item","shift","value","cooked","ex","end","start","loc","beforeLength","length","next","line","column","get","name","kind","FUNCTION","matches","match","unit","varId","addInterpolation","source","substring","e","Error","buildCodeFrameError","message","isValidValue","bind","undefined","__wyw_meta","className","push","original","rules","extractRules","location","includes"],"sources":["../../src/utils/templateProcessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\n/**\n * This file handles transforming template literals to class names or styled components and generates CSS content.\n * It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.\n */\n\nimport type { TemplateElement } from '@babel/types';\n\nimport type { ExpressionValue, Replacements } from '@wyw-in-js/shared';\nimport { hasEvalMeta, ValueType } from '@wyw-in-js/shared';\n\nimport type { TaggedTemplateProcessor } from '../TaggedTemplateProcessor';\nimport type { ValueCache, Rules } from '../types';\n\nimport { getVariableName } from './getVariableName';\nimport stripLines from './stripLines';\nimport throwIfInvalid from './throwIfInvalid';\nimport toCSS, { isCSSable } from './toCSS';\nimport type { IOptions } from './types';\nimport { units } from './units';\n\n// Match any valid CSS unit not immediately followed by an alphanumeric character or underscore.\nconst unitRegex = new RegExp(`^(?:${units.join('|')})(?![a-zA-Z0-9_])`);\n\nexport default function templateProcessor(\n tagProcessor: TaggedTemplateProcessor,\n [...template]: (TemplateElement | ExpressionValue)[],\n valueCache: ValueCache,\n variableNameConfig: IOptions['variableNameConfig'] | undefined\n): [rules: Rules, sourceMapReplacements: Replacements] | null {\n const sourceMapReplacements: Replacements = [];\n // Check if the variable is referenced anywhere for basic DCE\n // Only works when it's assigned to a variable\n const { isReferenced } = tagProcessor;\n\n // Serialize the tagged template literal to a string\n let cssText = '';\n\n let item: TemplateElement | ExpressionValue | undefined;\n // eslint-disable-next-line no-cond-assign\n while ((item = template.shift())) {\n if ('type' in item) {\n // It's a template element\n cssText += item.value.cooked;\n continue;\n }\n\n // It's an expression\n const { ex } = item;\n\n const { end, start } = ex.loc!;\n const beforeLength = cssText.length;\n\n // The location will be end of the current string to start of next string\n const next = template[0] as TemplateElement; // template[0] is the next template element\n const loc = {\n start,\n end: next\n ? { line: next.loc!.start.line, column: next.loc!.start.column }\n : { line: end.line, column: end.column + 1 },\n };\n\n const value = 'value' in item ? item.value : valueCache.get(item.ex.name);\n\n // Is it props based interpolation?\n if (item.kind === ValueType.FUNCTION || typeof value === 'function') {\n // Check if previous expression was a CSS variable that we replaced\n // If it has a unit after it, we need to move the unit into the interpolation\n // e.g. `var(--size)px` should actually be `var(--size)`\n // So we check if the current text starts with a unit, and add the unit to the previous interpolation\n // Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units\n // https://bugzilla.mozilla.org/show_bug.cgi?id=956573\n const matches = next.value.cooked?.match(unitRegex);\n\n try {\n if (matches) {\n template.shift();\n const [unit] = matches;\n\n const varId = tagProcessor.addInterpolation(\n item.ex,\n cssText,\n item.source,\n unit\n );\n cssText += getVariableName(varId, variableNameConfig);\n\n cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';\n } else {\n const varId = tagProcessor.addInterpolation(\n item.ex,\n cssText,\n item.source\n );\n cssText += getVariableName(varId, variableNameConfig);\n }\n } catch (e) {\n if (e instanceof Error) {\n throw item.buildCodeFrameError(e.message);\n }\n\n throw e;\n }\n } else {\n throwIfInvalid(\n tagProcessor.isValidValue.bind(tagProcessor),\n value,\n item,\n item.source\n );\n\n if (value !== undefined && typeof value !== 'function') {\n // Skip the blank string instead of throw ing an error\n if (value === '') {\n continue;\n }\n\n if (hasEvalMeta(value)) {\n // If it's a React component wrapped in styled, get the class name\n // Useful for interpolating components\n cssText += `.${value.__wyw_meta.className}`;\n } else if (isCSSable(value)) {\n // If it's a plain object or an array, convert it to a CSS string\n cssText += stripLines(loc, toCSS(value));\n } else {\n // For anything else, assume it'll be stringified\n cssText += stripLines(loc, value);\n }\n\n sourceMapReplacements.push({\n original: loc,\n length: cssText.length - beforeLength,\n });\n }\n }\n }\n\n const rules = tagProcessor.extractRules(\n valueCache,\n cssText,\n tagProcessor.location\n );\n\n // tagProcessor.doRuntimeReplacement(classes);\n if (!isReferenced && !cssText.includes(':global')) {\n return null;\n }\n\n // eslint-disable-next-line no-param-reassign\n return [rules, sourceMapReplacements];\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAKA,SAASA,WAAW,EAAEC,SAAS,QAAQ,mBAAmB;AAK1D,SAASC,eAAe,QAAQ,mBAAmB;AACnD,OAAOC,UAAU,MAAM,cAAc;AACrC,OAAOC,cAAc,MAAM,kBAAkB;AAC7C,OAAOC,KAAK,IAAIC,SAAS,QAAQ,SAAS;AAE1C,SAASC,KAAK,QAAQ,SAAS;;AAE/B;AACA,MAAMC,SAAS,GAAG,IAAIC,MAAM,CAAC,OAAOF,KAAK,CAACG,IAAI,CA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AsB,KAAK;KACzB,UAAU;KACV,QAAQ,QAAQ,SAAS;KAC1B,CAAC;;;;CAKR,MAAM,QAAQ,aAAa,aACzB,YACA,SACA,aAAa,SACd;;AAGD,KAAI,CAAC,gBAAgB,CAAC,QAAQ,SAAS,UAAU,EAAE;AACjD,SAAO;;;AAIT,QAAO,CAAC,OAAO,sBAAsB","names":[],"sources":["../../src/utils/templateProcessor.ts"],"version":3,"sourcesContent":["/* eslint-disable no-continue */\n/**\n * This file handles transforming template literals to class names or styled components and generates CSS content.\n * It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.\n */\n\nimport type { ExpressionValue, Replacements } from '@wyw-in-js/shared';\nimport { hasEvalMeta, ValueType } from '@wyw-in-js/shared';\n\nimport type { TaggedTemplateProcessor } from '../TaggedTemplateProcessor';\nimport type { Expression, TemplateElement } from '../ast';\nimport type { ValueCache, Rules } from '../types';\n\nimport { getVariableName } from './getVariableName';\nimport stripLines from './stripLines';\nimport throwIfInvalid from './throwIfInvalid';\nimport toCSS, { isCSSable } from './toCSS';\nimport type { IOptions } from './types';\nimport { units } from './units';\n\n// Match any valid CSS unit not immediately followed by an alphanumeric character or underscore.\nconst unitRegex = new RegExp(`^(?:${units.join('|')})(?![a-zA-Z0-9_])`);\n\nexport default function templateProcessor(\n tagProcessor: TaggedTemplateProcessor,\n [...template]: (TemplateElement | ExpressionValue)[],\n valueCache: ValueCache,\n variableNameConfig: IOptions['variableNameConfig'] | undefined\n): [rules: Rules, sourceMapReplacements: Replacements] | null {\n const sourceMapReplacements: Replacements = [];\n // Check if the variable is referenced anywhere for basic DCE\n // Only works when it's assigned to a variable\n const { isReferenced } = tagProcessor;\n\n // Serialize the tagged template literal to a string\n let cssText = '';\n\n let item: TemplateElement | ExpressionValue | undefined;\n // eslint-disable-next-line no-cond-assign\n while ((item = template.shift())) {\n if ('type' in item) {\n // It's a template element\n cssText += item.value.cooked;\n continue;\n }\n\n // It's an expression\n const { ex } = item;\n\n const { end, start } = ex.loc!;\n const beforeLength = cssText.length;\n\n // The location will be end of the current string to start of next string\n const next = template[0] as TemplateElement; // template[0] is the next template element\n const loc = {\n start,\n end: next\n ? { line: next.loc!.start.line, column: next.loc!.start.column }\n : { line: end.line, column: end.column + 1 },\n };\n\n const value = 'value' in item ? item.value : valueCache.get(item.ex.name);\n\n // Is it props based interpolation?\n if (item.kind === ValueType.FUNCTION || typeof value === 'function') {\n // Check if previous expression was a CSS variable that we replaced\n // If it has a unit after it, we need to move the unit into the interpolation\n // e.g. `var(--size)px` should actually be `var(--size)`\n // So we check if the current text starts with a unit, and add the unit to the previous interpolation\n // Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units\n // https://bugzilla.mozilla.org/show_bug.cgi?id=956573\n const matches = next.value.cooked?.match(unitRegex);\n\n try {\n if (matches) {\n template.shift();\n const [unit] = matches;\n\n const varId = tagProcessor.addInterpolation(\n item.ex as Expression,\n cssText,\n item.source,\n unit\n );\n cssText += getVariableName(varId, variableNameConfig);\n\n cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';\n } else {\n const varId = tagProcessor.addInterpolation(\n item.ex as Expression,\n cssText,\n item.source\n );\n cssText += getVariableName(varId, variableNameConfig);\n }\n } catch (e) {\n if (e instanceof Error) {\n throw item.buildCodeFrameError(e.message);\n }\n\n throw e;\n }\n } else {\n throwIfInvalid(\n tagProcessor.isValidValue.bind(tagProcessor),\n value,\n item,\n item.source\n );\n\n if (value !== undefined && typeof value !== 'function') {\n // Skip the blank string instead of throw ing an error\n if (value === '') {\n continue;\n }\n\n if (hasEvalMeta(value)) {\n // If it's a React component wrapped in styled, get the class name\n // Useful for interpolating components\n cssText += `.${value.__wyw_meta.className}`;\n } else if (isCSSable(value)) {\n // If it's a plain object or an array, convert it to a CSS string\n cssText += stripLines(loc, toCSS(value));\n } else {\n // For anything else, assume it'll be stringified\n cssText += stripLines(loc, value);\n }\n\n sourceMapReplacements.push({\n original: loc,\n length: cssText.length - beforeLength,\n });\n }\n }\n }\n\n const rules = tagProcessor.extractRules(\n valueCache,\n cssText,\n tagProcessor.location\n );\n\n // tagProcessor.doRuntimeReplacement(classes);\n if (!isReferenced && !cssText.includes(':global')) {\n return null;\n }\n\n // eslint-disable-next-line no-param-reassign\n return [rules, sourceMapReplacements];\n}\n"],"file":"templateProcessor.js"}

@@ -1,8 +0,7 @@

const isLikeError = value => typeof value === 'object' && value !== null && 'stack' in value && 'message' in value;
const isLikeError = (value) => typeof value === "object" && value !== null && "stack" in value && "message" in value;
// Throw if we can't handle the interpolated value
function throwIfInvalid(checker, value, ex, source) {
// We can't use instanceof here so let's use duck typing
if (isLikeError(value) && value.stack && value.message) {
throw ex.buildCodeFrameError(`An error occurred when evaluating the expression:
// We can't use instanceof here so let's use duck typing
if (isLikeError(value) && value.stack && value.message) {
throw ex.buildCodeFrameError(`An error occurred when evaluating the expression:

@@ -21,10 +20,10 @@ > ${value.message}.

`);
}
if (checker(value)) {
return;
}
const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value);
throw ex.buildCodeFrameError(`The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`);
}
if (checker(value)) {
return;
}
const stringified = typeof value === "object" ? JSON.stringify(value) : String(value);
throw ex.buildCodeFrameError(`The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`);
}
export default throwIfInvalid;
//# sourceMappingURL=throwIfInvalid.js.map
//# sourceMappingURL=throwIfInvalid.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"throwIfInvalid.js","names":["isLikeError","value","throwIfInvalid","checker","ex","source","stack","message","buildCodeFrameError","stringified","JSON","stringify","String"],"sources":["../../src/utils/throwIfInvalid.ts"],"sourcesContent":["import type { BuildCodeFrameErrorFn } from '@wyw-in-js/shared';\n\nconst isLikeError = (value: unknown): value is Error =>\n typeof value === 'object' &&\n value !== null &&\n 'stack' in value &&\n 'message' in value;\n\n// Throw if we can't handle the interpolated value\nfunction throwIfInvalid<T>(\n checker: (value: unknown) => value is T,\n value: Error | unknown,\n ex: { buildCodeFrameError: BuildCodeFrameErrorFn },\n source: string\n): asserts value is T {\n // We can't use instanceof here so let's use duck typing\n if (isLikeError(value) && value.stack && value.message) {\n throw ex.buildCodeFrameError(\n `An error occurred when evaluating the expression:\n\n > ${value.message}.\n\n Make sure you are not using a browser or Node specific API and all the variables are available in static context.\n Linaria have to extract pieces of your code to resolve the interpolated values.\n Defining styled component or class will not work inside:\n - function,\n - class,\n - method,\n - loop,\n because it cannot be statically determined in which context you use them.\n That's why some variables may be not defined during evaluation.\n `\n );\n }\n\n if (checker(value)) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n throw ex.buildCodeFrameError(\n `The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`\n );\n}\n\nexport default throwIfInvalid;\n"],"mappings":"AAEA,MAAMA,WAAW,GAAIC,KAAc,IACjC,OAAOA,KAAK,KAAK,QAAQ,IACzBA,KAAK,KAAK,IAAI,IACd,OAAO,IAAIA,KAAK,IAChB,SAAS,IAAIA,KAAK;;AAEpB;AACA,SAASC,cAAcA,CACrBC,OAAuC,EACvCF,KAAsB,EACtBG,EAAkD,EAClDC,MAAc,EACM;EACpB;EACA,IAAIL,WAAW,CAACC,KAAK,CAAC,IAAIA,KAAK,CAACK,KAAK,IAAIL,KAAK,CAACM,OAAO,EAAE;IACtD,MAAMH,EAAE,CAACI,mBAAmB,CAC1B;AACN;AACA,MAAMP,KAAK,CAACM,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OACI,CAAC;EACH;EAEA,IAAIJ,OAAO,CAACF,KAAK,CAAC,EAAE;IAClB;EACF;EAEA,MAAMQ,WAAW,GACf,OAAOR,KAAK,KAAK,QAAQ,GAAGS,IAAI,CAACC,SAAS,CAACV,KAAK,CAAC,GAAGW,MAAM,CAACX,KAAK,CAAC;EAEnE,MAAMG,EAAE,CAACI,mBAAmB,CAC1B,gCAAgCC,WAAW,8IAA8IJ,MAAM,KACjM,CAAC;AACH;AAEA,eAAeH,cAAc","ignoreList":[]}
{"mappings":"AAEA,MAAM,eAAe,UACnB,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,aAAa;;AAGf,SAAS,eACP,SACA,OACA,IACA,QACoB;;AAEpB,KAAI,YAAY,MAAM,IAAI,MAAM,SAAS,MAAM,SAAS;AACtD,QAAM,GAAG,oBACP;;MAEA,MAAM,QAAQ;;;;;;;;;;;QAYf;;AAGH,KAAI,QAAQ,MAAM,EAAE;AAClB;;CAGF,MAAM,cACJ,OAAO,UAAU,WAAW,KAAK,UAAU,MAAM,GAAG,OAAO,MAAM;AAEnE,OAAM,GAAG,oBACP,gCAAgC,YAAY,6IAA6I,OAAO,KACjM;;AAGH,eAAe","names":[],"sources":["../../src/utils/throwIfInvalid.ts"],"version":3,"sourcesContent":["import type { BuildCodeFrameErrorFn } from '@wyw-in-js/shared';\n\nconst isLikeError = (value: unknown): value is Error =>\n typeof value === 'object' &&\n value !== null &&\n 'stack' in value &&\n 'message' in value;\n\n// Throw if we can't handle the interpolated value\nfunction throwIfInvalid<T>(\n checker: (value: unknown) => value is T,\n value: Error | unknown,\n ex: { buildCodeFrameError: BuildCodeFrameErrorFn },\n source: string\n): asserts value is T {\n // We can't use instanceof here so let's use duck typing\n if (isLikeError(value) && value.stack && value.message) {\n throw ex.buildCodeFrameError(\n `An error occurred when evaluating the expression:\n\n > ${value.message}.\n\n Make sure you are not using a browser or Node specific API and all the variables are available in static context.\n Linaria have to extract pieces of your code to resolve the interpolated values.\n Defining styled component or class will not work inside:\n - function,\n - class,\n - method,\n - loop,\n because it cannot be statically determined in which context you use them.\n That's why some variables may be not defined during evaluation.\n `\n );\n }\n\n if (checker(value)) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n throw ex.buildCodeFrameError(\n `The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`\n );\n}\n\nexport default throwIfInvalid;\n"],"file":"throwIfInvalid.js"}

@@ -1,50 +0,41 @@

import { isBoxedPrimitive } from '@wyw-in-js/shared';
import { unitless } from './units';
const isCSSPropertyValue = o => {
return isBoxedPrimitive(o) || typeof o === 'string' || typeof o === 'number' && Number.isFinite(o);
import { isBoxedPrimitive } from "@wyw-in-js/shared";
import { unitless } from "./units.js";
const isCSSPropertyValue = (o) => {
return isBoxedPrimitive(o) || typeof o === "string" || typeof o === "number" && Number.isFinite(o);
};
export const isCSSable = o => {
if (isCSSPropertyValue(o)) {
return true;
}
if (Array.isArray(o)) {
return o.every(isCSSable);
}
if (typeof o === 'object') {
return o !== null && Object.values(o).every(isCSSable);
}
return false;
export const isCSSable = (o) => {
if (isCSSPropertyValue(o)) {
return true;
}
if (Array.isArray(o)) {
return o.every(isCSSable);
}
if (typeof o === "object") {
return o !== null && Object.values(o).every(isCSSable);
}
return false;
};
const hyphenate = s => {
if (s.startsWith('--')) {
// It's a custom property which is already well formatted.
return s;
}
return s
// Hyphenate CSS property names from camelCase version from JS string
.replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)
// Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`
.replace(/^ms-/, '-ms-');
const hyphenate = (s) => {
if (s.startsWith("--")) {
// It's a custom property which is already well formatted.
return s;
}
return s.replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`).replace(/^ms-/, "-ms-");
};
// Some tools such as polished.js output JS objects
// To support them transparently, we convert JS objects to CSS strings
export default function toCSS(o) {
if (Array.isArray(o)) {
return o.map(toCSS).join('\n');
}
if (isCSSPropertyValue(o)) {
return o.valueOf().toString();
}
return Object.entries(o).filter(([, value]) =>
// Ignore all falsy values except numbers
typeof value === 'number' || value).map(([key, value]) => {
if (!isCSSPropertyValue(value)) {
return `${key} { ${toCSS(value)} }`;
}
return `${hyphenate(key)}: ${typeof value === 'number' && value !== 0 &&
// Strip vendor prefixes when checking if the value is unitless
!(key.replace(/^(Webkit|Moz|O|ms)([A-Z])(.+)$/, (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`) in unitless) ? `${value}px` : value};`;
}).join(' ');
if (Array.isArray(o)) {
return o.map(toCSS).join("\n");
}
if (isCSSPropertyValue(o)) {
return o.valueOf().toString();
}
return Object.entries(o).filter(([, value]) => typeof value === "number" || value).map(([key, value]) => {
if (!isCSSPropertyValue(value)) {
return `${key} { ${toCSS(value)} }`;
}
return `${hyphenate(key)}: ${typeof value === "number" && value !== 0 && !(key.replace(/^(Webkit|Moz|O|ms)([A-Z])(.+)$/, (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`) in unitless) ? `${value}px` : value};`;
}).join(" ");
}
//# sourceMappingURL=toCSS.js.map
//# sourceMappingURL=toCSS.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"toCSS.js","names":["isBoxedPrimitive","unitless","isCSSPropertyValue","o","Number","isFinite","isCSSable","Array","isArray","every","Object","values","hyphenate","s","startsWith","replace","match","p1","toLowerCase","toCSS","map","join","valueOf","toString","entries","filter","value","key","p2","p3"],"sources":["../../src/utils/toCSS.ts"],"sourcesContent":["import { isBoxedPrimitive } from '@wyw-in-js/shared';\n\nimport type { CSSPropertyValue, CSSable } from '../types';\n\nimport { unitless } from './units';\n\nconst isCSSPropertyValue = (o: unknown): o is CSSPropertyValue => {\n return (\n isBoxedPrimitive(o) ||\n typeof o === 'string' ||\n (typeof o === 'number' && Number.isFinite(o))\n );\n};\n\nexport const isCSSable = (o: unknown): o is CSSable => {\n if (isCSSPropertyValue(o)) {\n return true;\n }\n\n if (Array.isArray(o)) {\n return o.every(isCSSable);\n }\n\n if (typeof o === 'object') {\n return o !== null && Object.values(o).every(isCSSable);\n }\n\n return false;\n};\n\nconst hyphenate = (s: string) => {\n if (s.startsWith('--')) {\n // It's a custom property which is already well formatted.\n return s;\n }\n return (\n s\n // Hyphenate CSS property names from camelCase version from JS string\n .replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)\n // Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`\n .replace(/^ms-/, '-ms-')\n );\n};\n\n// Some tools such as polished.js output JS objects\n// To support them transparently, we convert JS objects to CSS strings\nexport default function toCSS(o: CSSable): string {\n if (Array.isArray(o)) {\n return o.map(toCSS).join('\\n');\n }\n\n if (isCSSPropertyValue(o)) {\n return o.valueOf().toString();\n }\n\n return Object.entries(o)\n .filter(\n ([, value]) =>\n // Ignore all falsy values except numbers\n typeof value === 'number' || value\n )\n .map(([key, value]) => {\n if (!isCSSPropertyValue(value)) {\n return `${key} { ${toCSS(value)} }`;\n }\n\n return `${hyphenate(key)}: ${\n typeof value === 'number' &&\n value !== 0 &&\n // Strip vendor prefixes when checking if the value is unitless\n !(\n key.replace(\n /^(Webkit|Moz|O|ms)([A-Z])(.+)$/,\n (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`\n ) in unitless\n )\n ? `${value}px`\n : value\n };`;\n })\n .join(' ');\n}\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,mBAAmB;AAIpD,SAASC,QAAQ,QAAQ,SAAS;AAElC,MAAMC,kBAAkB,GAAIC,CAAU,IAA4B;EAChE,OACEH,gBAAgB,CAACG,CAAC,CAAC,IACnB,OAAOA,CAAC,KAAK,QAAQ,IACpB,OAAOA,CAAC,KAAK,QAAQ,IAAIC,MAAM,CAACC,QAAQ,CAACF,CAAC,CAAE;AAEjD,CAAC;AAED,OAAO,MAAMG,SAAS,GAAIH,CAAU,IAAmB;EACrD,IAAID,kBAAkB,CAACC,CAAC,CAAC,EAAE;IACzB,OAAO,IAAI;EACb;EAEA,IAAII,KAAK,CAACC,OAAO,CAACL,CAAC,CAAC,EAAE;IACpB,OAAOA,CAAC,CAACM,KAAK,CAACH,SAAS,CAAC;EAC3B;EAEA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AmB,MAAM,EAAE;AAC9B,UAAO,GAAG,IAAI,KAAK,MAAM,MAAM,CAAC;;AAGlC,SAAO,GAAG,UAAU,IAAI,CAAC,IACvB,OAAO,UAAU,YACjB,UAAU,KAEV,EACE,IAAI,QACF,mCACC,OAAO,IAAI,IAAI,OAAO,GAAG,GAAG,aAAa,GAAG,KAC9C,IAAI,YAEH,GAAG,MAAM,MACT,MACL;GACD,CACD,KAAK,IAAI","names":[],"sources":["../../src/utils/toCSS.ts"],"version":3,"sourcesContent":["import { isBoxedPrimitive } from '@wyw-in-js/shared';\n\nimport type { CSSPropertyValue, CSSable } from '../types';\n\nimport { unitless } from './units';\n\nconst isCSSPropertyValue = (o: unknown): o is CSSPropertyValue => {\n return (\n isBoxedPrimitive(o) ||\n typeof o === 'string' ||\n (typeof o === 'number' && Number.isFinite(o))\n );\n};\n\nexport const isCSSable = (o: unknown): o is CSSable => {\n if (isCSSPropertyValue(o)) {\n return true;\n }\n\n if (Array.isArray(o)) {\n return o.every(isCSSable);\n }\n\n if (typeof o === 'object') {\n return o !== null && Object.values(o).every(isCSSable);\n }\n\n return false;\n};\n\nconst hyphenate = (s: string) => {\n if (s.startsWith('--')) {\n // It's a custom property which is already well formatted.\n return s;\n }\n return (\n s\n // Hyphenate CSS property names from camelCase version from JS string\n .replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)\n // Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`\n .replace(/^ms-/, '-ms-')\n );\n};\n\n// Some tools such as polished.js output JS objects\n// To support them transparently, we convert JS objects to CSS strings\nexport default function toCSS(o: CSSable): string {\n if (Array.isArray(o)) {\n return o.map(toCSS).join('\\n');\n }\n\n if (isCSSPropertyValue(o)) {\n return o.valueOf().toString();\n }\n\n return Object.entries(o)\n .filter(\n ([, value]) =>\n // Ignore all falsy values except numbers\n typeof value === 'number' || value\n )\n .map(([key, value]) => {\n if (!isCSSPropertyValue(value)) {\n return `${key} { ${toCSS(value)} }`;\n }\n\n return `${hyphenate(key)}: ${\n typeof value === 'number' &&\n value !== 0 &&\n // Strip vendor prefixes when checking if the value is unitless\n !(\n key.replace(\n /^(Webkit|Moz|O|ms)([A-Z])(.+)$/,\n (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`\n ) in unitless\n )\n ? `${value}px`\n : value\n };`;\n })\n .join(' ');\n}\n"],"file":"toCSS.js"}
export function toValidCSSIdentifier(s) {
return s.replace(/[^-_a-z0-9\u00A0-\uFFFF]/gi, '_').replace(/^\d/, '_');
return s.replace(/[^-_a-z0-9\u00A0-\uFFFF]/gi, "_").replace(/^\d/, "_");
}
//# sourceMappingURL=toValidCSSIdentifier.js.map
//# sourceMappingURL=toValidCSSIdentifier.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"toValidCSSIdentifier.js","names":["toValidCSSIdentifier","s","replace"],"sources":["../../src/utils/toValidCSSIdentifier.ts"],"sourcesContent":["export function toValidCSSIdentifier(s: string) {\n return s.replace(/[^-_a-z0-9\\u00A0-\\uFFFF]/gi, '_').replace(/^\\d/, '_');\n}\n"],"mappings":"AAAA,OAAO,SAASA,oBAAoBA,CAACC,CAAS,EAAE;EAC9C,OAAOA,CAAC,CAACC,OAAO,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAACA,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;AACzE","ignoreList":[]}
{"mappings":"AAAA,OAAO,SAAS,qBAAqB,GAAW;AAC9C,QAAO,EAAE,QAAQ,8BAA8B,IAAI,CAAC,QAAQ,OAAO,IAAI","names":[],"sources":["../../src/utils/toValidCSSIdentifier.ts"],"version":3,"sourcesContent":["export function toValidCSSIdentifier(s: string) {\n return s.replace(/[^-_a-z0-9\\u00A0-\\uFFFF]/gi, '_').replace(/^\\d/, '_');\n}\n"],"file":"toValidCSSIdentifier.js"}
export {};
//# sourceMappingURL=types.js.map
//# sourceMappingURL=types.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"types.js","names":[],"sources":["../../src/utils/types.ts"],"sourcesContent":["import type { TransformOptions } from '@babel/core';\n\nimport type { ClassNameFn, VariableNameFn } from '@wyw-in-js/shared';\n\nexport interface IOptions {\n classNameSlug?: string | ClassNameFn;\n displayName: boolean;\n extensions?: string[];\n variableNameConfig?: 'var' | 'dashes' | 'raw';\n variableNameSlug?: string | VariableNameFn;\n}\n\nexport type IFileContext = Pick<TransformOptions, 'root' | 'filename'>;\n"],"mappings":"","ignoreList":[]}
{"mappings":"","names":[],"sources":["../../src/utils/types.ts"],"version":3,"sourcesContent":["import type { ClassNameFn, VariableNameFn } from '@wyw-in-js/shared';\n\nexport interface IOptions {\n classNameSlug?: string | ClassNameFn;\n displayName: boolean;\n extensions?: string[];\n variableNameConfig?: 'var' | 'dashes' | 'raw';\n variableNameSlug?: string | VariableNameFn;\n}\n\nexport type IFileContext = {\n filename?: string | null;\n root?: string | null;\n};\n"],"file":"types.js"}
// https://www.w3.org/TR/css-values-4/
export const units = [
// font relative lengths
'em', 'ex', 'cap', 'ch', 'ic', 'rem', 'lh', 'rlh',
// viewport percentage lengths
'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax',
// absolute lengths
'cm', 'mm', 'Q', 'in', 'pc', 'pt', 'px',
// angle units
'deg', 'grad', 'rad', 'turn',
// duration units
's', 'ms',
// frequency units
'Hz', 'kHz',
// resolution units
'dpi', 'dpcm', 'dppx', 'x',
// https://www.w3.org/TR/css-grid-1/#fr-unit
'fr',
// percentages
'%'];
"em",
"ex",
"cap",
"ch",
"ic",
"rem",
"lh",
"rlh",
"vw",
"vh",
"vi",
"vb",
"vmin",
"vmax",
"cm",
"mm",
"Q",
"in",
"pc",
"pt",
"px",
"deg",
"grad",
"rad",
"turn",
"s",
"ms",
"Hz",
"kHz",
"dpi",
"dpcm",
"dppx",
"x",
"fr",
"%"
];
export const unitless = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
//# sourceMappingURL=units.js.map
//# sourceMappingURL=units.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"units.js","names":["units","unitless","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"],"sources":["../../src/utils/units.ts"],"sourcesContent":["// https://www.w3.org/TR/css-values-4/\nexport const units = [\n // font relative lengths\n 'em',\n 'ex',\n 'cap',\n 'ch',\n 'ic',\n 'rem',\n 'lh',\n 'rlh',\n\n // viewport percentage lengths\n 'vw',\n 'vh',\n 'vi',\n 'vb',\n 'vmin',\n 'vmax',\n\n // absolute lengths\n 'cm',\n 'mm',\n 'Q',\n 'in',\n 'pc',\n 'pt',\n 'px',\n\n // angle units\n 'deg',\n 'grad',\n 'rad',\n 'turn',\n\n // duration units\n 's',\n 'ms',\n\n // frequency units\n 'Hz',\n 'kHz',\n\n // resolution units\n 'dpi',\n 'dpcm',\n 'dppx',\n 'x',\n\n // https://www.w3.org/TR/css-grid-1/#fr-unit\n 'fr',\n\n // percentages\n '%',\n];\n\nexport const unitless = {\n animationIterationCount: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true,\n};\n"],"mappings":"AAAA;AACA,OAAO,MAAMA,KAAK,GAAG;AACnB;AACA,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,IAAI,EACJ,KAAK;AAEL;AACA,IAAI,EAC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I;EACjBC,YAAY,EAAE,IAAI;EAClBC,WAAW,EAAE,IAAI;EACjBC,eAAe,EAAE,IAAI;EACrBC,gBAAgB,EAAE,IAAI;EACtBC,gBAAgB,EAAE,IAAI;EACtBC,aAAa,EAAE,IAAI;EACnBC,WAAW,EAAE;AACf,CAAC","ignoreList":[]}
{"mappings":";AACA,OAAO,MAAM,QAAQ;CAEnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CAGA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CAGA;CAGA;CACD;AAED,OAAO,MAAM,WAAW;CACtB,yBAAyB;CACzB,mBAAmB;CACnB,kBAAkB;CAClB,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,iBAAiB;CACjB,aAAa;CACb,SAAS;CACT,MAAM;CACN,UAAU;CACV,cAAc;CACd,YAAY;CACZ,cAAc;CACd,WAAW;CACX,SAAS;CACT,YAAY;CACZ,aAAa;CACb,cAAc;CACd,YAAY;CACZ,eAAe;CACf,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,WAAW;CACX,YAAY;CACZ,SAAS;CACT,OAAO;CACP,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,MAAM;;CAGN,aAAa;CACb,cAAc;CACd,aAAa;CACb,iBAAiB;CACjB,kBAAkB;CAClB,kBAAkB;CAClB,eAAe;CACf,aAAa;CACd","names":[],"sources":["../../src/utils/units.ts"],"version":3,"sourcesContent":["// https://www.w3.org/TR/css-values-4/\nexport const units = [\n // font relative lengths\n 'em',\n 'ex',\n 'cap',\n 'ch',\n 'ic',\n 'rem',\n 'lh',\n 'rlh',\n\n // viewport percentage lengths\n 'vw',\n 'vh',\n 'vi',\n 'vb',\n 'vmin',\n 'vmax',\n\n // absolute lengths\n 'cm',\n 'mm',\n 'Q',\n 'in',\n 'pc',\n 'pt',\n 'px',\n\n // angle units\n 'deg',\n 'grad',\n 'rad',\n 'turn',\n\n // duration units\n 's',\n 'ms',\n\n // frequency units\n 'Hz',\n 'kHz',\n\n // resolution units\n 'dpi',\n 'dpcm',\n 'dppx',\n 'x',\n\n // https://www.w3.org/TR/css-grid-1/#fr-unit\n 'fr',\n\n // percentages\n '%',\n];\n\nexport const unitless = {\n animationIterationCount: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true,\n};\n"],"file":"units.js"}

@@ -1,43 +0,33 @@

// ParamMapping maps each ParamName to its corresponding Param type.
// GetParamByName returns the Param type based on the input type T.
// If T is none of the above, return never.
// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.
// If TNames is an empty tuple, return the result tuple.
export function isValidParams(params, constraints) {
const length = Math.max(params.length, constraints.length);
for (let i = 0; i < length; i++) {
if (params[i] === undefined || constraints[i] === undefined) {
return false;
}
const constraint = constraints[i];
if (constraint === '...') {
return true;
}
if (constraint === '*') {
if (params[i] === undefined) {
return false;
}
} else if (Array.isArray(constraint)) {
if (constraint.every(c => c !== params[i]?.[0])) {
return false;
}
} else if (constraint !== params[i]?.[0]) {
return false;
}
}
return true;
const length = Math.max(params.length, constraints.length);
for (let i = 0; i < length; i++) {
if (params[i] === undefined || constraints[i] === undefined) {
return false;
}
const constraint = constraints[i];
if (constraint === "...") {
return true;
}
if (constraint === "*") {
if (params[i] === undefined) {
return false;
}
} else if (Array.isArray(constraint)) {
if (constraint.every((c) => c !== params[i]?.[0])) {
return false;
}
} else if (constraint !== params[i]?.[0]) {
return false;
}
}
return true;
}
export function validateParams(params, constraints, messageOrError) {
if (!isValidParams(params, constraints)) {
if (typeof messageOrError === 'string') {
throw new Error(messageOrError);
}
throw messageOrError;
}
if (!isValidParams(params, constraints)) {
if (typeof messageOrError === "string") {
throw new Error(messageOrError);
}
throw messageOrError;
}
}
//# sourceMappingURL=validateParams.js.map
//# sourceMappingURL=validateParams.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"validateParams.js","names":["isValidParams","params","constraints","length","Math","max","i","undefined","constraint","Array","isArray","every","c","validateParams","messageOrError","Error"],"sources":["../../src/utils/validateParams.ts"],"sourcesContent":["import type { Param, Params } from '../types';\n\ntype ParamName = Param[0];\ntype ParamConstraint = ParamName | [...ParamName[]] | '*';\n\nexport type ParamConstraints =\n | [...ParamConstraint[]]\n | [...ParamConstraint[], '...'];\n\n// ParamMapping maps each ParamName to its corresponding Param type.\ntype ParamMapping = {\n [K in ParamName]: Extract<Param, readonly [K, ...unknown[]]>; // For each ParamName K, extract the corresponding Param type.\n};\n\n// GetParamByName returns the Param type based on the input type T.\ntype GetParamByName<T> = T extends '*'\n ? Param // If T is '*', return Param type.\n : T extends keyof ParamMapping // If T is a key in ParamMapping (i.e., a ParamName).\n ? ParamMapping[T] // Return the corresponding Param type from ParamMapping.\n : T extends Array<infer TNames> // If T is an array of names.\n ? TNames extends ParamName // If TNames is a ParamName.\n ? Extract<Param, readonly [TNames, ...unknown[]]> // Return the corresponding Param type.\n : never // If TNames is not a ParamName, return never.\n : never; // If T is none of the above, return never.\n\n// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.\nexport type MapParams<\n TNames extends ParamConstraints,\n TRes extends Param[] = [],\n> = TNames extends [infer THead, ...infer TTail] // If TNames is a non-empty tuple.\n ? THead extends '...' // If the first element in the tuple is '...'.\n ? [...TRes, ...Params] // Append all Params to the result tuple.\n : MapParams<\n Extract<TTail, ParamConstraints>, // Extract the remaining ParamConstraints.\n [...TRes, GetParamByName<Extract<THead, ParamName | '*' | ParamName[]>>] // Append the mapped Param to the result tuple and recurse.\n >\n : TRes; // If TNames is an empty tuple, return the result tuple.\n\nexport function isValidParams<T extends ParamConstraints>(\n params: Params,\n constraints: T\n): params is MapParams<T> {\n const length = Math.max(params.length, constraints.length);\n for (let i = 0; i < length; i++) {\n if (params[i] === undefined || constraints[i] === undefined) {\n return false;\n }\n\n const constraint = constraints[i];\n if (constraint === '...') {\n return true;\n }\n\n if (constraint === '*') {\n if (params[i] === undefined) {\n return false;\n }\n } else if (Array.isArray(constraint)) {\n if (constraint.every((c) => c !== params[i]?.[0])) {\n return false;\n }\n } else if (constraint !== params[i]?.[0]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function validateParams<T extends ParamConstraints>(\n params: Params,\n constraints: T,\n messageOrError: unknown\n): asserts params is MapParams<T> {\n if (!isValidParams(params, constraints)) {\n if (typeof messageOrError === 'string') {\n throw new Error(messageOrError);\n }\n\n throw messageOrError;\n }\n}\n"],"mappings":"AASA;;AAKA;;AASW;;AAEX;;AAWU;;AAEV,OAAO,SAASA,aAAaA,CAC3BC,MAAc,EACdC,WAAc,EACU;EACxB,MAAMC,MAAM,GAAGC,IAAI,CAACC,GAAG,CAACJ,MAAM,CAACE,MAAM,EAAED,WAAW,CAACC,MAAM,CAAC;EAC1D,KAAK,IAAIG,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,MAAM,EAAEG,CAAC,EAAE,EAAE;IAC/B,IAAIL,MAAM,CAACK,CAAC,CAAC,KAAKC,SAAS,IAAIL,WAAW,CAACI,CAAC,CAAC,KAAKC,SAAS,EAAE;MAC3D,OAAO,KAAK;IACd;IAEA,MAAMC,UAAU,GAAGN,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KAAK,GAAG,EAAE;AACjD,WAAO;;aAEA,eAAe,OAAO,KAAK,IAAI;AACxC,UAAO;;;AAIX,QAAO;;AAGT,OAAO,SAAS,eACd,QACA,aACA,gBACgC;AAChC,KAAI,CAAC,cAAc,QAAQ,YAAY,EAAE;AACvC,MAAI,OAAO,mBAAmB,UAAU;AACtC,SAAM,IAAI,MAAM,eAAe;;AAGjC,QAAM","names":[],"sources":["../../src/utils/validateParams.ts"],"version":3,"sourcesContent":["import type { Param, Params } from '../types';\n\ntype ParamName = Param[0];\ntype ParamConstraint = ParamName | [...ParamName[]] | '*';\n\nexport type ParamConstraints =\n | [...ParamConstraint[]]\n | [...ParamConstraint[], '...'];\n\n// ParamMapping maps each ParamName to its corresponding Param type.\ntype ParamMapping = {\n [K in ParamName]: Extract<Param, readonly [K, ...unknown[]]>; // For each ParamName K, extract the corresponding Param type.\n};\n\n// GetParamByName returns the Param type based on the input type T.\ntype GetParamByName<T> = T extends '*'\n ? Param // If T is '*', return Param type.\n : T extends keyof ParamMapping // If T is a key in ParamMapping (i.e., a ParamName).\n ? ParamMapping[T] // Return the corresponding Param type from ParamMapping.\n : T extends Array<infer TNames> // If T is an array of names.\n ? TNames extends ParamName // If TNames is a ParamName.\n ? Extract<Param, readonly [TNames, ...unknown[]]> // Return the corresponding Param type.\n : never // If TNames is not a ParamName, return never.\n : never; // If T is none of the above, return never.\n\n// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.\nexport type MapParams<\n TNames extends ParamConstraints,\n TRes extends Param[] = [],\n> = TNames extends [infer THead, ...infer TTail] // If TNames is a non-empty tuple.\n ? THead extends '...' // If the first element in the tuple is '...'.\n ? [...TRes, ...Params] // Append all Params to the result tuple.\n : MapParams<\n Extract<TTail, ParamConstraints>, // Extract the remaining ParamConstraints.\n [...TRes, GetParamByName<Extract<THead, ParamName | '*' | ParamName[]>>] // Append the mapped Param to the result tuple and recurse.\n >\n : TRes; // If TNames is an empty tuple, return the result tuple.\n\nexport function isValidParams<T extends ParamConstraints>(\n params: Params,\n constraints: T\n): params is MapParams<T> {\n const length = Math.max(params.length, constraints.length);\n for (let i = 0; i < length; i++) {\n if (params[i] === undefined || constraints[i] === undefined) {\n return false;\n }\n\n const constraint = constraints[i];\n if (constraint === '...') {\n return true;\n }\n\n if (constraint === '*') {\n if (params[i] === undefined) {\n return false;\n }\n } else if (Array.isArray(constraint)) {\n if (constraint.every((c) => c !== params[i]?.[0])) {\n return false;\n }\n } else if (constraint !== params[i]?.[0]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function validateParams<T extends ParamConstraints>(\n params: Params,\n constraints: T,\n messageOrError: unknown\n): asserts params is MapParams<T> {\n if (!isValidParams(params, constraints)) {\n if (typeof messageOrError === 'string') {\n throw new Error(messageOrError);\n }\n\n throw messageOrError;\n }\n}\n"],"file":"validateParams.js"}
{
"name": "@wyw-in-js/processor-utils",
"version": "1.1.0",
"version": "2.0.0-alpha.0",
"type": "module",
"dependencies": {
"@babel/generator": "^7.23.5",
"@wyw-in-js/shared": "1.1.0"
"@wyw-in-js/shared": "2.0.0-alpha.0"
},
"devDependencies": {
"@babel/types": "^7.23.5",
"@types/babel__core": "^7.20.5",
"@types/babel__generator": "^7.6.7",
"@types/node": "^16.18.55",
"@wyw-in-js/babel-config": "workspace:*",
"@types/node": "^22.0.0",
"@wyw-in-js/eslint-config": "workspace:*",

@@ -19,11 +15,16 @@ "@wyw-in-js/ts-config": "workspace:*",

"engines": {
"node": ">=20.0.0"
"node": ">=22.0.0"
},
"exports": {
".": {
"types": "./types/index.d.ts",
"default": "./esm/index.js"
}
},
"files": [
"types/",
"lib/",
"esm/"
"esm/",
"types/"
],
"license": "MIT",
"main": "lib/index.js",
"main": "esm/index.js",
"module": "esm/index.js",

@@ -34,4 +35,3 @@ "publishConfig": {

"scripts": {
"build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
"build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
"build:esm": "node ../../scripts/build-esm-oxc.mjs",
"build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",

@@ -38,0 +38,0 @@ "lint": "eslint --ext .js,.ts .",

@@ -1,7 +0,6 @@

import type { NodePath, types as t } from '@babel/core';
import type { Expression, Identifier, SourceLocation, MemberExpression } from '@babel/types';
import type { Artifact, ExpressionValue } from '@wyw-in-js/shared';
import type { AstService, Expression, Identifier, MemberExpression, SourceLocation } from './ast';
import type { IInterpolation, Params, ProcessorDiagnostic, Value, ValueCache } from './types';
import type { IFileContext, IOptions } from './utils/types';
export { Expression };
export type { Expression };
export type ProcessorParams = ConstructorParameters<typeof BaseProcessor>;

@@ -15,8 +14,5 @@ export type TailProcessorParams = ProcessorParams extends [Params, ...infer T] ? T : never;

tagSource: TagSource;
protected readonly astService: typeof t & {
addDefaultImport: (source: string, nameHint?: string) => Identifier;
addNamedImport: (name: string, source: string, nameHint?: string) => Identifier;
};
protected readonly astService: AstService;
readonly location: SourceLocation | null;
protected readonly replacer: (replacement: Expression | ((tagPath: NodePath) => Expression), isPure: boolean) => void;
protected readonly replacer: (replacement: Expression | ((tagPath: unknown) => Expression), isPure: boolean) => void;
readonly displayName: string;

@@ -35,6 +31,3 @@ readonly isReferenced: boolean;

protected evaluated: Record<'dependencies' | 'expression', Value[]> | undefined;
constructor(params: Params, tagSource: TagSource, astService: typeof t & {
addDefaultImport: (source: string, nameHint?: string) => Identifier;
addNamedImport: (name: string, source: string, nameHint?: string) => Identifier;
}, location: SourceLocation | null, replacer: (replacement: Expression | ((tagPath: NodePath) => Expression), isPure: boolean) => void, displayName: string, isReferenced: boolean, idx: number, options: IOptions, context: IFileContext);
constructor(params: Params, tagSource: TagSource, astService: AstService, location: SourceLocation | null, replacer: (replacement: Expression | ((tagPath: unknown) => Expression), isPure: boolean) => void, displayName: string, isReferenced: boolean, idx: number, options: IOptions, context: IFileContext);
/**

@@ -41,0 +34,0 @@ * A replacement for tag referenced in a template literal.

@@ -1,14 +0,8 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseProcessor = void 0;
const generator_1 = __importDefault(require("@babel/generator"));
const shared_1 = require("@wyw-in-js/shared");
const diagnostics_1 = require("./diagnostics");
const getClassNameAndSlug_1 = __importDefault(require("./utils/getClassNameAndSlug"));
const toCSS_1 = require("./utils/toCSS");
const validateParams_1 = require("./utils/validateParams");
class BaseProcessor {
import { hasEvalMeta } from '@wyw-in-js/shared';
import { expressionToCode } from './ast';
import { createProcessorDiagnosticArtifact } from './diagnostics';
import getClassNameAndSlug from './utils/getClassNameAndSlug';
import { isCSSable } from './utils/toCSS';
import { validateParams } from './utils/validateParams';
export class BaseProcessor {
tagSource;

@@ -41,4 +35,4 @@ astService;

this.context = context;
(0, validateParams_1.validateParams)(params, ['callee'], 'Unknown error: a callee param is not specified');
const { className, slug } = (0, getClassNameAndSlug_1.default)(this.displayName, this.idx, this.options, this.context);
validateParams(params, ['callee'], 'Unknown error: a callee param is not specified');
const { className, slug } = getClassNameAndSlug(this.displayName, this.idx, this.options, this.context);
this.className = className;

@@ -49,3 +43,3 @@ this.slug = slug;

addDiagnostic(diagnostic) {
this.artifacts.push((0, diagnostics_1.createProcessorDiagnosticArtifact)({
this.artifacts.push(createProcessorDiagnosticArtifact({
...diagnostic,

@@ -57,3 +51,3 @@ end: diagnostic.end ?? this.location?.end ?? null,

isValidValue(value) {
return (typeof value === 'function' || (0, toCSS_1.isCSSable)(value) || (0, shared_1.hasEvalMeta)(value));
return (typeof value === 'function' || isCSSable(value) || hasEvalMeta(value));
}

@@ -64,8 +58,4 @@ toString() {

tagSourceCode() {
if (this.callee.type === 'Identifier') {
return this.callee.name;
}
return (0, generator_1.default)(this.callee).code;
return expressionToCode(this.callee);
}
}
exports.BaseProcessor = BaseProcessor;

@@ -1,8 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isProcessorDiagnosticArtifact = exports.createProcessorDiagnosticArtifact = exports.PROCESSOR_DIAGNOSTIC_ARTIFACT = void 0;
exports.PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic';
const createProcessorDiagnosticArtifact = (diagnostic) => [exports.PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];
exports.createProcessorDiagnosticArtifact = createProcessorDiagnosticArtifact;
const isProcessorDiagnosticArtifact = (artifact) => artifact[0] === exports.PROCESSOR_DIAGNOSTIC_ARTIFACT;
exports.isProcessorDiagnosticArtifact = isProcessorDiagnosticArtifact;
export const PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic';
export const createProcessorDiagnosticArtifact = (diagnostic) => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];
export const isProcessorDiagnosticArtifact = (artifact) => artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;
export { BaseProcessor } from './BaseProcessor';
export { expressionToCode } from './ast';
export { createProcessorDiagnosticArtifact, isProcessorDiagnosticArtifact, PROCESSOR_DIAGNOSTIC_ARTIFACT, } from './diagnostics';
export type { ProcessorDiagnosticArtifact } from './diagnostics';
export type { Expression, TagSource, ProcessorParams, TailProcessorParams, } from './BaseProcessor';
export type { ArrayExpression, ArrowFunctionExpression, AstService, BaseAstNode, BlockStatement, BooleanLiteral, CallExpression, Expression, Identifier, MemberExpression, NullLiteral, NumericLiteral, ObjectExpression, ObjectProperty, SourceLocation, StringLiteral, TemplateElement, } from './ast';
export type { ProcessorParams, TagSource, TailProcessorParams, } from './BaseProcessor';
export * from './types';

@@ -6,0 +8,0 @@ export { buildSlug } from './utils/buildSlug';

@@ -1,33 +0,8 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toValidCSSIdentifier = exports.TaggedTemplateProcessor = exports.validateParams = exports.isValidParams = exports.buildSlug = exports.PROCESSOR_DIAGNOSTIC_ARTIFACT = exports.isProcessorDiagnosticArtifact = exports.createProcessorDiagnosticArtifact = exports.BaseProcessor = void 0;
var BaseProcessor_1 = require("./BaseProcessor");
Object.defineProperty(exports, "BaseProcessor", { enumerable: true, get: function () { return BaseProcessor_1.BaseProcessor; } });
var diagnostics_1 = require("./diagnostics");
Object.defineProperty(exports, "createProcessorDiagnosticArtifact", { enumerable: true, get: function () { return diagnostics_1.createProcessorDiagnosticArtifact; } });
Object.defineProperty(exports, "isProcessorDiagnosticArtifact", { enumerable: true, get: function () { return diagnostics_1.isProcessorDiagnosticArtifact; } });
Object.defineProperty(exports, "PROCESSOR_DIAGNOSTIC_ARTIFACT", { enumerable: true, get: function () { return diagnostics_1.PROCESSOR_DIAGNOSTIC_ARTIFACT; } });
__exportStar(require("./types"), exports);
var buildSlug_1 = require("./utils/buildSlug");
Object.defineProperty(exports, "buildSlug", { enumerable: true, get: function () { return buildSlug_1.buildSlug; } });
var validateParams_1 = require("./utils/validateParams");
Object.defineProperty(exports, "isValidParams", { enumerable: true, get: function () { return validateParams_1.isValidParams; } });
Object.defineProperty(exports, "validateParams", { enumerable: true, get: function () { return validateParams_1.validateParams; } });
var TaggedTemplateProcessor_1 = require("./TaggedTemplateProcessor");
Object.defineProperty(exports, "TaggedTemplateProcessor", { enumerable: true, get: function () { return TaggedTemplateProcessor_1.TaggedTemplateProcessor; } });
var toValidCSSIdentifier_1 = require("./utils/toValidCSSIdentifier");
Object.defineProperty(exports, "toValidCSSIdentifier", { enumerable: true, get: function () { return toValidCSSIdentifier_1.toValidCSSIdentifier; } });
export { BaseProcessor } from './BaseProcessor';
export { expressionToCode } from './ast';
export { createProcessorDiagnosticArtifact, isProcessorDiagnosticArtifact, PROCESSOR_DIAGNOSTIC_ARTIFACT, } from './diagnostics';
export * from './types';
export { buildSlug } from './utils/buildSlug';
export { isValidParams, validateParams } from './utils/validateParams';
export { TaggedTemplateProcessor } from './TaggedTemplateProcessor';
export { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';

@@ -1,2 +0,2 @@

import type { Expression, SourceLocation } from '@babel/types';
import type { Expression, SourceLocation } from './ast';
import type { TailProcessorParams } from './BaseProcessor';

@@ -3,0 +3,0 @@ import { BaseProcessor } from './BaseProcessor';

@@ -1,21 +0,15 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaggedTemplateProcessor = void 0;
const shared_1 = require("@wyw-in-js/shared");
const BaseProcessor_1 = require("./BaseProcessor");
const templateProcessor_1 = __importDefault(require("./utils/templateProcessor"));
const validateParams_1 = require("./utils/validateParams");
class TaggedTemplateProcessor extends BaseProcessor_1.BaseProcessor {
import { ValueType } from '@wyw-in-js/shared';
import { BaseProcessor } from './BaseProcessor';
import templateProcessor from './utils/templateProcessor';
import { validateParams } from './utils/validateParams';
export class TaggedTemplateProcessor extends BaseProcessor {
#template;
constructor(params, ...args) {
// Should have at least two params and the first one should be a callee.
(0, validateParams_1.validateParams)(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
(0, validateParams_1.validateParams)(params, ['callee', 'template'], 'Invalid usage of template tag');
validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
validateParams(params, ['callee', 'template'], 'Invalid usage of template tag');
const [tag, [, template]] = params;
super([tag], ...args);
template.forEach((element) => {
if ('kind' in element && element.kind !== shared_1.ValueType.FUNCTION) {
if ('kind' in element && element.kind !== ValueType.FUNCTION) {
this.dependencies.push(element);

@@ -31,3 +25,3 @@ }

}
const artifact = (0, templateProcessor_1.default)(this, this.#template, values, this.options.variableNameConfig);
const artifact = templateProcessor(this, this.#template, values, this.options.variableNameConfig);
if (artifact) {

@@ -41,2 +35,1 @@ this.artifacts.push(['css', artifact]);

}
exports.TaggedTemplateProcessor = TaggedTemplateProcessor;

@@ -1,3 +0,3 @@

import type { Expression, Identifier, TemplateElement, MemberExpression } from '@babel/types';
import type { ExpressionValue, Location, WYWEvalMeta } from '@wyw-in-js/shared';
import type { Expression, Identifier, MemberExpression, TemplateElement } from './ast';
export type CSSPropertyValue = string | number;

@@ -4,0 +4,0 @@ export type ObjectWithSelectors = {

@@ -1,2 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildSlug = buildSlug;
const PLACEHOLDER = /\[(.*?)]/g;
const isValidArgName = (key, args) => key in args;
function buildSlug(pattern, args) {
export function buildSlug(pattern, args) {
return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : '');
}

@@ -1,18 +0,15 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getClassNameAndSlug;
const path_1 = require("path");
const shared_1 = require("@wyw-in-js/shared");
const buildSlug_1 = require("./buildSlug");
const toValidCSSIdentifier_1 = require("./toValidCSSIdentifier");
function getClassNameAndSlug(displayName, idx, options, context) {
import { basename, dirname, extname, relative, sep, posix } from 'path';
import { logger, slugify } from '@wyw-in-js/shared';
import { buildSlug } from './buildSlug';
import { toValidCSSIdentifier } from './toValidCSSIdentifier';
export default function getClassNameAndSlug(displayName, idx, options, context) {
const relativeFilename = (context.root && context.filename
? (0, path_1.relative)(context.root, context.filename)
: context.filename ?? 'unknown').replace(/\\/g, path_1.posix.sep);
? relative(context.root, context.filename)
: context.filename ?? 'unknown').replace(/\\/g, posix.sep);
// Custom properties need to start with a letter, so we prefix the slug
// Also use append the index of the class to the filename for uniqueness in the file
const slug = (0, toValidCSSIdentifier_1.toValidCSSIdentifier)(`${displayName.charAt(0).toLowerCase()}${(0, shared_1.slugify)(`${relativeFilename}:${idx}`)}`);
const slug = toValidCSSIdentifier(`${displayName.charAt(0).toLowerCase()}${slugify(`${relativeFilename}:${idx}`)}`);
// Collect some useful replacement patterns from the filename
// Available variables for the square brackets used in `classNameSlug` options
const ext = (0, path_1.extname)(relativeFilename);
const ext = extname(relativeFilename);
const slugVars = {

@@ -24,7 +21,7 @@ hash: slug,

ext,
name: (0, path_1.basename)(relativeFilename, ext),
dir: (0, path_1.dirname)(relativeFilename).split(path_1.sep).pop(),
name: basename(relativeFilename, ext),
dir: dirname(relativeFilename).split(sep).pop(),
};
let className = options.displayName
? `${(0, toValidCSSIdentifier_1.toValidCSSIdentifier)(displayName)}_${slug}`
? `${toValidCSSIdentifier(displayName)}_${slug}`
: slug;

@@ -34,3 +31,3 @@ // The className can be defined by the user either as fn or a string

try {
className = (0, toValidCSSIdentifier_1.toValidCSSIdentifier)(options.classNameSlug(slug, displayName, slugVars));
className = toValidCSSIdentifier(options.classNameSlug(slug, displayName, slugVars));
}

@@ -42,6 +39,6 @@ catch {

if (typeof options.classNameSlug === 'string') {
className = (0, toValidCSSIdentifier_1.toValidCSSIdentifier)((0, buildSlug_1.buildSlug)(options.classNameSlug, slugVars));
className = toValidCSSIdentifier(buildSlug(options.classNameSlug, slugVars));
}
shared_1.logger.extend('template-parse:generated-meta')(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
logger.extend('template-parse:generated-meta')(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
return { className, slug };
}

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getVariableName = getVariableName;
function getVariableName(varId, rawVariableName) {
export function getVariableName(varId, rawVariableName) {
switch (rawVariableName) {

@@ -6,0 +3,0 @@ case 'raw':

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = stripLines;
// Stripping away the new lines ensures that we preserve line numbers
// This is useful in case of tools such as the stylelint pre-processor
// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings
function stripLines(loc, text) {
export default function stripLines(loc, text) {
let result = String(text)

@@ -9,0 +6,0 @@ .replace(/[\r\n]+/g, ' ')

@@ -5,7 +5,7 @@ /**

*/
import type { TemplateElement } from '@babel/types';
import type { ExpressionValue, Replacements } from '@wyw-in-js/shared';
import type { TaggedTemplateProcessor } from '../TaggedTemplateProcessor';
import type { TemplateElement } from '../ast';
import type { ValueCache, Rules } from '../types';
import type { IOptions } from './types';
export default function templateProcessor(tagProcessor: TaggedTemplateProcessor, [...template]: (TemplateElement | ExpressionValue)[], valueCache: ValueCache, variableNameConfig: IOptions['variableNameConfig'] | undefined): [rules: Rules, sourceMapReplacements: Replacements] | null;

@@ -1,2 +0,1 @@

"use strict";
/* eslint-disable no-continue */

@@ -7,49 +6,11 @@ /**

*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = templateProcessor;
const shared_1 = require("@wyw-in-js/shared");
const getVariableName_1 = require("./getVariableName");
const stripLines_1 = __importDefault(require("./stripLines"));
const throwIfInvalid_1 = __importDefault(require("./throwIfInvalid"));
const toCSS_1 = __importStar(require("./toCSS"));
const units_1 = require("./units");
import { hasEvalMeta, ValueType } from '@wyw-in-js/shared';
import { getVariableName } from './getVariableName';
import stripLines from './stripLines';
import throwIfInvalid from './throwIfInvalid';
import toCSS, { isCSSable } from './toCSS';
import { units } from './units';
// Match any valid CSS unit not immediately followed by an alphanumeric character or underscore.
const unitRegex = new RegExp(`^(?:${units_1.units.join('|')})(?![a-zA-Z0-9_])`);
function templateProcessor(tagProcessor, [...template], valueCache, variableNameConfig) {
const unitRegex = new RegExp(`^(?:${units.join('|')})(?![a-zA-Z0-9_])`);
export default function templateProcessor(tagProcessor, [...template], valueCache, variableNameConfig) {
const sourceMapReplacements = [];

@@ -83,3 +44,3 @@ // Check if the variable is referenced anywhere for basic DCE

// Is it props based interpolation?
if (item.kind === shared_1.ValueType.FUNCTION || typeof value === 'function') {
if (item.kind === ValueType.FUNCTION || typeof value === 'function') {
// Check if previous expression was a CSS variable that we replaced

@@ -97,3 +58,3 @@ // If it has a unit after it, we need to move the unit into the interpolation

const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source, unit);
cssText += (0, getVariableName_1.getVariableName)(varId, variableNameConfig);
cssText += getVariableName(varId, variableNameConfig);
cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';

@@ -103,3 +64,3 @@ }

const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source);
cssText += (0, getVariableName_1.getVariableName)(varId, variableNameConfig);
cssText += getVariableName(varId, variableNameConfig);
}

@@ -115,3 +76,3 @@ }

else {
(0, throwIfInvalid_1.default)(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
throwIfInvalid(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
if (value !== undefined && typeof value !== 'function') {

@@ -122,3 +83,3 @@ // Skip the blank string instead of throw ing an error

}
if ((0, shared_1.hasEvalMeta)(value)) {
if (hasEvalMeta(value)) {
// If it's a React component wrapped in styled, get the class name

@@ -128,9 +89,9 @@ // Useful for interpolating components

}
else if ((0, toCSS_1.isCSSable)(value)) {
else if (isCSSable(value)) {
// If it's a plain object or an array, convert it to a CSS string
cssText += (0, stripLines_1.default)(loc, (0, toCSS_1.default)(value));
cssText += stripLines(loc, toCSS(value));
}
else {
// For anything else, assume it'll be stringified
cssText += (0, stripLines_1.default)(loc, value);
cssText += stripLines(loc, value);
}

@@ -137,0 +98,0 @@ sourceMapReplacements.push({

@@ -1,3 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const isLikeError = (value) => typeof value === 'object' &&

@@ -32,2 +30,2 @@ value !== null &&

}
exports.default = throwIfInvalid;
export default throwIfInvalid;

@@ -1,13 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCSSable = void 0;
exports.default = toCSS;
const shared_1 = require("@wyw-in-js/shared");
const units_1 = require("./units");
import { isBoxedPrimitive } from '@wyw-in-js/shared';
import { unitless } from './units';
const isCSSPropertyValue = (o) => {
return ((0, shared_1.isBoxedPrimitive)(o) ||
return (isBoxedPrimitive(o) ||
typeof o === 'string' ||
(typeof o === 'number' && Number.isFinite(o)));
};
const isCSSable = (o) => {
export const isCSSable = (o) => {
if (isCSSPropertyValue(o)) {

@@ -17,10 +13,9 @@ return true;

if (Array.isArray(o)) {
return o.every(exports.isCSSable);
return o.every(isCSSable);
}
if (typeof o === 'object') {
return o !== null && Object.values(o).every(exports.isCSSable);
return o !== null && Object.values(o).every(isCSSable);
}
return false;
};
exports.isCSSable = isCSSable;
const hyphenate = (s) => {

@@ -39,3 +34,3 @@ if (s.startsWith('--')) {

// To support them transparently, we convert JS objects to CSS strings
function toCSS(o) {
export default function toCSS(o) {
if (Array.isArray(o)) {

@@ -58,3 +53,3 @@ return o.map(toCSS).join('\n');

// Strip vendor prefixes when checking if the value is unitless
!(key.replace(/^(Webkit|Moz|O|ms)([A-Z])(.+)$/, (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`) in units_1.unitless)
!(key.replace(/^(Webkit|Moz|O|ms)([A-Z])(.+)$/, (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`) in unitless)
? `${value}px`

@@ -61,0 +56,0 @@ : value};`;

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toValidCSSIdentifier = toValidCSSIdentifier;
function toValidCSSIdentifier(s) {
export function toValidCSSIdentifier(s) {
return s.replace(/[^-_a-z0-9\u00A0-\uFFFF]/gi, '_').replace(/^\d/, '_');
}

@@ -1,2 +0,1 @@

import type { TransformOptions } from '@babel/core';
import type { ClassNameFn, VariableNameFn } from '@wyw-in-js/shared';

@@ -10,2 +9,5 @@ export interface IOptions {

}
export type IFileContext = Pick<TransformOptions, 'root' | 'filename'>;
export type IFileContext = {
filename?: string | null;
root?: string | null;
};

@@ -1,2 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unitless = exports.units = void 0;
// https://www.w3.org/TR/css-values-4/
exports.units = [
export const units = [
// font relative lengths

@@ -51,3 +48,3 @@ 'em',

];
exports.unitless = {
export const unitless = {
animationIterationCount: true,

@@ -54,0 +51,0 @@ borderImageOutset: true,

@@ -1,6 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidParams = isValidParams;
exports.validateParams = validateParams;
function isValidParams(params, constraints) {
export function isValidParams(params, constraints) {
const length = Math.max(params.length, constraints.length);

@@ -31,3 +27,3 @@ for (let i = 0; i < length; i++) {

}
function validateParams(params, constraints, messageOrError) {
export function validateParams(params, constraints, messageOrError) {
if (!isValidParams(params, constraints)) {

@@ -34,0 +30,0 @@ if (typeof messageOrError === 'string') {

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BaseProcessor = void 0;
var _generator = _interopRequireDefault(require("@babel/generator"));
var _shared = require("@wyw-in-js/shared");
var _diagnostics = require("./diagnostics");
var _getClassNameAndSlug = _interopRequireDefault(require("./utils/getClassNameAndSlug"));
var _toCSS = require("./utils/toCSS");
var _validateParams = require("./utils/validateParams");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/* eslint-disable class-methods-use-this */
class BaseProcessor {
static SKIP = Symbol('skip');
artifacts = [];
dependencies = [];
interpolations = [];
constructor(params, tagSource, astService, location, replacer, displayName, isReferenced, idx, options, context) {
this.tagSource = tagSource;
this.astService = astService;
this.location = location;
this.replacer = replacer;
this.displayName = displayName;
this.isReferenced = isReferenced;
this.idx = idx;
this.options = options;
this.context = context;
(0, _validateParams.validateParams)(params, ['callee'], 'Unknown error: a callee param is not specified');
const {
className,
slug
} = (0, _getClassNameAndSlug.default)(this.displayName, this.idx, this.options, this.context);
this.className = className;
this.slug = slug;
[[, this.callee]] = params;
}
/**
* A replacement for tag referenced in a template literal.
*/
/**
* A replacement for the tag in evaluation time.
* For example, `css` tag will be replaced with its className,
* whereas `styled` tag will be replaced with an object with metadata.
*/
addDiagnostic(diagnostic) {
var _ref, _diagnostic$end, _this$location, _ref2, _diagnostic$start, _this$location2;
this.artifacts.push((0, _diagnostics.createProcessorDiagnosticArtifact)({
...diagnostic,
end: (_ref = (_diagnostic$end = diagnostic.end) !== null && _diagnostic$end !== void 0 ? _diagnostic$end : (_this$location = this.location) === null || _this$location === void 0 ? void 0 : _this$location.end) !== null && _ref !== void 0 ? _ref : null,
start: (_ref2 = (_diagnostic$start = diagnostic.start) !== null && _diagnostic$start !== void 0 ? _diagnostic$start : (_this$location2 = this.location) === null || _this$location2 === void 0 ? void 0 : _this$location2.start) !== null && _ref2 !== void 0 ? _ref2 : null
}));
}
isValidValue(value) {
return typeof value === 'function' || (0, _toCSS.isCSSable)(value) || (0, _shared.hasEvalMeta)(value);
}
toString() {
return this.tagSourceCode();
}
tagSourceCode() {
if (this.callee.type === 'Identifier') {
return this.callee.name;
}
return (0, _generator.default)(this.callee).code;
}
/**
* Perform a replacement for the tag in evaluation time.
* For example, `css` tag will be replaced with its className,
* whereas `styled` tag will be replaced with an object with metadata.
*/
/**
* Perform a replacement for the tag with its runtime version.
* For example, `css` tag will be replaced with its className,
* whereas `styled` tag will be replaced with a component.
* If some parts require evaluated data for render,
* they will be replaced with placeholders.
*/
}
exports.BaseProcessor = BaseProcessor;
//# sourceMappingURL=BaseProcessor.js.map
{"version":3,"file":"BaseProcessor.js","names":["_generator","_interopRequireDefault","require","_shared","_diagnostics","_getClassNameAndSlug","_toCSS","_validateParams","e","__esModule","default","BaseProcessor","SKIP","Symbol","artifacts","dependencies","interpolations","constructor","params","tagSource","astService","location","replacer","displayName","isReferenced","idx","options","context","validateParams","className","slug","getClassNameAndSlug","callee","addDiagnostic","diagnostic","_ref","_diagnostic$end","_this$location","_ref2","_diagnostic$start","_this$location2","push","createProcessorDiagnosticArtifact","end","start","isValidValue","value","isCSSable","hasEvalMeta","toString","tagSourceCode","type","name","generator","code","exports"],"sources":["../src/BaseProcessor.ts"],"sourcesContent":["/* eslint-disable class-methods-use-this */\nimport type { NodePath, types as t } from '@babel/core';\nimport generator from '@babel/generator';\nimport type {\n Expression,\n Identifier,\n SourceLocation,\n MemberExpression,\n} from '@babel/types';\n\nimport type { Artifact, ExpressionValue } from '@wyw-in-js/shared';\nimport { hasEvalMeta } from '@wyw-in-js/shared';\n\nimport { createProcessorDiagnosticArtifact } from './diagnostics';\nimport type {\n IInterpolation,\n Params,\n ProcessorDiagnostic,\n Value,\n ValueCache,\n} from './types';\nimport getClassNameAndSlug from './utils/getClassNameAndSlug';\nimport { isCSSable } from './utils/toCSS';\nimport type { IFileContext, IOptions } from './utils/types';\nimport { validateParams } from './utils/validateParams';\n\nexport { Expression };\n\nexport type ProcessorParams = ConstructorParameters<typeof BaseProcessor>;\nexport type TailProcessorParams = ProcessorParams extends [Params, ...infer T]\n ? T\n : never;\n\nexport type TagSource = {\n imported: string;\n source: string;\n};\n\nexport abstract class BaseProcessor {\n public static SKIP = Symbol('skip');\n\n public readonly artifacts: Artifact[] = [];\n\n public readonly className: string;\n\n public readonly dependencies: ExpressionValue[] = [];\n\n public interpolations: IInterpolation[] = [];\n\n public readonly slug: string;\n\n protected callee: Identifier | MemberExpression;\n\n protected evaluated:\n | Record<'dependencies' | 'expression', Value[]>\n | undefined;\n\n public constructor(\n params: Params,\n public tagSource: TagSource,\n protected readonly astService: typeof t & {\n addDefaultImport: (source: string, nameHint?: string) => Identifier;\n addNamedImport: (\n name: string,\n source: string,\n nameHint?: string\n ) => Identifier;\n },\n public readonly location: SourceLocation | null,\n protected readonly replacer: (\n replacement: Expression | ((tagPath: NodePath) => Expression),\n isPure: boolean\n ) => void,\n public readonly displayName: string,\n public readonly isReferenced: boolean,\n protected readonly idx: number,\n protected readonly options: IOptions,\n protected readonly context: IFileContext\n ) {\n validateParams(\n params,\n ['callee'],\n 'Unknown error: a callee param is not specified'\n );\n\n const { className, slug } = getClassNameAndSlug(\n this.displayName,\n this.idx,\n this.options,\n this.context\n );\n\n this.className = className;\n this.slug = slug;\n\n [[, this.callee]] = params;\n }\n\n /**\n * A replacement for tag referenced in a template literal.\n */\n public abstract get asSelector(): string;\n\n /**\n * A replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract get value(): Expression;\n\n public addDiagnostic(diagnostic: ProcessorDiagnostic): void {\n this.artifacts.push(\n createProcessorDiagnosticArtifact({\n ...diagnostic,\n end: diagnostic.end ?? this.location?.end ?? null,\n start: diagnostic.start ?? this.location?.start ?? null,\n })\n );\n }\n\n public isValidValue(value: unknown): value is Value {\n return (\n typeof value === 'function' || isCSSable(value) || hasEvalMeta(value)\n );\n }\n\n public toString(): string {\n return this.tagSourceCode();\n }\n\n protected tagSourceCode(): string {\n if (this.callee.type === 'Identifier') {\n return this.callee.name;\n }\n\n return generator(this.callee).code;\n }\n\n public abstract build(values: ValueCache): void;\n\n /**\n * Perform a replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract doEvaltimeReplacement(): void;\n\n /**\n * Perform a replacement for the tag with its runtime version.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with a component.\n * If some parts require evaluated data for render,\n * they will be replaced with placeholders.\n */\n public abstract doRuntimeReplacement(): void;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,UAAA,GAAAC,sBAAA,CAAAC,OAAA;AASA,IAAAC,OAAA,GAAAD,OAAA;AAEA,IAAAE,YAAA,GAAAF,OAAA;AAQA,IAAAG,oBAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,MAAA,GAAAJ,OAAA;AAEA,IAAAK,eAAA,GAAAL,OAAA;AAAwD,SAAAD,uBAAAO,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAxBxD;;AAsCO,MAAeG,aAAa,CAAC;EAClC,OAAcC,IAAI,GAAGC,MAAM,CAAC,MAAM,CAAC;EAEnBC,SAAS,GAAe,EAAE;EAI1BC,YAAY,GAAsB,EAAE;EAE7CC,cAAc,GAAqB,EAAE;EAUrCC,WAAWA,CAChBC,MAAc,EACPC,SAAoB,EACRC,UAOlB,EACeC,QAA+B,EAC5BC,QAGV,EACOC,WAAmB,EACnBC,YAAqB,EAClBC,GAAW,EACXC,OAAiB,EACjBC,OAAqB,EACxC;IAAA,KAnBOR,SAAoB,GAApBA,SAAoB;IA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AAI,IAAI,CAACnB,QAAQ,cAAAmB,eAAA,uBAAbA,eAAA,CAAeI,KAAK,cAAAN,KAAA,cAAAA,KAAA,GAAI;IACrD,CAAC,CACH,CAAC;EACH;EAEOO,YAAYA,CAACC,KAAc,EAAkB;IAClD,OACE,OAAOA,KAAK,KAAK,UAAU,IAAI,IAAAC,gBAAS,EAACD,KAAK,CAAC,IAAI,IAAAE,mBAAW,EAACF,KAAK,CAAC;EAEzE;EAEOG,QAAQA,CAAA,EAAW;IACxB,OAAO,IAAI,CAACC,aAAa,CAAC,CAAC;EAC7B;EAEUA,aAAaA,CAAA,EAAW;IAChC,IAAI,IAAI,CAAClB,MAAM,CAACmB,IAAI,KAAK,YAAY,EAAE;MACrC,OAAO,IAAI,CAACnB,MAAM,CAACoB,IAAI;IACzB;IAEA,OAAO,IAAAC,kBAAS,EAAC,IAAI,CAACrB,MAAM,CAAC,CAACsB,IAAI;EACpC;;EAIA;AACF;AACA;AACA;AACA;;EAGE;AACF;AACA;AACA;AACA;AACA;AACA;AAEA;AAACC,OAAA,CAAA5C,aAAA,GAAAA,aAAA","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isProcessorDiagnosticArtifact = exports.createProcessorDiagnosticArtifact = exports.PROCESSOR_DIAGNOSTIC_ARTIFACT = void 0;
const PROCESSOR_DIAGNOSTIC_ARTIFACT = exports.PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic';
const createProcessorDiagnosticArtifact = diagnostic => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];
exports.createProcessorDiagnosticArtifact = createProcessorDiagnosticArtifact;
const isProcessorDiagnosticArtifact = artifact => artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;
exports.isProcessorDiagnosticArtifact = isProcessorDiagnosticArtifact;
//# sourceMappingURL=diagnostics.js.map
{"version":3,"file":"diagnostics.js","names":["PROCESSOR_DIAGNOSTIC_ARTIFACT","exports","createProcessorDiagnosticArtifact","diagnostic","isProcessorDiagnosticArtifact","artifact"],"sources":["../src/diagnostics.ts"],"sourcesContent":["import type { Artifact } from '@wyw-in-js/shared';\n\nimport type { ProcessorDiagnostic } from './types';\n\nexport const PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic' as const;\n\nexport type ProcessorDiagnosticArtifact = [\n name: typeof PROCESSOR_DIAGNOSTIC_ARTIFACT,\n data: ProcessorDiagnostic,\n];\n\nexport const createProcessorDiagnosticArtifact = (\n diagnostic: ProcessorDiagnostic\n): ProcessorDiagnosticArtifact => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];\n\nexport const isProcessorDiagnosticArtifact = (\n artifact: Artifact\n): artifact is ProcessorDiagnosticArtifact =>\n artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;\n"],"mappings":";;;;;;AAIO,MAAMA,6BAA6B,GAAAC,OAAA,CAAAD,6BAAA,GAAG,sBAA+B;AAOrE,MAAME,iCAAiC,GAC5CC,UAA+B,IACC,CAACH,6BAA6B,EAAEG,UAAU,CAAC;AAACF,OAAA,CAAAC,iCAAA,GAAAA,iCAAA;AAEvE,MAAME,6BAA6B,GACxCC,QAAkB,IAElBA,QAAQ,CAAC,CAAC,CAAC,KAAKL,6BAA6B;AAACC,OAAA,CAAAG,6BAAA,GAAAA,6BAAA","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
BaseProcessor: true,
createProcessorDiagnosticArtifact: true,
isProcessorDiagnosticArtifact: true,
PROCESSOR_DIAGNOSTIC_ARTIFACT: true,
buildSlug: true,
isValidParams: true,
validateParams: true,
TaggedTemplateProcessor: true,
toValidCSSIdentifier: true
};
Object.defineProperty(exports, "BaseProcessor", {
enumerable: true,
get: function () {
return _BaseProcessor.BaseProcessor;
}
});
Object.defineProperty(exports, "PROCESSOR_DIAGNOSTIC_ARTIFACT", {
enumerable: true,
get: function () {
return _diagnostics.PROCESSOR_DIAGNOSTIC_ARTIFACT;
}
});
Object.defineProperty(exports, "TaggedTemplateProcessor", {
enumerable: true,
get: function () {
return _TaggedTemplateProcessor.TaggedTemplateProcessor;
}
});
Object.defineProperty(exports, "buildSlug", {
enumerable: true,
get: function () {
return _buildSlug.buildSlug;
}
});
Object.defineProperty(exports, "createProcessorDiagnosticArtifact", {
enumerable: true,
get: function () {
return _diagnostics.createProcessorDiagnosticArtifact;
}
});
Object.defineProperty(exports, "isProcessorDiagnosticArtifact", {
enumerable: true,
get: function () {
return _diagnostics.isProcessorDiagnosticArtifact;
}
});
Object.defineProperty(exports, "isValidParams", {
enumerable: true,
get: function () {
return _validateParams.isValidParams;
}
});
Object.defineProperty(exports, "toValidCSSIdentifier", {
enumerable: true,
get: function () {
return _toValidCSSIdentifier.toValidCSSIdentifier;
}
});
Object.defineProperty(exports, "validateParams", {
enumerable: true,
get: function () {
return _validateParams.validateParams;
}
});
var _BaseProcessor = require("./BaseProcessor");
var _diagnostics = require("./diagnostics");
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _types[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _types[key];
}
});
});
var _buildSlug = require("./utils/buildSlug");
var _validateParams = require("./utils/validateParams");
var _TaggedTemplateProcessor = require("./TaggedTemplateProcessor");
var _toValidCSSIdentifier = require("./utils/toValidCSSIdentifier");
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","names":["_BaseProcessor","require","_diagnostics","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_buildSlug","_validateParams","_TaggedTemplateProcessor","_toValidCSSIdentifier"],"sources":["../src/index.ts"],"sourcesContent":["export { BaseProcessor } from './BaseProcessor';\nexport {\n createProcessorDiagnosticArtifact,\n isProcessorDiagnosticArtifact,\n PROCESSOR_DIAGNOSTIC_ARTIFACT,\n} from './diagnostics';\nexport type { ProcessorDiagnosticArtifact } from './diagnostics';\nexport type {\n Expression,\n TagSource,\n ProcessorParams,\n TailProcessorParams,\n} from './BaseProcessor';\nexport * from './types';\nexport { buildSlug } from './utils/buildSlug';\nexport type { IOptions, IFileContext } from './utils/types';\nexport { isValidParams, validateParams } from './utils/validateParams';\nexport type { MapParams, ParamConstraints } from './utils/validateParams';\nexport { TaggedTemplateProcessor } from './TaggedTemplateProcessor';\nexport { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,cAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AAYA,IAAAE,MAAA,GAAAF,OAAA;AAAAG,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,UAAA,GAAAf,OAAA;AAEA,IAAAgB,eAAA,GAAAhB,OAAA;AAEA,IAAAiB,wBAAA,GAAAjB,OAAA;AACA,IAAAkB,qBAAA,GAAAlB,OAAA","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TaggedTemplateProcessor = void 0;
var _shared = require("@wyw-in-js/shared");
var _BaseProcessor = require("./BaseProcessor");
var _templateProcessor = _interopRequireDefault(require("./utils/templateProcessor"));
var _validateParams = require("./utils/validateParams");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
class TaggedTemplateProcessor extends _BaseProcessor.BaseProcessor {
#template;
constructor(params, ...args) {
// Should have at least two params and the first one should be a callee.
(0, _validateParams.validateParams)(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
(0, _validateParams.validateParams)(params, ['callee', 'template'], 'Invalid usage of template tag');
const [tag, [, template]] = params;
super([tag], ...args);
template.forEach(element => {
if ('kind' in element && element.kind !== _shared.ValueType.FUNCTION) {
this.dependencies.push(element);
}
});
this.#template = template;
}
build(values) {
if (this.artifacts.length > 0) {
// FIXME: why it was called twice?
throw new Error('Tag is already built');
}
const artifact = (0, _templateProcessor.default)(this, this.#template, values, this.options.variableNameConfig);
if (artifact) {
this.artifacts.push(['css', artifact]);
}
}
toString() {
return `${super.toString()}\`…\``;
}
/**
* It is called for each resolved expression in a template literal.
* @param node
* @param precedingCss
* @param source
* @param unit
* @return chunk of CSS that should be added to extracted CSS
*/
}
exports.TaggedTemplateProcessor = TaggedTemplateProcessor;
//# sourceMappingURL=TaggedTemplateProcessor.js.map
{"version":3,"file":"TaggedTemplateProcessor.js","names":["_shared","require","_BaseProcessor","_templateProcessor","_interopRequireDefault","_validateParams","e","__esModule","default","TaggedTemplateProcessor","BaseProcessor","template","constructor","params","args","validateParams","SKIP","tag","forEach","element","kind","ValueType","FUNCTION","dependencies","push","build","values","artifacts","length","Error","artifact","templateProcessor","options","variableNameConfig","toString","exports"],"sources":["../src/TaggedTemplateProcessor.ts"],"sourcesContent":["import type { TemplateElement, Expression, SourceLocation } from '@babel/types';\n\nimport type { ExpressionValue } from '@wyw-in-js/shared';\nimport { ValueType } from '@wyw-in-js/shared';\n\nimport type { TailProcessorParams } from './BaseProcessor';\nimport { BaseProcessor } from './BaseProcessor';\nimport type { ValueCache, Rules, Params } from './types';\nimport templateProcessor from './utils/templateProcessor';\nimport { validateParams } from './utils/validateParams';\n\nexport abstract class TaggedTemplateProcessor extends BaseProcessor {\n readonly #template: (TemplateElement | ExpressionValue)[];\n\n protected constructor(params: Params, ...args: TailProcessorParams) {\n // Should have at least two params and the first one should be a callee.\n validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);\n\n validateParams(\n params,\n ['callee', 'template'],\n 'Invalid usage of template tag'\n );\n const [tag, [, template]] = params;\n\n super([tag], ...args);\n\n template.forEach((element) => {\n if ('kind' in element && element.kind !== ValueType.FUNCTION) {\n this.dependencies.push(element);\n }\n });\n\n this.#template = template;\n }\n\n public override build(values: ValueCache) {\n if (this.artifacts.length > 0) {\n // FIXME: why it was called twice?\n throw new Error('Tag is already built');\n }\n\n const artifact = templateProcessor(\n this,\n this.#template,\n values,\n this.options.variableNameConfig\n );\n if (artifact) {\n this.artifacts.push(['css', artifact]);\n }\n }\n\n public override toString(): string {\n return `${super.toString()}\\`…\\``;\n }\n\n /**\n * It is called for each resolved expression in a template literal.\n * @param node\n * @param precedingCss\n * @param source\n * @param unit\n * @return chunk of CSS that should be added to extracted CSS\n */\n public abstract addInterpolation(\n node: Expression,\n precedingCss: string,\n source: string,\n unit?: string\n ): string;\n\n public abstract extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): Rules;\n}\n"],"mappings":";;;;;;AAGA,IAAAA,OAAA,GAAAC,OAAA;AAGA,IAAAC,cAAA,GAAAD,OAAA;AAEA,IAAAE,kBAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AAAwD,SAAAG,uBAAAE,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAEjD,MAAeG,uBAAuB,SAASC,4BAAa,CAAC;EACzD,CAACC,QAAQ;EAERC,WAAWA,CAACC,MAAc,EAAE,GAAGC,IAAyB,EAAE;IAClE;IACA,IAAAC,8BAAc,EAACF,MAAM,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAEJ,uBAAuB,CAACO,IAAI,CAAC;IAEvE,IAAAD,8BAAc,EACZF,MAAM,EACN,CAAC,QAAQ,EAAE,UAAU,CAAC,EACtB,+BACF,CAAC;IACD,MAAM,CAACI,GAAG,EAAE,GAAGN,QAAQ,CAAC,CAAC,GAAGE,MAAM;IAElC,KAAK,CAAC,CAACI,GAAG,CAAC,EAAE,GAAGH,IAAI,CAAC;IAErBH,QAAQ,CAACO,OAAO,CAAEC,OAAO,IAAK;MAC5B,IAAI,MAAM,IAAIA,OAAO,IAAIA,OAAO,CAACC,IAAI,KAAKC,iBAAS,CAACC,QAAQ,EAAE;QAC5D,IAAI,CAACC,YAAY,CAACC,IAAI,CAACL,OAAO,CAAC;MACjC;IACF,CAAC,CAAC;IAEF,IAAI,CAAC,CAACR,QAAQ,GAAGA,QAAQ;EAC3B;EAEgBc,KAAKA,CAACC,MAAkB,EAAE;IACxC,IAAI,IAAI,CAACC,SAAS,CAACC,MAAM,GAAG,CAAC,EAAE;MAC7B;MACA,MAAM,IAAIC,KAAK,CAAC,sBAAsB,CAAC;IACzC;IAEA,MAAMC,QAAQ,GAAG,IAAAC,0BAAiB,EAChC,IAAI,EACJ,IAAI,CAAC,CAACpB,QAAQ,EACde,MAAM,EACN,IAAI,CAACM,OAAO,CAACC,kBACf,CAAC;IACD,IAAIH,QAAQ,EAAE;MACZ,IAAI,CAACH,SAAS,CAACH,IAAI,CAAC,CAAC,KAAK,EAAEM,QAAQ,CAAC,CAAC;IACxC;EACF;EAEgBI,QAAQA,CAAA,EAAW;IACjC,OAAO,GAAG,KAAK,CAACA,QAAQ,CAAC,CAAC,OAAO;EACnC;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AAaA;AAACC,OAAA,CAAA1B,uBAAA,GAAAA,uBAAA","ignoreList":[]}
"use strict";
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n Expression,\n Identifier,\n TemplateElement,\n MemberExpression,\n} from '@babel/types';\n\nimport type { ExpressionValue, Location, WYWEvalMeta } from '@wyw-in-js/shared';\n\nexport type CSSPropertyValue = string | number;\n\nexport type ObjectWithSelectors = {\n [key: string]:\n | ObjectWithSelectors\n | CSSPropertyValue\n | (ObjectWithSelectors | CSSPropertyValue)[];\n};\n\nexport type CSSable = ObjectWithSelectors[string];\n\nexport type Value = (() => void) | WYWEvalMeta | CSSable;\n\nexport type ValueCache = Map<string | number | boolean | null, unknown>;\n\nexport interface ICSSRule {\n atom?: boolean;\n className: string;\n cssText: string;\n displayName: string;\n start: Location | null | undefined;\n}\n\nexport interface IInterpolation {\n id: string;\n node: Expression;\n source: string;\n unit: string;\n}\n\nexport type ProcessorDiagnosticSeverity = 'error' | 'warning';\n\nexport type ProcessorDiagnostic = {\n category: string;\n end?: Location | null;\n message: string;\n severity: ProcessorDiagnosticSeverity;\n start?: Location | null;\n};\n\nexport type Rules = Record<string, ICSSRule>;\n\nexport type CalleeParam = readonly ['callee', Identifier | MemberExpression];\nexport type CallParam = readonly ['call', ...ExpressionValue[]];\nexport type MemberParam = readonly ['member', string];\nexport type TemplateParam = readonly [\n 'template',\n (TemplateElement | ExpressionValue)[],\n];\n\nexport type Param = CalleeParam | CallParam | MemberParam | TemplateParam;\nexport type Params = readonly Param[];\n"],"mappings":"","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildSlug = buildSlug;
const PLACEHOLDER = /\[(.*?)]/g;
const isValidArgName = (key, args) => key in args;
function buildSlug(pattern, args) {
return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : '');
}
//# sourceMappingURL=buildSlug.js.map
{"version":3,"file":"buildSlug.js","names":["PLACEHOLDER","isValidArgName","key","args","buildSlug","pattern","replace","_","name","toString"],"sources":["../../src/utils/buildSlug.ts"],"sourcesContent":["const PLACEHOLDER = /\\[(.*?)]/g;\n\nconst isValidArgName = <TArgs extends Record<string, { toString(): string }>>(\n key: string | number | symbol,\n args: TArgs\n): key is keyof TArgs => key in args;\n\nexport function buildSlug<TArgs extends Record<string, { toString(): string }>>(\n pattern: string,\n args: TArgs\n) {\n return pattern.replace(PLACEHOLDER, (_, name: string) =>\n isValidArgName(name, args) ? args[name].toString() : ''\n );\n}\n"],"mappings":";;;;;;AAAA,MAAMA,WAAW,GAAG,WAAW;AAE/B,MAAMC,cAAc,GAAGA,CACrBC,GAA6B,EAC7BC,IAAW,KACYD,GAAG,IAAIC,IAAI;AAE7B,SAASC,SAASA,CACvBC,OAAe,EACfF,IAAW,EACX;EACA,OAAOE,OAAO,CAACC,OAAO,CAACN,WAAW,EAAE,CAACO,CAAC,EAAEC,IAAY,KAClDP,cAAc,CAACO,IAAI,EAAEL,IAAI,CAAC,GAAGA,IAAI,CAACK,IAAI,CAAC,CAACC,QAAQ,CAAC,CAAC,GAAG,EACvD,CAAC;AACH","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getClassNameAndSlug;
var _path = require("path");
var _shared = require("@wyw-in-js/shared");
var _buildSlug = require("./buildSlug");
var _toValidCSSIdentifier = require("./toValidCSSIdentifier");
function getClassNameAndSlug(displayName, idx, options, context) {
var _context$filename;
const relativeFilename = (context.root && context.filename ? (0, _path.relative)(context.root, context.filename) : (_context$filename = context.filename) !== null && _context$filename !== void 0 ? _context$filename : 'unknown').replace(/\\/g, _path.posix.sep);
// Custom properties need to start with a letter, so we prefix the slug
// Also use append the index of the class to the filename for uniqueness in the file
const slug = (0, _toValidCSSIdentifier.toValidCSSIdentifier)(`${displayName.charAt(0).toLowerCase()}${(0, _shared.slugify)(`${relativeFilename}:${idx}`)}`);
// Collect some useful replacement patterns from the filename
// Available variables for the square brackets used in `classNameSlug` options
const ext = (0, _path.extname)(relativeFilename);
const slugVars = {
hash: slug,
title: displayName,
index: idx,
file: relativeFilename,
ext,
name: (0, _path.basename)(relativeFilename, ext),
dir: (0, _path.dirname)(relativeFilename).split(_path.sep).pop()
};
let className = options.displayName ? `${(0, _toValidCSSIdentifier.toValidCSSIdentifier)(displayName)}_${slug}` : slug;
// The className can be defined by the user either as fn or a string
if (typeof options.classNameSlug === 'function') {
try {
className = (0, _toValidCSSIdentifier.toValidCSSIdentifier)(options.classNameSlug(slug, displayName, slugVars));
} catch {
throw new Error('classNameSlug option must return a string');
}
}
if (typeof options.classNameSlug === 'string') {
className = (0, _toValidCSSIdentifier.toValidCSSIdentifier)((0, _buildSlug.buildSlug)(options.classNameSlug, slugVars));
}
_shared.logger.extend('template-parse:generated-meta')(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
return {
className,
slug
};
}
//# sourceMappingURL=getClassNameAndSlug.js.map
{"version":3,"file":"getClassNameAndSlug.js","names":["_path","require","_shared","_buildSlug","_toValidCSSIdentifier","getClassNameAndSlug","displayName","idx","options","context","_context$filename","relativeFilename","root","filename","relative","replace","posix","sep","slug","toValidCSSIdentifier","charAt","toLowerCase","slugify","ext","extname","slugVars","hash","title","index","file","name","basename","dir","dirname","split","pop","className","classNameSlug","Error","buildSlug","logger","extend"],"sources":["../../src/utils/getClassNameAndSlug.ts"],"sourcesContent":["import { basename, dirname, extname, relative, sep, posix } from 'path';\n\nimport type { ClassNameSlugVars } from '@wyw-in-js/shared';\nimport { logger, slugify } from '@wyw-in-js/shared';\n\nimport { buildSlug } from './buildSlug';\nimport { toValidCSSIdentifier } from './toValidCSSIdentifier';\nimport type { IFileContext, IOptions } from './types';\n\nexport default function getClassNameAndSlug(\n displayName: string,\n idx: number,\n options: IOptions,\n context: IFileContext\n): { className: string; slug: string } {\n const relativeFilename = (\n context.root && context.filename\n ? relative(context.root, context.filename)\n : context.filename ?? 'unknown'\n ).replace(/\\\\/g, posix.sep);\n\n // Custom properties need to start with a letter, so we prefix the slug\n // Also use append the index of the class to the filename for uniqueness in the file\n const slug = toValidCSSIdentifier(\n `${displayName.charAt(0).toLowerCase()}${slugify(\n `${relativeFilename}:${idx}`\n )}`\n );\n\n // Collect some useful replacement patterns from the filename\n // Available variables for the square brackets used in `classNameSlug` options\n const ext = extname(relativeFilename);\n const slugVars: ClassNameSlugVars = {\n hash: slug,\n title: displayName,\n index: idx,\n file: relativeFilename,\n ext,\n name: basename(relativeFilename, ext),\n dir: dirname(relativeFilename).split(sep).pop() as string,\n };\n\n let className = options.displayName\n ? `${toValidCSSIdentifier(displayName!)}_${slug!}`\n : slug!;\n\n // The className can be defined by the user either as fn or a string\n if (typeof options.classNameSlug === 'function') {\n try {\n className = toValidCSSIdentifier(\n options.classNameSlug(slug, displayName, slugVars)\n );\n } catch {\n throw new Error('classNameSlug option must return a string');\n }\n }\n\n if (typeof options.classNameSlug === 'string') {\n className = toValidCSSIdentifier(\n buildSlug(options.classNameSlug, slugVars)\n );\n }\n\n logger.extend('template-parse:generated-meta')(\n `slug: ${slug}, displayName: ${displayName}, className: ${className}`\n );\n\n return { className, slug };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAGA,IAAAC,OAAA,GAAAD,OAAA;AAEA,IAAAE,UAAA,GAAAF,OAAA;AACA,IAAAG,qBAAA,GAAAH,OAAA;AAGe,SAASI,mBAAmBA,CACzCC,WAAmB,EACnBC,GAAW,EACXC,OAAiB,EACjBC,OAAqB,EACgB;EAAA,IAAAC,iBAAA;EACrC,MAAMC,gBAAgB,GAAG,CACvBF,OAAO,CAACG,IAAI,IAAIH,OAAO,CAACI,QAAQ,GAC5B,IAAAC,cAAQ,EAACL,OAAO,CAACG,IAAI,EAAEH,OAAO,CAACI,QAAQ,CAAC,IAAAH,iBAAA,GACxCD,OAAO,CAACI,QAAQ,cAAAH,iBAAA,cAAAA,iBAAA,GAAI,SAAS,EACjCK,OAAO,CAAC,KAAK,EAAEC,WAAK,CAACC,GAAG,CAAC;;EAE3B;EACA;EACA,MAAMC,IAAI,GAAG,IAAAC,0CAAoB,EAC/B,GAAGb,WAAW,CAACc,MAAM,CAAC,CAAC,CAAC,CAACC,WAAW,CAAC,CAAC,GAAG,IAAAC,e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object.defineProperty(exports, "__esModule", {
value: true
});
exports.getVariableName = getVariableName;
function getVariableName(varId, rawVariableName) {
switch (rawVariableName) {
case 'raw':
return varId;
case 'dashes':
return `--${varId}`;
case 'var':
default:
return `var(--${varId})`;
}
}
//# sourceMappingURL=getVariableName.js.map
{"version":3,"file":"getVariableName.js","names":["getVariableName","varId","rawVariableName"],"sources":["../../src/utils/getVariableName.ts"],"sourcesContent":["import type { IOptions } from './types';\n\nexport function getVariableName(\n varId: string,\n rawVariableName: IOptions['variableNameConfig'] | undefined\n) {\n switch (rawVariableName) {\n case 'raw':\n return varId;\n case 'dashes':\n return `--${varId}`;\n case 'var':\n default:\n return `var(--${varId})`;\n }\n}\n"],"mappings":";;;;;;AAEO,SAASA,eAAeA,CAC7BC,KAAa,EACbC,eAA2D,EAC3D;EACA,QAAQA,eAAe;IACrB,KAAK,KAAK;MACR,OAAOD,KAAK;IACd,KAAK,QAAQ;MACX,OAAO,KAAKA,KAAK,EAAE;IACrB,KAAK,KAAK;IACV;MACE,OAAO,SAASA,KAAK,GAAG;EAC5B;AACF","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = stripLines;
// Stripping away the new lines ensures that we preserve line numbers
// This is useful in case of tools such as the stylelint pre-processor
// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings
function stripLines(loc, text) {
let result = String(text).replace(/[\r\n]+/g, ' ').trim();
// If the start and end line numbers aren't same, add new lines to span the text across multiple lines
if (loc.start.line !== loc.end.line) {
result += '\n'.repeat(loc.end.line - loc.start.line);
// Add extra spaces to offset the column
result += ' '.repeat(loc.end.column);
}
return result;
}
//# sourceMappingURL=stripLines.js.map
{"version":3,"file":"stripLines.js","names":["stripLines","loc","text","result","String","replace","trim","start","line","end","repeat","column"],"sources":["../../src/utils/stripLines.ts"],"sourcesContent":["import type { Location } from '@wyw-in-js/shared';\n\n// Stripping away the new lines ensures that we preserve line numbers\n// This is useful in case of tools such as the stylelint pre-processor\n// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings\nexport default function stripLines(\n loc: { end: Location; start: Location },\n text: string | number\n) {\n let result = String(text)\n .replace(/[\\r\\n]+/g, ' ')\n .trim();\n\n // If the start and end line numbers aren't same, add new lines to span the text across multiple lines\n if (loc.start.line !== loc.end.line) {\n result += '\\n'.repeat(loc.end.line - loc.start.line);\n\n // Add extra spaces to offset the column\n result += ' '.repeat(loc.end.column);\n }\n\n return result;\n}\n"],"mappings":";;;;;;AAEA;AACA;AACA;AACe,SAASA,UAAUA,CAChCC,GAAuC,EACvCC,IAAqB,EACrB;EACA,IAAIC,MAAM,GAAGC,MAAM,CAACF,IAAI,CAAC,CACtBG,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CACxBC,IAAI,CAAC,CAAC;;EAET;EACA,IAAIL,GAAG,CAACM,KAAK,CAACC,IAAI,KAAKP,GAAG,CAACQ,GAAG,CAACD,IAAI,EAAE;IACnCL,MAAM,IAAI,IAAI,CAACO,MAAM,CAACT,GAAG,CAACQ,GAAG,CAACD,IAAI,GAAGP,GAAG,CAACM,KAAK,CAACC,IAAI,CAAC;;IAEpD;IACAL,MAAM,IAAI,GAAG,CAACO,MAAM,CAACT,GAAG,CAACQ,GAAG,CAACE,MAAM,CAAC;EACtC;EAEA,OAAOR,MAAM;AACf","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = templateProcessor;
var _shared = require("@wyw-in-js/shared");
var _getVariableName = require("./getVariableName");
var _stripLines = _interopRequireDefault(require("./stripLines"));
var _throwIfInvalid = _interopRequireDefault(require("./throwIfInvalid"));
var _toCSS = _interopRequireWildcard(require("./toCSS"));
var _units = require("./units");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/* eslint-disable no-continue */
/**
* This file handles transforming template literals to class names or styled components and generates CSS content.
* It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.
*/
// Match any valid CSS unit not immediately followed by an alphanumeric character or underscore.
const unitRegex = new RegExp(`^(?:${_units.units.join('|')})(?![a-zA-Z0-9_])`);
function templateProcessor(tagProcessor, [...template], valueCache, variableNameConfig) {
const sourceMapReplacements = [];
// Check if the variable is referenced anywhere for basic DCE
// Only works when it's assigned to a variable
const {
isReferenced
} = tagProcessor;
// Serialize the tagged template literal to a string
let cssText = '';
let item;
// eslint-disable-next-line no-cond-assign
while (item = template.shift()) {
if ('type' in item) {
// It's a template element
cssText += item.value.cooked;
continue;
}
// It's an expression
const {
ex
} = item;
const {
end,
start
} = ex.loc;
const beforeLength = cssText.length;
// The location will be end of the current string to start of next string
const next = template[0]; // template[0] is the next template element
const loc = {
start,
end: next ? {
line: next.loc.start.line,
column: next.loc.start.column
} : {
line: end.line,
column: end.column + 1
}
};
const value = 'value' in item ? item.value : valueCache.get(item.ex.name);
// Is it props based interpolation?
if (item.kind === _shared.ValueType.FUNCTION || typeof value === 'function') {
var _next$value$cooked;
// Check if previous expression was a CSS variable that we replaced
// If it has a unit after it, we need to move the unit into the interpolation
// e.g. `var(--size)px` should actually be `var(--size)`
// So we check if the current text starts with a unit, and add the unit to the previous interpolation
// Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units
// https://bugzilla.mozilla.org/show_bug.cgi?id=956573
const matches = (_next$value$cooked = next.value.cooked) === null || _next$value$cooked === void 0 ? void 0 : _next$value$cooked.match(unitRegex);
try {
if (matches) {
var _next$value$cooked$su, _next$value$cooked2, _unit$length;
template.shift();
const [unit] = matches;
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source, unit);
cssText += (0, _getVariableName.getVariableName)(varId, variableNameConfig);
cssText += (_next$value$cooked$su = (_next$value$cooked2 = next.value.cooked) === null || _next$value$cooked2 === void 0 ? void 0 : _next$value$cooked2.substring((_unit$length = unit === null || unit === void 0 ? void 0 : unit.length) !== null && _unit$length !== void 0 ? _unit$length : 0)) !== null && _next$value$cooked$su !== void 0 ? _next$value$cooked$su : '';
} else {
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source);
cssText += (0, _getVariableName.getVariableName)(varId, variableNameConfig);
}
} catch (e) {
if (e instanceof Error) {
throw item.buildCodeFrameError(e.message);
}
throw e;
}
} else {
(0, _throwIfInvalid.default)(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
if (value !== undefined && typeof value !== 'function') {
// Skip the blank string instead of throw ing an error
if (value === '') {
continue;
}
if ((0, _shared.hasEvalMeta)(value)) {
// If it's a React component wrapped in styled, get the class name
// Useful for interpolating components
cssText += `.${value.__wyw_meta.className}`;
} else if ((0, _toCSS.isCSSable)(value)) {
// If it's a plain object or an array, convert it to a CSS string
cssText += (0, _stripLines.default)(loc, (0, _toCSS.default)(value));
} else {
// For anything else, assume it'll be stringified
cssText += (0, _stripLines.default)(loc, value);
}
sourceMapReplacements.push({
original: loc,
length: cssText.length - beforeLength
});
}
}
}
const rules = tagProcessor.extractRules(valueCache, cssText, tagProcessor.location);
// tagProcessor.doRuntimeReplacement(classes);
if (!isReferenced && !cssText.includes(':global')) {
return null;
}
// eslint-disable-next-line no-param-reassign
return [rules, sourceMapReplacements];
}
//# sourceMappingURL=templateProcessor.js.map
{"version":3,"file":"templateProcessor.js","names":["_shared","require","_getVariableName","_stripLines","_interopRequireDefault","_throwIfInvalid","_toCSS","_interopRequireWildcard","_units","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","unitRegex","RegExp","units","join","templateProcessor","tagProcessor","template","valueCache","variableNameConfig","sourceMapReplacements","isReferenced","cssText","item","shift","value","cooked","ex","end","start","loc","beforeLength","length","next","line","column","name","kind","ValueType","FUNCTION","_next$value$cooked","matches","match","_next$value$cooked$su","_next$value$cooked2","_unit$length","unit","varId","addInterpolation","source","getVariableName","substring","Error","buildCodeFrameError","message","throwIfInvalid","isValidValue","bind","undefined","hasEvalMeta","__wyw_meta","className","isCSSable","stripLines","toCSS","push","original","rules","extractRules","location","includes"],"sources":["../../src/utils/templateProcessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\n/**\n * This file handles transforming template literals to class names or styled components and generates CSS content.\n * It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.\n */\n\nimport type { TemplateElement } from '@babel/types';\n\nimport type { ExpressionValue, Replacements } from '@wyw-in-js/shared';\nimport { hasEvalMeta, ValueType } from '@wyw-in-js/shared';\n\nimport type { TaggedTemplateProcessor } from '../TaggedTemplateProcessor';\nimport type { ValueCache, Rules } from '../types';\n\nimport { getVariableName } from './getVariableName';\nimport stripLines from './stripLines';\nimport throwIfInvalid from './throwIfInvalid';\nimport toCSS, { isCSSable } from './toCSS';\nimport type { IOptions } from './types';\nimport { units } from './units';\n\n// Match any valid CSS unit not immediately followed by an alphanumeric character or underscore.\nconst unitRegex = new RegExp(`^(?:${units.join('|')})(?![a-zA-Z0-9_])`);\n\nexport default function templateProcessor(\n tagProcessor: TaggedTemplateProcessor,\n [...template]: (TemplateElement | ExpressionValue)[],\n valueCache: ValueCache,\n variableNameConfig: IOptions['variableNameConfig'] | undefined\n): [rules: Rules, sourceMapReplacements: Replacements] | null {\n const sourceMapReplacements: Replacements = [];\n // Check if the variable is referenced anywhere for basic DCE\n // Only works when it's assigned to a variable\n const { isReferenced } = tagProcessor;\n\n // Serialize the tagged template literal to a string\n let cssText = '';\n\n let item: TemplateElement | ExpressionValue | undefined;\n // eslint-disable-next-line no-cond-assign\n while ((item = template.shift())) {\n if ('type' in item) {\n // It's a template element\n cssText += item.value.cooked;\n continue;\n }\n\n // It's an expression\n const { ex } = item;\n\n const { end, start } = ex.loc!;\n const beforeLength = cssText.length;\n\n // The location will be end of the current string to start of next string\n const next = template[0] as TemplateElement; // template[0] is the next template element\n const loc = {\n start,\n end: next\n ? { line: next.loc!.start.line, column: next.loc!.start.column }\n : { line: end.line, column: end.column + 1 },\n };\n\n const value = 'value' in item ? item.value : valueCache.get(item.ex.name);\n\n // Is it props based interpolation?\n if (item.kind === ValueType.FUNCTION || typeof value === 'function') {\n // Check if previous expression was a CSS variable that we replaced\n // If it has a unit after it, we need to move the unit into the interpolation\n // e.g. `var(--size)px` should actually be `var(--size)`\n // So we check if the current text starts with a unit, and add the unit to the previous interpolation\n // Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units\n // https://bugzilla.mozilla.org/show_bug.cgi?id=956573\n const matches = next.value.cooked?.match(unitRegex);\n\n try {\n if (matches) {\n template.shift();\n const [unit] = matches;\n\n const varId = tagProcessor.addInterpolation(\n item.ex,\n cssText,\n item.source,\n unit\n );\n cssText += getVariableName(varId, variableNameConfig);\n\n cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';\n } else {\n const varId = tagProcessor.addInterpolation(\n item.ex,\n cssText,\n item.source\n );\n cssText += getVariableName(varId, variableNameConfig);\n }\n } catch (e) {\n if (e instanceof Error) {\n throw item.buildCodeFrameError(e.message);\n }\n\n throw e;\n }\n } else {\n throwIfInvalid(\n tagProcessor.isValidValue.bind(tagProcessor),\n value,\n item,\n item.source\n );\n\n if (value !== undefined && typeof value !== 'function') {\n // Skip the blank string instead of throw ing an error\n if (value === '') {\n continue;\n }\n\n if (hasEvalMeta(value)) {\n // If it's a React component wrapped in styled, get the class name\n // Useful for interpolating components\n cssText += `.${value.__wyw_meta.className}`;\n } else if (isCSSable(value)) {\n // If it's a plain object or an array, convert it to a CSS string\n cssText += stripLines(loc, toCSS(value));\n } else {\n // For anything else, assume it'll be stringified\n cssText += stripLines(loc, value);\n }\n\n sourceMapReplacements.push({\n original: loc,\n length: cssText.length - beforeLength,\n });\n }\n }\n }\n\n const rules = tagProcessor.extractRules(\n valueCache,\n cssText,\n tagProcessor.location\n );\n\n // tagProcessor.doRuntimeReplacement(classes);\n if (!isReferenced && !cssText.includes(':global')) {\n return null;\n }\n\n // eslint-disable-next-line no-param-reassign\n return [rules, sourceMapReplacements];\n}\n"],"mappings":";;;;;;AASA,IAAAA,OAAA,GAAAC,OAAA;AAKA,IAAAC,gBAAA,GAAAD,OAAA;AACA,IAAAE,WAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,eAAA,GAAAD,sBAAA,CAAAH,OAAA;AACA,IAAAK,MAAA,GAAAC,uBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAAgC,SAAAM,wBAAAE,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAJ,uBAAA,YAAAA,CAAAE,CAAA,EAAAC,CAAA,SAAAA,CAAA,IAAAD,CAAA,IAAAA,CAAA,CAAAK,UAAA,SAAAL,CAAA,MAAAM,CAAA,EAAAC,CAAA,EAAAC,CAAA,KAAAC,SAAA,QAAAC,OAAA,EAAAV,CAAA,iBAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,SAAAQ,CAAA,MAAAF,CAAA,GAAAL,CAAA,GAAAG,CAAA,GAAAD,CAAA,QAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,UAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,GAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,EAAAQ,CAAA,gBAAAP,CAAA,IAAAD,CAAA,gBAAAC,CAAA,OAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,EAAAC,CAAA,OAAAM,CAAA,IAAAD,CAAA,GAAAU,MAAA,CAAAC,cAAA,KAAAD,MAAA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AM,GAAGD;QAC3B,CAAC,CAAC;MACJ;IACF;EACF;EAEA,MAAMoC,KAAK,GAAGnD,YAAY,CAACoD,YAAY,CACrClD,UAAU,EACVI,OAAO,EACPN,YAAY,CAACqD,QACf,CAAC;;EAED;EACA,IAAI,CAAChD,YAAY,IAAI,CAACC,OAAO,CAACgD,QAAQ,CAAC,SAAS,CAAC,EAAE;IACjD,OAAO,IAAI;EACb;;EAEA;EACA,OAAO,CAACH,KAAK,EAAE/C,qBAAqB,CAAC;AACvC","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const isLikeError = value => typeof value === 'object' && value !== null && 'stack' in value && 'message' in value;
// Throw if we can't handle the interpolated value
function throwIfInvalid(checker, value, ex, source) {
// We can't use instanceof here so let's use duck typing
if (isLikeError(value) && value.stack && value.message) {
throw ex.buildCodeFrameError(`An error occurred when evaluating the expression:
> ${value.message}.
Make sure you are not using a browser or Node specific API and all the variables are available in static context.
Linaria have to extract pieces of your code to resolve the interpolated values.
Defining styled component or class will not work inside:
- function,
- class,
- method,
- loop,
because it cannot be statically determined in which context you use them.
That's why some variables may be not defined during evaluation.
`);
}
if (checker(value)) {
return;
}
const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value);
throw ex.buildCodeFrameError(`The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`);
}
var _default = exports.default = throwIfInvalid;
//# sourceMappingURL=throwIfInvalid.js.map
{"version":3,"file":"throwIfInvalid.js","names":["isLikeError","value","throwIfInvalid","checker","ex","source","stack","message","buildCodeFrameError","stringified","JSON","stringify","String","_default","exports","default"],"sources":["../../src/utils/throwIfInvalid.ts"],"sourcesContent":["import type { BuildCodeFrameErrorFn } from '@wyw-in-js/shared';\n\nconst isLikeError = (value: unknown): value is Error =>\n typeof value === 'object' &&\n value !== null &&\n 'stack' in value &&\n 'message' in value;\n\n// Throw if we can't handle the interpolated value\nfunction throwIfInvalid<T>(\n checker: (value: unknown) => value is T,\n value: Error | unknown,\n ex: { buildCodeFrameError: BuildCodeFrameErrorFn },\n source: string\n): asserts value is T {\n // We can't use instanceof here so let's use duck typing\n if (isLikeError(value) && value.stack && value.message) {\n throw ex.buildCodeFrameError(\n `An error occurred when evaluating the expression:\n\n > ${value.message}.\n\n Make sure you are not using a browser or Node specific API and all the variables are available in static context.\n Linaria have to extract pieces of your code to resolve the interpolated values.\n Defining styled component or class will not work inside:\n - function,\n - class,\n - method,\n - loop,\n because it cannot be statically determined in which context you use them.\n That's why some variables may be not defined during evaluation.\n `\n );\n }\n\n if (checker(value)) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n throw ex.buildCodeFrameError(\n `The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`\n );\n}\n\nexport default throwIfInvalid;\n"],"mappings":";;;;;;AAEA,MAAMA,WAAW,GAAIC,KAAc,IACjC,OAAOA,KAAK,KAAK,QAAQ,IACzBA,KAAK,KAAK,IAAI,IACd,OAAO,IAAIA,KAAK,IAChB,SAAS,IAAIA,KAAK;;AAEpB;AACA,SAASC,cAAcA,CACrBC,OAAuC,EACvCF,KAAsB,EACtBG,EAAkD,EAClDC,MAAc,EACM;EACpB;EACA,IAAIL,WAAW,CAACC,KAAK,CAAC,IAAIA,KAAK,CAACK,KAAK,IAAIL,KAAK,CAACM,OAAO,EAAE;IACtD,MAAMH,EAAE,CAACI,mBAAmB,CAC1B;AACN;AACA,MAAMP,KAAK,CAACM,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OACI,CAAC;EACH;EAEA,IAAIJ,OAAO,CAACF,KAAK,CAAC,EAAE;IAClB;EACF;EAEA,MAAMQ,WAAW,GACf,OAAOR,KAAK,KAAK,QAAQ,GAAGS,IAAI,CAACC,SAAS,CAACV,KAAK,CAAC,GAAGW,MAAM,CAACX,KAAK,CAAC;EAEnE,MAAMG,EAAE,CAACI,mBAAmB,CAC1B,gCAAgCC,WAAW,8IAA8IJ,MAAM,KACjM,CAAC;AACH;AAAC,IAAAQ,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcb,cAAc","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toCSS;
exports.isCSSable = void 0;
var _shared = require("@wyw-in-js/shared");
var _units = require("./units");
const isCSSPropertyValue = o => {
return (0, _shared.isBoxedPrimitive)(o) || typeof o === 'string' || typeof o === 'number' && Number.isFinite(o);
};
const isCSSable = o => {
if (isCSSPropertyValue(o)) {
return true;
}
if (Array.isArray(o)) {
return o.every(isCSSable);
}
if (typeof o === 'object') {
return o !== null && Object.values(o).every(isCSSable);
}
return false;
};
exports.isCSSable = isCSSable;
const hyphenate = s => {
if (s.startsWith('--')) {
// It's a custom property which is already well formatted.
return s;
}
return s
// Hyphenate CSS property names from camelCase version from JS string
.replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)
// Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`
.replace(/^ms-/, '-ms-');
};
// Some tools such as polished.js output JS objects
// To support them transparently, we convert JS objects to CSS strings
function toCSS(o) {
if (Array.isArray(o)) {
return o.map(toCSS).join('\n');
}
if (isCSSPropertyValue(o)) {
return o.valueOf().toString();
}
return Object.entries(o).filter(([, value]) =>
// Ignore all falsy values except numbers
typeof value === 'number' || value).map(([key, value]) => {
if (!isCSSPropertyValue(value)) {
return `${key} { ${toCSS(value)} }`;
}
return `${hyphenate(key)}: ${typeof value === 'number' && value !== 0 &&
// Strip vendor prefixes when checking if the value is unitless
!(key.replace(/^(Webkit|Moz|O|ms)([A-Z])(.+)$/, (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`) in _units.unitless) ? `${value}px` : value};`;
}).join(' ');
}
//# sourceMappingURL=toCSS.js.map
{"version":3,"file":"toCSS.js","names":["_shared","require","_units","isCSSPropertyValue","o","isBoxedPrimitive","Number","isFinite","isCSSable","Array","isArray","every","Object","values","exports","hyphenate","s","startsWith","replace","match","p1","toLowerCase","toCSS","map","join","valueOf","toString","entries","filter","value","key","p2","p3","unitless"],"sources":["../../src/utils/toCSS.ts"],"sourcesContent":["import { isBoxedPrimitive } from '@wyw-in-js/shared';\n\nimport type { CSSPropertyValue, CSSable } from '../types';\n\nimport { unitless } from './units';\n\nconst isCSSPropertyValue = (o: unknown): o is CSSPropertyValue => {\n return (\n isBoxedPrimitive(o) ||\n typeof o === 'string' ||\n (typeof o === 'number' && Number.isFinite(o))\n );\n};\n\nexport const isCSSable = (o: unknown): o is CSSable => {\n if (isCSSPropertyValue(o)) {\n return true;\n }\n\n if (Array.isArray(o)) {\n return o.every(isCSSable);\n }\n\n if (typeof o === 'object') {\n return o !== null && Object.values(o).every(isCSSable);\n }\n\n return false;\n};\n\nconst hyphenate = (s: string) => {\n if (s.startsWith('--')) {\n // It's a custom property which is already well formatted.\n return s;\n }\n return (\n s\n // Hyphenate CSS property names from camelCase version from JS string\n .replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)\n // Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`\n .replace(/^ms-/, '-ms-')\n );\n};\n\n// Some tools such as polished.js output JS objects\n// To support them transparently, we convert JS objects to CSS strings\nexport default function toCSS(o: CSSable): string {\n if (Array.isArray(o)) {\n return o.map(toCSS).join('\\n');\n }\n\n if (isCSSPropertyValue(o)) {\n return o.valueOf().toString();\n }\n\n return Object.entries(o)\n .filter(\n ([, value]) =>\n // Ignore all falsy values except numbers\n typeof value === 'number' || value\n )\n .map(([key, value]) => {\n if (!isCSSPropertyValue(value)) {\n return `${key} { ${toCSS(value)} }`;\n }\n\n return `${hyphenate(key)}: ${\n typeof value === 'number' &&\n value !== 0 &&\n // Strip vendor prefixes when checking if the value is unitless\n !(\n key.replace(\n /^(Webkit|Moz|O|ms)([A-Z])(.+)$/,\n (match, p1, p2, p3) => `${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IACpB,OAAOA,CAAC,CAACmB,GAAG,CAACD,KAAK,CAAC,CAACE,IAAI,CAAC,IAAI,CAAC;EAChC;EAEA,IAAIrB,kBAAkB,CAACC,CAAC,CAAC,EAAE;IACzB,OAAOA,CAAC,CAACqB,OAAO,CAAC,CAAC,CAACC,QAAQ,CAAC,CAAC;EAC/B;EAEA,OAAOd,MAAM,CAACe,OAAO,CAACvB,CAAC,CAAC,CACrBwB,MAAM,CACL,CAAC,GAAGC,KAAK,CAAC;EACR;EACA,OAAOA,KAAK,KAAK,QAAQ,IAAIA,KACjC,CAAC,CACAN,GAAG,CAAC,CAAC,CAACO,GAAG,EAAED,KAAK,CAAC,KAAK;IACrB,IAAI,CAAC1B,kBAAkB,CAAC0B,KAAK,CAAC,EAAE;MAC9B,OAAO,GAAGC,GAAG,MAAMR,KAAK,CAACO,KAAK,CAAC,IAAI;IACrC;IAEA,OAAO,GAAGd,SAAS,CAACe,GAAG,CAAC,KACtB,OAAOD,KAAK,KAAK,QAAQ,IACzBA,KAAK,KAAK,CAAC;IACX;IACA,EACEC,GAAG,CAACZ,OAAO,CACT,gCAAgC,EAChC,CAACC,KAAK,EAAEC,EAAE,EAAEW,EAAE,EAAEC,EAAE,KAAK,GAAGD,EAAE,CAACV,WAAW,CAAC,CAAC,GAAGW,EAAE,EACjD,CAAC,IAAIC,eAAQ,CACd,GACG,GAAGJ,KAAK,IAAI,GACZA,KAAK,GACR;EACL,CAAC,CAAC,CACDL,IAAI,CAAC,GAAG,CAAC;AACd","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.toValidCSSIdentifier = toValidCSSIdentifier;
function toValidCSSIdentifier(s) {
return s.replace(/[^-_a-z0-9\u00A0-\uFFFF]/gi, '_').replace(/^\d/, '_');
}
//# sourceMappingURL=toValidCSSIdentifier.js.map
{"version":3,"file":"toValidCSSIdentifier.js","names":["toValidCSSIdentifier","s","replace"],"sources":["../../src/utils/toValidCSSIdentifier.ts"],"sourcesContent":["export function toValidCSSIdentifier(s: string) {\n return s.replace(/[^-_a-z0-9\\u00A0-\\uFFFF]/gi, '_').replace(/^\\d/, '_');\n}\n"],"mappings":";;;;;;AAAO,SAASA,oBAAoBA,CAACC,CAAS,EAAE;EAC9C,OAAOA,CAAC,CAACC,OAAO,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAACA,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;AACzE","ignoreList":[]}
"use strict";
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","names":[],"sources":["../../src/utils/types.ts"],"sourcesContent":["import type { TransformOptions } from '@babel/core';\n\nimport type { ClassNameFn, VariableNameFn } from '@wyw-in-js/shared';\n\nexport interface IOptions {\n classNameSlug?: string | ClassNameFn;\n displayName: boolean;\n extensions?: string[];\n variableNameConfig?: 'var' | 'dashes' | 'raw';\n variableNameSlug?: string | VariableNameFn;\n}\n\nexport type IFileContext = Pick<TransformOptions, 'root' | 'filename'>;\n"],"mappings":"","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.units = exports.unitless = void 0;
// https://www.w3.org/TR/css-values-4/
const units = exports.units = [
// font relative lengths
'em', 'ex', 'cap', 'ch', 'ic', 'rem', 'lh', 'rlh',
// viewport percentage lengths
'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax',
// absolute lengths
'cm', 'mm', 'Q', 'in', 'pc', 'pt', 'px',
// angle units
'deg', 'grad', 'rad', 'turn',
// duration units
's', 'ms',
// frequency units
'Hz', 'kHz',
// resolution units
'dpi', 'dpcm', 'dppx', 'x',
// https://www.w3.org/TR/css-grid-1/#fr-unit
'fr',
// percentages
'%'];
const unitless = exports.unitless = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
//# sourceMappingURL=units.js.map
{"version":3,"file":"units.js","names":["units","exports","unitless","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"],"sources":["../../src/utils/units.ts"],"sourcesContent":["// https://www.w3.org/TR/css-values-4/\nexport const units = [\n // font relative lengths\n 'em',\n 'ex',\n 'cap',\n 'ch',\n 'ic',\n 'rem',\n 'lh',\n 'rlh',\n\n // viewport percentage lengths\n 'vw',\n 'vh',\n 'vi',\n 'vb',\n 'vmin',\n 'vmax',\n\n // absolute lengths\n 'cm',\n 'mm',\n 'Q',\n 'in',\n 'pc',\n 'pt',\n 'px',\n\n // angle units\n 'deg',\n 'grad',\n 'rad',\n 'turn',\n\n // duration units\n 's',\n 'ms',\n\n // frequency units\n 'Hz',\n 'kHz',\n\n // resolution units\n 'dpi',\n 'dpcm',\n 'dppx',\n 'x',\n\n // https://www.w3.org/TR/css-grid-1/#fr-unit\n 'fr',\n\n // percentages\n '%',\n];\n\nexport const unitless = {\n animationIterationCount: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true,\n};\n"],"mappings":";;;;;;AAAA;AACO,MAAMA,KAAK,GAAAC,OAAA,CAAAD,KAAA,GAAG;AACnB;AACA,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,IAAI,EACJ,KAAK;AAEL;AACA,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,MAAM;AAEN;AACA,IAAI,EACJ,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI;AAEJ;AACA,KAAK,EACL,MAAM,EACN,KAAK,EACL,MAAM;AAEN;AACA,GAAG,EACH,IAAI;AAEJ;AACA,IAAI,EACJ,KAAK;AAEL;AACA,KAAK,EACL,MAAM,EACN,MAAM,EACN,GAAG;AAEH;AACA,IAAI;AAEJ;AACA,GAAG,CACJ;AAEM,MAAME,QAAQ,GAAAD,OAAA,CAAAC,QAAA,GAAG;EACtBC,uBAAuB,EAAE,IAAI;EAC7BC,iBAAiB,EAAE,IAAI;EACvBC,gBAAgB,EAAE,IAAI;EACtBC,gBAAgB,EAAE,IAAI;EACtBC,OAAO,EAAE,IAAI;EACbC,YAAY,EAAE,IAAI;EAClBC,eAAe,EAAE,IAAI;EACrBC,WAAW,EAAE,IAAI;EACjBC,OAAO,EAAE,IAAI;EACbC,IAAI,EAAE,IAAI;EACVC,QAAQ,EAAE,IAAI;EACdC,YAAY,EAAE,IAAI;EAClBC,UAAU,EAAE,IAAI;EAChBC,YAAY,EAAE,IAAI;EAClBC,SAAS,EAAE,IAAI;EACfC,OAAO,EAAE,IAAI;EACbC,UAAU,EAAE,IAAI;EAChBC,WAAW,EAAE,IAAI;EACjBC,YAAY,EAAE,IAAI;EAClBC,UAAU,EAAE,IAAI;EAChBC,aAAa,EAAE,IAAI;EACnBC,cAAc,EAAE,IAAI;EACpBC,eAAe,EAAE,IAAI;EACrBC,UAAU,EAAE,IAAI;EAChBC,SAAS,EAAE,IAAI;EACfC,UAAU,EAAE,IAAI;EAChBC,OAAO,EAAE,IAAI;EACbC,KAAK,EAAE,IAAI;EACXC,OAAO,EAAE,IAAI;EACbC,OAAO,EAAE,IAAI;EACbC,MAAM,EAAE,IAAI;EACZC,MAAM,EAAE,IAAI;EACZC,IAAI,EAAE,IAAI;EAEV;EACAC,WAAW,EAAE,IAAI;EACjBC,YAAY,EAAE,IAAI;EAClBC,WAAW,EAAE,IAAI;EACjBC,eAAe,EAAE,IAAI;EACrBC,gBAAgB,EAAE,IAAI;EACtBC,gBAAgB,EAAE,IAAI;EACtBC,aAAa,EAAE,IAAI;EACnBC,WAAW,EAAE;AACf,CAAC","ignoreList":[]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isValidParams = isValidParams;
exports.validateParams = validateParams;
// ParamMapping maps each ParamName to its corresponding Param type.
// GetParamByName returns the Param type based on the input type T.
// If T is none of the above, return never.
// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.
// If TNames is an empty tuple, return the result tuple.
function isValidParams(params, constraints) {
const length = Math.max(params.length, constraints.length);
for (let i = 0; i < length; i++) {
var _params$i2;
if (params[i] === undefined || constraints[i] === undefined) {
return false;
}
const constraint = constraints[i];
if (constraint === '...') {
return true;
}
if (constraint === '*') {
if (params[i] === undefined) {
return false;
}
} else if (Array.isArray(constraint)) {
if (constraint.every(c => {
var _params$i;
return c !== ((_params$i = params[i]) === null || _params$i === void 0 ? void 0 : _params$i[0]);
})) {
return false;
}
} else if (constraint !== ((_params$i2 = params[i]) === null || _params$i2 === void 0 ? void 0 : _params$i2[0])) {
return false;
}
}
return true;
}
function validateParams(params, constraints, messageOrError) {
if (!isValidParams(params, constraints)) {
if (typeof messageOrError === 'string') {
throw new Error(messageOrError);
}
throw messageOrError;
}
}
//# sourceMappingURL=validateParams.js.map
{"version":3,"file":"validateParams.js","names":["isValidParams","params","constraints","length","Math","max","i","_params$i2","undefined","constraint","Array","isArray","every","c","_params$i","validateParams","messageOrError","Error"],"sources":["../../src/utils/validateParams.ts"],"sourcesContent":["import type { Param, Params } from '../types';\n\ntype ParamName = Param[0];\ntype ParamConstraint = ParamName | [...ParamName[]] | '*';\n\nexport type ParamConstraints =\n | [...ParamConstraint[]]\n | [...ParamConstraint[], '...'];\n\n// ParamMapping maps each ParamName to its corresponding Param type.\ntype ParamMapping = {\n [K in ParamName]: Extract<Param, readonly [K, ...unknown[]]>; // For each ParamName K, extract the corresponding Param type.\n};\n\n// GetParamByName returns the Param type based on the input type T.\ntype GetParamByName<T> = T extends '*'\n ? Param // If T is '*', return Param type.\n : T extends keyof ParamMapping // If T is a key in ParamMapping (i.e., a ParamName).\n ? ParamMapping[T] // Return the corresponding Param type from ParamMapping.\n : T extends Array<infer TNames> // If T is an array of names.\n ? TNames extends ParamName // If TNames is a ParamName.\n ? Extract<Param, readonly [TNames, ...unknown[]]> // Return the corresponding Param type.\n : never // If TNames is not a ParamName, return never.\n : never; // If T is none of the above, return never.\n\n// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.\nexport type MapParams<\n TNames extends ParamConstraints,\n TRes extends Param[] = [],\n> = TNames extends [infer THead, ...infer TTail] // If TNames is a non-empty tuple.\n ? THead extends '...' // If the first element in the tuple is '...'.\n ? [...TRes, ...Params] // Append all Params to the result tuple.\n : MapParams<\n Extract<TTail, ParamConstraints>, // Extract the remaining ParamConstraints.\n [...TRes, GetParamByName<Extract<THead, ParamName | '*' | ParamName[]>>] // Append the mapped Param to the result tuple and recurse.\n >\n : TRes; // If TNames is an empty tuple, return the result tuple.\n\nexport function isValidParams<T extends ParamConstraints>(\n params: Params,\n constraints: T\n): params is MapParams<T> {\n const length = Math.max(params.length, constraints.length);\n for (let i = 0; i < length; i++) {\n if (params[i] === undefined || constraints[i] === undefined) {\n return false;\n }\n\n const constraint = constraints[i];\n if (constraint === '...') {\n return true;\n }\n\n if (constraint === '*') {\n if (params[i] === undefined) {\n return false;\n }\n } else if (Array.isArray(constraint)) {\n if (constraint.every((c) => c !== params[i]?.[0])) {\n return false;\n }\n } else if (constraint !== params[i]?.[0]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function validateParams<T extends ParamConstraints>(\n params: Params,\n constraints: T,\n messageOrError: unknown\n): asserts params is MapParams<T> {\n if (!isValidParams(params, constraints)) {\n if (typeof messageOrError === 'string') {\n throw new Error(messageOrError);\n }\n\n throw messageOrError;\n }\n}\n"],"mappings":";;;;;;;AASA;;AAKA;;AASW;;AAEX;;AAWU;;AAEH,SAASA,aAAaA,CAC3BC,MAAc,EACdC,WAAc,EACU;EACxB,MAAMC,MAAM,GAAGC,IAAI,CAACC,GAAG,CAACJ,MAAM,CAACE,MAAM,EAAED,WAAW,CAACC,MAAM,CAAC;EAC1D,KAAK,IAAIG,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,MAAM,EAAEG,CAAC,EAAE,EAAE;IAAA,IAAAC,UAAA;IAC/B,IAAIN,MAAM,CAACK,CAAC,CAAC,KAAKE,SAAS,IAAIN,WAAW,CAACI,CAAC,CAAC,KAAKE,SAAS,EAAE;MAC3D,OAAO,KAAK;IACd;IAEA,MAAMC,UAAU,GAAGP,WAAW,CAACI,CAAC,CAAC;IACjC,IAAIG,UAAU,KAAK,KAAK,EAAE;MAC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