@promptbook/core 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/esm/index.es.js +733 -733
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/conversion/prettify/prettifyPromptbookString.d.ts +1 -1
  4. package/esm/typings/conversion/prettify/renderPromptbookMermaid.d.ts +2 -1
  5. package/esm/typings/conversion/utils/extractParametersFromPromptTemplate.d.ts +3 -3
  6. package/esm/typings/conversion/utils/extractVariables.d.ts +2 -1
  7. package/esm/typings/conversion/validation/_importPromptbook.d.ts +2 -2
  8. package/esm/typings/execution/LlmExecutionTools.d.ts +4 -2
  9. package/esm/typings/execution/PromptResult.d.ts +5 -1
  10. package/esm/typings/execution/ScriptExecutionTools.d.ts +2 -1
  11. package/esm/typings/execution/UserInterfaceTools.d.ts +2 -1
  12. package/esm/typings/execution/createPromptbookExecutor.d.ts +3 -3
  13. package/esm/typings/execution/plugins/llm-execution-tools/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +4 -2
  14. package/esm/typings/execution/plugins/llm-execution-tools/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  15. package/esm/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -2
  16. package/esm/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +2 -1
  17. package/esm/typings/execution/plugins/llm-execution-tools/mocked/MockedEchoLlmExecutionTools.d.ts +4 -2
  18. package/esm/typings/execution/plugins/llm-execution-tools/mocked/MockedFackedLlmExecutionTools.d.ts +4 -2
  19. package/esm/typings/execution/plugins/llm-execution-tools/mocked/fakeTextToExpectations.d.ts +1 -1
  20. package/esm/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionTools.d.ts +4 -2
  21. package/esm/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionToolsOptions.d.ts +2 -1
  22. package/esm/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionTools.d.ts +4 -2
  23. package/esm/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  24. package/esm/typings/execution/plugins/llm-execution-tools/openai/openai-models.d.ts +1 -1
  25. package/esm/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionTools.d.ts +4 -2
  26. package/esm/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionToolsOptions.d.ts +2 -1
  27. package/esm/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Progress.d.ts +1 -1
  28. package/esm/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Response.d.ts +1 -1
  29. package/esm/typings/execution/plugins/llm-execution-tools/remote/interfaces/RemoteServerOptions.d.ts +2 -1
  30. package/esm/typings/execution/plugins/llm-execution-tools/remote/startRemoteServer.d.ts +1 -1
  31. package/esm/typings/execution/plugins/script-execution-tools/python/PythonExecutionTools.d.ts +3 -2
  32. package/esm/typings/execution/plugins/script-execution-tools/typescript/TypescriptExecutionTools.d.ts +3 -2
  33. package/esm/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceTools.d.ts +3 -2
  34. package/esm/typings/execution/plugins/user-interface-execution-tools/simple-prompt/SimplePromptInterfaceTools.d.ts +3 -2
  35. package/esm/typings/execution/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +1 -1
  36. package/esm/typings/execution/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +1 -1
  37. package/esm/typings/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +2 -2
  38. package/esm/typings/execution/translation/automatic-translate/translateMessages.d.ts +2 -2
  39. package/esm/typings/execution/utils/replaceParameters.d.ts +2 -2
  40. package/esm/typings/library/SimplePromptbookLibrary.d.ts +1 -1
  41. package/esm/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +2 -2
  42. package/esm/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +2 -2
  43. package/esm/typings/library/constructors/createPromptbookLibraryFromSources.d.ts +2 -1
  44. package/esm/typings/library/constructors/createPromptbookLibraryFromUrl.d.ts +2 -2
  45. package/esm/typings/library/constructors/createPromptbookSublibrary.d.ts +1 -1
  46. package/esm/typings/types/Command.d.ts +5 -2
  47. package/esm/typings/types/Prompt.d.ts +4 -1
  48. package/esm/typings/types/PromptbookJson/PromptTemplateJson.d.ts +8 -1
  49. package/esm/typings/types/PromptbookJson/PromptbookJson.d.ts +2 -1
  50. package/esm/typings/types/TaskProgress.d.ts +2 -1
  51. package/esm/typings/types/execution-report/ExecutionReportJson.d.ts +2 -1
  52. package/esm/typings/types/execution-report/countWorkingDuration.d.ts +1 -1
  53. package/esm/typings/utils/emojis.d.ts +1 -1
  54. package/esm/typings/utils/expectation-counters/index.d.ts +2 -1
  55. package/esm/typings/utils/extractParameters.d.ts +2 -1
  56. package/esm/typings/utils/markdown/addAutoGeneratedSection.d.ts +2 -1
  57. package/esm/typings/utils/markdown/createMarkdownChart.d.ts +2 -2
  58. package/esm/typings/utils/markdown/createMarkdownTable.d.ts +2 -1
  59. package/esm/typings/utils/markdown/escapeMarkdownBlock.d.ts +1 -1
  60. package/esm/typings/utils/markdown/extractAllListItemsFromMarkdown.d.ts +2 -1
  61. package/esm/typings/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  62. package/esm/typings/utils/markdown/removeContentComments.d.ts +2 -1
  63. package/esm/typings/utils/markdown/removeMarkdownFormatting.d.ts +1 -1
  64. package/esm/typings/utils/markdown-json/countMarkdownStructureDeepness.d.ts +1 -1
  65. package/esm/typings/utils/markdown-json/markdownToMarkdownStructure.d.ts +1 -1
  66. package/esm/typings/utils/normalization/isValidKeyword.d.ts +1 -1
  67. package/esm/typings/utils/normalization/parseKeywords.d.ts +1 -1
  68. package/esm/typings/utils/normalization/parseKeywordsFromString.d.ts +1 -1
  69. package/esm/typings/utils/normalization/searchKeywords.d.ts +1 -1
  70. package/esm/typings/utils/postprocessing/extractBlock.d.ts +1 -1
  71. package/package.json +1 -1
  72. package/umd/index.umd.js +733 -733
  73. package/umd/index.umd.js.map +1 -1
  74. package/umd/typings/conversion/prettify/prettifyPromptbookString.d.ts +1 -1
  75. package/umd/typings/conversion/prettify/renderPromptbookMermaid.d.ts +2 -1
  76. package/umd/typings/conversion/utils/extractParametersFromPromptTemplate.d.ts +3 -3
  77. package/umd/typings/conversion/utils/extractVariables.d.ts +2 -1
  78. package/umd/typings/conversion/validation/_importPromptbook.d.ts +2 -2
  79. package/umd/typings/execution/LlmExecutionTools.d.ts +4 -2
  80. package/umd/typings/execution/PromptResult.d.ts +5 -1
  81. package/umd/typings/execution/ScriptExecutionTools.d.ts +2 -1
  82. package/umd/typings/execution/UserInterfaceTools.d.ts +2 -1
  83. package/umd/typings/execution/createPromptbookExecutor.d.ts +3 -3
  84. package/umd/typings/execution/plugins/llm-execution-tools/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +4 -2
  85. package/umd/typings/execution/plugins/llm-execution-tools/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  86. package/umd/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -2
  87. package/umd/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +2 -1
  88. package/umd/typings/execution/plugins/llm-execution-tools/mocked/MockedEchoLlmExecutionTools.d.ts +4 -2
  89. package/umd/typings/execution/plugins/llm-execution-tools/mocked/MockedFackedLlmExecutionTools.d.ts +4 -2
  90. package/umd/typings/execution/plugins/llm-execution-tools/mocked/fakeTextToExpectations.d.ts +1 -1
  91. package/umd/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionTools.d.ts +4 -2
  92. package/umd/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionToolsOptions.d.ts +2 -1
  93. package/umd/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionTools.d.ts +4 -2
  94. package/umd/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  95. package/umd/typings/execution/plugins/llm-execution-tools/openai/openai-models.d.ts +1 -1
  96. package/umd/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionTools.d.ts +4 -2
  97. package/umd/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionToolsOptions.d.ts +2 -1
  98. package/umd/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Progress.d.ts +1 -1
  99. package/umd/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Response.d.ts +1 -1
  100. package/umd/typings/execution/plugins/llm-execution-tools/remote/interfaces/RemoteServerOptions.d.ts +2 -1
  101. package/umd/typings/execution/plugins/llm-execution-tools/remote/startRemoteServer.d.ts +1 -1
  102. package/umd/typings/execution/plugins/script-execution-tools/python/PythonExecutionTools.d.ts +3 -2
  103. package/umd/typings/execution/plugins/script-execution-tools/typescript/TypescriptExecutionTools.d.ts +3 -2
  104. package/umd/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceTools.d.ts +3 -2
  105. package/umd/typings/execution/plugins/user-interface-execution-tools/simple-prompt/SimplePromptInterfaceTools.d.ts +3 -2
  106. package/umd/typings/execution/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +1 -1
  107. package/umd/typings/execution/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +1 -1
  108. package/umd/typings/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +2 -2
  109. package/umd/typings/execution/translation/automatic-translate/translateMessages.d.ts +2 -2
  110. package/umd/typings/execution/utils/replaceParameters.d.ts +2 -2
  111. package/umd/typings/library/SimplePromptbookLibrary.d.ts +1 -1
  112. package/umd/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +2 -2
  113. package/umd/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +2 -2
  114. package/umd/typings/library/constructors/createPromptbookLibraryFromSources.d.ts +2 -1
  115. package/umd/typings/library/constructors/createPromptbookLibraryFromUrl.d.ts +2 -2
  116. package/umd/typings/library/constructors/createPromptbookSublibrary.d.ts +1 -1
  117. package/umd/typings/types/Command.d.ts +5 -2
  118. package/umd/typings/types/Prompt.d.ts +4 -1
  119. package/umd/typings/types/PromptbookJson/PromptTemplateJson.d.ts +8 -1
  120. package/umd/typings/types/PromptbookJson/PromptbookJson.d.ts +2 -1
  121. package/umd/typings/types/TaskProgress.d.ts +2 -1
  122. package/umd/typings/types/execution-report/ExecutionReportJson.d.ts +2 -1
  123. package/umd/typings/types/execution-report/countWorkingDuration.d.ts +1 -1
  124. package/umd/typings/utils/emojis.d.ts +1 -1
  125. package/umd/typings/utils/expectation-counters/index.d.ts +2 -1
  126. package/umd/typings/utils/extractParameters.d.ts +2 -1
  127. package/umd/typings/utils/markdown/addAutoGeneratedSection.d.ts +2 -1
  128. package/umd/typings/utils/markdown/createMarkdownChart.d.ts +2 -2
  129. package/umd/typings/utils/markdown/createMarkdownTable.d.ts +2 -1
  130. package/umd/typings/utils/markdown/escapeMarkdownBlock.d.ts +1 -1
  131. package/umd/typings/utils/markdown/extractAllListItemsFromMarkdown.d.ts +2 -1
  132. package/umd/typings/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  133. package/umd/typings/utils/markdown/removeContentComments.d.ts +2 -1
  134. package/umd/typings/utils/markdown/removeMarkdownFormatting.d.ts +1 -1
  135. package/umd/typings/utils/markdown-json/countMarkdownStructureDeepness.d.ts +1 -1
  136. package/umd/typings/utils/markdown-json/markdownToMarkdownStructure.d.ts +1 -1
  137. package/umd/typings/utils/normalization/isValidKeyword.d.ts +1 -1
  138. package/umd/typings/utils/normalization/parseKeywords.d.ts +1 -1
  139. package/umd/typings/utils/normalization/parseKeywordsFromString.d.ts +1 -1
  140. package/umd/typings/utils/normalization/searchKeywords.d.ts +1 -1
  141. package/umd/typings/utils/postprocessing/extractBlock.d.ts +1 -1
