Plugin.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import type { PugPlugin, PugToken, PugAST, PugNode, PugNodes, PugNodeAttribute, LexerPlugin } from "pug";
  2. import { Hook } from "./plugin/Hook";
  3. import { ConditionalHook } from "./plugin/hooks/ConditionalHook";
  4. import { PropertyHook } from "./plugin/hooks/PropertyHook";
  5. import { PupperToAlpineHook } from "./plugin/hooks/PupperToAlpineHook";
  6. import { ImportHook } from "./plugin/hooks/ImportHook";
  7. import { CompilerNode } from "../model/core/nodes/CompilerNode";
  8. import { StyleAndScriptHook } from "./plugin/hooks/StyleAndScriptHook";
  9. import { AstNode } from "./plugin/nodes/AstNode";
  10. import { EachNode } from "./plugin/nodes/EachNode";
  11. import { TagNode } from "./plugin/nodes/TagNode";
  12. import { NodeModel } from "../model/core/NodeModel";
  13. import { MixinNode } from "./plugin/nodes/MixinNode";
  14. import { ConditionalNode } from "./plugin/nodes/ConditionalNode";
  15. import { Pug } from "../typings/pug";
  16. import { TemplateTagNode } from "./plugin/nodes/tags/TemplateTagNode";
  17. import { PrepareComponents } from "./plugin/phases/PrepareComponentsHook";
  18. import { CompilationType, PupperCompiler } from "./Compiler";
  19. import lex from "pug-lexer";
  20. type THookConstructor = { new(plugin: Plugin): Hook };
  21. type THookArray = THookConstructor[];
  22. export type TPugNodesWithTypes = {
  23. [key in PugNodes["type"]]: Extract<PugNodes, { type: key }>
  24. }
  25. export type TPugNodeTypes = Pick<PugNodes, "type">["type"];
  26. /**
  27. * Anything that extends a compiler node.
  28. */
  29. export type TCompilerNode<T extends CompilerNode = any> = T;
  30. /**
  31. * The relationship between a pug node type and a plugin node.
  32. */
  33. interface INodeModelPugNodeTypeRelationship extends Record<TPugNodeTypes, TCompilerNode> {
  34. Tag: TagNode;
  35. Conditional: ConditionalNode;
  36. Each: EachNode;
  37. Mixin: MixinNode;
  38. //Block: AstNode;
  39. }
  40. /**
  41. * Retrieves a node model by the pug node type.
  42. */
  43. type TNodeModelByPugNodeType<TNode extends TPugNodeTypes> = Pick<INodeModelPugNodeTypeRelationship, TNode>;
  44. /**
  45. * Retrieves the node model by the pug node.
  46. */
  47. type TNodeModelByPugNode<TNode extends PugNodes, TNodeType extends TPugNodeTypes = TNode["type"]> = TNodeModelByPugNodeType<TNodeType>;
  48. export { PugToken, PugAST, PugNode, PugNodeAttribute, PugNodes, CompilerNode as IPluginNode };
  49. /**
  50. * Documentation for this class is available in the PugPlugin interface
  51. */
  52. export default class Plugin implements PugPlugin {
  53. public static Hooks: THookArray = [
  54. ConditionalHook,
  55. PropertyHook,
  56. PupperToAlpineHook,
  57. ImportHook,
  58. StyleAndScriptHook
  59. ];
  60. /**
  61. * All phases to be executed.
  62. * Phases are executed before hooks.
  63. */
  64. public static Phases: THookArray = [
  65. PrepareComponents
  66. ];
  67. /**
  68. * Creates a compiler node from a pug node.
  69. * @param node The pug node.
  70. * @param parent The parent node to this node.
  71. * @returns
  72. */
  73. public static createNode<TNode extends PugNodes>(node: TNode, parent: NodeModel): TNodeModelByPugNode<TNode> | CompilerNode {
  74. // If somehow this happens, prevent from going further
  75. if (node instanceof CompilerNode) {
  76. return node;
  77. }
  78. switch(node.type) {
  79. default:
  80. return new CompilerNode(node, parent);
  81. case "Each":
  82. return new EachNode(node, parent);
  83. case "Tag":
  84. return this.makeTagNode(node, parent);
  85. case "Mixin":
  86. return new MixinNode(node, parent);
  87. case "Conditional":
  88. return new ConditionalNode(node, parent);
  89. }
  90. }
  91. /**
  92. * Creates a compiler tag node.
  93. * @param node The pug node related to this new node.
  94. * @param parent The parent node related to this node.
  95. * @returns
  96. */
  97. public static makeTagNode(node: Pug.Nodes.TagNode, parent: NodeModel): TagNode {
  98. switch(node.name) {
  99. default:
  100. return new TagNode(node, parent);
  101. case "template":
  102. return new TemplateTagNode(node, parent);
  103. }
  104. }
  105. /**
  106. * A handler for the plugin filters.
  107. */
  108. private filters: Record<string, { callback: Function, hook: THookArray[0] }[]> = {};
  109. /**
  110. * Any data to be shared between hooks and phases.
  111. */
  112. public sharedData: Record<any, any> = {};
  113. public lex: LexerPlugin;
  114. constructor(
  115. public compiler: PupperCompiler
  116. ) {
  117. // Create the lexer
  118. this.lex = {
  119. isExpression: (lexer: lex.Lexer, exp: string) =>
  120. this.applyFilters<string, boolean>("testExpression", exp)
  121. };
  122. }
  123. public get options() {
  124. return this.compiler.options;
  125. }
  126. /**
  127. * Prepares a list of ordered hooks.
  128. */
  129. public prepareHooks() {
  130. const hookOrder: string[] = [];
  131. if (this.compiler.compilationType !== CompilationType.TEMPLATE) {
  132. Plugin.Phases
  133. .map((Phase) => new Phase(this))
  134. .forEach((phase) => {
  135. phase.prepareFilters();
  136. hookOrder.push(phase.constructor.name);
  137. });
  138. }
  139. Plugin.Hooks
  140. // Create the hooks instances
  141. .map((Hook) => new Hook(this))
  142. .sort((b, a) => {
  143. if (a.$before) {
  144. const $before = a.$before?.map((hook) => hook.prototype.constructor.name);
  145. // If A needs to run before B
  146. if ($before.includes(b.constructor.name)) {
  147. return -1;
  148. } else {
  149. return 1;
  150. }
  151. }
  152. if (a.$after) {
  153. const $after = a.$after.map((hook) => hook.prototype.constructor.name);
  154. // If A needs to run after B
  155. if ($after.includes(b.constructor.name)) {
  156. return 1;
  157. } else {
  158. return -1;
  159. }
  160. }
  161. return 0;
  162. })
  163. .forEach((hook) => {
  164. // Prepare their filters
  165. hook.prepareFilters();
  166. hookOrder.push(hook.constructor.name);
  167. });
  168. }
  169. /**
  170. * Retrieves the compiler options
  171. * @returns
  172. */
  173. public getCompilerOptions() {
  174. return this.options;
  175. }
  176. /**
  177. * Adds a filter to a given event.
  178. * @param filter The filter to be added.
  179. * @param callback The filter callback.
  180. * @returns
  181. */
  182. public addFilter(filter: string, callback: Function, hook: THookConstructor) {
  183. if (this.filters[filter] === undefined) {
  184. this.filters[filter] = [];
  185. }
  186. return this.filters[filter].push({
  187. callback,
  188. hook
  189. });
  190. }
  191. /**
  192. * Applies all hooks filters for a given value.
  193. * @param filter The filter name to be applied.
  194. * @param value The filter initial value.
  195. * @returns
  196. */
  197. public applyFilters<TValue, TResultingValue = TValue>(filter: string, value: TValue, options?: {
  198. skip: THookArray
  199. }): TResultingValue {
  200. // If has no filters, return the initial value
  201. if (this.filters[filter] === undefined) {
  202. return value as any as TResultingValue;
  203. }
  204. try {
  205. for(let callback of this.filters[filter]) {
  206. // @ts-ignore
  207. if (options?.skip?.some((sk) => callback.hook instanceof sk)) {
  208. continue;
  209. }
  210. value = callback.callback(value);
  211. }
  212. } catch(e) {
  213. console.error(e);
  214. throw e;
  215. }
  216. return value as any as TResultingValue;
  217. }
  218. /**
  219. * Parses the children of a node.
  220. * @param node The node or node array to be parsed.
  221. * @returns
  222. */
  223. public parseChildren<TInput extends NodeModel | NodeModel[], TResult>(node: TInput, skipComponentCheck: boolean = false) {
  224. let options = skipComponentCheck ? {
  225. skip: [PrepareComponents]
  226. } : undefined;
  227. if (Array.isArray(node)) {
  228. this.applyFilters("parse", node, options);
  229. node.forEach((node) => {
  230. this.parseChildren(node);
  231. });
  232. return node;
  233. }
  234. node.setChildren(
  235. this.applyFilters("parse", node.getChildren(), options)
  236. );
  237. node.getChildren().forEach((child) => {
  238. if (child.hasChildren()) {
  239. this.parseChildren(child);
  240. }
  241. });
  242. return node;
  243. }
  244. /**
  245. * Parses an AST.
  246. * @param ast The AST to be parsed.
  247. * @returns
  248. */
  249. public parseNodes(ast: PugAST) {
  250. try {
  251. const astNode = new AstNode(ast, this);
  252. // Parse the AST children
  253. this.parseChildren(astNode);
  254. return astNode.toPugNode();
  255. } catch(e) {
  256. console.error(e);
  257. throw e;
  258. }
  259. }
  260. /**
  261. * Pug filters implementations
  262. */
  263. public preLex(template: string) {
  264. this.compiler.contents = this.applyFilters("preLex", template);
  265. return this.compiler.contents;
  266. }
  267. public preParse(tokens: PugToken[]) {
  268. return this.applyFilters("lex", tokens);
  269. }
  270. public postParse(block: PugAST) {
  271. return this.parseNodes(block);
  272. }
  273. public preCodeGen(ast: PugAST): PugAST {
  274. return this.applyFilters("preCodeGen", ast);
  275. }
  276. public postCodeGen(code: string): string {
  277. return this.applyFilters("postCodeGen", code);
  278. }
  279. public get makeError() {
  280. return this.compiler.makeError.bind(this.compiler);
  281. }
  282. public get makeParseError() {
  283. return this.compiler.makeParseError.bind(this.compiler);
  284. }
  285. }