@promptbook/node 0.59.0-2 → 0.59.0-21

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 (567) hide show
  1. package/esm/index.es.js +2522 -1574
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/promptbook-library/promptbook-library.d.ts +25 -0
  4. package/{umd/typings → esm/typings/src}/_packages/core.index.d.ts +7 -6
  5. package/esm/typings/{_packages → src/_packages}/node.index.d.ts +1 -1
  6. package/{umd/typings → esm/typings/src}/_packages/types.index.d.ts +1 -1
  7. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +21 -0
  8. package/{umd/typings → esm/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  9. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  10. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  11. package/{umd/typings → esm/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  12. package/esm/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +1 -1
  13. package/package.json +3 -3
  14. package/umd/index.umd.js +2522 -1574
  15. package/umd/index.umd.js.map +1 -1
  16. package/umd/typings/promptbook-library/promptbook-library.d.ts +25 -0
  17. package/{esm/typings → umd/typings/src}/_packages/core.index.d.ts +7 -6
  18. package/umd/typings/{_packages → src/_packages}/node.index.d.ts +1 -1
  19. package/{esm/typings → umd/typings/src}/_packages/types.index.d.ts +1 -1
  20. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +21 -0
  21. package/{esm/typings → umd/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  22. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  23. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  24. package/{esm/typings → umd/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  25. package/umd/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +1 -1
  26. package/esm/typings/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -7
  27. package/umd/typings/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -7
  28. /package/esm/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  29. /package/esm/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  30. /package/esm/typings/{_packages → src/_packages}/cli.index.d.ts +0 -0
  31. /package/esm/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  32. /package/esm/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  33. /package/esm/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  34. /package/esm/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  35. /package/esm/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  36. /package/esm/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  37. /package/esm/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  38. /package/esm/typings/{config.d.ts → src/config.d.ts} +0 -0
  39. /package/esm/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  40. /package/esm/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  41. /package/esm/typings/{conversion → src/conversion}/prettify/prettifyPromptbookStringCli.d.ts +0 -0
  42. /package/esm/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  43. /package/esm/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  44. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  45. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  46. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  47. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  48. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  49. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  50. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  51. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  52. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  53. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  54. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  55. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  56. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  57. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  58. /package/esm/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  59. /package/esm/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  60. /package/esm/typings/{conversion → src/conversion}/validation/validatePromptbookJson-logicErrors.test.d.ts +0 -0
  61. /package/esm/typings/{conversion → src/conversion}/validation/validatePromptbookJson.d.ts +0 -0
  62. /package/esm/typings/{conversion → src/conversion}/validation/validatePromptbookJson.test.d.ts +0 -0
  63. /package/esm/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  64. /package/esm/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  65. /package/esm/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  66. /package/esm/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  67. /package/esm/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  68. /package/esm/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  69. /package/esm/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  70. /package/esm/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  71. /package/esm/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  72. /package/esm/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  73. /package/esm/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  74. /package/esm/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  75. /package/esm/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  76. /package/esm/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  77. /package/esm/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  78. /package/esm/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  79. /package/esm/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  80. /package/esm/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  81. /package/esm/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  82. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  83. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  84. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  85. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  86. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  87. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  88. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  89. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  90. /package/esm/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  91. /package/esm/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  92. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  93. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  94. /package/esm/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  95. /package/esm/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  96. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  97. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  98. /package/esm/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  99. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  100. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  101. /package/esm/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  102. /package/esm/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  103. /package/esm/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  104. /package/esm/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  105. /package/esm/typings/{formats → src/formats}/index.d.ts +0 -0
  106. /package/esm/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  107. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  108. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  109. /package/esm/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  110. /package/esm/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  111. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  112. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  113. /package/esm/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  114. /package/esm/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  115. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  116. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  117. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  118. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  119. /package/esm/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  120. /package/esm/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +0 -0
  121. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.d.ts +0 -0
  122. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.test.d.ts +0 -0
  123. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.d.ts +0 -0
  124. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.test.d.ts +0 -0
  125. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.d.ts +0 -0
  126. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.test.d.ts +0 -0
  127. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromUrl.d.ts +0 -0
  128. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookSublibrary.d.ts +0 -0
  129. /package/esm/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  130. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  131. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  132. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +0 -0
  133. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  134. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  135. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  136. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  137. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  138. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  139. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  140. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  141. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.test.d.ts +0 -0
  142. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/faked-completion.test.d.ts +0 -0
  143. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  144. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  145. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  146. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  147. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  148. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  149. /package/esm/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionTools.d.ts +0 -0
  150. /package/esm/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  151. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  152. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  153. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeUsage.test.d.ts +0 -0
  154. /package/esm/typings/{llm-providers → src/llm-providers}/openai/openai-models.d.ts +0 -0
  155. /package/esm/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  156. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  157. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  158. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  159. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  160. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  161. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  162. /package/esm/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +0 -0
  163. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-async.test.ts.test.d.ts +0 -0
  164. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-missing.test.d.ts +0 -0
  165. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-with-dependencies.test.d.ts +0 -0
  166. /package/esm/typings/{scripting → src/scripting}/_test/custom-function.test.d.ts +0 -0
  167. /package/esm/typings/{scripting → src/scripting}/_test/postprocessing.test.d.ts +0 -0
  168. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-errors.test.d.ts +0 -0
  169. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-tools.test.d.ts +0 -0
  170. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  171. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  172. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  173. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  174. /package/esm/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  175. /package/esm/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  176. /package/esm/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  177. /package/esm/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  178. /package/esm/typings/{types → src/types}/Command.d.ts +0 -0
  179. /package/esm/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  180. /package/esm/typings/{types → src/types}/ModelRequirements.d.ts +0 -0
  181. /package/esm/typings/{types → src/types}/Parameters.d.ts +0 -0
  182. /package/esm/typings/{types → src/types}/Prompt.d.ts +0 -0
  183. /package/esm/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  184. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  185. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  186. /package/esm/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  187. /package/esm/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  188. /package/esm/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  189. /package/esm/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  190. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  191. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  192. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  193. /package/esm/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  194. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  195. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.test.d.ts +0 -0
  196. /package/esm/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  197. /package/esm/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  198. /package/esm/typings/{types → src/types}/typeAliases.d.ts +0 -0
  199. /package/esm/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  200. /package/esm/typings/{utils → src/utils}/emojis.d.ts +0 -0
  201. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  202. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.test.d.ts +0 -0
  203. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  204. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.test.d.ts +0 -0
  205. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  206. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.test.d.ts +0 -0
  207. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  208. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.test.d.ts +0 -0
  209. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  210. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.test.d.ts +0 -0
  211. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  212. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.test.d.ts +0 -0
  213. /package/esm/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  214. /package/esm/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  215. /package/esm/typings/{utils → src/utils}/extractParameters.test.d.ts +0 -0
  216. /package/esm/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  217. /package/esm/typings/{utils → src/utils}/formatNumber.test.d.ts +0 -0
  218. /package/esm/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  219. /package/esm/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  220. /package/esm/typings/{utils → src/utils}/just.d.ts +0 -0
  221. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  222. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.test.d.ts +0 -0
  223. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  224. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.test.d.ts +0 -0
  225. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  226. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.test.d.ts +0 -0
  227. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  228. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.test.d.ts +0 -0
  229. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  230. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.test.d.ts +0 -0
  231. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  232. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.test.d.ts +0 -0
  233. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  234. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.test.d.ts +0 -0
  235. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  236. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.test.d.ts +0 -0
  237. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  238. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.test.d.ts +0 -0
  239. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  240. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.test.d.ts +0 -0
  241. /package/esm/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  242. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  243. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.test.d.ts +0 -0
  244. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  245. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.test.d.ts +0 -0
  246. /package/esm/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  247. /package/esm/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  248. /package/esm/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  249. /package/esm/typings/{utils → src/utils}/normalization/capitalize.test.d.ts +0 -0
  250. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  251. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.test.d.ts +0 -0
  252. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  253. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.test.d.ts +0 -0
  254. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  255. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.test.d.ts +0 -0
  256. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  257. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.test.d.ts +0 -0
  258. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  259. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.test.d.ts +0 -0
  260. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  261. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.test.d.ts +0 -0
  262. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  263. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.test.d.ts +0 -0
  264. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  265. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.test.d.ts +0 -0
  266. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  267. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.test.d.ts +0 -0
  268. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  269. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.test.d.ts +0 -0
  270. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  271. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.test.d.ts +0 -0
  272. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  273. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.test.d.ts +0 -0
  274. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  275. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.test.d.ts +0 -0
  276. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  277. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.test.d.ts +0 -0
  278. /package/esm/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  279. /package/esm/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  280. /package/esm/typings/{utils → src/utils}/removeEmojis.test.d.ts +0 -0
  281. /package/esm/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  282. /package/esm/typings/{utils → src/utils}/removeQuotes.test.d.ts +0 -0
  283. /package/esm/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  284. /package/esm/typings/{utils → src/utils}/sets/difference.test.d.ts +0 -0
  285. /package/esm/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  286. /package/esm/typings/{utils → src/utils}/sets/intersection.test.d.ts +0 -0
  287. /package/esm/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  288. /package/esm/typings/{utils → src/utils}/sets/union.test.d.ts +0 -0
  289. /package/esm/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  290. /package/esm/typings/{utils → src/utils}/trimCodeBlock.test.d.ts +0 -0
  291. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  292. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.test.d.ts +0 -0
  293. /package/esm/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  294. /package/esm/typings/{utils → src/utils}/unwrapResult.test.d.ts +0 -0
  295. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  296. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.test.d.ts +0 -0
  297. /package/esm/typings/{version.d.ts → src/version.d.ts} +0 -0
  298. /package/umd/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  299. /package/umd/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  300. /package/umd/typings/{_packages → src/_packages}/cli.index.d.ts +0 -0
  301. /package/umd/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  302. /package/umd/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  303. /package/umd/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  304. /package/umd/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  305. /package/umd/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  306. /package/umd/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  307. /package/umd/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  308. /package/umd/typings/{config.d.ts → src/config.d.ts} +0 -0
  309. /package/umd/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  310. /package/umd/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  311. /package/umd/typings/{conversion → src/conversion}/prettify/prettifyPromptbookStringCli.d.ts +0 -0
  312. /package/umd/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  313. /package/umd/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  314. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  315. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  316. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  317. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  318. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  319. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  320. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  321. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  322. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  323. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  324. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  325. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  326. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  327. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  328. /package/umd/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  329. /package/umd/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  330. /package/umd/typings/{conversion → src/conversion}/validation/validatePromptbookJson-logicErrors.test.d.ts +0 -0
  331. /package/umd/typings/{conversion → src/conversion}/validation/validatePromptbookJson.d.ts +0 -0
  332. /package/umd/typings/{conversion → src/conversion}/validation/validatePromptbookJson.test.d.ts +0 -0
  333. /package/umd/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  334. /package/umd/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  335. /package/umd/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  336. /package/umd/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  337. /package/umd/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  338. /package/umd/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  339. /package/umd/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  340. /package/umd/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  341. /package/umd/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  342. /package/umd/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  343. /package/umd/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  344. /package/umd/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  345. /package/umd/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  346. /package/umd/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  347. /package/umd/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  348. /package/umd/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  349. /package/umd/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  350. /package/umd/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  351. /package/umd/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  352. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  353. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  354. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  355. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  356. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  357. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  358. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  359. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  360. /package/umd/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  361. /package/umd/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  362. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  363. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  364. /package/umd/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  365. /package/umd/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  366. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  367. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  368. /package/umd/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  369. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  370. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  371. /package/umd/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  372. /package/umd/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  373. /package/umd/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  374. /package/umd/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  375. /package/umd/typings/{formats → src/formats}/index.d.ts +0 -0
  376. /package/umd/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  377. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  378. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  379. /package/umd/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  380. /package/umd/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  381. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  382. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  383. /package/umd/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  384. /package/umd/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  385. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  386. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  387. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  388. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  389. /package/umd/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  390. /package/umd/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +0 -0
  391. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.d.ts +0 -0
  392. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.test.d.ts +0 -0
  393. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.d.ts +0 -0
  394. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.test.d.ts +0 -0
  395. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.d.ts +0 -0
  396. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.test.d.ts +0 -0
  397. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromUrl.d.ts +0 -0
  398. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookSublibrary.d.ts +0 -0
  399. /package/umd/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  400. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  401. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  402. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +0 -0
  403. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  404. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  405. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  406. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  407. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  408. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  409. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  410. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  411. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.test.d.ts +0 -0
  412. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/faked-completion.test.d.ts +0 -0
  413. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  414. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  415. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  416. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  417. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  418. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  419. /package/umd/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionTools.d.ts +0 -0
  420. /package/umd/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  421. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  422. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  423. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeUsage.test.d.ts +0 -0
  424. /package/umd/typings/{llm-providers → src/llm-providers}/openai/openai-models.d.ts +0 -0
  425. /package/umd/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  426. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  427. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  428. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  429. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  430. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  431. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  432. /package/umd/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +0 -0
  433. /package/umd/typings/{scripting → src/scripting}/_test/custom-function-async.test.ts.test.d.ts +0 -0
  434. /package/umd/typings/{scripting → src/scripting}/_test/custom-function-missing.test.d.ts +0 -0
  435. /package/umd/typings/{scripting → src/scripting}/_test/custom-function-with-dependencies.test.d.ts +0 -0
  436. /package/umd/typings/{scripting → src/scripting}/_test/custom-function.test.d.ts +0 -0
  437. /package/umd/typings/{scripting → src/scripting}/_test/postprocessing.test.d.ts +0 -0
  438. /package/umd/typings/{scripting → src/scripting}/_test/script-execution-errors.test.d.ts +0 -0
  439. /package/umd/typings/{scripting → src/scripting}/_test/script-execution-tools.test.d.ts +0 -0
  440. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  441. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  442. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  443. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  444. /package/umd/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  445. /package/umd/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  446. /package/umd/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  447. /package/umd/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  448. /package/umd/typings/{types → src/types}/Command.d.ts +0 -0
  449. /package/umd/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  450. /package/umd/typings/{types → src/types}/ModelRequirements.d.ts +0 -0
  451. /package/umd/typings/{types → src/types}/Parameters.d.ts +0 -0
  452. /package/umd/typings/{types → src/types}/Prompt.d.ts +0 -0
  453. /package/umd/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  454. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  455. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  456. /package/umd/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  457. /package/umd/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  458. /package/umd/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  459. /package/umd/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  460. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  461. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  462. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  463. /package/umd/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  464. /package/umd/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  465. /package/umd/typings/{types → src/types}/execution-report/countWorkingDuration.test.d.ts +0 -0
  466. /package/umd/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  467. /package/umd/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  468. /package/umd/typings/{types → src/types}/typeAliases.d.ts +0 -0
  469. /package/umd/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  470. /package/umd/typings/{utils → src/utils}/emojis.d.ts +0 -0
  471. /package/umd/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  472. /package/umd/typings/{utils → src/utils}/expectation-counters/countCharacters.test.d.ts +0 -0
  473. /package/umd/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  474. /package/umd/typings/{utils → src/utils}/expectation-counters/countLines.test.d.ts +0 -0
  475. /package/umd/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  476. /package/umd/typings/{utils → src/utils}/expectation-counters/countPages.test.d.ts +0 -0
  477. /package/umd/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  478. /package/umd/typings/{utils → src/utils}/expectation-counters/countParagraphs.test.d.ts +0 -0
  479. /package/umd/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  480. /package/umd/typings/{utils → src/utils}/expectation-counters/countSentences.test.d.ts +0 -0
  481. /package/umd/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  482. /package/umd/typings/{utils → src/utils}/expectation-counters/countWords.test.d.ts +0 -0
  483. /package/umd/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  484. /package/umd/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  485. /package/umd/typings/{utils → src/utils}/extractParameters.test.d.ts +0 -0
  486. /package/umd/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  487. /package/umd/typings/{utils → src/utils}/formatNumber.test.d.ts +0 -0
  488. /package/umd/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  489. /package/umd/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  490. /package/umd/typings/{utils → src/utils}/just.d.ts +0 -0
  491. /package/umd/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  492. /package/umd/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.test.d.ts +0 -0
  493. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  494. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownChart.test.d.ts +0 -0
  495. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  496. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownTable.test.d.ts +0 -0
  497. /package/umd/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  498. /package/umd/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.test.d.ts +0 -0
  499. /package/umd/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  500. /package/umd/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.test.d.ts +0 -0
  501. /package/umd/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  502. /package/umd/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.test.d.ts +0 -0
  503. /package/umd/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  504. /package/umd/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.test.d.ts +0 -0
  505. /package/umd/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  506. /package/umd/typings/{utils → src/utils}/markdown/prettifyMarkdown.test.d.ts +0 -0
  507. /package/umd/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  508. /package/umd/typings/{utils → src/utils}/markdown/removeContentComments.test.d.ts +0 -0
  509. /package/umd/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  510. /package/umd/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.test.d.ts +0 -0
  511. /package/umd/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  512. /package/umd/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  513. /package/umd/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.test.d.ts +0 -0
  514. /package/umd/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  515. /package/umd/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.test.d.ts +0 -0
  516. /package/umd/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  517. /package/umd/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  518. /package/umd/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  519. /package/umd/typings/{utils → src/utils}/normalization/capitalize.test.d.ts +0 -0
  520. /package/umd/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  521. /package/umd/typings/{utils → src/utils}/normalization/decapitalize.test.d.ts +0 -0
  522. /package/umd/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  523. /package/umd/typings/{utils → src/utils}/normalization/isValidKeyword.test.d.ts +0 -0
  524. /package/umd/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  525. /package/umd/typings/{utils → src/utils}/normalization/nameToUriPart.test.d.ts +0 -0
  526. /package/umd/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  527. /package/umd/typings/{utils → src/utils}/normalization/nameToUriParts.test.d.ts +0 -0
  528. /package/umd/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  529. /package/umd/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.test.d.ts +0 -0
  530. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  531. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.test.d.ts +0 -0
  532. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  533. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.test.d.ts +0 -0
  534. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  535. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.test.d.ts +0 -0
  536. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  537. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.test.d.ts +0 -0
  538. /package/umd/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  539. /package/umd/typings/{utils → src/utils}/normalization/normalizeWhitespaces.test.d.ts +0 -0
  540. /package/umd/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  541. /package/umd/typings/{utils → src/utils}/normalization/parseKeywords.test.d.ts +0 -0
  542. /package/umd/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  543. /package/umd/typings/{utils → src/utils}/normalization/parseKeywordsFromString.test.d.ts +0 -0
  544. /package/umd/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  545. /package/umd/typings/{utils → src/utils}/normalization/removeDiacritics.test.d.ts +0 -0
  546. /package/umd/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  547. /package/umd/typings/{utils → src/utils}/normalization/searchKeywords.test.d.ts +0 -0
  548. /package/umd/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  549. /package/umd/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  550. /package/umd/typings/{utils → src/utils}/removeEmojis.test.d.ts +0 -0
  551. /package/umd/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  552. /package/umd/typings/{utils → src/utils}/removeQuotes.test.d.ts +0 -0
  553. /package/umd/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  554. /package/umd/typings/{utils → src/utils}/sets/difference.test.d.ts +0 -0
  555. /package/umd/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  556. /package/umd/typings/{utils → src/utils}/sets/intersection.test.d.ts +0 -0
  557. /package/umd/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  558. /package/umd/typings/{utils → src/utils}/sets/union.test.d.ts +0 -0
  559. /package/umd/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  560. /package/umd/typings/{utils → src/utils}/trimCodeBlock.test.d.ts +0 -0
  561. /package/umd/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  562. /package/umd/typings/{utils → src/utils}/trimEndOfCodeBlock.test.d.ts +0 -0
  563. /package/umd/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  564. /package/umd/typings/{utils → src/utils}/unwrapResult.test.d.ts +0 -0
  565. /package/umd/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  566. /package/umd/typings/{utils → src/utils}/validators/url/isValidUrl.test.d.ts +0 -0
  567. /package/umd/typings/{version.d.ts → src/version.d.ts} +0 -0
package/umd/index.umd.js CHANGED
@@ -142,49 +142,66 @@
142
142
  return PromptbookSyntaxError;
143
143
  }(Error));
144
144
 
145
- // import prepareKnowledgeFromMarkdownStringPromptbook from './prepare-knowledge-from-markdown.ptbk.md';
146
- function prepareKnowledgeFromMarkdown(options) {
147
- return __awaiter(this, void 0, void 0, function () {
148
- return __generator(this, function (_a) {
149
- return [2 /*return*/, []];
150
- });
151
- });
152
- }
145
+ var promptbookLibrary = [{title:"Prepare Knowledge from Markdown",promptbookUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.59.0-20",parameters:[{name:"content",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledge",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{name:"knowledge",title:"Knowledge",dependentParameterNames:["content"],executionType:"PROMPT_TEMPLATE",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {content}",resultingParameterName:"knowledge"}],knowledge:[]}];
153
146
 
154
147
  /**
155
- * Supported script languages
148
+ * This error indicates errors during the execution of the promptbook
156
149
  */
157
- var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
150
+ var PromptbookExecutionError = /** @class */ (function (_super) {
151
+ __extends(PromptbookExecutionError, _super);
152
+ function PromptbookExecutionError(message) {
153
+ var _this = _super.call(this, message) || this;
154
+ _this.name = 'PromptbookExecutionError';
155
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
156
+ return _this;
157
+ }
158
+ return PromptbookExecutionError;
159
+ }(Error));
158
160
 
159
161
  /**
160
- * Computes the deepness of the markdown structure.
162
+ * Asserts that the execution of a promptnook is successful
161
163
  *
162
- * @private within the library
164
+ * @param executionResult - The partial result of the promptnook execution
165
+ * @throws {PromptbookExecutionError} If the execution is not successful or if multiple errors occurred
163
166
  */
164
- function countMarkdownStructureDeepness(markdownStructure) {
165
- var e_1, _a;
166
- var maxDeepness = 0;
167
- try {
168
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
169
- var section = _c.value;
170
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
171
- }
167
+ function assertsExecutionSuccessful(executionResult) {
168
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
169
+ if (isSuccessful === true) {
170
+ return;
172
171
  }
173
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
174
- finally {
175
- try {
176
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
177
- }
178
- finally { if (e_1) throw e_1.error; }
172
+ if (errors.length === 0) {
173
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
174
+ }
175
+ else if (errors.length === 1) {
176
+ throw errors[0];
177
+ }
178
+ else {
179
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Multiple errors occurred during promptnook execution\n\n ".concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n')), "\n "); }));
179
180
  }
180
- return maxDeepness + 1;
181
181
  }
182
+ /**
183
+ * TODO: [🧠] Can this return type be better typed than void
184
+ */
182
185
 
183
186
  /**
184
187
  * The maximum number of iterations for a loops
185
188
  */
186
189
  var LOOP_LIMIT = 1000;
187
190
 
191
+ /**
192
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
193
+ */
194
+ var PromptbookLogicError = /** @class */ (function (_super) {
195
+ __extends(PromptbookLogicError, _super);
196
+ function PromptbookLogicError(message) {
197
+ var _this = _super.call(this, message) || this;
198
+ _this.name = 'PromptbookLogicError';
199
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
200
+ return _this;
201
+ }
202
+ return PromptbookLogicError;
203
+ }(Error));
204
+
188
205
  /**
189
206
  * This error type indicates that the error should not happen and its last check before crashing with some other error
190
207
  */
@@ -200,804 +217,400 @@
200
217
  }(Error));
201
218
 
202
219
  /**
203
- * Parse a markdown string into a MarkdownStructure object.
204
- *
205
- * Note: This function does work with code blocks
206
- * Note: This function does not work with markdown comments
207
- *
208
- * @param markdown The markdown string to parse.
209
- * @returns The MarkdownStructure object.
220
+ * Tests if given string is valid URL.
210
221
  *
211
- * @private within the library
222
+ * Note: Dataurl are considered perfectly valid.
212
223
  */
213
- function markdownToMarkdownStructure(markdown) {
214
- var e_1, _a;
215
- var lines = markdown.split('\n');
216
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
217
- var current = root;
218
- var isInsideCodeBlock = false;
224
+ function isValidUrl(url) {
225
+ if (typeof url !== 'string') {
226
+ return false;
227
+ }
219
228
  try {
220
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
221
- var line = lines_1_1.value;
222
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
223
- if (isInsideCodeBlock || !headingMatch) {
224
- if (line.startsWith('```')) {
225
- isInsideCodeBlock = !isInsideCodeBlock;
226
- }
227
- current.contentLines.push(line);
228
- }
229
- else {
230
- var level = headingMatch.groups.mark.length;
231
- var title = headingMatch.groups.title.trim();
232
- var parent_1 = void 0;
233
- if (level > current.level) {
234
- // Note: Going deeper (next section is child of current)
235
- parent_1 = current;
236
- }
237
- else {
238
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
239
- parent_1 = current;
240
- var loopLimit = LOOP_LIMIT;
241
- while (parent_1.level !== level - 1) {
242
- if (loopLimit-- < 0) {
243
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
244
- }
245
- if (parent_1.parent === null /* <- Note: We are in root */) {
246
- // [🌻]
247
- throw new Error(spaceTrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
248
- }
249
- parent_1 = parent_1.parent;
250
- }
251
- }
252
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
253
- parent_1.sections.push(section);
254
- current = section;
255
- }
229
+ if (url.startsWith('blob:')) {
230
+ url = url.replace(/^blob:/, '');
256
231
  }
257
- }
258
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
259
- finally {
260
- try {
261
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
232
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
233
+ var urlObject = new URL(url);
234
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
235
+ return false;
262
236
  }
263
- finally { if (e_1) throw e_1.error; }
237
+ return true;
264
238
  }
265
- if (root.sections.length === 1) {
266
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
267
- return markdownStructure;
239
+ catch (error) {
240
+ return false;
268
241
  }
269
- // [🌻]
270
- throw new Error('The markdown file must have exactly one top-level section.');
271
- // return root;
272
- }
273
- /**
274
- * @private
275
- */
276
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
277
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
278
- return {
279
- level: level,
280
- title: title,
281
- content: spaceTrim.spaceTrim(contentLines.join('\n')),
282
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
283
- };
284
242
  }
285
243
 
286
244
  /**
287
- * Utility function to extract all list items from markdown
245
+ * Validates PromptbookJson if it is logically valid
288
246
  *
289
- * Note: It works with both ul and ol
290
- * Note: It omits list items in code blocks
291
- * Note: It flattens nested lists
292
- * Note: It can not work with html syntax and comments
247
+ * It checks:
248
+ * - if it has correct parameters dependency
293
249
  *
294
- * @param markdown any valid markdown
295
- * @returns
250
+ * It does NOT check:
251
+ * - if it is valid json
252
+ * - if it is meaningful
253
+ *
254
+ * @param promptbook valid or invalid PromptbookJson
255
+ * @returns the same promptbook if it is logically valid
256
+ * @throws {PromptbookLogicError} on logical error in the promptbook
296
257
  */
297
- function extractAllListItemsFromMarkdown(markdown) {
298
- var e_1, _a;
299
- var lines = markdown.split('\n');
300
- var listItems = [];
301
- var isInCodeBlock = false;
258
+ function validatePromptbookJson(promptbook) {
259
+ // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
260
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
261
+ if (promptbook.promptbookUrl !== undefined) {
262
+ if (!isValidUrl(promptbook.promptbookUrl)) {
263
+ // TODO: This should be maybe the syntax error detected during parsing
264
+ throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
265
+ }
266
+ }
267
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
268
+ if (!Array.isArray(promptbook.parameters)) {
269
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
270
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.parameters expected to be an array, but got ".concat(typeof promptbook.parameters, "\n ")));
271
+ }
272
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
273
+ if (!Array.isArray(promptbook.promptTemplates)) {
274
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
275
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.promptTemplates expected to be an array, but got ".concat(typeof promptbook.promptTemplates, "\n ")));
276
+ }
277
+ var _loop_1 = function (parameter) {
278
+ if (parameter.isInput && parameter.isOutput) {
279
+ throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
280
+ }
281
+ // Note: Testing that parameter is either intermediate or output BUT not created and unused
282
+ if (!parameter.isInput &&
283
+ !parameter.isOutput &&
284
+ !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
285
+ throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
286
+ }
287
+ // Note: Testing that parameter is either input or result of some template
288
+ if (!parameter.isInput &&
289
+ !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
290
+ throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
291
+ }
292
+ };
302
293
  try {
303
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
304
- var line = lines_1_1.value;
305
- var trimmedLine = line.trim();
306
- if (trimmedLine.startsWith('```')) {
307
- isInCodeBlock = !isInCodeBlock;
308
- }
309
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
310
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
311
- listItems.push(listItem);
312
- }
294
+ // Note: Check each parameter individually
295
+ for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
296
+ var parameter = _f.value;
297
+ _loop_1(parameter);
313
298
  }
314
299
  }
315
300
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
316
301
  finally {
317
302
  try {
318
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
303
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
319
304
  }
320
305
  finally { if (e_1) throw e_1.error; }
321
306
  }
322
- return listItems;
323
- }
324
-
325
- /**
326
- * Makes first letter of a string uppercase
327
- *
328
- */
329
- function capitalize(word) {
330
- return word.substring(0, 1).toUpperCase() + word.substring(1);
331
- }
332
-
333
- /**
334
- * Extracts all code blocks from markdown.
335
- *
336
- * Note: There are 3 simmilar function:
337
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
338
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
339
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
340
- *
341
- * @param markdown any valid markdown
342
- * @returns code blocks with language and content
343
- *
344
- */
345
- function extractAllBlocksFromMarkdown(markdown) {
346
- var e_1, _a;
347
- var codeBlocks = [];
348
- var lines = markdown.split('\n');
349
- var currentCodeBlock = null;
307
+ // Note: Check each template individually
308
+ var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
309
+ var isInput = _a.isInput;
310
+ return isInput;
311
+ }).map(function (_a) {
312
+ var name = _a.name;
313
+ return name;
314
+ }));
350
315
  try {
351
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
352
- var line = lines_1_1.value;
353
- if (line.startsWith('```')) {
354
- var language = line.slice(3).trim() || null;
355
- if (currentCodeBlock === null) {
356
- currentCodeBlock = { language: language, content: '' };
357
- }
358
- else {
359
- if (language !== null) {
360
- // [🌻]
361
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
316
+ for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
317
+ var template = _h.value;
318
+ if (definedParameters.has(template.resultingParameterName)) {
319
+ throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
320
+ }
321
+ definedParameters.add(template.resultingParameterName);
322
+ if (template.executionType === 'PROMPT_TEMPLATE' &&
323
+ (template.modelRequirements.modelVariant === undefined)) {
324
+ throw new PromptbookLogicError(spaceTrim.spaceTrim("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
325
+ }
326
+ if (template.jokers && template.jokers.length > 0) {
327
+ if (!template.expectFormat &&
328
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
329
+ throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
330
+ }
331
+ try {
332
+ for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
333
+ var joker = _k.value;
334
+ if (!template.dependentParameterNames.includes(joker)) {
335
+ throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
336
+ }
362
337
  }
363
- codeBlocks.push(currentCodeBlock);
364
- currentCodeBlock = null;
338
+ }
339
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
340
+ finally {
341
+ try {
342
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
343
+ }
344
+ finally { if (e_3) throw e_3.error; }
365
345
  }
366
346
  }
367
- else if (currentCodeBlock !== null) {
368
- if (currentCodeBlock.content !== '') {
369
- currentCodeBlock.content += '\n';
347
+ if (template.expectations) {
348
+ try {
349
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
350
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
351
+ if (min !== undefined && max !== undefined && min > max) {
352
+ throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
353
+ }
354
+ if (min !== undefined && min < 0) {
355
+ throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
356
+ }
357
+ if (max !== undefined && max <= 0) {
358
+ throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
359
+ }
360
+ }
361
+ }
362
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
363
+ finally {
364
+ try {
365
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
366
+ }
367
+ finally { if (e_4) throw e_4.error; }
370
368
  }
371
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
372
369
  }
373
370
  }
374
371
  }
375
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
372
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
376
373
  finally {
377
374
  try {
378
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
375
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
379
376
  }
380
- finally { if (e_1) throw e_1.error; }
377
+ finally { if (e_2) throw e_2.error; }
381
378
  }
382
- if (currentCodeBlock !== null) {
383
- // [🌻]
384
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
379
+ // Note: Detect circular dependencies
380
+ var resovedParameters = promptbook.parameters
381
+ .filter(function (_a) {
382
+ var isInput = _a.isInput;
383
+ return isInput;
384
+ })
385
+ .map(function (_a) {
386
+ var name = _a.name;
387
+ return name;
388
+ });
389
+ var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
390
+ var loopLimit = LOOP_LIMIT;
391
+ var _loop_2 = function () {
392
+ if (loopLimit-- < 0) {
393
+ throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbookJson`');
394
+ }
395
+ var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
396
+ return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
397
+ });
398
+ if (currentlyResovedTemplates.length === 0) {
399
+ throw new PromptbookLogicError(spaceTrim.spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
400
+ .map(function (_a) {
401
+ var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
402
+ return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
403
+ .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
404
+ .join(', '));
405
+ })
406
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
407
+ }
408
+ resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
409
+ var resultingParameterName = _a.resultingParameterName;
410
+ return resultingParameterName;
411
+ })), false);
412
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
413
+ };
414
+ while (unresovedTemplates.length > 0) {
415
+ _loop_2();
385
416
  }
386
- return codeBlocks;
417
+ return promptbook;
387
418
  }
419
+ /**
420
+ * TODO: [🧠] Work with promptbookVersion
421
+ * TODO: Use here some json-schema, Zod or something similar and change it to:
422
+ * > /**
423
+ * > * Validates PromptbookJson if it is logically valid.
424
+ * > *
425
+ * > * It checks:
426
+ * > * - it has a valid structure
427
+ * > * - ...
428
+ * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
429
+ */
388
430
 
389
431
  /**
390
- * Extracts exactly ONE code block from markdown.
391
- *
392
- * Note: If there are multiple or no code blocks the function throws an error
393
- *
394
- * Note: There are 3 simmilar function:
395
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
396
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
397
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
432
+ * This error occurs when some expectation is not met in the execution of the pipeline
398
433
  *
399
- * @param markdown any valid markdown
400
- * @returns code block with language and content
434
+ * @private Always catched and rethrown as `PromptbookExecutionError`
435
+ * Note: This is a kindof subtype of PromptbookExecutionError
401
436
  */
402
- function extractOneBlockFromMarkdown(markdown) {
403
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
404
- if (codeBlocks.length !== 1) {
405
- // TODO: Report more specific place where the error happened
406
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
437
+ var ExpectError = /** @class */ (function (_super) {
438
+ __extends(ExpectError, _super);
439
+ function ExpectError(message) {
440
+ var _this = _super.call(this, message) || this;
441
+ _this.name = 'ExpectError';
442
+ Object.setPrototypeOf(_this, ExpectError.prototype);
443
+ return _this;
407
444
  }
408
- return codeBlocks[0];
409
- }
410
- /***
411
- * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
412
- */
445
+ return ExpectError;
446
+ }(Error));
413
447
 
414
448
  /**
415
- * Removes HTML or Markdown comments from a string.
416
- *
417
- * @param {string} content - The string to remove comments from.
418
- * @returns {string} The input string with all comments removed.
449
+ * Function isValidJsonString will tell you if the string is valid JSON or not
419
450
  */
420
- function removeContentComments(content) {
421
- return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
451
+ function isValidJsonString(value /* <-[👨‍⚖️] */) {
452
+ try {
453
+ JSON.parse(value);
454
+ return true;
455
+ }
456
+ catch (error) {
457
+ if (!(error instanceof Error)) {
458
+ throw error;
459
+ }
460
+ if (error.message.includes('Unexpected token')) {
461
+ return false;
462
+ }
463
+ return false;
464
+ }
422
465
  }
423
466
 
424
467
  /**
425
- * Creates a new set with all elements that are present in either set
468
+ * The version of the Promptbook library
426
469
  */
427
- function union() {
428
- var e_1, _a, e_2, _b;
429
- var sets = [];
470
+ var PROMPTBOOK_VERSION = '0.59.0-20';
471
+
472
+ /**
473
+ * Function `addUsage` will add multiple usages into one
474
+ *
475
+ * Note: If you provide 0 values, it returns void usage
476
+ */
477
+ function addUsage() {
478
+ var usageItems = [];
430
479
  for (var _i = 0; _i < arguments.length; _i++) {
431
- sets[_i] = arguments[_i];
432
- }
433
- var union = new Set();
434
- try {
435
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
436
- var set = sets_1_1.value;
437
- try {
438
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
439
- var item = _d.value;
440
- union.add(item);
480
+ usageItems[_i] = arguments[_i];
481
+ }
482
+ var initialStructure = {
483
+ price: { value: 0 },
484
+ input: {
485
+ tokensCount: { value: 0 },
486
+ charactersCount: { value: 0 },
487
+ wordsCount: { value: 0 },
488
+ sentencesCount: { value: 0 },
489
+ linesCount: { value: 0 },
490
+ paragraphsCount: { value: 0 },
491
+ pagesCount: { value: 0 },
492
+ },
493
+ output: {
494
+ tokensCount: { value: 0 },
495
+ charactersCount: { value: 0 },
496
+ wordsCount: { value: 0 },
497
+ sentencesCount: { value: 0 },
498
+ linesCount: { value: 0 },
499
+ paragraphsCount: { value: 0 },
500
+ pagesCount: { value: 0 },
501
+ },
502
+ };
503
+ return usageItems.reduce(function (acc, item) {
504
+ var e_1, _a, e_2, _b;
505
+ var _c;
506
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
507
+ try {
508
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
509
+ var key = _e.value;
510
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
511
+ //@ts-ignore
512
+ if (item.input[key]) {
513
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
514
+ //@ts-ignore
515
+ acc.input[key].value += item.input[key].value || 0;
516
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
517
+ //@ts-ignore
518
+ if (item.input[key].isUncertain) {
519
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
520
+ //@ts-ignore
521
+ acc.input[key].isUncertain = true;
522
+ }
441
523
  }
442
524
  }
443
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
444
- finally {
445
- try {
446
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
447
- }
448
- finally { if (e_2) throw e_2.error; }
525
+ }
526
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
527
+ finally {
528
+ try {
529
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
449
530
  }
531
+ finally { if (e_1) throw e_1.error; }
450
532
  }
451
- }
452
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
453
- finally {
454
533
  try {
455
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
534
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
535
+ var key = _g.value;
536
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
537
+ //@ts-ignore
538
+ if (item.output[key]) {
539
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
540
+ //@ts-ignore
541
+ acc.output[key].value += item.output[key].value || 0;
542
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
543
+ //@ts-ignore
544
+ if (item.output[key].isUncertain) {
545
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
546
+ //@ts-ignore
547
+ acc.output[key].isUncertain = true;
548
+ }
549
+ }
550
+ }
456
551
  }
457
- finally { if (e_1) throw e_1.error; }
458
- }
459
- return union;
552
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
553
+ finally {
554
+ try {
555
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
556
+ }
557
+ finally { if (e_2) throw e_2.error; }
558
+ }
559
+ return acc;
560
+ }, initialStructure);
460
561
  }
461
562
 
462
563
  /**
463
- * The version of the Promptbook library
564
+ * Counts number of characters in the text
464
565
  */
465
- var PROMPTBOOK_VERSION = '0.59.0-1';
566
+ function countCharacters(text) {
567
+ // Remove null characters
568
+ text = text.replace(/\0/g, '');
569
+ // Replace emojis (and also ZWJ sequence) with hyphens
570
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
571
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
572
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
573
+ return text.length;
574
+ }
466
575
 
467
576
  /**
468
- * Parses the template and returns the list of all parameter names
469
- *
470
- * @param template the template with parameters in {curly} braces
471
- * @returns the list of parameter names
577
+ * Counts number of lines in the text
472
578
  */
473
- function extractParameters(template) {
474
- var e_1, _a;
475
- var matches = template.matchAll(/{\w+}/g);
476
- var parameterNames = new Set();
477
- try {
478
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
479
- var match = matches_1_1.value;
480
- var parameterName = match[0].slice(1, -1);
481
- parameterNames.add(parameterName);
482
- }
483
- }
484
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
485
- finally {
486
- try {
487
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
488
- }
489
- finally { if (e_1) throw e_1.error; }
579
+ function countLines(text) {
580
+ if (text === '') {
581
+ return 0;
490
582
  }
491
- return parameterNames;
583
+ return text.split('\n').length;
492
584
  }
493
585
 
494
586
  /**
495
- * Parses the given script and returns the list of all used variables that are not defined in the script
496
- *
497
- * @param script from which to extract the variables
498
- * @returns the list of variable names
499
- * @throws {PromptbookSyntaxError} if the script is invalid
587
+ * Counts number of pages in the text
500
588
  */
501
- function extractVariables(script) {
502
- var variables = new Set();
503
- script = "(()=>{".concat(script, "})()");
504
- try {
505
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
506
- try {
507
- eval(script);
508
- }
509
- catch (error) {
510
- if (!(error instanceof ReferenceError)) {
511
- throw error;
512
- }
513
- var undefinedName = error.message.split(' ')[0];
514
- /*
515
- Note: Remapping error
516
- From: [ReferenceError: thing is not defined],
517
- To: [Error: Parameter {thing} is not defined],
518
- */
519
- if (!undefinedName) {
520
- throw error;
521
- }
522
- if (script.includes(undefinedName + '(')) {
523
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
524
- }
525
- else {
526
- variables.add(undefinedName);
527
- script = "const ".concat(undefinedName, " = '';") + script;
528
- }
529
- }
530
- }
531
- catch (error) {
532
- if (!(error instanceof Error)) {
533
- throw error;
534
- }
535
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
536
- }
537
- return variables;
589
+ function countPages(text) {
590
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
591
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
592
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
593
+ return pageCount;
538
594
  }
539
- /**
540
- * TODO: [🔣] Support for multiple languages - python, java,...
541
- */
542
595
 
543
596
  /**
544
- * Parses the prompt template and returns the set of all used parameters
545
- *
546
- * @param promptTemplate the template with used parameters
547
- * @returns the set of parameter names
548
- * @throws {PromptbookSyntaxError} if the script is invalid
549
- */
550
- function extractParametersFromPromptTemplate(promptTemplate) {
551
- var e_1, _a, e_2, _b;
552
- var parameterNames = new Set();
553
- try {
554
- for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
555
- var parameterName = _d.value;
556
- parameterNames.add(parameterName);
557
- }
558
- }
559
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
560
- finally {
561
- try {
562
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
563
- }
564
- finally { if (e_1) throw e_1.error; }
565
- }
566
- if (promptTemplate.executionType === 'SCRIPT') {
567
- try {
568
- for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
569
- var parameterName = _f.value;
570
- parameterNames.add(parameterName);
571
- }
572
- }
573
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
574
- finally {
575
- try {
576
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
577
- }
578
- finally { if (e_2) throw e_2.error; }
579
- }
580
- }
581
- return parameterNames;
582
- }
583
- /**
584
- * TODO: [🔣] If script require contentLanguage
597
+ * Counts number of paragraphs in the text
585
598
  */
586
-
587
- /* tslint:disable */
588
- /*
589
- TODO: Tests
590
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
591
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
592
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
593
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
594
- */
595
- function normalizeTo_SCREAMING_CASE(sentence) {
596
- var e_1, _a;
597
- var charType;
598
- var lastCharType = 'OTHER';
599
- var normalizedName = '';
600
- try {
601
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
602
- var char = sentence_1_1.value;
603
- var normalizedChar = void 0;
604
- if (/^[a-z]$/.test(char)) {
605
- charType = 'LOWERCASE';
606
- normalizedChar = char.toUpperCase();
607
- }
608
- else if (/^[A-Z]$/.test(char)) {
609
- charType = 'UPPERCASE';
610
- normalizedChar = char;
611
- }
612
- else if (/^[0-9]$/.test(char)) {
613
- charType = 'NUMBER';
614
- normalizedChar = char;
615
- }
616
- else if (/^\/$/.test(char)) {
617
- charType = 'SLASH';
618
- normalizedChar = char;
619
- }
620
- else {
621
- charType = 'OTHER';
622
- normalizedChar = '_';
623
- }
624
- if (charType !== lastCharType &&
625
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
626
- !(lastCharType === 'NUMBER') &&
627
- !(charType === 'NUMBER')) {
628
- normalizedName += '_';
629
- }
630
- normalizedName += normalizedChar;
631
- lastCharType = charType;
632
- }
633
- }
634
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
635
- finally {
636
- try {
637
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
638
- }
639
- finally { if (e_1) throw e_1.error; }
640
- }
641
- normalizedName = normalizedName.replace(/_+/g, '_');
642
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
643
- normalizedName = normalizedName.replace(/^_/, '');
644
- normalizedName = normalizedName.replace(/_$/, '');
645
- return normalizedName;
599
+ function countParagraphs(text) {
600
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
646
601
  }
647
- /**
648
- * TODO: [🌺] Use some intermediate util splitWords
649
- */
650
-
651
- /**
652
- * Execution type describes the way how the block is executed
653
- *
654
- * @see https://github.com/webgptorg/promptbook#execution-type
655
- */
656
- var ExecutionTypes = [
657
- 'PROMPT_TEMPLATE',
658
- 'SIMPLE_TEMPLATE',
659
- 'SCRIPT',
660
- 'PROMPT_DIALOG',
661
- // <- [🥻] Insert here when making new command
662
- ];
663
-
664
- /**
665
- * Units of text measurement
666
- */
667
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
668
- /**
669
- * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
670
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
671
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
672
- */
673
602
 
674
603
  /**
675
- * Removes Markdown formatting tags from a string.
676
- *
677
- * @param {string} str - The string to remove Markdown tags from.
678
- * @returns {string} The input string with all Markdown tags removed.
604
+ * Split text into sentences
679
605
  */
680
- function removeMarkdownFormatting(str) {
681
- // Remove bold formatting
682
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
683
- // Remove italic formatting
684
- str = str.replace(/\*(.*?)\*/g, '$1');
685
- // Remove code formatting
686
- str = str.replace(/`(.*?)`/g, '$1');
687
- return str;
606
+ function splitIntoSentences(text) {
607
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
688
608
  }
689
-
690
609
  /**
691
- * Function parseNumber will parse number from string
692
- *
693
- * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
694
- * Note: it also works only with decimal numbers
695
- *
696
- * @returns parsed number
697
- * @throws {PromptbookSyntaxError} if the value is not a number
698
- *
699
- * @private within the parseCommand
610
+ * Counts number of sentences in the text
700
611
  */
701
- function parseNumber(value) {
702
- var originalValue = value;
703
- if (typeof value === 'number') {
704
- value = value.toString(); // <- TODO: Maybe more efficient way to do this
705
- }
706
- if (typeof value !== 'string') {
707
- return 0;
708
- }
709
- value = value.trim();
710
- if (value.startsWith('+')) {
711
- return parseNumber(value.substring(1));
712
- }
713
- if (value.startsWith('-')) {
714
- var number = parseNumber(value.substring(1));
715
- if (number === 0) {
716
- return 0; // <- Note: To prevent -0
717
- }
718
- return -number;
719
- }
720
- value = value.replace(/,/g, '.');
721
- value = value.toUpperCase();
722
- if (value === '') {
723
- return 0;
724
- }
725
- if (value === '♾' || value.startsWith('INF')) {
726
- return Infinity;
727
- }
728
- if (value.includes('/')) {
729
- var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
730
- var numerator = parseNumber(numerator_);
731
- var denominator = parseNumber(denominator_);
732
- if (denominator === 0) {
733
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
734
- }
735
- return numerator / denominator;
736
- }
737
- if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
738
- return 0;
739
- }
740
- if (value.includes('E')) {
741
- var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
742
- return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
743
- }
744
- if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
745
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
746
- }
747
- var num = parseFloat(value);
748
- if (isNaN(num)) {
749
- throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
750
- }
751
- return num;
752
- }
753
- /**
754
- * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
755
- */
756
-
757
- /**
758
- * Parses one line of ul/ol to command
759
- *
760
- * @returns parsed command object
761
- * @throws {PromptbookSyntaxError} if the command is invalid
762
- *
763
- * @private within the promptbookStringToJson
764
- */
765
- function parseCommand(listItem) {
766
- var e_1, _a;
767
- if (listItem.includes('\n') || listItem.includes('\r')) {
768
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
769
- }
770
- var type = listItem.trim();
771
- type = type.split('`').join('');
772
- type = type.split('"').join('');
773
- type = type.split("'").join('');
774
- type = type.split('~').join('');
775
- type = type.split('[').join('');
776
- type = type.split(']').join('');
777
- type = type.split('(').join('');
778
- type = type.split(')').join('');
779
- type = normalizeTo_SCREAMING_CASE(type);
780
- type = type.split('DIALOGUE').join('DIALOG');
781
- var listItemParts = listItem
782
- .split(' ')
783
- .map(function (part) { return part.trim(); })
784
- .filter(function (item) { return item !== ''; })
785
- .filter(function (item) { return !/^PTBK$/i.test(item); })
786
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
787
- .map(removeMarkdownFormatting);
788
- if (type.startsWith('URL') ||
789
- type.startsWith('PTBK_URL') ||
790
- type.startsWith('PTBKURL') ||
791
- type.startsWith('PROMPTBOOK_URL') ||
792
- type.startsWith('PROMPTBOOKURL') ||
793
- type.startsWith('HTTPS')) {
794
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
795
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
796
- }
797
- var promptbookUrlString = listItemParts.pop();
798
- var promptbookUrl = new URL(promptbookUrlString);
799
- if (promptbookUrl.protocol !== 'https:') {
800
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
801
- }
802
- if (promptbookUrl.hash !== '') {
803
- throw new PromptbookSyntaxError(spaceTrim.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 ")));
804
- }
805
- return {
806
- type: 'PROMPTBOOK_URL',
807
- promptbookUrl: promptbookUrl,
808
- };
809
- }
810
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
811
- if (listItemParts.length !== 2) {
812
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
813
- }
814
- var promptbookVersion = listItemParts.pop();
815
- // TODO: Validate version
816
- return {
817
- type: 'PROMPTBOOK_VERSION',
818
- promptbookVersion: promptbookVersion,
819
- };
820
- }
821
- else if (type.startsWith('EXECUTE') ||
822
- type.startsWith('EXEC') ||
823
- type.startsWith('PROMPT_DIALOG') ||
824
- type.startsWith('SIMPLE_TEMPLATE')) {
825
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
826
- if (executionTypes.length !== 1) {
827
- throw new PromptbookSyntaxError(spaceTrim.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 "); }));
828
- }
829
- return {
830
- type: 'EXECUTE',
831
- executionType: executionTypes[0],
832
- };
833
- }
834
- else if (type.startsWith('MODEL')) {
835
- // TODO: Make this more elegant and dynamically
836
- if (type.startsWith('MODEL_VARIANT')) {
837
- if (type === 'MODEL_VARIANT_CHAT') {
838
- return {
839
- type: 'MODEL',
840
- key: 'modelVariant',
841
- value: 'CHAT',
842
- };
843
- }
844
- else if (type === 'MODEL_VARIANT_COMPLETION') {
845
- return {
846
- type: 'MODEL',
847
- key: 'modelVariant',
848
- value: 'COMPLETION',
849
- };
850
- }
851
- else {
852
- throw new PromptbookSyntaxError(spaceTrim.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 "); }));
853
- }
854
- }
855
- if (type.startsWith('MODEL_NAME')) {
856
- return {
857
- type: 'MODEL',
858
- key: 'modelName',
859
- value: listItemParts.pop(),
860
- };
861
- }
862
- else {
863
- throw new PromptbookSyntaxError(spaceTrim.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 "); }));
864
- }
865
- }
866
- else if (type.startsWith('PARAM') ||
867
- type.startsWith('INPUT_PARAM') ||
868
- type.startsWith('OUTPUT_PARAM') ||
869
- listItem.startsWith('{') ||
870
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
871
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
872
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
873
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
874
- }
875
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
876
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
877
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
878
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
879
- }
880
- var isInput = type.startsWith('INPUT');
881
- var isOutput = type.startsWith('OUTPUT');
882
- if (listItem.startsWith('> {')) {
883
- isInput = false;
884
- isOutput = false;
885
- }
886
- return {
887
- type: 'PARAMETER',
888
- parameterName: parameterName,
889
- parameterDescription: parameterDescription.trim() || null,
890
- isInput: isInput,
891
- isOutput: isOutput,
892
- };
893
- }
894
- else if (type.startsWith('JOKER')) {
895
- if (listItemParts.length !== 2) {
896
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
897
- }
898
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
899
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
900
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
901
- }
902
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
903
- var parameterName = parametersMatch.groups.parameterName;
904
- return {
905
- type: 'JOKER',
906
- parameterName: parameterName,
907
- };
908
- }
909
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
910
- if (listItemParts.length !== 2) {
911
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
912
- }
913
- var functionName = listItemParts.pop();
914
- return {
915
- type: 'POSTPROCESS',
916
- functionName: functionName,
917
- };
918
- }
919
- else if (type.startsWith('EXPECT_JSON')) {
920
- return {
921
- type: 'EXPECT_FORMAT',
922
- format: 'JSON',
923
- };
924
- // [🥤]
925
- }
926
- else if (type.startsWith('EXPECT')) {
927
- try {
928
- listItemParts.shift();
929
- var sign = void 0;
930
- var signRaw = listItemParts.shift();
931
- if (/^exact/i.test(signRaw)) {
932
- sign = 'EXACTLY';
933
- }
934
- else if (/^min/i.test(signRaw)) {
935
- sign = 'MINIMUM';
936
- }
937
- else if (/^max/i.test(signRaw)) {
938
- sign = 'MAXIMUM';
939
- }
940
- else {
941
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
942
- }
943
- var amountRaw = listItemParts.shift();
944
- var amount = parseNumber(amountRaw);
945
- if (amount < 0) {
946
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
947
- }
948
- if (amount !== Math.floor(amount)) {
949
- throw new PromptbookSyntaxError('Amount must be whole number');
950
- }
951
- var unitRaw = listItemParts.shift();
952
- var unit = undefined;
953
- try {
954
- 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()) {
955
- var existingUnit = EXPECTATION_UNITS_1_1.value;
956
- var existingUnitText = existingUnit;
957
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
958
- if (existingUnitText === 'CHARACTER') {
959
- existingUnitText = 'CHAR';
960
- }
961
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
962
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
963
- if (unit !== undefined) {
964
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
965
- }
966
- unit = existingUnit;
967
- }
968
- }
969
- }
970
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
971
- finally {
972
- try {
973
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
974
- }
975
- finally { if (e_1) throw e_1.error; }
976
- }
977
- if (unit === undefined) {
978
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
979
- }
980
- return {
981
- type: 'EXPECT_AMOUNT',
982
- sign: sign,
983
- unit: unit,
984
- amount: amount,
985
- };
986
- }
987
- catch (error) {
988
- if (!(error instanceof Error)) {
989
- throw error;
990
- }
991
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
992
- }
993
- /*
994
- } else if (type.startsWith('__________________')) {
995
- // <- [🥻] Insert here when making new command
996
- */
997
- }
998
- else {
999
- throw new PromptbookSyntaxError(spaceTrim.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 ")));
1000
- }
612
+ function countSentences(text) {
613
+ return splitIntoSentences(text).length;
1001
614
  }
1002
615
 
1003
616
  var defaultDiacriticsRemovalMap = [
@@ -1252,674 +865,744 @@
1252
865
  });
1253
866
  }
1254
867
 
1255
- /* tslint:disable */
1256
- function normalizeToKebabCase(sentence) {
868
+ /**
869
+ * Counts number of words in the text
870
+ */
871
+ function countWords(text) {
872
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
873
+ text = removeDiacritics(text);
874
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
875
+ }
876
+
877
+ /**
878
+ * Index of all counter functions
879
+ */
880
+ var CountUtils = {
881
+ CHARACTERS: countCharacters,
882
+ WORDS: countWords,
883
+ SENTENCES: countSentences,
884
+ PARAGRAPHS: countParagraphs,
885
+ LINES: countLines,
886
+ PAGES: countPages,
887
+ };
888
+
889
+ /**
890
+ * Function checkExpectations will check if the expectations on given value are met
891
+ *
892
+ * Note: There are two simmilar functions:
893
+ * - `checkExpectations` which throws an error if the expectations are not met
894
+ * - `isPassingExpectations` which returns a boolean
895
+ *
896
+ * @throws {ExpectError} if the expectations are not met
897
+ * @returns {void} Nothing
898
+ */
899
+ function checkExpectations(expectations, value) {
1257
900
  var e_1, _a;
1258
- sentence = removeDiacritics(sentence);
1259
- var charType;
1260
- var lastCharType = 'OTHER';
1261
- var normalizedName = '';
1262
901
  try {
1263
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1264
- var char = sentence_1_1.value;
1265
- var normalizedChar = void 0;
1266
- if (/^[a-z]$/.test(char)) {
1267
- charType = 'LOWERCASE';
1268
- normalizedChar = char;
1269
- }
1270
- else if (/^[A-Z]$/.test(char)) {
1271
- charType = 'UPPERCASE';
1272
- normalizedChar = char.toLowerCase();
1273
- }
1274
- else if (/^[0-9]$/.test(char)) {
1275
- charType = 'NUMBER';
1276
- normalizedChar = char;
1277
- }
1278
- else if (/^\/$/.test(char)) {
1279
- charType = 'SLASH';
1280
- normalizedChar = char;
1281
- }
1282
- else {
1283
- charType = 'OTHER';
1284
- normalizedChar = '-';
902
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
903
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
904
+ var amount = CountUtils[unit.toUpperCase()](value);
905
+ if (min && amount < min) {
906
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
907
+ } /* not else */
908
+ if (max && amount > max) {
909
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1285
910
  }
1286
- if (charType !== lastCharType &&
1287
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1288
- !(lastCharType === 'NUMBER') &&
1289
- !(charType === 'NUMBER')) {
1290
- normalizedName += '-';
1291
- }
1292
- normalizedName += normalizedChar;
1293
- lastCharType = charType;
1294
911
  }
1295
912
  }
1296
913
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1297
914
  finally {
1298
915
  try {
1299
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
916
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1300
917
  }
1301
918
  finally { if (e_1) throw e_1.error; }
1302
919
  }
1303
- normalizedName = normalizedName.split(/-+/g).join('-');
1304
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1305
- normalizedName = normalizedName.replace(/^-/, '');
1306
- normalizedName = normalizedName.replace(/-$/, '');
1307
- return normalizedName;
1308
920
  }
921
+ /**
922
+ * TODO: [💝] Unite object for expecting amount and format
923
+ */
1309
924
 
1310
925
  /**
1311
- * Removes emojis from a string and fix whitespaces
926
+ * This error occurs during the parameter replacement in the template
1312
927
  *
1313
- * @param text with emojis
1314
- * @returns text without emojis
928
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
1315
929
  */
1316
- function removeEmojis(text) {
1317
- // Replace emojis (and also ZWJ sequence) with hyphens
1318
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1319
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1320
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1321
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
1322
- return text;
1323
- }
930
+ var TemplateError = /** @class */ (function (_super) {
931
+ __extends(TemplateError, _super);
932
+ function TemplateError(message) {
933
+ var _this = _super.call(this, message) || this;
934
+ _this.name = 'TemplateError';
935
+ Object.setPrototypeOf(_this, TemplateError.prototype);
936
+ return _this;
937
+ }
938
+ return TemplateError;
939
+ }(Error));
1324
940
 
1325
941
  /**
1326
- * Function normalizes title to name which can be used as identifier
942
+ * Replaces parameters in template with values from parameters object
943
+ *
944
+ * @param template the template with parameters in {curly} braces
945
+ * @param parameters the object with parameters
946
+ * @returns the template with replaced parameters
947
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
948
+ *
949
+ * @private within the createPromptbookExecutor
1327
950
  */
1328
- function titleToName(value) {
1329
- value = removeEmojis(value);
1330
- value = normalizeToKebabCase(value);
1331
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
1332
- return value;
951
+ function replaceParameters(template, parameters) {
952
+ var replacedTemplate = template;
953
+ var match;
954
+ var loopLimit = LOOP_LIMIT;
955
+ var _loop_1 = function () {
956
+ if (loopLimit-- < 0) {
957
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
958
+ }
959
+ var precol = match.groups.precol;
960
+ var parameterName = match.groups.parameterName;
961
+ if (parameterName === '') {
962
+ return "continue";
963
+ }
964
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
965
+ throw new TemplateError('Parameter is already opened or not closed');
966
+ }
967
+ if (parameters[parameterName] === undefined) {
968
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
969
+ }
970
+ var parameterValue = parameters[parameterName];
971
+ if (parameterValue === undefined) {
972
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
973
+ }
974
+ parameterValue = parameterValue.toString();
975
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
976
+ parameterValue = parameterValue
977
+ .split('\n')
978
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
979
+ .join('\n');
980
+ }
981
+ replacedTemplate =
982
+ replacedTemplate.substring(0, match.index + precol.length) +
983
+ parameterValue +
984
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
985
+ };
986
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
987
+ .exec(replacedTemplate))) {
988
+ _loop_1();
989
+ }
990
+ // [💫] Check if there are parameters that are not closed properly
991
+ if (/{\w+$/.test(replacedTemplate)) {
992
+ throw new TemplateError('Parameter is not closed');
993
+ }
994
+ // [💫] Check if there are parameters that are not opened properly
995
+ if (/^\w+}/.test(replacedTemplate)) {
996
+ throw new TemplateError('Parameter is not opened');
997
+ }
998
+ return replacedTemplate;
1333
999
  }
1334
1000
 
1335
1001
  /**
1336
- * Compile promptbook from string (markdown) format to JSON format
1337
- *
1338
- * @param promptbookString {Promptbook} in string markdown format (.ptbk.md)
1339
- * @param options - Options and tools for the compilation
1340
- * @returns {Promptbook} compiled in JSON format (.ptbk.json)
1341
- * @throws {PromptbookSyntaxError} if the promptbook string is not valid
1002
+ * Creates executor function from promptbook and execution tools.
1342
1003
  *
1343
- * Note: This function does not validate logic of the pipeline only the syntax
1344
- * Note: This function acts as compilation process
1004
+ * @returns The executor function
1005
+ * @throws {PromptbookLogicError} on logical error in the promptbook
1345
1006
  */
1346
- function promptbookStringToJson(promptbookString, options) {
1347
- if (options === void 0) { options = {}; }
1348
- return __awaiter(this, void 0, void 0, function () {
1349
- var llmTools, promptbookJson, knowledge, addParam, markdownStructure, markdownStructureDeepness, description, defaultModelRequirements, listItems, listItems_1, listItems_1_1, listItem, command, _loop_1, _a, _b, section;
1350
- var e_1, _c, e_2, _d;
1351
- return __generator(this, function (_e) {
1352
- switch (_e.label) {
1353
- case 0:
1354
- llmTools = options.llmTools;
1355
- promptbookJson = {
1007
+ function createPromptbookExecutor(options) {
1008
+ var _this = this;
1009
+ var promptbook = options.promptbook, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
1010
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
1011
+ validatePromptbookJson(promptbook);
1012
+ var promptbookExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1013
+ function executeSingleTemplate(currentTemplate) {
1014
+ return __awaiter(this, void 0, void 0, function () {
1015
+ var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, error_4;
1016
+ var e_2, _j, e_4, _k, e_3, _l, _m;
1017
+ var _this = this;
1018
+ return __generator(this, function (_o) {
1019
+ switch (_o.label) {
1020
+ case 0:
1021
+ name = "promptbook-executor-frame-".concat(currentTemplate.name);
1022
+ title = currentTemplate.title;
1023
+ priority = promptbook.promptTemplates.length - promptbook.promptTemplates.indexOf(currentTemplate);
1024
+ if (!onProgress /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
1025
+ return [4 /*yield*/, onProgress({
1026
+ name: name,
1027
+ title: title,
1028
+ isStarted: false,
1029
+ isDone: false,
1030
+ executionType: currentTemplate.executionType,
1031
+ parameterName: currentTemplate.resultingParameterName,
1032
+ parameterValue: null,
1033
+ // <- [3]
1034
+ })];
1035
+ case 1:
1036
+ _o.sent();
1037
+ _o.label = 2;
1038
+ case 2:
1039
+ result = null;
1040
+ resultString = null;
1041
+ expectError = null;
1042
+ maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1043
+ jokers = currentTemplate.jokers || [];
1044
+ attempt = -jokers.length;
1045
+ _o.label = 3;
1046
+ case 3:
1047
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1048
+ isJokerAttempt = attempt < 0;
1049
+ joker = jokers[jokers.length + attempt];
1050
+ if (isJokerAttempt && !joker) {
1051
+ throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
1052
+ }
1053
+ result = null;
1054
+ resultString = null;
1055
+ expectError = null;
1056
+ if (isJokerAttempt) {
1057
+ if (typeof parametersToPass[joker] === 'undefined') {
1058
+ throw new PromptbookExecutionError("Joker parameter {".concat(joker, "} not defined"));
1059
+ }
1060
+ resultString = parametersToPass[joker];
1061
+ }
1062
+ _o.label = 4;
1063
+ case 4:
1064
+ _o.trys.push([4, 45, 46, 47]);
1065
+ if (!!isJokerAttempt) return [3 /*break*/, 27];
1066
+ _a = currentTemplate.executionType;
1067
+ switch (_a) {
1068
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
1069
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
1070
+ case 'SCRIPT': return [3 /*break*/, 13];
1071
+ case 'PROMPT_DIALOG': return [3 /*break*/, 24];
1072
+ }
1073
+ return [3 /*break*/, 26];
1074
+ case 5:
1075
+ resultString = replaceParameters(currentTemplate.content, parametersToPass);
1076
+ return [3 /*break*/, 27];
1077
+ case 6:
1078
+ prompt = {
1079
+ title: currentTemplate.title,
1080
+ promptbookUrl: "".concat(promptbook.promptbookUrl
1081
+ ? promptbook.promptbookUrl
1082
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous PROMPTBOOKs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1083
+ parameters: parametersToPass,
1084
+ content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1085
+ modelRequirements: currentTemplate.modelRequirements,
1086
+ expectations: currentTemplate.expectations,
1087
+ expectFormat: currentTemplate.expectFormat,
1088
+ postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
1089
+ var errors, _a, _b, scriptTools, error_5, e_5_1;
1090
+ var e_5, _c;
1091
+ return __generator(this, function (_d) {
1092
+ switch (_d.label) {
1093
+ case 0:
1094
+ errors = [];
1095
+ _d.label = 1;
1096
+ case 1:
1097
+ _d.trys.push([1, 8, 9, 10]);
1098
+ _a = __values(tools.script), _b = _a.next();
1099
+ _d.label = 2;
1100
+ case 2:
1101
+ if (!!_b.done) return [3 /*break*/, 7];
1102
+ scriptTools = _b.value;
1103
+ _d.label = 3;
1104
+ case 3:
1105
+ _d.trys.push([3, 5, , 6]);
1106
+ return [4 /*yield*/, scriptTools.execute({
1107
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1108
+ script: "".concat(functionName, "(result)"),
1109
+ parameters: {
1110
+ result: result || '',
1111
+ // Note: No ...parametersToPass, because working with result only
1112
+ },
1113
+ })];
1114
+ case 4: return [2 /*return*/, _d.sent()];
1115
+ case 5:
1116
+ error_5 = _d.sent();
1117
+ if (!(error_5 instanceof Error)) {
1118
+ throw error_5;
1119
+ }
1120
+ errors.push(error_5);
1121
+ return [3 /*break*/, 6];
1122
+ case 6:
1123
+ _b = _a.next();
1124
+ return [3 /*break*/, 2];
1125
+ case 7: return [3 /*break*/, 10];
1126
+ case 8:
1127
+ e_5_1 = _d.sent();
1128
+ e_5 = { error: e_5_1 };
1129
+ return [3 /*break*/, 10];
1130
+ case 9:
1131
+ try {
1132
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1133
+ }
1134
+ finally { if (e_5) throw e_5.error; }
1135
+ return [7 /*endfinally*/];
1136
+ case 10:
1137
+ if (errors.length === 0) {
1138
+ throw new PromptbookExecutionError('Postprocessing in LlmExecutionTools failed because no ScriptExecutionTools were provided');
1139
+ }
1140
+ else if (errors.length === 1) {
1141
+ throw errors[0];
1142
+ }
1143
+ else {
1144
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Postprocessing in LlmExecutionTools failed ".concat(errors.length, "x\n\n ").concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n\n')), "\n "); }));
1145
+ }
1146
+ }
1147
+ });
1148
+ }); }; }),
1149
+ };
1150
+ _b = currentTemplate.modelRequirements.modelVariant;
1151
+ switch (_b) {
1152
+ case 'CHAT': return [3 /*break*/, 7];
1153
+ case 'COMPLETION': return [3 /*break*/, 9];
1154
+ }
1155
+ return [3 /*break*/, 11];
1156
+ case 7: return [4 /*yield*/, tools.llm.gptChat(prompt)];
1157
+ case 8:
1158
+ chatThread = _o.sent();
1159
+ // TODO: [🍬] Destroy chatThread
1160
+ result = chatThread;
1161
+ resultString = chatThread.content;
1162
+ return [3 /*break*/, 12];
1163
+ case 9: return [4 /*yield*/, tools.llm.gptComplete(prompt)];
1164
+ case 10:
1165
+ completionResult = _o.sent();
1166
+ result = completionResult;
1167
+ resultString = completionResult.content;
1168
+ return [3 /*break*/, 12];
1169
+ case 11: throw new PromptbookExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
1170
+ case 12: return [3 /*break*/, 27];
1171
+ case 13:
1172
+ if (tools.script.length === 0) {
1173
+ throw new PromptbookExecutionError('No script execution tools are available');
1174
+ }
1175
+ if (!currentTemplate.contentLanguage) {
1176
+ throw new PromptbookExecutionError("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
1177
+ }
1178
+ // TODO: DRY [1]
1179
+ scriptExecutionErrors = [];
1180
+ _o.label = 14;
1181
+ case 14:
1182
+ _o.trys.push([14, 21, 22, 23]);
1183
+ _c = (e_2 = void 0, __values(tools.script)), _d = _c.next();
1184
+ _o.label = 15;
1185
+ case 15:
1186
+ if (!!_d.done) return [3 /*break*/, 20];
1187
+ scriptTools = _d.value;
1188
+ _o.label = 16;
1189
+ case 16:
1190
+ _o.trys.push([16, 18, , 19]);
1191
+ return [4 /*yield*/, scriptTools.execute({
1192
+ scriptLanguage: currentTemplate.contentLanguage,
1193
+ script: currentTemplate.content,
1194
+ parameters: parametersToPass,
1195
+ })];
1196
+ case 17:
1197
+ resultString = _o.sent();
1198
+ return [3 /*break*/, 20];
1199
+ case 18:
1200
+ error_2 = _o.sent();
1201
+ if (!(error_2 instanceof Error)) {
1202
+ throw error_2;
1203
+ }
1204
+ scriptExecutionErrors.push(error_2);
1205
+ return [3 /*break*/, 19];
1206
+ case 19:
1207
+ _d = _c.next();
1208
+ return [3 /*break*/, 15];
1209
+ case 20: return [3 /*break*/, 23];
1210
+ case 21:
1211
+ e_2_1 = _o.sent();
1212
+ e_2 = { error: e_2_1 };
1213
+ return [3 /*break*/, 23];
1214
+ case 22:
1215
+ try {
1216
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
1217
+ }
1218
+ finally { if (e_2) throw e_2.error; }
1219
+ return [7 /*endfinally*/];
1220
+ case 23:
1221
+ if (resultString !== null) {
1222
+ return [3 /*break*/, 27];
1223
+ }
1224
+ if (scriptExecutionErrors.length === 1) {
1225
+ throw scriptExecutionErrors[0];
1226
+ }
1227
+ else {
1228
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
1229
+ .map(function (error) { return '- ' + error.message; })
1230
+ .join('\n\n')), "\n "); }));
1231
+ }
1232
+ case 24:
1233
+ if (tools.userInterface === undefined) {
1234
+ throw new PromptbookExecutionError('User interface tools are not available');
1235
+ }
1236
+ return [4 /*yield*/, tools.userInterface.promptDialog({
1237
+ promptTitle: currentTemplate.title,
1238
+ promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
1239
+ defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
1240
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
1241
+ placeholder: undefined,
1242
+ priority: priority,
1243
+ })];
1244
+ case 25:
1245
+ // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
1246
+ resultString = _o.sent();
1247
+ return [3 /*break*/, 27];
1248
+ case 26: throw new PromptbookExecutionError(
1356
1249
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1357
- title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
1358
- promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
1359
- promptbookVersion: PROMPTBOOK_VERSION,
1360
- description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
1361
- parameters: [],
1362
- promptTemplates: [],
1363
- knowledge: [],
1250
+ "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
1251
+ case 27:
1252
+ if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
1253
+ _o.label = 28;
1254
+ case 28:
1255
+ _o.trys.push([28, 42, 43, 44]);
1256
+ _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
1257
+ _o.label = 29;
1258
+ case 29:
1259
+ if (!!_f.done) return [3 /*break*/, 41];
1260
+ functionName = _f.value;
1261
+ // TODO: DRY [1]
1262
+ scriptExecutionErrors = [];
1263
+ postprocessingError = null;
1264
+ _o.label = 30;
1265
+ case 30:
1266
+ _o.trys.push([30, 37, 38, 39]);
1267
+ _g = (e_3 = void 0, __values(tools.script)), _h = _g.next();
1268
+ _o.label = 31;
1269
+ case 31:
1270
+ if (!!_h.done) return [3 /*break*/, 36];
1271
+ scriptTools = _h.value;
1272
+ _o.label = 32;
1273
+ case 32:
1274
+ _o.trys.push([32, 34, , 35]);
1275
+ return [4 /*yield*/, scriptTools.execute({
1276
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1277
+ script: "".concat(functionName, "(resultString)"),
1278
+ parameters: {
1279
+ resultString: resultString || '',
1280
+ // Note: No ...parametersToPass, because working with result only
1281
+ },
1282
+ })];
1283
+ case 33:
1284
+ resultString = _o.sent();
1285
+ postprocessingError = null;
1286
+ return [3 /*break*/, 36];
1287
+ case 34:
1288
+ error_3 = _o.sent();
1289
+ if (!(error_3 instanceof Error)) {
1290
+ throw error_3;
1291
+ }
1292
+ postprocessingError = error_3;
1293
+ scriptExecutionErrors.push(error_3);
1294
+ return [3 /*break*/, 35];
1295
+ case 35:
1296
+ _h = _g.next();
1297
+ return [3 /*break*/, 31];
1298
+ case 36: return [3 /*break*/, 39];
1299
+ case 37:
1300
+ e_3_1 = _o.sent();
1301
+ e_3 = { error: e_3_1 };
1302
+ return [3 /*break*/, 39];
1303
+ case 38:
1304
+ try {
1305
+ if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
1306
+ }
1307
+ finally { if (e_3) throw e_3.error; }
1308
+ return [7 /*endfinally*/];
1309
+ case 39:
1310
+ if (postprocessingError) {
1311
+ throw postprocessingError;
1312
+ }
1313
+ _o.label = 40;
1314
+ case 40:
1315
+ _f = _e.next();
1316
+ return [3 /*break*/, 29];
1317
+ case 41: return [3 /*break*/, 44];
1318
+ case 42:
1319
+ e_4_1 = _o.sent();
1320
+ e_4 = { error: e_4_1 };
1321
+ return [3 /*break*/, 44];
1322
+ case 43:
1323
+ try {
1324
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
1325
+ }
1326
+ finally { if (e_4) throw e_4.error; }
1327
+ return [7 /*endfinally*/];
1328
+ case 44:
1329
+ // TODO: [💝] Unite object for expecting amount and format
1330
+ if (currentTemplate.expectFormat) {
1331
+ if (currentTemplate.expectFormat === 'JSON') {
1332
+ if (!isValidJsonString(resultString || '')) {
1333
+ throw new ExpectError('Expected valid JSON string');
1334
+ }
1335
+ }
1336
+ }
1337
+ // TODO: [💝] Unite object for expecting amount and format
1338
+ if (currentTemplate.expectations) {
1339
+ checkExpectations(currentTemplate.expectations, resultString || '');
1340
+ }
1341
+ return [3 /*break*/, 49];
1342
+ case 45:
1343
+ error_4 = _o.sent();
1344
+ if (!(error_4 instanceof ExpectError)) {
1345
+ throw error_4;
1346
+ }
1347
+ expectError = error_4;
1348
+ return [3 /*break*/, 47];
1349
+ case 46:
1350
+ if (!isJokerAttempt &&
1351
+ currentTemplate.executionType === 'PROMPT_TEMPLATE' &&
1352
+ prompt
1353
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
1354
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
1355
+ ) {
1356
+ // TODO: [🧠] Maybe put other executionTypes into report
1357
+ executionReport.promptExecutions.push({
1358
+ prompt: {
1359
+ title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
1360
+ content: prompt.content,
1361
+ modelRequirements: prompt.modelRequirements,
1362
+ expectations: prompt.expectations,
1363
+ expectFormat: prompt.expectFormat,
1364
+ // <- Note: Do want to pass ONLY wanted information to the report
1365
+ },
1366
+ result: result || undefined,
1367
+ error: expectError || undefined,
1368
+ });
1369
+ }
1370
+ return [7 /*endfinally*/];
1371
+ case 47:
1372
+ if (expectError !== null && attempt === maxAttempts - 1) {
1373
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ---\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
1374
+ }
1375
+ _o.label = 48;
1376
+ case 48:
1377
+ attempt++;
1378
+ return [3 /*break*/, 3];
1379
+ case 49:
1380
+ if (resultString === null) {
1381
+ throw new UnexpectedError('Something went wrong and prompt result is null');
1382
+ }
1383
+ if (onProgress /* <- [3] */) {
1384
+ onProgress({
1385
+ name: name,
1386
+ title: title,
1387
+ isStarted: true,
1388
+ isDone: true,
1389
+ executionType: currentTemplate.executionType,
1390
+ parameterName: currentTemplate.resultingParameterName,
1391
+ parameterValue: resultString,
1392
+ // <- [3]
1393
+ });
1394
+ }
1395
+ parametersToPass = __assign(__assign({}, parametersToPass), (_m = {}, _m[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _m));
1396
+ return [2 /*return*/];
1397
+ }
1398
+ });
1399
+ });
1400
+ }
1401
+ var parametersToPass, executionReport, resovedParameters_1, unresovedTemplates, resolving_1, loopLimit, _loop_1, error_1, usage_1, _a, _b, parameter, usage;
1402
+ var e_1, _c;
1403
+ return __generator(this, function (_d) {
1404
+ switch (_d.label) {
1405
+ case 0:
1406
+ parametersToPass = inputParameters;
1407
+ executionReport = {
1408
+ promptbookUrl: promptbook.promptbookUrl,
1409
+ title: promptbook.title,
1410
+ promptbookUsedVersion: PROMPTBOOK_VERSION,
1411
+ promptbookRequestedVersion: promptbook.promptbookVersion,
1412
+ description: promptbook.description,
1413
+ promptExecutions: [],
1364
1414
  };
1365
- if (!llmTools) return [3 /*break*/, 2];
1366
- return [4 /*yield*/, prepareKnowledgeFromMarkdown()];
1415
+ _d.label = 1;
1367
1416
  case 1:
1368
- knowledge = _e.sent();
1369
- console.info('!!!! knowledge', knowledge);
1370
- _e.label = 2;
1371
- case 2:
1372
- // =============================================================
1373
- // Note: 1️⃣ Normalization of the PROMPTBOOK string
1374
- promptbookString = removeContentComments(promptbookString);
1375
- promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
1376
- promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
1377
- addParam = function (parameterCommand) {
1378
- var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
1379
- var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
1380
- if (existingParameter &&
1381
- existingParameter.description &&
1382
- existingParameter.description !== parameterDescription &&
1383
- parameterDescription) {
1384
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
1385
- }
1386
- if (existingParameter) {
1387
- if (parameterDescription) {
1388
- existingParameter.description = parameterDescription;
1417
+ _d.trys.push([1, 6, , 7]);
1418
+ resovedParameters_1 = promptbook.parameters
1419
+ .filter(function (_a) {
1420
+ var isInput = _a.isInput;
1421
+ return isInput;
1422
+ })
1423
+ .map(function (_a) {
1424
+ var name = _a.name;
1425
+ return name;
1426
+ });
1427
+ unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1428
+ resolving_1 = [];
1429
+ loopLimit = LOOP_LIMIT;
1430
+ _loop_1 = function () {
1431
+ var currentTemplate, work_1;
1432
+ return __generator(this, function (_e) {
1433
+ switch (_e.label) {
1434
+ case 0:
1435
+ if (loopLimit-- < 0) {
1436
+ throw new UnexpectedError('Loop limit reached during resolving parameters promptbook execution');
1437
+ }
1438
+ currentTemplate = unresovedTemplates.find(function (template) {
1439
+ return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
1440
+ });
1441
+ if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
1442
+ throw new UnexpectedError(spaceTrim.spaceTrim("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbookJson\n "));
1443
+ case 1:
1444
+ if (!!currentTemplate) return [3 /*break*/, 3];
1445
+ /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
1446
+ case 2:
1447
+ /* [5] */ _e.sent();
1448
+ return [3 /*break*/, 4];
1449
+ case 3:
1450
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return template !== currentTemplate; });
1451
+ work_1 = executeSingleTemplate(currentTemplate)
1452
+ .then(function () {
1453
+ resovedParameters_1 = __spreadArray(__spreadArray([], __read(resovedParameters_1), false), [currentTemplate.resultingParameterName], false);
1454
+ })
1455
+ .then(function () {
1456
+ resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
1457
+ });
1458
+ resolving_1.push(work_1);
1459
+ _e.label = 4;
1460
+ case 4: return [2 /*return*/];
1389
1461
  }
1390
- }
1391
- else {
1392
- promptbookJson.parameters.push({
1393
- name: parameterName,
1394
- description: parameterDescription || undefined,
1395
- isInput: isInput,
1396
- isOutput: isOutput,
1397
- });
1398
- }
1462
+ });
1399
1463
  };
1400
- markdownStructure = markdownToMarkdownStructure(promptbookString);
1401
- markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
1402
- if (markdownStructureDeepness !== 2) {
1403
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
1404
- }
1405
- promptbookJson.title = markdownStructure.title;
1406
- description = markdownStructure.content;
1407
- // Note: Remove codeblocks
1408
- description = description.split(/^```.*^```/gms).join('');
1409
- //Note: Remove lists and return statement
1410
- description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1411
- description = spaceTrim.spaceTrim(description);
1412
- if (description === '') {
1413
- description = undefined;
1464
+ _d.label = 2;
1465
+ case 2:
1466
+ if (!(unresovedTemplates.length > 0)) return [3 /*break*/, 4];
1467
+ return [5 /*yield**/, _loop_1()];
1468
+ case 3:
1469
+ _d.sent();
1470
+ return [3 /*break*/, 2];
1471
+ case 4: return [4 /*yield*/, Promise.all(resolving_1)];
1472
+ case 5:
1473
+ _d.sent();
1474
+ return [3 /*break*/, 7];
1475
+ case 6:
1476
+ error_1 = _d.sent();
1477
+ if (!(error_1 instanceof Error)) {
1478
+ throw error_1;
1414
1479
  }
1415
- promptbookJson.description = description;
1416
- defaultModelRequirements = {};
1417
- listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
1480
+ usage_1 = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1481
+ var result = _a.result;
1482
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1483
+ })), false));
1484
+ return [2 /*return*/, {
1485
+ isSuccessful: false,
1486
+ errors: [error_1],
1487
+ usage: usage_1,
1488
+ executionReport: executionReport,
1489
+ outputParameters: parametersToPass,
1490
+ }];
1491
+ case 7:
1418
1492
  try {
1419
- for (listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
1420
- listItem = listItems_1_1.value;
1421
- command = parseCommand(listItem);
1422
- switch (command.type) {
1423
- case 'PROMPTBOOK_URL':
1424
- promptbookJson.promptbookUrl = command.promptbookUrl.href;
1425
- break;
1426
- case 'PROMPTBOOK_VERSION':
1427
- promptbookJson.promptbookVersion = command.promptbookVersion;
1428
- break;
1429
- case 'MODEL':
1430
- defaultModelRequirements[command.key] = command.value;
1431
- break;
1432
- case 'PARAMETER':
1433
- addParam(command);
1434
- break;
1435
- default:
1436
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
1493
+ // Note: Filter ONLY output parameters
1494
+ for (_a = __values(promptbook.parameters), _b = _a.next(); !_b.done; _b = _a.next()) {
1495
+ parameter = _b.value;
1496
+ if (parameter.isOutput) {
1497
+ continue;
1437
1498
  }
1499
+ delete parametersToPass[parameter.name];
1438
1500
  }
1439
1501
  }
1440
1502
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1441
1503
  finally {
1442
1504
  try {
1443
- if (listItems_1_1 && !listItems_1_1.done && (_c = listItems_1.return)) _c.call(listItems_1);
1505
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1444
1506
  }
1445
1507
  finally { if (e_1) throw e_1.error; }
1446
1508
  }
1447
- _loop_1 = function (section) {
1448
- var e_3, _f;
1449
- // TODO: Parse prompt template description (the content out of the codeblock and lists)
1450
- var templateModelRequirements = __assign({}, defaultModelRequirements);
1451
- var listItems_3 = extractAllListItemsFromMarkdown(section.content);
1452
- var dependentParameterNames = new Set();
1453
- var executionType = 'PROMPT_TEMPLATE';
1454
- var jokers = [];
1455
- var postprocessing = [];
1456
- var expectAmount = {};
1457
- var expectFormat = undefined;
1458
- var isExecutionTypeChanged = false;
1459
- try {
1460
- for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
1461
- var listItem = listItems_2_1.value;
1462
- var command = parseCommand(listItem);
1463
- switch (command.type) {
1464
- case 'JOKER':
1465
- jokers.push(command.parameterName);
1466
- dependentParameterNames.add(command.parameterName);
1467
- break;
1468
- case 'EXECUTE':
1469
- if (isExecutionTypeChanged) {
1470
- throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
1471
- }
1472
- executionType = command.executionType;
1473
- isExecutionTypeChanged = true;
1474
- break;
1475
- case 'MODEL':
1476
- templateModelRequirements[command.key] = command.value;
1477
- break;
1478
- case 'PARAMETER':
1479
- // Note: This is just for detecting resulitng parameter name
1480
- addParam(command);
1481
- break;
1482
- case 'POSTPROCESS':
1483
- postprocessing.push(command.functionName);
1484
- break;
1485
- case 'EXPECT_AMOUNT':
1486
- // eslint-disable-next-line no-case-declarations
1487
- var unit = command.unit.toLowerCase();
1488
- expectAmount[unit] = expectAmount[unit] || {};
1489
- if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
1490
- if (expectAmount[unit].min !== undefined) {
1491
- throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
1492
- }
1493
- expectAmount[unit].min = command.amount;
1494
- } /* not else */
1495
- if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
1496
- if (expectAmount[unit].max !== undefined) {
1497
- throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
1498
- }
1499
- expectAmount[unit].max = command.amount;
1500
- }
1501
- break;
1502
- case 'EXPECT_FORMAT':
1503
- if (expectFormat !== undefined && command.format !== expectFormat) {
1504
- throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
1505
- }
1506
- expectFormat = command.format;
1507
- break;
1508
- default:
1509
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
1510
- }
1511
- }
1512
- }
1513
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1514
- finally {
1515
- try {
1516
- if (listItems_2_1 && !listItems_2_1.done && (_f = listItems_2.return)) _f.call(listItems_2);
1517
- }
1518
- finally { if (e_3) throw e_3.error; }
1519
- }
1520
- var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
1521
- if (executionType === 'SCRIPT') {
1522
- if (!language) {
1523
- throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
1524
- }
1525
- else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
1526
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
1527
- }
1528
- }
1529
- var lastLine = section.content.split('\n').pop();
1530
- var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1531
- if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1532
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1533
- // TODO: Show code of invalid sections each time + DRY
1534
- section.content
1535
- .split('\n')
1536
- .map(function (line) { return "> ".concat(line); })
1537
- .join('\n')), "\n "); }));
1538
- }
1539
- var resultingParameterName = match.groups.resultingParamName;
1540
- // TODO: [1] DRY description
1541
- var description_1 = section.content;
1542
- // Note: Remove codeblocks
1543
- description_1 = description_1.split(/^```.*^```/gms).join('');
1544
- //Note: Remove lists and return statement
1545
- description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1546
- description_1 = spaceTrim.spaceTrim(description_1);
1547
- if (description_1 === '') {
1548
- description_1 = undefined;
1549
- }
1550
- if (Object.keys(jokers).length === 0) {
1551
- jokers = undefined;
1552
- }
1553
- if (Object.keys(expectAmount).length === 0) {
1554
- expectAmount = undefined;
1555
- }
1556
- if (Object.keys(postprocessing).length === 0) {
1557
- postprocessing = undefined;
1558
- }
1559
- dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, executionType: executionType, content: content })));
1560
- if (templateModelRequirements.modelVariant === undefined) {
1561
- templateModelRequirements.modelVariant = 'CHAT';
1562
- }
1563
- promptbookJson.promptTemplates.push({
1564
- name: titleToName(section.title),
1565
- title: section.title,
1566
- description: description_1,
1567
- dependentParameterNames: Array.from(dependentParameterNames),
1568
- executionType: executionType,
1569
- jokers: jokers,
1570
- postprocessing: postprocessing,
1571
- expectations: expectAmount,
1572
- expectFormat: expectFormat,
1573
- modelRequirements: templateModelRequirements,
1574
- contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1575
- content: content,
1576
- resultingParameterName: resultingParameterName,
1577
- });
1578
- };
1579
- try {
1580
- for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
1581
- section = _b.value;
1582
- _loop_1(section);
1583
- }
1584
- }
1585
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1586
- finally {
1587
- try {
1588
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
1589
- }
1590
- finally { if (e_2) throw e_2.error; }
1591
- }
1592
- // =============================================================
1593
- return [2 /*return*/, promptbookJson];
1509
+ usage = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1510
+ var result = _a.result;
1511
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1512
+ })), false));
1513
+ return [2 /*return*/, {
1514
+ isSuccessful: true,
1515
+ errors: [],
1516
+ usage: usage,
1517
+ executionReport: executionReport,
1518
+ outputParameters: parametersToPass,
1519
+ }];
1594
1520
  }