package/esm/index.es.js CHANGED
@@ -448,7 +448,7 @@ function union() {
448
448
  /**
449
449
  * The version of the Promptbook library
450
450
  */
451
- var PROMPTBOOK_VERSION = '0.52.0-33';
451
+ var PROMPTBOOK_VERSION = '0.52.0';
452
452
 
453
453
  /**
454
454
  * Parses the template and returns the list of all parameter names
@@ -570,88 +570,108 @@ function extractParametersFromPromptTemplate(promptTemplate) {
570
570
  * TODO: [🔣] If script require contentLanguage
571
571
  */
572
572
 
573
+ /* tslint:disable */
574
+ /*
575
+ TODO: Tests
576
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
577
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
578
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
579
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
580
+ */
581
+ function normalizeTo_SCREAMING_CASE(sentence) {
582
+ var e_1, _a;
583
+ var charType;
584
+ var lastCharType = 'OTHER';
585
+ var normalizedName = '';
586
+ try {
587
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
588
+ var char = sentence_1_1.value;
589
+ var normalizedChar = void 0;
590
+ if (/^[a-z]$/.test(char)) {
591
+ charType = 'LOWERCASE';
592
+ normalizedChar = char.toUpperCase();
593
+ }
594
+ else if (/^[A-Z]$/.test(char)) {
595
+ charType = 'UPPERCASE';
596
+ normalizedChar = char;
597
+ }
598
+ else if (/^[0-9]$/.test(char)) {
599
+ charType = 'NUMBER';
600
+ normalizedChar = char;
601
+ }
602
+ else if (/^\/$/.test(char)) {
603
+ charType = 'SLASH';
604
+ normalizedChar = char;
605
+ }
606
+ else {
607
+ charType = 'OTHER';
608
+ normalizedChar = '_';
609
+ }
610
+ if (charType !== lastCharType &&
611
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
612
+ !(lastCharType === 'NUMBER') &&
613
+ !(charType === 'NUMBER')) {
614
+ normalizedName += '_';
615
+ }
616
+ normalizedName += normalizedChar;
617
+ lastCharType = charType;
618
+ }
619
+ }
620
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
621
+ finally {
622
+ try {
623
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
624
+ }
625
+ finally { if (e_1) throw e_1.error; }
626
+ }
627
+ normalizedName = normalizedName.replace(/_+/g, '_');
628
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
629
+ normalizedName = normalizedName.replace(/^_/, '');
630
+ normalizedName = normalizedName.replace(/_$/, '');
631
+ return normalizedName;
632
+ }
573
633
  /**
574
- * Removes emojis from a string and fix whitespaces
634
+ * TODO: [🌺] Use some intermediate util splitWords
635
+ */
636
+
637
+ /**
638
+ * Execution type describes the way how the block is executed
575
639
  *
576
- * @param text with emojis
577
- * @returns text without emojis
640
+ * @see https://github.com/webgptorg/promptbook#execution-type
578
641
  */
579
- function removeEmojis(text) {
580
- // Replace emojis (and also ZWJ sequence) with hyphens
581
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
582
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
583
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
584
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
585
- return text;
586
- }
642
+ var ExecutionTypes = [
643
+ 'PROMPT_TEMPLATE',
644
+ 'SIMPLE_TEMPLATE',
645
+ 'SCRIPT',
646
+ 'PROMPT_DIALOG',
647
+ // <- [🥻] Insert here when making new command
648
+ ];
587
649
 
588
650
  /**
589
- * Function normalizes title to name which can be used as identifier
651
+ * Units of text measurement
652
+ */
653
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
654
+ /**
655
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
656
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
657
+ * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
590
658
  */
591
- function titleToName(value) {
592
- value = removeEmojis(value);
593
- value = normalizeToKebabCase(value);
594
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
595
- return value;
596
- }
597
659
 
