@wyw-in-js/processor-utils 1.0.5 → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/esm/BaseProcessor.js +47 -68
  2. package/esm/BaseProcessor.js.map +1 -1
  3. package/esm/TaggedTemplateProcessor.js +32 -41
  4. package/esm/TaggedTemplateProcessor.js.map +1 -1
  5. package/esm/ast.js +72 -0
  6. package/esm/ast.js.map +1 -0
  7. package/esm/diagnostics.js +4 -0
  8. package/esm/diagnostics.js.map +1 -0
  9. package/esm/index.js +9 -7
  10. package/esm/index.js.map +1 -1
  11. package/esm/types.js +1 -1
  12. package/esm/types.js.map +1 -1
  13. package/esm/utils/buildSlug.js +2 -2
  14. package/esm/utils/buildSlug.js.map +1 -1
  15. package/esm/utils/getClassNameAndSlug.js +38 -41
  16. package/esm/utils/getClassNameAndSlug.js.map +1 -1
  17. package/esm/utils/getVariableName.js +7 -10
  18. package/esm/utils/getVariableName.js.map +1 -1
  19. package/esm/utils/stripLines.js +9 -11
  20. package/esm/utils/stripLines.js.map +1 -1
  21. package/esm/utils/templateProcessor.js +98 -118
  22. package/esm/utils/templateProcessor.js.map +1 -1
  23. package/esm/utils/throwIfInvalid.js +11 -12
  24. package/esm/utils/throwIfInvalid.js.map +1 -1
  25. package/esm/utils/toCSS.js +34 -43
  26. package/esm/utils/toCSS.js.map +1 -1
  27. package/esm/utils/toValidCSSIdentifier.js +2 -2
  28. package/esm/utils/toValidCSSIdentifier.js.map +1 -1
  29. package/esm/utils/types.js +1 -1
  30. package/esm/utils/types.js.map +1 -1
  31. package/esm/utils/units.js +79 -61
  32. package/esm/utils/units.js.map +1 -1
  33. package/esm/utils/validateParams.js +29 -39
  34. package/esm/utils/validateParams.js.map +1 -1
  35. package/package.json +15 -15
  36. package/types/BaseProcessor.d.ts +7 -13
  37. package/types/BaseProcessor.js +18 -20
  38. package/types/TaggedTemplateProcessor.d.ts +1 -1
  39. package/types/TaggedTemplateProcessor.js +9 -16
  40. package/types/ast.d.ts +95 -0
  41. package/types/ast.js +80 -0
  42. package/types/diagnostics.d.ts +9 -0
  43. package/types/diagnostics.js +3 -0
  44. package/types/index.d.ts +5 -1
  45. package/types/index.js +8 -29
  46. package/types/types.d.ts +9 -1
  47. package/types/types.js +1 -2
  48. package/types/utils/buildSlug.js +1 -4
  49. package/types/utils/getClassNameAndSlug.js +15 -18
  50. package/types/utils/getVariableName.js +1 -4
  51. package/types/utils/stripLines.js +1 -4
  52. package/types/utils/templateProcessor.d.ts +1 -1
  53. package/types/utils/templateProcessor.js +16 -55
  54. package/types/utils/throwIfInvalid.js +1 -3
  55. package/types/utils/toCSS.js +8 -13
  56. package/types/utils/toValidCSSIdentifier.js +1 -4
  57. package/types/utils/types.d.ts +4 -2
  58. package/types/utils/types.js +1 -2
  59. package/types/utils/units.js +2 -5
  60. package/types/utils/validateParams.js +2 -6
  61. package/lib/BaseProcessor.js +0 -78
  62. package/lib/BaseProcessor.js.map +0 -1
  63. package/lib/TaggedTemplateProcessor.js +0 -51
  64. package/lib/TaggedTemplateProcessor.js.map +0 -1
  65. package/lib/index.js +0 -67
  66. package/lib/index.js.map +0 -1
  67. package/lib/types.js +0 -2
  68. package/lib/types.js.map +0 -1
  69. package/lib/utils/buildSlug.js +0 -12
  70. package/lib/utils/buildSlug.js.map +0 -1
  71. package/lib/utils/getClassNameAndSlug.js +0 -50
  72. package/lib/utils/getClassNameAndSlug.js.map +0 -1
  73. package/lib/utils/getVariableName.js +0 -18
  74. package/lib/utils/getVariableName.js.map +0 -1
  75. package/lib/utils/stripLines.js +0 -22
  76. package/lib/utils/stripLines.js.map +0 -1
  77. package/lib/utils/templateProcessor.js +0 -129
  78. package/lib/utils/templateProcessor.js.map +0 -1
  79. package/lib/utils/throwIfInvalid.js +0 -35
  80. package/lib/utils/throwIfInvalid.js.map +0 -1
  81. package/lib/utils/toCSS.js +0 -58
  82. package/lib/utils/toCSS.js.map +0 -1
  83. package/lib/utils/toValidCSSIdentifier.js +0 -10
  84. package/lib/utils/toValidCSSIdentifier.js.map +0 -1
  85. package/lib/utils/types.js +0 -2
  86. package/lib/utils/types.js.map +0 -1
  87. package/lib/utils/units.js +0 -71
  88. package/lib/utils/units.js.map +0 -1
  89. package/lib/utils/validateParams.js +0 -54
  90. package/lib/utils/validateParams.js.map +0 -1