1595
1521
  });
1596
- });
1522
+ }); };
1523
+ return promptbookExecutor;
1597
1524
  }
1598
1525
  /**
1599
- * TODO: Report here line/column of error
1600
- * TODO: Use spaceTrim more effectively
1601
- * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1602
- */
1603
-
1604
- /**
1605
- * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
1526
+ * TODO: [🧠] When not meet expectations in PROMPT_DIALOG, make some way to tell the user
1527
+ * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
1528
+ * Note: CreatePromptbookExecutorOptions are just connected to PromptbookExecutor so do not extract to types folder
1529
+ * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
1606
1530
  */
1607
- var PromptbookLogicError = /** @class */ (function (_super) {
1608
- __extends(PromptbookLogicError, _super);
1609
- function PromptbookLogicError(message) {
1610
- var _this = _super.call(this, message) || this;
1611
- _this.name = 'PromptbookLogicError';
1612
- Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
1613
- return _this;
1614
- }
1615
- return PromptbookLogicError;
1616
- }(Error));
1617
1531
 
1618
1532
  /**
1619
- * Tests if given string is valid URL.
1533
+ * Prettify the html code
1620
1534
  *
1621
- * Note: Dataurl are considered perfectly valid.
1535
+ * @param content raw html code
1536
+ * @returns formatted html code
1622
1537
  */