598
660
  /**
599
- * Creates a Mermaid graph based on the promptbook
661
+ * Removes Markdown formatting tags from a string.
600
662
  *
601
- * Note: The result is not wrapped in a Markdown code block
663
+ * @param {string} str - The string to remove Markdown tags from.
664
+ * @returns {string} The input string with all Markdown tags removed.
602
665
  */
603
- function renderPromptbookMermaid(promptbookJson, options) {
604
- var _a = (options || {}).linkPromptTemplate, linkPromptTemplate = _a === void 0 ? function () { return null; } : _a;
605
- var parameterNameToTemplateName = function (parameterName) {
606
- var parameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
607
- if (!parameter) {
608
- throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
609
- }
610
- if (parameter.isInput) {
611
- return 'input';
612
- }
613
- var template = promptbookJson.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
614
- if (!template) {
615
- throw new Error("Could not find template for {".concat(parameterName, "}"));
616
- }
617
- return normalizeTo_camelCase('template-' + titleToName(template.title));
618
- };
619
- var promptbookMermaid = spaceTrim(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
620
- .flatMap(function (_a) {
621
- var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
622
- return __spreadArray([
623
- "".concat(parameterNameToTemplateName(resultingParameterName), "(\"").concat(title, "\")")
624
- ], __read(dependentParameterNames.map(function (dependentParameterName) {
625
- return "".concat(parameterNameToTemplateName(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName(resultingParameterName));
626
- })), false);
627
- })
628
- .join('\n')), "\n\n ").concat(block(promptbookJson.parameters
629
- .filter(function (_a) {
630
- var isOutput = _a.isOutput;
631
- return isOutput;
632
- })
633
- .map(function (_a) {
634
- var name = _a.name;
635
- return "".concat(parameterNameToTemplateName(name), "--\"{").concat(name, "}\"-->output");
636
- })
637
- .join('\n')), "\n output((Output)):::output\n\n ").concat(block(promptbookJson.promptTemplates
638
- .map(function (promptTemplate) {
639
- var link = linkPromptTemplate(promptTemplate);
640
- if (link === null) {
641
- return '';
642
- }
643
- var href = link.href, title = link.title;
644
- var templateName = parameterNameToTemplateName(promptTemplate.resultingParameterName);
645
- return "click ".concat(templateName, " href \"").concat(href, "\" \"").concat(title, "\";");
646
- })
647
- .filter(function (line) { return line !== ''; })
648
- .join('\n')), "\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n "); });
649
- return promptbookMermaid;
666
+ function removeMarkdownFormatting(str) {
667
+ // Remove bold formatting
668
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
669
+ // Remove italic formatting
670
+ str = str.replace(/\*(.*?)\*/g, '$1');
671
+ // Remove code formatting
672
+ str = str.replace(/`(.*?)`/g, '$1');
673
+ return str;
650
674
  }
651
- /**
652
- * TODO: Maybe use some Mermaid library instead of string templating
653
- * TODO: [🕌] When more than 2 functionalities, split into separate functions
654
- */
655
675
 
656
676
  /**
657
677
  * Function parseNumber will parse number from string
@@ -721,146 +741,249 @@ function parseNumber(value) {
721
741
  */
722
742
 
723
743
  /**
724
- * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
725
- */
726
- var PromptbookLogicError = /** @class */ (function (_super) {
727
- __extends(PromptbookLogicError, _super);
728
- function PromptbookLogicError(message) {
729
- var _this = _super.call(this, message) || this;
730
- _this.name = 'PromptbookLogicError';
731
- Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
732
- return _this;
733
- }
734
- return PromptbookLogicError;
735
- }(Error));
736
-
737
- /**
738
- * This error occurs during the parameter replacement in the template
739
- *
740
- * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
741
- */
742
- var TemplateError = /** @class */ (function (_super) {
743
- __extends(TemplateError, _super);
744
- function TemplateError(message) {
745
- var _this = _super.call(this, message) || this;
746
- _this.name = 'TemplateError';
747
- Object.setPrototypeOf(_this, TemplateError.prototype);
748
- return _this;
749
- }
750
- return TemplateError;
751
- }(Error));
752
-
753
- /**
754
- * Replaces parameters in template with values from parameters object
744
+ * Parses one line of ul/ol to command
755
745
  *
756
- * @param template the template with parameters in {curly} braces
757
- * @param parameters the object with parameters
758
- * @returns the template with replaced parameters
759
- * @throws {TemplateError} if parameter is not defined, not closed, or not opened
746
+ * @returns parsed command object
747
+ * @throws {PromptbookSyntaxError} if the command is invalid
760
748
  *
761
- * @private within the createPromptbookExecutor
749
+ * @private within the promptbookStringToJson
762
750
  */