@@ -1,43 +1,33 @@
1
- // ParamMapping maps each ParamName to its corresponding Param type.
2
-
3
- // GetParamByName returns the Param type based on the input type T.
4
-
5
- // If T is none of the above, return never.
6
-
7
- // MapParams iteratively maps the input ParamConstraints to their corresponding Param types.
8
-
9
- // If TNames is an empty tuple, return the result tuple.
10
-
11
1
  export function isValidParams(params, constraints) {
12
- const length = Math.max(params.length, constraints.length);
13
- for (let i = 0; i < length; i++) {
14
- if (params[i] === undefined || constraints[i] === undefined) {
15
- return false;
16
- }
17
- const constraint = constraints[i];
18
- if (constraint === '...') {
19
- return true;
20
- }
21
- if (constraint === '*') {
22
- if (params[i] === undefined) {
23
- return false;
24
- }
25
- } else if (Array.isArray(constraint)) {
26
- if (constraint.every(c => c !== params[i]?.[0])) {
27
- return false;
28
- }
29
- } else if (constraint !== params[i]?.[0]) {
30
- return false;
31
- }
32
- }
33
- return true;
2
+ const length = Math.max(params.length, constraints.length);
3
+ for (let i = 0; i < length; i++) {
4
+ if (params[i] === undefined || constraints[i] === undefined) {
5
+ return false;
6
+ }
7
+ const constraint = constraints[i];
8
+ if (constraint === "...") {
9
+ return true;
10
+ }
11
+ if (constraint === "*") {
12
+ if (params[i] === undefined) {
13
+ return false;
14
+ }
15
+ } else if (Array.isArray(constraint)) {
16
+ if (constraint.every((c) => c !== params[i]?.[0])) {
17
+ return false;
18
+ }
19
+ } else if (constraint !== params[i]?.[0]) {
20
+ return false;
21
+ }
22
+ }
23
+ return true;
34
24
  }
35
25
  export function validateParams(params, constraints, messageOrError) {
36
- if (!isValidParams(params, constraints)) {
37
- if (typeof messageOrError === 'string') {
38
- throw new Error(messageOrError);
39
- }
40
- throw messageOrError;
41
- }
26
+ if (!isValidParams(params, constraints)) {
27
+ if (typeof messageOrError === "string") {
28
+ throw new Error(messageOrError);
29
+ }
30
+ throw messageOrError;
31
+ }
42
32
  }