1623
- function isValidUrl(url) {
1624
- if (typeof url !== 'string') {
1625
- return false;
1626
- }
1538
+ function prettifyMarkdown(content) {
1627
1539
  try {
1628
- if (url.startsWith('blob:')) {
1629
- url = url.replace(/^blob:/, '');
1630
- }
1631
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1632
- var urlObject = new URL(url);
1633
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1634
- return false;
1635
- }
1636
- return true;
1540
+ return prettier.format(content, {
1541
+ parser: 'markdown',
1542
+ plugins: [parserHtml__default["default"]],
1543
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1544
+ endOfLine: 'lf',
1545
+ tabWidth: 4,
1546
+ singleQuote: true,
1547
+ trailingComma: 'all',
1548
+ arrowParens: 'always',
1549
+ printWidth: 120,
1550
+ htmlWhitespaceSensitivity: 'ignore',
1551
+ jsxBracketSameLine: false,
1552
+ bracketSpacing: true,
1553
+ });
1637
1554
  }
1638
1555
  catch (error) {
1639
- return false;
1556
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1557
+ error: error,
1558
+ html: content,
1559
+ });
1560
+ return content;
1640
1561
  }
1641
1562
  }
1642
1563
 
1643
1564
  /**
1644
- * Validates PromptbookJson if it is logically valid
1645
- *
1646
- * It checks:
1647
- * - if it has correct parameters dependency
1565
+ * Makes first letter of a string uppercase
1648
1566
  *
1649
- * It does NOT check:
1650
- * - if it is valid json
1651
- * - if it is meaningful
1567
+ */
1568
+ function capitalize(word) {
1569
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
1570
+ }
1571
+
1572
+ /**
1573
+ * Converts promptbook in JSON format to string format
1652
1574
  *
1653
- * @param promptbook valid or invalid PromptbookJson
1654
- * @returns the same promptbook if it is logically valid
1655
- * @throws {PromptbookLogicError} on logical error in the promptbook
1575
+ * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1576
+ * @returns Promptbook in string format (.ptbk.md)
1656
1577
  */