763
- function replaceParameters(template, parameters) {
764
- var replacedTemplate = template;
765
- var match;
766
- var loopLimit = LOOP_LIMIT;
767
- var _loop_1 = function () {
768
- if (loopLimit-- < 0) {
769
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
770
- }
771
- var precol = match.groups.precol;
772
- var parameterName = match.groups.parameterName;
773
- if (parameterName === '') {
774
- return "continue";
751
+ function parseCommand(listItem) {
752
+ var e_1, _a;
753
+ if (listItem.includes('\n') || listItem.includes('\r')) {
754
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
755
+ }
756
+ var type = listItem.trim();
757
+ type = type.split('`').join('');
758
+ type = type.split('"').join('');
759
+ type = type.split("'").join('');
760
+ type = type.split('~').join('');
761
+ type = type.split('[').join('');
762
+ type = type.split(']').join('');
763
+ type = type.split('(').join('');
764
+ type = type.split(')').join('');
765
+ type = normalizeTo_SCREAMING_CASE(type);
766
+ type = type.split('DIALOGUE').join('DIALOG');
767
+ var listItemParts = listItem
768
+ .split(' ')
769
+ .map(function (part) { return part.trim(); })
770
+ .filter(function (item) { return item !== ''; })
771
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
772
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
773
+ .map(removeMarkdownFormatting);
774
+ if (type.startsWith('URL') ||
775
+ type.startsWith('PTBK_URL') ||
776
+ type.startsWith('PTBKURL') ||
777
+ type.startsWith('PROMPTBOOK_URL') ||
778
+ type.startsWith('PROMPTBOOKURL') ||
779
+ type.startsWith('HTTPS')) {
780
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
781
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
775
782
  }
776
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
777
- throw new TemplateError('Parameter is already opened or not closed');
783
+ var promptbookUrlString = listItemParts.pop();
784
+ var promptbookUrl = new URL(promptbookUrlString);
785
+ if (promptbookUrl.protocol !== 'https:') {
786
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
778
787
  }
779
- if (parameters[parameterName] === undefined) {
780
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
788
+ if (promptbookUrl.hash !== '') {
789
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
781
790
  }
782
- var parameterValue = parameters[parameterName];
783
- if (parameterValue === undefined) {
784
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
791
+ return {
792
+ type: 'PROMPTBOOK_URL',
793
+ promptbookUrl: promptbookUrl,
794
+ };
795
+ }
796
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
797
+ if (listItemParts.length !== 2) {
798
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
785
799
  }
786
- parameterValue = parameterValue.toString();
787
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
788
- parameterValue = parameterValue
789
- .split('\n')
790
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
791
- .join('\n');
800
+ var promptbookVersion = listItemParts.pop();
801
+ // TODO: Validate version
802
+ return {
803
+ type: 'PROMPTBOOK_VERSION',
804
+ promptbookVersion: promptbookVersion,
805
+ };
806
+ }
807
+ else if (type.startsWith('EXECUTE') ||
808
+ type.startsWith('EXEC') ||
809
+ type.startsWith('PROMPT_DIALOG') ||
810
+ type.startsWith('SIMPLE_TEMPLATE')) {
811
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
812
+ if (executionTypes.length !== 1) {
813
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
792
814
  }
793
- replacedTemplate =
794
- replacedTemplate.substring(0, match.index + precol.length) +
795
- parameterValue +
796
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
797
- };
798
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
799
- .exec(replacedTemplate))) {
800
- _loop_1();
815
+ return {
816
+ type: 'EXECUTE',
817
+ executionType: executionTypes[0],
818
+ };
801
819
  }
802
- // [💫] Check if there are parameters that are not closed properly
803
- if (/{\w+$/.test(replacedTemplate)) {
804
- throw new TemplateError('Parameter is not closed');
820
+ else if (type.startsWith('MODEL')) {
821
+ // TODO: Make this more elegant and dynamically
822
+ if (type.startsWith('MODEL_VARIANT')) {
823
+ if (type === 'MODEL_VARIANT_CHAT') {
824
+ return {
825
+ type: 'MODEL',
826
+ key: 'modelVariant',
827
+ value: 'CHAT',
828
+ };
829
+ }
830
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
831
+ return {
832
+ type: 'MODEL',
833
+ key: 'modelVariant',
834
+ value: 'COMPLETION',
835
+ };
836
+ }
837
+ else {
838
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
839
+ }
840
+ }
841
+ if (type.startsWith('MODEL_NAME')) {
842
+ return {
843
+ type: 'MODEL',
844
+ key: 'modelName',
845
+ value: listItemParts.pop(),
846
+ };
847
+ }
848
+ else {
849
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
850
+ }
805
851
  }
806
- // [💫] Check if there are parameters that are not opened properly
807
- if (/^\w+}/.test(replacedTemplate)) {
808
- throw new TemplateError('Parameter is not opened');
852
+ else if (type.startsWith('PARAM') ||
853
+ type.startsWith('INPUT_PARAM') ||
854
+ type.startsWith('OUTPUT_PARAM') ||
855
+ listItem.startsWith('{') ||
856
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
857
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
858
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
859
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
860
+ }
861
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
862
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
863
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
864
+ throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
865
+ }
866
+ var isInput = type.startsWith('INPUT');
867
+ var isOutput = type.startsWith('OUTPUT');
868
+ if (listItem.startsWith('> {')) {
869
+ isInput = false;
870
+ isOutput = false;
871
+ }
872
+ return {
873
+ type: 'PARAMETER',
874
+ parameterName: parameterName,
875
+ parameterDescription: parameterDescription.trim() || null,
876
+ isInput: isInput,
877
+ isOutput: isOutput,
878
+ };
809
879
  }
810
- return replacedTemplate;
811
- }
812
-
813
- /**
814
- * Counts number of characters in the text
815
- */
816
- function countCharacters(text) {
817
- // Remove null characters
818
- text = text.replace(/\0/g, '');
819
- // Replace emojis (and also ZWJ sequence) with hyphens
820
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
821
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
822
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
823
- return text.length;
824
- }
825
-
826
- /**
827
- * Counts number of lines in the text
828
- */
829
- function countLines(text) {
830
- if (text === '') {
831
- return 0;
880
+ else if (type.startsWith('JOKER')) {
881
+ if (listItemParts.length !== 2) {
882
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
883
+ }
884
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
885
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
886
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
887
+ }
888
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
889
+ var parameterName = parametersMatch.groups.parameterName;
890
+ return {
891
+ type: 'JOKER',
892
+ parameterName: parameterName,
893
+ };
894
+ }
895
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
896
+ if (listItemParts.length !== 2) {
897
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
898
+ }
899
+ var functionName = listItemParts.pop();
900
+ return {
901
+ type: 'POSTPROCESS',
902
+ functionName: functionName,
903
+ };
904
+ }
905
+ else if (type.startsWith('EXPECT_JSON')) {
906
+ return {
907
+ type: 'EXPECT_FORMAT',
908
+ format: 'JSON',
909
+ };
910
+ // [🥤]
911
+ }
912
+ else if (type.startsWith('EXPECT')) {
913
+ try {
914
+ listItemParts.shift();
915
+ var sign = void 0;
916
+ var signRaw = listItemParts.shift();
917
+ if (/^exact/i.test(signRaw)) {
918
+ sign = 'EXACTLY';
919
+ }
920
+ else if (/^min/i.test(signRaw)) {
921
+ sign = 'MINIMUM';
922
+ }
923
+ else if (/^max/i.test(signRaw)) {
924
+ sign = 'MAXIMUM';
925
+ }
926
+ else {
927
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
928
+ }
929
+ var amountRaw = listItemParts.shift();
930
+ var amount = parseNumber(amountRaw);
931
+ if (amount < 0) {
932
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
933
+ }
934
+ if (amount !== Math.floor(amount)) {
935
+ throw new PromptbookSyntaxError('Amount must be whole number');
936
+ }
937
+ var unitRaw = listItemParts.shift();
938
+ var unit = undefined;
939
+ try {
940
+ for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
941
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
942
+ var existingUnitText = existingUnit;
943
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
944
+ if (existingUnitText === 'CHARACTER') {
945
+ existingUnitText = 'CHAR';
946
+ }
947
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
948
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
949
+ if (unit !== undefined) {
950
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
951
+ }
952
+ unit = existingUnit;
953
+ }
954
+ }
955
+ }
956
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
957
+ finally {
958
+ try {
959
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
960
+ }
961
+ finally { if (e_1) throw e_1.error; }
962
+ }
963
+ if (unit === undefined) {
964
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
965
+ }
966
+ return {
967
+ type: 'EXPECT_AMOUNT',
968
+ sign: sign,
969
+ unit: unit,
970
+ amount: amount,
971
+ };
972
+ }
973
+ catch (error) {
974
+ if (!(error instanceof Error)) {
975
+ throw error;
976
+ }
977
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
978
+ }
979
+ /*
980
+ } else if (type.startsWith('__________________')) {
981
+ // <- [🥻] Insert here when making new command
982
+ */
983
+ }
984
+ else {
985
+ throw new PromptbookSyntaxError(spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
832
986
  }
833
- return text.split('\n').length;
834
- }
835
-
836
- /**
837
- * Counts number of pages in the text
838
- */
839
- function countPages(text) {
840
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
841
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
842
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
843
- return pageCount;
844
- }
845
-
846
- /**
847
- * Counts number of paragraphs in the text
848
- */
849
- function countParagraphs(text) {
850
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
851
- }
852
-
853
- /**
854
- * Split text into sentences
855
- */
856
- function splitIntoSentences(text) {
857
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
858
- }
859
- /**
860
- * Counts number of sentences in the text
861
- */
862
- function countSentences(text) {
863
- return splitIntoSentences(text).length;
864
987
  }
865
988
 
866
989
  var defaultDiacriticsRemovalMap = [
@@ -1115,187 +1238,12 @@ function removeDiacritics(input) {
1115
1238
  });
1116
1239
  }
1117
1240
 
