@riotprompt/riotprompt 0.0.3 → 0.0.4

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.
@@ -0,0 +1,5 @@
1
+ ---
2
+ description:
3
+ globs:
4
+ alwaysApply: false
5
+ ---
package/README.md CHANGED
@@ -1,97 +1,86 @@
1
- # 🚀 RiotPrompt
1
+ # 🔥 RiotPrompt
2
2
 
3
- A structured prompt engineering library for LLMs - because you have better things to do than worry about prompt formatting.
3
+ A powerful, flexible prompt building library for AI applications with zero hardcoded assumptions.
4
4
 
5
- > "I don't wanna hear it, know you're full of sh*t" - Minor Threat
5
+ ## 🎯 Features
6
6
 
7
- [![npm version](https://badge.fury.io/js/@riotprompt%2Friotprompt.svg)](https://badge.fury.io/js/@riotprompt%2Friotprompt)
8
- [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
7
+ - **Generic & Extensible**: No hardcoded domain concepts - build any type of prompt
8
+ - **Template System**: Create reusable templates for common patterns
9
+ - **Declarative Configuration**: Simple object-based prompt creation
10
+ - **Type-Safe**: Full TypeScript support with excellent IntelliSense
11
+ - **Override System**: Customize prompts with hierarchical overrides
12
+ - **Multiple Content Types**: Support for files, directories, and inline content
9
13
 
10
- ## Quick Start
14
+ ## 🚀 Quick Start
11
15
 
12
- ### Installation
16
+ ```typescript
17
+ import { cook, registerTemplates } from 'riotprompt';
13
18
 
14
- ```bash
15
- npm install @riotprompt/riotprompt
16
- ```
17
-
18
- ### Basic Usage
19
-
20
- ```js
21
- import { createSection, Formatter } from '@riotprompt/riotprompt';
22
-
23
- // Create a section
24
- const instructions = createSection({ title: "Instructions" });
25
- instructions.add("Answer in a concise manner");
26
- instructions.add("Provide code examples when appropriate");
27
-
28
- // Format it
29
- const formatter = Formatter.create();
30
- console.log(formatter.format(instructions));
31
- ```
32
-
33
- **Output:**
34
- ```xml
35
- <Instructions>
36
- Answer in a concise manner
37
-
38
- Provide code examples when appropriate
39
- </Instructions>
40
- ```
41
-
42
- ### Revolutionary Recipes System
43
-
44
- Transform verbose builder code into simple, declarative configuration:
19
+ // Simple prompt creation
20
+ const prompt = await cook({
21
+ basePath: __dirname,
22
+ persona: { content: 'You are a helpful AI assistant' },
23
+ instructions: [
24
+ { content: 'Analyze the provided content carefully' },
25
+ { path: 'instructions/guidelines.md' },
26
+ ],
27
+ content: [
28
+ { content: sourceData, title: 'Source Data', weight: 1.0 },
29
+ { directories: ['examples/'], weight: 0.5 },
30
+ ],
31
+ context: [
32
+ { content: 'Additional context', title: 'Context' },
33
+ ],
34
+ });
45
35
 
46
- ```js
47
- import { quick } from '@riotprompt/riotprompt';
36
+ // Register and use templates
37
+ registerTemplates({
38
+ 'analysis': {
39
+ persona: { content: 'You are an expert analyst' },
40
+ instructions: [{ content: 'Provide detailed analysis' }],
41
+ },
42
+ });
48
43
 
49
- // Just one line!
50
- const prompt = await quick.commit(diffContent, {
44
+ const analysisPrompt = await cook({
51
45
  basePath: __dirname,
52
- userDirection: "Focus on performance"
46
+ template: 'analysis',
47
+ content: [{ content: dataToAnalyze, title: 'Data' }],
53
48
  });
54
49
  ```
55
50
 
56
- ## Why RiotPrompt?
51
+ ## 📚 Documentation
57
52
 
58
- - **📋 Structured Organization**: Organize prompts into logical categories (instructions, content, context)
59
- - **🔄 Reusable Components**: Create reusable persona definitions and prompt templates
60
- - **⚡ Multiple APIs**: Choose from simple one-liners to complex programmatic construction
61
- - **🎨 Flexible Formatting**: Support for both XML tags and Markdown output
62
- - **📁 File-Based Management**: Load prompts from files and directories
63
- - **🔧 Override System**: Multi-layered customization without modifying core files
64
- - **📊 90%+ Code Reduction**: Transform 25+ lines into 1-5 lines of clean configuration
53
+ - [Core Concepts](docs/public/core-concepts.md)
54
+ - [Recipes System](docs/public/recipes.md)
55
+ - [API Reference](docs/public/api-reference.md)
56
+ - [Template Configuration](docs/public/template-configuration.md)
65
57
 
66
- ## Documentation
58
+ ## 🔧 Installation
67
59
 
68
- 📖 **[Complete Documentation](https://stjustreckoning.github.io/riotprompt/)**
60
+ ```bash
61
+ npm install riotprompt
62
+ ```
69
63
 
70
- ### Key Topics
64
+ ## 💡 Philosophy
71
65
 
72
- - **[Getting Started](https://stjustreckoning.github.io/riotprompt/?section=getting-started)** - Installation and basic usage
73
- - **[Core Concepts](https://stjustreckoning.github.io/riotprompt/?section=core-concepts)** - Understanding WeightedText and Sections
74
- - **[Recipes System](https://stjustreckoning.github.io/riotprompt/?section=recipes)** - Revolutionary prompt creation API
75
- - **[Override System](https://stjustreckoning.github.io/riotprompt/?section=override)** - Multi-layered customization
76
- - **[API Reference](https://stjustreckoning.github.io/riotprompt/?section=api-reference)** - Complete API documentation
66
+ RiotPrompt is designed to be completely generic and unopinionated. Unlike other prompt libraries that assume specific use cases, RiotPrompt provides the building blocks for any prompt-based application while maintaining type safety and developer experience.
77
67
 
78
- ## Model Support
68
+ ## 🏗️ Architecture
79
69
 
80
- RiotPrompt works with any LLM that accepts text prompts:
81
- - OpenAI GPT models
82
- - Anthropic Claude
83
- - Google Gemini
84
- - Local models via Ollama
85
- - Any other text-based LLM
70
+ - **Cook Function**: Core prompt creation engine
71
+ - **Template System**: Reusable configuration patterns
72
+ - **Content Processing**: Flexible content handling (files, directories, inline)
73
+ - **Override System**: Hierarchical customization
74
+ - **Type Safety**: Full TypeScript support throughout
86
75
 
87
- ## Contributing
76
+ ## 🤝 Contributing
88
77
 
89
- We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
78
+ Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
90
79
 
91
- ## License
80
+ ## 📄 License
92
81
 
93
- Licensed under the [Apache-2.0 License](LICENSE).
82
+ MIT License - see [LICENSE](LICENSE) for details.
94
83
 
95
- ## Why the Name?
84
+ ---
96
85
 
97
- Because organizing your prompts shouldn't be a riot - but the results should be! 🎉
86
+ *Build better prompts, faster.*
package/dist/builder.js CHANGED
@@ -122,7 +122,7 @@ const create = (builderOptions)=>{
122
122
  const addContent = async (content, sectionOptions = {})=>{
123
123
  logger.debug("Adding content", typeof content);
124
124
  const currentOptions = loadOptions(sectionOptions);
125
- const parsedContentSection = parser$1.parse(content, currentOptions);
125
+ const parsedContentSection = await parser$1.parse(content, currentOptions);
126
126
  contentSection.add(parsedContentSection);
127
127
  return instance;
128
128
  };
@@ -130,7 +130,7 @@ const create = (builderOptions)=>{
130
130
  const addContext = async (context, sectionOptions = {})=>{
131
131
  logger.debug("Adding context", typeof context);
132
132
  const currentOptions = loadOptions(sectionOptions);
133
- const parsedContextSection = parser$1.parse(context, currentOptions);
133
+ const parsedContextSection = await parser$1.parse(context, currentOptions);
134
134
  contextSection.add(parsedContextSection);
135
135
  return instance;
136
136
  };
@@ -1 +1 @@
1
- {"version":3,"file":"builder.js","sources":["../src/builder.ts"],"sourcesContent":["import path from \"path\";\nimport { z } from \"zod\";\nimport { ParametersSchema } from \"./items/parameters\";\nimport { SectionOptions, SectionOptionsSchema } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Content, Context, createPrompt, createSection, Instruction, Loader, Override, Parser, Prompt, Section, Weighted } from \"./riotprompt\";\n\nconst OptionSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n basePath: z.string(),\n overridePaths: z.array(z.string()).optional().default([\"./\"]),\n overrides: z.boolean().optional().default(false),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionSchema>;\n\nexport type OptionsParam = Required<Pick<Options, 'basePath'>> & Partial<Omit<Options, 'basePath'>>;\n\nexport interface Instance {\n addPersonaPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContextPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addInstructionPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContentPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContent(content: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContext(context: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n loadContext(contextDirectories: string[], sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n loadContent(contentDirectories: string[], sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n build(): Promise<Prompt>;\n}\n\nexport const create = (builderOptions: OptionsParam): Instance => {\n const options: Required<Options> = OptionSchema.parse(builderOptions) as Required<Options>;\n\n const logger = wrapLogger(options.logger, 'Builder');\n const parser = Parser.create({ logger });\n const override = Override.create({\n logger, configDirs: options.overridePaths || [\"./\"],\n overrides: options.overrides || false\n });\n const loader = Loader.create({ logger });\n\n const personaSection: Section<Instruction> = createSection({ title: \"Persona\" });\n const contextSection: Section<Context> = createSection({ title: \"Context\" });\n const instructionSection: Section<Instruction> = createSection({ title: \"Instruction\" });\n const contentSection: Section<Content> = createSection({ title: \"Content\" });\n const parameters = options.parameters;\n\n\n const instance: Partial<Instance> = {}\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n const loadDirectories = async <T extends Weighted>(\n directories: string[],\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Section<T>[]> => {\n const currentOptions = loadOptions(sectionOptions);\n logger.debug(\"Loading directories\", directories);\n const sections: Section<T>[] = await loader.load<T>(directories, currentOptions);\n return sections;\n }\n\n const loadContext = async (\n contextDirectories: string[],\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n const currentOptions = loadOptions(sectionOptions);\n logger.debug('Loading context', contextDirectories);\n const context: Section<Context>[] = await loadDirectories<Context>(contextDirectories, currentOptions);\n contextSection.add(context);\n return instance as Instance;\n }\n instance.loadContext = loadContext;\n\n const loadContent = async (\n contentDirectories: string[],\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n const currentOptions = loadOptions(sectionOptions);\n const content: Section<Content>[] = await loadDirectories<Content>(contentDirectories, currentOptions);\n contentSection.add(content);\n return instance as Instance;\n }\n instance.loadContent = loadContent;\n\n const loadPath = async <T extends Weighted>(\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Section<T>> => {\n const currentOptions = loadOptions(sectionOptions);\n const defaultPath = path.join(options.basePath as string, contentPath);\n const section: Section<T> = await parser.parseFile<T>(defaultPath, currentOptions);\n const overrideSection = await override.customize<T>(contentPath, section, currentOptions);\n return overrideSection;\n }\n\n const addPersonaPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n const currentOptions = loadOptions(sectionOptions);\n const persona: Section<Instruction> = await loadPath<Instruction>(contentPath, currentOptions);\n personaSection.add(persona);\n return instance as Instance;\n }\n instance.addPersonaPath = addPersonaPath;\n\n const addContextPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding context path\", contentPath);\n const currentOptions = loadOptions(sectionOptions);\n const context: Section<Context> = await loadPath<Context>(contentPath, currentOptions);\n contextSection.add(context);\n return instance as Instance;\n }\n instance.addContextPath = addContextPath;\n\n const addInstructionPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding instruction path\", contentPath);\n const currentOptions = loadOptions(sectionOptions);\n const instruction: Section<Instruction> = await loadPath<Instruction>(contentPath, currentOptions);\n instructionSection.add(instruction);\n return instance as Instance;\n }\n instance.addInstructionPath = addInstructionPath;\n\n const addContentPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding content path\", contentPath);\n const currentOptions = loadOptions(sectionOptions);\n const content: Section<Content> = await loadPath<Content>(contentPath, currentOptions);\n contentSection.add(content);\n return instance as Instance;\n }\n instance.addContentPath = addContentPath;\n\n const addContent = async (\n content: string | Buffer,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding content\", typeof content);\n const currentOptions = loadOptions(sectionOptions);\n const parsedContentSection: Section<Content> = parser.parse<Content>(content, currentOptions);\n contentSection.add(parsedContentSection);\n return instance as Instance;\n }\n instance.addContent = addContent;\n\n const addContext = async (\n context: string | Buffer,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding context\", typeof context);\n const currentOptions = loadOptions(sectionOptions);\n const parsedContextSection: Section<Context> = parser.parse<Context>(context, currentOptions);\n contextSection.add(parsedContextSection);\n return instance as Instance;\n }\n instance.addContext = addContext;\n\n const build = async () => {\n logger.debug(\"Building prompt\", {});\n const prompt = createPrompt({ persona: personaSection, contexts: contextSection, instructions: instructionSection, contents: contentSection });\n return prompt;\n }\n instance.build = build;\n\n return instance as Instance;\n}\n"],"names":["OptionSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","basePath","string","overridePaths","array","overrides","boolean","parameters","ParametersSchema","create","builderOptions","options","parse","wrapLogger","parser","Parser","override","Override","configDirs","loader","Loader","personaSection","createSection","title","contextSection","instructionSection","contentSection","instance","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","loadDirectories","directories","debug","sections","load","loadContext","contextDirectories","context","add","loadContent","contentDirectories","content","loadPath","contentPath","defaultPath","path","join","section","parseFile","overrideSection","customize","addPersonaPath","persona","addContextPath","addInstructionPath","instruction","addContentPath","addContent","parsedContentSection","addContext","parsedContextSection","build","prompt","createPrompt","contexts","instructions","contents"],"mappings":";;;;;;;;;;;;;AAOA,MAAMA,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;AAC1BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;AACnCC,IAAAA,QAAAA,EAAUP,EAAEQ,MAAM,EAAA;IAClBC,aAAAA,EAAeT,CAAAA,CAA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B,OAAOS,OAAAA,CAAAA;AACtC,QAAA,MAAMb,iBAAiBF,WAAAA,CAAYC,cAAAA,CAAAA;AACnC,QAAA,MAAM+B,oBAAAA,GAAyC9C,QAAAA,CAAOF,KAAK,CAAU+B,OAAAA,EAASb,cAAAA,CAAAA;AAC9EJ,QAAAA,cAAAA,CAAec,GAAG,CAACoB,oBAAAA,CAAAA;QACnB,OAAOjC,QAAAA;AACX,KAAA;AACAA,IAAAA,QAAAA,CAASgC,UAAU,GAAGA,UAAAA;AAEtB,IAAA,MAAME,UAAAA,GAAa,OACftB,OAAAA,EACAV,cAAAA,GAA0C,EAAE,GAAA;QAE5CjC,MAAAA,CAAOsC,KAAK,CAAC,gBAAA,EAAkB,OAAOK,OAAAA,CAAAA;AACtC,QAAA,MAAMT,iBAAiBF,WAAAA,CAAYC,cAAAA,CAAAA;AACnC,QAAA,MAAMiC,oBAAAA,GAAyChD,QAAAA,CAAOF,KAAK,CAAU2B,OAAAA,EAAST,cAAAA,CAAAA;AAC9EN,QAAAA,cAAAA,CAAegB,GAAG,CAACsB,oBAAAA,CAAAA;QACnB,OAAOnC,QAAAA;AACX,KAAA;AACAA,IAAAA,QAAAA,CAASkC,UAAU,GAAGA,UAAAA;AAEtB,IAAA,MAAME,KAAAA,GAAQ,UAAA;QACVnE,MAAAA,CAAOsC,KAAK,CAAC,iBAAA,EAAmB,EAAC,CAAA;AACjC,QAAA,MAAM8B,SAASC,QAAAA,CAAa;YAAEX,OAAAA,EAASjC,cAAAA;YAAgB6C,QAAAA,EAAU1C,cAAAA;YAAgB2C,YAAAA,EAAc1C,kBAAAA;YAAoB2C,QAAAA,EAAU1C;AAAe,SAAA,CAAA;QAC5I,OAAOsC,MAAAA;AACX,KAAA;AACArC,IAAAA,QAAAA,CAASoC,KAAK,GAAGA,KAAAA;IAEjB,OAAOpC,QAAAA;AACX;;;;"}
1
+ {"version":3,"file":"builder.js","sources":["../src/builder.ts"],"sourcesContent":["import path from \"path\";\nimport { z } from \"zod\";\nimport { ParametersSchema } from \"./items/parameters\";\nimport { SectionOptions, SectionOptionsSchema } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Content, Context, createPrompt, createSection, Instruction, Loader, Override, Parser, Prompt, Section, Weighted } from \"./riotprompt\";\n\nconst OptionSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n basePath: z.string(),\n overridePaths: z.array(z.string()).optional().default([\"./\"]),\n overrides: z.boolean().optional().default(false),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionSchema>;\n\nexport type OptionsParam = Required<Pick<Options, 'basePath'>> & Partial<Omit<Options, 'basePath'>>;\n\nexport interface Instance {\n addPersonaPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContextPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addInstructionPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContentPath(contentPath: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContent(content: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n addContext(context: string, sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n loadContext(contextDirectories: string[], sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n loadContent(contentDirectories: string[], sectionOptions?: Partial<SectionOptions>): Promise<Instance>;\n build(): Promise<Prompt>;\n}\n\nexport const create = (builderOptions: OptionsParam): Instance => {\n const options: Required<Options> = OptionSchema.parse(builderOptions) as Required<Options>;\n\n const logger = wrapLogger(options.logger, 'Builder');\n const parser = Parser.create({ logger });\n const override = Override.create({\n logger, configDirs: options.overridePaths || [\"./\"],\n overrides: options.overrides || false\n });\n const loader = Loader.create({ logger });\n\n const personaSection: Section<Instruction> = createSection({ title: \"Persona\" });\n const contextSection: Section<Context> = createSection({ title: \"Context\" });\n const instructionSection: Section<Instruction> = createSection({ title: \"Instruction\" });\n const contentSection: Section<Content> = createSection({ title: \"Content\" });\n const parameters = options.parameters;\n\n\n const instance: Partial<Instance> = {}\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n const loadDirectories = async <T extends Weighted>(\n directories: string[],\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Section<T>[]> => {\n const currentOptions = loadOptions(sectionOptions);\n logger.debug(\"Loading directories\", directories);\n const sections: Section<T>[] = await loader.load<T>(directories, currentOptions);\n return sections;\n }\n\n const loadContext = async (\n contextDirectories: string[],\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n const currentOptions = loadOptions(sectionOptions);\n logger.debug('Loading context', contextDirectories);\n const context: Section<Context>[] = await loadDirectories<Context>(contextDirectories, currentOptions);\n contextSection.add(context);\n return instance as Instance;\n }\n instance.loadContext = loadContext;\n\n const loadContent = async (\n contentDirectories: string[],\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n const currentOptions = loadOptions(sectionOptions);\n const content: Section<Content>[] = await loadDirectories<Content>(contentDirectories, currentOptions);\n contentSection.add(content);\n return instance as Instance;\n }\n instance.loadContent = loadContent;\n\n const loadPath = async <T extends Weighted>(\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Section<T>> => {\n const currentOptions = loadOptions(sectionOptions);\n const defaultPath = path.join(options.basePath as string, contentPath);\n const section: Section<T> = await parser.parseFile<T>(defaultPath, currentOptions);\n const overrideSection = await override.customize<T>(contentPath, section, currentOptions);\n return overrideSection;\n }\n\n const addPersonaPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n const currentOptions = loadOptions(sectionOptions);\n const persona: Section<Instruction> = await loadPath<Instruction>(contentPath, currentOptions);\n personaSection.add(persona);\n return instance as Instance;\n }\n instance.addPersonaPath = addPersonaPath;\n\n const addContextPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding context path\", contentPath);\n const currentOptions = loadOptions(sectionOptions);\n const context: Section<Context> = await loadPath<Context>(contentPath, currentOptions);\n contextSection.add(context);\n return instance as Instance;\n }\n instance.addContextPath = addContextPath;\n\n const addInstructionPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding instruction path\", contentPath);\n const currentOptions = loadOptions(sectionOptions);\n const instruction: Section<Instruction> = await loadPath<Instruction>(contentPath, currentOptions);\n instructionSection.add(instruction);\n return instance as Instance;\n }\n instance.addInstructionPath = addInstructionPath;\n\n const addContentPath = async (\n contentPath: string,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding content path\", contentPath);\n const currentOptions = loadOptions(sectionOptions);\n const content: Section<Content> = await loadPath<Content>(contentPath, currentOptions);\n contentSection.add(content);\n return instance as Instance;\n }\n instance.addContentPath = addContentPath;\n\n const addContent = async (\n content: string | Buffer,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding content\", typeof content);\n const currentOptions = loadOptions(sectionOptions);\n const parsedContentSection: Section<Content> = await parser.parse<Content>(content, currentOptions);\n contentSection.add(parsedContentSection);\n return instance as Instance;\n }\n instance.addContent = addContent;\n\n const addContext = async (\n context: string | Buffer,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Instance> => {\n logger.debug(\"Adding context\", typeof context);\n const currentOptions = loadOptions(sectionOptions);\n const parsedContextSection: Section<Context> = await parser.parse<Context>(context, currentOptions);\n contextSection.add(parsedContextSection);\n return instance as Instance;\n }\n instance.addContext = addContext;\n\n const build = async () => {\n logger.debug(\"Building prompt\", {});\n const prompt = createPrompt({ persona: personaSection, contexts: contextSection, instructions: instructionSection, contents: contentSection });\n return prompt;\n }\n instance.build = build;\n\n return instance as Instance;\n}\n"],"names":["OptionSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","basePath","string","overridePaths","array","overrides","boolean","parameters","ParametersSchema","create","builderOptions","options","parse","wrapLogger","parser","Parser","override","Override","configDirs","loader","Loader","personaSection","createSection","title","contextSection","instructionSection","contentSection","instance","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","loadDirectories","directories","debug","sections","load","loadContext","contextDirectories","context","add","loadContent","contentDirectories","content","loadPath","contentPath","defaultPath","path","join","section","parseFile","overrideSection","customize","addPersonaPath","persona","addContextPath","addInstructionPath","instruction","addContentPath","addContent","parsedContentSection","addContext","parsedContextSection","build","prompt","createPrompt","contexts","instructions","contents"],"mappings":";;;;;;;;;;;;;AAOA,MAAMA,YAAAA,GAAeC,CAAAA,CAAEC,MAAM,CAAC;AAC1BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;AACnCC,IAAAA,QAAAA,EAAUP,EAAEQ,MAAM,EAAA;IAClBC,aAAAA,EAAeT,CAAAA,CAAEU,KAAK,CAACV,CAAAA,CAAEQ,MAAM,EAAA,CAAA,CAAIJ,QAAQ,EAAA,CAAGC,OAAO,CAAC;AAAC,QAAA;AAAK,KAAA,CAAA;AAC5DM,IAAAA,SAAAA,EAAWX,EAAEY,OAAO,EAAA,CAAGR,QAAQ,EAAA,CAAGC,OAAO,CAAC,KAAA,CAAA;AAC1CQ,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBV,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAkBO,MAAMU,SAAS,CAACC,cAAAA,GAAAA;IACnB,MAAMC,OAAAA,GAA6BlB,YAAAA,CAAamB,KAAK,CAACF,cAAAA,CAAAA;AAEtD,IAAA,MAAMd,MAAAA,GAASiB,UAAAA,CAAWF,OAAAA,CAAQf,MAAM,EAAE,SAAA,CAAA;IAC1C,MAAMkB,QAAAA,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MT,iBAAiBF,WAAAA,CAAYC,cAAAA,CAAAA;AACnC,QAAA,MAAMiC,oBAAAA,GAAyC,MAAMhD,QAAAA,CAAOF,KAAK,CAAU2B,OAAAA,EAAST,cAAAA,CAAAA;AACpFN,QAAAA,cAAAA,CAAegB,GAAG,CAACsB,oBAAAA,CAAAA;QACnB,OAAOnC,QAAAA;AACX,IAAA,CAAA;AACAA,IAAAA,QAAAA,CAASkC,UAAU,GAAGA,UAAAA;AAEtB,IAAA,MAAME,KAAAA,GAAQ,UAAA;QACVnE,MAAAA,CAAOsC,KAAK,CAAC,iBAAA,EAAmB,EAAC,CAAA;AACjC,QAAA,MAAM8B,SAASC,QAAAA,CAAa;YAAEX,OAAAA,EAASjC,cAAAA;YAAgB6C,QAAAA,EAAU1C,cAAAA;YAAgB2C,YAAAA,EAAc1C,kBAAAA;YAAoB2C,QAAAA,EAAU1C;AAAe,SAAA,CAAA;QAC5I,OAAOsC,MAAAA;AACX,IAAA,CAAA;AACArC,IAAAA,QAAAA,CAASoC,KAAK,GAAGA,KAAAA;IAEjB,OAAOpC,QAAAA;AACX;;;;"}
package/dist/chat.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"chat.js","sources":["../src/chat.ts"],"sourcesContent":["import { DEFAULT_PERSONA_ROLE } from \"./constants\";\n\nexport type Role = \"user\" | \"assistant\" | \"system\" | \"developer\";\n\nexport type Model = \"gpt-4o\" | \"gpt-4o-mini\" | \"o1-preview\" | \"o1-mini\" | \"o1\" | \"o3-mini\" | \"o1-pro\";\n\nexport interface Message {\n role: Role;\n content: string | string[];\n name?: string;\n}\n\nexport interface Request {\n messages: Message[];\n model: Model;\n\n addMessage(message: Message): void;\n}\n\nexport const getPersonaRole = (model: Model): Role => {\n if (model === \"gpt-4o\" || model === \"gpt-4o-mini\") {\n return \"system\";\n }\n return DEFAULT_PERSONA_ROLE;\n}\n\nexport const createRequest = (model: Model): Request => {\n const messages: Message[] = [];\n\n return {\n model,\n messages,\n addMessage: (message: Message) => {\n messages.push(message);\n }\n }\n}\n"],"names":["getPersonaRole","model","DEFAULT_PERSONA_ROLE","createRequest","messages","addMessage","message","push"],"mappings":";;AAmBO,MAAMA,iBAAiB,CAACC,KAAAA,GAAAA;IAC3B,IAAIA,KAAAA,KAAU,QAAA,IAAYA,KAAAA,KAAU,aAAA,EAAe;QAC/C,OAAO,QAAA;AACX;IACA,OAAOC,oBAAAA;AACX;AAEO,MAAMC,gBAAgB,CAACF,KAAAA,GAAAA;AAC1B,IAAA,MAAMG,WAAsB,EAAE;IAE9B,OAAO;AACHH,QAAAA,KAAAA;AACAG,QAAAA,QAAAA;AACAC,QAAAA,UAAAA,EAAY,CAACC,OAAAA,GAAAA;AACTF,YAAAA,QAAAA,CAASG,IAAI,CAACD,OAAAA,CAAAA;AAClB;AACJ,KAAA;AACJ;;;;"}
1
+ {"version":3,"file":"chat.js","sources":["../src/chat.ts"],"sourcesContent":["import { DEFAULT_PERSONA_ROLE } from \"./constants\";\n\nexport type Role = \"user\" | \"assistant\" | \"system\" | \"developer\";\n\nexport type Model = \"gpt-4o\" | \"gpt-4o-mini\" | \"o1-preview\" | \"o1-mini\" | \"o1\" | \"o3-mini\" | \"o1-pro\";\n\nexport interface Message {\n role: Role;\n content: string | string[];\n name?: string;\n}\n\nexport interface Request {\n messages: Message[];\n model: Model;\n\n addMessage(message: Message): void;\n}\n\nexport const getPersonaRole = (model: Model): Role => {\n if (model === \"gpt-4o\" || model === \"gpt-4o-mini\") {\n return \"system\";\n }\n return DEFAULT_PERSONA_ROLE;\n}\n\nexport const createRequest = (model: Model): Request => {\n const messages: Message[] = [];\n\n return {\n model,\n messages,\n addMessage: (message: Message) => {\n messages.push(message);\n }\n }\n}\n"],"names":["getPersonaRole","model","DEFAULT_PERSONA_ROLE","createRequest","messages","addMessage","message","push"],"mappings":";;AAmBO,MAAMA,iBAAiB,CAACC,KAAAA,GAAAA;IAC3B,IAAIA,KAAAA,KAAU,QAAA,IAAYA,KAAAA,KAAU,aAAA,EAAe;QAC/C,OAAO,QAAA;AACX,IAAA;IACA,OAAOC,oBAAAA;AACX;AAEO,MAAMC,gBAAgB,CAACF,KAAAA,GAAAA;AAC1B,IAAA,MAAMG,WAAsB,EAAE;IAE9B,OAAO;AACHH,QAAAA,KAAAA;AACAG,QAAAA,QAAAA;AACAC,QAAAA,UAAAA,EAAY,CAACC,OAAAA,GAAAA;AACTF,YAAAA,QAAAA,CAASG,IAAI,CAACD,OAAAA,CAAAA;AAClB,QAAA;AACJ,KAAA;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"formatter.js","sources":["../src/formatter.ts"],"sourcesContent":["import { Instruction } from \"riotprompt\";\nimport { z } from \"zod\";\nimport * as Chat from \"./chat\";\nimport { getPersonaRole, Message, Model } from \"./chat\";\nimport { DEFAULT_FORMAT_OPTIONS } from \"./constants\";\nimport { Section } from \"./items/section\";\nimport { Weighted } from \"./items/weighted\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Prompt } from \"./prompt\";\nimport { clean, stringifyJSON } from \"./util/general\";\n\nexport const SectionSeparatorSchema = z.enum([\"tag\", \"markdown\"]);\nexport const SectionTitlePropertySchema = z.enum([\"title\", \"name\"]);\n\nexport type SectionSeparator = z.infer<typeof SectionSeparatorSchema>;\nexport type SectionTitleProperty = z.infer<typeof SectionTitlePropertySchema>;\n\n\nexport const FormatOptionsSchema = z.object({\n sectionSeparator: SectionSeparatorSchema,\n sectionIndentation: z.boolean(),\n sectionTitleProperty: SectionTitlePropertySchema,\n sectionTitlePrefix: z.string().optional(),\n sectionTitleSeparator: z.string().optional(),\n sectionDepth: z.number().default(1),\n});\n\nexport type FormatOptions = z.infer<typeof FormatOptionsSchema>;\n\n\nexport const OptionSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n formatOptions: FormatOptionsSchema.partial().optional().default(DEFAULT_FORMAT_OPTIONS),\n});\n\nexport type Options = z.infer<typeof OptionSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n formatPersona: (model: Model, persona: Section<Instruction>) => Message;\n format: <T extends Weighted>(weightedText: T | Section<T>, sectionDepth?: number) => string;\n formatArray: <T extends Weighted>(items: (T | Section<T>)[], sectionDepth?: number) => string;\n formatPrompt: (model: Model, prompt: Prompt) => Chat.Request;\n}\n\n// Type guard to check if an object is a Section\nfunction isSection<T extends Weighted>(obj: T | Section<T>): obj is Section<T> {\n return obj && typeof obj === 'object' && 'items' in obj && Array.isArray((obj as Section<T>).items);\n}\n\n// Type guard to check if an object is a Section\nfunction isWeighted<T extends Weighted>(obj: T | Section<T>): obj is T {\n return obj && typeof obj === 'object' && 'text' in obj;\n}\n\n\nexport const create = (formatterOptions?: OptionsParam): Instance => {\n const options: Required<Options> = OptionSchema.parse(formatterOptions || {}) as Required<Options>;\n\n const logger = wrapLogger(options.logger, 'Formatter');\n\n let formatOptions: FormatOptions = DEFAULT_FORMAT_OPTIONS;\n if (options?.formatOptions) {\n formatOptions = {\n ...formatOptions,\n ...clean(options.formatOptions),\n };\n }\n\n const formatPersona = (model: Model, persona: Section<Instruction>): Message => {\n logger.silly(`Formatting persona`);\n if (persona) {\n const formattedPersona = formatSection(persona);\n\n return {\n role: getPersonaRole(model),\n content: `${formattedPersona}`,\n }\n } else {\n throw new Error(\"Persona is required\");\n }\n }\n\n const format = <T extends Weighted>(\n item: T | Section<T>,\n sectionDepth?: number,\n ): string => {\n logger.silly(`Formatting ${isSection(item) ? \"section\" : \"item\"} Item: %s`, stringifyJSON(item));\n const currentSectionDepth = sectionDepth ?? formatOptions.sectionDepth;\n logger.silly(`\\t\\tCurrent section depth: ${currentSectionDepth}`);\n\n let result: string = \"\";\n if (isSection(item)) {\n result = formatSection(item, currentSectionDepth + 1);\n } else if (isWeighted(item)) {\n result = item.text;\n } else {\n //If the item is neither a section nor a weighted item, it is empty.\n result = '';\n }\n return result;\n }\n\n const formatSection = <T extends Weighted>(section: Section<T>, sectionDepth?: number): string => {\n logger.silly(`Formatting section`);\n const currentSectionDepth = sectionDepth ?? formatOptions.sectionDepth;\n logger.silly(`\\t\\tCurrent section depth: ${currentSectionDepth}`);\n\n if (section) {\n const formattedItems = section.items.map(item => format(item, currentSectionDepth)).join(\"\\n\\n\");\n\n if (formatOptions.sectionSeparator === \"tag\") {\n return `<${section.title ?? \"section\"}>\\n${formattedItems}\\n</${section.title ?? \"section\"}>`;\n } else {\n // Default depth to 1 if not provided, resulting in H2 (##) matching the test case.\n const headingLevel = currentSectionDepth;\n const hashes = '#'.repeat(headingLevel);\n logger.silly(`\\t\\tHeading level: ${headingLevel}`);\n logger.silly(`\\t\\tSection title: ${section.title}`);\n return `${hashes} ${formatOptions.sectionTitlePrefix ? `${formatOptions.sectionTitlePrefix} ${formatOptions.sectionTitleSeparator} ` : \"\"}${section.title}\\n\\n${formattedItems}`;\n }\n } else {\n return '';\n }\n }\n\n // Helper function to format arrays of items or sections\n const formatArray = <T extends Weighted>(\n items: (T | Section<T>)[],\n sectionDepth?: number\n ): string => {\n logger.silly(`Formatting array`);\n const currentSectionDepth = sectionDepth ?? formatOptions.sectionDepth;\n return items.map(item => format(item, currentSectionDepth)).join(\"\\n\\n\");\n }\n\n const formatPrompt = (model: Model, prompt: Prompt): Chat.Request => {\n logger.silly('Formatting prompt');\n const chatRequest: Chat.Request = Chat.createRequest(model);\n\n if (prompt.persona) {\n [prompt.persona].forEach((persona: Section<Instruction>) => {\n chatRequest.addMessage(formatPersona(model, persona));\n });\n }\n\n let formattedAreas: string = formatSection(prompt.instructions) + '\\n\\n';\n\n if (prompt.contents) {\n formattedAreas += formatSection(prompt.contents) + '\\n\\n';\n }\n\n if (prompt.contexts) {\n formattedAreas += formatSection(prompt.contexts) + '\\n\\n';\n }\n\n chatRequest.addMessage({\n role: \"user\",\n content: formattedAreas,\n });\n\n return chatRequest;\n }\n\n return {\n formatPersona,\n format,\n formatPrompt,\n formatArray,\n }\n}\n"],"names":["SectionSeparatorSchema","z","enum","SectionTitlePropertySchema","FormatOptionsSchema","object","sectionSeparator","sectionIndentation","boolean","sectionTitleProperty","sectionTitlePrefix","string","optional","sectionTitleSeparator","sectionDepth","number","default","OptionSchema","logger","any","DEFAULT_LOGGER","formatOptions","partial","DEFAULT_FORMAT_OPTIONS","isSection","obj","Array","isArray","items","isWeighted","create","formatterOptions","options","parse","wrapLogger","clean","formatPersona","model","persona","silly","formattedPersona","formatSection","role","getPersonaRole","content","Error","format","item","stringifyJSON","currentSectionDepth","result","text","section","formattedItems","map","join","title","headingLevel","hashes","repeat","formatArray","formatPrompt","prompt","chatRequest","Chat","forEach","addMessage","formattedAreas","instructions","contents","contexts"],"mappings":";;;;;;AAWO,MAAMA,sBAAAA,GAAyBC,CAAAA,CAAEC,IAAI,CAAC;AAAC,IAAA,KAAA;AAAO,IAAA;CAAW;AACzD,MAAMC,0BAAAA,GAA6BF,CAAAA,CAAEC,IAAI,CAAC;AAAC,IAAA,OAAA;AAAS,IAAA;CAAO;AAM3D,MAAME,mBAAAA,GAAsBH,CAAAA,CAAEI,MAAM,CAAC;IACxCC,gBAAAA,EAAkBN,sBAAAA;AAClBO,IAAAA,kBAAAA,EAAoBN,EAAEO,OAAO,EAAA;IAC7BC,oBAAAA,EAAsBN,0BAAAA;IACtBO,kBAAAA,EAAoBT,CAAAA,CAAEU,MAAM,EAAA,CAAGC,QAAQ,EAAA;IACvCC,qBAAAA,EAAuBZ,CAAAA,CAAEU,MAAM,EAAA,CAAGC,QAAQ,EAAA;AAC1CE,IAAAA,YAAAA,EAAcb,CAAAA,CAAEc,MAAM,EAAA,CAAGC,OAAO,CAAC,CAAA;AACrC,CAAA;AAKO,MAAMC,YAAAA,GAAehB,CAAAA,CAAEI,MAAM,CAAC;AACjCa,IAAAA,MAAAA,EAAQjB,EAAEkB,GAAG,EAAA,CAAGP,QAAQ,EAAA,CAAGI,OAAO,CAACI,cAAAA,CAAAA;AACnCC,IAAAA,aAAAA,EAAejB,oBAAoBkB,OAAO,EAAA,CAAGV,QAAQ,EAAA,CAA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A,EAASuB;AACb,SAAA,CAAA;QAEA,OAAOJ,WAAAA;AACX,KAAA;IAEA,OAAO;AACH3B,QAAAA,aAAAA;AACAU,QAAAA,MAAAA;AACAe,QAAAA,YAAAA;AACAD,QAAAA;AACJ,KAAA;AACJ;;;;"}
1
+ {"version":3,"file":"formatter.js","sources":["../src/formatter.ts"],"sourcesContent":["import { Instruction } from \"riotprompt\";\nimport { z } from \"zod\";\nimport * as Chat from \"./chat\";\nimport { getPersonaRole, Message, Model } from \"./chat\";\nimport { DEFAULT_FORMAT_OPTIONS } from \"./constants\";\nimport { Section } from \"./items/section\";\nimport { Weighted } from \"./items/weighted\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Prompt } from \"./prompt\";\nimport { clean, stringifyJSON } from \"./util/general\";\n\nexport const SectionSeparatorSchema = z.enum([\"tag\", \"markdown\"]);\nexport const SectionTitlePropertySchema = z.enum([\"title\", \"name\"]);\n\nexport type SectionSeparator = z.infer<typeof SectionSeparatorSchema>;\nexport type SectionTitleProperty = z.infer<typeof SectionTitlePropertySchema>;\n\n\nexport const FormatOptionsSchema = z.object({\n sectionSeparator: SectionSeparatorSchema,\n sectionIndentation: z.boolean(),\n sectionTitleProperty: SectionTitlePropertySchema,\n sectionTitlePrefix: z.string().optional(),\n sectionTitleSeparator: z.string().optional(),\n sectionDepth: z.number().default(1),\n});\n\nexport type FormatOptions = z.infer<typeof FormatOptionsSchema>;\n\n\nexport const OptionSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n formatOptions: FormatOptionsSchema.partial().optional().default(DEFAULT_FORMAT_OPTIONS),\n});\n\nexport type Options = z.infer<typeof OptionSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n formatPersona: (model: Model, persona: Section<Instruction>) => Message;\n format: <T extends Weighted>(weightedText: T | Section<T>, sectionDepth?: number) => string;\n formatArray: <T extends Weighted>(items: (T | Section<T>)[], sectionDepth?: number) => string;\n formatPrompt: (model: Model, prompt: Prompt) => Chat.Request;\n}\n\n// Type guard to check if an object is a Section\nfunction isSection<T extends Weighted>(obj: T | Section<T>): obj is Section<T> {\n return obj && typeof obj === 'object' && 'items' in obj && Array.isArray((obj as Section<T>).items);\n}\n\n// Type guard to check if an object is a Section\nfunction isWeighted<T extends Weighted>(obj: T | Section<T>): obj is T {\n return obj && typeof obj === 'object' && 'text' in obj;\n}\n\n\nexport const create = (formatterOptions?: OptionsParam): Instance => {\n const options: Required<Options> = OptionSchema.parse(formatterOptions || {}) as Required<Options>;\n\n const logger = wrapLogger(options.logger, 'Formatter');\n\n let formatOptions: FormatOptions = DEFAULT_FORMAT_OPTIONS;\n if (options?.formatOptions) {\n formatOptions = {\n ...formatOptions,\n ...clean(options.formatOptions),\n };\n }\n\n const formatPersona = (model: Model, persona: Section<Instruction>): Message => {\n logger.silly(`Formatting persona`);\n if (persona) {\n const formattedPersona = formatSection(persona);\n\n return {\n role: getPersonaRole(model),\n content: `${formattedPersona}`,\n }\n } else {\n throw new Error(\"Persona is required\");\n }\n }\n\n const format = <T extends Weighted>(\n item: T | Section<T>,\n sectionDepth?: number,\n ): string => {\n logger.silly(`Formatting ${isSection(item) ? \"section\" : \"item\"} Item: %s`, stringifyJSON(item));\n const currentSectionDepth = sectionDepth ?? formatOptions.sectionDepth;\n logger.silly(`\\t\\tCurrent section depth: ${currentSectionDepth}`);\n\n let result: string = \"\";\n if (isSection(item)) {\n result = formatSection(item, currentSectionDepth + 1);\n } else if (isWeighted(item)) {\n result = item.text;\n } else {\n //If the item is neither a section nor a weighted item, it is empty.\n result = '';\n }\n return result;\n }\n\n const formatSection = <T extends Weighted>(section: Section<T>, sectionDepth?: number): string => {\n logger.silly(`Formatting section`);\n const currentSectionDepth = sectionDepth ?? formatOptions.sectionDepth;\n logger.silly(`\\t\\tCurrent section depth: ${currentSectionDepth}`);\n\n if (section) {\n const formattedItems = section.items.map(item => format(item, currentSectionDepth)).join(\"\\n\\n\");\n\n if (formatOptions.sectionSeparator === \"tag\") {\n return `<${section.title ?? \"section\"}>\\n${formattedItems}\\n</${section.title ?? \"section\"}>`;\n } else {\n // Default depth to 1 if not provided, resulting in H2 (##) matching the test case.\n const headingLevel = currentSectionDepth;\n const hashes = '#'.repeat(headingLevel);\n logger.silly(`\\t\\tHeading level: ${headingLevel}`);\n logger.silly(`\\t\\tSection title: ${section.title}`);\n return `${hashes} ${formatOptions.sectionTitlePrefix ? `${formatOptions.sectionTitlePrefix} ${formatOptions.sectionTitleSeparator} ` : \"\"}${section.title}\\n\\n${formattedItems}`;\n }\n } else {\n return '';\n }\n }\n\n // Helper function to format arrays of items or sections\n const formatArray = <T extends Weighted>(\n items: (T | Section<T>)[],\n sectionDepth?: number\n ): string => {\n logger.silly(`Formatting array`);\n const currentSectionDepth = sectionDepth ?? formatOptions.sectionDepth;\n return items.map(item => format(item, currentSectionDepth)).join(\"\\n\\n\");\n }\n\n const formatPrompt = (model: Model, prompt: Prompt): Chat.Request => {\n logger.silly('Formatting prompt');\n const chatRequest: Chat.Request = Chat.createRequest(model);\n\n if (prompt.persona) {\n [prompt.persona].forEach((persona: Section<Instruction>) => {\n chatRequest.addMessage(formatPersona(model, persona));\n });\n }\n\n let formattedAreas: string = formatSection(prompt.instructions) + '\\n\\n';\n\n if (prompt.contents) {\n formattedAreas += formatSection(prompt.contents) + '\\n\\n';\n }\n\n if (prompt.contexts) {\n formattedAreas += formatSection(prompt.contexts) + '\\n\\n';\n }\n\n chatRequest.addMessage({\n role: \"user\",\n content: formattedAreas,\n });\n\n return chatRequest;\n }\n\n return {\n formatPersona,\n format,\n formatPrompt,\n formatArray,\n }\n}\n"],"names":["SectionSeparatorSchema","z","enum","SectionTitlePropertySchema","FormatOptionsSchema","object","sectionSeparator","sectionIndentation","boolean","sectionTitleProperty","sectionTitlePrefix","string","optional","sectionTitleSeparator","sectionDepth","number","default","OptionSchema","logger","any","DEFAULT_LOGGER","formatOptions","partial","DEFAULT_FORMAT_OPTIONS","isSection","obj","Array","isArray","items","isWeighted","create","formatterOptions","options","parse","wrapLogger","clean","formatPersona","model","persona","silly","formattedPersona","formatSection","role","getPersonaRole","content","Error","format","item","stringifyJSON","currentSectionDepth","result","text","section","formattedItems","map","join","title","headingLevel","hashes","repeat","formatArray","formatPrompt","prompt","chatRequest","Chat","forEach","addMessage","formattedAreas","instructions","contents","contexts"],"mappings":";;;;;;AAWO,MAAMA,sBAAAA,GAAyBC,CAAAA,CAAEC,IAAI,CAAC;AAAC,IAAA,KAAA;AAAO,IAAA;CAAW;AACzD,MAAMC,0BAAAA,GAA6BF,CAAAA,CAAEC,IAAI,CAAC;AAAC,IAAA,OAAA;AAAS,IAAA;CAAO;AAM3D,MAAME,mBAAAA,GAAsBH,CAAAA,CAAEI,MAAM,CAAC;IACxCC,gBAAAA,EAAkBN,sBAAAA;AAClBO,IAAAA,kBAAAA,EAAoBN,EAAEO,OAAO,EAAA;IAC7BC,oBAAAA,EAAsBN,0BAAAA;IACtBO,kBAAAA,EAAoBT,CAAAA,CAAEU,MAAM,EAAA,CAAGC,QAAQ,EAAA;IACvCC,qBAAAA,EAAuBZ,CAAAA,CAAEU,MAAM,EAAA,CAAGC,QAAQ,EAAA;AAC1CE,IAAAA,YAAAA,EAAcb,CAAAA,CAAEc,MAAM,EAAA,CAAGC,OAAO,CAAC,CAAA;AACrC,CAAA;AAKO,MAAMC,YAAAA,GAAehB,CAAAA,CAAEI,MAAM,CAAC;AACjCa,IAAAA,MAAAA,EAAQjB,EAAEkB,GAAG,EAAA,CAAGP,QAAQ,EAAA,CAAGI,OAAO,CAACI,cAAAA,CAAAA;AACnCC,IAAAA,aAAAA,EAAejB,oBAAoBkB,OAAO,EAAA,CAAGV,QAAQ,EAAA,CAAGI,OAAO,CAACO,sBAAAA;AACpE,CAAA;AAaA;AACA,SAASC,UAA8BC,GAAmB,EAAA;IACtD,OAAOA,GAAAA,IAAO,OAAOA,GAAAA,KAAQ,QAAA,IAAY,OAAA,IAAWA,GAAAA,IAAOC,KAAAA,CA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;IAEA,OAAO;AACH3B,QAAAA,aAAAA;AACAU,QAAAA,MAAAA;AACAe,QAAAA,YAAAA;AACAD,QAAAA;AACJ,KAAA;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"parameters.js","sources":["../../src/items/parameters.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport const ParametersSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number(), z.boolean()]))]));\n\nexport type Parameters = z.infer<typeof ParametersSchema>;\n\nexport const create = (parameters: Parameters): Parameters => {\n return parameters;\n}\n\nexport const apply = (text: string, parameters?: Parameters): string => {\n if (!parameters) {\n return text;\n }\n\n // First, trim parameters keys to handle whitespace in placeholder names\n const trimmedParams: Record<string, any> = {};\n Object.keys(parameters).forEach(key => {\n trimmedParams[key.trim()] = parameters[key];\n });\n\n // Process all placeholders, preserving ones that don't have matching parameters\n return text.replace(/\\{\\{([^{}]+)\\}\\}/g, (match, p1) => {\n const paramKey = p1.trim();\n const parameter = trimmedParams[paramKey];\n\n if (parameter === undefined) {\n // Preserve the original placeholder if parameter doesn't exist\n return match;\n } else if (typeof parameter === 'string') {\n return parameter;\n } else if (typeof parameter === 'number') {\n return parameter.toString();\n } else if (typeof parameter === 'boolean') {\n return parameter.toString();\n } else if (Array.isArray(parameter)) {\n return parameter.join(', ');\n } else {\n return match;\n }\n });\n}"],"names":["ParametersSchema","z","record","string","union","number","boolean","array","create","parameters","apply","text","trimmedParams","Object","keys","forEach","key","trim","replace","match","p1","paramKey","parameter","undefined","toString","Array","isArray","join"],"mappings":";;AAEO,MAAMA,gBAAAA,GAAmBC,CAAAA,CAAEC,MAAM,CAACD,EAAEE,MAAM,EAAA,EAAIF,CAAAA,CAAEG,KAAK,CAAC;AAACH,IAAAA,CAAAA,CAAEE,MAAM,EAAA;AAAIF,IAAAA,CAAAA,CAAEI,MAAM,EAAA;AAAIJ,IAAAA,CAAAA,CAAEK,OAAO,EAAA;AAAIL,IAAAA,CA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A,CAAUK,IAAI,CAAC,IAAA,CAAA;SAC1B,MAAO;YACH,OAAOR,KAAAA;AACX;AACJ,KAAA,CAAA;AACJ;;;;"}
1
+ {"version":3,"file":"parameters.js","sources":["../../src/items/parameters.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport const ParametersSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number(), z.boolean()]))]));\n\nexport type Parameters = z.infer<typeof ParametersSchema>;\n\nexport const create = (parameters: Parameters): Parameters => {\n return parameters;\n}\n\nexport const apply = (text: string, parameters?: Parameters): string => {\n if (!parameters) {\n return text;\n }\n\n // First, trim parameters keys to handle whitespace in placeholder names\n const trimmedParams: Record<string, any> = {};\n Object.keys(parameters).forEach(key => {\n trimmedParams[key.trim()] = parameters[key];\n });\n\n // Process all placeholders, preserving ones that don't have matching parameters\n return text.replace(/\\{\\{([^{}]+)\\}\\}/g, (match, p1) => {\n const paramKey = p1.trim();\n const parameter = trimmedParams[paramKey];\n\n if (parameter === undefined) {\n // Preserve the original placeholder if parameter doesn't exist\n return match;\n } else if (typeof parameter === 'string') {\n return parameter;\n } else if (typeof parameter === 'number') {\n return parameter.toString();\n } else if (typeof parameter === 'boolean') {\n return parameter.toString();\n } else if (Array.isArray(parameter)) {\n return parameter.join(', ');\n } else {\n return match;\n }\n });\n}"],"names":["ParametersSchema","z","record","string","union","number","boolean","array","create","parameters","apply","text","trimmedParams","Object","keys","forEach","key","trim","replace","match","p1","paramKey","parameter","undefined","toString","Array","isArray","join"],"mappings":";;AAEO,MAAMA,gBAAAA,GAAmBC,CAAAA,CAAEC,MAAM,CAACD,EAAEE,MAAM,EAAA,EAAIF,CAAAA,CAAEG,KAAK,CAAC;AAACH,IAAAA,CAAAA,CAAEE,MAAM,EAAA;AAAIF,IAAAA,CAAAA,CAAEI,MAAM,EAAA;AAAIJ,IAAAA,CAAAA,CAAEK,OAAO,EAAA;AAAIL,IAAAA,CAAAA,CAAEM,KAAK,CAACN,C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AAOA,SAAAA,CAAUK,IAAI,CAAC,IAAA,CAAA;QAC1B,CAAA,MAAO;YACH,OAAOR,KAAAA;AACX,QAAA;AACJ,IAAA,CAAA,CAAA;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"section.js","sources":["../../src/items/section.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { ParametersSchema } from \"./parameters\";\nimport { Weighted, WeightedOptions, WeightedOptionsSchema, create as createWeighted } from \"./weighted\";\n\nexport interface Section<T extends Weighted> {\n title?: string;\n items: (T | Section<T>)[];\n weight?: number;\n add: (\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n append: (\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n prepend: (\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n insert: (\n index: number,\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n replace: (\n index: number,\n item: T | Section<T> | string,\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n remove: (index: number) => Section<T>;\n}\n\nexport const SectionOptionsSchema = z.object({\n title: z.string().optional(),\n weight: z.number().optional(),\n itemWeight: z.number().optional(),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type SectionOptions = z.infer<typeof SectionOptionsSchema>;\n\nexport const isSection = (object: any): boolean => {\n return object !== undefined && object != null && typeof object === 'object' && 'items' in object;\n}\n\nexport const convertToSection = (\n object: any,\n options: Partial<SectionOptions> = {}\n): Section<Weighted> => {\n const sectionOptions = SectionOptionsSchema.parse(options);\n\n const weightedOptions = WeightedOptionsSchema.parse({\n ...sectionOptions,\n weight: sectionOptions.itemWeight,\n });\n\n if (isSection(object)) {\n const section = create({ ...sectionOptions, title: object.title });\n object.items.forEach((item: any) => {\n if (isSection(item)) {\n section.append(convertToSection(item, sectionOptions));\n } else {\n section.append(createWeighted(item.text, weightedOptions));\n }\n });\n return section;\n } else {\n throw new Error('Object is not a section');\n }\n}\n\nexport const create = <T extends Weighted>(\n options: Partial<SectionOptions> = {}\n): Section<T> => {\n const items: (T | Section<T>)[] = [];\n const sectionOptions = SectionOptionsSchema.parse(options);\n\n const sectionItemOptions = WeightedOptionsSchema.parse({\n ...sectionOptions,\n weight: sectionOptions.itemWeight,\n });\n\n const append = (item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (Array.isArray(item)) {\n item.forEach((item) => {\n append(item);\n });\n } else {\n if (typeof item === 'string') {\n items.push(createWeighted<T>(item, itemOptions));\n } else {\n items.push(item);\n }\n }\n return section;\n }\n\n const prepend = (item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (Array.isArray(item)) {\n item.forEach((item) => {\n prepend(item);\n });\n } else {\n if (typeof item === 'string') {\n items.unshift(createWeighted<T>(item, itemOptions));\n } else {\n items.unshift(item);\n }\n }\n return section;\n }\n\n const insert = (index: number, item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (Array.isArray(item)) {\n item.forEach((item) => {\n insert(index, item);\n });\n } else {\n if (typeof item === 'string') {\n items.splice(index, 0, createWeighted<T>(item, itemOptions));\n } else {\n items.splice(index, 0, item);\n }\n }\n return section;\n }\n\n const remove = (index: number): Section<T> => {\n items.splice(index, 1);\n return section;\n }\n\n const replace = (index: number, item: T | Section<T> | string, options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (typeof item === 'string') {\n items[index] = createWeighted<T>(item, itemOptions);\n } else {\n items[index] = item;\n }\n return section;\n }\n\n const add = (item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n return append(item, itemOptions);\n }\n\n const section: Section<T> = {\n title: sectionOptions.title,\n items,\n weight: sectionOptions.weight,\n add,\n append,\n prepend,\n insert,\n remove,\n replace,\n }\n\n return section;\n}\n\n\n"],"names":["SectionOptionsSchema","z","object","title","string","optional","weight","number","itemWeight","parameters","ParametersSchema","default","create","options","items","sectionOptions","parse","sectionItemOptions","WeightedOptionsSchema","append","item","itemOptions","Array","isArray","forEach","push","createWeighted","section","prepend","unshift","insert","index","splice","remove","replace","add"],"mappings":";;;;AAiCO,MAAMA,oBAAAA,GAAuBC,CAAAA,CAAEC,MAAM,CAAC;IACzCC,KAAAA,EAAOF,CAAAA,CAAEG,MAAM,EAAA,CAAGC,QAAQ,EAAA;IAC1BC,MAAAA,EAAQL,CAAAA,CAAEM,MAAM,EAAA,CAAGF,QAAQ,EAAA;IAC3BG,UAAAA,EAAYP,CAAAA,CAAEM,MAAM,EAAA,CAAGF,QAAQ,EAAA;AAC/BI,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBL,QAAQ,EAAA,CAAGM,OAAO,CAAC,EAAC;AACrD,CAAA;AAkCO,MAAMC,MAAAA,GAAS,CAClBC,OAAAA,GAAmC,EAAE,GAAA;AAErC,IAAA,MAAMC,QAA4B,EAAE;IACpC,MAAMC,cAAAA,GAAiBf,oBAAAA,CAAqBgB,KAAK,CAACH,OAAAA,CAAAA;IAElD,MAAMI,kBAAAA,GAAqBC,qBAAAA,CAAsBF,KAAK,CAAC;AACnD,QAAA,GAAGD,cAAc;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AAAY,SAAA;QAEtD,IAAI,OAAOD,SAAS,QAAA,EAAU;AAC1BN,YAAAA,KAAK,CAACiB,KAAAA,CAAM,GAAGL,QAAAA,CAAkBN,IAAAA,EAAMC,WAAAA,CAAAA;SAC3C,MAAO;YACHP,KAAK,CAACiB,MAAM,GAAGX,IAAAA;AACnB;QACA,OAAOO,OAAAA;AACX,KAAA;AAEA,IAAA,MAAMQ,GAAAA,GAAM,CAACf,IAAAA,EAA+DP,OAAAA,GAAoC,EAAE,GAAA;QAC9G,IAAIQ,WAAAA,GAA+BH,qBAAAA,CAAsBF,KAAK,CAACH,OAAAA,CAAAA;QAC/DQ,WAAAA,GAAc;AAAE,YAAA,GAAGJ,kBAAkB;AAAE,YAAA,GAAGI;AAAY,SAAA;AAEtD,QAAA,OAAOF,OAAOC,IAAAA,EAAMC,WAAAA,CAAAA;AACxB,KAAA;AAEA,IAAA,MAAMM,OAAAA,GAAsB;AACxBxB,QAAAA,KAAAA,EAAOY,eAAeZ,KAAK;AAC3BW,QAAAA,KAAAA;AACAR,QAAAA,MAAAA,EAAQS,eAAeT,MAAM;AAC7B6B,QAAAA,GAAAA;AACAhB,QAAAA,MAAAA;AACAS,QAAAA,OAAAA;AACAE,QAAAA,MAAAA;AACAG,QAAAA,MAAAA;AACAC,QAAAA;AACJ,KAAA;IAEA,OAAOP,OAAAA;AACX;;;;"}
1
+ {"version":3,"file":"section.js","sources":["../../src/items/section.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { ParametersSchema } from \"./parameters\";\nimport { Weighted, WeightedOptions, WeightedOptionsSchema, create as createWeighted } from \"./weighted\";\n\nexport interface Section<T extends Weighted> {\n title?: string;\n items: (T | Section<T>)[];\n weight?: number;\n add: (\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n append: (\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n prepend: (\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n insert: (\n index: number,\n item: T | T[] | Section<T> | Section<T>[] | string | string[],\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n replace: (\n index: number,\n item: T | Section<T> | string,\n options?: Partial<WeightedOptions>\n ) => Section<T>;\n remove: (index: number) => Section<T>;\n}\n\nexport const SectionOptionsSchema = z.object({\n title: z.string().optional(),\n weight: z.number().optional(),\n itemWeight: z.number().optional(),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type SectionOptions = z.infer<typeof SectionOptionsSchema>;\n\nexport const isSection = (object: any): boolean => {\n return object !== undefined && object != null && typeof object === 'object' && 'items' in object;\n}\n\nexport const convertToSection = (\n object: any,\n options: Partial<SectionOptions> = {}\n): Section<Weighted> => {\n const sectionOptions = SectionOptionsSchema.parse(options);\n\n const weightedOptions = WeightedOptionsSchema.parse({\n ...sectionOptions,\n weight: sectionOptions.itemWeight,\n });\n\n if (isSection(object)) {\n const section = create({ ...sectionOptions, title: object.title });\n object.items.forEach((item: any) => {\n if (isSection(item)) {\n section.append(convertToSection(item, sectionOptions));\n } else {\n section.append(createWeighted(item.text, weightedOptions));\n }\n });\n return section;\n } else {\n throw new Error('Object is not a section');\n }\n}\n\nexport const create = <T extends Weighted>(\n options: Partial<SectionOptions> = {}\n): Section<T> => {\n const items: (T | Section<T>)[] = [];\n const sectionOptions = SectionOptionsSchema.parse(options);\n\n const sectionItemOptions = WeightedOptionsSchema.parse({\n ...sectionOptions,\n weight: sectionOptions.itemWeight,\n });\n\n const append = (item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (Array.isArray(item)) {\n item.forEach((item) => {\n append(item);\n });\n } else {\n if (typeof item === 'string') {\n items.push(createWeighted<T>(item, itemOptions));\n } else {\n items.push(item);\n }\n }\n return section;\n }\n\n const prepend = (item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (Array.isArray(item)) {\n item.forEach((item) => {\n prepend(item);\n });\n } else {\n if (typeof item === 'string') {\n items.unshift(createWeighted<T>(item, itemOptions));\n } else {\n items.unshift(item);\n }\n }\n return section;\n }\n\n const insert = (index: number, item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (Array.isArray(item)) {\n item.forEach((item) => {\n insert(index, item);\n });\n } else {\n if (typeof item === 'string') {\n items.splice(index, 0, createWeighted<T>(item, itemOptions));\n } else {\n items.splice(index, 0, item);\n }\n }\n return section;\n }\n\n const remove = (index: number): Section<T> => {\n items.splice(index, 1);\n return section;\n }\n\n const replace = (index: number, item: T | Section<T> | string, options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n if (typeof item === 'string') {\n items[index] = createWeighted<T>(item, itemOptions);\n } else {\n items[index] = item;\n }\n return section;\n }\n\n const add = (item: T | T[] | Section<T> | Section<T>[] | string | string[], options: Partial<WeightedOptions> = {}): Section<T> => {\n let itemOptions: WeightedOptions = WeightedOptionsSchema.parse(options);\n itemOptions = { ...sectionItemOptions, ...itemOptions };\n\n return append(item, itemOptions);\n }\n\n const section: Section<T> = {\n title: sectionOptions.title,\n items,\n weight: sectionOptions.weight,\n add,\n append,\n prepend,\n insert,\n remove,\n replace,\n }\n\n return section;\n}\n\n\n"],"names":["SectionOptionsSchema","z","object","title","string","optional","weight","number","itemWeight","parameters","ParametersSchema","default","create","options","items","sectionOptions","parse","sectionItemOptions","WeightedOptionsSchema","append","item","itemOptions","Array","isArray","forEach","push","createWeighted","section","prepend","unshift","insert","index","splice","remove","replace","add"],"mappings":";;;;AAiCO,MAAMA,oBAAAA,GAAuBC,CAAAA,CAAEC,MAAM,CAAC;IACzCC,KAAAA,EAAOF,CAAAA,CAAEG,MAAM,EAAA,CAAGC,QAAQ,EAAA;IAC1BC,MAAAA,EAAQL,CAAAA,CAAEM,MAAM,EAAA,CAAGF,QAAQ,EAAA;IAC3BG,UAAAA,EAAYP,CAAAA,CAAEM,MAAM,EAAA,CAAGF,QAAQ,EAAA;AAC/BI,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBL,QAAQ,EAAA,CAAGM,OAAO,CAAC,EAAC;AACrD,CAAA;AAkCO,MAAMC,MAAAA,GAAS,CAClBC,OAAAA,GAAmC,EAAE,GAAA;AAErC,IAAA,MAAMC,QAA4B,EAAE;IACpC,MAAMC,cAAAA,GAAiBf,oBAAAA,CAAqBgB,KAAK,CAACH,OAAAA,CAAAA;IAElD,MAAMI,kBAAAA,GAAqBC,qBAAAA,CAAsBF,KAAK,CAAC;AACnD,QAAA,GAAGD,cAAc;AACjBT,QAAAA,MAAAA,EAAQS,eAAeP;AAC3B,KAAA,CAAA;AAEA,IAAA,MAAMW,MAAAA,GAAS,CAACC,IAAAA,EAA+DP,OAAAA,GAAoC,EAAE,GAAA;QACjH,IAAIQ,WAAAA,GAA+BH,qBAAAA,CAAsBF,KAAK,CAACH,OAAAA,CAAAA;QAC/DQ,WAAAA,GAAc;AAAE,YAAA,GAAGJ,kBAAkB;AAAE,YAAA,GAAGI;AAAY,SAAA;QAEtD,IAAIC,KAAAA,CAAMC,OAAO,CAACH,IAAAA,CAAAA,EAAO;YACrBA,IAAAA,CAAKI,OAAO,CAAC,CAACJ,IAAAA,GAAAA;gBACVD,MAAAA,CAAOC,IAAAA,CAAAA;AACX,YAAA,CAAA,CAAA;QACJ,CAAA,MAAO;YACH,IAAI,OAAOA,SAAS,QAAA,EAAU;gBAC1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Q,WAAAA,GAAc;AAAE,YAAA,GAAGJ,kBAAkB;AAAE,YAAA,GAAGI;AAAY,SAAA;AAEtD,QAAA,OAAOF,OAAOC,IAAAA,EAAMC,WAAAA,CAAAA;AACxB,IAAA,CAAA;AAEA,IAAA,MAAMM,OAAAA,GAAsB;AACxBxB,QAAAA,KAAAA,EAAOY,eAAeZ,KAAK;AAC3BW,QAAAA,KAAAA;AACAR,QAAAA,MAAAA,EAAQS,eAAeT,MAAM;AAC7B6B,QAAAA,GAAAA;AACAhB,QAAAA,MAAAA;AACAS,QAAAA,OAAAA;AACAE,QAAAA,MAAAA;AACAG,QAAAA,MAAAA;AACAC,QAAAA;AACJ,KAAA;IAEA,OAAOP,OAAAA;AACX;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"loader.js","sources":["../src/loader.ts"],"sourcesContent":["import path from \"path\";\nimport { z } from \"zod\";\nimport { DEFAULT_IGNORE_PATTERNS } from \"./constants\";\nimport { ParametersSchema } from \"./items/parameters\";\nimport { SectionOptions, SectionOptionsSchema } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Section, Weighted, createSection } from \"./riotprompt\";\nimport * as Storage from \"./util/storage\";\n\nconst OptionsSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n ignorePatterns: z.array(z.string()).optional().default(DEFAULT_IGNORE_PATTERNS),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionsSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n load: <T extends Weighted>(contextDirectories?: string[], options?: SectionOptions) => Promise<Section<T>[]>;\n}\n\n/**\n * Extracts the first header from Markdown text\n * @param markdownText The Markdown text to parse\n * @returns The first header found in the Markdown or null if none is found\n */\nexport function extractFirstHeader(markdownText: string): string | null {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match && match[2]) {\n return match[2].trim();\n }\n\n return null;\n}\n\n/**\n * Removes the first header from Markdown text\n * @param markdownText The Markdown text to process\n * @returns The Markdown text without the first header\n */\nexport function removeFirstHeader(markdownText: string): string {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match) {\n return markdownText.replace(headerRegex, '').trim();\n }\n\n return markdownText;\n}\n\nexport const create = (loaderOptions?: OptionsParam): Instance => {\n const options: Required<Options> = OptionsSchema.parse(loaderOptions || {}) as Required<Options>;\n const parameters = options.parameters;\n\n const logger = wrapLogger(options.logger, 'Loader');\n const ignorePatterns = options.ignorePatterns;\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n /**\n * Loads context from the provided directories and returns instruction sections\n * \n * @param contextDirectories Directories containing context files\n * @returns Array of instruction sections loaded from context directories\n */\n const load = async<T extends Weighted>(\n contextDirectories: string[] = [],\n options: Partial<SectionOptions> = {}\n ): Promise<Section<T>[]> => {\n const sectionOptions = loadOptions(options);\n\n logger.debug(`Loading context from ${contextDirectories}`);\n const contextSections: Section<T>[] = [];\n\n if (!contextDirectories || contextDirectories.length === 0) {\n logger.debug(`No context directories provided, returning empty context`);\n return contextSections;\n }\n\n const storage = Storage.create({ log: logger.debug });\n\n // Add context sections from each directory\n for (const contextDir of contextDirectories) {\n try {\n const dirName = path.basename(contextDir);\n logger.debug(`Processing context directory ${dirName}`);\n let mainContextSection: Section<T>;\n\n // First check if there's a context.md file\n const contextFile = path.join(contextDir, 'context.md');\n\n if (await storage.exists(contextFile)) {\n logger.debug(`Found context.md file in ${contextDir}`);\n const mainContextContent = await storage.readFile(contextFile, 'utf8');\n // Extract the first header from the Markdown content\n const firstHeader = extractFirstHeader(mainContextContent);\n\n // Use the header from context.md as the section title, or fallback to directory name\n const sectionTitle = firstHeader || dirName;\n mainContextSection = createSection<T>({ ...sectionOptions, title: sectionTitle });\n\n // Add content without the header\n if (firstHeader) {\n mainContextSection.add(removeFirstHeader(mainContextContent), { ...sectionOptions });\n } else {\n mainContextSection.add(mainContextContent, { ...sectionOptions });\n }\n } else {\n // If no context.md exists, use directory name as title\n mainContextSection = createSection<T>({ ...sectionOptions, title: dirName });\n }\n\n // Get all other files in the directory\n const files = await storage.listFiles(contextDir);\n const ignorePatternsRegex = ignorePatterns.map(pattern => new RegExp(pattern, 'i'));\n\n const filteredFiles = files.filter(file =>\n !ignorePatternsRegex.some(regex => regex.test(file))\n );\n\n for (const file of filteredFiles) {\n // Skip the context.md file as it's already processed\n if (file === 'context.md') continue;\n\n logger.debug(`Processing file ${file} in ${contextDir}`);\n const filePath = path.join(contextDir, file);\n if (await storage.isFile(filePath)) {\n const fileContent = await storage.readFile(filePath, 'utf8');\n let sectionName = file;\n let contentToAdd = fileContent;\n\n // Extract header if it exists\n if (file.endsWith('.md')) {\n const fileHeader = extractFirstHeader(fileContent);\n if (fileHeader) {\n sectionName = fileHeader;\n // Remove the header from the content\n contentToAdd = removeFirstHeader(fileContent);\n }\n }\n\n // Create a subsection with the extracted name\n const fileSection = createSection<T>({ ...sectionOptions, title: sectionName });\n fileSection.add(contentToAdd, { ...sectionOptions });\n\n // Add this file section to the main context section\n mainContextSection.add(fileSection as unknown as T, { ...sectionOptions });\n }\n }\n\n contextSections.push(mainContextSection);\n } catch (error) {\n logger.error(`Error processing context directory ${contextDir}: ${error}`);\n }\n }\n\n return contextSections;\n }\n\n\n return {\n load\n }\n}\n"],"names":["OptionsSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","ignorePatterns","array","string","DEFAULT_IGNORE_PATTERNS","parameters","ParametersSchema","extractFirstHeader","markdownText","headerRegex","match","trim","removeFirstHeader","replace","create","loaderOptions","options","parse","wrapLogger","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","load","contextDirectories","debug","contextSections","length","storage","Storage","log","contextDir","dirName","path","basename","mainContextSection","contextFile","join","exists","mainContextContent","readFile","firstHeader","sectionTitle","createSection","title","add","files","listFiles","ignorePatternsRegex","map","pattern","RegExp","filteredFiles","filter","file","some","regex","test","filePath","isFile","fileContent","sectionName","contentToAdd","endsWith","fileHeader","fileSection","push","error"],"mappings":";;;;;;;;;;;;;;AASA,MAAMA,aAAAA,GAAgBC,CAAAA,CAAEC,MAAM,CAAC;AAC3BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;IACnCC,cAAAA,EAAgBP,CAAAA,CAAEQ,KAAK,CAACR,CAAAA,CAAES,MAAM,EAAA,CAAA,CAAIL,QAAQ,EAAA,CAAGC,OAAO,CAACK,uBAAAA,CAAAA;AACvDC,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBR,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAUA;;;;IAKO,SAASQ,kBAAAA,CAAmBC,YAAoB,EAAA;;AAEnD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,GAAQF,YAAAA,CAAaE,KAAK,CAACD,WAAAA,CAAAA;AAEjC,IAAA,IAAIC,KAAAA,IAASA,KAAK,CAAC,CAAA,CAAE,EAAE;AACnB,QAAA,OAAOA,KAAK,CAAC,CAAA,CAAE,CAACC,IAAI,EAAA;AACxB;IAEA,OAAO,IAAA;AACX;AAEA;;;;IAKO,SAASC,iBAAAA,CAAkBJ,YAAoB,EAAA;;AAElD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,GAAQF,YAAAA,CAAaE,KAAK,CAACD,WAAAA,CAAAA;AAEjC,IAAA,IAAIC,KAAAA,EAAO;AACP,QAAA,OAAOF,YAAAA,CAAaK,OAAO,CAACJ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BAAA,GAAGvB,cAAc;4BAAEwB,KAAAA,EAAOiB;AAAY,yBAAA,CAAA;wBAC7EI,WAAAA,CAAYpB,GAAG,CAACiB,YAAAA,EAAc;AAAE,4BAAA,GAAG1C;AAAe,yBAAA,CAAA;;wBAGlDe,kBAAAA,CAAmBU,GAAG,CAACoB,WAAAA,EAA6B;AAAE,4BAAA,GAAG7C;AAAe,yBAAA,CAAA;AAC5E;AACJ;AAEAM,gBAAAA,eAAAA,CAAgBwC,IAAI,CAAC/B,kBAAAA,CAAAA;AACzB,aAAA,CAAE,OAAOgC,KAAAA,EAAO;gBACZvE,MAAAA,CAAOuE,KAAK,CAAC,CAAC,mCAAmC,EAAEpC,UAAAA,CAAW,EAAE,EAAEoC,KAAAA,CAAAA,CAAO,CAAA;AAC7E;AACJ;QAEA,OAAOzC,eAAAA;AACX,KAAA;IAGA,OAAO;AACHH,QAAAA;AACJ,KAAA;AACJ;;;;"}
1
+ {"version":3,"file":"loader.js","sources":["../src/loader.ts"],"sourcesContent":["import path from \"path\";\nimport { z } from \"zod\";\nimport { DEFAULT_IGNORE_PATTERNS } from \"./constants\";\nimport { ParametersSchema } from \"./items/parameters\";\nimport { SectionOptions, SectionOptionsSchema } from \"./items/section\";\nimport { DEFAULT_LOGGER, wrapLogger } from \"./logger\";\nimport { Section, Weighted, createSection } from \"./riotprompt\";\nimport * as Storage from \"./util/storage\";\n\nconst OptionsSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n ignorePatterns: z.array(z.string()).optional().default(DEFAULT_IGNORE_PATTERNS),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionsSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n load: <T extends Weighted>(contextDirectories?: string[], options?: SectionOptions) => Promise<Section<T>[]>;\n}\n\n/**\n * Extracts the first header from Markdown text\n * @param markdownText The Markdown text to parse\n * @returns The first header found in the Markdown or null if none is found\n */\nexport function extractFirstHeader(markdownText: string): string | null {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match && match[2]) {\n return match[2].trim();\n }\n\n return null;\n}\n\n/**\n * Removes the first header from Markdown text\n * @param markdownText The Markdown text to process\n * @returns The Markdown text without the first header\n */\nexport function removeFirstHeader(markdownText: string): string {\n // Regular expression to match Markdown headers (# Header, ## Header, etc.)\n const headerRegex = /^(#{1,6})\\s+(.+?)(?:\\n|$)/m;\n const match = markdownText.match(headerRegex);\n\n if (match) {\n return markdownText.replace(headerRegex, '').trim();\n }\n\n return markdownText;\n}\n\nexport const create = (loaderOptions?: OptionsParam): Instance => {\n const options: Required<Options> = OptionsSchema.parse(loaderOptions || {}) as Required<Options>;\n const parameters = options.parameters;\n\n const logger = wrapLogger(options.logger, 'Loader');\n const ignorePatterns = options.ignorePatterns;\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n /**\n * Loads context from the provided directories and returns instruction sections\n * \n * @param contextDirectories Directories containing context files\n * @returns Array of instruction sections loaded from context directories\n */\n const load = async<T extends Weighted>(\n contextDirectories: string[] = [],\n options: Partial<SectionOptions> = {}\n ): Promise<Section<T>[]> => {\n const sectionOptions = loadOptions(options);\n\n logger.debug(`Loading context from ${contextDirectories}`);\n const contextSections: Section<T>[] = [];\n\n if (!contextDirectories || contextDirectories.length === 0) {\n logger.debug(`No context directories provided, returning empty context`);\n return contextSections;\n }\n\n const storage = Storage.create({ log: logger.debug });\n\n // Add context sections from each directory\n for (const contextDir of contextDirectories) {\n try {\n const dirName = path.basename(contextDir);\n logger.debug(`Processing context directory ${dirName}`);\n let mainContextSection: Section<T>;\n\n // First check if there's a context.md file\n const contextFile = path.join(contextDir, 'context.md');\n\n if (await storage.exists(contextFile)) {\n logger.debug(`Found context.md file in ${contextDir}`);\n const mainContextContent = await storage.readFile(contextFile, 'utf8');\n // Extract the first header from the Markdown content\n const firstHeader = extractFirstHeader(mainContextContent);\n\n // Use the header from context.md as the section title, or fallback to directory name\n const sectionTitle = firstHeader || dirName;\n mainContextSection = createSection<T>({ ...sectionOptions, title: sectionTitle });\n\n // Add content without the header\n if (firstHeader) {\n mainContextSection.add(removeFirstHeader(mainContextContent), { ...sectionOptions });\n } else {\n mainContextSection.add(mainContextContent, { ...sectionOptions });\n }\n } else {\n // If no context.md exists, use directory name as title\n mainContextSection = createSection<T>({ ...sectionOptions, title: dirName });\n }\n\n // Get all other files in the directory\n const files = await storage.listFiles(contextDir);\n const ignorePatternsRegex = ignorePatterns.map(pattern => new RegExp(pattern, 'i'));\n\n const filteredFiles = files.filter(file =>\n !ignorePatternsRegex.some(regex => regex.test(file))\n );\n\n for (const file of filteredFiles) {\n // Skip the context.md file as it's already processed\n if (file === 'context.md') continue;\n\n logger.debug(`Processing file ${file} in ${contextDir}`);\n const filePath = path.join(contextDir, file);\n if (await storage.isFile(filePath)) {\n const fileContent = await storage.readFile(filePath, 'utf8');\n let sectionName = file;\n let contentToAdd = fileContent;\n\n // Extract header if it exists\n if (file.endsWith('.md')) {\n const fileHeader = extractFirstHeader(fileContent);\n if (fileHeader) {\n sectionName = fileHeader;\n // Remove the header from the content\n contentToAdd = removeFirstHeader(fileContent);\n }\n }\n\n // Create a subsection with the extracted name\n const fileSection = createSection<T>({ ...sectionOptions, title: sectionName });\n fileSection.add(contentToAdd, { ...sectionOptions });\n\n // Add this file section to the main context section\n mainContextSection.add(fileSection as unknown as T, { ...sectionOptions });\n }\n }\n\n contextSections.push(mainContextSection);\n } catch (error) {\n logger.error(`Error processing context directory ${contextDir}: ${error}`);\n }\n }\n\n return contextSections;\n }\n\n\n return {\n load\n }\n}\n"],"names":["OptionsSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","ignorePatterns","array","string","DEFAULT_IGNORE_PATTERNS","parameters","ParametersSchema","extractFirstHeader","markdownText","headerRegex","match","trim","removeFirstHeader","replace","create","loaderOptions","options","parse","wrapLogger","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","load","contextDirectories","debug","contextSections","length","storage","Storage","log","contextDir","dirName","path","basename","mainContextSection","contextFile","join","exists","mainContextContent","readFile","firstHeader","sectionTitle","createSection","title","add","files","listFiles","ignorePatternsRegex","map","pattern","RegExp","filteredFiles","filter","file","some","regex","test","filePath","isFile","fileContent","sectionName","contentToAdd","endsWith","fileHeader","fileSection","push","error"],"mappings":";;;;;;;;;;;;;;AASA,MAAMA,aAAAA,GAAgBC,CAAAA,CAAEC,MAAM,CAAC;AAC3BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;IACnCC,cAAAA,EAAgBP,CAAAA,CAAEQ,KAAK,CAACR,CAAAA,CAAES,MAAM,EAAA,CAAA,CAAIL,QAAQ,EAAA,CAAGC,OAAO,CAACK,uBAAAA,CAAAA;AACvDC,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBR,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAUA;;;;IAKO,SAASQ,kBAAAA,CAAmBC,YAAoB,EAAA;;AAEnD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,GAAQF,YAAAA,CAAaE,KAAK,CAACD,WAAAA,CAAAA;AAEjC,IAAA,IAAIC,KAAAA,IAASA,KAAK,CAAC,CAAA,CAAE,EAAE;AACnB,QAAA,OAAOA,KAAK,CAAC,CAAA,CAAE,CAACC,IAAI,EAAA;AACxB,IAAA;IAEA,OAAO,IAAA;AACX;AAEA;;;;IAKO,SAASC,iBAAAA,CAAkBJ,YAAoB,EAAA;;AAElD,IAAA,MAAMC,WAAAA,GAAc,4BAAA;IACpB,MAAMC,KAAAA,GAAQF,YAAAA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AY;gCACZH,WAAAA,GAAcG,UAAAA;;AAEdF,gCAAAA,YAAAA,GAAelD,iBAAAA,CAAkBgD,WAAAA,CAAAA;AACrC,4BAAA;AACJ,wBAAA;;AAGA,wBAAA,MAAMK,cAActB,QAAAA,CAAiB;AAAE,4BAAA,GAAGvB,cAAc;4BAAEwB,KAAAA,EAAOiB;AAAY,yBAAA,CAAA;wBAC7EI,WAAAA,CAAYpB,GAAG,CAACiB,YAAAA,EAAc;AAAE,4BAAA,GAAG1C;AAAe,yBAAA,CAAA;;wBAGlDe,kBAAAA,CAAmBU,GAAG,CAACoB,WAAAA,EAA6B;AAAE,4BAAA,GAAG7C;AAAe,yBAAA,CAAA;AAC5E,oBAAA;AACJ,gBAAA;AAEAM,gBAAAA,eAAAA,CAAgBwC,IAAI,CAAC/B,kBAAAA,CAAAA;AACzB,YAAA,CAAA,CAAE,OAAOgC,KAAAA,EAAO;gBACZvE,MAAAA,CAAOuE,KAAK,CAAC,CAAC,mCAAmC,EAAEpC,UAAAA,CAAW,EAAE,EAAEoC,KAAAA,CAAAA,CAAO,CAAA;AAC7E,YAAA;AACJ,QAAA;QAEA,OAAOzC,eAAAA;AACX,IAAA,CAAA;IAGA,OAAO;AACHH,QAAAA;AACJ,KAAA;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","sources":["../src/logger.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { LIBRARY_NAME } from \"./constants\";\n\nexport interface Logger {\n name: string;\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, ...args: any[]) => void;\n verbose: (message: string, ...args: any[]) => void;\n silly: (message: string, ...args: any[]) => void;\n}\n\nexport const DEFAULT_LOGGER: Logger = {\n name: 'default',\n debug: (message: string, ...args: any[]) => console.debug(message, ...args),\n info: (message: string, ...args: any[]) => console.info(message, ...args),\n warn: (message: string, ...args: any[]) => console.warn(message, ...args),\n error: (message: string, ...args: any[]) => console.error(message, ...args),\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n verbose: (message: string, ...args: any[]) => { },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n silly: (message: string, ...args: any[]) => { },\n}\n\nexport const wrapLogger = (toWrap: Logger, name?: string): Logger => {\n\n const requiredMethods: (keyof Logger)[] = ['debug', 'info', 'warn', 'error', 'verbose', 'silly'];\n const missingMethods = requiredMethods.filter(method => typeof toWrap[method] !== 'function');\n\n if (missingMethods.length > 0) {\n throw new Error(`Logger is missing required methods: ${missingMethods.join(', ')}`);\n }\n\n const log = (level: keyof Logger, message: string, ...args: any[]) => {\n message = `[${LIBRARY_NAME}] ${name ? `[${name}]` : ''}: ${message}`;\n\n if (level === 'debug') toWrap.debug(message, ...args);\n else if (level === 'info') toWrap.info(message, ...args);\n else if (level === 'warn') toWrap.warn(message, ...args);\n else if (level === 'error') toWrap.error(message, ...args);\n else if (level === 'verbose') toWrap.verbose(message, ...args);\n else if (level === 'silly') toWrap.silly(message, ...args);\n }\n\n return {\n name: 'wrapped',\n debug: (message: string, ...args: any[]) => log('debug', message, ...args),\n info: (message: string, ...args: any[]) => log('info', message, ...args),\n warn: (message: string, ...args: any[]) => log('warn', message, ...args),\n error: (message: string, ...args: any[]) => log('error', message, ...args),\n verbose: (message: string, ...args: any[]) => log('verbose', message, ...args),\n silly: (message: string, ...args: any[]) => log('silly', message, ...args),\n }\n}"],"names":["DEFAULT_LOGGER","name","debug","message","args","console","info","warn","error","verbose","silly","wrapLogger","toWrap","requiredMethods","missingMethods","filter","method","length","Error","join","log","level","LIBRARY_NAME"],"mappings":";;MAaaA,cAAAA,GAAyB;IAClCC,IAAAA,EAAM,SAAA;AACNC,IAAAA,KAAAA,EAAO,CAACC,OAAAA,EAAiB,GAAGC,OAAgBC,OAAAA,CAAQH,KAAK,CAACC,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACtEE,IAAAA,IAAAA,EAAM,CAACH,OAAAA,EAAiB,GAAG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A;AACrEK,QAAAA,OAAAA,EAAS,CAACN,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,WAAWjB,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACzEM,QAAAA,KAAAA,EAAO,CAACP,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,SAASjB,OAAAA,EAAAA,GAAYC,IAAAA;AACzE,KAAA;AACJ;;;;"}
1
+ {"version":3,"file":"logger.js","sources":["../src/logger.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { LIBRARY_NAME } from \"./constants\";\n\nexport interface Logger {\n name: string;\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, ...args: any[]) => void;\n verbose: (message: string, ...args: any[]) => void;\n silly: (message: string, ...args: any[]) => void;\n}\n\nexport const DEFAULT_LOGGER: Logger = {\n name: 'default',\n debug: (message: string, ...args: any[]) => console.debug(message, ...args),\n info: (message: string, ...args: any[]) => console.info(message, ...args),\n warn: (message: string, ...args: any[]) => console.warn(message, ...args),\n error: (message: string, ...args: any[]) => console.error(message, ...args),\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n verbose: (message: string, ...args: any[]) => { },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n silly: (message: string, ...args: any[]) => { },\n}\n\nexport const wrapLogger = (toWrap: Logger, name?: string): Logger => {\n\n const requiredMethods: (keyof Logger)[] = ['debug', 'info', 'warn', 'error', 'verbose', 'silly'];\n const missingMethods = requiredMethods.filter(method => typeof toWrap[method] !== 'function');\n\n if (missingMethods.length > 0) {\n throw new Error(`Logger is missing required methods: ${missingMethods.join(', ')}`);\n }\n\n const log = (level: keyof Logger, message: string, ...args: any[]) => {\n message = `[${LIBRARY_NAME}] ${name ? `[${name}]` : ''}: ${message}`;\n\n if (level === 'debug') toWrap.debug(message, ...args);\n else if (level === 'info') toWrap.info(message, ...args);\n else if (level === 'warn') toWrap.warn(message, ...args);\n else if (level === 'error') toWrap.error(message, ...args);\n else if (level === 'verbose') toWrap.verbose(message, ...args);\n else if (level === 'silly') toWrap.silly(message, ...args);\n }\n\n return {\n name: 'wrapped',\n debug: (message: string, ...args: any[]) => log('debug', message, ...args),\n info: (message: string, ...args: any[]) => log('info', message, ...args),\n warn: (message: string, ...args: any[]) => log('warn', message, ...args),\n error: (message: string, ...args: any[]) => log('error', message, ...args),\n verbose: (message: string, ...args: any[]) => log('verbose', message, ...args),\n silly: (message: string, ...args: any[]) => log('silly', message, ...args),\n }\n}"],"names":["DEFAULT_LOGGER","name","debug","message","args","console","info","warn","error","verbose","silly","wrapLogger","toWrap","requiredMethods","missingMethods","filter","method","length","Error","join","log","level","LIBRARY_NAME"],"mappings":";;MAaaA,cAAAA,GAAyB;IAClCC,IAAAA,EAAM,SAAA;AACNC,IAAAA,KAAAA,EAAO,CAACC,OAAAA,EAAiB,GAAGC,OAAgBC,OAAAA,CAAQH,KAAK,CAACC,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACtEE,IAAAA,IAAAA,EAAM,CAACH,OAAAA,EAAiB,GAAGC,OAAgBC,OAAAA,CAAQC,IAAI,CAACH,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACpEG,IAAAA,IAAAA,EAAM,CAACJ,OAAAA,EAAiB,GAAGC,OAAgBC,OAAAA,CAAQE,IAAI,CAACJ,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACpEI,IAAAA,KAAAA,EAAO,CAACL,OAAAA,EAAiB,GAAGC,OAAgBC,OAAAA,CAAQG,KAAK,CAACL,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;;IAEtEK,OAAAA,EAAS,CAACN,OAAAA,EAAiB,GAAGC,IAAAA,GAAAA,CAAkB,CAAA;;IAEhDM,KAAAA,EAAO,CAACP,OAAAA,EAAiB,GAAGC,IAAAA,GAAAA,CAAkB;AAClD;AAEO,MAAMO,UAAAA,GAAa,CAACC,MAAAA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CAAOH,OAAO,CAACN,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACpD,aAAA,IAAIiB,KAAAA,KAAU,OAAA,EAAST,MAAAA,CAAOF,KAAK,CAACP,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACzD,IAAA,CAAA;IAEA,OAAO;QACHH,IAAAA,EAAM,SAAA;AACNC,QAAAA,KAAAA,EAAO,CAACC,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,SAASjB,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACrEE,QAAAA,IAAAA,EAAM,CAACH,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,QAAQjB,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACnEG,QAAAA,IAAAA,EAAM,CAACJ,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,QAAQjB,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACnEI,QAAAA,KAAAA,EAAO,CAACL,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,SAASjB,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACrEK,QAAAA,OAAAA,EAAS,CAACN,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,WAAWjB,OAAAA,EAAAA,GAAYC,IAAAA,CAAAA;AACzEM,QAAAA,KAAAA,EAAO,CAACP,OAAAA,EAAiB,GAAGC,IAAAA,GAAgBgB,GAAAA,CAAI,SAASjB,OAAAA,EAAAA,GAAYC,IAAAA;AACzE,KAAA;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"override.js","sources":["../src/override.ts"],"sourcesContent":["import path from 'path';\nimport { z } from 'zod';\nimport { ParametersSchema } from './items/parameters';\nimport { SectionOptions, SectionOptionsSchema } from './items/section';\nimport { DEFAULT_LOGGER, wrapLogger } from './logger';\nimport { Formatter, Parser, Section, Weighted } from './riotprompt';\nimport * as Storage from './util/storage';\n\nconst OptionsSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n configDirs: z.array(z.string()).default(['./overrides']),\n overrides: z.boolean().default(false),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionsSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n customize: <T extends Weighted>(overrideFile: string, section: Section<T>, sectionOptions?: SectionOptions) => Promise<Section<T>>;\n override: <T extends Weighted>(overrideFile: string, section: Section<T>, sectionOptions?: SectionOptions) =>\n Promise<{ override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] }>;\n}\n\nexport const create = (overrideOptions: OptionsParam = {}): Instance => {\n const options: Required<Options> = OptionsSchema.parse(overrideOptions) as Required<Options>;\n\n const parameters = options.parameters;\n\n const logger = wrapLogger(options?.logger, 'Override');\n const storage = Storage.create({ log: logger.debug });\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n const override = async <T extends Weighted>(\n overrideFile: string,\n section: Section<T>,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<{ override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] }> => {\n const currentSectionOptions = loadOptions(sectionOptions);\n\n const response: { override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] } = {\n prepends: [],\n appends: []\n };\n\n // Process directories in order (closest to furthest)\n for (let i = 0; i < options.configDirs.length; i++) {\n const configDir = options.configDirs[i];\n const baseFile = path.join(configDir, overrideFile);\n const preFile = baseFile.replace('.md', '-pre.md');\n const postFile = baseFile.replace('.md', '-post.md');\n\n // Check for prepend files (-pre.md)\n if (await storage.exists(preFile)) {\n logger.silly('Found pre file %s (layer %d)', preFile, i + 1);\n const parser = Parser.create({ logger });\n const prependSection = await parser.parseFile<T>(preFile, currentSectionOptions);\n response.prepends.push(prependSection);\n }\n\n // Check for append files (-post.md)\n if (await storage.exists(postFile)) {\n logger.silly('Found post file %s (layer %d)', postFile, i + 1);\n const parser = Parser.create({ logger });\n const appendSection = await parser.parseFile<T>(postFile, currentSectionOptions);\n response.appends.push(appendSection);\n }\n\n // Check for complete override files - use the first (closest) one found\n if (!response.override && await storage.exists(baseFile)) {\n logger.silly('Found base file %s (layer %d)', baseFile, i + 1);\n if (options.overrides) {\n logger.warn('WARNING: Core directives are being overwritten by custom configuration at layer %d', i + 1);\n const parser = Parser.create({ logger });\n response.override = await parser.parseFile<T>(baseFile, currentSectionOptions);\n } else {\n logger.error('ERROR: Core directives are being overwritten by custom configuration');\n throw new Error('Core directives are being overwritten by custom configuration, but overrides are not enabled. Please enable --overrides to use this feature.');\n }\n }\n }\n\n return response;\n }\n\n const customize = async <T extends Weighted>(\n overrideFile: string,\n section: Section<T>,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Section<T>> => {\n const currentSectionOptions = loadOptions(sectionOptions);\n\n const { override: overrideContent, prepends, appends }: { override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] } = await override(overrideFile, section, currentSectionOptions);\n let finalSection: Section<T> = section;\n\n if (overrideContent) {\n if (options.overrides) {\n logger.warn('Override found, replacing content from file %s', overrideContent);\n finalSection = overrideContent;\n } else {\n logger.error('ERROR: Core directives are being overwritten by custom configuration');\n throw new Error('Core directives are being overwritten by custom configuration, but overrides are not enabled. Please enable --overrides to use this feature.');\n }\n }\n\n // Apply prepends in order (closest layer first)\n for (const prepend of prepends) {\n logger.silly('Prepend found, adding to content from file %s', prepend);\n finalSection = finalSection.prepend(prepend);\n }\n\n // Apply appends in reverse order (furthest layers first, then closest)\n for (const append of appends.reverse()) {\n logger.silly('Append found, adding to content from file %s', append);\n finalSection = finalSection.append(append);\n }\n\n const formatter = Formatter.create({ logger });\n logger.silly('Final section %s:\\n\\n%s\\n\\n', logger.name, formatter.format(finalSection));\n\n return finalSection;\n }\n\n return {\n override,\n customize,\n }\n}"],"names":["OptionsSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","configDirs","array","string","overrides","boolean","parameters","ParametersSchema","create","overrideOptions","options","parse","wrapLogger","storage","Storage","log","debug","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","override","overrideFile","section","currentSectionOptions","response","prepends","appends","i","length","configDir","baseFile","path","join","preFile","replace","postFile","exists","silly","parser","Parser","prependSection","parseFile","push","appendSection","warn","error","Error","customize","overrideContent","finalSection","prepend","append","reverse","formatter","Formatter","name","format"],"mappings":";;;;;;;;;;;;;AAQA,MAAMA,aAAAA,GAAgBC,CAAAA,CAAEC,MAAM,CAAC;AAC3BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;AACnCC,IAAAA,UAAAA,EAAYP,EAAEQ,KAAK,CAACR,EAAES,MAAM,EAAA,CAAA,CAAIJ,OAAO,CAAC;AAAC,QAAA;AAAc,KAAA,CAAA;AACvDK,IAAAA,SAAAA,EAAWV,CAAAA,CAAEW,OAAO,EAAA,CAAGN,OAAO,CAAC,KAAA,CAAA;AAC/BO,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBT,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAYO,MAAMS,MAAAA,GAAS,CAACC,eAAAA,GAAgC,EAAE,GAAA;IACrD,MAAMC,OAAAA,GAA6BjB,aAAAA,CAAckB,KAAK,CAACF,eAAAA,CAAAA;IAEvD,MAAMH,UAAAA,GAAaI,QAAQJ,UAAU;AAErC,IAAA,MAAMV,SAASgB,UAAAA,CAAWF,OAAAA,KAAAA,IAAAA,IAAAA,OAAAA,KAAAA,MAAAA,GAAAA,MAAAA,GAAAA,OAAAA,CAASd,MAAM,EAAE,UAAA,CAAA;IAC3C,MAAMiB,OAAAA,GAAUC,QAAc,CAAC;AAAEC,QAAAA,GAAAA,EAAKnB,O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CAAO4D,IAAI,EAAEF,WAAAA,CAAUG,MAAM,CAACP,YAAAA,CAAAA,CAAAA;QAE1E,OAAOA,YAAAA;AACX,KAAA;IAEA,OAAO;AACH7B,QAAAA,QAAAA;AACA2B,QAAAA;AACJ,KAAA;AACJ;;;;"}
1
+ {"version":3,"file":"override.js","sources":["../src/override.ts"],"sourcesContent":["import path from 'path';\nimport { z } from 'zod';\nimport { ParametersSchema } from './items/parameters';\nimport { SectionOptions, SectionOptionsSchema } from './items/section';\nimport { DEFAULT_LOGGER, wrapLogger } from './logger';\nimport { Formatter, Parser, Section, Weighted } from './riotprompt';\nimport * as Storage from './util/storage';\n\nconst OptionsSchema = z.object({\n logger: z.any().optional().default(DEFAULT_LOGGER),\n configDirs: z.array(z.string()).default(['./overrides']),\n overrides: z.boolean().default(false),\n parameters: ParametersSchema.optional().default({}),\n});\n\nexport type Options = z.infer<typeof OptionsSchema>;\n\nexport type OptionsParam = Partial<Options>;\n\nexport interface Instance {\n customize: <T extends Weighted>(overrideFile: string, section: Section<T>, sectionOptions?: SectionOptions) => Promise<Section<T>>;\n override: <T extends Weighted>(overrideFile: string, section: Section<T>, sectionOptions?: SectionOptions) =>\n Promise<{ override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] }>;\n}\n\nexport const create = (overrideOptions: OptionsParam = {}): Instance => {\n const options: Required<Options> = OptionsSchema.parse(overrideOptions) as Required<Options>;\n\n const parameters = options.parameters;\n\n const logger = wrapLogger(options?.logger, 'Override');\n const storage = Storage.create({ log: logger.debug });\n\n const loadOptions = (sectionOptions: Partial<SectionOptions> = {}): SectionOptions => {\n const currentOptions = SectionOptionsSchema.parse(sectionOptions);\n return {\n ...currentOptions,\n parameters: {\n ...parameters,\n ...currentOptions.parameters\n }\n }\n }\n\n const override = async <T extends Weighted>(\n overrideFile: string,\n section: Section<T>,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<{ override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] }> => {\n const currentSectionOptions = loadOptions(sectionOptions);\n\n const response: { override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] } = {\n prepends: [],\n appends: []\n };\n\n // Process directories in order (closest to furthest)\n for (let i = 0; i < options.configDirs.length; i++) {\n const configDir = options.configDirs[i];\n const baseFile = path.join(configDir, overrideFile);\n const preFile = baseFile.replace('.md', '-pre.md');\n const postFile = baseFile.replace('.md', '-post.md');\n\n // Check for prepend files (-pre.md)\n if (await storage.exists(preFile)) {\n logger.silly('Found pre file %s (layer %d)', preFile, i + 1);\n const parser = Parser.create({ logger });\n const prependSection = await parser.parseFile<T>(preFile, currentSectionOptions);\n response.prepends.push(prependSection);\n }\n\n // Check for append files (-post.md)\n if (await storage.exists(postFile)) {\n logger.silly('Found post file %s (layer %d)', postFile, i + 1);\n const parser = Parser.create({ logger });\n const appendSection = await parser.parseFile<T>(postFile, currentSectionOptions);\n response.appends.push(appendSection);\n }\n\n // Check for complete override files - use the first (closest) one found\n if (!response.override && await storage.exists(baseFile)) {\n logger.silly('Found base file %s (layer %d)', baseFile, i + 1);\n if (options.overrides) {\n logger.warn('WARNING: Core directives are being overwritten by custom configuration at layer %d', i + 1);\n const parser = Parser.create({ logger });\n response.override = await parser.parseFile<T>(baseFile, currentSectionOptions);\n } else {\n logger.error('ERROR: Core directives are being overwritten by custom configuration');\n throw new Error('Core directives are being overwritten by custom configuration, but overrides are not enabled. Please enable --overrides to use this feature.');\n }\n }\n }\n\n return response;\n }\n\n const customize = async <T extends Weighted>(\n overrideFile: string,\n section: Section<T>,\n sectionOptions: Partial<SectionOptions> = {}\n ): Promise<Section<T>> => {\n const currentSectionOptions = loadOptions(sectionOptions);\n\n const { override: overrideContent, prepends, appends }: { override?: Section<T>, prepends: Section<T>[], appends: Section<T>[] } = await override(overrideFile, section, currentSectionOptions);\n let finalSection: Section<T> = section;\n\n if (overrideContent) {\n if (options.overrides) {\n logger.warn('Override found, replacing content from file %s', overrideContent);\n finalSection = overrideContent;\n } else {\n logger.error('ERROR: Core directives are being overwritten by custom configuration');\n throw new Error('Core directives are being overwritten by custom configuration, but overrides are not enabled. Please enable --overrides to use this feature.');\n }\n }\n\n // Apply prepends in order (closest layer first)\n for (const prepend of prepends) {\n logger.silly('Prepend found, adding to content from file %s', prepend);\n finalSection = finalSection.prepend(prepend);\n }\n\n // Apply appends in reverse order (furthest layers first, then closest)\n for (const append of appends.reverse()) {\n logger.silly('Append found, adding to content from file %s', append);\n finalSection = finalSection.append(append);\n }\n\n const formatter = Formatter.create({ logger });\n logger.silly('Final section %s:\\n\\n%s\\n\\n', logger.name, formatter.format(finalSection));\n\n return finalSection;\n }\n\n return {\n override,\n customize,\n }\n}"],"names":["OptionsSchema","z","object","logger","any","optional","default","DEFAULT_LOGGER","configDirs","array","string","overrides","boolean","parameters","ParametersSchema","create","overrideOptions","options","parse","wrapLogger","storage","Storage","log","debug","loadOptions","sectionOptions","currentOptions","SectionOptionsSchema","override","overrideFile","section","currentSectionOptions","response","prepends","appends","i","length","configDir","baseFile","path","join","preFile","replace","postFile","exists","silly","parser","Parser","prependSection","parseFile","push","appendSection","warn","error","Error","customize","overrideContent","finalSection","prepend","append","reverse","formatter","Formatter","name","format"],"mappings":";;;;;;;;;;;;;AAQA,MAAMA,aAAAA,GAAgBC,CAAAA,CAAEC,MAAM,CAAC;AAC3BC,IAAAA,MAAAA,EAAQF,EAAEG,GAAG,EAAA,CAAGC,QAAQ,EAAA,CAAGC,OAAO,CAACC,cAAAA,CAAAA;AACnCC,IAAAA,UAAAA,EAAYP,EAAEQ,KAAK,CAACR,EAAES,MAAM,EAAA,CAAA,CAAIJ,OAAO,CAAC;AAAC,QAAA;AAAc,KAAA,CAAA;AACvDK,IAAAA,SAAAA,EAAWV,CAAAA,CAAEW,OAAO,EAAA,CAAGN,OAAO,CAAC,KAAA,CAAA;AAC/BO,IAAAA,UAAAA,EAAYC,gBAAAA,CAAiBT,QAAQ,EAAA,CAAGC,OAAO,CAAC,EAAC;AACrD,CAAA,CAAA;AAYO,MAAMS,MA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C,+CAAA,EAAiDa,OAAAA,CAAAA;YAC9DD,YAAAA,GAAeA,YAAAA,CAAaC,OAAO,CAACA,OAAAA,CAAAA;AACxC,QAAA;;AAGA,QAAA,KAAK,MAAMC,MAAAA,IAAUzB,OAAAA,CAAQ0B,OAAO,EAAA,CAAI;YACpCzD,MAAAA,CAAO0C,KAAK,CAAC,8CAAA,EAAgDc,MAAAA,CAAAA;YAC7DF,YAAAA,GAAeA,YAAAA,CAAaE,MAAM,CAACA,MAAAA,CAAAA;AACvC,QAAA;QAEA,MAAME,WAAAA,GAAYC,QAAgB,CAAC;AAAE3D,YAAAA;AAAO,SAAA,CAAA;QAC5CA,MAAAA,CAAO0C,KAAK,CAAC,6BAAA,EAA+B1C,MAAAA,CAAO4D,IAAI,EAAEF,WAAAA,CAAUG,MAAM,CAACP,YAAAA,CAAAA,CAAAA;QAE1E,OAAOA,YAAAA;AACX,IAAA,CAAA;IAEA,OAAO;AACH7B,QAAAA,QAAAA;AACA2B,QAAAA;AACJ,KAAA;AACJ;;;;"}
@@ -1,3 +1,3 @@
1
1
  import { Section, SectionOptions } from '../items/section';
2
2
  import { Weighted } from '../items/weighted';
3
- export declare const parseMarkdown: <T extends Weighted>(input: string | Buffer, options?: Partial<SectionOptions>) => Section<T>;
3
+ export declare const parseMarkdown: <T extends Weighted>(input: string | Buffer, options?: Partial<SectionOptions>) => Promise<Section<T>>;
@@ -1,8 +1,9 @@
1
- import { marked } from 'marked';
2
1
  import { SectionOptionsSchema, create } from '../items/section.js';
3
2
  import { WeightedOptionsSchema, create as create$1 } from '../items/weighted.js';
4
3
 
5
- const parseMarkdown = (input, options = {})=>{
4
+ const parseMarkdown = async (input, options = {})=>{
5
+ // Dynamic import for marked (ES module)
6
+ const { marked } = await import('marked');
6
7
  let markdownContent;
7
8
  if (typeof input === 'string') {
8
9
  markdownContent = input;