1657
- function validatePromptbookJson(promptbook) {
1658
- // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1659
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
1660
- if (promptbook.promptbookUrl !== undefined) {
1661
- if (!isValidUrl(promptbook.promptbookUrl)) {
1662
- // TODO: This should be maybe the syntax error detected during parsing
1663
- throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
1664
- }
1665
- }
1666
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1667
- if (!Array.isArray(promptbook.parameters)) {
1668
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1669
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.parameters expected to be an array, but got ".concat(typeof promptbook.parameters, "\n ")));
1578
+ function promptbookJsonToString(promptbookJson) {
1579
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1580
+ var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1581
+ var promptbookString = "# ".concat(title);
1582
+ if (description) {
1583
+ promptbookString += '\n\n';
1584
+ promptbookString += description;
1670
1585
  }
1671
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1672
- if (!Array.isArray(promptbook.promptTemplates)) {
1673
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1674
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.promptTemplates expected to be an array, but got ".concat(typeof promptbook.promptTemplates, "\n ")));
1586
+ // TODO:> const commands: Array<Command>
1587
+ var commands = [];
1588
+ if (promptbookUrl) {
1589
+ commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1675
1590
  }
1676
- var _loop_1 = function (parameter) {
1677
- if (parameter.isInput && parameter.isOutput) {
1678
- throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
1679
- }
1680
- // Note: Testing that parameter is either intermediate or output BUT not created and unused
1681
- if (!parameter.isInput &&
1682
- !parameter.isOutput &&
1683
- !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
1684
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
1685
- }
1686
- // Note: Testing that parameter is either input or result of some template
1687
- if (!parameter.isInput &&
1688
- !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
1689
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
1690
- }
1691
- };
1591
+ commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1592
+ promptbookString = prettifyMarkdown(promptbookString);
1692
1593
  try {
1693
- // Note: Check each parameter individually
1694
- for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
1695
- var parameter = _f.value;
1696
- _loop_1(parameter);
1594
+ for (var _g = __values(parameters.filter(function (_a) {
1595
+ var isInput = _a.isInput;
1596
+ return isInput;
1597
+ })), _h = _g.next(); !_h.done; _h = _g.next()) {
1598
+ var parameter = _h.value;
1599
+ commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1697
1600
  }
1698
1601
  }
1699
1602
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1700
1603
  finally {
1701
1604
  try {
1702
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
1703
- }
1704
- finally { if (e_1) throw e_1.error; }
1705
- }
1706
- // Note: Check each template individually
1707
- var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
1708
- var isInput = _a.isInput;
1709
- return isInput;
1710
- }).map(function (_a) {
1711
- var name = _a.name;
1712
- return name;
1713
- }));
1714
- try {
1715
- for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
1716
- var template = _h.value;
1717
- if (definedParameters.has(template.resultingParameterName)) {
1718
- throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
1719
- }
1720
- definedParameters.add(template.resultingParameterName);
1721
- if (template.executionType === 'PROMPT_TEMPLATE' &&
1722
- (template.modelRequirements.modelVariant === undefined)) {
1723
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
1724
- }
1725
- if (template.jokers && template.jokers.length > 0) {
1726
- if (!template.expectFormat &&
1727
- !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1728
- throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
1729
- }
1730
- try {
1731
- for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
1732
- var joker = _k.value;
1733
- if (!template.dependentParameterNames.includes(joker)) {
1734
- throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
1735
- }
1736
- }
1737
- }
1738
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1739
- finally {
1740
- try {
1741
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
1742
- }
1743
- finally { if (e_3) throw e_3.error; }
1744
- }
1745
- }
1746
- if (template.expectations) {
1747
- try {
1748
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1749
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1750
- if (min !== undefined && max !== undefined && min > max) {
1751
- throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
1752
- }
1753
- if (min !== undefined && min < 0) {
1754
- throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
1755
- }
1756
- if (max !== undefined && max <= 0) {
1757
- throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
1758
- }
1759
- }
1760
- }
1761
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1762
- finally {
1763
- try {
1764
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
1765
- }
1766
- finally { if (e_4) throw e_4.error; }
1767
- }
1768
- }
1769
- }
1770
- }
1771
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1772
- finally {
1773
- try {
1774
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
1775
- }
1776
- finally { if (e_2) throw e_2.error; }
1777
- }
1778
- // Note: Detect circular dependencies
1779
- var resovedParameters = promptbook.parameters
1780
- .filter(function (_a) {
1781
- var isInput = _a.isInput;
1782
- return isInput;
1783
- })
1784
- .map(function (_a) {
1785
- var name = _a.name;
1786
- return name;
1787
- });
1788
- var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1789
- var loopLimit = LOOP_LIMIT;
1790
- var _loop_2 = function () {
1791
- if (loopLimit-- < 0) {
1792
- throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbookJson`');
1793
- }
1794
- var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
1795
- return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
1796
- });
1797
- if (currentlyResovedTemplates.length === 0) {
1798
- throw new PromptbookLogicError(spaceTrim.spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
1799
- .map(function (_a) {
1800
- var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
1801
- return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
1802
- .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
1803
- .join(', '));
1804
- })
1805
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
1806
- }
1807
- resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
1808
- var resultingParameterName = _a.resultingParameterName;
1809
- return resultingParameterName;
1810
- })), false);
1811
- unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
1812
- };
1813
- while (unresovedTemplates.length > 0) {
1814
- _loop_2();
1815
- }
1816
- return promptbook;
1817
- }
1818
- /**
1819
- * TODO: [🧠] Work with promptbookVersion
1820
- * TODO: Use here some json-schema, Zod or something similar and change it to:
1821
- * > /**
1822
- * > * Validates PromptbookJson if it is logically valid.
1823
- * > *
1824
- * > * It checks:
1825
- * > * - it has a valid structure
1826
- * > * - ...
1827
- * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
1828
- */
1829
-
1830
- /**
1831
- * This error indicates that the promptbook library cannot be propperly loaded
1832
- */
1833
- var PromptbookLibraryError = /** @class */ (function (_super) {
1834
- __extends(PromptbookLibraryError, _super);
1835
- function PromptbookLibraryError(message) {
1836
- var _this = _super.call(this, message) || this;
1837
- _this.name = 'PromptbookLibraryError';
1838
- Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
1839
- return _this;
1840
- }
1841
- return PromptbookLibraryError;
1842
- }(Error));
1843
-
1844
- /**
1845
- * Detects if the code is running in a browser environment in main thread (Not in a web worker)
1846
- */
1847
- new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1848
- /**
1849
- * Detects if the code is running in a Node.js environment
1850
- */
1851
- var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1852
- /**
1853
- * Detects if the code is running in a web worker
1854
- */
1855
- new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
1856
-
1857
- /**
1858
- * Prettify the html code
1859
- *
1860
- * @param content raw html code
1861
- * @returns formatted html code
1862
- */
1863
- function prettifyMarkdown(content) {
1864
- try {
1865
- return prettier.format(content, {
1866
- parser: 'markdown',
1867
- plugins: [parserHtml__default["default"]],
1868
- // TODO: DRY - make some import or auto-copy of .prettierrc
1869
- endOfLine: 'lf',
1870
- tabWidth: 4,
1871
- singleQuote: true,
1872
- trailingComma: 'all',
1873
- arrowParens: 'always',
1874
- printWidth: 120,
1875
- htmlWhitespaceSensitivity: 'ignore',
1876
- jsxBracketSameLine: false,
1877
- bracketSpacing: true,
1878
- });
1879
- }
1880
- catch (error) {
1881
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1882
- error: error,
1883
- html: content,
1884
- });
1885
- return content;
1886
- }
1887
- }
1888
-
1889
- /**
1890
- * Converts promptbook in JSON format to string format
1891
- *
1892
- * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1893
- * @returns Promptbook in string format (.ptbk.md)
1894
- */
1895
- function promptbookJsonToString(promptbookJson) {
1896
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1897
- var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1898
- var promptbookString = "# ".concat(title);
1899
- if (description) {
1900
- promptbookString += '\n\n';
1901
- promptbookString += description;
1902
- }
1903
- // TODO:> const commands: Array<Command>
1904
- var commands = [];
1905
- if (promptbookUrl) {
1906
- commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1907
- }
1908
- commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1909
- promptbookString = prettifyMarkdown(promptbookString);
1910
- try {
1911
- for (var _g = __values(parameters.filter(function (_a) {
1912
- var isInput = _a.isInput;
1913
- return isInput;
1914
- })), _h = _g.next(); !_h.done; _h = _g.next()) {
1915
- var parameter = _h.value;
1916
- commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1917
- }
1918
- }
1919
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1920
- finally {
1921
- try {
1922
- if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1605
+ if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1923
1606
  }
1924
1607
  finally { if (e_1) throw e_1.error; }
1925
1608
  }
@@ -2011,252 +1694,1517 @@
2011
1694
  catch (e_5_1) { e_5 = { error: e_5_1 }; }
2012
1695
  finally {
2013
1696
  try {
2014
- if (postprocessing_1_1 && !postprocessing_1_1.done && (_e = postprocessing_1.return)) _e.call(postprocessing_1);
2015
- }
2016
- finally { if (e_5) throw e_5.error; }
2017
- }
2018
- } /* not else */
2019
- if (expectations) {
2020
- try {
2021
- for (var _l = (e_6 = void 0, __values(Object.entries(expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
2022
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
2023
- if (min === max) {
2024
- commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
2025
- }
2026
- else {
2027
- if (min !== undefined) {
2028
- commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
2029
- } /* not else */
2030
- if (max !== undefined) {
2031
- commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
2032
- }
1697
+ if (postprocessing_1_1 && !postprocessing_1_1.done && (_e = postprocessing_1.return)) _e.call(postprocessing_1);
1698
+ }
1699
+ finally { if (e_5) throw e_5.error; }
1700
+ }
1701
+ } /* not else */
1702
+ if (expectations) {
1703
+ try {
1704
+ for (var _l = (e_6 = void 0, __values(Object.entries(expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1705
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1706
+ if (min === max) {
1707
+ commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1708
+ }
1709
+ else {
1710
+ if (min !== undefined) {
1711
+ commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1712
+ } /* not else */
1713
+ if (max !== undefined) {
1714
+ commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
1715
+ }
1716
+ }
1717
+ }
1718
+ }
1719
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
1720
+ finally {
1721
+ try {
1722
+ if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
1723
+ }
1724
+ finally { if (e_6) throw e_6.error; }
1725
+ }
1726
+ } /* not else */
1727
+ if (expectFormat) {
1728
+ if (expectFormat === 'JSON') {
1729
+ // TODO: @deprecated remove
1730
+ commands_1.push("EXPECT JSON");
1731
+ }
1732
+ } /* not else */
1733
+ promptbookString += '\n\n';
1734
+ promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
1735
+ promptbookString += '\n\n';
1736
+ promptbookString += '```' + contentLanguage;
1737
+ promptbookString += '\n';
1738
+ promptbookString += spaceTrim__default["default"](content);
1739
+ // <- TODO: !!! Escape
1740
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1741
+ promptbookString += '\n';
1742
+ promptbookString += '```';
1743
+ promptbookString += '\n\n';
1744
+ promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
1745
+ }
1746
+ }
1747
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1748
+ finally {
1749
+ try {
1750
+ if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
1751
+ }
1752
+ finally { if (e_3) throw e_3.error; }
1753
+ }
1754
+ return promptbookString;
1755
+ }
1756
+ /**
1757
+ * @private internal util of promptbookJsonToString
1758
+ */
1759
+ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
1760
+ var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
1761
+ var parameterString = "{".concat(name, "}");
1762
+ if (description) {
1763
+ parameterString = "".concat(parameterString, " ").concat(description);
1764
+ }
1765
+ return parameterString;
1766
+ }
1767
+ /**
1768
+ * TODO: Escape all
1769
+ */
1770
+
1771
+ /**
1772
+ * This error indicates that promptbook not found in the library
1773
+ */
1774
+ var PromptbookNotFoundError = /** @class */ (function (_super) {
1775
+ __extends(PromptbookNotFoundError, _super);
1776
+ function PromptbookNotFoundError(message) {
1777
+ var _this = _super.call(this, message) || this;
1778
+ _this.name = 'PromptbookNotFoundError';
1779
+ Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
1780
+ return _this;
1781
+ }
1782
+ return PromptbookNotFoundError;
1783
+ }(Error));
1784
+
1785
+ /**
1786
+ * This error indicates errors in referencing promptbooks between each other
1787
+ */
1788
+ var PromptbookReferenceError = /** @class */ (function (_super) {
1789
+ __extends(PromptbookReferenceError, _super);
1790
+ function PromptbookReferenceError(message) {
1791
+ var _this = _super.call(this, message) || this;
1792
+ _this.name = 'PromptbookReferenceError';
1793
+ Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
1794
+ return _this;
1795
+ }
1796
+ return PromptbookReferenceError;
1797
+ }(Error));
1798
+
1799
+ /**
1800
+ * Library of promptbooks that groups together promptbooks for an application.
1801
+ * This implementation is a very thin wrapper around the Array / Map of promptbooks.
1802
+ *
1803
+ * @see https://github.com/webgptorg/promptbook#promptbook-library
1804
+ */
1805
+ var SimplePromptbookLibrary = /** @class */ (function () {
1806
+ /**
1807
+ * Constructs a promptbook library from promptbooks
1808
+ *
1809
+ * @param promptbooks !!!
1810
+ *
1811
+ * Note: During the construction logic of all promptbooks are validated
1812
+ * Note: It is not recommended to use this constructor directly, use `createPromptbookLibraryFromSources` *(or other variant)* instead
1813
+ */
1814
+ function SimplePromptbookLibrary() {
1815
+ var e_1, _a;
1816
+ var promptbooks = [];
1817
+ for (var _i = 0; _i < arguments.length; _i++) {
1818
+ promptbooks[_i] = arguments[_i];
1819
+ }
1820
+ this.library = new Map();
1821
+ try {
1822
+ for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
1823
+ var promptbook = promptbooks_1_1.value;
1824
+ if (promptbook.promptbookUrl === undefined) {
1825
+ throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
1826
+ }
1827
+ validatePromptbookJson(promptbook);
1828
+ // Note: [🦄]
1829
+ if (this.library.has(promptbook.promptbookUrl) &&
1830
+ promptbookJsonToString(promptbook) !==
1831
+ promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
1832
+ throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
1833
+ }
1834
+ this.library.set(promptbook.promptbookUrl, promptbook);
1835
+ }
1836
+ }
1837
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1838
+ finally {
1839
+ try {
1840
+ if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
1841
+ }
1842
+ finally { if (e_1) throw e_1.error; }
1843
+ }
1844
+ }
1845
+ /**
1846
+ * Gets all promptbooks in the library
1847
+ */
1848
+ SimplePromptbookLibrary.prototype.listPromptbooks = function () {
1849
+ return Array.from(this.library.keys());
1850
+ };
1851
+ /**
1852
+ * Gets promptbook by its URL
1853
+ *
1854
+ * Note: This is not a direct fetching from the URL, but a lookup in the library
1855
+ */
1856
+ SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
1857
+ var _this = this;
1858
+ var promptbook = this.library.get(url);
1859
+ if (!promptbook) {
1860
+ if (this.listPromptbooks().length === 0) {
1861
+ throw new PromptbookNotFoundError(spaceTrim.spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
1862
+ }
1863
+ throw new PromptbookNotFoundError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
1864
+ .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
1865
+ .join('\n')), "\n\n "); }));
1866
+ }
1867
+ return promptbook;
1868
+ };
1869
+ /**
1870
+ * Checks whether given prompt was defined in any promptbook in the library
1871
+ */
1872
+ SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
1873
+ return true;
1874
+ };
1875
+ return SimplePromptbookLibrary;
1876
+ }());
1877
+
1878
+ /**
1879
+ * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
1880
+ *
1881
+ * Note: You can combine `PromptbookString` (`.ptbk.md`) with `PromptbookJson` BUT it is not recommended
1882
+ * Note: During the construction syntax and logic of all sources are validated
1883
+ *
1884
+ * @param promptbookSources
1885
+ * @returns PromptbookLibrary
1886
+ */
1887
+ function createPromptbookLibraryFromSources() {
1888
+ var promptbookSources = [];
1889
+ for (var _i = 0; _i < arguments.length; _i++) {
1890
+ promptbookSources[_i] = arguments[_i];
1891
+ }
1892
+ return __awaiter(this, void 0, void 0, function () {
1893
+ var promptbooks, promptbookSources_1, promptbookSources_1_1, source, promptbook, e_1_1;
1894
+ var e_1, _a;
1895
+ return __generator(this, function (_b) {
1896
+ switch (_b.label) {
1897
+ case 0:
1898
+ promptbooks = new Array();
1899
+ _b.label = 1;
1900
+ case 1:
1901
+ _b.trys.push([1, 8, 9, 10]);
1902
+ promptbookSources_1 = __values(promptbookSources), promptbookSources_1_1 = promptbookSources_1.next();
1903
+ _b.label = 2;
1904
+ case 2:
1905
+ if (!!promptbookSources_1_1.done) return [3 /*break*/, 7];
1906
+ source = promptbookSources_1_1.value;
1907
+ promptbook = void 0;
1908
+ if (!(typeof source === 'string')) return [3 /*break*/, 4];
1909
+ return [4 /*yield*/, promptbookStringToJson(source)];
1910
+ case 3:
1911
+ // Note: When directly creating from string, no need to validate the source
1912
+ // The validation is performed always before execution
1913
+ promptbook = _b.sent();
1914
+ return [3 /*break*/, 5];
1915
+ case 4:
1916
+ promptbook = source;
1917
+ _b.label = 5;
1918
+ case 5:
1919
+ promptbooks.push(promptbook);
1920
+ _b.label = 6;
1921
+ case 6:
1922
+ promptbookSources_1_1 = promptbookSources_1.next();
1923
+ return [3 /*break*/, 2];
1924
+ case 7: return [3 /*break*/, 10];
1925
+ case 8:
1926
+ e_1_1 = _b.sent();
1927
+ e_1 = { error: e_1_1 };
1928
+ return [3 /*break*/, 10];
1929
+ case 9:
1930
+ try {
1931
+ if (promptbookSources_1_1 && !promptbookSources_1_1.done && (_a = promptbookSources_1.return)) _a.call(promptbookSources_1);
1932
+ }
1933
+ finally { if (e_1) throw e_1.error; }
1934
+ return [7 /*endfinally*/];
1935
+ case 10: return [2 /*return*/, new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))()];
1936
+ }
1937
+ });
1938
+ });
1939
+ }
1940
+ /**
1941
+ * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1942
+ */
1943
+
1944
+ /* tslint:disable */
1945
+ function normalizeToKebabCase(sentence) {
1946
+ var e_1, _a;
1947
+ sentence = removeDiacritics(sentence);
1948
+ var charType;
1949
+ var lastCharType = 'OTHER';
1950
+ var normalizedName = '';
1951
+ try {
1952
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1953
+ var char = sentence_1_1.value;
1954
+ var normalizedChar = void 0;
1955
+ if (/^[a-z]$/.test(char)) {
1956
+ charType = 'LOWERCASE';
1957
+ normalizedChar = char;
1958
+ }
1959
+ else if (/^[A-Z]$/.test(char)) {
1960
+ charType = 'UPPERCASE';
1961
+ normalizedChar = char.toLowerCase();
1962
+ }
1963
+ else if (/^[0-9]$/.test(char)) {
1964
+ charType = 'NUMBER';
1965
+ normalizedChar = char;
1966
+ }
1967
+ else if (/^\/$/.test(char)) {
1968
+ charType = 'SLASH';
1969
+ normalizedChar = char;
1970
+ }
1971
+ else {
1972
+ charType = 'OTHER';
1973
+ normalizedChar = '-';
1974
+ }
1975
+ if (charType !== lastCharType &&
1976
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1977
+ !(lastCharType === 'NUMBER') &&
1978
+ !(charType === 'NUMBER')) {
1979
+ normalizedName += '-';
1980
+ }
1981
+ normalizedName += normalizedChar;
1982
+ lastCharType = charType;
1983
+ }
1984
+ }
1985
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1986
+ finally {
1987
+ try {
1988
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1989
+ }
1990
+ finally { if (e_1) throw e_1.error; }
1991
+ }
1992
+ normalizedName = normalizedName.split(/-+/g).join('-');
1993
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1994
+ normalizedName = normalizedName.replace(/^-/, '');
1995
+ normalizedName = normalizedName.replace(/-$/, '');
1996
+ return normalizedName;
1997
+ }
1998
+
1999
+ function prepareKnowledgeFromMarkdown(options) {
2000
+ return __awaiter(this, void 0, void 0, function () {
2001
+ var content, llmTools, _a, isVerbose, library, promptbook, executor, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
2002
+ var _this = this;
2003
+ return __generator(this, function (_b) {
2004
+ switch (_b.label) {
2005
+ case 0:
2006
+ content = options.content, llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
2007
+ return [4 /*yield*/, createPromptbookLibraryFromSources.apply(void 0, __spreadArray([], __read(promptbookLibrary), false))];
2008
+ case 1:
2009
+ library = _b.sent();
2010
+ promptbook = library.getPromptbookByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md');
2011
+ executor = createPromptbookExecutor({
2012
+ promptbook: promptbook,
2013
+ tools: {
2014
+ llm: llmTools,
2015
+ script: [
2016
+ /* <- TODO: Allow to just keep script undefined */
2017
+ ],
2018
+ },
2019
+ });
2020
+ return [4 /*yield*/, executor({ content: content })];
2021
+ case 2:
2022
+ result = _b.sent();
2023
+ assertsExecutionSuccessful(result);
2024
+ outputParameters = result.outputParameters;
2025
+ knowledgeRaw = outputParameters.knowledge;
2026
+ knowledgeTextPieces = (knowledgeRaw || '').split('\n---\n');
2027
+ if (isVerbose) {
2028
+ console.info('knowledgeTextPieces:', knowledgeTextPieces);
2029
+ }
2030
+ return [4 /*yield*/, Promise.all(knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
2031
+ var name, title, content, keywords, index, sources;
2032
+ return __generator(this, function (_a) {
2033
+ name = "piece-".concat(i);
2034
+ title = spaceTrim__default["default"](knowledgeTextPiece.substring(0, 100));
2035
+ content = spaceTrim__default["default"](knowledgeTextPiece);
2036
+ keywords = [];
2037
+ index = [];
2038
+ sources = [];
2039
+ try {
2040
+ // TODO: !!!! Summarize name and title from the content
2041
+ title = spaceTrim__default["default"](knowledgeTextPiece.substring(0, 30));
2042
+ name = normalizeToKebabCase(title);
2043
+ // TODO: !!!! Extract keywords via prompt
2044
+ // TODO: !!!! Index through LLM model
2045
+ // TODO: [🖖] !!!! Make system for sources and identification of sources
2046
+ }
2047
+ catch (error) {
2048
+ console.error(error);
2049
+ }
2050
+ return [2 /*return*/, {
2051
+ name: name,
2052
+ title: title,
2053
+ content: content,
2054
+ keywords: keywords,
2055
+ index: index,
2056
+ sources: sources,
2057
+ }];
2058
+ });
2059
+ }); }))];
2060
+ case 3:
2061
+ knowledge = _b.sent();
2062
+ return [2 /*return*/, knowledge];
2063
+ }
2064
+ });
2065
+ });
2066
+ }
2067
+
2068
+ /**
2069
+ * Supported script languages
2070
+ */
2071
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
2072
+
2073
+ /**
2074
+ * Computes the deepness of the markdown structure.
2075
+ *
2076
+ * @private within the library
2077
+ */
2078
+ function countMarkdownStructureDeepness(markdownStructure) {
2079
+ var e_1, _a;
2080
+ var maxDeepness = 0;
2081
+ try {
2082
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
2083
+ var section = _c.value;
2084
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
2085
+ }
2086
+ }
2087
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2088
+ finally {
2089
+ try {
2090
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2091
+ }
2092
+ finally { if (e_1) throw e_1.error; }
2093
+ }
2094
+ return maxDeepness + 1;
2095
+ }
2096
+
2097
+ /**
2098
+ * Parse a markdown string into a MarkdownStructure object.
2099
+ *
2100
+ * Note: This function does work with code blocks
2101
+ * Note: This function does not work with markdown comments
2102
+ *
2103
+ * @param markdown The markdown string to parse.
2104
+ * @returns The MarkdownStructure object.
2105
+ *
2106
+ * @private within the library
2107
+ */
2108
+ function markdownToMarkdownStructure(markdown) {
2109
+ var e_1, _a;
2110
+ var lines = markdown.split('\n');
2111
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
2112
+ var current = root;
2113
+ var isInsideCodeBlock = false;
2114
+ try {
2115
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2116
+ var line = lines_1_1.value;
2117
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
2118
+ if (isInsideCodeBlock || !headingMatch) {
2119
+ if (line.startsWith('```')) {
2120
+ isInsideCodeBlock = !isInsideCodeBlock;
2121
+ }
2122
+ current.contentLines.push(line);
2123
+ }
2124
+ else {
2125
+ var level = headingMatch.groups.mark.length;
2126
+ var title = headingMatch.groups.title.trim();
2127
+ var parent_1 = void 0;
2128
+ if (level > current.level) {
2129
+ // Note: Going deeper (next section is child of current)
2130
+ parent_1 = current;
2131
+ }
2132
+ else {
2133
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
2134
+ parent_1 = current;
2135
+ var loopLimit = LOOP_LIMIT;
2136
+ while (parent_1.level !== level - 1) {
2137
+ if (loopLimit-- < 0) {
2138
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
2139
+ }
2140
+ if (parent_1.parent === null /* <- Note: We are in root */) {
2141
+ // [🌻]
2142
+ throw new Error(spaceTrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
2143
+ }
2144
+ parent_1 = parent_1.parent;
2145
+ }
2146
+ }
2147
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
2148
+ parent_1.sections.push(section);
2149
+ current = section;
2150
+ }
2151
+ }
2152
+ }
2153
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2154
+ finally {
2155
+ try {
2156
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2157
+ }
2158
+ finally { if (e_1) throw e_1.error; }
2159
+ }
2160
+ if (root.sections.length === 1) {
2161
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
2162
+ return markdownStructure;
2163
+ }
2164
+ // [🌻]
2165
+ throw new Error('The markdown file must have exactly one top-level section.');
2166
+ // return root;
2167
+ }
2168
+ /**
2169
+ * @private
2170
+ */
2171
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
2172
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
2173
+ return {
2174
+ level: level,
2175
+ title: title,
2176
+ content: spaceTrim.spaceTrim(contentLines.join('\n')),
2177
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
2178
+ };
2179
+ }
2180
+
2181
+ /**
2182
+ * Utility function to extract all list items from markdown
2183
+ *
2184
+ * Note: It works with both ul and ol
2185
+ * Note: It omits list items in code blocks
2186
+ * Note: It flattens nested lists
2187
+ * Note: It can not work with html syntax and comments
2188
+ *
2189
+ * @param markdown any valid markdown
2190
+ * @returns
2191
+ */
2192
+ function extractAllListItemsFromMarkdown(markdown) {
2193
+ var e_1, _a;
2194
+ var lines = markdown.split('\n');
2195
+ var listItems = [];
2196
+ var isInCodeBlock = false;
2197
+ try {
2198
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2199
+ var line = lines_1_1.value;
2200
+ var trimmedLine = line.trim();
2201
+ if (trimmedLine.startsWith('```')) {
2202
+ isInCodeBlock = !isInCodeBlock;
2203
+ }
2204
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
2205
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
2206
+ listItems.push(listItem);
2207
+ }
2208
+ }
2209
+ }
2210
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2211
+ finally {
2212
+ try {
2213
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2214
+ }
2215
+ finally { if (e_1) throw e_1.error; }
2216
+ }
2217
+ return listItems;
2218
+ }
2219
+
2220
+ /**
2221
+ * Extracts all code blocks from markdown.
2222
+ *
2223
+ * Note: There are 3 simmilar function:
2224
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2225
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2226
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2227
+ *
2228
+ * @param markdown any valid markdown
2229
+ * @returns code blocks with language and content
2230
+ *
2231
+ */
2232
+ function extractAllBlocksFromMarkdown(markdown) {
2233
+ var e_1, _a;
2234
+ var codeBlocks = [];
2235
+ var lines = markdown.split('\n');
2236
+ var currentCodeBlock = null;
2237
+ try {
2238
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2239
+ var line = lines_1_1.value;
2240
+ if (line.startsWith('```')) {
2241
+ var language = line.slice(3).trim() || null;
2242
+ if (currentCodeBlock === null) {
2243
+ currentCodeBlock = { language: language, content: '' };
2244
+ }
2245
+ else {
2246
+ if (language !== null) {
2247
+ // [🌻]
2248
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2249
+ }
2250
+ codeBlocks.push(currentCodeBlock);
2251
+ currentCodeBlock = null;
2252
+ }
2253
+ }
2254
+ else if (currentCodeBlock !== null) {
2255
+ if (currentCodeBlock.content !== '') {
2256
+ currentCodeBlock.content += '\n';
2257
+ }
2258
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2259
+ }
2260
+ }
2261
+ }
2262
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2263
+ finally {
2264
+ try {
2265
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2266
+ }
2267
+ finally { if (e_1) throw e_1.error; }
2268
+ }
2269
+ if (currentCodeBlock !== null) {
2270
+ // [🌻]
2271
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2272
+ }
2273
+ return codeBlocks;
2274
+ }
2275
+
2276
+ /**
2277
+ * Extracts exactly ONE code block from markdown.
2278
+ *
2279
+ * Note: If there are multiple or no code blocks the function throws an error
2280
+ *
2281
+ * Note: There are 3 simmilar function:
2282
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2283
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2284
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2285
+ *
2286
+ * @param markdown any valid markdown
2287
+ * @returns code block with language and content
2288
+ */
2289
+ function extractOneBlockFromMarkdown(markdown) {
2290
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2291
+ if (codeBlocks.length !== 1) {
2292
+ // TODO: Report more specific place where the error happened
2293
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
2294
+ }
2295
+ return codeBlocks[0];
2296
+ }
2297
+ /***
2298
+ * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
2299
+ */
2300
+
2301
+ /**
2302
+ * Removes HTML or Markdown comments from a string.
2303
+ *
2304
+ * @param {string} content - The string to remove comments from.
2305
+ * @returns {string} The input string with all comments removed.
2306
+ */
2307
+ function removeContentComments(content) {
2308
+ return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
2309
+ }
2310
+
2311
+ /**
2312
+ * Creates a new set with all elements that are present in either set
2313
+ */
2314
+ function union() {
2315
+ var e_1, _a, e_2, _b;
2316
+ var sets = [];
2317
+ for (var _i = 0; _i < arguments.length; _i++) {
2318
+ sets[_i] = arguments[_i];
2319
+ }
2320
+ var union = new Set();
2321
+ try {
2322
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2323
+ var set = sets_1_1.value;
2324
+ try {
2325
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2326
+ var item = _d.value;
2327
+ union.add(item);
2328
+ }
2329
+ }
2330
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2331
+ finally {
2332
+ try {
2333
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2334
+ }
2335
+ finally { if (e_2) throw e_2.error; }
2336
+ }
2337
+ }
2338
+ }
2339
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2340
+ finally {
2341
+ try {
2342
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2343
+ }
2344
+ finally { if (e_1) throw e_1.error; }
2345
+ }
2346
+ return union;
2347
+ }
2348
+
2349
+ /**
2350
+ * Parses the template and returns the list of all parameter names
2351
+ *
2352
+ * @param template the template with parameters in {curly} braces
2353
+ * @returns the list of parameter names
2354
+ */
2355
+ function extractParameters(template) {
2356
+ var e_1, _a;
2357
+ var matches = template.matchAll(/{\w+}/g);
2358
+ var parameterNames = new Set();
2359
+ try {
2360
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
2361
+ var match = matches_1_1.value;
2362
+ var parameterName = match[0].slice(1, -1);
2363
+ parameterNames.add(parameterName);
2364
+ }
2365
+ }
2366
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2367
+ finally {
2368
+ try {
2369
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
2370
+ }
2371
+ finally { if (e_1) throw e_1.error; }
2372
+ }
2373
+ return parameterNames;
2374
+ }
2375
+
2376
+ /**
2377
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2378
+ *
2379
+ * @param script from which to extract the variables
2380
+ * @returns the list of variable names
2381
+ * @throws {PromptbookSyntaxError} if the script is invalid
2382
+ */
2383
+ function extractVariables(script) {
2384
+ var variables = new Set();
2385
+ script = "(()=>{".concat(script, "})()");
2386
+ try {
2387
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2388
+ try {
2389
+ eval(script);
2390
+ }
2391
+ catch (error) {
2392
+ if (!(error instanceof ReferenceError)) {
2393
+ throw error;
2394
+ }
2395
+ var undefinedName = error.message.split(' ')[0];
2396
+ /*
2397
+ Note: Remapping error
2398
+ From: [ReferenceError: thing is not defined],
2399
+ To: [Error: Parameter {thing} is not defined],
2400
+ */
2401
+ if (!undefinedName) {
2402
+ throw error;
2403
+ }
2404
+ if (script.includes(undefinedName + '(')) {
2405
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2406
+ }
2407
+ else {
2408
+ variables.add(undefinedName);
2409
+ script = "const ".concat(undefinedName, " = '';") + script;
2410
+ }
2411
+ }
2412
+ }
2413
+ catch (error) {
2414
+ if (!(error instanceof Error)) {
2415
+ throw error;
2416
+ }
2417
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
2418
+ }
2419
+ return variables;
2420
+ }
2421
+ /**
2422
+ * TODO: [🔣] Support for multiple languages - python, java,...
2423
+ */
2424
+
2425
+ /**
2426
+ * Parses the prompt template and returns the set of all used parameters
2427
+ *
2428
+ * @param promptTemplate the template with used parameters
2429
+ * @returns the set of parameter names
2430
+ * @throws {PromptbookSyntaxError} if the script is invalid
2431
+ */
2432
+ function extractParametersFromPromptTemplate(promptTemplate) {
2433
+ var e_1, _a, e_2, _b;
2434
+ var parameterNames = new Set();
2435
+ try {
2436
+ for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
2437
+ var parameterName = _d.value;
2438
+ parameterNames.add(parameterName);
2439
+ }
2440
+ }
2441
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2442
+ finally {
2443
+ try {
2444
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
2445
+ }
2446
+ finally { if (e_1) throw e_1.error; }
2447
+ }
2448
+ if (promptTemplate.executionType === 'SCRIPT') {
2449
+ try {
2450
+ for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
2451
+ var parameterName = _f.value;
2452
+ parameterNames.add(parameterName);
2453
+ }
2454
+ }
2455
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2456
+ finally {
2457
+ try {
2458
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
2459
+ }
2460
+ finally { if (e_2) throw e_2.error; }
2461
+ }
2462
+ }
2463
+ return parameterNames;
2464
+ }
2465
+ /**
2466
+ * TODO: [🔣] If script require contentLanguage
2467
+ */
2468
+
2469
+ /* tslint:disable */
2470
+ /*
2471
+ TODO: Tests
2472
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
2473
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
2474
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
2475
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
2476
+ */
2477
+ function normalizeTo_SCREAMING_CASE(sentence) {
2478
+ var e_1, _a;
2479
+ var charType;
2480
+ var lastCharType = 'OTHER';
2481
+ var normalizedName = '';
2482
+ try {
2483
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
2484
+ var char = sentence_1_1.value;
2485
+ var normalizedChar = void 0;
2486
+ if (/^[a-z]$/.test(char)) {
2487
+ charType = 'LOWERCASE';
2488
+ normalizedChar = char.toUpperCase();
2489
+ }
2490
+ else if (/^[A-Z]$/.test(char)) {
2491
+ charType = 'UPPERCASE';
2492
+ normalizedChar = char;
2493
+ }
2494
+ else if (/^[0-9]$/.test(char)) {
2495
+ charType = 'NUMBER';
2496
+ normalizedChar = char;
2497
+ }
2498
+ else if (/^\/$/.test(char)) {
2499
+ charType = 'SLASH';
2500
+ normalizedChar = char;
2501
+ }
2502
+ else {
2503
+ charType = 'OTHER';
2504
+ normalizedChar = '_';
2505
+ }
2506
+ if (charType !== lastCharType &&
2507
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
2508
+ !(lastCharType === 'NUMBER') &&
2509
+ !(charType === 'NUMBER')) {
2510
+ normalizedName += '_';
2511
+ }
2512
+ normalizedName += normalizedChar;
2513
+ lastCharType = charType;
2514
+ }
2515
+ }
2516
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2517
+ finally {
2518
+ try {
2519
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
2520
+ }
2521
+ finally { if (e_1) throw e_1.error; }
2522
+ }
2523
+ normalizedName = normalizedName.replace(/_+/g, '_');
2524
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
2525
+ normalizedName = normalizedName.replace(/^_/, '');
2526
+ normalizedName = normalizedName.replace(/_$/, '');
2527
+ return normalizedName;
2528
+ }
2529
+ /**
2530
+ * TODO: [🌺] Use some intermediate util splitWords
2531
+ */
2532
+
2533
+ /**
2534
+ * Execution type describes the way how the block is executed
2535
+ *
2536
+ * @see https://github.com/webgptorg/promptbook#execution-type
2537
+ */
2538
+ var ExecutionTypes = [
2539
+ 'PROMPT_TEMPLATE',
2540
+ 'SIMPLE_TEMPLATE',
2541
+ 'SCRIPT',
2542
+ 'PROMPT_DIALOG',
2543
+ // <- [🥻] Insert here when making new command
2544
+ ];
2545
+
2546
+ /**
2547
+ * Units of text measurement
2548
+ */
2549
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2550
+ /**
2551
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
2552
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
2553
+ * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
2554
+ */
2555
+
2556
+ /**
2557
+ * Removes Markdown formatting tags from a string.
2558
+ *
2559
+ * @param {string} str - The string to remove Markdown tags from.
2560
+ * @returns {string} The input string with all Markdown tags removed.
2561
+ */
2562
+ function removeMarkdownFormatting(str) {
2563
+ // Remove bold formatting
2564
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
2565
+ // Remove italic formatting
2566
+ str = str.replace(/\*(.*?)\*/g, '$1');
2567
+ // Remove code formatting
2568
+ str = str.replace(/`(.*?)`/g, '$1');
2569
+ return str;
2570
+ }
2571
+
2572
+ /**
2573
+ * Function parseNumber will parse number from string
2574
+ *
2575
+ * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
2576
+ * Note: it also works only with decimal numbers
2577
+ *
2578
+ * @returns parsed number
2579
+ * @throws {PromptbookSyntaxError} if the value is not a number
2580
+ *
2581
+ * @private within the parseCommand
2582
+ */
2583
+ function parseNumber(value) {
2584
+ var originalValue = value;
2585
+ if (typeof value === 'number') {
2586
+ value = value.toString(); // <- TODO: Maybe more efficient way to do this
2587
+ }
2588
+ if (typeof value !== 'string') {
2589
+ return 0;
2590
+ }
2591
+ value = value.trim();
2592
+ if (value.startsWith('+')) {
2593
+ return parseNumber(value.substring(1));
2594
+ }
2595
+ if (value.startsWith('-')) {
2596
+ var number = parseNumber(value.substring(1));
2597
+ if (number === 0) {
2598
+ return 0; // <- Note: To prevent -0
2599
+ }
2600
+ return -number;
2601
+ }
2602
+ value = value.replace(/,/g, '.');
2603
+ value = value.toUpperCase();
2604
+ if (value === '') {
2605
+ return 0;
2606
+ }
2607
+ if (value === '♾' || value.startsWith('INF')) {
2608
+ return Infinity;
2609
+ }
2610
+ if (value.includes('/')) {
2611
+ var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
2612
+ var numerator = parseNumber(numerator_);
2613
+ var denominator = parseNumber(denominator_);
2614
+ if (denominator === 0) {
2615
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
2616
+ }
2617
+ return numerator / denominator;
2618
+ }
2619
+ if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
2620
+ return 0;
2621
+ }
2622
+ if (value.includes('E')) {
2623
+ var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
2624
+ return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
2625
+ }
2626
+ if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
2627
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
2628
+ }
2629
+ var num = parseFloat(value);
2630
+ if (isNaN(num)) {
2631
+ throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
2632
+ }
2633
+ return num;
2634
+ }
2635
+ /**
2636
+ * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
2637
+ */
2638
+
2639
+ /**
2640
+ * Parses one line of ul/ol to command
2641
+ *
2642
+ * @returns parsed command object
2643
+ * @throws {PromptbookSyntaxError} if the command is invalid
2644
+ *
2645
+ * @private within the promptbookStringToJson
2646
+ */
2647
+ function parseCommand(listItem) {
2648
+ var e_1, _a;
2649
+ if (listItem.includes('\n') || listItem.includes('\r')) {
2650
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
2651
+ }
2652
+ var type = listItem.trim();
2653
+ type = type.split('`').join('');
2654
+ type = type.split('"').join('');
2655
+ type = type.split("'").join('');
2656
+ type = type.split('~').join('');
2657
+ type = type.split('[').join('');
2658
+ type = type.split(']').join('');
2659
+ type = type.split('(').join('');
2660
+ type = type.split(')').join('');
2661
+ type = normalizeTo_SCREAMING_CASE(type);
2662
+ type = type.split('DIALOGUE').join('DIALOG');
2663
+ var listItemParts = listItem
2664
+ .split(' ')
2665
+ .map(function (part) { return part.trim(); })
2666
+ .filter(function (item) { return item !== ''; })
2667
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
2668
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
2669
+ .map(removeMarkdownFormatting);
2670
+ if (type.startsWith('URL') ||
2671
+ type.startsWith('PTBK_URL') ||
2672
+ type.startsWith('PTBKURL') ||
2673
+ type.startsWith('PROMPTBOOK_URL') ||
2674
+ type.startsWith('PROMPTBOOKURL') ||
2675
+ type.startsWith('HTTPS')) {
2676
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
2677
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
2678
+ }
2679
+ var promptbookUrlString = listItemParts.pop();
2680
+ var promptbookUrl = new URL(promptbookUrlString);
2681
+ if (promptbookUrl.protocol !== 'https:') {
2682
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
2683
+ }
2684
+ if (promptbookUrl.hash !== '') {
2685
+ throw new PromptbookSyntaxError(spaceTrim.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 ")));
2686
+ }
2687
+ return {
2688
+ type: 'PROMPTBOOK_URL',
2689
+ promptbookUrl: promptbookUrl,
2690
+ };
2691
+ }
2692
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
2693
+ if (listItemParts.length !== 2) {
2694
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
2695
+ }
2696
+ var promptbookVersion = listItemParts.pop();
2697
+ // TODO: Validate version
2698
+ return {
2699
+ type: 'PROMPTBOOK_VERSION',
2700
+ promptbookVersion: promptbookVersion,
2701
+ };
2702
+ }
2703
+ else if (type.startsWith('EXECUTE') ||
2704
+ type.startsWith('EXEC') ||
2705
+ type.startsWith('PROMPT_DIALOG') ||
2706
+ type.startsWith('SIMPLE_TEMPLATE')) {
2707
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
2708
+ if (executionTypes.length !== 1) {
2709
+ throw new PromptbookSyntaxError(spaceTrim.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 "); }));
2710
+ }
2711
+ return {
2712
+ type: 'EXECUTE',
2713
+ executionType: executionTypes[0],
2714
+ };
2715
+ }
2716
+ else if (type.startsWith('MODEL')) {
2717
+ // TODO: Make this more elegant and dynamically
2718
+ if (type.startsWith('MODEL_VARIANT')) {
2719
+ if (type === 'MODEL_VARIANT_CHAT') {
2720
+ return {
2721
+ type: 'MODEL',
2722
+ key: 'modelVariant',
2723
+ value: 'CHAT',
2724
+ };
2725
+ }
2726
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
2727
+ return {
2728
+ type: 'MODEL',
2729
+ key: 'modelVariant',
2730
+ value: 'COMPLETION',
2731
+ };
2732
+ }
2733
+ else {
2734
+ throw new PromptbookSyntaxError(spaceTrim.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 "); }));
2735
+ }
2736
+ }
2737
+ if (type.startsWith('MODEL_NAME')) {
2738
+ return {
2739
+ type: 'MODEL',
2740
+ key: 'modelName',
2741
+ value: listItemParts.pop(),
2742
+ };
2743
+ }
2744
+ else {
2745
+ throw new PromptbookSyntaxError(spaceTrim.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 "); }));
2746
+ }
2747
+ }
2748
+ else if (type.startsWith('PARAM') ||
2749
+ type.startsWith('INPUT_PARAM') ||
2750
+ type.startsWith('OUTPUT_PARAM') ||
2751
+ listItem.startsWith('{') ||
2752
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
2753
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
2754
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2755
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2756
+ }
2757
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2758
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
2759
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
2760
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
2761
+ }
2762
+ var isInput = type.startsWith('INPUT');
2763
+ var isOutput = type.startsWith('OUTPUT');
2764
+ if (listItem.startsWith('> {')) {
2765
+ isInput = false;
2766
+ isOutput = false;
2767
+ }
2768
+ return {
2769
+ type: 'PARAMETER',
2770
+ parameterName: parameterName,
2771
+ parameterDescription: parameterDescription.trim() || null,
2772
+ isInput: isInput,
2773
+ isOutput: isOutput,
2774
+ };
2775
+ }
2776
+ else if (type.startsWith('JOKER')) {
2777
+ if (listItemParts.length !== 2) {
2778
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
2779
+ }
2780
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
2781
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2782
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2783
+ }
2784
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2785
+ var parameterName = parametersMatch.groups.parameterName;
2786
+ return {
2787
+ type: 'JOKER',
2788
+ parameterName: parameterName,
2789
+ };
2790
+ }
2791
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
2792
+ if (listItemParts.length !== 2) {
2793
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
2794
+ }
2795
+ var functionName = listItemParts.pop();
2796
+ return {
2797
+ type: 'POSTPROCESS',
2798
+ functionName: functionName,
2799
+ };
2800
+ }
2801
+ else if (type.startsWith('EXPECT_JSON')) {
2802
+ return {
2803
+ type: 'EXPECT_FORMAT',
2804
+ format: 'JSON',
2805
+ };
2806
+ // [🥤]
2807
+ }
2808
+ else if (type.startsWith('EXPECT')) {
2809
+ try {
2810
+ listItemParts.shift();
2811
+ var sign = void 0;
2812
+ var signRaw = listItemParts.shift();
2813
+ if (/^exact/i.test(signRaw)) {
2814
+ sign = 'EXACTLY';
2815
+ }
2816
+ else if (/^min/i.test(signRaw)) {
2817
+ sign = 'MINIMUM';
2818
+ }
2819
+ else if (/^max/i.test(signRaw)) {
2820
+ sign = 'MAXIMUM';
2821
+ }
2822
+ else {
2823
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
2824
+ }
2825
+ var amountRaw = listItemParts.shift();
2826
+ var amount = parseNumber(amountRaw);
2827
+ if (amount < 0) {
2828
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
2829
+ }
2830
+ if (amount !== Math.floor(amount)) {
2831
+ throw new PromptbookSyntaxError('Amount must be whole number');
2832
+ }
2833
+ var unitRaw = listItemParts.shift();
2834
+ var unit = undefined;
2835
+ try {
2836
+ 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()) {
2837
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
2838
+ var existingUnitText = existingUnit;
2839
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
2840
+ if (existingUnitText === 'CHARACTER') {
2841
+ existingUnitText = 'CHAR';
2842
+ }
2843
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
2844
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
2845
+ if (unit !== undefined) {
2846
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
2847
+ }
2848
+ unit = existingUnit;
2849
+ }
2850
+ }
2851
+ }
2852
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2853
+ finally {
2854
+ try {
2855
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
2856
+ }
2857
+ finally { if (e_1) throw e_1.error; }
2858
+ }
2859
+ if (unit === undefined) {
2860
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
2861
+ }
2862
+ return {
2863
+ type: 'EXPECT_AMOUNT',
2864
+ sign: sign,
2865
+ unit: unit,
2866
+ amount: amount,
2867
+ };
2868
+ }
2869
+ catch (error) {
2870
+ if (!(error instanceof Error)) {
2871
+ throw error;
2872
+ }
2873
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
2874
+ }
2875
+ /*
2876
+ } else if (type.startsWith('__________________')) {
2877
+ // <- [🥻] Insert here when making new command
2878
+ */
2879
+ }
2880
+ else {
2881
+ throw new PromptbookSyntaxError(spaceTrim.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 ")));
2882
+ }
2883
+ }
2884
+
2885
+ /**
2886
+ * Removes emojis from a string and fix whitespaces
2887
+ *
2888
+ * @param text with emojis
2889
+ * @returns text without emojis
2890
+ */
2891
+ function removeEmojis(text) {
2892
+ // Replace emojis (and also ZWJ sequence) with hyphens
2893
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2894
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2895
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
2896
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
2897
+ return text;
2898
+ }
2899
+
2900
+ /**
2901
+ * Function normalizes title to name which can be used as identifier
2902
+ */
2903
+ function titleToName(value) {
2904
+ value = removeEmojis(value);
2905
+ value = normalizeToKebabCase(value);
2906
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
2907
+ return value;
2908
+ }
2909
+
2910
+ /**
2911
+ * Compile promptbook from string (markdown) format to JSON format
2912
+ *
2913
+ * @param promptbookString {Promptbook} in string markdown format (.ptbk.md)
2914
+ * @param options - Options and tools for the compilation
2915
+ * @returns {Promptbook} compiled in JSON format (.ptbk.json)
2916
+ * @throws {PromptbookSyntaxError} if the promptbook string is not valid
2917
+ *
2918
+ * Note: This function does not validate logic of the pipeline only the syntax
2919
+ * Note: This function acts as compilation process
2920
+ */
2921
+ function promptbookStringToJson(promptbookString, options) {
2922
+ if (options === void 0) { options = {}; }
2923
+ return __awaiter(this, void 0, void 0, function () {
2924
+ var llmTools, promptbookJson, knowledge, addParam, markdownStructure, markdownStructureDeepness, description, defaultModelRequirements, listItems, listItems_1, listItems_1_1, listItem, command, _loop_1, _a, _b, section;
2925
+ var e_1, _c, e_2, _d;
2926
+ return __generator(this, function (_e) {
2927
+ switch (_e.label) {
2928
+ case 0:
2929
+ llmTools = options.llmTools;
2930
+ promptbookJson = {
2931
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2932
+ title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
2933
+ promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
2934
+ promptbookVersion: PROMPTBOOK_VERSION,
2935
+ description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
2936
+ parameters: [],
2937
+ promptTemplates: [],
2938
+ knowledge: [],
2939
+ };
2940
+ if (!llmTools) return [3 /*break*/, 2];
2941
+ return [4 /*yield*/, prepareKnowledgeFromMarkdown({
2942
+ content: 'Roses are red, violets are blue, programmers use Promptbook, users too',
2943
+ llmTools: llmTools,
2944
+ })];
2945
+ case 1:
2946
+ knowledge = _e.sent();
2947
+ console.info('!!!! knowledge', knowledge);
2948
+ _e.label = 2;
2949
+ case 2:
2950
+ // =============================================================
2951
+ // Note: 1️⃣ Normalization of the PROMPTBOOK string
2952
+ promptbookString = removeContentComments(promptbookString);
2953
+ promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
2954
+ promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
2955
+ addParam = function (parameterCommand) {
2956
+ var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
2957
+ var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
2958
+ if (existingParameter &&
2959
+ existingParameter.description &&
2960
+ existingParameter.description !== parameterDescription &&
2961
+ parameterDescription) {
2962
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
2963
+ }
2964
+ if (existingParameter) {
2965
+ if (parameterDescription) {
2966
+ existingParameter.description = parameterDescription;
2967
+ }
2968
+ }
2969
+ else {
2970
+ promptbookJson.parameters.push({
2971
+ name: parameterName,
2972
+ description: parameterDescription || undefined,
2973
+ isInput: isInput,
2974
+ isOutput: isOutput,
2975
+ });
2976
+ }
2977
+ };
2978
+ markdownStructure = markdownToMarkdownStructure(promptbookString);
2979
+ markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
2980
+ if (markdownStructureDeepness !== 2) {
2981
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
2982
+ }
2983
+ promptbookJson.title = markdownStructure.title;
2984
+ description = markdownStructure.content;
2985
+ // Note: Remove codeblocks
2986
+ description = description.split(/^```.*^```/gms).join('');
2987
+ //Note: Remove lists and return statement
2988
+ description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
2989
+ description = spaceTrim.spaceTrim(description);
2990
+ if (description === '') {
2991
+ description = undefined;
2992
+ }
2993
+ promptbookJson.description = description;
2994
+ defaultModelRequirements = {};
2995
+ listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
2996
+ try {
2997
+ for (listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
2998
+ listItem = listItems_1_1.value;
2999
+ command = parseCommand(listItem);
3000
+ switch (command.type) {
3001
+ case 'PROMPTBOOK_URL':
3002
+ promptbookJson.promptbookUrl = command.promptbookUrl.href;
3003
+ break;
3004
+ case 'PROMPTBOOK_VERSION':
3005
+ promptbookJson.promptbookVersion = command.promptbookVersion;
3006
+ break;
3007
+ case 'MODEL':
3008
+ defaultModelRequirements[command.key] = command.value;
3009
+ break;
3010
+ case 'PARAMETER':
3011
+ addParam(command);
3012
+ break;
3013
+ default:
3014
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
3015
+ }
3016
+ }
3017
+ }
3018
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3019
+ finally {
3020
+ try {
3021
+ if (listItems_1_1 && !listItems_1_1.done && (_c = listItems_1.return)) _c.call(listItems_1);
3022
+ }
3023
+ finally { if (e_1) throw e_1.error; }
3024
+ }
3025
+ _loop_1 = function (section) {
3026
+ var e_3, _f;
3027
+ // TODO: Parse prompt template description (the content out of the codeblock and lists)
3028
+ var templateModelRequirements = __assign({}, defaultModelRequirements);
3029
+ var listItems_3 = extractAllListItemsFromMarkdown(section.content);
3030
+ var dependentParameterNames = new Set();
3031
+ var executionType = 'PROMPT_TEMPLATE';
3032
+ var jokers = [];
3033
+ var postprocessing = [];
3034
+ var expectAmount = {};
3035
+ var expectFormat = undefined;
3036
+ var isExecutionTypeChanged = false;
3037
+ try {
3038
+ for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
3039
+ var listItem = listItems_2_1.value;
3040
+ var command = parseCommand(listItem);
3041
+ switch (command.type) {
3042
+ case 'JOKER':
3043
+ jokers.push(command.parameterName);
3044
+ dependentParameterNames.add(command.parameterName);
3045
+ break;
3046
+ case 'EXECUTE':
3047
+ if (isExecutionTypeChanged) {
3048
+ throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
3049
+ }
3050
+ executionType = command.executionType;
3051
+ isExecutionTypeChanged = true;
3052
+ break;
3053
+ case 'MODEL':
3054
+ templateModelRequirements[command.key] = command.value;
3055
+ break;
3056
+ case 'PARAMETER':
3057
+ // Note: This is just for detecting resulitng parameter name
3058
+ addParam(command);
3059
+ break;
3060
+ case 'POSTPROCESS':
3061
+ postprocessing.push(command.functionName);
3062
+ break;
3063
+ case 'EXPECT_AMOUNT':
3064
+ // eslint-disable-next-line no-case-declarations
3065
+ var unit = command.unit.toLowerCase();
3066
+ expectAmount[unit] = expectAmount[unit] || {};
3067
+ if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
3068
+ if (expectAmount[unit].min !== undefined) {
3069
+ throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
3070
+ }
3071
+ expectAmount[unit].min = command.amount;
3072
+ } /* not else */
3073
+ if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
3074
+ if (expectAmount[unit].max !== undefined) {
3075
+ throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
3076
+ }
3077
+ expectAmount[unit].max = command.amount;
3078
+ }
3079
+ break;
3080
+ case 'EXPECT_FORMAT':
3081
+ if (expectFormat !== undefined && command.format !== expectFormat) {
3082
+ throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
3083
+ }
3084
+ expectFormat = command.format;
3085
+ break;
3086
+ default:
3087
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
3088
+ }
3089
+ }
3090
+ }
3091
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
3092
+ finally {
3093
+ try {
3094
+ if (listItems_2_1 && !listItems_2_1.done && (_f = listItems_2.return)) _f.call(listItems_2);
3095
+ }
3096
+ finally { if (e_3) throw e_3.error; }
3097
+ }
3098
+ var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
3099
+ if (executionType === 'SCRIPT') {
3100
+ if (!language) {
3101
+ throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
3102
+ }
3103
+ else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
3104
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
3105
+ }
3106
+ }
3107
+ var lastLine = section.content.split('\n').pop();
3108
+ var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
3109
+ if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
3110
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
3111
+ // TODO: Show code of invalid sections each time + DRY
3112
+ section.content
3113
+ .split('\n')
3114
+ .map(function (line) { return "> ".concat(line); })
3115
+ .join('\n')), "\n "); }));
3116
+ }
3117
+ var resultingParameterName = match.groups.resultingParamName;
3118
+ // TODO: [1] DRY description
3119
+ var description_1 = section.content;
3120
+ // Note: Remove codeblocks
3121
+ description_1 = description_1.split(/^```.*^```/gms).join('');
3122
+ //Note: Remove lists and return statement
3123
+ description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
3124
+ description_1 = spaceTrim.spaceTrim(description_1);
3125
+ if (description_1 === '') {
3126
+ description_1 = undefined;
3127
+ }
3128
+ if (Object.keys(jokers).length === 0) {
3129
+ jokers = undefined;
3130
+ }
3131
+ if (Object.keys(expectAmount).length === 0) {
3132
+ expectAmount = undefined;
3133
+ }
3134
+ if (Object.keys(postprocessing).length === 0) {
3135
+ postprocessing = undefined;
3136
+ }
3137
+ dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, executionType: executionType, content: content })));
3138
+ if (templateModelRequirements.modelVariant === undefined) {
3139
+ templateModelRequirements.modelVariant = 'CHAT';
3140
+ }
3141
+ promptbookJson.promptTemplates.push({
3142
+ name: titleToName(section.title),
3143
+ title: section.title,
3144
+ description: description_1,
3145
+ dependentParameterNames: Array.from(dependentParameterNames),
3146
+ executionType: executionType,
3147
+ jokers: jokers,
3148
+ postprocessing: postprocessing,
3149
+ expectations: expectAmount,
3150
+ expectFormat: expectFormat,
3151
+ modelRequirements: templateModelRequirements,
3152
+ contentLanguage: executionType === 'SCRIPT' ? language : undefined,
3153
+ content: content,
3154
+ resultingParameterName: resultingParameterName,
3155
+ });
3156
+ };
3157
+ try {
3158
+ for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
3159
+ section = _b.value;
3160
+ _loop_1(section);
2033
3161
  }