1118
- /**
1119
- * Counts number of words in the text
1120
- */
1121
- function countWords(text) {
1122
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
1123
- text = removeDiacritics(text);
1124
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
1125
- }
1126
-
1127
- /**
1128
- * Index of all counter functions
1129
- */
1130
- var CountUtils = {
1131
- CHARACTERS: countCharacters,
1132
- WORDS: countWords,
1133
- SENTENCES: countSentences,
1134
- PARAGRAPHS: countParagraphs,
1135
- LINES: countLines,
1136
- PAGES: countPages,
1137
- };
1138
-
1139
- /**
1140
- * Function isValidJsonString will tell you if the string is valid JSON or not
1141
- */
1142
- function isValidJsonString(value) {
1143
- try {
1144
- JSON.parse(value);
1145
- return true;
1146
- }
1147
- catch (error) {
1148
- if (!(error instanceof Error)) {
1149
- throw error;
1150
- }
1151
- if (error.message.includes('Unexpected token')) {
1152
- return false;
1153
- }
1154
- return false;
1155
- }
1156
- }
1157
-
1158
- /**
1159
- * Removes Markdown formatting tags from a string.
1160
- *
1161
- * @param {string} str - The string to remove Markdown tags from.
1162
- * @returns {string} The input string with all Markdown tags removed.
1163
- */
1164
- function removeMarkdownFormatting(str) {
1165
- // Remove bold formatting
1166
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
1167
- // Remove italic formatting
1168
- str = str.replace(/\*(.*?)\*/g, '$1');
1169
- // Remove code formatting
1170
- str = str.replace(/`(.*?)`/g, '$1');
1171
- return str;
1172
- }
1173
-
1174
- /* tslint:disable */
1175
- /*
1176
- TODO: Tests
1177
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
1178
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
1179
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
1180
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
1181
- */
1182
- function normalizeTo_SCREAMING_CASE(sentence) {
1183
- var e_1, _a;
1184
- var charType;
1185
- var lastCharType = 'OTHER';
1186
- var normalizedName = '';
1187
- try {
1188
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1189
- var char = sentence_1_1.value;
1190
- var normalizedChar = void 0;
1191
- if (/^[a-z]$/.test(char)) {
1192
- charType = 'LOWERCASE';
1193
- normalizedChar = char.toUpperCase();
1194
- }
1195
- else if (/^[A-Z]$/.test(char)) {
1196
- charType = 'UPPERCASE';
1197
- normalizedChar = char;
1198
- }
1199
- else if (/^[0-9]$/.test(char)) {
1200
- charType = 'NUMBER';
1201
- normalizedChar = char;
1202
- }
1203
- else if (/^\/$/.test(char)) {
1204
- charType = 'SLASH';
1205
- normalizedChar = char;
1206
- }
1207
- else {
1208
- charType = 'OTHER';
1209
- normalizedChar = '_';
1210
- }
1211
- if (charType !== lastCharType &&
1212
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1213
- !(lastCharType === 'NUMBER') &&
1214
- !(charType === 'NUMBER')) {
1215
- normalizedName += '_';
1216
- }
1217
- normalizedName += normalizedChar;
1218
- lastCharType = charType;
1219
- }
1220
- }
1221
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1222
- finally {
1223
- try {
1224
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1225
- }
1226
- finally { if (e_1) throw e_1.error; }
1227
- }
1228
- normalizedName = normalizedName.replace(/_+/g, '_');
1229
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
1230
- normalizedName = normalizedName.replace(/^_/, '');
1231
- normalizedName = normalizedName.replace(/_$/, '');
1232
- return normalizedName;
1233
- }
1234
- /**
1235
- * TODO: [🌺] Use some intermediate util splitWords
1236
- */
1237
-
1238
1241
  /* tslint:disable */
1239
1242
  function normalizeToKebabCase(sentence) {
1240
1243
  var e_1, _a;
1241
1244
  sentence = removeDiacritics(sentence);
1242
1245
  var charType;
1243
- var lastCharType = 'OTHER';
1244
- var normalizedName = '';
1245
- try {
1246
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1247
- var char = sentence_1_1.value;
1248
- var normalizedChar = void 0;
1249
- if (/^[a-z]$/.test(char)) {
1250
- charType = 'LOWERCASE';
1251
- normalizedChar = char;
1252
- }
1253
- else if (/^[A-Z]$/.test(char)) {
1254
- charType = 'UPPERCASE';
1255
- normalizedChar = char.toLowerCase();
1256
- }
1257
- else if (/^[0-9]$/.test(char)) {
1258
- charType = 'NUMBER';
1259
- normalizedChar = char;
1260
- }
1261
- else if (/^\/$/.test(char)) {
1262
- charType = 'SLASH';
1263
- normalizedChar = char;
1264
- }
1265
- else {
1266
- charType = 'OTHER';
1267
- normalizedChar = '-';
1268
- }
1269
- if (charType !== lastCharType &&
1270
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1271
- !(lastCharType === 'NUMBER') &&
1272
- !(charType === 'NUMBER')) {
1273
- normalizedName += '-';
1274
- }
1275
- normalizedName += normalizedChar;
1276
- lastCharType = charType;
1277
- }
1278
- }
1279
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1280
- finally {
1281
- try {
1282
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1283
- }
1284
- finally { if (e_1) throw e_1.error; }
1285
- }
1286
- normalizedName = normalizedName.split(/-+/g).join('-');
1287
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1288
- normalizedName = normalizedName.replace(/^-/, '');
1289
- normalizedName = normalizedName.replace(/-$/, '');
1290
- return normalizedName;
1291
- }
1292
-
1293
- /* tslint:disable */
1294
- function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1295
- var e_1, _a;
1296
- if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1297
- var charType;
1298
- var lastCharType = null;
1246
+ var lastCharType = 'OTHER';
1299
1247
  var normalizedName = '';
1300
1248
  try {
1301
1249
  for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
@@ -1307,311 +1255,67 @@ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1307
1255
  }
