ecto 4.5.1 → 4.7.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 (4) hide show
  1. package/README.md +505 -1
  2. package/dist/ecto.d.ts +120 -64
  3. package/dist/ecto.js +266 -67
  4. package/package.json +14 -14
package/README.md CHANGED
@@ -30,6 +30,7 @@ Ecto is a modern template consolidation engine that enables the best template en
30
30
  * [Default Engine](#default-engine)
31
31
  * [Engine Mappings](#engine-mappings)
32
32
  * [FrontMatter Helper Functions](#frontmatter-helper-functions)
33
+ * [Detect Template Engine](#detect-template-engine)
33
34
  * [The Template Engines We Support](#the-template-engines-we-support)
34
35
  * [EJS](#ejs)
35
36
  * [Markdown](#markdown)
@@ -41,6 +42,13 @@ Ecto is a modern template consolidation engine that enables the best template en
41
42
  * [FrontMatter Helper Functions](#frontmatter-helper-functions)
42
43
  * [Caching on Rendering](#caching-on-rendering)
43
44
  * [Emitting Events](#emitting-events)
45
+ * [Creating Custom Engines](#creating-custom-engines)
46
+ * [Direct Engine Usage](#direct-engine-usage)
47
+ * [Creating a Custom Engine](#creating-a-custom-engine)
48
+ * [Integrating Custom Engine with Ecto](#integrating-custom-engine-with-ecto)
49
+ * [Engine Interface Reference](#engine-interface-reference)
50
+ * [BaseEngine Helper Methods](#baseengine-helper-methods)
51
+ * [Tips for Custom Engines](#tips-for-custom-engines)
44
52
  * [How to Contribute](#how-to-contribute)
45
53
  * [License](#license)
46
54
 
@@ -470,6 +478,68 @@ This will return the string “handlebars”, which is the corresponding engine
470
478
 
471
479
  Gaining an understanding of this class will provide you with more options and possibilities when using Ecto.
472
480
 
481
+ ## Detect Template Engine
482
+
483
+ Ecto provides a `detectEngine` method that can automatically detect the template engine from a template string by analyzing its syntax patterns. This is useful when you receive template content but don't know which engine it uses.
484
+
485
+ ## detectEngine(source: string): string
486
+
487
+ The `detectEngine` method analyzes the template syntax and returns the detected engine name. If no specific template syntax is found, it returns the configured default engine.
488
+
489
+ | Name | Type | Description |
490
+ | ------ | ------ | ------------------------------------------------- |
491
+ | source | string | The template source string to analyze |
492
+
493
+ **Returns:** The detected engine name ('ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid') or the default engine if no specific syntax is detected.
494
+
495
+ ### Basic Usage
496
+
497
+ ```javascript
498
+ const ecto = new Ecto();
499
+
500
+ // Detect EJS templates
501
+ const ejsEngine = ecto.detectEngine('<%= name %>');
502
+ console.log(ejsEngine); // 'ejs'
503
+
504
+ // Detect Handlebars templates
505
+ const hbsEngine = ecto.detectEngine('{{name}}');
506
+ console.log(hbsEngine); // 'handlebars'
507
+
508
+ // Detect Markdown
509
+ const mdEngine = ecto.detectEngine('# Hello World\n\nThis is markdown');
510
+ console.log(mdEngine); // 'markdown'
511
+
512
+ // Detect Pug templates
513
+ const pugEngine = ecto.detectEngine('div.container\n h1 Hello');
514
+ console.log(pugEngine); // 'pug'
515
+
516
+ // Detect Nunjucks templates
517
+ const njkEngine = ecto.detectEngine('{% block content %}Hello{% endblock %}');
518
+ console.log(njkEngine); // 'nunjucks'
519
+
520
+ // Detect Liquid templates
521
+ const liquidEngine = ecto.detectEngine('{% assign name = "John" %}{{ name | upcase }}');
522
+ console.log(liquidEngine); // 'liquid'
523
+
524
+ // Returns default engine for plain text
525
+ const defaultEngine = ecto.detectEngine('Plain text without template syntax');
526
+ console.log(defaultEngine); // 'ejs' (or whatever is set as defaultEngine)
527
+ ```
528
+
529
+ ### Detection Patterns
530
+
531
+ The `detectEngine` method recognizes the following syntax patterns:
532
+
533
+ - **EJS**: `<% %>`, `<%= %>`, `<%- %>`
534
+ - **Handlebars/Mustache**: `{{ }}`, `{{# }}`, `{{> }}`
535
+ - **Pug**: Indentation-based syntax without angle brackets
536
+ - **Nunjucks**: `{% block %}`, `{% extends %}`, `{% include %}`
537
+ - **Liquid**: `{% assign %}`, `{% capture %}`, pipe filters `{{ var | filter }}`
538
+ - **Markdown**: Headers `#`, lists, code blocks, links, tables
539
+
540
+ Note: For ambiguous syntax (like simple `{{ }}` which could be Handlebars, Mustache, or Liquid), the method makes intelligent decisions based on additional context clues in the template.
541
+
542
+
473
543
  # The Template Engines We Support
474
544
 
475
545
  A template engine is a tool that allows developers to write HTML markup that contains the template engine’s defined tags and syntax. These tags are used to insert variables into the final output of the template, or run some programming logic at run-time before sending the final HTML to the browser for display.
@@ -562,7 +632,7 @@ Ecto has added in some helper functions for frontmatter in markdown files. Front
562
632
 
563
633
  * `.hasFrontMatter(source: string): boolean` - This function checks if the markdown file has frontmatter. It takes in a string and returns a boolean value.
564
634
  * `.getFrontMatter(source: string): object` - This function gets the frontmatter from the markdown file. It takes in a string and returns an object.
565
- * `setFrontMatter(source:string, data: Record<string, unknown>)` - This function sets the front matter even if it already exists and returns the full source with the new front matter.
635
+ * `setFrontMatter(source:string, data: Record<string, unknown>)` - This function sets the front matter even if it already exists and returns the full source with the new front matter.
566
636
  * `.removeFrontMatter(source: string): string` - This function removes the frontmatter from the markdown file. It takes in a string and returns a string.
567
637
 
568
638
  # Caching on Rendering
@@ -642,6 +712,440 @@ const data = { firstName: "John", lastName: "Doe" };
642
712
  await ecto.render(source, data); // <h1>Hello John Doe!</h1>
643
713
  ```
644
714
 
715
+ # Creating Custom Engines
716
+
717
+ Ecto allows you to create your own custom template engines by implementing the `EngineInterface`. This is useful when you want to integrate a template engine that isn't built into Ecto or when you need custom rendering logic.
718
+
719
+ ## Direct Engine Usage
720
+
721
+ All built-in engines can be imported and used directly without going through the main `Ecto` class:
722
+
723
+ ```typescript
724
+ import { EJS, Handlebars, Liquid, Markdown, Nunjucks, Pug } from 'ecto';
725
+
726
+ // Use any engine directly
727
+ const handlebars = new Handlebars();
728
+ const result = await handlebars.render('Hello {{name}}', { name: 'World' });
729
+ ```
730
+
731
+ ### Customizing Engines via Constructor
732
+
733
+ The recommended way to customize engines is through the `engineOptions` parameter in the Ecto constructor:
734
+
735
+ ```typescript
736
+ import { Ecto } from 'ecto';
737
+
738
+ const ecto = new Ecto({
739
+ engineOptions: {
740
+ handlebars: {
741
+ noEscape: false,
742
+ strict: true
743
+ },
744
+ markdown: {
745
+ html: true,
746
+ breaks: true
747
+ },
748
+ ejs: {
749
+ delimiter: '?' // Use <? ?> instead of <% %>
750
+ }
751
+ }
752
+ });
753
+
754
+ // Engines are now configured with your options
755
+ await ecto.render('<? name ?>', { name: 'World' }, 'ejs');
756
+ ```
757
+
758
+ ### Accessing and Modifying Engines After Creation
759
+
760
+ After creating an Ecto instance, you can access each engine directly and modify it. This is useful for adding custom helpers or changing settings dynamically:
761
+
762
+ ```typescript
763
+ import { Ecto } from 'ecto';
764
+
765
+ const ecto = new Ecto();
766
+
767
+ // Access the Handlebars engine and add custom helpers
768
+ ecto.handlebars.engine.registerHelper('uppercase', (text) => {
769
+ return text.toUpperCase();
770
+ });
771
+
772
+ ecto.handlebars.engine.registerHelper('formatDate', (date) => {
773
+ return new Date(date).toLocaleDateString();
774
+ });
775
+
776
+ // Now use the customized engine
777
+ const result = await ecto.render(
778
+ 'Hello {{uppercase name}} - {{formatDate date}}',
779
+ { name: 'world', date: '2024-01-15' },
780
+ 'handlebars'
781
+ );
782
+ // Output: Hello WORLD - 1/15/2024
783
+
784
+ // Works with renderFromFile too
785
+ await ecto.renderFromFile('./template.hbs', { name: 'world', date: '2024-01-15' });
786
+ ```
787
+
788
+ ### Customizing Multiple Engines
789
+
790
+ You can customize multiple engines in the same Ecto instance:
791
+
792
+ ```typescript
793
+ import { Ecto } from 'ecto';
794
+
795
+ const ecto = new Ecto();
796
+
797
+ // Customize Handlebars with helpers
798
+ ecto.handlebars.engine.registerHelper('bold', (text) => {
799
+ return `<strong>${text}</strong>`;
800
+ });
801
+
802
+ // Customize EJS options
803
+ ecto.ejs.opts = {
804
+ ...ecto.ejs.opts,
805
+ delimiter: '?',
806
+ openDelimiter: '[',
807
+ closeDelimiter: ']'
808
+ };
809
+
810
+ // Customize Markdown options
811
+ ecto.markdown.opts = {
812
+ ...ecto.markdown.opts,
813
+ html: true,
814
+ breaks: true
815
+ };
816
+
817
+ // Use all customized engines
818
+ await ecto.render('{{bold "Hello"}}', {}, 'handlebars');
819
+ await ecto.render('[? name ?]', { name: 'World' }, 'ejs');
820
+ await ecto.render('# Hello\n\nVisit https://example.com', {}, 'markdown');
821
+ ```
822
+
823
+ ### Setting Partials Path for Handlebars
824
+
825
+ You can configure Handlebars to look for partials in multiple directories:
826
+
827
+ ```typescript
828
+ import { Ecto } from 'ecto';
829
+
830
+ const ecto = new Ecto();
831
+
832
+ // Configure where to look for partials
833
+ ecto.handlebars.partialsPath = ['partials', 'includes', 'components', 'layouts'];
834
+ ecto.handlebars.rootTemplatePath = './templates';
835
+
836
+ // Now partials will be loaded from multiple directories
837
+ await ecto.render('{{> header}}Content{{> footer}}', {}, 'handlebars');
838
+ ```
839
+
840
+ ### Using Exported Engines Standalone
841
+
842
+ You can also use the exported engine classes independently of Ecto:
843
+
844
+ ```typescript
845
+ import { Handlebars } from 'ecto';
846
+
847
+ // Create a standalone engine instance
848
+ const handlebars = new Handlebars();
849
+
850
+ // Add custom helpers
851
+ handlebars.engine.registerHelper('shout', (text) => {
852
+ return text.toUpperCase() + '!!!';
853
+ });
854
+
855
+ // Use it directly
856
+ const result = await handlebars.render('{{shout greeting}}', { greeting: 'hello' });
857
+ console.log(result); // HELLO!!!
858
+ ```
859
+
860
+ This pattern is particularly powerful when:
861
+ - You need consistent helpers across all templates
862
+ - You want to configure engine-specific options globally
863
+ - You're building a framework or application with specific template requirements
864
+ - You need to extend engine functionality beyond default behavior
865
+
866
+ ## Creating a Custom Engine
867
+
868
+ To create a custom engine, you need to:
869
+
870
+ 1. Extend the `BaseEngine` class
871
+ 2. Implement the `EngineInterface`
872
+ 3. Define your engine's name and file extensions
873
+ 4. Implement the `render` and `renderSync` methods
874
+
875
+ ### Basic Custom Engine Example
876
+
877
+ Here's a simple example of a custom uppercase engine:
878
+
879
+ ```typescript
880
+ import { BaseEngine, type EngineInterface } from 'ecto';
881
+
882
+ class UppercaseEngine extends BaseEngine implements EngineInterface {
883
+ constructor(options?: Record<string, unknown>) {
884
+ super();
885
+
886
+ // Define the engine name(s)
887
+ this.names = ['uppercase', 'upper'];
888
+
889
+ // Set any options
890
+ this.opts = options;
891
+
892
+ // Define file extensions this engine handles
893
+ this.setExtensions(['upper', 'uppercase']);
894
+ }
895
+
896
+ async render(source: string, data?: Record<string, unknown>): Promise<string> {
897
+ // Simple rendering logic: replace variables and uppercase everything
898
+ let result = source;
899
+
900
+ if (data) {
901
+ // Replace {{variable}} with data values
902
+ for (const [key, value] of Object.entries(data)) {
903
+ const regex = new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, 'g');
904
+ result = result.replace(regex, String(value));
905
+ }
906
+ }
907
+
908
+ // Convert to uppercase
909
+ return result.toUpperCase();
910
+ }
911
+
912
+ renderSync(source: string, data?: Record<string, unknown>): string {
913
+ // Same logic for synchronous rendering
914
+ let result = source;
915
+
916
+ if (data) {
917
+ for (const [key, value] of Object.entries(data)) {
918
+ const regex = new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, 'g');
919
+ result = result.replace(regex, String(value));
920
+ }
921
+ }
922
+
923
+ return result.toUpperCase();
924
+ }
925
+ }
926
+
927
+ // Use the custom engine
928
+ const engine = new UppercaseEngine();
929
+ const result = await engine.render('Hello {{name}}!', { name: 'World' });
930
+ console.log(result); // Output: HELLO WORLD!
931
+ ```
932
+
933
+ ### Integrating Custom Engine with Ecto
934
+
935
+ To use your custom engine with the main Ecto class, you need to register it:
936
+
937
+ ```typescript
938
+ import { Ecto } from 'ecto';
939
+
940
+ const ecto = new Ecto();
941
+
942
+ // Create and register your custom engine
943
+ const uppercaseEngine = new UppercaseEngine();
944
+
945
+ // Add to the engines collection
946
+ ecto.engines.set('uppercase', uppercaseEngine);
947
+
948
+ // Register the file extensions
949
+ ecto.mappings.set('uppercase', ['upper', 'uppercase']);
950
+
951
+ // Now you can use it with render
952
+ const result = await ecto.render('Hello {{name}}!', { name: 'World' }, 'uppercase');
953
+ console.log(result); // HELLO WORLD!
954
+
955
+ // Or with renderFromFile (for .upper or .uppercase files)
956
+ await ecto.renderFromFile('./template.upper', { name: 'World' });
957
+ ```
958
+
959
+ ### Advanced Custom Engine with Template Library
960
+
961
+ Here's a more advanced example that wraps an external template library:
962
+
963
+ ```typescript
964
+ import { BaseEngine, type EngineInterface } from 'ecto';
965
+ import Handlebars from 'handlebars'; // Example external library
966
+
967
+ class CustomHandlebarsEngine extends BaseEngine implements EngineInterface {
968
+ constructor(options?: Record<string, unknown>) {
969
+ super();
970
+
971
+ this.names = ['custom-handlebars'];
972
+ this.opts = options;
973
+ this.setExtensions(['chbs']);
974
+
975
+ // Initialize the underlying engine
976
+ this.engine = Handlebars.create();
977
+
978
+ // Register custom helpers
979
+ this.engine.registerHelper('shout', (text: string) => {
980
+ return text.toUpperCase() + '!!!';
981
+ });
982
+
983
+ this.engine.registerHelper('whisper', (text: string) => {
984
+ return text.toLowerCase() + '...';
985
+ });
986
+ }
987
+
988
+ async render(source: string, data?: Record<string, unknown>): Promise<string> {
989
+ const template = this.engine.compile(source, this.opts);
990
+ return template(data);
991
+ }
992
+
993
+ renderSync(source: string, data?: Record<string, unknown>): string {
994
+ const template = this.engine.compile(source, this.opts);
995
+ return template(data);
996
+ }
997
+ }
998
+
999
+ // Usage
1000
+ const engine = new CustomHandlebarsEngine();
1001
+ const result = await engine.render(
1002
+ 'Normal: {{name}}, Shout: {{shout name}}, Whisper: {{whisper name}}',
1003
+ { name: 'Hello' }
1004
+ );
1005
+ console.log(result);
1006
+ // Output: Normal: Hello, Shout: HELLO!!!, Whisper: hello...
1007
+ ```
1008
+
1009
+ ### Custom Engine with Partials Support
1010
+
1011
+ If your engine needs to support partials, you can handle the `rootTemplatePath`:
1012
+
1013
+ ```typescript
1014
+ import fs from 'node:fs';
1015
+ import { BaseEngine, type EngineInterface } from 'ecto';
1016
+
1017
+ class CustomEngineWithPartials extends BaseEngine implements EngineInterface {
1018
+ private partials: Map<string, string> = new Map();
1019
+
1020
+ constructor(options?: Record<string, unknown>) {
1021
+ super();
1022
+ this.names = ['custom-partials'];
1023
+ this.opts = options;
1024
+ this.setExtensions(['cpart']);
1025
+ }
1026
+
1027
+ async render(source: string, data?: Record<string, unknown>): Promise<string> {
1028
+ // Load partials if rootTemplatePath is set
1029
+ if (this.rootTemplatePath) {
1030
+ await this.loadPartials(this.rootTemplatePath);
1031
+ }
1032
+
1033
+ // Process includes: {{> partialName}}
1034
+ let result = source;
1035
+ const includeRegex = /\{\{>\s*(\w+)\s*\}\}/g;
1036
+ result = result.replace(includeRegex, (match, partialName) => {
1037
+ return this.partials.get(partialName) || match;
1038
+ });
1039
+
1040
+ // Process variables: {{variableName}}
1041
+ if (data) {
1042
+ for (const [key, value] of Object.entries(data)) {
1043
+ const regex = new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, 'g');
1044
+ result = result.replace(regex, String(value));
1045
+ }
1046
+ }
1047
+
1048
+ return result;
1049
+ }
1050
+
1051
+ renderSync(source: string, data?: Record<string, unknown>): string {
1052
+ if (this.rootTemplatePath) {
1053
+ this.loadPartialsSync(this.rootTemplatePath);
1054
+ }
1055
+
1056
+ let result = source;
1057
+ const includeRegex = /\{\{>\s*(\w+)\s*\}\}/g;
1058
+ result = result.replace(includeRegex, (match, partialName) => {
1059
+ return this.partials.get(partialName) || match;
1060
+ });
1061
+
1062
+ if (data) {
1063
+ for (const [key, value] of Object.entries(data)) {
1064
+ const regex = new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, 'g');
1065
+ result = result.replace(regex, String(value));
1066
+ }
1067
+ }
1068
+
1069
+ return result;
1070
+ }
1071
+
1072
+ private async loadPartials(partialsPath: string): Promise<void> {
1073
+ const files = await fs.promises.readdir(partialsPath);
1074
+ for (const file of files) {
1075
+ if (file.endsWith('.cpart')) {
1076
+ const name = file.replace('.cpart', '');
1077
+ const content = await fs.promises.readFile(
1078
+ `${partialsPath}/${file}`,
1079
+ 'utf-8'
1080
+ );
1081
+ this.partials.set(name, content);
1082
+ }
1083
+ }
1084
+ }
1085
+
1086
+ private loadPartialsSync(partialsPath: string): void {
1087
+ const files = fs.readdirSync(partialsPath);
1088
+ for (const file of files) {
1089
+ if (file.endsWith('.cpart')) {
1090
+ const name = file.replace('.cpart', '');
1091
+ const content = fs.readFileSync(`${partialsPath}/${file}`, 'utf-8');
1092
+ this.partials.set(name, content);
1093
+ }
1094
+ }
1095
+ }
1096
+ }
1097
+
1098
+ // Usage
1099
+ const engine = new CustomEngineWithPartials();
1100
+ engine.rootTemplatePath = './templates/partials';
1101
+ const result = await engine.render('{{> header}}\nHello {{name}}!\n{{> footer}}', {
1102
+ name: 'World'
1103
+ });
1104
+ ```
1105
+
1106
+ ## Engine Interface Reference
1107
+
1108
+ When creating a custom engine, implement these required methods:
1109
+
1110
+ ```typescript
1111
+ interface EngineInterface {
1112
+ // Engine name(s) - can support multiple aliases
1113
+ names: string[];
1114
+
1115
+ // The underlying template engine (if wrapping a library)
1116
+ engine: any;
1117
+
1118
+ // Optional configuration
1119
+ opts?: Record<string, unknown>;
1120
+
1121
+ // Root path for templates (used for partials/includes)
1122
+ rootTemplatePath?: string;
1123
+
1124
+ // Async rendering method
1125
+ render(source: string, data?: Record<string, unknown>): Promise<string>;
1126
+
1127
+ // Synchronous rendering method
1128
+ renderSync(source: string, data?: Record<string, unknown>): string;
1129
+ }
1130
+ ```
1131
+
1132
+ ## BaseEngine Helper Methods
1133
+
1134
+ The `BaseEngine` class provides useful helper methods:
1135
+
1136
+ - `getExtensions()`: Get registered file extensions
1137
+ - `setExtensions(extensions: string[])`: Set file extensions this engine handles
1138
+ - `deleteExtension(name: string)`: Remove a file extension
1139
+
1140
+ ## Tips for Custom Engines
1141
+
1142
+ 1. **Error Handling**: Always wrap your rendering logic in try-catch blocks
1143
+ 2. **Options**: Make your engine configurable through the constructor options
1144
+ 3. **Performance**: Consider caching compiled templates if applicable
1145
+ 4. **Type Safety**: Use TypeScript for better development experience
1146
+ 5. **Testing**: Write comprehensive tests for your custom engine
1147
+ 6. **Documentation**: Document your engine's syntax and features
1148
+
645
1149
  # How to Contribute
646
1150
 
647
1151
  To contribute please ready our [CONTRIBUTING.md](CONTRIBUTING.md) guide. Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
package/dist/ecto.d.ts CHANGED
@@ -195,121 +195,177 @@ declare class Ecto extends Hookified {
195
195
  */
196
196
  get liquid(): Liquid;
197
197
  /**
198
- * Async render the source with the data
199
- * @param {string} source - The source to render
200
- * @param {Record<string, unknown} data - data to render with the source
201
- * @param {string} [engineName] - The engine to use for rendering
202
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
203
- * @param {string} [filePathOutput] - The file path to write the output
204
- * @returns {Promise<string>}
198
+ * Asynchronously render a template source with data using the specified engine
199
+ * @param {string} source - The template source string to render
200
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
201
+ * @param {string} [engineName] - Name of the engine to use (e.g., 'ejs', 'pug'). Defaults to defaultEngine
202
+ * @param {string} [rootTemplatePath] - Root directory path for template includes/partials resolution
203
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
204
+ * @returns {Promise<string>} The rendered template output as a string
205
+ * @example
206
+ * const result = await ecto.render('<%= name %>', { name: 'World' }, 'ejs');
205
207
  */
206
208
  render(source: string, data?: Record<string, unknown>, engineName?: string, rootTemplatePath?: string, filePathOutput?: string): Promise<string>;
207
209
  /**
208
- * Synchronously render the source with the data
209
- * @param {string} source - The source to render
210
- * @param {Record<string, unknown} data - data to render with the source
211
- * @param {string} [engineName] - The engine to use for rendering
212
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
213
- * @param {string} [filePathOutput] - The file path to write the output
214
- * @returns {string}
210
+ * Synchronously render a template source with data using the specified engine
211
+ * @param {string} source - The template source string to render
212
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
213
+ * @param {string} [engineName] - Name of the engine to use (e.g., 'ejs', 'pug'). Defaults to defaultEngine
214
+ * @param {string} [rootTemplatePath] - Root directory path for template includes/partials resolution
215
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
216
+ * @returns {string} The rendered template output as a string
217
+ * @example
218
+ * const result = ecto.renderSync('<%= name %>', { name: 'World' }, 'ejs');
215
219
  */
216
220
  renderSync(source: string, data?: Record<string, unknown>, engineName?: string, rootTemplatePath?: string, filePathOutput?: string): string;
217
221
  /**
218
- * Render from a file path
219
- * @param {string} filePath - The file path to the source
220
- * @param {Record<string, unknown>} data - The data to render with the source
221
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
222
- * @param {string} [filePathOutput] - The file path to write the output
223
- * @param {string} [engineName] - The engine to use for rendering
224
- * @returns
222
+ * Asynchronously render a template from a file path
223
+ * @param {string} filePath - Path to the template file to render
224
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
225
+ * @param {string} [rootTemplatePath] - Root directory for template includes. Defaults to file's directory
226
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
227
+ * @param {string} [engineName] - Engine to use. If not specified, determined from file extension
228
+ * @returns {Promise<string>} The rendered template output as a string
229
+ * @example
230
+ * const result = await ecto.renderFromFile('./templates/index.ejs', { title: 'Home' });
225
231
  */
226
232
  renderFromFile(filePath: string, data?: Record<string, unknown>, rootTemplatePath?: string, filePathOutput?: string, engineName?: string): Promise<string>;
227
233
  /**
228
- * Sync render from a file path
229
- * @param {string} filePath - The file path to the source
230
- * @param {Record<string, unknown>} data - The data to render with the source
231
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
232
- * @param {string} [filePathOutput] - The file path to write the output
233
- * @param {string} [engineName] - The engine to use for rendering
234
- * @returns {string}
234
+ * Synchronously render a template from a file path
235
+ * @param {string} filePath - Path to the template file to render
236
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
237
+ * @param {string} [rootTemplatePath] - Root directory for template includes. Defaults to file's directory
238
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
239
+ * @param {string} [engineName] - Engine to use. If not specified, determined from file extension
240
+ * @returns {string} The rendered template output as a string
241
+ * @example
242
+ * const result = ecto.renderFromFileSync('./templates/index.ejs', { title: 'Home' });
235
243
  */
236
244
  renderFromFileSync(filePath: string, data?: Record<string, unknown>, rootTemplatePath?: string, filePathOutput?: string, engineName?: string): string;
237
245
  /**
238
- * Ensure the file path exists or create it
239
- * @param {string} path
246
+ * Asynchronously ensure that the directory path for a file exists, creating it if necessary
247
+ * @param {string} path - The full file path (directories will be extracted from this)
240
248
  * @returns {Promise<void>}
249
+ * @example
250
+ * await ecto.ensureFilePath('/path/to/file.txt');
241
251
  */
242
252
  ensureFilePath(path: string): Promise<void>;
243
253
  /**
244
- * Ensure the file path exists or create it synchronously
245
- * @param {string} path
254
+ * Synchronously ensure that the directory path for a file exists, creating it if necessary
255
+ * @param {string} path - The full file path (directories will be extracted from this)
246
256
  * @returns {void}
257
+ * @example
258
+ * ecto.ensureFilePathSync('/path/to/file.txt');
247
259
  */
248
260
  ensureFilePathSync(path: string): void;
249
261
  /**
250
- * Get the Engine By File Path
251
- * @param {string} filePath
252
- * @returns {string} - will return the engine name such as 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid'
262
+ * Determine the appropriate template engine based on a file's extension
263
+ * @param {string} filePath - The file path to analyze
264
+ * @returns {string} The engine name (e.g., 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid')
265
+ * @example
266
+ * const engine = ecto.getEngineByFilePath('template.ejs'); // Returns 'ejs'
253
267
  */
254
268
  getEngineByFilePath(filePath: string): string;
255
269
  /**
256
- * Find the template without the extension. This will look in a directory for a file that starts with the template name
257
- * @param {string} path - the path to look for the template file
258
- * @param {string} templateName
259
- * @returns {Promise<string>} - the path to the template file
270
+ * Asynchronously find a template file in a directory by name, regardless of extension
271
+ * @param {string} path - Directory path to search in
272
+ * @param {string} templateName - Template name without extension
273
+ * @returns {Promise<string>} Full path to the found template file, or empty string if not found
274
+ * @example
275
+ * const templatePath = await ecto.findTemplateWithoutExtension('./templates', 'index');
260
276
  */
261
277
  findTemplateWithoutExtension(path: string, templateName: string): Promise<string>;
262
278
  /**
263
- * Syncronously find the template without the extension. This will look in a directory for a file that starts with the template name
264
- * @param {string} path - the path to look for the template file
265
- * @param {string} templateName
266
- * @returns {string} - the path to the template file
279
+ * Synchronously find a template file in a directory by name, regardless of extension
280
+ * @param {string} path - Directory path to search in
281
+ * @param {string} templateName - Template name without extension
282
+ * @returns {string} Full path to the found template file, or empty string if not found
283
+ * @example
284
+ * const templatePath = ecto.findTemplateWithoutExtensionSync('./templates', 'index');
267
285
  */
268
286
  findTemplateWithoutExtensionSync(path: string, templateName: string): string;
269
287
  /**
270
- * Is it a valid engine that is registered in ecto
271
- * @param engineName
272
- * @returns {boolean}
288
+ * Check if the given engine name is valid and registered in Ecto
289
+ * @param {string} [engineName] - The engine name to validate
290
+ * @returns {boolean} True if the engine is valid and registered, false otherwise
291
+ * @example
292
+ * const isValid = ecto.isValidEngine('ejs'); // Returns true
273
293
  */
274
294
  isValidEngine(engineName?: string): boolean;
275
295
  /**
276
- * Register the engine mappings
296
+ * Detect the template engine from a template string by analyzing its syntax
297
+ * @param {string} source - The template source string to analyze
298
+ * @returns {string} The detected engine name ('ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid') or the default engine
299
+ * @example
300
+ * const engine = ecto.detectEngine('<%= name %>'); // Returns 'ejs'
301
+ * const engine2 = ecto.detectEngine('{{name}}'); // Returns 'handlebars' or 'liquid'
302
+ * const engine3 = ecto.detectEngine('# Heading'); // Returns 'markdown'
303
+ * const engine4 = ecto.detectEngine('plain text'); // Returns defaultEngine (e.g., 'ejs')
304
+ */
305
+ detectEngine(source: string): string;
306
+ /**
307
+ * Register all engine mappings between engine names and file extensions
277
308
  * @returns {void}
309
+ * @private
278
310
  */
279
311
  registerEngineMappings(): void;
280
312
  /**
281
- * Get Render Engine by the engine name. Default is EJS
282
- * @param {string} engineName
283
- * @returns {EngineInterface}
313
+ * Get the render engine instance by name
314
+ * @param {string} engineName - The name of the engine to retrieve
315
+ * @returns {EngineInterface} The engine instance (defaults to EJS if not found)
316
+ * @example
317
+ * const engine = ecto.getRenderEngine('pug');
284
318
  */
285
319
  getRenderEngine(engineName: string): EngineInterface;
286
320
  /**
287
- * Checks if the source has front matter
288
- * @param {string} source
289
- * @returns {boolean}
321
+ * Check if the source content contains front matter (YAML metadata)
322
+ * @param {string} source - The source content to check
323
+ * @returns {boolean} True if front matter is present, false otherwise
324
+ * @example
325
+ * const hasFM = ecto.hasFrontMatter('---\ntitle: Test\n---\nContent');
290
326
  */
291
327
  hasFrontMatter(source: string): boolean;
292
328
  /**
293
- * Get the Front Matter from the source
294
- * @param {string} source
295
- * @returns {Record<string, unknown>}
329
+ * Extract front matter data from the source content
330
+ * @param {string} source - The source content containing front matter
331
+ * @returns {Record<string, unknown>} Parsed front matter as an object
332
+ * @example
333
+ * const data = ecto.getFrontMatter('---\ntitle: Test\n---\nContent');
296
334
  */
297
335
  getFrontMatter(source: string): Record<string, unknown>;
298
336
  /**
299
- * Will set the front matter in the source and return the source
300
- * @param {string} source - The source to set the front matter
301
- * @param {Record<string, unknown>} data - The front matter data
302
- * @returns {string} - The source with the front matter
337
+ * Set or replace front matter in the source content
338
+ * @param {string} source - The source content
339
+ * @param {Record<string, unknown>} data - The front matter data to set
340
+ * @returns {string} The source content with updated front matter
341
+ * @example
342
+ * const updated = ecto.setFrontMatter('Content', { title: 'New Title' });
303
343
  */
304
344
  setFrontMatter(source: string, data: Record<string, unknown>): string;
305
345
  /**
306
- * Remove the Front Matter from the source
307
- * @param {string} source
308
- * @returns {string}
346
+ * Remove front matter from the source content, returning only the body
347
+ * @param {string} source - The source content with front matter
348
+ * @returns {string} The source content without front matter
349
+ * @example
350
+ * const body = ecto.removeFrontMatter('---\ntitle: Test\n---\nContent');
309
351
  */
310
352
  removeFrontMatter(source: string): string;
353
+ /**
354
+ * Write content to a file asynchronously, creating directories if needed
355
+ * @private
356
+ * @param {string} [filePath] - The path to write the file to
357
+ * @param {string} [source] - The content to write to the file
358
+ * @returns {Promise<void>}
359
+ */
311
360
  private writeFile;
361
+ /**
362
+ * Write content to a file synchronously, creating directories if needed
363
+ * @private
364
+ * @param {string} [filePath] - The path to write the file to
365
+ * @param {string} [source] - The content to write to the file
366
+ * @returns {void}
367
+ */
312
368
  private writeFileSync;
313
369
  }
314
370
 
315
- export { Ecto, EctoEvents, type EctoOptions };
371
+ export { BaseEngine, EJS, Ecto, EctoEvents, type EctoOptions, type EngineInterface, Handlebars, Liquid, Markdown, Nunjucks, Pug };
package/dist/ecto.js CHANGED
@@ -114,7 +114,7 @@ var EJS = class extends BaseEngine {
114
114
  // src/engines/handlebars.ts
115
115
  import fs from "fs";
116
116
  import { fumanchu } from "@jaredwray/fumanchu";
117
- import * as _ from "underscore";
117
+ import { decode } from "ent";
118
118
  var Handlebars = class extends BaseEngine {
119
119
  partialsPath = ["partials", "includes", "templates"];
120
120
  constructor(options) {
@@ -130,7 +130,7 @@ var Handlebars = class extends BaseEngine {
130
130
  }
131
131
  const template = this.engine.compile(source, this.opts);
132
132
  let result = template(data, this.opts);
133
- result = _.unescape(result);
133
+ result = decode(result);
134
134
  return result;
135
135
  }
136
136
  renderSync(source, data) {
@@ -139,7 +139,7 @@ var Handlebars = class extends BaseEngine {
139
139
  }
140
140
  const template = this.engine.compile(source, this.opts);
141
141
  let result = template(data, this.opts);
142
- result = _.unescape(result);
142
+ result = decode(result);
143
143
  return result;
144
144
  }
145
145
  initPartials() {
@@ -459,13 +459,15 @@ var Ecto = class extends Hookified {
459
459
  return this._liquid;
460
460
  }
461
461
  /**
462
- * Async render the source with the data
463
- * @param {string} source - The source to render
464
- * @param {Record<string, unknown} data - data to render with the source
465
- * @param {string} [engineName] - The engine to use for rendering
466
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
467
- * @param {string} [filePathOutput] - The file path to write the output
468
- * @returns {Promise<string>}
462
+ * Asynchronously render a template source with data using the specified engine
463
+ * @param {string} source - The template source string to render
464
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
465
+ * @param {string} [engineName] - Name of the engine to use (e.g., 'ejs', 'pug'). Defaults to defaultEngine
466
+ * @param {string} [rootTemplatePath] - Root directory path for template includes/partials resolution
467
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
468
+ * @returns {Promise<string>} The rendered template output as a string
469
+ * @example
470
+ * const result = await ecto.render('<%= name %>', { name: 'World' }, 'ejs');
469
471
  */
470
472
  async render(source, data, engineName, rootTemplatePath, filePathOutput) {
471
473
  try {
@@ -498,13 +500,15 @@ var Ecto = class extends Hookified {
498
500
  }
499
501
  }
500
502
  /**
501
- * Synchronously render the source with the data
502
- * @param {string} source - The source to render
503
- * @param {Record<string, unknown} data - data to render with the source
504
- * @param {string} [engineName] - The engine to use for rendering
505
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
506
- * @param {string} [filePathOutput] - The file path to write the output
507
- * @returns {string}
503
+ * Synchronously render a template source with data using the specified engine
504
+ * @param {string} source - The template source string to render
505
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
506
+ * @param {string} [engineName] - Name of the engine to use (e.g., 'ejs', 'pug'). Defaults to defaultEngine
507
+ * @param {string} [rootTemplatePath] - Root directory path for template includes/partials resolution
508
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
509
+ * @returns {string} The rendered template output as a string
510
+ * @example
511
+ * const result = ecto.renderSync('<%= name %>', { name: 'World' }, 'ejs');
508
512
  */
509
513
  renderSync(source, data, engineName, rootTemplatePath, filePathOutput) {
510
514
  try {
@@ -537,13 +541,15 @@ var Ecto = class extends Hookified {
537
541
  }
538
542
  }
539
543
  /**
540
- * Render from a file path
541
- * @param {string} filePath - The file path to the source
542
- * @param {Record<string, unknown>} data - The data to render with the source
543
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
544
- * @param {string} [filePathOutput] - The file path to write the output
545
- * @param {string} [engineName] - The engine to use for rendering
546
- * @returns
544
+ * Asynchronously render a template from a file path
545
+ * @param {string} filePath - Path to the template file to render
546
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
547
+ * @param {string} [rootTemplatePath] - Root directory for template includes. Defaults to file's directory
548
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
549
+ * @param {string} [engineName] - Engine to use. If not specified, determined from file extension
550
+ * @returns {Promise<string>} The rendered template output as a string
551
+ * @example
552
+ * const result = await ecto.renderFromFile('./templates/index.ejs', { title: 'Home' });
547
553
  */
548
554
  async renderFromFile(filePath, data, rootTemplatePath, filePathOutput, engineName) {
549
555
  let result = "";
@@ -560,13 +566,15 @@ var Ecto = class extends Hookified {
560
566
  return result;
561
567
  }
562
568
  /**
563
- * Sync render from a file path
564
- * @param {string} filePath - The file path to the source
565
- * @param {Record<string, unknown>} data - The data to render with the source
566
- * @param {string} [rootTemplatePath] - The root path to the template if using includes / partials
567
- * @param {string} [filePathOutput] - The file path to write the output
568
- * @param {string} [engineName] - The engine to use for rendering
569
- * @returns {string}
569
+ * Synchronously render a template from a file path
570
+ * @param {string} filePath - Path to the template file to render
571
+ * @param {Record<string, unknown>} [data] - Data object to pass to the template engine
572
+ * @param {string} [rootTemplatePath] - Root directory for template includes. Defaults to file's directory
573
+ * @param {string} [filePathOutput] - Optional file path to write the rendered output to
574
+ * @param {string} [engineName] - Engine to use. If not specified, determined from file extension
575
+ * @returns {string} The rendered template output as a string
576
+ * @example
577
+ * const result = ecto.renderFromFileSync('./templates/index.ejs', { title: 'Home' });
570
578
  */
571
579
  renderFromFileSync(filePath, data, rootTemplatePath, filePathOutput, engineName) {
572
580
  let result = "";
@@ -583,9 +591,11 @@ var Ecto = class extends Hookified {
583
591
  return result;
584
592
  }
585
593
  /**
586
- * Ensure the file path exists or create it
587
- * @param {string} path
594
+ * Asynchronously ensure that the directory path for a file exists, creating it if necessary
595
+ * @param {string} path - The full file path (directories will be extracted from this)
588
596
  * @returns {Promise<void>}
597
+ * @example
598
+ * await ecto.ensureFilePath('/path/to/file.txt');
589
599
  */
590
600
  async ensureFilePath(path2) {
591
601
  const pathList = path2.split("/");
@@ -596,9 +606,11 @@ var Ecto = class extends Hookified {
596
606
  }
597
607
  }
598
608
  /**
599
- * Ensure the file path exists or create it synchronously
600
- * @param {string} path
609
+ * Synchronously ensure that the directory path for a file exists, creating it if necessary
610
+ * @param {string} path - The full file path (directories will be extracted from this)
601
611
  * @returns {void}
612
+ * @example
613
+ * ecto.ensureFilePathSync('/path/to/file.txt');
602
614
  */
603
615
  ensureFilePathSync(path2) {
604
616
  const pathList = path2.split("/");
@@ -609,9 +621,11 @@ var Ecto = class extends Hookified {
609
621
  }
610
622
  }
611
623
  /**
612
- * Get the Engine By File Path
613
- * @param {string} filePath
614
- * @returns {string} - will return the engine name such as 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid'
624
+ * Determine the appropriate template engine based on a file's extension
625
+ * @param {string} filePath - The file path to analyze
626
+ * @returns {string} The engine name (e.g., 'ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid')
627
+ * @example
628
+ * const engine = ecto.getEngineByFilePath('template.ejs'); // Returns 'ejs'
615
629
  */
616
630
  getEngineByFilePath(filePath) {
617
631
  let result = this._defaultEngine;
@@ -625,10 +639,12 @@ var Ecto = class extends Hookified {
625
639
  return result;
626
640
  }
627
641
  /**
628
- * Find the template without the extension. This will look in a directory for a file that starts with the template name
629
- * @param {string} path - the path to look for the template file
630
- * @param {string} templateName
631
- * @returns {Promise<string>} - the path to the template file
642
+ * Asynchronously find a template file in a directory by name, regardless of extension
643
+ * @param {string} path - Directory path to search in
644
+ * @param {string} templateName - Template name without extension
645
+ * @returns {Promise<string>} Full path to the found template file, or empty string if not found
646
+ * @example
647
+ * const templatePath = await ecto.findTemplateWithoutExtension('./templates', 'index');
632
648
  */
633
649
  async findTemplateWithoutExtension(path2, templateName) {
634
650
  let result = "";
@@ -642,10 +658,12 @@ var Ecto = class extends Hookified {
642
658
  return result;
643
659
  }
644
660
  /**
645
- * Syncronously find the template without the extension. This will look in a directory for a file that starts with the template name
646
- * @param {string} path - the path to look for the template file
647
- * @param {string} templateName
648
- * @returns {string} - the path to the template file
661
+ * Synchronously find a template file in a directory by name, regardless of extension
662
+ * @param {string} path - Directory path to search in
663
+ * @param {string} templateName - Template name without extension
664
+ * @returns {string} Full path to the found template file, or empty string if not found
665
+ * @example
666
+ * const templatePath = ecto.findTemplateWithoutExtensionSync('./templates', 'index');
649
667
  */
650
668
  findTemplateWithoutExtensionSync(path2, templateName) {
651
669
  let result = "";
@@ -659,9 +677,11 @@ var Ecto = class extends Hookified {
659
677
  return result;
660
678
  }
661
679
  /**
662
- * Is it a valid engine that is registered in ecto
663
- * @param engineName
664
- * @returns {boolean}
680
+ * Check if the given engine name is valid and registered in Ecto
681
+ * @param {string} [engineName] - The engine name to validate
682
+ * @returns {boolean} True if the engine is valid and registered, false otherwise
683
+ * @example
684
+ * const isValid = ecto.isValidEngine('ejs'); // Returns true
665
685
  */
666
686
  isValidEngine(engineName) {
667
687
  let result = false;
@@ -671,8 +691,156 @@ var Ecto = class extends Hookified {
671
691
  return result;
672
692
  }
673
693
  /**
674
- * Register the engine mappings
694
+ * Detect the template engine from a template string by analyzing its syntax
695
+ * @param {string} source - The template source string to analyze
696
+ * @returns {string} The detected engine name ('ejs', 'markdown', 'pug', 'nunjucks', 'handlebars', 'liquid') or the default engine
697
+ * @example
698
+ * const engine = ecto.detectEngine('<%= name %>'); // Returns 'ejs'
699
+ * const engine2 = ecto.detectEngine('{{name}}'); // Returns 'handlebars' or 'liquid'
700
+ * const engine3 = ecto.detectEngine('# Heading'); // Returns 'markdown'
701
+ * const engine4 = ecto.detectEngine('plain text'); // Returns defaultEngine (e.g., 'ejs')
702
+ */
703
+ detectEngine(source) {
704
+ if (!source || typeof source !== "string") {
705
+ return this._defaultEngine;
706
+ }
707
+ if (source.includes("<%")) {
708
+ if (source.includes("<%=") || source.includes("<%-") || source.includes("%>")) {
709
+ return "ejs";
710
+ }
711
+ }
712
+ if (source.includes("{%")) {
713
+ const liquidKeywords = [
714
+ "liquid",
715
+ "assign",
716
+ "capture",
717
+ "endcapture",
718
+ "case",
719
+ "when",
720
+ "unless",
721
+ "endunless",
722
+ "tablerow",
723
+ "endtablerow",
724
+ "increment",
725
+ "decrement"
726
+ ];
727
+ for (const keyword of liquidKeywords) {
728
+ if (source.includes(`{% ${keyword}`) || source.includes(`{%${keyword}`)) {
729
+ return "liquid";
730
+ }
731
+ }
732
+ if (source.includes("{{") && source.includes("|") && source.includes("}}")) {
733
+ const nunjucksSpecific = [
734
+ "block",
735
+ "extends",
736
+ "macro",
737
+ "import",
738
+ "call"
739
+ ];
740
+ let hasNunjucksKeyword = false;
741
+ for (const keyword of nunjucksSpecific) {
742
+ if (source.includes(`{% ${keyword}`) || source.includes(`{%${keyword}`)) {
743
+ hasNunjucksKeyword = true;
744
+ break;
745
+ }
746
+ }
747
+ if (!hasNunjucksKeyword) {
748
+ return "liquid";
749
+ }
750
+ }
751
+ }
752
+ if (source.includes("{%")) {
753
+ const nunjucksKeywords = [
754
+ "block",
755
+ "extends",
756
+ "include",
757
+ "import",
758
+ "for",
759
+ "if",
760
+ "elif",
761
+ "else",
762
+ "endif",
763
+ "endfor",
764
+ "set",
765
+ "macro",
766
+ "endmacro",
767
+ "call"
768
+ ];
769
+ for (const keyword of nunjucksKeywords) {
770
+ if (source.includes(`{% ${keyword}`) || source.includes(`{%${keyword}`)) {
771
+ return "nunjucks";
772
+ }
773
+ }
774
+ }
775
+ if (source.includes("{{")) {
776
+ if (source.includes(" | ") && source.includes("}}")) {
777
+ if (source.includes("{% assign ") || source.includes("{% capture ") || source.includes("{% unless ") || source.includes("{% increment ") || source.includes("{% decrement ") || source.includes("{% tablerow ") || source.includes("{% case ") || source.includes("{% when ") || source.includes(" | upcase") || source.includes(" | downcase") || source.includes(" | capitalize") || source.includes(" | minus:") || source.includes(" | plus:") || source.includes(" | money") || source.includes(" | date:")) {
778
+ return "liquid";
779
+ }
780
+ }
781
+ if (source.includes("{{#") || source.includes("{{/") || source.includes("{{>") || source.includes("{{!--")) {
782
+ return "handlebars";
783
+ }
784
+ if (source.includes("}}") && !source.includes("{%")) {
785
+ return "handlebars";
786
+ }
787
+ }
788
+ const lines = source.split("\n");
789
+ let markdownIndicators = 0;
790
+ let pugIndicators = 0;
791
+ for (const line of lines) {
792
+ const trimmed = line.trim();
793
+ if (trimmed.startsWith("# ") || trimmed.startsWith("## ") || trimmed.startsWith("### ") || trimmed.startsWith("#### ") || trimmed.startsWith("##### ") || trimmed.startsWith("###### ")) {
794
+ markdownIndicators++;
795
+ }
796
+ if (trimmed.startsWith("- ") || trimmed.startsWith("* ") || trimmed.startsWith("+ ")) {
797
+ markdownIndicators++;
798
+ }
799
+ const firstChar = trimmed.charAt(0);
800
+ if (firstChar >= "0" && firstChar <= "9") {
801
+ const dotIndex = trimmed.indexOf(".");
802
+ if (dotIndex > 0 && dotIndex < 4 && trimmed.charAt(dotIndex + 1) === " ") {
803
+ markdownIndicators++;
804
+ }
805
+ }
806
+ if (trimmed.startsWith("> ")) {
807
+ markdownIndicators++;
808
+ }
809
+ if (trimmed.startsWith("```")) {
810
+ markdownIndicators++;
811
+ }
812
+ if (!trimmed.startsWith("# ") && !trimmed.startsWith("- ") && !trimmed.startsWith("* ") && !trimmed.startsWith("+ ") && !trimmed.startsWith("> ")) {
813
+ if (trimmed.startsWith("doctype") || trimmed.startsWith("html") || trimmed.startsWith("head") || trimmed.startsWith("body") || trimmed.startsWith("div") || trimmed.startsWith("p") || trimmed.startsWith("h") && trimmed.length > 1 && trimmed.charAt(1) >= "1" && trimmed.charAt(1) <= "6") {
814
+ pugIndicators++;
815
+ }
816
+ if (trimmed.includes("(") && trimmed.includes(")") || trimmed.indexOf(".") === 0 || // starts with dot for class
817
+ trimmed.indexOf("#") === 0 && !trimmed.includes(" ")) {
818
+ pugIndicators++;
819
+ }
820
+ }
821
+ }
822
+ if (source.includes("](") && (source.includes("[") || source.includes("!["))) {
823
+ markdownIndicators++;
824
+ }
825
+ if (source.includes("|") && source.includes("---")) {
826
+ markdownIndicators++;
827
+ }
828
+ if (markdownIndicators > 0) {
829
+ if (!source.includes("<%") && !source.includes("{{") && !source.includes("{%")) {
830
+ return "markdown";
831
+ }
832
+ }
833
+ const hasHtmlOpenTag = source.includes("<") && source.includes(">");
834
+ const hasHtmlCloseTag = source.includes("</");
835
+ if (pugIndicators > 0 && !hasHtmlOpenTag && !hasHtmlCloseTag && !source.includes("<%") && !source.includes("{{") && !source.includes("{%")) {
836
+ return "pug";
837
+ }
838
+ return this._defaultEngine;
839
+ }
840
+ /**
841
+ * Register all engine mappings between engine names and file extensions
675
842
  * @returns {void}
843
+ * @private
676
844
  */
677
845
  registerEngineMappings() {
678
846
  for (const eng of this._engines) {
@@ -682,9 +850,11 @@ var Ecto = class extends Hookified {
682
850
  }
683
851
  }
684
852
  /**
685
- * Get Render Engine by the engine name. Default is EJS
686
- * @param {string} engineName
687
- * @returns {EngineInterface}
853
+ * Get the render engine instance by name
854
+ * @param {string} engineName - The name of the engine to retrieve
855
+ * @returns {EngineInterface} The engine instance (defaults to EJS if not found)
856
+ * @example
857
+ * const engine = ecto.getRenderEngine('pug');
688
858
  */
689
859
  getRenderEngine(engineName) {
690
860
  let result = this._ejs;
@@ -722,9 +892,11 @@ var Ecto = class extends Hookified {
722
892
  return result;
723
893
  }
724
894
  /**
725
- * Checks if the source has front matter
726
- * @param {string} source
727
- * @returns {boolean}
895
+ * Check if the source content contains front matter (YAML metadata)
896
+ * @param {string} source - The source content to check
897
+ * @returns {boolean} True if front matter is present, false otherwise
898
+ * @example
899
+ * const hasFM = ecto.hasFrontMatter('---\ntitle: Test\n---\nContent');
728
900
  */
729
901
  hasFrontMatter(source) {
730
902
  const writr = new Writr2(source);
@@ -734,19 +906,23 @@ var Ecto = class extends Hookified {
734
906
  return false;
735
907
  }
736
908
  /**
737
- * Get the Front Matter from the source
738
- * @param {string} source
739
- * @returns {Record<string, unknown>}
909
+ * Extract front matter data from the source content
910
+ * @param {string} source - The source content containing front matter
911
+ * @returns {Record<string, unknown>} Parsed front matter as an object
912
+ * @example
913
+ * const data = ecto.getFrontMatter('---\ntitle: Test\n---\nContent');
740
914
  */
741
915
  getFrontMatter(source) {
742
916
  const writr = new Writr2(source);
743
917
  return writr.frontMatter;
744
918
  }
745
919
  /**
746
- * Will set the front matter in the source and return the source
747
- * @param {string} source - The source to set the front matter
748
- * @param {Record<string, unknown>} data - The front matter data
749
- * @returns {string} - The source with the front matter
920
+ * Set or replace front matter in the source content
921
+ * @param {string} source - The source content
922
+ * @param {Record<string, unknown>} data - The front matter data to set
923
+ * @returns {string} The source content with updated front matter
924
+ * @example
925
+ * const updated = ecto.setFrontMatter('Content', { title: 'New Title' });
750
926
  */
751
927
  setFrontMatter(source, data) {
752
928
  const writr = new Writr2(source);
@@ -754,20 +930,36 @@ var Ecto = class extends Hookified {
754
930
  return writr.content;
755
931
  }
756
932
  /**
757
- * Remove the Front Matter from the source
758
- * @param {string} source
759
- * @returns {string}
933
+ * Remove front matter from the source content, returning only the body
934
+ * @param {string} source - The source content with front matter
935
+ * @returns {string} The source content without front matter
936
+ * @example
937
+ * const body = ecto.removeFrontMatter('---\ntitle: Test\n---\nContent');
760
938
  */
761
939
  removeFrontMatter(source) {
762
940
  const writr = new Writr2(source);
763
941
  return writr.body;
764
942
  }
943
+ /**
944
+ * Write content to a file asynchronously, creating directories if needed
945
+ * @private
946
+ * @param {string} [filePath] - The path to write the file to
947
+ * @param {string} [source] - The content to write to the file
948
+ * @returns {Promise<void>}
949
+ */
765
950
  async writeFile(filePath, source) {
766
951
  if (filePath && source) {
767
952
  await this.ensureFilePath(filePath);
768
953
  await fs2.promises.writeFile(filePath, source);
769
954
  }
770
955
  }
956
+ /**
957
+ * Write content to a file synchronously, creating directories if needed
958
+ * @private
959
+ * @param {string} [filePath] - The path to write the file to
960
+ * @param {string} [source] - The content to write to the file
961
+ * @returns {void}
962
+ */
771
963
  writeFileSync(filePath, source) {
772
964
  if (filePath && source) {
773
965
  this.ensureFilePathSync(filePath);
@@ -776,6 +968,13 @@ var Ecto = class extends Hookified {
776
968
  }
777
969
  };
778
970
  export {
971
+ EJS,
779
972
  Ecto,
780
- EctoEvents
973
+ EctoEvents,
974
+ Handlebars,
975
+ Liquid,
976
+ Markdown,
977
+ Nunjucks,
978
+ Pug
781
979
  };
980
+ /* v8 ignore next -- @preserve */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ecto",
3
- "version": "4.5.1",
3
+ "version": "4.7.0",
4
4
  "description": "Modern Template Consolidation Engine for EJS, Markdown, Pug, Nunjucks, Liquid, and Handlebars",
5
5
  "type": "module",
6
6
  "main": "./dist/ecto.js",
@@ -50,29 +50,29 @@
50
50
  ],
51
51
  "dependencies": {
52
52
  "@jaredwray/fumanchu": "^4.3.0",
53
- "cacheable": "^2.0.1",
53
+ "cacheable": "^2.1.1",
54
54
  "ejs": "^3.1.10",
55
- "hookified": "^1.12.1",
56
- "liquidjs": "^10.21.1",
55
+ "ent": "^2.2.2",
56
+ "hookified": "^1.12.2",
57
+ "liquidjs": "^10.23.0",
57
58
  "nunjucks": "^3.2.4",
58
59
  "pug": "^3.0.3",
59
- "underscore": "^1.13.7",
60
- "writr": "^4.5.0"
60
+ "writr": "^4.5.1"
61
61
  },
62
62
  "devDependencies": {
63
- "@biomejs/biome": "^2.2.4",
63
+ "@biomejs/biome": "^2.3.0",
64
+ "@faker-js/faker": "^10.1.0",
64
65
  "@types/ejs": "^3.1.5",
65
- "@types/node": "^24.5.2",
66
+ "@types/ent": "^2.2.8",
67
+ "@types/node": "^24.9.1",
66
68
  "@types/nunjucks": "^3.2.6",
67
69
  "@types/pug": "^2.0.10",
68
- "@types/underscore": "^1.13.0",
69
- "@vitest/coverage-v8": "^3.2.4",
70
- "docula": "^0.20.0",
70
+ "@vitest/coverage-v8": "^4.0.3",
71
+ "docula": "^0.31.0",
71
72
  "rimraf": "^6.0.1",
72
73
  "tsup": "^8.5.0",
73
- "typescript": "^5.9.2",
74
- "vitest": "^3.2.4",
75
- "webpack": "^5.101.3"
74
+ "typescript": "^5.9.3",
75
+ "vitest": "^4.0.3"
76
76
  },
77
77
  "files": [
78
78
  "dist",