2034
3162
  }
2035
- }
2036
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
2037
- finally {
2038
- try {
2039
- if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
3163
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
3164
+ finally {
3165
+ try {
3166
+ if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
3167
+ }
3168
+ finally { if (e_2) throw e_2.error; }
2040
3169
  }
2041
- finally { if (e_6) throw e_6.error; }
2042
- }
2043
- } /* not else */
2044
- if (expectFormat) {
2045
- if (expectFormat === 'JSON') {
2046
- // TODO: @deprecated remove
2047
- commands_1.push("EXPECT JSON");
2048
- }
2049
- } /* not else */
2050
- promptbookString += '\n\n';
2051
- promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
2052
- promptbookString += '\n\n';
2053
- promptbookString += '```' + contentLanguage;
2054
- promptbookString += '\n';
2055
- promptbookString += spaceTrim__default["default"](content);
2056
- // <- TODO: !!! Escape
2057
- // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
2058
- promptbookString += '\n';
2059
- promptbookString += '```';
2060
- promptbookString += '\n\n';
2061
- promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
2062
- }
2063
- }
2064
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2065
- finally {
2066
- try {
2067
- if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
2068
- }
2069
- finally { if (e_3) throw e_3.error; }
2070
- }
2071
- return promptbookString;
2072
- }
2073
- /**
2074
- * @private internal util of promptbookJsonToString
2075
- */
2076
- function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
2077
- var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
2078
- var parameterString = "{".concat(name, "}");
2079
- if (description) {
2080
- parameterString = "".concat(parameterString, " ").concat(description);
2081
- }
2082
- return parameterString;
3170
+ // =============================================================
3171
+ return [2 /*return*/, promptbookJson];
3172
+ }
3173
+ });
3174
+ });
2083
3175
  }