1308
1256
  else if (/^[A-Z]$/.test(char)) {
1309
1257
  charType = 'UPPERCASE';
1310
- normalizedChar = char.toLowerCase();
1311
- }
1312
- else if (/^[0-9]$/.test(char)) {
1313
- charType = 'NUMBER';
1314
- normalizedChar = char;
1315
- }
1316
- else {
1317
- charType = 'OTHER';
1318
- normalizedChar = '';
1319
- }
1320
- if (!lastCharType) {
1321
- if (__firstLetterCapital) {
1322
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1323
- }
1324
- }
1325
- else if (charType !== lastCharType &&
1326
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1327
- !(lastCharType === 'NUMBER') &&
1328
- !(charType === 'NUMBER')) {
1329
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1330
- }
1331
- normalizedName += normalizedChar;
1332
- lastCharType = charType;
1333
- }
1334
- }
1335
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1336
- finally {
1337
- try {
1338
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1339
- }
1340
- finally { if (e_1) throw e_1.error; }
1341
- }
1342
- return normalizedName;
1343
- }
1344
- /**
1345
- * TODO: [🌺] Use some intermediate util splitWords
1346
- */
1347
-
1348
- /**
1349
- * Execution type describes the way how the block is executed
1350
- *
1351
- * @see https://github.com/webgptorg/promptbook#execution-type
1352
- */
1353
- var ExecutionTypes = [
1354
- 'PROMPT_TEMPLATE',
1355
- 'SIMPLE_TEMPLATE',
1356
- 'SCRIPT',
1357
- 'PROMPT_DIALOG',
1358
- // <- [🥻] Insert here when making new command
1359
- ];
1360
-
1361
- /**
1362
- * Units of text measurement
1363
- */
1364
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
1365
- /**
1366
- * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
1367
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
1368
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
1369
- */
1370
-
1371
- /**
1372
- * Parses one line of ul/ol to command
1373
- *
1374
- * @returns parsed command object
1375
- * @throws {PromptbookSyntaxError} if the command is invalid
1376
- *
1377
- * @private within the promptbookStringToJson
1378
- */
1379
- function parseCommand(listItem) {
1380
- var e_1, _a;
1381
- if (listItem.includes('\n') || listItem.includes('\r')) {
1382
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
1383
- }
1384
- var type = listItem.trim();
1385
- type = type.split('`').join('');
1386
- type = type.split('"').join('');
1387
- type = type.split("'").join('');
1388
- type = type.split('~').join('');
1389
- type = type.split('[').join('');
1390
- type = type.split(']').join('');
1391
- type = type.split('(').join('');
1392
- type = type.split(')').join('');
1393
- type = normalizeTo_SCREAMING_CASE(type);
1394
- type = type.split('DIALOGUE').join('DIALOG');
1395
- var listItemParts = listItem
1396
- .split(' ')
1397
- .map(function (part) { return part.trim(); })
1398
- .filter(function (item) { return item !== ''; })
1399
- .filter(function (item) { return !/^PTBK$/i.test(item); })
1400
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
1401
- .map(removeMarkdownFormatting);
1402
- if (type.startsWith('URL') ||
1403
- type.startsWith('PTBK_URL') ||
1404
- type.startsWith('PTBKURL') ||
1405
- type.startsWith('PROMPTBOOK_URL') ||
1406
- type.startsWith('PROMPTBOOKURL') ||
1407
- type.startsWith('HTTPS')) {
1408
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
1409
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
1410
- }
1411
- var promptbookUrlString = listItemParts.pop();
1412
- var promptbookUrl = new URL(promptbookUrlString);
1413
- if (promptbookUrl.protocol !== 'https:') {
1414
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
1415
- }
1416
- if (promptbookUrl.hash !== '') {
1417
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
1418
- }
1419
- return {
1420
- type: 'PROMPTBOOK_URL',
1421
- promptbookUrl: promptbookUrl,
1422
- };
1423
- }
1424
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
1425
- if (listItemParts.length !== 2) {
1426
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
1427
- }
1428
- var promptbookVersion = listItemParts.pop();
1429
- // TODO: Validate version
1430
- return {
1431
- type: 'PROMPTBOOK_VERSION',
1432
- promptbookVersion: promptbookVersion,
1433
- };
1434
- }
1435
- else if (type.startsWith('EXECUTE') ||
1436
- type.startsWith('EXEC') ||
1437
- type.startsWith('PROMPT_DIALOG') ||
1438
- type.startsWith('SIMPLE_TEMPLATE')) {
1439
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
1440
- if (executionTypes.length !== 1) {
1441
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
1442
- }
1443
- return {
1444
- type: 'EXECUTE',
1445
- executionType: executionTypes[0],
1446
- };
1447
- }
1448
- else if (type.startsWith('MODEL')) {
1449
- // TODO: Make this more elegant and dynamically
1450
- if (type.startsWith('MODEL_VARIANT')) {
1451
- if (type === 'MODEL_VARIANT_CHAT') {
1452
- return {
1453
- type: 'MODEL',
1454
- key: 'modelVariant',
1455
- value: 'CHAT',
1456
- };
1457
- }
1458
- else if (type === 'MODEL_VARIANT_COMPLETION') {
1459
- return {
1460
- type: 'MODEL',
1461
- key: 'modelVariant',
1462
- value: 'COMPLETION',
1463
- };
1464
- }
1465
- else {
1466
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
1467
- }
1468
- }
1469
- if (type.startsWith('MODEL_NAME')) {
1470
- return {
1471
- type: 'MODEL',
1472
- key: 'modelName',
1473
- value: listItemParts.pop(),
1474
- };
1475
- }
1476
- else {
1477
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
1478
- }
1479
- }
1480
- else if (type.startsWith('PARAM') ||
1481
- type.startsWith('INPUT_PARAM') ||
1482
- type.startsWith('OUTPUT_PARAM') ||
1483
- listItem.startsWith('{') ||
1484
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
1485
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
1486
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1487
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1488
- }
1489
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1490
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
1491
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
1492
- throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
1493
- }
1494
- var isInput = type.startsWith('INPUT');
1495
- var isOutput = type.startsWith('OUTPUT');
1496
- if (listItem.startsWith('> {')) {
1497
- isInput = false;
1498
- isOutput = false;
1499
- }
1500
- return {
1501
- type: 'PARAMETER',
1502
- parameterName: parameterName,
1503
- parameterDescription: parameterDescription.trim() || null,
1504
- isInput: isInput,
1505
- isOutput: isOutput,
1506
- };
1507
- }
1508
- else if (type.startsWith('JOKER')) {
1509
- if (listItemParts.length !== 2) {
1510
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
1511
- }
1512
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
1513
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1514
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1515
- }
1516
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1517
- var parameterName = parametersMatch.groups.parameterName;
1518
- return {
1519
- type: 'JOKER',
1520
- parameterName: parameterName,
1521
- };
1522
- }
1523
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
1524
- if (listItemParts.length !== 2) {
1525
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
1526
- }
1527
- var functionName = listItemParts.pop();
1528
- return {
1529
- type: 'POSTPROCESS',
1530
- functionName: functionName,
1531
- };
1532
- }
1533
- else if (type.startsWith('EXPECT_JSON')) {
1534
- return {
1535
- type: 'EXPECT_FORMAT',
1536
- format: 'JSON',
1537
- };
1538
- // [🥤]
1539
- }
1540
- else if (type.startsWith('EXPECT')) {
1541
- try {
1542
- listItemParts.shift();
1543
- var sign = void 0;
1544
- var signRaw = listItemParts.shift();
1545
- if (/^exact/i.test(signRaw)) {
1546
- sign = 'EXACTLY';
1547
- }
1548
- else if (/^min/i.test(signRaw)) {
1549
- sign = 'MINIMUM';
1550
- }
1551
- else if (/^max/i.test(signRaw)) {
1552
- sign = 'MAXIMUM';
1553
- }
1554
- else {
1555
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
1556
- }
1557
- var amountRaw = listItemParts.shift();
1558
- var amount = parseNumber(amountRaw);
1559
- if (amount < 0) {
1560
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
1561
- }
1562
- if (amount !== Math.floor(amount)) {
1563
- throw new PromptbookSyntaxError('Amount must be whole number');
1258
+ normalizedChar = char.toLowerCase();
1564
1259
  }
1565
- var unitRaw = listItemParts.shift();
1566
- var unit = undefined;
1567
- try {
1568
- for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
1569
- var existingUnit = EXPECTATION_UNITS_1_1.value;
1570
- var existingUnitText = existingUnit;
1571
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
1572
- if (existingUnitText === 'CHARACTER') {
1573
- existingUnitText = 'CHAR';
1574
- }
1575
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
1576
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
1577
- if (unit !== undefined) {
1578
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
1579
- }
1580
- unit = existingUnit;
1581
- }
1582
- }
1260
+ else if (/^[0-9]$/.test(char)) {
1261
+ charType = 'NUMBER';
1262
+ normalizedChar = char;
1583
1263
  }
1584
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1585
- finally {
1586
- try {
1587
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
1588
- }
1589
- finally { if (e_1) throw e_1.error; }
1264
+ else if (/^\/$/.test(char)) {
1265
+ charType = 'SLASH';
1266
+ normalizedChar = char;
1590
1267
  }
1591
- if (unit === undefined) {
1592
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
1268
+ else {
1269
+ charType = 'OTHER';
1270
+ normalizedChar = '-';
1593
1271
  }
1594
- return {
1595
- type: 'EXPECT_AMOUNT',
1596
- sign: sign,
1597
- unit: unit,
1598
- amount: amount,
1599
- };
1600
- }
1601
- catch (error) {
1602
- if (!(error instanceof Error)) {
1603
- throw error;
1272
+ if (charType !== lastCharType &&
1273
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1274
+ !(lastCharType === 'NUMBER') &&
1275
+ !(charType === 'NUMBER')) {
1276
+ normalizedName += '-';
1604
1277
  }
1605
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1278
+ normalizedName += normalizedChar;
1279
+ lastCharType = charType;
1606
1280
  }
1607
- /*
1608
- } else if (type.startsWith('__________________')) {
1609
- // <- [🥻] Insert here when making new command
1610
- */
1611
1281
  }
1612
- else {
1613
- throw new PromptbookSyntaxError(spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
1282
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1283
+ finally {
1284
+ try {
1285
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1286
+ }
1287
+ finally { if (e_1) throw e_1.error; }
1614
1288
  }
1289
+ normalizedName = normalizedName.split(/-+/g).join('-');
1290
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1291
+ normalizedName = normalizedName.replace(/^-/, '');
1292
+ normalizedName = normalizedName.replace(/-$/, '');
1293
+ return normalizedName;
1294
+ }
1295
+
1296
+ /**
1297
+ * Removes emojis from a string and fix whitespaces
1298
+ *
1299
+ * @param text with emojis
1300
+ * @returns text without emojis
1301
+ */
1302
+ function removeEmojis(text) {
1303
+ // Replace emojis (and also ZWJ sequence) with hyphens
1304
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1305
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1306
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1307
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
1308
+ return text;
1309
+ }
1310
+
1311
+ /**
1312
+ * Function normalizes title to name which can be used as identifier
1313
+ */
1314
+ function titleToName(value) {
1315
+ value = removeEmojis(value);
1316
+ value = normalizeToKebabCase(value);
1317
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
1318
+ return value;
1615
1319
  }
1616
1320
 
1617
1321
  /**
@@ -1855,69 +1559,182 @@ function promptbookStringToJson(promptbookString) {
1855
1559
  try {
1856
1560
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1857
1561
  }
1858
- finally { if (e_2) throw e_2.error; }
1859
- }
1860
- // =============================================================
1861
- return promptbookJson;
1862
- }
1863
- /**
1864
- * TODO: Report here line/column of error
1865
- * TODO: Use spaceTrim more effectively
1866
- * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1867
- */
1868
-
1869
- /**
1870
- * Add or modify an auto-generated section in a markdown file
1871
- *
1872
- * @private within the library
1873
- */
1874
- function addAutoGeneratedSection(content, options) {
1875
- var sectionName = options.sectionName, sectionContent = options.sectionContent;
1876
- var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1877
- var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1878
- var sectionMatch = content.match(sectionRegex);
1879
- if (sectionMatch) {
1880
- return content.replace(sectionRegex, spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1881
- }
1882
- var placeForSection = removeContentComments(content).match(/^##.*$/im);
1883
- if (!placeForSection) {
1884
- throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1885
- }
1886
- var _a = __read(placeForSection, 1), heading = _a[0];
1887
- return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1562
+ finally { if (e_2) throw e_2.error; }
1563
+ }
1564
+ // =============================================================
1565
+ return promptbookJson;
1566
+ }
1567
+ /**
1568
+ * TODO: Report here line/column of error
1569
+ * TODO: Use spaceTrim more effectively
1570
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1571
+ */
1572
+
1573
+ /**
1574
+ * Add or modify an auto-generated section in a markdown file
1575
+ *
1576
+ * @private within the library
1577
+ */
1578
+ function addAutoGeneratedSection(content, options) {
1579
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
1580
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1581
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1582
+ var sectionMatch = content.match(sectionRegex);
1583
+ if (sectionMatch) {
1584
+ return content.replace(sectionRegex, spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1585
+ }
1586
+ var placeForSection = removeContentComments(content).match(/^##.*$/im);
1587
+ if (!placeForSection) {
1588
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1589
+ }
1590
+ var _a = __read(placeForSection, 1), heading = _a[0];
1591
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1592
+ }
1593
+
1594
+ /**
1595
+ * Prettify the html code
1596
+ *
1597
+ * @param content raw html code
1598
+ * @returns formatted html code
1599
+ */
1600
+ function prettifyMarkdown(content) {
1601
+ try {
1602
+ return format(content, {
1603
+ parser: 'markdown',
1604
+ plugins: [parserHtml],
1605
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1606
+ endOfLine: 'lf',
1607
+ tabWidth: 4,
1608
+ singleQuote: true,
1609
+ trailingComma: 'all',
1610
+ arrowParens: 'always',
1611
+ printWidth: 120,
1612
+ htmlWhitespaceSensitivity: 'ignore',
1613
+ jsxBracketSameLine: false,
1614
+ bracketSpacing: true,
1615
+ });
1616
+ }
1617
+ catch (error) {
1618
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1619
+ error: error,
1620
+ html: content,
1621
+ });
1622
+ return content;
1623
+ }
1624
+ }
1625
+
1626
+ /* tslint:disable */
1627
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1628
+ var e_1, _a;
1629
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1630
+ var charType;
1631
+ var lastCharType = null;
1632
+ var normalizedName = '';
1633
+ try {
1634
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1635
+ var char = sentence_1_1.value;
1636
+ var normalizedChar = void 0;
1637
+ if (/^[a-z]$/.test(char)) {
1638
+ charType = 'LOWERCASE';
1639
+ normalizedChar = char;
1640
+ }
1641
+ else if (/^[A-Z]$/.test(char)) {
1642
+ charType = 'UPPERCASE';
1643
+ normalizedChar = char.toLowerCase();
1644
+ }
1645
+ else if (/^[0-9]$/.test(char)) {
1646
+ charType = 'NUMBER';
1647
+ normalizedChar = char;
1648
+ }
1649
+ else {
1650
+ charType = 'OTHER';
1651
+ normalizedChar = '';
1652
+ }
1653
+ if (!lastCharType) {
1654
+ if (__firstLetterCapital) {
1655
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1656
+ }
1657
+ }
1658
+ else if (charType !== lastCharType &&
1659
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1660
+ !(lastCharType === 'NUMBER') &&
1661
+ !(charType === 'NUMBER')) {
1662
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1663
+ }
1664
+ normalizedName += normalizedChar;
1665
+ lastCharType = charType;
1666
+ }
1667
+ }
1668
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1669
+ finally {
1670
+ try {
1671
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1672
+ }
1673
+ finally { if (e_1) throw e_1.error; }
1674
+ }
1675
+ return normalizedName;
1676
+ }
1677
+ /**
1678
+ * TODO: [🌺] Use some intermediate util splitWords
1679
+ */
1680
+
1681
+ /**
1682
+ * Creates a Mermaid graph based on the promptbook
1683
+ *
1684
+ * Note: The result is not wrapped in a Markdown code block
1685
+ */
1686
+ function renderPromptbookMermaid(promptbookJson, options) {
1687
+ var _a = (options || {}).linkPromptTemplate, linkPromptTemplate = _a === void 0 ? function () { return null; } : _a;
1688
+ var parameterNameToTemplateName = function (parameterName) {
1689
+ var parameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
1690
+ if (!parameter) {
1691
+ throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
1692
+ }
1693
+ if (parameter.isInput) {
1694
+ return 'input';
1695
+ }
1696
+ var template = promptbookJson.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
1697
+ if (!template) {
1698
+ throw new Error("Could not find template for {".concat(parameterName, "}"));
1699
+ }
1700
+ return normalizeTo_camelCase('template-' + titleToName(template.title));
1701
+ };
1702
+ var promptbookMermaid = spaceTrim(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
1703
+ .flatMap(function (_a) {
1704
+ var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
1705
+ return __spreadArray([
1706
+ "".concat(parameterNameToTemplateName(resultingParameterName), "(\"").concat(title, "\")")
1707
+ ], __read(dependentParameterNames.map(function (dependentParameterName) {
1708
+ return "".concat(parameterNameToTemplateName(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName(resultingParameterName));
1709
+ })), false);
1710
+ })
1711
+ .join('\n')), "\n\n ").concat(block(promptbookJson.parameters
1712
+ .filter(function (_a) {
1713
+ var isOutput = _a.isOutput;
1714
+ return isOutput;
1715
+ })
1716
+ .map(function (_a) {
1717
+ var name = _a.name;
1718
+ return "".concat(parameterNameToTemplateName(name), "--\"{").concat(name, "}\"-->output");
1719
+ })
1720
+ .join('\n')), "\n output((Output)):::output\n\n ").concat(block(promptbookJson.promptTemplates
1721
+ .map(function (promptTemplate) {
1722
+ var link = linkPromptTemplate(promptTemplate);
1723
+ if (link === null) {
1724
+ return '';
1725
+ }
1726
+ var href = link.href, title = link.title;
1727
+ var templateName = parameterNameToTemplateName(promptTemplate.resultingParameterName);
1728
+ return "click ".concat(templateName, " href \"").concat(href, "\" \"").concat(title, "\";");
1729
+ })
1730
+ .filter(function (line) { return line !== ''; })
1731
+ .join('\n')), "\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n "); });
1732
+ return promptbookMermaid;
1888
1733
  }