43
- //# sourceMappingURL=validateParams.js.map
33
+ //# sourceMappingURL=validateParams.js.map
@@ -1 +1 @@
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,WAAW,CAACI,CAAC,CAAC;IACjC,IAAIE,UAAU,KAAK,KAAK,EAAE;MACxB,OAAO,IAAI;IACb;IAEA,IAAIA,UAAU,KAAK,GAAG,EAAE;MACtB,IAAIP,MAAM,CAACK,CAAC,CAAC,KAAKC,SAAS,EAAE;QAC3B,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAIE,KAAK,CAACC,OAAO,CAACF,UAAU,CAAC,EAAE;MACpC,IAAIA,UAAU,CAACG,KAAK,CAAEC,CAAC,IAAKA,CAAC,KAAKX,MAAM,CAACK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;QACjD,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAIE,UAAU,KAAKP,MAAM,CAACK,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE;MACxC,OAAO,KAAK;IACd;EACF;EAEA,OAAO,IAAI;AACb;AAEA,OAAO,SAASO,cAAcA,CAC5BZ,MAAc,EACdC,WAAc,EACdY,cAAuB,EACS;EAChC,IAAI,CAACd,aAAa,CAACC,MAAM,EAAEC,WAAW,CAAC,EAAE;IACvC,IAAI,OAAOY,cAAc,KAAK,QAAQ,EAAE;MACtC,MAAM,IAAIC,KAAK,CAACD,cAAc,CAAC;IACjC;IAEA,MAAMA,cAAc;EACtB;AACF","ignoreList":[]}
1
+ {"mappings":"AAsCA,OAAO,SAAS,cACd,QACA,aACwB;CACxB,MAAM,SAAS,KAAK,IAAI,OAAO,QAAQ,YAAY,OAAO;AAC1D,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,MAAI,OAAO,OAAO,aAAa,YAAY,OAAO,WAAW;AAC3D,UAAO;;EAGT,MAAM,aAAa,YAAY;AAC/B,MAAI,eAAe,OAAO;AACxB,UAAO;;AAGT,MAAI,eAAe,KAAK;AACtB,OAAI,OAAO,OAAO,WAAW;AAC3B,WAAO;;aAEA,MAAM,QAAQ,WAAW,EAAE;AACpC,OAAI,WAAW,OAAO,MAAM,MAAM,OAAO,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"}
package/package.json CHANGED
@@ -1,37 +1,37 @@
1
1
  {
2
2
  "name": "@wyw-in-js/processor-utils",
3
- "version": "1.0.5",
3
+ "version": "2.0.0-alpha.0",
4
+ "type": "module",
4
5
  "dependencies": {
5
- "@babel/generator": "^7.23.5",
6
- "@wyw-in-js/shared": "1.0.5"
6
+ "@wyw-in-js/shared": "2.0.0-alpha.0"
7
7
  },
8
8
  "devDependencies": {
9
- "@babel/types": "^7.23.5",
10
- "@types/babel__core": "^7.20.5",
11
- "@types/babel__generator": "^7.6.7",
12
- "@types/node": "^16.18.55",
13
- "@wyw-in-js/babel-config": "workspace:*",
9
+ "@types/node": "^22.0.0",
14
10
  "@wyw-in-js/eslint-config": "workspace:*",
15
11
  "@wyw-in-js/ts-config": "workspace:*",
16
12
  "typescript": "^5.2.2"
17
13
  },
18
14
  "engines": {
19
- "node": ">=20.0.0"
15
+ "node": ">=22.0.0"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./types/index.d.ts",
20
+ "default": "./esm/index.js"
21
+ }
20
22
  },
21
23
  "files": [
22
- "types/",
23
- "lib/",
24
- "esm/"
24
+ "esm/",
25
+ "types/"
25
26
  ],
26
27
  "license": "MIT",
27
- "main": "lib/index.js",
28
+ "main": "esm/index.js",
28
29
  "module": "esm/index.js",
29
30
  "publishConfig": {
30
31
  "access": "public"
31
32
  },