2084
3176
  /**
2085
- * TODO: Escape all
2086
- */
2087
-
2088
- /**
2089
- * This error indicates that promptbook not found in the library
3177
+ * TODO: Report here line/column of error
3178
+ * TODO: Use spaceTrim more effectively
3179
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
2090
3180
  */
2091
- var PromptbookNotFoundError = /** @class */ (function (_super) {
2092
- __extends(PromptbookNotFoundError, _super);
2093
- function PromptbookNotFoundError(message) {
2094
- var _this = _super.call(this, message) || this;
2095
- _this.name = 'PromptbookNotFoundError';
2096
- Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
2097
- return _this;
2098
- }
2099
- return PromptbookNotFoundError;
2100
- }(Error));
2101
3181
 
2102
3182
  /**
2103
- * This error indicates errors in referencing promptbooks between each other
3183
+ * This error indicates that the promptbook library cannot be propperly loaded
2104
3184
  */
2105
- var PromptbookReferenceError = /** @class */ (function (_super) {
2106
- __extends(PromptbookReferenceError, _super);
2107
- function PromptbookReferenceError(message) {
3185
+ var PromptbookLibraryError = /** @class */ (function (_super) {
3186
+ __extends(PromptbookLibraryError, _super);
3187
+ function PromptbookLibraryError(message) {
2108
3188
  var _this = _super.call(this, message) || this;
2109
- _this.name = 'PromptbookReferenceError';
2110
- Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
3189
+ _this.name = 'PromptbookLibraryError';
3190
+ Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
2111
3191
  return _this;
2112
3192
  }
2113
- return PromptbookReferenceError;
3193
+ return PromptbookLibraryError;
2114
3194
  }(Error));
2115
3195
 
2116
3196
  /**
2117
- * Library of promptbooks that groups together promptbooks for an application.
2118
- * This implementation is a very thin wrapper around the Array / Map of promptbooks.
2119
- *
2120
- * @see https://github.com/webgptorg/promptbook#promptbook-library
3197
+ * Detects if the code is running in a browser environment in main thread (Not in a web worker)
2121
3198
  */
2122
- var SimplePromptbookLibrary = /** @class */ (function () {
2123
- /**
2124
- * Constructs a promptbook library from promptbooks
2125
- *
2126
- * @param promptbooks !!!
2127
- *
2128
- * Note: During the construction logic of all promptbooks are validated
2129
- * Note: It is not recommended to use this constructor directly, use `createPromptbookLibraryFromSources` *(or other variant)* instead
2130
- */
2131
- function SimplePromptbookLibrary() {
2132
- var e_1, _a;
2133
- var promptbooks = [];
2134
- for (var _i = 0; _i < arguments.length; _i++) {
2135
- promptbooks[_i] = arguments[_i];
2136
- }
2137
- this.library = new Map();
2138
- try {
2139
- for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
2140
- var promptbook = promptbooks_1_1.value;
2141
- if (promptbook.promptbookUrl === undefined) {
2142
- throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
2143
- }
2144
- validatePromptbookJson(promptbook);
2145
- // Note: [🦄]
2146
- if (this.library.has(promptbook.promptbookUrl) &&
2147
- promptbookJsonToString(promptbook) !==
2148
- promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
2149
- throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
2150
- }
2151
- this.library.set(promptbook.promptbookUrl, promptbook);
2152
- }
2153
- }
2154
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2155
- finally {
2156
- try {
2157
- if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
2158
- }
2159
- finally { if (e_1) throw e_1.error; }
2160
- }
2161
- }
2162
- /**
2163
- * Gets all promptbooks in the library
2164
- */
2165
- SimplePromptbookLibrary.prototype.listPromptbooks = function () {
2166
- return Array.from(this.library.keys());
2167
- };
2168
- /**
2169
- * Gets promptbook by its URL
2170
- *
2171
- * Note: This is not a direct fetching from the URL, but a lookup in the library
2172
- */
2173
- SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
2174
- var _this = this;
2175
- var promptbook = this.library.get(url);
2176
- if (!promptbook) {
2177
- if (this.listPromptbooks().length === 0) {
2178
- throw new PromptbookNotFoundError(spaceTrim.spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
2179
- }
2180
- throw new PromptbookNotFoundError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2181
- .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2182
- .join('\n')), "\n\n "); }));
2183
- }
2184
- return promptbook;
2185
- };
2186
- /**
2187
- * Checks whether given prompt was defined in any promptbook in the library
2188
- */
2189
- SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
2190
- return true;
2191
- };
2192
- return SimplePromptbookLibrary;
2193
- }());
2194
-
3199
+ new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
2195
3200
  /**
2196
- * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
2197
- *
2198
- * Note: You can combine `PromptbookString` (`.ptbk.md`) with `PromptbookJson` BUT it is not recommended
2199
- * Note: During the construction syntax and logic of all sources are validated
2200
- *
2201
- * @param promptbookSources
2202
- * @returns PromptbookLibrary
3201
+ * Detects if the code is running in a Node.js environment
2203
3202
  */