1889
-
1890
1734
  /**
1891
- * Prettify the html code
1892
- *
1893
- * @param content raw html code
1894
- * @returns formatted html code
1735
+ * TODO: Maybe use some Mermaid library instead of string templating
1736
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
1895
1737
  */
1896
- function prettifyMarkdown(content) {
1897
- try {
1898
- return format(content, {
1899
- parser: 'markdown',
1900
- plugins: [parserHtml],
1901
- // TODO: DRY - make some import or auto-copy of .prettierrc
1902
- endOfLine: 'lf',
1903
- tabWidth: 4,
1904
- singleQuote: true,
1905
- trailingComma: 'all',
1906
- arrowParens: 'always',
1907
- printWidth: 120,
1908
- htmlWhitespaceSensitivity: 'ignore',
1909
- jsxBracketSameLine: false,
1910
- bracketSpacing: true,
1911
- });
1912
- }
1913
- catch (error) {
1914
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1915
- error: error,
1916
- html: content,
1917
- });
1918
- return content;
1919
- }
1920
- }
1921
1738
 
1922
1739
  /**
1923
1740
  * Prettyfies Promptbook string and adds Mermaid graph
@@ -2133,6 +1950,20 @@ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
2133
1950
  * TODO: Escape all
2134
1951
  */
2135
1952
 