32
33
  "scripts": {
33
- "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
34
- "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
34
+ "build:esm": "node ../../scripts/build-esm-oxc.mjs",
35
35
  "build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",
36
36
  "lint": "eslint --ext .js,.ts .",
37
37
  "test": "bun test src"
@@ -1,9 +1,8 @@
1
- import type { NodePath, types as t } from '@babel/core';
2
- import type { Expression, Identifier, SourceLocation, MemberExpression } from '@babel/types';
3
1
  import type { Artifact, ExpressionValue } from '@wyw-in-js/shared';
4
- import type { IInterpolation, Params, Value, ValueCache } from './types';
2
+ import type { AstService, Expression, Identifier, MemberExpression, SourceLocation } from './ast';
3
+ import type { IInterpolation, Params, ProcessorDiagnostic, Value, ValueCache } from './types';
5
4
  import type { IFileContext, IOptions } from './utils/types';
6
- export { Expression };
5
+ export type { Expression };
7
6
  export type ProcessorParams = ConstructorParameters<typeof BaseProcessor>;
8
7
  export type TailProcessorParams = ProcessorParams extends [Params, ...infer T] ? T : never;
9
8
  export type TagSource = {
@@ -12,12 +11,9 @@ export type TagSource = {
12
11
  };
13
12
  export declare abstract class BaseProcessor {
14
13
  tagSource: TagSource;
15
- protected readonly astService: typeof t & {
16
- addDefaultImport: (source: string, nameHint?: string) => Identifier;
17
- addNamedImport: (name: string, source: string, nameHint?: string) => Identifier;
18
- };
14
+ protected readonly astService: AstService;
19
15
  readonly location: SourceLocation | null;
20
- protected readonly replacer: (replacement: Expression | ((tagPath: NodePath) => Expression), isPure: boolean) => void;
16
+ protected readonly replacer: (replacement: Expression | ((tagPath: unknown) => Expression), isPure: boolean) => void;
21
17
  readonly displayName: string;
22
18
  readonly isReferenced: boolean;
23
19
  protected readonly idx: number;
@@ -31,10 +27,7 @@ export declare abstract class BaseProcessor {
31
27
  readonly slug: string;
32
28
  protected callee: Identifier | MemberExpression;
33
29
  protected evaluated: Record<'dependencies' | 'expression', Value[]> | undefined;
34
- constructor(params: Params, tagSource: TagSource, astService: typeof t & {
35
- addDefaultImport: (source: string, nameHint?: string) => Identifier;
36
- addNamedImport: (name: string, source: string, nameHint?: string) => Identifier;
37
- }, location: SourceLocation | null, replacer: (replacement: Expression | ((tagPath: NodePath) => Expression), isPure: boolean) => void, displayName: string, isReferenced: boolean, idx: number, options: IOptions, context: IFileContext);
30
+ 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);
38
31
  /**
39
32
  * A replacement for tag referenced in a template literal.
40
33
  */
@@ -45,6 +38,7 @@ export declare abstract class BaseProcessor {
45
38
  * whereas `styled` tag will be replaced with an object with metadata.
46
39
  */
47
40
  abstract get value(): Expression;
41
+ addDiagnostic(diagnostic: ProcessorDiagnostic): void;
48
42
  isValidValue(value: unknown): value is Value;
49
43
  toString(): string;
50
44
  protected tagSourceCode(): string;
@@ -1,15 +1,10 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BaseProcessor = void 0;
7
- const generator_1 = __importDefault(require("@babel/generator"));
8
- const shared_1 = require("@wyw-in-js/shared");
9
- const getClassNameAndSlug_1 = __importDefault(require("./utils/getClassNameAndSlug"));
10
- const toCSS_1 = require("./utils/toCSS");
11
- const validateParams_1 = require("./utils/validateParams");
12
- class BaseProcessor {
1
+ import { hasEvalMeta } from '@wyw-in-js/shared';
2
+ import { expressionToCode } from './ast';
3
+ import { createProcessorDiagnosticArtifact } from './diagnostics';
4
+ import getClassNameAndSlug from './utils/getClassNameAndSlug';
5
+ import { isCSSable } from './utils/toCSS';
6
+ import { validateParams } from './utils/validateParams';
7
+ export class BaseProcessor {
13
8
  tagSource;
14
9
  astService;
15
10
  location;
@@ -37,23 +32,26 @@ class BaseProcessor {
37
32
  this.idx = idx;
38
33
  this.options = options;
39
34
  this.context = context;
40
- (0, validateParams_1.validateParams)(params, ['callee'], 'Unknown error: a callee param is not specified');
41
- const { className, slug } = (0, getClassNameAndSlug_1.default)(this.displayName, this.idx, this.options, this.context);
35
+ validateParams(params, ['callee'], 'Unknown error: a callee param is not specified');
36
+ const { className, slug } = getClassNameAndSlug(this.displayName, this.idx, this.options, this.context);
42
37
  this.className = className;
43
38
  this.slug = slug;
44
39
  [[, this.callee]] = params;
45
40
  }
41
+ addDiagnostic(diagnostic) {
42
+ this.artifacts.push(createProcessorDiagnosticArtifact({
43
+ ...diagnostic,
44
+ end: diagnostic.end ?? this.location?.end ?? null,
45
+ start: diagnostic.start ?? this.location?.start ?? null,
46
+ }));
47
+ }
46
48
  isValidValue(value) {
47
- return (typeof value === 'function' || (0, toCSS_1.isCSSable)(value) || (0, shared_1.hasEvalMeta)(value));
49
+ return (typeof value === 'function' || isCSSable(value) || hasEvalMeta(value));
48
50
  }
49
51
  toString() {
50
52
  return this.tagSourceCode();
51
53
  }
52
54
  tagSourceCode() {
53
- if (this.callee.type === 'Identifier') {
54
- return this.callee.name;
55
- }
56
- return (0, generator_1.default)(this.callee).code;
55
+ return expressionToCode(this.callee);
57
56
  }
58
57
  }
59
- exports.BaseProcessor = BaseProcessor;
@@ -1,4 +1,4 @@
1
- import type { Expression, SourceLocation } from '@babel/types';
1
+ import type { Expression, SourceLocation } from './ast';
2
2
  import type { TailProcessorParams } from './BaseProcessor';
3
3
  import { BaseProcessor } from './BaseProcessor';
4
4
  import type { ValueCache, Rules, Params } from './types';
@@ -1,23 +1,17 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.TaggedTemplateProcessor = void 0;
7
- const shared_1 = require("@wyw-in-js/shared");
8
- const BaseProcessor_1 = require("./BaseProcessor");
9
- const templateProcessor_1 = __importDefault(require("./utils/templateProcessor"));
10
- const validateParams_1 = require("./utils/validateParams");
11
- class TaggedTemplateProcessor extends BaseProcessor_1.BaseProcessor {
1
+ import { ValueType } from '@wyw-in-js/shared';
2
+ import { BaseProcessor } from './BaseProcessor';
3
+ import templateProcessor from './utils/templateProcessor';
4
+ import { validateParams } from './utils/validateParams';
5
+ export class TaggedTemplateProcessor extends BaseProcessor {
12
6
  #template;
13
7
  constructor(params, ...args) {
14
8
  // Should have at least two params and the first one should be a callee.
15
- (0, validateParams_1.validateParams)(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
16
- (0, validateParams_1.validateParams)(params, ['callee', 'template'], 'Invalid usage of template tag');
9
+ validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
10
+ validateParams(params, ['callee', 'template'], 'Invalid usage of template tag');
17
11
  const [tag, [, template]] = params;
18
12
  super([tag], ...args);
19
13
  template.forEach((element) => {
20
- if ('kind' in element && element.kind !== shared_1.ValueType.FUNCTION) {
14
+ if ('kind' in element && element.kind !== ValueType.FUNCTION) {
21
15
  this.dependencies.push(element);
22
16
  }
23
17
  });
@@ -28,7 +22,7 @@ class TaggedTemplateProcessor extends BaseProcessor_1.BaseProcessor {
28
22
  // FIXME: why it was called twice?
29
23
  throw new Error('Tag is already built');
30
24
  }
31
- const artifact = (0, templateProcessor_1.default)(this, this.#template, values, this.options.variableNameConfig);
25
+ const artifact = templateProcessor(this, this.#template, values, this.options.variableNameConfig);
32
26
  if (artifact) {
33
27
  this.artifacts.push(['css', artifact]);
34
28
  }
@@ -37,4 +31,3 @@ class TaggedTemplateProcessor extends BaseProcessor_1.BaseProcessor {
37
31
  return `${super.toString()}\`…\``;
38
32
  }
39
33
  }
40
- exports.TaggedTemplateProcessor = TaggedTemplateProcessor;
package/types/ast.d.ts ADDED
@@ -0,0 +1,95 @@
1
+ import type { Location } from '@wyw-in-js/shared';
2
+ export type SourceLocation = {
3
+ end: Location;
4
+ filename?: string;
5
+ identifierName?: string | null;
6
+ start: Location;
7
+ };
8
+ export type BaseAstNode = {
9
+ end?: number | null;
10
+ loc?: unknown;
11
+ start?: number | null;
12
+ type: string;
13
+ };
14
+ export type Expression = BaseAstNode;
15
+ export type Identifier = Expression & {
16
+ name: string;
17
+ type: 'Identifier';
18
+ };
19
+ export type StringLiteral = Expression & {
20
+ type: 'StringLiteral';
21
+ value: string;
22
+ };
23
+ export type NumericLiteral = Expression & {
24
+ type: 'NumericLiteral';
25
+ value: number;
26
+ };
27
+ export type BooleanLiteral = Expression & {
28
+ type: 'BooleanLiteral';
29
+ value: boolean;
30
+ };
31
+ export type NullLiteral = Expression & {
32
+ type: 'NullLiteral';
33
+ };
34
+ export type BlockStatement = BaseAstNode & {
35
+ body: BaseAstNode[];
36
+ type: 'BlockStatement';
37
+ };
38
+ export type TemplateElement = BaseAstNode & {
39
+ loc?: SourceLocation | null;
40
+ tail: boolean;
41
+ type: 'TemplateElement';
42
+ value: {
43
+ cooked?: string | null;
44
+ raw: string;
45
+ };
46
+ };
47
+ export type MemberExpression = Expression & {
48
+ computed?: boolean;
49
+ object: Expression;
50
+ property: Expression;
51
+ type: 'MemberExpression';
52
+ };
53
+ export type ObjectProperty = BaseAstNode & {
54
+ computed?: boolean;
55
+ key: Expression;
56
+ shorthand?: boolean;
57
+ type: 'ObjectProperty';
58
+ value: Expression;
59
+ };
60
+ export type ObjectExpression = Expression & {
61
+ properties: ObjectProperty[];
62
+ type: 'ObjectExpression';
63
+ };
64
+ export type ArrayExpression = Expression & {
65
+ elements: (Expression | null)[];
66
+ type: 'ArrayExpression';
67
+ };
68
+ export type CallExpression = Expression & {
69
+ arguments: Expression[];
70
+ callee: Expression;
71
+ type: 'CallExpression';
72
+ };
73
+ export type ArrowFunctionExpression = Expression & {
74
+ async?: boolean;
75
+ body: BlockStatement | Expression;
76
+ params: Identifier[];
77
+ type: 'ArrowFunctionExpression';
78
+ };
79
+ export type AstService = {
80
+ addDefaultImport(source: string, nameHint?: string): Identifier;
81
+ addNamedImport(name: string, source: string, nameHint?: string): Identifier;
82
+ arrayExpression(elements: (Expression | null)[]): ArrayExpression;
83
+ arrowFunctionExpression(params: Identifier[], body: BlockStatement | Expression): ArrowFunctionExpression;
84
+ blockStatement(body: BaseAstNode[]): BlockStatement;
85
+ booleanLiteral(value: boolean): BooleanLiteral;
86
+ callExpression(callee: Expression, args: Expression[]): CallExpression;
87
+ identifier(name: string): Identifier;
88
+ memberExpression(object: Expression, property: Expression, computed?: boolean): MemberExpression;
89
+ nullLiteral(): NullLiteral;
90
+ numericLiteral(value: number): NumericLiteral;
91
+ objectExpression(properties: ObjectProperty[]): ObjectExpression;
92
+ objectProperty(key: Expression, value: Expression): ObjectProperty;
93
+ stringLiteral(value: string): StringLiteral;
94
+ };
95
+ export declare const expressionToCode: (expression: Expression) => string;
package/types/ast.js ADDED
@@ -0,0 +1,80 @@
1
+ const stringLiteralCode = (value, quote = 'double') => {
2
+ const json = JSON.stringify(value);
3
+ if (quote === 'double') {
4
+ return json;
5
+ }
6
+ return `'${json.slice(1, -1).replace(/'/g, "\\'")}'`;
7
+ };
8
+ const indent = (level) => ' '.repeat(level);
9
+ const expressionToCodeWithContext = (expression, context) => {
10
+ if (expression.type === 'Identifier') {
11
+ return expression.name;
12
+ }
13
+ if (expression.type === 'StringLiteral') {
14
+ return stringLiteralCode(expression.value, context.quote);
15
+ }
16
+ if (expression.type === 'NumericLiteral' ||
17
+ expression.type === 'BooleanLiteral') {
18
+ return String(expression.value);
19
+ }
20
+ if (expression.type === 'NullLiteral') {
21
+ return 'null';
22
+ }
23
+ if (expression.type === 'MemberExpression') {
24
+ const memberExpression = expression;
25
+ const object = expressionToCodeWithContext(memberExpression.object, context);
26
+ const property = expressionToCodeWithContext(memberExpression.property, context);
27
+ return memberExpression.computed
28
+ ? `${object}[${property}]`
29
+ : `${object}.${property}`;
30
+ }
31
+ if (expression.type === 'CallExpression') {
32
+ const callExpression = expression;
33
+ const callee = expressionToCodeWithContext(callExpression.callee, context);
34
+ const args = callExpression.arguments.map((arg) => expressionToCodeWithContext(arg, {
35
+ ...context,
36
+ quote: arg.type === 'StringLiteral' ? 'single' : context.quote,
37
+ }));
38
+ return `${callee}(${args.join(', ')})`;
39
+ }
40
+ if (expression.type === 'ArrowFunctionExpression') {
41
+ const arrow = expression;
42
+ return `(${arrow.params
43
+ .map((param) => expressionToCodeWithContext(param, context))
44
+ .join(', ')}) => ${expressionToCodeWithContext(arrow.body, context)}`;
45
+ }
46
+ if (expression.type === 'ArrayExpression') {
47
+ return `[${expression.elements
48
+ .map((item) => item ? expressionToCodeWithContext(item, context) : '')
49
+ .join(', ')}]`;
50
+ }
51
+ if (expression.type === 'BlockStatement') {
52
+ return '{ }';
53
+ }
54
+ if (expression.type === 'ObjectExpression') {
55
+ const objectExpression = expression;
56
+ if (objectExpression.properties.length === 0) {
57
+ return '{}';
58
+ }
59
+ const nextIndent = context.indent + 1;
60
+ const properties = objectExpression.properties
61
+ .map((property) => {
62
+ const key = expressionToCodeWithContext(property.key, {
63
+ ...context,
64
+ quote: 'double',
65
+ });
66
+ const value = expressionToCodeWithContext(property.value, {
67
+ indent: nextIndent,
68
+ quote: 'double',
69
+ });
70
+ return `${indent(nextIndent)}${key}: ${value}`;
71
+ })
72
+ .join(',\n');
73
+ return `{\n${properties}\n${indent(context.indent)}}`;
74
+ }
75
+ return expression.type;
76
+ };
77
+ export const expressionToCode = (expression) => expressionToCodeWithContext(expression, {
78
+ indent: 0,
79
+ quote: 'double',
80
+ });
@@ -0,0 +1,9 @@
1
+ import type { Artifact } from '@wyw-in-js/shared';
2
+ import type { ProcessorDiagnostic } from './types';
3
+ export declare const PROCESSOR_DIAGNOSTIC_ARTIFACT: "wyw-in-js:diagnostic";
4
+ export type ProcessorDiagnosticArtifact = [
5
+ name: typeof PROCESSOR_DIAGNOSTIC_ARTIFACT,
6
+ data: ProcessorDiagnostic
7
+ ];
8
+ export declare const createProcessorDiagnosticArtifact: (diagnostic: ProcessorDiagnostic) => ProcessorDiagnosticArtifact;
9
+ export declare const isProcessorDiagnosticArtifact: (artifact: Artifact) => artifact is ProcessorDiagnosticArtifact;
@@ -0,0 +1,3 @@
1
+ export const PROCESSOR_DIAGNOSTIC_ARTIFACT = 'wyw-in-js:diagnostic';
2
+ export const createProcessorDiagnosticArtifact = (diagnostic) => [PROCESSOR_DIAGNOSTIC_ARTIFACT, diagnostic];
3
+ export const isProcessorDiagnosticArtifact = (artifact) => artifact[0] === PROCESSOR_DIAGNOSTIC_ARTIFACT;
package/types/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export { BaseProcessor } from './BaseProcessor';
2
- export type { Expression, TagSource, ProcessorParams, TailProcessorParams, } from './BaseProcessor';
2
+ export { expressionToCode } from './ast';
3
+ export { createProcessorDiagnosticArtifact, isProcessorDiagnosticArtifact, PROCESSOR_DIAGNOSTIC_ARTIFACT, } from './diagnostics';
4
+ export type { ProcessorDiagnosticArtifact } from './diagnostics';
5
+ export type { ArrayExpression, ArrowFunctionExpression, AstService, BaseAstNode, BlockStatement, BooleanLiteral, CallExpression, Expression, Identifier, MemberExpression, NullLiteral, NumericLiteral, ObjectExpression, ObjectProperty, SourceLocation, StringLiteral, TemplateElement, } from './ast';
6
+ export type { ProcessorParams, TagSource, TailProcessorParams, } from './BaseProcessor';
3
7
  export * from './types';
4
8
  export { buildSlug } from './utils/buildSlug';
5
9
  export type { IOptions, IFileContext } from './utils/types';
package/types/index.js CHANGED
@@ -1,29 +1,8 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.toValidCSSIdentifier = exports.TaggedTemplateProcessor = exports.validateParams = exports.isValidParams = exports.buildSlug = exports.BaseProcessor = void 0;
18
- var BaseProcessor_1 = require("./BaseProcessor");
19
- Object.defineProperty(exports, "BaseProcessor", { enumerable: true, get: function () { return BaseProcessor_1.BaseProcessor; } });
20
- __exportStar(require("./types"), exports);
21
- var buildSlug_1 = require("./utils/buildSlug");
22
- Object.defineProperty(exports, "buildSlug", { enumerable: true, get: function () { return buildSlug_1.buildSlug; } });
23
- var validateParams_1 = require("./utils/validateParams");
24
- Object.defineProperty(exports, "isValidParams", { enumerable: true, get: function () { return validateParams_1.isValidParams; } });
25
- Object.defineProperty(exports, "validateParams", { enumerable: true, get: function () { return validateParams_1.validateParams; } });
26
- var TaggedTemplateProcessor_1 = require("./TaggedTemplateProcessor");
27
- Object.defineProperty(exports, "TaggedTemplateProcessor", { enumerable: true, get: function () { return TaggedTemplateProcessor_1.TaggedTemplateProcessor; } });
28
- var toValidCSSIdentifier_1 = require("./utils/toValidCSSIdentifier");
29
- Object.defineProperty(exports, "toValidCSSIdentifier", { enumerable: true, get: function () { return toValidCSSIdentifier_1.toValidCSSIdentifier; } });
1
+ export { BaseProcessor } from './BaseProcessor';
2
+ export { expressionToCode } from './ast';
3
+ export { createProcessorDiagnosticArtifact, isProcessorDiagnosticArtifact, PROCESSOR_DIAGNOSTIC_ARTIFACT, } from './diagnostics';
4
+ export * from './types';
5
+ export { buildSlug } from './utils/buildSlug';
6
+ export { isValidParams, validateParams } from './utils/validateParams';
7
+ export { TaggedTemplateProcessor } from './TaggedTemplateProcessor';
8
+ export { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';
package/types/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Expression, Identifier, TemplateElement, MemberExpression } from '@babel/types';
2
1
  import type { ExpressionValue, Location, WYWEvalMeta } from '@wyw-in-js/shared';
2
+ import type { Expression, Identifier, MemberExpression, TemplateElement } from './ast';
3
3
  export type CSSPropertyValue = string | number;
4
4
  export type ObjectWithSelectors = {
5
5
  [key: string]: ObjectWithSelectors | CSSPropertyValue | (ObjectWithSelectors | CSSPropertyValue)[];
@@ -20,6 +20,14 @@ export interface IInterpolation {
20
20
  source: string;
21
21
  unit: string;
22
22
  }
23
+ export type ProcessorDiagnosticSeverity = 'error' | 'warning';
24
+ export type ProcessorDiagnostic = {
25
+ category: string;
26
+ end?: Location | null;
27
+ message: string;
28
+ severity: ProcessorDiagnosticSeverity;
29
+ start?: Location | null;
30
+ };
23
31
  export type Rules = Record<string, ICSSRule>;
24
32
  export type CalleeParam = readonly ['callee', Identifier | MemberExpression];
25
33
  export type CallParam = readonly ['call', ...ExpressionValue[]];
package/types/types.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,8 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildSlug = buildSlug;
4
1
  const PLACEHOLDER = /\[(.*?)]/g;
5
2
  const isValidArgName = (key, args) => key in args;
6
- function buildSlug(pattern, args) {
3
+ export function buildSlug(pattern, args) {
7
4
  return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : '');
8
5
  }