2204
- function createPromptbookLibraryFromSources() {
2205
- var promptbookSources = [];
2206
- for (var _i = 0; _i < arguments.length; _i++) {
2207
- promptbookSources[_i] = arguments[_i];
2208
- }
2209
- return __awaiter(this, void 0, void 0, function () {
2210
- var promptbooks, promptbookSources_1, promptbookSources_1_1, source, promptbook, e_1_1;
2211
- var e_1, _a;
2212
- return __generator(this, function (_b) {
2213
- switch (_b.label) {
2214
- case 0:
2215
- promptbooks = new Array();
2216
- _b.label = 1;
2217
- case 1:
2218
- _b.trys.push([1, 8, 9, 10]);
2219
- promptbookSources_1 = __values(promptbookSources), promptbookSources_1_1 = promptbookSources_1.next();
2220
- _b.label = 2;
2221
- case 2:
2222
- if (!!promptbookSources_1_1.done) return [3 /*break*/, 7];
2223
- source = promptbookSources_1_1.value;
2224
- promptbook = void 0;
2225
- if (!(typeof source === 'string')) return [3 /*break*/, 4];
2226
- return [4 /*yield*/, promptbookStringToJson(source)];
2227
- case 3:
2228
- // Note: When directly creating from string, no need to validate the source
2229
- // The validation is performed always before execution
2230
- promptbook = _b.sent();
2231
- return [3 /*break*/, 5];
2232
- case 4:
2233
- promptbook = source;
2234
- _b.label = 5;
2235
- case 5:
2236
- promptbooks.push(promptbook);
2237
- _b.label = 6;
2238
- case 6:
2239
- promptbookSources_1_1 = promptbookSources_1.next();
2240
- return [3 /*break*/, 2];
2241
- case 7: return [3 /*break*/, 10];
2242
- case 8:
2243
- e_1_1 = _b.sent();
2244
- e_1 = { error: e_1_1 };
2245
- return [3 /*break*/, 10];
2246
- case 9:
2247
- try {
2248
- if (promptbookSources_1_1 && !promptbookSources_1_1.done && (_a = promptbookSources_1.return)) _a.call(promptbookSources_1);
2249
- }
2250
- finally { if (e_1) throw e_1.error; }
2251
- return [7 /*endfinally*/];
2252
- case 10: return [2 /*return*/, new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))()];
2253
- }
2254
- });
2255
- });
2256
- }
3203
+ var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
2257
3204
  /**
2258
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
3205
+ * Detects if the code is running in a web worker
2259
3206
  */
3207
+ new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
2260
3208
 
2261
3209
  /**
2262
3210
  * Constructs Promptbook from async sources