1953
+ /**
1954
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
1955
+ */
1956
+ var PromptbookLogicError = /** @class */ (function (_super) {
1957
+ __extends(PromptbookLogicError, _super);
1958
+ function PromptbookLogicError(message) {
1959
+ var _this = _super.call(this, message) || this;
1960
+ _this.name = 'PromptbookLogicError';
1961
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
1962
+ return _this;
1963
+ }
1964
+ return PromptbookLogicError;
1965
+ }(Error));
1966
+
2136
1967
  /**
2137
1968
  * Tests if given string is valid URL.
2138
1969
  *
@@ -2401,6 +2232,99 @@ var ExpectError = /** @class */ (function (_super) {
2401
2232
  return ExpectError;
2402
2233
  }(Error));
2403
2234
 
2235
+ /**
2236
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2237
+ */
2238
+ function isValidJsonString(value) {
2239
+ try {
2240
+ JSON.parse(value);
2241
+ return true;
2242
+ }
2243
+ catch (error) {
2244
+ if (!(error instanceof Error)) {
2245
+ throw error;
2246
+ }
2247
+ if (error.message.includes('Unexpected token')) {
2248
+ return false;
2249
+ }
2250
+ return false;
2251
+ }
2252
+ }
2253
+
2254
+ /**
2255
+ * Counts number of characters in the text
2256
+ */
2257
+ function countCharacters(text) {
2258
+ // Remove null characters
2259
+ text = text.replace(/\0/g, '');
2260
+ // Replace emojis (and also ZWJ sequence) with hyphens
2261
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2262
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2263
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
2264
+ return text.length;
2265
+ }
2266
+
2267
+ /**
2268
+ * Counts number of lines in the text
2269
+ */
2270
+ function countLines(text) {
2271
+ if (text === '') {
2272
+ return 0;
2273
+ }
2274
+ return text.split('\n').length;
2275
+ }
2276
+
2277
+ /**
2278
+ * Counts number of pages in the text
2279
+ */
2280
+ function countPages(text) {
2281
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
2282
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
2283
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
2284
+ return pageCount;
2285
+ }
2286
+
2287
+ /**
2288
+ * Counts number of paragraphs in the text
2289
+ */
2290
+ function countParagraphs(text) {
2291
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
2292
+ }
2293
+
2294
+ /**
2295
+ * Split text into sentences
2296
+ */
2297
+ function splitIntoSentences(text) {
2298
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
2299
+ }
2300
+ /**
2301
+ * Counts number of sentences in the text
2302
+ */
2303
+ function countSentences(text) {
2304
+ return splitIntoSentences(text).length;
2305
+ }
2306
+
2307
+ /**
2308
+ * Counts number of words in the text
2309
+ */
2310
+ function countWords(text) {
2311
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
2312
+ text = removeDiacritics(text);
2313
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
2314
+ }
2315
+
2316
+ /**
2317
+ * Index of all counter functions
2318
+ */
2319
+ var CountUtils = {
2320
+ CHARACTERS: countCharacters,
2321
+ WORDS: countWords,
2322
+ SENTENCES: countSentences,
2323
+ PARAGRAPHS: countParagraphs,
2324
+ LINES: countLines,
2325
+ PAGES: countPages,
2326
+ };
2327
+
2404
2328
  /**
2405
2329
  * Function checkExpectations will check if the expectations on given value are met
2406
2330
  *
@@ -2458,6 +2382,82 @@ function isPassingExpectations(expectations, value) {
2458
2382
  * TODO: [💝] Unite object for expecting amount and format
2459
2383
  */
2460
2384
 
2385
+ /**
2386
+ * This error occurs during the parameter replacement in the template
2387
+ *
2388
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
2389
+ */
2390
+ var TemplateError = /** @class */ (function (_super) {
2391
+ __extends(TemplateError, _super);
2392
+ function TemplateError(message) {
2393
+ var _this = _super.call(this, message) || this;
2394
+ _this.name = 'TemplateError';
2395
+ Object.setPrototypeOf(_this, TemplateError.prototype);
2396
+ return _this;
2397
+ }
2398
+ return TemplateError;
2399
+ }(Error));
2400
+
2401
+ /**
2402
+ * Replaces parameters in template with values from parameters object
2403
+ *
2404
+ * @param template the template with parameters in {curly} braces
2405
+ * @param parameters the object with parameters
2406
+ * @returns the template with replaced parameters
2407
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
2408
+ *
2409
+ * @private within the createPromptbookExecutor
2410
+ */
2411
+ function replaceParameters(template, parameters) {
2412
+ var replacedTemplate = template;
2413
+ var match;
2414
+ var loopLimit = LOOP_LIMIT;
2415
+ var _loop_1 = function () {
2416
+ if (loopLimit-- < 0) {
2417
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
2418
+ }
2419
+ var precol = match.groups.precol;
2420
+ var parameterName = match.groups.parameterName;
2421
+ if (parameterName === '') {
2422
+ return "continue";
2423
+ }
2424
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2425
+ throw new TemplateError('Parameter is already opened or not closed');
2426
+ }
2427
+ if (parameters[parameterName] === undefined) {
2428
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
2429
+ }
2430
+ var parameterValue = parameters[parameterName];
2431
+ if (parameterValue === undefined) {
2432
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
2433
+ }
2434
+ parameterValue = parameterValue.toString();
2435
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2436
+ parameterValue = parameterValue
2437
+ .split('\n')
2438
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2439
+ .join('\n');
2440
+ }
2441
+ replacedTemplate =
2442
+ replacedTemplate.substring(0, match.index + precol.length) +
2443
+ parameterValue +
2444
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2445
+ };
2446
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2447
+ .exec(replacedTemplate))) {
2448
+ _loop_1();
2449
+ }
2450
+ // [💫] Check if there are parameters that are not closed properly
2451
+ if (/{\w+$/.test(replacedTemplate)) {
2452
+ throw new TemplateError('Parameter is not closed');
2453
+ }
2454
+ // [💫] Check if there are parameters that are not opened properly
2455
+ if (/^\w+}/.test(replacedTemplate)) {
2456
+ throw new TemplateError('Parameter is not opened');
2457
+ }
2458
+ return replacedTemplate;
2459
+ }
2460
+
2461
2461
  /**
2462
2462
  * Creates executor function from promptbook and execution tools.
2463
2463
  *