@promptbook/cli 0.59.0-3 → 0.59.0-30

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 (585) hide show
  1. package/README.md +55 -0
  2. package/bin/promptbook-cli.js +2 -4
  3. package/esm/index.es.js +3153 -1115
  4. package/esm/index.es.js.map +1 -1
  5. package/esm/typings/promptbook-library/index.d.ts +25 -0
  6. package/esm/typings/src/_packages/cli.index.d.ts +10 -0
  7. package/{umd/typings → esm/typings/src}/_packages/core.index.d.ts +10 -9
  8. package/esm/typings/src/_packages/node.index.d.ts +4 -0
  9. package/{umd/typings → esm/typings/src}/_packages/types.index.d.ts +1 -1
  10. package/esm/typings/src/cli/actions/hello.d.ts +7 -0
  11. package/esm/typings/src/cli/actions/make.d.ts +7 -0
  12. package/esm/typings/src/cli/actions/prettify.d.ts +7 -0
  13. package/esm/typings/{conversion/prettify/prettifyPromptbookStringCli.d.ts → src/cli/promptbookCli.d.ts} +2 -2
  14. package/esm/typings/{config.d.ts → src/config.d.ts} +4 -0
  15. package/{umd/typings/conversion/validation/validatePromptbookJson.d.ts → esm/typings/src/conversion/validation/validatePromptbook.d.ts} +2 -2
  16. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +21 -0
  17. package/{umd/typings → esm/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  18. package/esm/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +3 -1
  19. package/esm/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.d.ts → src/library/constructors/createLibraryFromDirectory.d.ts} +2 -2
  20. package/esm/typings/src/library/constructors/createLibraryFromJson.d.ts +12 -0
  21. package/esm/typings/{promptbook-library/constructors/createPromptbookLibraryFromPromise.d.ts → src/library/constructors/createLibraryFromPromise.d.ts} +3 -7
  22. package/{umd/typings/promptbook-library/constructors/createPromptbookLibraryFromUrl.d.ts → esm/typings/src/library/constructors/createLibraryFromUrl.d.ts} +2 -2
  23. package/esm/typings/{promptbook-library/constructors/createPromptbookSublibrary.d.ts → src/library/constructors/createSublibrary.d.ts} +1 -1
  24. package/esm/typings/src/library/libraryToJson.d.ts +8 -0
  25. package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +1 -0
  26. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  27. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  28. package/{umd/typings → esm/typings/src}/llm-providers/openai/OpenAiExecutionTools.d.ts +8 -0
  29. package/{umd/typings → esm/typings/src}/llm-providers/openai/openai-models.d.ts +1 -0
  30. package/{umd/typings → esm/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  31. package/esm/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +1 -1
  32. package/{umd/typings → esm/typings/src}/types/ModelRequirements.d.ts +1 -1
  33. package/esm/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +2 -2
  34. package/package.json +3 -3
  35. package/umd/index.umd.js +3155 -1117
  36. package/umd/index.umd.js.map +1 -1
  37. package/umd/typings/promptbook-library/index.d.ts +25 -0
  38. package/umd/typings/src/_packages/cli.index.d.ts +10 -0
  39. package/{esm/typings → umd/typings/src}/_packages/core.index.d.ts +10 -9
  40. package/umd/typings/src/_packages/node.index.d.ts +4 -0
  41. package/{esm/typings → umd/typings/src}/_packages/types.index.d.ts +1 -1
  42. package/umd/typings/src/cli/actions/hello.d.ts +7 -0
  43. package/umd/typings/src/cli/actions/make.d.ts +7 -0
  44. package/umd/typings/src/cli/actions/prettify.d.ts +7 -0
  45. package/umd/typings/{conversion/prettify/prettifyPromptbookStringCli.d.ts → src/cli/promptbookCli.d.ts} +2 -2
  46. package/umd/typings/{config.d.ts → src/config.d.ts} +4 -0
  47. package/{esm/typings/conversion/validation/validatePromptbookJson.d.ts → umd/typings/src/conversion/validation/validatePromptbook.d.ts} +2 -2
  48. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +21 -0
  49. package/{esm/typings → umd/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  50. package/umd/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +3 -1
  51. package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.d.ts → src/library/constructors/createLibraryFromDirectory.d.ts} +2 -2
  52. package/umd/typings/src/library/constructors/createLibraryFromJson.d.ts +12 -0
  53. package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromPromise.d.ts → src/library/constructors/createLibraryFromPromise.d.ts} +3 -7
  54. package/{esm/typings/promptbook-library/constructors/createPromptbookLibraryFromUrl.d.ts → umd/typings/src/library/constructors/createLibraryFromUrl.d.ts} +2 -2
  55. package/umd/typings/{promptbook-library/constructors/createPromptbookSublibrary.d.ts → src/library/constructors/createSublibrary.d.ts} +1 -1
  56. package/umd/typings/src/library/libraryToJson.d.ts +8 -0
  57. package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +1 -0
  58. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  59. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  60. package/{esm/typings → umd/typings/src}/llm-providers/openai/OpenAiExecutionTools.d.ts +8 -0
  61. package/{esm/typings → umd/typings/src}/llm-providers/openai/openai-models.d.ts +1 -0
  62. package/{esm/typings → umd/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  63. package/umd/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +1 -1
  64. package/{esm/typings → umd/typings/src}/types/ModelRequirements.d.ts +1 -1
  65. package/umd/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +2 -2
  66. package/umd/typings/src/utils/unwrapResult.test.d.ts +1 -0
  67. package/umd/typings/src/utils/validators/url/isValidUrl.test.d.ts +1 -0
  68. package/esm/typings/_packages/cli.index.d.ts +0 -10
  69. package/esm/typings/_packages/node.index.d.ts +0 -4
  70. package/esm/typings/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -7
  71. package/esm/typings/promptbook-library/constructors/createPromptbookLibraryFromSources.d.ts +0 -16
  72. package/umd/typings/_packages/cli.index.d.ts +0 -10
  73. package/umd/typings/_packages/node.index.d.ts +0 -4
  74. package/umd/typings/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -7
  75. package/umd/typings/promptbook-library/constructors/createPromptbookLibraryFromSources.d.ts +0 -16
  76. /package/esm/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  77. /package/esm/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  78. /package/esm/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  79. /package/esm/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  80. /package/esm/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  81. /package/esm/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  82. /package/esm/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  83. /package/esm/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  84. /package/esm/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  85. /package/esm/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  86. /package/esm/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  87. /package/esm/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  88. /package/esm/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  89. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  90. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  91. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  92. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  93. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  94. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  95. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  96. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  97. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  98. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  99. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  100. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  101. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  102. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  103. /package/esm/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  104. /package/esm/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  105. /package/esm/typings/{conversion/validation/validatePromptbookJson-logicErrors.test.d.ts → src/conversion/validation/validatePromptbook-logicErrors.test.d.ts} +0 -0
  106. /package/esm/typings/{conversion/validation/validatePromptbookJson.test.d.ts → src/conversion/validation/validatePromptbook.test.d.ts} +0 -0
  107. /package/esm/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  108. /package/esm/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  109. /package/esm/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  110. /package/esm/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  111. /package/esm/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  112. /package/esm/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  113. /package/esm/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  114. /package/esm/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  115. /package/esm/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  116. /package/esm/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  117. /package/esm/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  118. /package/esm/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  119. /package/esm/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  120. /package/esm/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  121. /package/esm/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  122. /package/esm/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  123. /package/esm/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  124. /package/esm/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  125. /package/esm/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  126. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  127. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  128. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  129. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  130. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  131. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  132. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  133. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  134. /package/esm/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  135. /package/esm/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  136. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  137. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  138. /package/esm/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  139. /package/esm/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  140. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  141. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  142. /package/esm/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  143. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  144. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  145. /package/esm/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  146. /package/esm/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  147. /package/esm/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  148. /package/esm/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  149. /package/esm/typings/{formats → src/formats}/index.d.ts +0 -0
  150. /package/esm/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  151. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  152. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  153. /package/esm/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  154. /package/esm/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  155. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  156. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  157. /package/esm/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  158. /package/esm/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  159. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  160. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  161. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  162. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  163. /package/esm/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  164. /package/esm/typings/{llm-providers/mocked/fakeTextToExpectations.test.d.ts → src/library/constructors/createLibraryFromDirectory.test.d.ts} +0 -0
  165. /package/esm/typings/{llm-providers/mocked/faked-completion.test.d.ts → src/library/constructors/createLibraryFromJson.test.d.ts} +0 -0
  166. /package/esm/typings/{llm-providers/openai/computeUsage.test.d.ts → src/library/constructors/createLibraryFromPromise.test.d.ts} +0 -0
  167. /package/esm/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  168. /package/esm/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.test.d.ts → src/library/libraryToJson.test.d.ts} +0 -0
  169. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  170. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  171. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  172. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  173. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  174. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  175. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  176. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  177. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  178. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  179. /package/{umd/typings → esm/typings/src}/llm-providers/mocked/fakeTextToExpectations.test.d.ts +0 -0
  180. /package/{umd/typings → esm/typings/src}/llm-providers/mocked/faked-completion.test.d.ts +0 -0
  181. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  182. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  183. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  184. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  185. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  186. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  187. /package/esm/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  188. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  189. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  190. /package/{umd/typings → esm/typings/src}/llm-providers/openai/computeUsage.test.d.ts +0 -0
  191. /package/esm/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  192. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  193. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  194. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  195. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  196. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  197. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  198. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-async.test.ts.test.d.ts +0 -0
  199. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-missing.test.d.ts +0 -0
  200. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-with-dependencies.test.d.ts +0 -0
  201. /package/esm/typings/{scripting → src/scripting}/_test/custom-function.test.d.ts +0 -0
  202. /package/esm/typings/{scripting → src/scripting}/_test/postprocessing.test.d.ts +0 -0
  203. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-errors.test.d.ts +0 -0
  204. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-tools.test.d.ts +0 -0
  205. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  206. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  207. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  208. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  209. /package/esm/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  210. /package/esm/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  211. /package/esm/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  212. /package/esm/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  213. /package/esm/typings/{types → src/types}/Command.d.ts +0 -0
  214. /package/esm/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  215. /package/esm/typings/{types → src/types}/Parameters.d.ts +0 -0
  216. /package/esm/typings/{types → src/types}/Prompt.d.ts +0 -0
  217. /package/esm/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  218. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  219. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  220. /package/esm/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  221. /package/esm/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  222. /package/esm/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  223. /package/esm/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  224. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  225. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  226. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  227. /package/esm/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  228. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  229. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.test.d.ts +0 -0
  230. /package/esm/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  231. /package/esm/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  232. /package/esm/typings/{types → src/types}/typeAliases.d.ts +0 -0
  233. /package/esm/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  234. /package/esm/typings/{utils → src/utils}/emojis.d.ts +0 -0
  235. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  236. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.test.d.ts +0 -0
  237. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  238. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.test.d.ts +0 -0
  239. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  240. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.test.d.ts +0 -0
  241. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  242. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.test.d.ts +0 -0
  243. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  244. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.test.d.ts +0 -0
  245. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  246. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.test.d.ts +0 -0
  247. /package/esm/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  248. /package/esm/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  249. /package/esm/typings/{utils → src/utils}/extractParameters.test.d.ts +0 -0
  250. /package/esm/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  251. /package/esm/typings/{utils → src/utils}/formatNumber.test.d.ts +0 -0
  252. /package/esm/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  253. /package/esm/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  254. /package/esm/typings/{utils → src/utils}/just.d.ts +0 -0
  255. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  256. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.test.d.ts +0 -0
  257. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  258. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.test.d.ts +0 -0
  259. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  260. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.test.d.ts +0 -0
  261. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  262. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.test.d.ts +0 -0
  263. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  264. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.test.d.ts +0 -0
  265. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  266. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.test.d.ts +0 -0
  267. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  268. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.test.d.ts +0 -0
  269. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  270. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.test.d.ts +0 -0
  271. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  272. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.test.d.ts +0 -0
  273. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  274. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.test.d.ts +0 -0
  275. /package/esm/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  276. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  277. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.test.d.ts +0 -0
  278. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  279. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.test.d.ts +0 -0
  280. /package/esm/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  281. /package/esm/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  282. /package/esm/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  283. /package/esm/typings/{utils → src/utils}/normalization/capitalize.test.d.ts +0 -0
  284. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  285. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.test.d.ts +0 -0
  286. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  287. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.test.d.ts +0 -0
  288. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  289. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.test.d.ts +0 -0
  290. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  291. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.test.d.ts +0 -0
  292. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  293. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.test.d.ts +0 -0
  294. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  295. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.test.d.ts +0 -0
  296. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  297. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.test.d.ts +0 -0
  298. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  299. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.test.d.ts +0 -0
  300. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  301. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.test.d.ts +0 -0
  302. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  303. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.test.d.ts +0 -0
  304. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  305. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.test.d.ts +0 -0
  306. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  307. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.test.d.ts +0 -0
  308. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  309. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.test.d.ts +0 -0
  310. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  311. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.test.d.ts +0 -0
  312. /package/esm/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  313. /package/esm/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  314. /package/esm/typings/{utils → src/utils}/removeEmojis.test.d.ts +0 -0
  315. /package/esm/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  316. /package/esm/typings/{utils → src/utils}/removeQuotes.test.d.ts +0 -0
  317. /package/esm/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  318. /package/esm/typings/{utils → src/utils}/sets/difference.test.d.ts +0 -0
  319. /package/esm/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  320. /package/esm/typings/{utils → src/utils}/sets/intersection.test.d.ts +0 -0
  321. /package/esm/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  322. /package/esm/typings/{utils → src/utils}/sets/union.test.d.ts +0 -0
  323. /package/esm/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  324. /package/esm/typings/{utils → src/utils}/trimCodeBlock.test.d.ts +0 -0
  325. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  326. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.test.d.ts +0 -0
  327. /package/esm/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  328. /package/esm/typings/{utils → src/utils}/unwrapResult.test.d.ts +0 -0
  329. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  330. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.test.d.ts +0 -0
  331. /package/esm/typings/{version.d.ts → src/version.d.ts} +0 -0
  332. /package/umd/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  333. /package/umd/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  334. /package/umd/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  335. /package/umd/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  336. /package/umd/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  337. /package/umd/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  338. /package/umd/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  339. /package/umd/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  340. /package/umd/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  341. /package/umd/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  342. /package/umd/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  343. /package/umd/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  344. /package/umd/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  345. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  346. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  347. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  348. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  349. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  350. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  351. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  352. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  353. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  354. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  355. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  356. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  357. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  358. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  359. /package/umd/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  360. /package/umd/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  361. /package/{esm/typings/promptbook-library/constructors/createPromptbookLibraryFromPromise.test.d.ts → umd/typings/src/conversion/validation/validatePromptbook-logicErrors.test.d.ts} +0 -0
  362. /package/{esm/typings/promptbook-library/constructors/createPromptbookLibraryFromSources.test.d.ts → umd/typings/src/conversion/validation/validatePromptbook.test.d.ts} +0 -0
  363. /package/umd/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  364. /package/umd/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  365. /package/umd/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  366. /package/umd/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  367. /package/umd/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  368. /package/umd/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  369. /package/umd/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  370. /package/umd/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  371. /package/umd/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  372. /package/umd/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  373. /package/umd/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  374. /package/umd/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  375. /package/umd/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  376. /package/umd/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  377. /package/umd/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  378. /package/umd/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  379. /package/umd/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  380. /package/umd/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  381. /package/umd/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  382. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  383. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  384. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  385. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  386. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  387. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  388. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  389. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  390. /package/umd/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  391. /package/umd/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  392. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  393. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  394. /package/umd/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  395. /package/umd/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  396. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  397. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  398. /package/umd/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  399. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  400. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  401. /package/umd/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  402. /package/umd/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  403. /package/umd/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  404. /package/umd/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  405. /package/umd/typings/{formats → src/formats}/index.d.ts +0 -0
  406. /package/umd/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  407. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  408. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  409. /package/umd/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  410. /package/umd/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  411. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  412. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  413. /package/umd/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  414. /package/umd/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  415. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  416. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  417. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  418. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  419. /package/umd/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  420. /package/umd/typings/{conversion/validation/validatePromptbookJson-logicErrors.test.d.ts → src/library/constructors/createLibraryFromDirectory.test.d.ts} +0 -0
  421. /package/umd/typings/{conversion/validation/validatePromptbookJson.test.d.ts → src/library/constructors/createLibraryFromJson.test.d.ts} +0 -0
  422. /package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.test.d.ts → src/library/constructors/createLibraryFromPromise.test.d.ts} +0 -0
  423. /package/umd/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  424. /package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromPromise.test.d.ts → src/library/libraryToJson.test.d.ts} +0 -0
  425. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  426. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  427. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  428. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  429. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  430. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  431. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  432. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  433. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  434. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  435. /package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromSources.test.d.ts → src/llm-providers/mocked/fakeTextToExpectations.test.d.ts} +0 -0
  436. /package/umd/typings/{scripting/_test/custom-function-async.test.ts.test.d.ts → src/llm-providers/mocked/faked-completion.test.d.ts} +0 -0
  437. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  438. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  439. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  440. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  441. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  442. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  443. /package/umd/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  444. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  445. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  446. /package/umd/typings/{scripting/_test/custom-function-missing.test.d.ts → src/llm-providers/openai/computeUsage.test.d.ts} +0 -0
  447. /package/umd/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  448. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  449. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  450. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  451. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  452. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  453. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  454. /package/umd/typings/{scripting/_test/custom-function-with-dependencies.test.d.ts → src/scripting/_test/custom-function-async.test.ts.test.d.ts} +0 -0
  455. /package/umd/typings/{scripting/_test/custom-function.test.d.ts → src/scripting/_test/custom-function-missing.test.d.ts} +0 -0
  456. /package/umd/typings/{scripting/_test/postprocessing.test.d.ts → src/scripting/_test/custom-function-with-dependencies.test.d.ts} +0 -0
  457. /package/umd/typings/{scripting/_test/script-execution-errors.test.d.ts → src/scripting/_test/custom-function.test.d.ts} +0 -0
  458. /package/umd/typings/{scripting/_test/script-execution-tools.test.d.ts → src/scripting/_test/postprocessing.test.d.ts} +0 -0
  459. /package/umd/typings/{types/execution-report/countWorkingDuration.test.d.ts → src/scripting/_test/script-execution-errors.test.d.ts} +0 -0
  460. /package/umd/typings/{utils/expectation-counters/countCharacters.test.d.ts → src/scripting/_test/script-execution-tools.test.d.ts} +0 -0
  461. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  462. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  463. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  464. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  465. /package/umd/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  466. /package/umd/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  467. /package/umd/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  468. /package/umd/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  469. /package/umd/typings/{types → src/types}/Command.d.ts +0 -0
  470. /package/umd/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  471. /package/umd/typings/{types → src/types}/Parameters.d.ts +0 -0
  472. /package/umd/typings/{types → src/types}/Prompt.d.ts +0 -0
  473. /package/umd/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  474. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  475. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  476. /package/umd/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  477. /package/umd/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  478. /package/umd/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  479. /package/umd/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  480. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  481. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  482. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  483. /package/umd/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  484. /package/umd/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  485. /package/umd/typings/{utils/expectation-counters/countLines.test.d.ts → src/types/execution-report/countWorkingDuration.test.d.ts} +0 -0
  486. /package/umd/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  487. /package/umd/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  488. /package/umd/typings/{types → src/types}/typeAliases.d.ts +0 -0
  489. /package/umd/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  490. /package/umd/typings/{utils → src/utils}/emojis.d.ts +0 -0
  491. /package/umd/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  492. /package/umd/typings/{utils/expectation-counters/countPages.test.d.ts → src/utils/expectation-counters/countCharacters.test.d.ts} +0 -0
  493. /package/umd/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  494. /package/umd/typings/{utils/expectation-counters/countParagraphs.test.d.ts → src/utils/expectation-counters/countLines.test.d.ts} +0 -0
  495. /package/umd/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  496. /package/umd/typings/{utils/expectation-counters/countSentences.test.d.ts → src/utils/expectation-counters/countPages.test.d.ts} +0 -0
  497. /package/umd/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  498. /package/umd/typings/{utils/expectation-counters/countWords.test.d.ts → src/utils/expectation-counters/countParagraphs.test.d.ts} +0 -0
  499. /package/umd/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  500. /package/umd/typings/{utils/extractParameters.test.d.ts → src/utils/expectation-counters/countSentences.test.d.ts} +0 -0
  501. /package/umd/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  502. /package/umd/typings/{utils/formatNumber.test.d.ts → src/utils/expectation-counters/countWords.test.d.ts} +0 -0
  503. /package/umd/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  504. /package/umd/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  505. /package/umd/typings/{utils/markdown-json/countMarkdownStructureDeepness.test.d.ts → src/utils/extractParameters.test.d.ts} +0 -0
  506. /package/umd/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  507. /package/umd/typings/{utils/markdown-json/markdownToMarkdownStructure.test.d.ts → src/utils/formatNumber.test.d.ts} +0 -0
  508. /package/umd/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  509. /package/umd/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  510. /package/umd/typings/{utils → src/utils}/just.d.ts +0 -0
  511. /package/umd/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  512. /package/umd/typings/{utils/markdown/createMarkdownTable.test.d.ts → src/utils/markdown/addAutoGeneratedSection.test.d.ts} +0 -0
  513. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  514. /package/umd/typings/{utils/markdown/escapeMarkdownBlock.test.d.ts → src/utils/markdown/createMarkdownChart.test.d.ts} +0 -0
  515. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  516. /package/umd/typings/{utils/markdown/extractAllBlocksFromMarkdown.test.d.ts → src/utils/markdown/createMarkdownTable.test.d.ts} +0 -0
  517. /package/umd/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  518. /package/umd/typings/{utils/markdown/extractAllListItemsFromMarkdown.test.d.ts → src/utils/markdown/escapeMarkdownBlock.test.d.ts} +0 -0
  519. /package/umd/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  520. /package/umd/typings/{utils/markdown/extractOneBlockFromMarkdown.test.d.ts → src/utils/markdown/extractAllBlocksFromMarkdown.test.d.ts} +0 -0
  521. /package/umd/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  522. /package/umd/typings/{utils/markdown/prettifyMarkdown.test.d.ts → src/utils/markdown/extractAllListItemsFromMarkdown.test.d.ts} +0 -0
  523. /package/umd/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  524. /package/umd/typings/{utils/markdown/removeContentComments.test.d.ts → src/utils/markdown/extractOneBlockFromMarkdown.test.d.ts} +0 -0
  525. /package/umd/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  526. /package/umd/typings/{utils/markdown/removeMarkdownFormatting.test.d.ts → src/utils/markdown/prettifyMarkdown.test.d.ts} +0 -0
  527. /package/umd/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  528. /package/umd/typings/{utils/normalization/capitalize.test.d.ts → src/utils/markdown/removeContentComments.test.d.ts} +0 -0
  529. /package/umd/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  530. /package/umd/typings/{utils/normalization/decapitalize.test.d.ts → src/utils/markdown/removeMarkdownFormatting.test.d.ts} +0 -0
  531. /package/umd/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  532. /package/umd/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  533. /package/umd/typings/{utils/markdown/addAutoGeneratedSection.test.d.ts → src/utils/markdown-json/countMarkdownStructureDeepness.test.d.ts} +0 -0
  534. /package/umd/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  535. /package/umd/typings/{utils/markdown/createMarkdownChart.test.d.ts → src/utils/markdown-json/markdownToMarkdownStructure.test.d.ts} +0 -0
  536. /package/umd/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  537. /package/umd/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  538. /package/umd/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  539. /package/umd/typings/{utils/normalization/isValidKeyword.test.d.ts → src/utils/normalization/capitalize.test.d.ts} +0 -0
  540. /package/umd/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  541. /package/umd/typings/{utils/normalization/nameToUriPart.test.d.ts → src/utils/normalization/decapitalize.test.d.ts} +0 -0
  542. /package/umd/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  543. /package/umd/typings/{utils/normalization/nameToUriParts.test.d.ts → src/utils/normalization/isValidKeyword.test.d.ts} +0 -0
  544. /package/umd/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  545. /package/umd/typings/{utils/normalization/normalize-to-kebab-case.test.d.ts → src/utils/normalization/nameToUriPart.test.d.ts} +0 -0
  546. /package/umd/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  547. /package/umd/typings/{utils/normalization/normalizeTo_PascalCase.test.d.ts → src/utils/normalization/nameToUriParts.test.d.ts} +0 -0
  548. /package/umd/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  549. /package/umd/typings/{utils/normalization/normalizeTo_SCREAMING_CASE.test.d.ts → src/utils/normalization/normalize-to-kebab-case.test.d.ts} +0 -0
  550. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  551. /package/umd/typings/{utils/normalization/normalizeTo_camelCase.test.d.ts → src/utils/normalization/normalizeTo_PascalCase.test.d.ts} +0 -0
  552. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  553. /package/umd/typings/{utils/normalization/normalizeTo_snake_case.test.d.ts → src/utils/normalization/normalizeTo_SCREAMING_CASE.test.d.ts} +0 -0
  554. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  555. /package/umd/typings/{utils/normalization/normalizeWhitespaces.test.d.ts → src/utils/normalization/normalizeTo_camelCase.test.d.ts} +0 -0
  556. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  557. /package/umd/typings/{utils/normalization/parseKeywords.test.d.ts → src/utils/normalization/normalizeTo_snake_case.test.d.ts} +0 -0
  558. /package/umd/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  559. /package/umd/typings/{utils/normalization/parseKeywordsFromString.test.d.ts → src/utils/normalization/normalizeWhitespaces.test.d.ts} +0 -0
  560. /package/umd/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  561. /package/umd/typings/{utils/normalization/removeDiacritics.test.d.ts → src/utils/normalization/parseKeywords.test.d.ts} +0 -0
  562. /package/umd/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  563. /package/umd/typings/{utils/normalization/searchKeywords.test.d.ts → src/utils/normalization/parseKeywordsFromString.test.d.ts} +0 -0
  564. /package/umd/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  565. /package/umd/typings/{utils/removeEmojis.test.d.ts → src/utils/normalization/removeDiacritics.test.d.ts} +0 -0
  566. /package/umd/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  567. /package/umd/typings/{utils/removeQuotes.test.d.ts → src/utils/normalization/searchKeywords.test.d.ts} +0 -0
  568. /package/umd/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  569. /package/umd/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  570. /package/umd/typings/{utils/sets/difference.test.d.ts → src/utils/removeEmojis.test.d.ts} +0 -0
  571. /package/umd/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  572. /package/umd/typings/{utils/sets/intersection.test.d.ts → src/utils/removeQuotes.test.d.ts} +0 -0
  573. /package/umd/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  574. /package/umd/typings/{utils/sets/union.test.d.ts → src/utils/sets/difference.test.d.ts} +0 -0
  575. /package/umd/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  576. /package/umd/typings/{utils/trimCodeBlock.test.d.ts → src/utils/sets/intersection.test.d.ts} +0 -0
  577. /package/umd/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  578. /package/umd/typings/{utils/trimEndOfCodeBlock.test.d.ts → src/utils/sets/union.test.d.ts} +0 -0
  579. /package/umd/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  580. /package/umd/typings/{utils/unwrapResult.test.d.ts → src/utils/trimCodeBlock.test.d.ts} +0 -0
  581. /package/umd/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  582. /package/umd/typings/{utils/validators/url/isValidUrl.test.d.ts → src/utils/trimEndOfCodeBlock.test.d.ts} +0 -0
  583. /package/umd/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  584. /package/umd/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  585. /package/umd/typings/{version.d.ts → src/version.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -1,11 +1,12 @@
1
- import colors from 'colors';
2
1
  import commander from 'commander';
3
- import { writeFile, readFile } from 'fs/promises';
4
- import glob from 'glob-promise';
5
- import { spaceTrim } from 'spacetrim';
2
+ import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
3
+ import colors from 'colors';
6
4
  import { forTime } from 'waitasecond';
5
+ import { access, constants, readFile, readdir, writeFile } from 'fs/promises';
6
+ import { join } from 'path';
7
7
  import { format } from 'prettier';
8
8
  import parserHtml from 'prettier/parser-html';
9
+ import glob from 'glob-promise';
9
10
 
10
11
  /*! *****************************************************************************
11
12
  Copyright (c) Microsoft Corporation.
@@ -142,70 +143,60 @@ new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined'
142
143
  /**
143
144
  * The version of the Promptbook library
144
145
  */
145
- var PROMPTBOOK_VERSION = '0.59.0-2';
146
+ var PROMPTBOOK_VERSION = '0.59.0-29';
146
147
 
147
148
  /**
148
- * Removes HTML or Markdown comments from a string.
149
+ * Initializes testing `hello` command for Promptbook CLI utilities
149
150
  *
150
- * @param {string} content - The string to remove comments from.
151
- * @returns {string} The input string with all comments removed.
151
+ * @private part of `promptbookCli`
152
152
  */
153
- function removeContentComments(content) {
154
- return spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
153
+ function initializeHello(program) {
154
+ var _this = this;
155
+ var helloCommand = program.command('hello');
156
+ helloCommand.description(spaceTrim("\n Just command for testing\n "));
157
+ helloCommand.argument('<name>', 'Your name');
158
+ helloCommand.option('-g, --greeting <greeting>', "Greeting", 'Hello');
159
+ helloCommand.action(function (name, _a) {
160
+ var greeting = _a.greeting;
161
+ return __awaiter(_this, void 0, void 0, function () {
162
+ return __generator(this, function (_b) {
163
+ switch (_b.label) {
164
+ case 0:
165
+ console.info(colors.cyan("".concat(greeting, " ").concat(name)));
166
+ return [4 /*yield*/, forTime(1000)];
167
+ case 1:
168
+ _b.sent();
169
+ console.info(colors.rainbow("Nice to meet you!"));
170
+ process.exit(0);
171
+ return [2 /*return*/];
172
+ }
173
+ });
174
+ });
175
+ });
155
176
  }
156
177
 
157
178
  /**
158
- * Add or modify an auto-generated section in a markdown file
159
- *
160
- * @private within the library
179
+ * The maximum number of iterations for a loops
161
180
  */
162
- function addAutoGeneratedSection(content, options) {
163
- var sectionName = options.sectionName, sectionContent = options.sectionContent;
164
- var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
165
- var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
166
- var sectionMatch = content.match(sectionRegex);
167
- if (sectionMatch) {
168
- return content.replace(sectionRegex, spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
169
- }
170
- var placeForSection = removeContentComments(content).match(/^##.*$/im);
171
- if (!placeForSection) {
172
- throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
173
- }
174
- var _a = __read(placeForSection, 1), heading = _a[0];
175
- return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
176
- }
181
+ var LOOP_LIMIT = 1000;
182
+ /**
183
+ * The name of the builded promptbook library made by CLI `promptbook make` and for lookup in `createLibraryFromDirectory`
184
+ */
185
+ var PROMPTBOOK_MAKED_BASE_FILENAME = "index";
177
186
 
178
187
  /**
179
- * Prettify the html code
180
- *
181
- * @param content raw html code
182
- * @returns formatted html code
188
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
183
189
  */
184
- function prettifyMarkdown(content) {
185
- try {
186
- return format(content, {
187
- parser: 'markdown',
188
- plugins: [parserHtml],
189
- // TODO: DRY - make some import or auto-copy of .prettierrc
190
- endOfLine: 'lf',
191
- tabWidth: 4,
192
- singleQuote: true,
193
- trailingComma: 'all',
194
- arrowParens: 'always',
195
- printWidth: 120,
196
- htmlWhitespaceSensitivity: 'ignore',
197
- jsxBracketSameLine: false,
198
- bracketSpacing: true,
199
- });
200
- }
201
- catch (error) {
202
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
203
- error: error,
204
- html: content,
205
- });
206
- return content;
190
+ var PromptbookLogicError = /** @class */ (function (_super) {
191
+ __extends(PromptbookLogicError, _super);
192
+ function PromptbookLogicError(message) {
193
+ var _this = _super.call(this, message) || this;
194
+ _this.name = 'PromptbookLogicError';
195
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
196
+ return _this;
207
197
  }
208
- }
198
+ return PromptbookLogicError;
199
+ }(Error));
209
200
 
210
201
  /**
211
202
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -221,56 +212,13 @@ var PromptbookSyntaxError = /** @class */ (function (_super) {
221
212
  return PromptbookSyntaxError;
222
213
  }(Error));
223
214
 
224
- // import prepareKnowledgeFromMarkdownStringPromptbook from './prepare-knowledge-from-markdown.ptbk.md';
225
- function prepareKnowledgeFromMarkdown(options) {
226
- return __awaiter(this, void 0, void 0, function () {
227
- return __generator(this, function (_a) {
228
- return [2 /*return*/, []];
229
- });
230
- });
231
- }
232
-
233
- /**
234
- * Supported script languages
235
- */
236
- var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
237
-
238
- /**
239
- * Computes the deepness of the markdown structure.
240
- *
241
- * @private within the library
242
- */
243
- function countMarkdownStructureDeepness(markdownStructure) {
244
- var e_1, _a;
245
- var maxDeepness = 0;
246
- try {
247
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
248
- var section = _c.value;
249
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
250
- }
251
- }
252
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
253
- finally {
254
- try {
255
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
256
- }
257
- finally { if (e_1) throw e_1.error; }
258
- }
259
- return maxDeepness + 1;
260
- }
261
-
262
- /**
263
- * The maximum number of iterations for a loops
264
- */
265
- var LOOP_LIMIT = 1000;
266
-
267
215
  /**
268
216
  * This error type indicates that the error should not happen and its last check before crashing with some other error
269
217
  */
270
218
  var UnexpectedError = /** @class */ (function (_super) {
271
219
  __extends(UnexpectedError, _super);
272
220
  function UnexpectedError(message) {
273
- var _this = _super.call(this, spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
221
+ var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
274
222
  _this.name = 'UnexpectedError';
275
223
  Object.setPrototypeOf(_this, UnexpectedError.prototype);
276
224
  return _this;
@@ -279,385 +227,1722 @@ var UnexpectedError = /** @class */ (function (_super) {
279
227
  }(Error));
280
228
 
281
229
  /**
282
- * Parse a markdown string into a MarkdownStructure object.
230
+ * Tests if given string is valid URL.
283
231
  *
284
- * Note: This function does work with code blocks
285
- * Note: This function does not work with markdown comments
232
+ * Note: Dataurl are considered perfectly valid.
233
+ */
234
+ function isValidUrl(url) {
235
+ if (typeof url !== 'string') {
236
+ return false;
237
+ }
238
+ try {
239
+ if (url.startsWith('blob:')) {
240
+ url = url.replace(/^blob:/, '');
241
+ }
242
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
243
+ var urlObject = new URL(url);
244
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
245
+ return false;
246
+ }
247
+ return true;
248
+ }
249
+ catch (error) {
250
+ return false;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Validates PromptbookJson if it is logically valid
286
256
  *
287
- * @param markdown The markdown string to parse.
288
- * @returns The MarkdownStructure object.
257
+ * It checks:
258
+ * - if it has correct parameters dependency
289
259
  *
290
- * @private within the library
260
+ * It does NOT check:
261
+ * - if it is valid json
262
+ * - if it is meaningful
263
+ *
264
+ * @param promptbook valid or invalid PromptbookJson
265
+ * @returns the same promptbook if it is logically valid
266
+ * @throws {PromptbookLogicError} on logical error in the promptbook
291
267
  */
292
- function markdownToMarkdownStructure(markdown) {
293
- var e_1, _a;
294
- var lines = markdown.split('\n');
295
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
296
- var current = root;
297
- var isInsideCodeBlock = false;
268
+ function validatePromptbook(promptbook) {
269
+ // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
270
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
271
+ if (promptbook.promptbookUrl !== undefined) {
272
+ if (!isValidUrl(promptbook.promptbookUrl)) {
273
+ // TODO: This should be maybe the syntax error detected during parsing
274
+ throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
275
+ }
276
+ }
277
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
278
+ if (!Array.isArray(promptbook.parameters)) {
279
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
280
+ throw new PromptbookSyntaxError(spaceTrim$1("\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 ")));
281
+ }
282
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
283
+ if (!Array.isArray(promptbook.promptTemplates)) {
284
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
285
+ throw new PromptbookSyntaxError(spaceTrim$1("\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 ")));
286
+ }
287
+ var _loop_1 = function (parameter) {
288
+ if (parameter.isInput && parameter.isOutput) {
289
+ throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
290
+ }
291
+ // Note: Testing that parameter is either intermediate or output BUT not created and unused
292
+ if (!parameter.isInput &&
293
+ !parameter.isOutput &&
294
+ !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
295
+ throw new PromptbookLogicError(spaceTrim$1("\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 ")));
296
+ }
297
+ // Note: Testing that parameter is either input or result of some template
298
+ if (!parameter.isInput &&
299
+ !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
300
+ throw new PromptbookLogicError(spaceTrim$1("\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 ")));
301
+ }
302
+ };
298
303
  try {
299
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
300
- var line = lines_1_1.value;
301
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
302
- if (isInsideCodeBlock || !headingMatch) {
303
- if (line.startsWith('```')) {
304
- isInsideCodeBlock = !isInsideCodeBlock;
305
- }
306
- current.contentLines.push(line);
304
+ // Note: Check each parameter individually
305
+ for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
306
+ var parameter = _f.value;
307
+ _loop_1(parameter);
308
+ }
309
+ }
310
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
311
+ finally {
312
+ try {
313
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
314
+ }
315
+ finally { if (e_1) throw e_1.error; }
316
+ }
317
+ // Note: Check each template individually
318
+ var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
319
+ var isInput = _a.isInput;
320
+ return isInput;
321
+ }).map(function (_a) {
322
+ var name = _a.name;
323
+ return name;
324
+ }));
325
+ try {
326
+ for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
327
+ var template = _h.value;
328
+ if (definedParameters.has(template.resultingParameterName)) {
329
+ throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
307
330
  }
308
- else {
309
- var level = headingMatch.groups.mark.length;
310
- var title = headingMatch.groups.title.trim();
311
- var parent_1 = void 0;
312
- if (level > current.level) {
313
- // Note: Going deeper (next section is child of current)
314
- parent_1 = current;
331
+ definedParameters.add(template.resultingParameterName);
332
+ if (template.executionType === 'PROMPT_TEMPLATE' && template.modelRequirements.modelVariant === undefined) {
333
+ throw new PromptbookLogicError(spaceTrim$1("\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 ")));
334
+ }
335
+ if (template.jokers && template.jokers.length > 0) {
336
+ if (!template.expectFormat &&
337
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
338
+ throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
315
339
  }
316
- else {
317
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
318
- parent_1 = current;
319
- var loopLimit = LOOP_LIMIT;
320
- while (parent_1.level !== level - 1) {
321
- if (loopLimit-- < 0) {
322
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
340
+ try {
341
+ for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
342
+ var joker = _k.value;
343
+ if (!template.dependentParameterNames.includes(joker)) {
344
+ throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
323
345
  }
324
- if (parent_1.parent === null /* <- Note: We are in root */) {
325
- // [🌻]
326
- throw new Error(spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
346
+ }
347
+ }
348
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
349
+ finally {
350
+ try {
351
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
352
+ }
353
+ finally { if (e_3) throw e_3.error; }
354
+ }
355
+ }
356
+ if (template.expectations) {
357
+ try {
358
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
359
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
360
+ if (min !== undefined && max !== undefined && min > max) {
361
+ throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
362
+ }
363
+ if (min !== undefined && min < 0) {
364
+ throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
365
+ }
366
+ if (max !== undefined && max <= 0) {
367
+ throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
327
368
  }
328
- parent_1 = parent_1.parent;
329
369
  }
330
370
  }
331
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
332
- parent_1.sections.push(section);
333
- current = section;
371
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
372
+ finally {
373
+ try {
374
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
375
+ }
376
+ finally { if (e_4) throw e_4.error; }
377
+ }
334
378
  }
335
379
  }
336
380
  }
337
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
381
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
338
382
  finally {
339
383
  try {
340
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
384
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
341
385
  }
342
- finally { if (e_1) throw e_1.error; }
386
+ finally { if (e_2) throw e_2.error; }
343
387
  }
344
- if (root.sections.length === 1) {
345
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
346
- return markdownStructure;
388
+ // Note: Detect circular dependencies
389
+ var resovedParameters = promptbook.parameters
390
+ .filter(function (_a) {
391
+ var isInput = _a.isInput;
392
+ return isInput;
393
+ })
394
+ .map(function (_a) {
395
+ var name = _a.name;
396
+ return name;
397
+ });
398
+ var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
399
+ var loopLimit = LOOP_LIMIT;
400
+ var _loop_2 = function () {
401
+ if (loopLimit-- < 0) {
402
+ throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbook`');
403
+ }
404
+ var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
405
+ return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
406
+ });
407
+ if (currentlyResovedTemplates.length === 0) {
408
+ throw new PromptbookLogicError(spaceTrim$1(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
409
+ .map(function (_a) {
410
+ var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
411
+ return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
412
+ .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
413
+ .join(', '));
414
+ })
415
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
416
+ }
417
+ resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
418
+ var resultingParameterName = _a.resultingParameterName;
419
+ return resultingParameterName;
420
+ })), false);
421
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
422
+ };
423
+ while (unresovedTemplates.length > 0) {
424
+ _loop_2();
347
425
  }
348
- // [🌻]
349
- throw new Error('The markdown file must have exactly one top-level section.');
350
- // return root;
426
+ return promptbook;
351
427
  }
352
428
  /**
353
- * @private
429
+ * TODO: [🧠] Work with promptbookVersion
430
+ * TODO: Use here some json-schema, Zod or something similar and change it to:
431
+ * > /**
432
+ * > * Validates PromptbookJson if it is logically valid.
433
+ * > *
434
+ * > * It checks:
435
+ * > * - it has a valid structure
436
+ * > * - ...
437
+ * > ex port function validatePromptbook(promptbook: unknown): asserts promptbook is PromptbookJson {
354
438
  */
355
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
356
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
357
- return {
358
- level: level,
359
- title: title,
360
- content: spaceTrim(contentLines.join('\n')),
361
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
362
- };
363
- }
439
+
440
+ var promptbookLibrary = [{title:"Prepare Keywords",promptbookUrl:"https://promptbook.studio/promptbook/prepare-keywords.ptbk.md",promptbookVersion:"0.59.0-29",parameters:[{name:"content",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",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, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {content}",resultingParameterName:"keywords"}],knowledge:[]},{title:"Prepare Knowledge from Markdown",promptbookUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.59.0-29",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:[]}];
364
441
 
365
442
  /**
366
- * Utility function to extract all list items from markdown
443
+ * This error indicates errors during the execution of the promptbook
444
+ */
445
+ var PromptbookExecutionError = /** @class */ (function (_super) {
446
+ __extends(PromptbookExecutionError, _super);
447
+ function PromptbookExecutionError(message) {
448
+ var _this = _super.call(this, message) || this;
449
+ _this.name = 'PromptbookExecutionError';
450
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
451
+ return _this;
452
+ }
453
+ return PromptbookExecutionError;
454
+ }(Error));
455
+
456
+ /**
457
+ * Asserts that the execution of a promptnook is successful
367
458
  *
368
- * Note: It works with both ul and ol
369
- * Note: It omits list items in code blocks
370
- * Note: It flattens nested lists
371
- * Note: It can not work with html syntax and comments
459
+ * @param executionResult - The partial result of the promptnook execution
460
+ * @throws {PromptbookExecutionError} If the execution is not successful or if multiple errors occurred
461
+ */
462
+ function assertsExecutionSuccessful(executionResult) {
463
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
464
+ if (isSuccessful === true) {
465
+ return;
466
+ }
467
+ if (errors.length === 0) {
468
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
469
+ }
470
+ else if (errors.length === 1) {
471
+ throw errors[0];
472
+ }
473
+ else {
474
+ throw new PromptbookExecutionError(spaceTrim$1(function (block) { return "\n Multiple errors occurred during promptnook execution\n\n ".concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n')), "\n "); }));
475
+ }
476
+ }
477
+ /**
478
+ * TODO: [🧠] Can this return type be better typed than void
479
+ */
480
+
481
+ /**
482
+ * This error occurs when some expectation is not met in the execution of the pipeline
372
483
  *
373
- * @param markdown any valid markdown
374
- * @returns
484
+ * @private Always catched and rethrown as `PromptbookExecutionError`
485
+ * Note: This is a kindof subtype of PromptbookExecutionError
375
486
  */
376
- function extractAllListItemsFromMarkdown(markdown) {
377
- var e_1, _a;
378
- var lines = markdown.split('\n');
379
- var listItems = [];
380
- var isInCodeBlock = false;
487
+ var ExpectError = /** @class */ (function (_super) {
488
+ __extends(ExpectError, _super);
489
+ function ExpectError(message) {
490
+ var _this = _super.call(this, message) || this;
491
+ _this.name = 'ExpectError';
492
+ Object.setPrototypeOf(_this, ExpectError.prototype);
493
+ return _this;
494
+ }
495
+ return ExpectError;
496
+ }(Error));
497
+
498
+ /**
499
+ * Function isValidJsonString will tell you if the string is valid JSON or not
500
+ */
501
+ function isValidJsonString(value /* <-[👨‍⚖️] */) {
381
502
  try {
382
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
383
- var line = lines_1_1.value;
384
- var trimmedLine = line.trim();
385
- if (trimmedLine.startsWith('```')) {
386
- isInCodeBlock = !isInCodeBlock;
387
- }
388
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
389
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
390
- listItems.push(listItem);
391
- }
392
- }
503
+ JSON.parse(value);
504
+ return true;
393
505
  }
394
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
395
- finally {
396
- try {
397
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
506
+ catch (error) {
507
+ if (!(error instanceof Error)) {
508
+ throw error;
398
509
  }
399
- finally { if (e_1) throw e_1.error; }
510
+ if (error.message.includes('Unexpected token')) {
511
+ return false;
512
+ }
513
+ return false;
400
514
  }
401
- return listItems;
402
- }
403
-
404
- /**
405
- * Makes first letter of a string uppercase
406
- *
407
- */
408
- function capitalize(word) {
409
- return word.substring(0, 1).toUpperCase() + word.substring(1);
410
515
  }
411
516
 
412
517
  /**
413
- * Extracts all code blocks from markdown.
414
- *
415
- * Note: There are 3 simmilar function:
416
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
417
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
418
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
419
- *
420
- * @param markdown any valid markdown
421
- * @returns code blocks with language and content
518
+ * Function `addUsage` will add multiple usages into one
422
519
  *
520
+ * Note: If you provide 0 values, it returns void usage
423
521
  */
424
- function extractAllBlocksFromMarkdown(markdown) {
425
- var e_1, _a;
426
- var codeBlocks = [];
427
- var lines = markdown.split('\n');
428
- var currentCodeBlock = null;
429
- try {
430
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
431
- var line = lines_1_1.value;
432
- if (line.startsWith('```')) {
433
- var language = line.slice(3).trim() || null;
434
- if (currentCodeBlock === null) {
435
- currentCodeBlock = { language: language, content: '' };
436
- }
437
- else {
438
- if (language !== null) {
439
- // [🌻]
440
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
522
+ function addUsage() {
523
+ var usageItems = [];
524
+ for (var _i = 0; _i < arguments.length; _i++) {
525
+ usageItems[_i] = arguments[_i];
526
+ }
527
+ var initialStructure = {
528
+ price: { value: 0 },
529
+ input: {
530
+ tokensCount: { value: 0 },
531
+ charactersCount: { value: 0 },
532
+ wordsCount: { value: 0 },
533
+ sentencesCount: { value: 0 },
534
+ linesCount: { value: 0 },
535
+ paragraphsCount: { value: 0 },
536
+ pagesCount: { value: 0 },
537
+ },
538
+ output: {
539
+ tokensCount: { value: 0 },
540
+ charactersCount: { value: 0 },
541
+ wordsCount: { value: 0 },
542
+ sentencesCount: { value: 0 },
543
+ linesCount: { value: 0 },
544
+ paragraphsCount: { value: 0 },
545
+ pagesCount: { value: 0 },
546
+ },
547
+ };
548
+ return usageItems.reduce(function (acc, item) {
549
+ var e_1, _a, e_2, _b;
550
+ var _c;
551
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
552
+ try {
553
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
554
+ var key = _e.value;
555
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
556
+ //@ts-ignore
557
+ if (item.input[key]) {
558
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
559
+ //@ts-ignore
560
+ acc.input[key].value += item.input[key].value || 0;
561
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
562
+ //@ts-ignore
563
+ if (item.input[key].isUncertain) {
564
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
565
+ //@ts-ignore
566
+ acc.input[key].isUncertain = true;
441
567
  }
442
- codeBlocks.push(currentCodeBlock);
443
- currentCodeBlock = null;
444
568
  }
445
569
  }
446
- else if (currentCodeBlock !== null) {
447
- if (currentCodeBlock.content !== '') {
448
- currentCodeBlock.content += '\n';
449
- }
450
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
570
+ }
571
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
572
+ finally {
573
+ try {
574
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
451
575
  }
576
+ finally { if (e_1) throw e_1.error; }
452
577
  }
453
- }
454
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
455
- finally {
456
578
  try {
457
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
579
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
580
+ var key = _g.value;
581
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
582
+ //@ts-ignore
583
+ if (item.output[key]) {
584
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
585
+ //@ts-ignore
586
+ acc.output[key].value += item.output[key].value || 0;
587
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
588
+ //@ts-ignore
589
+ if (item.output[key].isUncertain) {
590
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
591
+ //@ts-ignore
592
+ acc.output[key].isUncertain = true;
593
+ }
594
+ }
595
+ }
458
596
  }
459
- finally { if (e_1) throw e_1.error; }
460
- }
461
- if (currentCodeBlock !== null) {
462
- // [🌻]
463
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
464
- }
465
- return codeBlocks;
597
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
598
+ finally {
599
+ try {
600
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
601
+ }
602
+ finally { if (e_2) throw e_2.error; }
603
+ }
604
+ return acc;
605
+ }, initialStructure);
466
606
  }
467
607
 
468
608
  /**
469
- * Extracts exactly ONE code block from markdown.
470
- *
471
- * Note: If there are multiple or no code blocks the function throws an error
472
- *
473
- * Note: There are 3 simmilar function:
474
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
475
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
476
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
477
- *
478
- * @param markdown any valid markdown
479
- * @returns code block with language and content
609
+ * Counts number of characters in the text
480
610
  */
481
- function extractOneBlockFromMarkdown(markdown) {
482
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
483
- if (codeBlocks.length !== 1) {
484
- // TODO: Report more specific place where the error happened
485
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
486
- }
487
- return codeBlocks[0];
611
+ function countCharacters(text) {
612
+ // Remove null characters
613
+ text = text.replace(/\0/g, '');
614
+ // Replace emojis (and also ZWJ sequence) with hyphens
615
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
616
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
617
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
618
+ return text.length;
488
619
  }
489
- /***
490
- * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
491
- */
492
620
 
493
621
  /**
494
- * Creates a new set with all elements that are present in either set
622
+ * Counts number of lines in the text
495
623
  */
496
- function union() {
497
- var e_1, _a, e_2, _b;
498
- var sets = [];
499
- for (var _i = 0; _i < arguments.length; _i++) {
500
- sets[_i] = arguments[_i];
501
- }
502
- var union = new Set();
503
- try {
504
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
505
- var set = sets_1_1.value;
506
- try {
507
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
508
- var item = _d.value;
509
- union.add(item);
510
- }
511
- }
512
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
513
- finally {
514
- try {
515
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
516
- }
517
- finally { if (e_2) throw e_2.error; }
518
- }
519
- }
520
- }
521
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
522
- finally {
523
- try {
524
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
525
- }
526
- finally { if (e_1) throw e_1.error; }
624
+ function countLines(text) {
625
+ if (text === '') {
626
+ return 0;
527
627
  }
528
- return union;
628
+ return text.split('\n').length;
529
629
  }
530
630
 
531
631
  /**
532
- * Parses the template and returns the list of all parameter names
533
- *
534
- * @param template the template with parameters in {curly} braces
535
- * @returns the list of parameter names
632
+ * Counts number of pages in the text
536
633
  */
537
- function extractParameters(template) {
538
- var e_1, _a;
539
- var matches = template.matchAll(/{\w+}/g);
540
- var parameterNames = new Set();
541
- try {
542
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
543
- var match = matches_1_1.value;
544
- var parameterName = match[0].slice(1, -1);
545
- parameterNames.add(parameterName);
546
- }
547
- }
548
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
549
- finally {
550
- try {
551
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
552
- }
553
- finally { if (e_1) throw e_1.error; }
554
- }
555
- return parameterNames;
634
+ function countPages(text) {
635
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
636
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
637
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
638
+ return pageCount;
556
639
  }
557
640
 
558
641
  /**
559
- * Parses the given script and returns the list of all used variables that are not defined in the script
560
- *
561
- * @param script from which to extract the variables
562
- * @returns the list of variable names
563
- * @throws {PromptbookSyntaxError} if the script is invalid
642
+ * Counts number of paragraphs in the text
564
643
  */
565
- function extractVariables(script) {
566
- var variables = new Set();
567
- script = "(()=>{".concat(script, "})()");
568
- try {
569
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
570
- try {
571
- eval(script);
572
- }
573
- catch (error) {
574
- if (!(error instanceof ReferenceError)) {
575
- throw error;
576
- }
577
- var undefinedName = error.message.split(' ')[0];
578
- /*
579
- Note: Remapping error
580
- From: [ReferenceError: thing is not defined],
581
- To: [Error: Parameter {thing} is not defined],
582
- */
583
- if (!undefinedName) {
584
- throw error;
585
- }
586
- if (script.includes(undefinedName + '(')) {
587
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
588
- }
589
- else {
590
- variables.add(undefinedName);
591
- script = "const ".concat(undefinedName, " = '';") + script;
592
- }
593
- }
594
- }
595
- catch (error) {
596
- if (!(error instanceof Error)) {
597
- throw error;
598
- }
599
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
600
- }
601
- return variables;
644
+ function countParagraphs(text) {
645
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
602
646
  }
603
- /**
604
- * TODO: [🔣] Support for multiple languages - python, java,...
605
- */
606
647
 
607
648
  /**
608
- * Parses the prompt template and returns the set of all used parameters
609
- *
610
- * @param promptTemplate the template with used parameters
611
- * @returns the set of parameter names
612
- * @throws {PromptbookSyntaxError} if the script is invalid
649
+ * Split text into sentences
613
650
  */
614
- function extractParametersFromPromptTemplate(promptTemplate) {
615
- var e_1, _a, e_2, _b;
616
- var parameterNames = new Set();
617
- try {
618
- 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()) {
619
- var parameterName = _d.value;
620
- parameterNames.add(parameterName);
621
- }
622
- }
623
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
624
- finally {
625
- try {
626
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
627
- }
628
- finally { if (e_1) throw e_1.error; }
629
- }
630
- if (promptTemplate.executionType === 'SCRIPT') {
631
- try {
632
- for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
633
- var parameterName = _f.value;
634
- parameterNames.add(parameterName);
635
- }
636
- }
637
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
638
- finally {
639
- try {
640
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
641
- }
642
- finally { if (e_2) throw e_2.error; }
643
- }
644
- }
645
- return parameterNames;
651
+ function splitIntoSentences(text) {
652
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
646
653
  }
647
654
  /**
648
- * TODO: [🔣] If script require contentLanguage
655
+ * Counts number of sentences in the text
649
656
  */
657
+ function countSentences(text) {
658
+ return splitIntoSentences(text).length;
659
+ }
650
660
 
651
- /* tslint:disable */
652
- /*
653
- TODO: Tests
654
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
655
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
656
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
657
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
661
+ var defaultDiacriticsRemovalMap = [
662
+ {
663
+ base: 'A',
664
+ letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F',
665
+ },
666
+ { base: 'AA', letters: '\uA732' },
667
+ { base: 'AE', letters: '\u00C6\u01FC\u01E2' },
668
+ { base: 'AO', letters: '\uA734' },
669
+ { base: 'AU', letters: '\uA736' },
670
+ { base: 'AV', letters: '\uA738\uA73A' },
671
+ { base: 'AY', letters: '\uA73C' },
672
+ {
673
+ base: 'B',
674
+ letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181',
675
+ },
676
+ {
677
+ base: 'C',
678
+ letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E',
679
+ },
680
+ {
681
+ base: 'D',
682
+ letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0',
683
+ },
684
+ { base: 'DZ', letters: '\u01F1\u01C4' },
685
+ { base: 'Dz', letters: '\u01F2\u01C5' },
686
+ {
687
+ base: 'E',
688
+ letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E',
689
+ },
690
+ { base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
691
+ {
692
+ base: 'G',
693
+ letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E',
694
+ },
695
+ {
696
+ base: 'H',
697
+ letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D',
698
+ },
699
+ {
700
+ base: 'I',
701
+ letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197',
702
+ },
703
+ { base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
704
+ {
705
+ base: 'K',
706
+ letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2',
707
+ },
708
+ {
709
+ base: 'L',
710
+ letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780',
711
+ },
712
+ { base: 'LJ', letters: '\u01C7' },
713
+ { base: 'Lj', letters: '\u01C8' },
714
+ { base: 'M', letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
715
+ {
716
+ base: 'N',
717
+ letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4',
718
+ },
719
+ { base: 'NJ', letters: '\u01CA' },
720
+ { base: 'Nj', letters: '\u01CB' },
721
+ {
722
+ base: 'O',
723
+ letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C',
724
+ },
725
+ { base: 'OI', letters: '\u01A2' },
726
+ { base: 'OO', letters: '\uA74E' },
727
+ { base: 'OU', letters: '\u0222' },
728
+ { base: 'OE', letters: '\u008C\u0152' },
729
+ { base: 'oe', letters: '\u009C\u0153' },
730
+ {
731
+ base: 'P',
732
+ letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754',
733
+ },
734
+ { base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
735
+ {
736
+ base: 'R',
737
+ letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782',
738
+ },
739
+ {
740
+ base: 'S',
741
+ letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784',
742
+ },
743
+ {
744
+ base: 'T',
745
+ letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786',
746
+ },
747
+ { base: 'TZ', letters: '\uA728' },
748
+ {
749
+ base: 'U',
750
+ letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244',
751
+ },
752
+ { base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
753
+ { base: 'VY', letters: '\uA760' },
754
+ {
755
+ base: 'W',
756
+ letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72',
757
+ },
758
+ { base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
759
+ {
760
+ base: 'Y',
761
+ letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE',
762
+ },
763
+ {
764
+ base: 'Z',
765
+ letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762',
766
+ },
767
+ {
768
+ base: 'a',
769
+ letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250',
770
+ },
771
+ { base: 'aa', letters: '\uA733' },
772
+ { base: 'ae', letters: '\u00E6\u01FD\u01E3' },
773
+ { base: 'ao', letters: '\uA735' },
774
+ { base: 'au', letters: '\uA737' },
775
+ { base: 'av', letters: '\uA739\uA73B' },
776
+ { base: 'ay', letters: '\uA73D' },
777
+ {
778
+ base: 'b',
779
+ letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253',
780
+ },
781
+ {
782
+ base: 'c',
783
+ letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184',
784
+ },
785
+ {
786
+ base: 'd',
787
+ letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A',
788
+ },
789
+ { base: 'dz', letters: '\u01F3\u01C6' },
790
+ {
791
+ base: 'e',
792
+ letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD',
793
+ },
794
+ { base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
795
+ {
796
+ base: 'g',
797
+ letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F',
798
+ },
799
+ {
800
+ base: 'h',
801
+ letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265',
802
+ },
803
+ { base: 'hv', letters: '\u0195' },
804
+ {
805
+ base: 'i',
806
+ letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131',
807
+ },
808
+ { base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
809
+ {
810
+ base: 'k',
811
+ letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3',
812
+ },
813
+ {
814
+ base: 'l',
815
+ letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747',
816
+ },
817
+ { base: 'lj', letters: '\u01C9' },
818
+ { base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
819
+ {
820
+ base: 'n',
821
+ letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5',
822
+ },
823
+ { base: 'nj', letters: '\u01CC' },
824
+ {
825
+ base: 'o',
826
+ letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275',
827
+ },
828
+ { base: 'oi', letters: '\u01A3' },
829
+ { base: 'ou', letters: '\u0223' },
830
+ { base: 'oo', letters: '\uA74F' },
831
+ {
832
+ base: 'p',
833
+ letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755',
834
+ },
835
+ { base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
836
+ {
837
+ base: 'r',
838
+ letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783',
839
+ },
840
+ {
841
+ base: 's',
842
+ letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B',
843
+ },
844
+ {
845
+ base: 't',
846
+ letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787',
847
+ },
848
+ { base: 'tz', letters: '\uA729' },
849
+ {
850
+ base: 'u',
851
+ letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289',
852
+ },
853
+ { base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
854
+ { base: 'vy', letters: '\uA761' },
855
+ {
856
+ base: 'w',
857
+ letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73',
858
+ },
859
+ { base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
860
+ {
861
+ base: 'y',
862
+ letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF',
863
+ },
864
+ {
865
+ base: 'z',
866
+ letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763',
867
+ },
868
+ ];
869
+ /**
870
+ * Map of letters from diacritic variant to diacritless variant
871
+ * Contains lowercase and uppercase separatelly
872
+ *
873
+ * > "á" => "a"
874
+ * > "ě" => "e"
875
+ * > "Ă" => "A"
876
+ * > ...
877
+ */
878
+ var DIACRITIC_VARIANTS_LETTERS = {};
879
+ // tslint:disable-next-line: prefer-for-of
880
+ for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
881
+ var letters = defaultDiacriticsRemovalMap[i].letters;
882
+ // tslint:disable-next-line: prefer-for-of
883
+ for (var j = 0; j < letters.length; j++) {
884
+ DIACRITIC_VARIANTS_LETTERS[letters[j]] = defaultDiacriticsRemovalMap[i].base;
885
+ }
886
+ }
887
+ // <- TODO: [🍓] Put to maker function to save execution time if not needed
888
+ /*
889
+ @see https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
890
+ Licensed under the Apache License, Version 2.0 (the "License");
891
+ you may not use this file except in compliance with the License.
892
+ You may obtain a copy of the License at
893
+
894
+ http://www.apache.org/licenses/LICENSE-2.0
895
+
896
+ Unless required by applicable law or agreed to in writing, software
897
+ distributed under the License is distributed on an "AS IS" BASIS,
898
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
899
+ See the License for the specific language governing permissions and
900
+ limitations under the License.
658
901
  */
659
- function normalizeTo_SCREAMING_CASE(sentence) {
902
+
903
+ /**
904
+ *
905
+ */
906
+ function removeDiacritics(input) {
907
+ /*eslint no-control-regex: "off"*/
908
+ return input.replace(/[^\u0000-\u007E]/g, function (a) {
909
+ return DIACRITIC_VARIANTS_LETTERS[a] || a;
910
+ });
911
+ }
912
+
913
+ /**
914
+ * Counts number of words in the text
915
+ */
916
+ function countWords(text) {
917
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
918
+ text = removeDiacritics(text);
919
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
920
+ }
921
+
922
+ /**
923
+ * Index of all counter functions
924
+ */
925
+ var CountUtils = {
926
+ CHARACTERS: countCharacters,
927
+ WORDS: countWords,
928
+ SENTENCES: countSentences,
929
+ PARAGRAPHS: countParagraphs,
930
+ LINES: countLines,
931
+ PAGES: countPages,
932
+ };
933
+
934
+ /**
935
+ * Function checkExpectations will check if the expectations on given value are met
936
+ *
937
+ * Note: There are two simmilar functions:
938
+ * - `checkExpectations` which throws an error if the expectations are not met
939
+ * - `isPassingExpectations` which returns a boolean
940
+ *
941
+ * @throws {ExpectError} if the expectations are not met
942
+ * @returns {void} Nothing
943
+ */
944
+ function checkExpectations(expectations, value) {
945
+ var e_1, _a;
946
+ try {
947
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
948
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
949
+ var amount = CountUtils[unit.toUpperCase()](value);
950
+ if (min && amount < min) {
951
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
952
+ } /* not else */
953
+ if (max && amount > max) {
954
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
955
+ }
956
+ }
957
+ }
958
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
959
+ finally {
960
+ try {
961
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
962
+ }
963
+ finally { if (e_1) throw e_1.error; }
964
+ }
965
+ }
966
+ /**
967
+ * TODO: [💝] Unite object for expecting amount and format
968
+ */
969
+
970
+ /**
971
+ * This error occurs during the parameter replacement in the template
972
+ *
973
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
974
+ */
975
+ var TemplateError = /** @class */ (function (_super) {
976
+ __extends(TemplateError, _super);
977
+ function TemplateError(message) {
978
+ var _this = _super.call(this, message) || this;
979
+ _this.name = 'TemplateError';
980
+ Object.setPrototypeOf(_this, TemplateError.prototype);
981
+ return _this;
982
+ }
983
+ return TemplateError;
984
+ }(Error));
985
+
986
+ /**
987
+ * Replaces parameters in template with values from parameters object
988
+ *
989
+ * @param template the template with parameters in {curly} braces
990
+ * @param parameters the object with parameters
991
+ * @returns the template with replaced parameters
992
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
993
+ *
994
+ * @private within the createPromptbookExecutor
995
+ */
996
+ function replaceParameters(template, parameters) {
997
+ var replacedTemplate = template;
998
+ var match;
999
+ var loopLimit = LOOP_LIMIT;
1000
+ var _loop_1 = function () {
1001
+ if (loopLimit-- < 0) {
1002
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
1003
+ }
1004
+ var precol = match.groups.precol;
1005
+ var parameterName = match.groups.parameterName;
1006
+ if (parameterName === '') {
1007
+ return "continue";
1008
+ }
1009
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
1010
+ throw new TemplateError('Parameter is already opened or not closed');
1011
+ }
1012
+ if (parameters[parameterName] === undefined) {
1013
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
1014
+ }
1015
+ var parameterValue = parameters[parameterName];
1016
+ if (parameterValue === undefined) {
1017
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
1018
+ }
1019
+ parameterValue = parameterValue.toString();
1020
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
1021
+ parameterValue = parameterValue
1022
+ .split('\n')
1023
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
1024
+ .join('\n');
1025
+ }
1026
+ replacedTemplate =
1027
+ replacedTemplate.substring(0, match.index + precol.length) +
1028
+ parameterValue +
1029
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
1030
+ };
1031
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
1032
+ .exec(replacedTemplate))) {
1033
+ _loop_1();
1034
+ }
1035
+ // [💫] Check if there are parameters that are not closed properly
1036
+ if (/{\w+$/.test(replacedTemplate)) {
1037
+ throw new TemplateError('Parameter is not closed');
1038
+ }
1039
+ // [💫] Check if there are parameters that are not opened properly
1040
+ if (/^\w+}/.test(replacedTemplate)) {
1041
+ throw new TemplateError('Parameter is not opened');
1042
+ }
1043
+ return replacedTemplate;
1044
+ }
1045
+
1046
+ /**
1047
+ * Creates executor function from promptbook and execution tools.
1048
+ *
1049
+ * @returns The executor function
1050
+ * @throws {PromptbookLogicError} on logical error in the promptbook
1051
+ */
1052
+ function createPromptbookExecutor(options) {
1053
+ var _this = this;
1054
+ var promptbook = options.promptbook, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
1055
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
1056
+ validatePromptbook(promptbook);
1057
+ var promptbookExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1058
+ function executeSingleTemplate(currentTemplate) {
1059
+ return __awaiter(this, void 0, void 0, function () {
1060
+ 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;
1061
+ var e_2, _j, e_4, _k, e_3, _l, _m;
1062
+ var _this = this;
1063
+ return __generator(this, function (_o) {
1064
+ switch (_o.label) {
1065
+ case 0:
1066
+ name = "promptbook-executor-frame-".concat(currentTemplate.name);
1067
+ title = currentTemplate.title;
1068
+ priority = promptbook.promptTemplates.length - promptbook.promptTemplates.indexOf(currentTemplate);
1069
+ if (!onProgress /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
1070
+ return [4 /*yield*/, onProgress({
1071
+ name: name,
1072
+ title: title,
1073
+ isStarted: false,
1074
+ isDone: false,
1075
+ executionType: currentTemplate.executionType,
1076
+ parameterName: currentTemplate.resultingParameterName,
1077
+ parameterValue: null,
1078
+ // <- [3]
1079
+ })];
1080
+ case 1:
1081
+ _o.sent();
1082
+ _o.label = 2;
1083
+ case 2:
1084
+ result = null;
1085
+ resultString = null;
1086
+ expectError = null;
1087
+ maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1088
+ jokers = currentTemplate.jokers || [];
1089
+ attempt = -jokers.length;
1090
+ _o.label = 3;
1091
+ case 3:
1092
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1093
+ isJokerAttempt = attempt < 0;
1094
+ joker = jokers[jokers.length + attempt];
1095
+ if (isJokerAttempt && !joker) {
1096
+ throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
1097
+ }
1098
+ result = null;
1099
+ resultString = null;
1100
+ expectError = null;
1101
+ if (isJokerAttempt) {
1102
+ if (typeof parametersToPass[joker] === 'undefined') {
1103
+ throw new PromptbookExecutionError("Joker parameter {".concat(joker, "} not defined"));
1104
+ }
1105
+ resultString = parametersToPass[joker];
1106
+ }
1107
+ _o.label = 4;
1108
+ case 4:
1109
+ _o.trys.push([4, 45, 46, 47]);
1110
+ if (!!isJokerAttempt) return [3 /*break*/, 27];
1111
+ _a = currentTemplate.executionType;
1112
+ switch (_a) {
1113
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
1114
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
1115
+ case 'SCRIPT': return [3 /*break*/, 13];
1116
+ case 'PROMPT_DIALOG': return [3 /*break*/, 24];
1117
+ }
1118
+ return [3 /*break*/, 26];
1119
+ case 5:
1120
+ resultString = replaceParameters(currentTemplate.content, parametersToPass);
1121
+ return [3 /*break*/, 27];
1122
+ case 6:
1123
+ prompt = {
1124
+ title: currentTemplate.title,
1125
+ promptbookUrl: "".concat(promptbook.promptbookUrl
1126
+ ? promptbook.promptbookUrl
1127
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous PROMPTBOOKs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1128
+ parameters: parametersToPass,
1129
+ content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1130
+ modelRequirements: currentTemplate.modelRequirements,
1131
+ expectations: currentTemplate.expectations,
1132
+ expectFormat: currentTemplate.expectFormat,
1133
+ postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
1134
+ var errors, _a, _b, scriptTools, error_5, e_5_1;
1135
+ var e_5, _c;
1136
+ return __generator(this, function (_d) {
1137
+ switch (_d.label) {
1138
+ case 0:
1139
+ errors = [];
1140
+ _d.label = 1;
1141
+ case 1:
1142
+ _d.trys.push([1, 8, 9, 10]);
1143
+ _a = __values(tools.script), _b = _a.next();
1144
+ _d.label = 2;
1145
+ case 2:
1146
+ if (!!_b.done) return [3 /*break*/, 7];
1147
+ scriptTools = _b.value;
1148
+ _d.label = 3;
1149
+ case 3:
1150
+ _d.trys.push([3, 5, , 6]);
1151
+ return [4 /*yield*/, scriptTools.execute({
1152
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1153
+ script: "".concat(functionName, "(result)"),
1154
+ parameters: {
1155
+ result: result || '',
1156
+ // Note: No ...parametersToPass, because working with result only
1157
+ },
1158
+ })];
1159
+ case 4: return [2 /*return*/, _d.sent()];
1160
+ case 5:
1161
+ error_5 = _d.sent();
1162
+ if (!(error_5 instanceof Error)) {
1163
+ throw error_5;
1164
+ }
1165
+ errors.push(error_5);
1166
+ return [3 /*break*/, 6];
1167
+ case 6:
1168
+ _b = _a.next();
1169
+ return [3 /*break*/, 2];
1170
+ case 7: return [3 /*break*/, 10];
1171
+ case 8:
1172
+ e_5_1 = _d.sent();
1173
+ e_5 = { error: e_5_1 };
1174
+ return [3 /*break*/, 10];
1175
+ case 9:
1176
+ try {
1177
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1178
+ }
1179
+ finally { if (e_5) throw e_5.error; }
1180
+ return [7 /*endfinally*/];
1181
+ case 10:
1182
+ if (errors.length === 0) {
1183
+ throw new PromptbookExecutionError('Postprocessing in LlmExecutionTools failed because no ScriptExecutionTools were provided');
1184
+ }
1185
+ else if (errors.length === 1) {
1186
+ throw errors[0];
1187
+ }
1188
+ else {
1189
+ throw new PromptbookExecutionError(spaceTrim$1(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 "); }));
1190
+ }
1191
+ }
1192
+ });
1193
+ }); }; }),
1194
+ };
1195
+ _b = currentTemplate.modelRequirements.modelVariant;
1196
+ switch (_b) {
1197
+ case 'CHAT': return [3 /*break*/, 7];
1198
+ case 'COMPLETION': return [3 /*break*/, 9];
1199
+ }
1200
+ return [3 /*break*/, 11];
1201
+ case 7: return [4 /*yield*/, tools.llm.gptChat(prompt)];
1202
+ case 8:
1203
+ chatThread = _o.sent();
1204
+ // TODO: [🍬] Destroy chatThread
1205
+ result = chatThread;
1206
+ resultString = chatThread.content;
1207
+ return [3 /*break*/, 12];
1208
+ case 9: return [4 /*yield*/, tools.llm.gptComplete(prompt)];
1209
+ case 10:
1210
+ completionResult = _o.sent();
1211
+ result = completionResult;
1212
+ resultString = completionResult.content;
1213
+ return [3 /*break*/, 12];
1214
+ case 11: throw new PromptbookExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
1215
+ case 12: return [3 /*break*/, 27];
1216
+ case 13:
1217
+ if (tools.script.length === 0) {
1218
+ throw new PromptbookExecutionError('No script execution tools are available');
1219
+ }
1220
+ if (!currentTemplate.contentLanguage) {
1221
+ throw new PromptbookExecutionError("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
1222
+ }
1223
+ // TODO: DRY [1]
1224
+ scriptExecutionErrors = [];
1225
+ _o.label = 14;
1226
+ case 14:
1227
+ _o.trys.push([14, 21, 22, 23]);
1228
+ _c = (e_2 = void 0, __values(tools.script)), _d = _c.next();
1229
+ _o.label = 15;
1230
+ case 15:
1231
+ if (!!_d.done) return [3 /*break*/, 20];
1232
+ scriptTools = _d.value;
1233
+ _o.label = 16;
1234
+ case 16:
1235
+ _o.trys.push([16, 18, , 19]);
1236
+ return [4 /*yield*/, scriptTools.execute({
1237
+ scriptLanguage: currentTemplate.contentLanguage,
1238
+ script: currentTemplate.content,
1239
+ parameters: parametersToPass,
1240
+ })];
1241
+ case 17:
1242
+ resultString = _o.sent();
1243
+ return [3 /*break*/, 20];
1244
+ case 18:
1245
+ error_2 = _o.sent();
1246
+ if (!(error_2 instanceof Error)) {
1247
+ throw error_2;
1248
+ }
1249
+ scriptExecutionErrors.push(error_2);
1250
+ return [3 /*break*/, 19];
1251
+ case 19:
1252
+ _d = _c.next();
1253
+ return [3 /*break*/, 15];
1254
+ case 20: return [3 /*break*/, 23];
1255
+ case 21:
1256
+ e_2_1 = _o.sent();
1257
+ e_2 = { error: e_2_1 };
1258
+ return [3 /*break*/, 23];
1259
+ case 22:
1260
+ try {
1261
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
1262
+ }
1263
+ finally { if (e_2) throw e_2.error; }
1264
+ return [7 /*endfinally*/];
1265
+ case 23:
1266
+ if (resultString !== null) {
1267
+ return [3 /*break*/, 27];
1268
+ }
1269
+ if (scriptExecutionErrors.length === 1) {
1270
+ throw scriptExecutionErrors[0];
1271
+ }
1272
+ else {
1273
+ throw new PromptbookExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
1274
+ .map(function (error) { return '- ' + error.message; })
1275
+ .join('\n\n')), "\n "); }));
1276
+ }
1277
+ case 24:
1278
+ if (tools.userInterface === undefined) {
1279
+ throw new PromptbookExecutionError('User interface tools are not available');
1280
+ }
1281
+ return [4 /*yield*/, tools.userInterface.promptDialog({
1282
+ promptTitle: currentTemplate.title,
1283
+ promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
1284
+ defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
1285
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
1286
+ placeholder: undefined,
1287
+ priority: priority,
1288
+ })];
1289
+ case 25:
1290
+ // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
1291
+ resultString = _o.sent();
1292
+ return [3 /*break*/, 27];
1293
+ case 26: throw new PromptbookExecutionError(
1294
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1295
+ "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
1296
+ case 27:
1297
+ if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
1298
+ _o.label = 28;
1299
+ case 28:
1300
+ _o.trys.push([28, 42, 43, 44]);
1301
+ _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
1302
+ _o.label = 29;
1303
+ case 29:
1304
+ if (!!_f.done) return [3 /*break*/, 41];
1305
+ functionName = _f.value;
1306
+ // TODO: DRY [1]
1307
+ scriptExecutionErrors = [];
1308
+ postprocessingError = null;
1309
+ _o.label = 30;
1310
+ case 30:
1311
+ _o.trys.push([30, 37, 38, 39]);
1312
+ _g = (e_3 = void 0, __values(tools.script)), _h = _g.next();
1313
+ _o.label = 31;
1314
+ case 31:
1315
+ if (!!_h.done) return [3 /*break*/, 36];
1316
+ scriptTools = _h.value;
1317
+ _o.label = 32;
1318
+ case 32:
1319
+ _o.trys.push([32, 34, , 35]);
1320
+ return [4 /*yield*/, scriptTools.execute({
1321
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1322
+ script: "".concat(functionName, "(resultString)"),
1323
+ parameters: {
1324
+ resultString: resultString || '',
1325
+ // Note: No ...parametersToPass, because working with result only
1326
+ },
1327
+ })];
1328
+ case 33:
1329
+ resultString = _o.sent();
1330
+ postprocessingError = null;
1331
+ return [3 /*break*/, 36];
1332
+ case 34:
1333
+ error_3 = _o.sent();
1334
+ if (!(error_3 instanceof Error)) {
1335
+ throw error_3;
1336
+ }
1337
+ postprocessingError = error_3;
1338
+ scriptExecutionErrors.push(error_3);
1339
+ return [3 /*break*/, 35];
1340
+ case 35:
1341
+ _h = _g.next();
1342
+ return [3 /*break*/, 31];
1343
+ case 36: return [3 /*break*/, 39];
1344
+ case 37:
1345
+ e_3_1 = _o.sent();
1346
+ e_3 = { error: e_3_1 };
1347
+ return [3 /*break*/, 39];
1348
+ case 38:
1349
+ try {
1350
+ if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
1351
+ }
1352
+ finally { if (e_3) throw e_3.error; }
1353
+ return [7 /*endfinally*/];
1354
+ case 39:
1355
+ if (postprocessingError) {
1356
+ throw postprocessingError;
1357
+ }
1358
+ _o.label = 40;
1359
+ case 40:
1360
+ _f = _e.next();
1361
+ return [3 /*break*/, 29];
1362
+ case 41: return [3 /*break*/, 44];
1363
+ case 42:
1364
+ e_4_1 = _o.sent();
1365
+ e_4 = { error: e_4_1 };
1366
+ return [3 /*break*/, 44];
1367
+ case 43:
1368
+ try {
1369
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
1370
+ }
1371
+ finally { if (e_4) throw e_4.error; }
1372
+ return [7 /*endfinally*/];
1373
+ case 44:
1374
+ // TODO: [💝] Unite object for expecting amount and format
1375
+ if (currentTemplate.expectFormat) {
1376
+ if (currentTemplate.expectFormat === 'JSON') {
1377
+ if (!isValidJsonString(resultString || '')) {
1378
+ throw new ExpectError('Expected valid JSON string');
1379
+ }
1380
+ }
1381
+ }
1382
+ // TODO: [💝] Unite object for expecting amount and format
1383
+ if (currentTemplate.expectations) {
1384
+ checkExpectations(currentTemplate.expectations, resultString || '');
1385
+ }
1386
+ return [3 /*break*/, 49];
1387
+ case 45:
1388
+ error_4 = _o.sent();
1389
+ if (!(error_4 instanceof ExpectError)) {
1390
+ throw error_4;
1391
+ }
1392
+ expectError = error_4;
1393
+ return [3 /*break*/, 47];
1394
+ case 46:
1395
+ if (!isJokerAttempt &&
1396
+ currentTemplate.executionType === 'PROMPT_TEMPLATE' &&
1397
+ prompt
1398
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
1399
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
1400
+ ) {
1401
+ // TODO: [🧠] Maybe put other executionTypes into report
1402
+ executionReport.promptExecutions.push({
1403
+ prompt: {
1404
+ title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
1405
+ content: prompt.content,
1406
+ modelRequirements: prompt.modelRequirements,
1407
+ expectations: prompt.expectations,
1408
+ expectFormat: prompt.expectFormat,
1409
+ // <- Note: Do want to pass ONLY wanted information to the report
1410
+ },
1411
+ result: result || undefined,
1412
+ error: expectError || undefined,
1413
+ });
1414
+ }
1415
+ return [7 /*endfinally*/];
1416
+ case 47:
1417
+ if (expectError !== null && attempt === maxAttempts - 1) {
1418
+ throw new PromptbookExecutionError(spaceTrim$1(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 "); }));
1419
+ }
1420
+ _o.label = 48;
1421
+ case 48:
1422
+ attempt++;
1423
+ return [3 /*break*/, 3];
1424
+ case 49:
1425
+ if (resultString === null) {
1426
+ throw new UnexpectedError('Something went wrong and prompt result is null');
1427
+ }
1428
+ if (onProgress /* <- [3] */) {
1429
+ onProgress({
1430
+ name: name,
1431
+ title: title,
1432
+ isStarted: true,
1433
+ isDone: true,
1434
+ executionType: currentTemplate.executionType,
1435
+ parameterName: currentTemplate.resultingParameterName,
1436
+ parameterValue: resultString,
1437
+ // <- [3]
1438
+ });
1439
+ }
1440
+ 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));
1441
+ return [2 /*return*/];
1442
+ }
1443
+ });
1444
+ });
1445
+ }
1446
+ var parametersToPass, executionReport, resovedParameters_1, unresovedTemplates, resolving_1, loopLimit, _loop_1, error_1, usage_1, _a, _b, parameter, usage;
1447
+ var e_1, _c;
1448
+ return __generator(this, function (_d) {
1449
+ switch (_d.label) {
1450
+ case 0:
1451
+ parametersToPass = inputParameters;
1452
+ executionReport = {
1453
+ promptbookUrl: promptbook.promptbookUrl,
1454
+ title: promptbook.title,
1455
+ promptbookUsedVersion: PROMPTBOOK_VERSION,
1456
+ promptbookRequestedVersion: promptbook.promptbookVersion,
1457
+ description: promptbook.description,
1458
+ promptExecutions: [],
1459
+ };
1460
+ _d.label = 1;
1461
+ case 1:
1462
+ _d.trys.push([1, 6, , 7]);
1463
+ resovedParameters_1 = promptbook.parameters
1464
+ .filter(function (_a) {
1465
+ var isInput = _a.isInput;
1466
+ return isInput;
1467
+ })
1468
+ .map(function (_a) {
1469
+ var name = _a.name;
1470
+ return name;
1471
+ });
1472
+ unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1473
+ resolving_1 = [];
1474
+ loopLimit = LOOP_LIMIT;
1475
+ _loop_1 = function () {
1476
+ var currentTemplate, work_1;
1477
+ return __generator(this, function (_e) {
1478
+ switch (_e.label) {
1479
+ case 0:
1480
+ if (loopLimit-- < 0) {
1481
+ throw new UnexpectedError('Loop limit reached during resolving parameters promptbook execution');
1482
+ }
1483
+ currentTemplate = unresovedTemplates.find(function (template) {
1484
+ return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
1485
+ });
1486
+ if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
1487
+ throw new UnexpectedError(spaceTrim$1("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbook\n "));
1488
+ case 1:
1489
+ if (!!currentTemplate) return [3 /*break*/, 3];
1490
+ /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
1491
+ case 2:
1492
+ /* [5] */ _e.sent();
1493
+ return [3 /*break*/, 4];
1494
+ case 3:
1495
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return template !== currentTemplate; });
1496
+ work_1 = executeSingleTemplate(currentTemplate)
1497
+ .then(function () {
1498
+ resovedParameters_1 = __spreadArray(__spreadArray([], __read(resovedParameters_1), false), [currentTemplate.resultingParameterName], false);
1499
+ })
1500
+ .then(function () {
1501
+ resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
1502
+ });
1503
+ resolving_1.push(work_1);
1504
+ _e.label = 4;
1505
+ case 4: return [2 /*return*/];
1506
+ }
1507
+ });
1508
+ };
1509
+ _d.label = 2;
1510
+ case 2:
1511
+ if (!(unresovedTemplates.length > 0)) return [3 /*break*/, 4];
1512
+ return [5 /*yield**/, _loop_1()];
1513
+ case 3:
1514
+ _d.sent();
1515
+ return [3 /*break*/, 2];
1516
+ case 4: return [4 /*yield*/, Promise.all(resolving_1)];
1517
+ case 5:
1518
+ _d.sent();
1519
+ return [3 /*break*/, 7];
1520
+ case 6:
1521
+ error_1 = _d.sent();
1522
+ if (!(error_1 instanceof Error)) {
1523
+ throw error_1;
1524
+ }
1525
+ usage_1 = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1526
+ var result = _a.result;
1527
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1528
+ })), false));
1529
+ return [2 /*return*/, {
1530
+ isSuccessful: false,
1531
+ errors: [error_1],
1532
+ usage: usage_1,
1533
+ executionReport: executionReport,
1534
+ outputParameters: parametersToPass,
1535
+ }];
1536
+ case 7:
1537
+ try {
1538
+ // Note: Filter ONLY output parameters
1539
+ for (_a = __values(promptbook.parameters), _b = _a.next(); !_b.done; _b = _a.next()) {
1540
+ parameter = _b.value;
1541
+ if (parameter.isOutput) {
1542
+ continue;
1543
+ }
1544
+ delete parametersToPass[parameter.name];
1545
+ }
1546
+ }
1547
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1548
+ finally {
1549
+ try {
1550
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1551
+ }
1552
+ finally { if (e_1) throw e_1.error; }
1553
+ }
1554
+ usage = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1555
+ var result = _a.result;
1556
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1557
+ })), false));
1558
+ return [2 /*return*/, {
1559
+ isSuccessful: true,
1560
+ errors: [],
1561
+ usage: usage,
1562
+ executionReport: executionReport,
1563
+ outputParameters: parametersToPass,
1564
+ }];
1565
+ }
1566
+ });
1567
+ }); };
1568
+ return promptbookExecutor;
1569
+ }
1570
+ /**
1571
+ * TODO: [🧠] When not meet expectations in PROMPT_DIALOG, make some way to tell the user
1572
+ * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
1573
+ * Note: CreatePromptbookExecutorOptions are just connected to PromptbookExecutor so do not extract to types folder
1574
+ * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
1575
+ */
1576
+
1577
+ /**
1578
+ * Prettify the html code
1579
+ *
1580
+ * @param content raw html code
1581
+ * @returns formatted html code
1582
+ */
1583
+ function prettifyMarkdown(content) {
1584
+ try {
1585
+ return format(content, {
1586
+ parser: 'markdown',
1587
+ plugins: [parserHtml],
1588
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1589
+ endOfLine: 'lf',
1590
+ tabWidth: 4,
1591
+ singleQuote: true,
1592
+ trailingComma: 'all',
1593
+ arrowParens: 'always',
1594
+ printWidth: 120,
1595
+ htmlWhitespaceSensitivity: 'ignore',
1596
+ jsxBracketSameLine: false,
1597
+ bracketSpacing: true,
1598
+ });
1599
+ }
1600
+ catch (error) {
1601
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1602
+ error: error,
1603
+ html: content,
1604
+ });
1605
+ return content;
1606
+ }
1607
+ }
1608
+
1609
+ /**
1610
+ * Makes first letter of a string uppercase
1611
+ *
1612
+ */
1613
+ function capitalize(word) {
1614
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
1615
+ }
1616
+
1617
+ /**
1618
+ * Converts promptbook in JSON format to string format
1619
+ *
1620
+ * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1621
+ * @returns Promptbook in string format (.ptbk.md)
1622
+ */
1623
+ function promptbookJsonToString(promptbookJson) {
1624
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1625
+ var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1626
+ var promptbookString = "# ".concat(title);
1627
+ if (description) {
1628
+ promptbookString += '\n\n';
1629
+ promptbookString += description;
1630
+ }
1631
+ // TODO:> const commands: Array<Command>
1632
+ var commands = [];
1633
+ if (promptbookUrl) {
1634
+ commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1635
+ }
1636
+ commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1637
+ promptbookString = prettifyMarkdown(promptbookString);
1638
+ try {
1639
+ for (var _g = __values(parameters.filter(function (_a) {
1640
+ var isInput = _a.isInput;
1641
+ return isInput;
1642
+ })), _h = _g.next(); !_h.done; _h = _g.next()) {
1643
+ var parameter = _h.value;
1644
+ commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1645
+ }
1646
+ }
1647
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1648
+ finally {
1649
+ try {
1650
+ if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1651
+ }
1652
+ finally { if (e_1) throw e_1.error; }
1653
+ }
1654
+ try {
1655
+ for (var _j = __values(parameters.filter(function (_a) {
1656
+ var isOutput = _a.isOutput;
1657
+ return isOutput;
1658
+ })), _k = _j.next(); !_k.done; _k = _j.next()) {
1659
+ var parameter = _k.value;
1660
+ commands.push("OUTPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1661
+ }
1662
+ }
1663
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1664
+ finally {
1665
+ try {
1666
+ if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
1667
+ }
1668
+ finally { if (e_2) throw e_2.error; }
1669
+ }
1670
+ promptbookString += '\n\n';
1671
+ promptbookString += commands.map(function (command) { return "- ".concat(command); }).join('\n');
1672
+ try {
1673
+ for (var promptTemplates_1 = __values(promptTemplates), promptTemplates_1_1 = promptTemplates_1.next(); !promptTemplates_1_1.done; promptTemplates_1_1 = promptTemplates_1.next()) {
1674
+ var promptTemplate = promptTemplates_1_1.value;
1675
+ var
1676
+ /* Note: Not using:> name, */
1677
+ title_1 = promptTemplate.title, description_1 = promptTemplate.description,
1678
+ /* Note: dependentParameterNames, */
1679
+ jokers = promptTemplate.jokers, executionType = promptTemplate.executionType, content = promptTemplate.content, postprocessing = promptTemplate.postprocessing, expectations = promptTemplate.expectations, expectFormat = promptTemplate.expectFormat, resultingParameterName = promptTemplate.resultingParameterName;
1680
+ promptbookString += '\n\n';
1681
+ promptbookString += "## ".concat(title_1);
1682
+ if (description_1) {
1683
+ promptbookString += '\n\n';
1684
+ promptbookString += description_1;
1685
+ }
1686
+ // TODO:> const commands: Array<Command>
1687
+ var commands_1 = [];
1688
+ var contentLanguage = 'text';
1689
+ if (executionType === 'PROMPT_TEMPLATE') {
1690
+ var modelRequirements = promptTemplate.modelRequirements;
1691
+ var modelName = modelRequirements.modelName, modelVariant = modelRequirements.modelVariant;
1692
+ commands_1.push("EXECUTE PROMPT TEMPLATE");
1693
+ if (modelVariant) {
1694
+ commands_1.push("MODEL VARIANT ".concat(capitalize(modelVariant)));
1695
+ }
1696
+ if (modelName) {
1697
+ commands_1.push("MODEL NAME `".concat(modelName, "`"));
1698
+ }
1699
+ }
1700
+ else if (executionType === 'SIMPLE_TEMPLATE') {
1701
+ commands_1.push("SIMPLE TEMPLATE");
1702
+ // Note: Nothing special here
1703
+ }
1704
+ else if (executionType === 'SCRIPT') {
1705
+ commands_1.push("EXECUTE SCRIPT");
1706
+ if (promptTemplate.contentLanguage) {
1707
+ contentLanguage = promptTemplate.contentLanguage;
1708
+ }
1709
+ else {
1710
+ contentLanguage = '';
1711
+ }
1712
+ }
1713
+ else if (executionType === 'PROMPT_DIALOG') {
1714
+ commands_1.push("PROMPT DIALOG");
1715
+ // Note: Nothing special here
1716
+ }
1717
+ if (jokers) {
1718
+ try {
1719
+ for (var jokers_1 = (e_4 = void 0, __values(jokers)), jokers_1_1 = jokers_1.next(); !jokers_1_1.done; jokers_1_1 = jokers_1.next()) {
1720
+ var joker = jokers_1_1.value;
1721
+ commands_1.push("JOKER {".concat(joker, "}"));
1722
+ }
1723
+ }
1724
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1725
+ finally {
1726
+ try {
1727
+ if (jokers_1_1 && !jokers_1_1.done && (_d = jokers_1.return)) _d.call(jokers_1);
1728
+ }
1729
+ finally { if (e_4) throw e_4.error; }
1730
+ }
1731
+ } /* not else */
1732
+ if (postprocessing) {
1733
+ try {
1734
+ for (var postprocessing_1 = (e_5 = void 0, __values(postprocessing)), postprocessing_1_1 = postprocessing_1.next(); !postprocessing_1_1.done; postprocessing_1_1 = postprocessing_1.next()) {
1735
+ var postprocessingFunctionName = postprocessing_1_1.value;
1736
+ commands_1.push("POSTPROCESSING `".concat(postprocessingFunctionName, "`"));
1737
+ }
1738
+ }
1739
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
1740
+ finally {
1741
+ try {
1742
+ if (postprocessing_1_1 && !postprocessing_1_1.done && (_e = postprocessing_1.return)) _e.call(postprocessing_1);
1743
+ }
1744
+ finally { if (e_5) throw e_5.error; }
1745
+ }
1746
+ } /* not else */
1747
+ if (expectations) {
1748
+ try {
1749
+ for (var _l = (e_6 = void 0, __values(Object.entries(expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1750
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1751
+ if (min === max) {
1752
+ commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1753
+ }
1754
+ else {
1755
+ if (min !== undefined) {
1756
+ commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1757
+ } /* not else */
1758
+ if (max !== undefined) {
1759
+ commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
1760
+ }
1761
+ }
1762
+ }
1763
+ }
1764
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
1765
+ finally {
1766
+ try {
1767
+ if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
1768
+ }
1769
+ finally { if (e_6) throw e_6.error; }
1770
+ }
1771
+ } /* not else */
1772
+ if (expectFormat) {
1773
+ if (expectFormat === 'JSON') {
1774
+ // TODO: @deprecated remove
1775
+ commands_1.push("EXPECT JSON");
1776
+ }
1777
+ } /* not else */
1778
+ promptbookString += '\n\n';
1779
+ promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
1780
+ promptbookString += '\n\n';
1781
+ promptbookString += '```' + contentLanguage;
1782
+ promptbookString += '\n';
1783
+ promptbookString += spaceTrim(content);
1784
+ // <- TODO: !!! Escape
1785
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1786
+ promptbookString += '\n';
1787
+ promptbookString += '```';
1788
+ promptbookString += '\n\n';
1789
+ promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
1790
+ }
1791
+ }
1792
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1793
+ finally {
1794
+ try {
1795
+ if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
1796
+ }
1797
+ finally { if (e_3) throw e_3.error; }
1798
+ }
1799
+ return promptbookString;
1800
+ }
1801
+ /**
1802
+ * @private internal util of promptbookJsonToString
1803
+ */
1804
+ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
1805
+ var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
1806
+ var parameterString = "{".concat(name, "}");
1807
+ if (description) {
1808
+ parameterString = "".concat(parameterString, " ").concat(description);
1809
+ }
1810
+ return parameterString;
1811
+ }
1812
+ /**
1813
+ * TODO: Escape all
1814
+ */
1815
+
1816
+ /**
1817
+ * This error indicates that promptbook not found in the library
1818
+ */
1819
+ var PromptbookNotFoundError = /** @class */ (function (_super) {
1820
+ __extends(PromptbookNotFoundError, _super);
1821
+ function PromptbookNotFoundError(message) {
1822
+ var _this = _super.call(this, message) || this;
1823
+ _this.name = 'PromptbookNotFoundError';
1824
+ Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
1825
+ return _this;
1826
+ }
1827
+ return PromptbookNotFoundError;
1828
+ }(Error));
1829
+
1830
+ /**
1831
+ * This error indicates errors in referencing promptbooks between each other
1832
+ */
1833
+ var PromptbookReferenceError = /** @class */ (function (_super) {
1834
+ __extends(PromptbookReferenceError, _super);
1835
+ function PromptbookReferenceError(message) {
1836
+ var _this = _super.call(this, message) || this;
1837
+ _this.name = 'PromptbookReferenceError';
1838
+ Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
1839
+ return _this;
1840
+ }
1841
+ return PromptbookReferenceError;
1842
+ }(Error));
1843
+
1844
+ /**
1845
+ * Library of promptbooks that groups together promptbooks for an application.
1846
+ * This implementation is a very thin wrapper around the Array / Map of promptbooks.
1847
+ *
1848
+ * @private use `createLibraryFromJson` instead
1849
+ * @see https://github.com/webgptorg/promptbook#promptbook-library
1850
+ */
1851
+ var SimplePromptbookLibrary = /** @class */ (function () {
1852
+ /**
1853
+ * Constructs a promptbook library from promptbooks
1854
+ *
1855
+ * @param promptbooks !!!
1856
+ *
1857
+ * @private Use instead `createLibraryFromJson`
1858
+ * Note: During the construction logic of all promptbooks are validated
1859
+ * Note: It is not recommended to use this constructor directly, use `createLibraryFromJson` *(or other variant)* instead
1860
+ */
1861
+ function SimplePromptbookLibrary() {
1862
+ var e_1, _a;
1863
+ var promptbooks = [];
1864
+ for (var _i = 0; _i < arguments.length; _i++) {
1865
+ promptbooks[_i] = arguments[_i];
1866
+ }
1867
+ this.library = new Map();
1868
+ try {
1869
+ for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
1870
+ var promptbook = promptbooks_1_1.value;
1871
+ if (promptbook.promptbookUrl === undefined) {
1872
+ throw new PromptbookReferenceError(spaceTrim$1("\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 ")));
1873
+ }
1874
+ validatePromptbook(promptbook);
1875
+ // Note: [🦄]
1876
+ if (this.library.has(promptbook.promptbookUrl) &&
1877
+ promptbookJsonToString(promptbook) !==
1878
+ promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
1879
+ throw new PromptbookReferenceError(spaceTrim$1("\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 ")));
1880
+ }
1881
+ this.library.set(promptbook.promptbookUrl, promptbook);
1882
+ }
1883
+ }
1884
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1885
+ finally {
1886
+ try {
1887
+ if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
1888
+ }
1889
+ finally { if (e_1) throw e_1.error; }
1890
+ }
1891
+ }
1892
+ /**
1893
+ * Gets all promptbooks in the library
1894
+ */
1895
+ SimplePromptbookLibrary.prototype.listPromptbooks = function () {
1896
+ return Array.from(this.library.keys());
1897
+ };
1898
+ /**
1899
+ * Gets promptbook by its URL
1900
+ *
1901
+ * Note: This is not a direct fetching from the URL, but a lookup in the library
1902
+ */
1903
+ SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
1904
+ var _this = this;
1905
+ var promptbook = this.library.get(url);
1906
+ if (!promptbook) {
1907
+ if (this.listPromptbooks().length === 0) {
1908
+ throw new PromptbookNotFoundError(spaceTrim$1("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
1909
+ }
1910
+ throw new PromptbookNotFoundError(spaceTrim$1(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
1911
+ .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
1912
+ .join('\n')), "\n\n "); }));
1913
+ }
1914
+ return promptbook;
1915
+ };
1916
+ /**
1917
+ * Checks whether given prompt was defined in any promptbook in the library
1918
+ */
1919
+ SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
1920
+ return true;
1921
+ };
1922
+ return SimplePromptbookLibrary;
1923
+ }());
1924
+
1925
+ /**
1926
+ * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
1927
+ *
1928
+ * Note: Functions `libraryToJson` and `createLibraryFromJson` are complementary
1929
+ * Note: During the construction syntax and logic of all sources are validated
1930
+ *
1931
+ * @param promptbookSources
1932
+ * @returns PromptbookLibrary
1933
+ */
1934
+ function createLibraryFromJson() {
1935
+ var promptbooks = [];
1936
+ for (var _i = 0; _i < arguments.length; _i++) {
1937
+ promptbooks[_i] = arguments[_i];
1938
+ }
1939
+ return new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))();
1940
+ }
1941
+
1942
+ /* tslint:disable */
1943
+ function normalizeToKebabCase(sentence) {
660
1944
  var e_1, _a;
1945
+ sentence = removeDiacritics(sentence);
661
1946
  var charType;
662
1947
  var lastCharType = 'OTHER';
663
1948
  var normalizedName = '';
@@ -667,11 +1952,11 @@ function normalizeTo_SCREAMING_CASE(sentence) {
667
1952
  var normalizedChar = void 0;
668
1953
  if (/^[a-z]$/.test(char)) {
669
1954
  charType = 'LOWERCASE';
670
- normalizedChar = char.toUpperCase();
1955
+ normalizedChar = char;
671
1956
  }
672
1957
  else if (/^[A-Z]$/.test(char)) {
673
1958
  charType = 'UPPERCASE';
674
- normalizedChar = char;
1959
+ normalizedChar = char.toLowerCase();
675
1960
  }
676
1961
  else if (/^[0-9]$/.test(char)) {
677
1962
  charType = 'NUMBER';
@@ -683,13 +1968,13 @@ function normalizeTo_SCREAMING_CASE(sentence) {
683
1968
  }
684
1969
  else {
685
1970
  charType = 'OTHER';
686
- normalizedChar = '_';
1971
+ normalizedChar = '-';
687
1972
  }
688
1973
  if (charType !== lastCharType &&
689
1974
  !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
690
1975
  !(lastCharType === 'NUMBER') &&
691
1976
  !(charType === 'NUMBER')) {
692
- normalizedName += '_';
1977
+ normalizedName += '-';
693
1978
  }
694
1979
  normalizedName += normalizedChar;
695
1980
  lastCharType = charType;
@@ -702,673 +1987,930 @@ function normalizeTo_SCREAMING_CASE(sentence) {
702
1987
  }
703
1988
  finally { if (e_1) throw e_1.error; }
704
1989
  }
705
- normalizedName = normalizedName.replace(/_+/g, '_');
706
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
707
- normalizedName = normalizedName.replace(/^_/, '');
708
- normalizedName = normalizedName.replace(/_$/, '');
1990
+ normalizedName = normalizedName.split(/-+/g).join('-');
1991
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1992
+ normalizedName = normalizedName.replace(/^-/, '');
1993
+ normalizedName = normalizedName.replace(/-$/, '');
709
1994
  return normalizedName;
710
1995
  }
1996
+
1997
+ function prepareKnowledgeFromMarkdown(options) {
1998
+ return __awaiter(this, void 0, void 0, function () {
1999
+ var content, llmTools, _a, isVerbose, library, prepareKnowledgeFromMarkdownPromptbook, prepareKnowledgeFromMarkdownExecutor, prepareKeywordsPromptbook, prepareKeywordsExecutor, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
2000
+ var _this = this;
2001
+ return __generator(this, function (_b) {
2002
+ switch (_b.label) {
2003
+ case 0:
2004
+ content = options.content, llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
2005
+ library = createLibraryFromJson.apply(void 0, __spreadArray([], __read(promptbookLibrary), false));
2006
+ return [4 /*yield*/, library.getPromptbookByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
2007
+ case 1:
2008
+ prepareKnowledgeFromMarkdownPromptbook = _b.sent();
2009
+ prepareKnowledgeFromMarkdownExecutor = createPromptbookExecutor({
2010
+ promptbook: prepareKnowledgeFromMarkdownPromptbook,
2011
+ tools: {
2012
+ llm: llmTools,
2013
+ script: [
2014
+ /* <- TODO: Allow to just keep script undefined */
2015
+ ],
2016
+ },
2017
+ });
2018
+ return [4 /*yield*/, library.getPromptbookByUrl('https://promptbook.studio/promptbook/prepare-keywords.ptbk.md')];
2019
+ case 2:
2020
+ prepareKeywordsPromptbook = _b.sent();
2021
+ prepareKeywordsExecutor = createPromptbookExecutor({
2022
+ promptbook: prepareKeywordsPromptbook,
2023
+ tools: {
2024
+ llm: llmTools,
2025
+ script: [
2026
+ /* <- TODO: Allow to just keep script undefined */
2027
+ ],
2028
+ },
2029
+ });
2030
+ return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ content: content })];
2031
+ case 3:
2032
+ result = _b.sent();
2033
+ assertsExecutionSuccessful(result);
2034
+ outputParameters = result.outputParameters;
2035
+ knowledgeRaw = outputParameters.knowledge;
2036
+ knowledgeTextPieces = (knowledgeRaw || '').split('\n---\n');
2037
+ if (isVerbose) {
2038
+ console.info('knowledgeTextPieces:', knowledgeTextPieces);
2039
+ }
2040
+ return [4 /*yield*/, Promise.all(knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
2041
+ var name, title, content, keywords, index, sources, result_1, _a, outputParameters_1, keywordsRaw, error_1;
2042
+ return __generator(this, function (_b) {
2043
+ switch (_b.label) {
2044
+ case 0:
2045
+ name = "piece-".concat(i);
2046
+ title = spaceTrim(knowledgeTextPiece.substring(0, 100));
2047
+ content = spaceTrim(knowledgeTextPiece);
2048
+ keywords = [];
2049
+ index = [];
2050
+ sources = [];
2051
+ _b.label = 1;
2052
+ case 1:
2053
+ _b.trys.push([1, 3, , 4]);
2054
+ // TODO: !!!! Summarize name and title from the content
2055
+ title = spaceTrim(knowledgeTextPiece.substring(0, 30));
2056
+ name = normalizeToKebabCase(title);
2057
+ return [4 /*yield*/, prepareKeywordsExecutor({ content: content })];
2058
+ case 2:
2059
+ result_1 = _b.sent();
2060
+ _a = result_1.outputParameters, outputParameters_1 = _a === void 0 ? {} : _a;
2061
+ keywordsRaw = outputParameters_1.keywords;
2062
+ keywords = (keywordsRaw || '')
2063
+ .split(',')
2064
+ .map(function (keyword) { return keyword.trim(); })
2065
+ .filter(function (keyword) { return keyword !== ''; });
2066
+ if (isVerbose) {
2067
+ console.info("Keywords for \"".concat(title, "\":"), keywords);
2068
+ }
2069
+ // ---
2070
+ // TODO: !!!! Index through LLM model
2071
+ index.push({
2072
+ modelName: 'fake-model',
2073
+ position: new Array(25).fill(0).map(function () { return Math.random() * 2 - 1; }),
2074
+ });
2075
+ return [3 /*break*/, 4];
2076
+ case 3:
2077
+ error_1 = _b.sent();
2078
+ console.error(error_1);
2079
+ return [3 /*break*/, 4];
2080
+ case 4: return [2 /*return*/, {
2081
+ name: name,
2082
+ title: title,
2083
+ content: content,
2084
+ keywords: keywords,
2085
+ index: index,
2086
+ sources: sources,
2087
+ }];
2088
+ }
2089
+ });
2090
+ }); }))];
2091
+ case 4:
2092
+ knowledge = _b.sent();
2093
+ return [2 /*return*/, knowledge];
2094
+ }
2095
+ });
2096
+ });
2097
+ }
2098
+
711
2099
  /**
712
- * TODO: [🌺] Use some intermediate util splitWords
2100
+ * Supported script languages
713
2101
  */
2102
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
714
2103
 
715
2104
  /**
716
- * Execution type describes the way how the block is executed
2105
+ * Computes the deepness of the markdown structure.
717
2106
  *
718
- * @see https://github.com/webgptorg/promptbook#execution-type
2107
+ * @private within the library
719
2108
  */
720
- var ExecutionTypes = [
721
- 'PROMPT_TEMPLATE',
722
- 'SIMPLE_TEMPLATE',
723
- 'SCRIPT',
724
- 'PROMPT_DIALOG',
725
- // <- [🥻] Insert here when making new command
726
- ];
2109
+ function countMarkdownStructureDeepness(markdownStructure) {
2110
+ var e_1, _a;
2111
+ var maxDeepness = 0;
2112
+ try {
2113
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
2114
+ var section = _c.value;
2115
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
2116
+ }
2117
+ }
2118
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2119
+ finally {
2120
+ try {
2121
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2122
+ }
2123
+ finally { if (e_1) throw e_1.error; }
2124
+ }
2125
+ return maxDeepness + 1;
2126
+ }
727
2127
 
728
2128
  /**
729
- * Units of text measurement
2129
+ * Parse a markdown string into a MarkdownStructure object.
2130
+ *
2131
+ * Note: This function does work with code blocks
2132
+ * Note: This function does not work with markdown comments
2133
+ *
2134
+ * @param markdown The markdown string to parse.
2135
+ * @returns The MarkdownStructure object.
2136
+ *
2137
+ * @private within the library
730
2138
  */
731
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2139
+ function markdownToMarkdownStructure(markdown) {
2140
+ var e_1, _a;
2141
+ var lines = markdown.split('\n');
2142
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
2143
+ var current = root;
2144
+ var isInsideCodeBlock = false;
2145
+ try {
2146
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2147
+ var line = lines_1_1.value;
2148
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
2149
+ if (isInsideCodeBlock || !headingMatch) {
2150
+ if (line.startsWith('```')) {
2151
+ isInsideCodeBlock = !isInsideCodeBlock;
2152
+ }
2153
+ current.contentLines.push(line);
2154
+ }
2155
+ else {
2156
+ var level = headingMatch.groups.mark.length;
2157
+ var title = headingMatch.groups.title.trim();
2158
+ var parent_1 = void 0;
2159
+ if (level > current.level) {
2160
+ // Note: Going deeper (next section is child of current)
2161
+ parent_1 = current;
2162
+ }
2163
+ else {
2164
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
2165
+ parent_1 = current;
2166
+ var loopLimit = LOOP_LIMIT;
2167
+ while (parent_1.level !== level - 1) {
2168
+ if (loopLimit-- < 0) {
2169
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
2170
+ }
2171
+ if (parent_1.parent === null /* <- Note: We are in root */) {
2172
+ // [🌻]
2173
+ throw new Error(spaceTrim$1("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
2174
+ }
2175
+ parent_1 = parent_1.parent;
2176
+ }
2177
+ }
2178
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
2179
+ parent_1.sections.push(section);
2180
+ current = section;
2181
+ }
2182
+ }
2183
+ }
2184
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2185
+ finally {
2186
+ try {
2187
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2188
+ }
2189
+ finally { if (e_1) throw e_1.error; }
2190
+ }
2191
+ if (root.sections.length === 1) {
2192
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
2193
+ return markdownStructure;
2194
+ }
2195
+ // [🌻]
2196
+ throw new Error('The markdown file must have exactly one top-level section.');
2197
+ // return root;
2198
+ }
732
2199
  /**
733
- * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
734
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
735
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
2200
+ * @private
736
2201
  */
2202
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
2203
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
2204
+ return {
2205
+ level: level,
2206
+ title: title,
2207
+ content: spaceTrim$1(contentLines.join('\n')),
2208
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
2209
+ };
2210
+ }
737
2211
 
738
2212
  /**
739
- * Removes Markdown formatting tags from a string.
2213
+ * Utility function to extract all list items from markdown
740
2214
  *
741
- * @param {string} str - The string to remove Markdown tags from.
742
- * @returns {string} The input string with all Markdown tags removed.
2215
+ * Note: It works with both ul and ol
2216
+ * Note: It omits list items in code blocks
2217
+ * Note: It flattens nested lists
2218
+ * Note: It can not work with html syntax and comments
2219
+ *
2220
+ * @param markdown any valid markdown
2221
+ * @returns
743
2222
  */
744
- function removeMarkdownFormatting(str) {
745
- // Remove bold formatting
746
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
747
- // Remove italic formatting
748
- str = str.replace(/\*(.*?)\*/g, '$1');
749
- // Remove code formatting
750
- str = str.replace(/`(.*?)`/g, '$1');
751
- return str;
2223
+ function extractAllListItemsFromMarkdown(markdown) {
2224
+ var e_1, _a;
2225
+ var lines = markdown.split('\n');
2226
+ var listItems = [];
2227
+ var isInCodeBlock = false;
2228
+ try {
2229
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2230
+ var line = lines_1_1.value;
2231
+ var trimmedLine = line.trim();
2232
+ if (trimmedLine.startsWith('```')) {
2233
+ isInCodeBlock = !isInCodeBlock;
2234
+ }
2235
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
2236
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
2237
+ listItems.push(listItem);
2238
+ }
2239
+ }
2240
+ }
2241
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2242
+ finally {
2243
+ try {
2244
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2245
+ }
2246
+ finally { if (e_1) throw e_1.error; }
2247
+ }
2248
+ return listItems;
752
2249
  }
753
2250
 
754
2251
  /**
755
- * Function parseNumber will parse number from string
2252
+ * Extracts all code blocks from markdown.
756
2253
  *
757
- * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
758
- * Note: it also works only with decimal numbers
2254
+ * Note: There are 3 simmilar function:
2255
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2256
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2257
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
759
2258
  *
760
- * @returns parsed number
761
- * @throws {PromptbookSyntaxError} if the value is not a number
2259
+ * @param markdown any valid markdown
2260
+ * @returns code blocks with language and content
762
2261
  *
763
- * @private within the parseCommand
764
2262
  */
765
- function parseNumber(value) {
766
- var originalValue = value;
767
- if (typeof value === 'number') {
768
- value = value.toString(); // <- TODO: Maybe more efficient way to do this
769
- }
770
- if (typeof value !== 'string') {
771
- return 0;
772
- }
773
- value = value.trim();
774
- if (value.startsWith('+')) {
775
- return parseNumber(value.substring(1));
776
- }
777
- if (value.startsWith('-')) {
778
- var number = parseNumber(value.substring(1));
779
- if (number === 0) {
780
- return 0; // <- Note: To prevent -0
2263
+ function extractAllBlocksFromMarkdown(markdown) {
2264
+ var e_1, _a;
2265
+ var codeBlocks = [];
2266
+ var lines = markdown.split('\n');
2267
+ var currentCodeBlock = null;
2268
+ try {
2269
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2270
+ var line = lines_1_1.value;
2271
+ if (line.startsWith('```')) {
2272
+ var language = line.slice(3).trim() || null;
2273
+ if (currentCodeBlock === null) {
2274
+ currentCodeBlock = { language: language, content: '' };
2275
+ }
2276
+ else {
2277
+ if (language !== null) {
2278
+ // [🌻]
2279
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2280
+ }
2281
+ codeBlocks.push(currentCodeBlock);
2282
+ currentCodeBlock = null;
2283
+ }
2284
+ }
2285
+ else if (currentCodeBlock !== null) {
2286
+ if (currentCodeBlock.content !== '') {
2287
+ currentCodeBlock.content += '\n';
2288
+ }
2289
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2290
+ }
781
2291
  }
782
- return -number;
783
- }
784
- value = value.replace(/,/g, '.');
785
- value = value.toUpperCase();
786
- if (value === '') {
787
- return 0;
788
- }
789
- if (value === '♾' || value.startsWith('INF')) {
790
- return Infinity;
791
2292
  }
792
- if (value.includes('/')) {
793
- var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
794
- var numerator = parseNumber(numerator_);
795
- var denominator = parseNumber(denominator_);
796
- if (denominator === 0) {
797
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
2293
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2294
+ finally {
2295
+ try {
2296
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
798
2297
  }
799
- return numerator / denominator;
800
- }
801
- if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
802
- return 0;
803
- }
804
- if (value.includes('E')) {
805
- var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
806
- return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
807
- }
808
- if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
809
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
2298
+ finally { if (e_1) throw e_1.error; }
810
2299
  }
811
- var num = parseFloat(value);
812
- if (isNaN(num)) {
813
- throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
2300
+ if (currentCodeBlock !== null) {
2301
+ // [🌻]
2302
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
814
2303
  }
815
- return num;
2304
+ return codeBlocks;
816
2305
  }
817
- /**
818
- * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
819
- */
820
2306
 
821
2307
  /**
822
- * Parses one line of ul/ol to command
2308
+ * Extracts exactly ONE code block from markdown.
823
2309
  *
824
- * @returns parsed command object
825
- * @throws {PromptbookSyntaxError} if the command is invalid
2310
+ * Note: If there are multiple or no code blocks the function throws an error
826
2311
  *
827
- * @private within the promptbookStringToJson
2312
+ * Note: There are 3 simmilar function:
2313
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2314
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2315
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2316
+ *
2317
+ * @param markdown any valid markdown
2318
+ * @returns code block with language and content
828
2319
  */
829
- function parseCommand(listItem) {
830
- var e_1, _a;
831
- if (listItem.includes('\n') || listItem.includes('\r')) {
832
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
833
- }
834
- var type = listItem.trim();
835
- type = type.split('`').join('');
836
- type = type.split('"').join('');
837
- type = type.split("'").join('');
838
- type = type.split('~').join('');
839
- type = type.split('[').join('');
840
- type = type.split(']').join('');
841
- type = type.split('(').join('');
842
- type = type.split(')').join('');
843
- type = normalizeTo_SCREAMING_CASE(type);
844
- type = type.split('DIALOGUE').join('DIALOG');
845
- var listItemParts = listItem
846
- .split(' ')
847
- .map(function (part) { return part.trim(); })
848
- .filter(function (item) { return item !== ''; })
849
- .filter(function (item) { return !/^PTBK$/i.test(item); })
850
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
851
- .map(removeMarkdownFormatting);
852
- if (type.startsWith('URL') ||
853
- type.startsWith('PTBK_URL') ||
854
- type.startsWith('PTBKURL') ||
855
- type.startsWith('PROMPTBOOK_URL') ||
856
- type.startsWith('PROMPTBOOKURL') ||
857
- type.startsWith('HTTPS')) {
858
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
859
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
860
- }
861
- var promptbookUrlString = listItemParts.pop();
862
- var promptbookUrl = new URL(promptbookUrlString);
863
- if (promptbookUrl.protocol !== 'https:') {
864
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
865
- }
866
- if (promptbookUrl.hash !== '') {
867
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
868
- }
869
- return {
870
- type: 'PROMPTBOOK_URL',
871
- promptbookUrl: promptbookUrl,
872
- };
873
- }
874
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
875
- if (listItemParts.length !== 2) {
876
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
877
- }
878
- var promptbookVersion = listItemParts.pop();
879
- // TODO: Validate version
880
- return {
881
- type: 'PROMPTBOOK_VERSION',
882
- promptbookVersion: promptbookVersion,
883
- };
2320
+ function extractOneBlockFromMarkdown(markdown) {
2321
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2322
+ if (codeBlocks.length !== 1) {
2323
+ // TODO: Report more specific place where the error happened
2324
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
884
2325
  }
885
- else if (type.startsWith('EXECUTE') ||
886
- type.startsWith('EXEC') ||
887
- type.startsWith('PROMPT_DIALOG') ||
888
- type.startsWith('SIMPLE_TEMPLATE')) {
889
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
890
- if (executionTypes.length !== 1) {
891
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
892
- }
893
- return {
894
- type: 'EXECUTE',
895
- executionType: executionTypes[0],
896
- };
2326
+ return codeBlocks[0];
2327
+ }
2328
+ /***
2329
+ * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
2330
+ */
2331
+
2332
+ /**
2333
+ * Removes HTML or Markdown comments from a string.
2334
+ *
2335
+ * @param {string} content - The string to remove comments from.
2336
+ * @returns {string} The input string with all comments removed.
2337
+ */
2338
+ function removeContentComments(content) {
2339
+ return spaceTrim$1(content.replace(/<!--(.*?)-->/gs, ''));
2340
+ }
2341
+
2342
+ /**
2343
+ * Creates a new set with all elements that are present in either set
2344
+ */
2345
+ function union() {
2346
+ var e_1, _a, e_2, _b;
2347
+ var sets = [];
2348
+ for (var _i = 0; _i < arguments.length; _i++) {
2349
+ sets[_i] = arguments[_i];
897
2350
  }
898
- else if (type.startsWith('MODEL')) {
899
- // TODO: Make this more elegant and dynamically
900
- if (type.startsWith('MODEL_VARIANT')) {
901
- if (type === 'MODEL_VARIANT_CHAT') {
902
- return {
903
- type: 'MODEL',
904
- key: 'modelVariant',
905
- value: 'CHAT',
906
- };
907
- }
908
- else if (type === 'MODEL_VARIANT_COMPLETION') {
909
- return {
910
- type: 'MODEL',
911
- key: 'modelVariant',
912
- value: 'COMPLETION',
913
- };
914
- }
915
- else {
916
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
2351
+ var union = new Set();
2352
+ try {
2353
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2354
+ var set = sets_1_1.value;
2355
+ try {
2356
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2357
+ var item = _d.value;
2358
+ union.add(item);
2359
+ }
2360
+ }
2361
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2362
+ finally {
2363
+ try {
2364
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2365
+ }
2366
+ finally { if (e_2) throw e_2.error; }
917
2367
  }
918
2368
  }
919
- if (type.startsWith('MODEL_NAME')) {
920
- return {
921
- type: 'MODEL',
922
- key: 'modelName',
923
- value: listItemParts.pop(),
924
- };
925
- }
926
- else {
927
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
928
- }
929
- }
930
- else if (type.startsWith('PARAM') ||
931
- type.startsWith('INPUT_PARAM') ||
932
- type.startsWith('OUTPUT_PARAM') ||
933
- listItem.startsWith('{') ||
934
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
935
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
936
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
937
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
938
- }
939
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
940
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
941
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
942
- throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
2369
+ }
2370
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2371
+ finally {
2372
+ try {
2373
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
943
2374
  }
944
- var isInput = type.startsWith('INPUT');
945
- var isOutput = type.startsWith('OUTPUT');
946
- if (listItem.startsWith('> {')) {
947
- isInput = false;
948
- isOutput = false;
2375
+ finally { if (e_1) throw e_1.error; }
2376
+ }
2377
+ return union;
2378
+ }
2379
+
2380
+ /**
2381
+ * Parses the template and returns the list of all parameter names
2382
+ *
2383
+ * @param template the template with parameters in {curly} braces
2384
+ * @returns the list of parameter names
2385
+ */
2386
+ function extractParameters(template) {
2387
+ var e_1, _a;
2388
+ var matches = template.matchAll(/{\w+}/g);
2389
+ var parameterNames = new Set();
2390
+ try {
2391
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
2392
+ var match = matches_1_1.value;
2393
+ var parameterName = match[0].slice(1, -1);
2394
+ parameterNames.add(parameterName);
949
2395
  }
950
- return {
951
- type: 'PARAMETER',
952
- parameterName: parameterName,
953
- parameterDescription: parameterDescription.trim() || null,
954
- isInput: isInput,
955
- isOutput: isOutput,
956
- };
957
2396
  }
958
- else if (type.startsWith('JOKER')) {
959
- if (listItemParts.length !== 2) {
960
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
2397
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2398
+ finally {
2399
+ try {
2400
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
961
2401
  }
962
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
963
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
964
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2402
+ finally { if (e_1) throw e_1.error; }
2403
+ }
2404
+ return parameterNames;
2405
+ }
2406
+
2407
+ /**
2408
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2409
+ *
2410
+ * @param script from which to extract the variables
2411
+ * @returns the list of variable names
2412
+ * @throws {PromptbookSyntaxError} if the script is invalid
2413
+ */
2414
+ function extractVariables(script) {
2415
+ var variables = new Set();
2416
+ script = "(()=>{".concat(script, "})()");
2417
+ try {
2418
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2419
+ try {
2420
+ eval(script);
2421
+ }
2422
+ catch (error) {
2423
+ if (!(error instanceof ReferenceError)) {
2424
+ throw error;
2425
+ }
2426
+ var undefinedName = error.message.split(' ')[0];
2427
+ /*
2428
+ Note: Remapping error
2429
+ From: [ReferenceError: thing is not defined],
2430
+ To: [Error: Parameter {thing} is not defined],
2431
+ */
2432
+ if (!undefinedName) {
2433
+ throw error;
2434
+ }
2435
+ if (script.includes(undefinedName + '(')) {
2436
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2437
+ }
2438
+ else {
2439
+ variables.add(undefinedName);
2440
+ script = "const ".concat(undefinedName, " = '';") + script;
2441
+ }
2442
+ }
2443
+ }
2444
+ catch (error) {
2445
+ if (!(error instanceof Error)) {
2446
+ throw error;
965
2447
  }
966
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
967
- var parameterName = parametersMatch.groups.parameterName;
968
- return {
969
- type: 'JOKER',
970
- parameterName: parameterName,
971
- };
2448
+ throw new PromptbookSyntaxError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
972
2449
  }
973
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
974
- if (listItemParts.length !== 2) {
975
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
2450
+ return variables;
2451
+ }
2452
+ /**
2453
+ * TODO: [🔣] Support for multiple languages - python, java,...
2454
+ */
2455
+
2456
+ /**
2457
+ * Parses the prompt template and returns the set of all used parameters
2458
+ *
2459
+ * @param promptTemplate the template with used parameters
2460
+ * @returns the set of parameter names
2461
+ * @throws {PromptbookSyntaxError} if the script is invalid
2462
+ */
2463
+ function extractParametersFromPromptTemplate(promptTemplate) {
2464
+ var e_1, _a, e_2, _b;
2465
+ var parameterNames = new Set();
2466
+ try {
2467
+ 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()) {
2468
+ var parameterName = _d.value;
2469
+ parameterNames.add(parameterName);
976
2470
  }
977
- var functionName = listItemParts.pop();
978
- return {
979
- type: 'POSTPROCESS',
980
- functionName: functionName,
981
- };
982
2471
  }
983
- else if (type.startsWith('EXPECT_JSON')) {
984
- return {
985
- type: 'EXPECT_FORMAT',
986
- format: 'JSON',
987
- };
988
- // [🥤]
2472
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2473
+ finally {
2474
+ try {
2475
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
2476
+ }
2477
+ finally { if (e_1) throw e_1.error; }
989
2478
  }
990
- else if (type.startsWith('EXPECT')) {
2479
+ if (promptTemplate.executionType === 'SCRIPT') {
991
2480
  try {
992
- listItemParts.shift();
993
- var sign = void 0;
994
- var signRaw = listItemParts.shift();
995
- if (/^exact/i.test(signRaw)) {
996
- sign = 'EXACTLY';
997
- }
998
- else if (/^min/i.test(signRaw)) {
999
- sign = 'MINIMUM';
1000
- }
1001
- else if (/^max/i.test(signRaw)) {
1002
- sign = 'MAXIMUM';
2481
+ for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
2482
+ var parameterName = _f.value;
2483
+ parameterNames.add(parameterName);
1003
2484
  }
1004
- else {
1005
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
2485
+ }
2486
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2487
+ finally {
2488
+ try {
2489
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1006
2490
  }
1007
- var amountRaw = listItemParts.shift();
1008
- var amount = parseNumber(amountRaw);
1009
- if (amount < 0) {
1010
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
2491
+ finally { if (e_2) throw e_2.error; }
2492
+ }
2493
+ }
2494
+ return parameterNames;
2495
+ }
2496
+ /**
2497
+ * TODO: [🔣] If script require contentLanguage
2498
+ */
2499
+
2500
+ /* tslint:disable */
2501
+ /*
2502
+ TODO: Tests
2503
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
2504
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
2505
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
2506
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
2507
+ */
2508
+ function normalizeTo_SCREAMING_CASE(sentence) {
2509
+ var e_1, _a;
2510
+ var charType;
2511
+ var lastCharType = 'OTHER';
2512
+ var normalizedName = '';
2513
+ try {
2514
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
2515
+ var char = sentence_1_1.value;
2516
+ var normalizedChar = void 0;
2517
+ if (/^[a-z]$/.test(char)) {
2518
+ charType = 'LOWERCASE';
2519
+ normalizedChar = char.toUpperCase();
1011
2520
  }
1012
- if (amount !== Math.floor(amount)) {
1013
- throw new PromptbookSyntaxError('Amount must be whole number');
2521
+ else if (/^[A-Z]$/.test(char)) {
2522
+ charType = 'UPPERCASE';
2523
+ normalizedChar = char;
1014
2524
  }
1015
- var unitRaw = listItemParts.shift();
1016
- var unit = undefined;
1017
- try {
1018
- 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()) {
1019
- var existingUnit = EXPECTATION_UNITS_1_1.value;
1020
- var existingUnitText = existingUnit;
1021
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
1022
- if (existingUnitText === 'CHARACTER') {
1023
- existingUnitText = 'CHAR';
1024
- }
1025
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
1026
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
1027
- if (unit !== undefined) {
1028
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
1029
- }
1030
- unit = existingUnit;
1031
- }
1032
- }
2525
+ else if (/^[0-9]$/.test(char)) {
2526
+ charType = 'NUMBER';
2527
+ normalizedChar = char;
1033
2528
  }
1034
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1035
- finally {
1036
- try {
1037
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
1038
- }
1039
- finally { if (e_1) throw e_1.error; }
2529
+ else if (/^\/$/.test(char)) {
2530
+ charType = 'SLASH';
2531
+ normalizedChar = char;
1040
2532
  }
1041
- if (unit === undefined) {
1042
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
2533
+ else {
2534
+ charType = 'OTHER';
2535
+ normalizedChar = '_';
1043
2536
  }
1044
- return {
1045
- type: 'EXPECT_AMOUNT',
1046
- sign: sign,
1047
- unit: unit,
1048
- amount: amount,
1049
- };
1050
- }
1051
- catch (error) {
1052
- if (!(error instanceof Error)) {
1053
- throw error;
2537
+ if (charType !== lastCharType &&
2538
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
2539
+ !(lastCharType === 'NUMBER') &&
2540
+ !(charType === 'NUMBER')) {
2541
+ normalizedName += '_';
1054
2542
  }
1055
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1056
- }
1057
- /*
1058
- } else if (type.startsWith('__________________')) {
1059
- // <- [🥻] Insert here when making new command
1060
- */
2543
+ normalizedName += normalizedChar;
2544
+ lastCharType = charType;
2545
+ }
1061
2546
  }
1062
- else {
1063
- throw new PromptbookSyntaxError(spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
2547
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2548
+ finally {
2549
+ try {
2550
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
2551
+ }
2552
+ finally { if (e_1) throw e_1.error; }
1064
2553
  }
2554
+ normalizedName = normalizedName.replace(/_+/g, '_');
2555
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
2556
+ normalizedName = normalizedName.replace(/^_/, '');
2557
+ normalizedName = normalizedName.replace(/_$/, '');
2558
+ return normalizedName;
1065
2559
  }
2560
+ /**
2561
+ * TODO: [🌺] Use some intermediate util splitWords
2562
+ */
1066
2563
 
1067
- var defaultDiacriticsRemovalMap = [
1068
- {
1069
- base: 'A',
1070
- letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F',
1071
- },
1072
- { base: 'AA', letters: '\uA732' },
1073
- { base: 'AE', letters: '\u00C6\u01FC\u01E2' },
1074
- { base: 'AO', letters: '\uA734' },
1075
- { base: 'AU', letters: '\uA736' },
1076
- { base: 'AV', letters: '\uA738\uA73A' },
1077
- { base: 'AY', letters: '\uA73C' },
1078
- {
1079
- base: 'B',
1080
- letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181',
1081
- },
1082
- {
1083
- base: 'C',
1084
- letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E',
1085
- },
1086
- {
1087
- base: 'D',
1088
- letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0',
1089
- },
1090
- { base: 'DZ', letters: '\u01F1\u01C4' },
1091
- { base: 'Dz', letters: '\u01F2\u01C5' },
1092
- {
1093
- base: 'E',
1094
- letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E',
1095
- },
1096
- { base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
1097
- {
1098
- base: 'G',
1099
- letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E',
1100
- },
1101
- {
1102
- base: 'H',
1103
- letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D',
1104
- },
1105
- {
1106
- base: 'I',
1107
- letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197',
1108
- },
1109
- { base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
1110
- {
1111
- base: 'K',
1112
- letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2',
1113
- },
1114
- {
1115
- base: 'L',
1116
- letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780',
1117
- },
1118
- { base: 'LJ', letters: '\u01C7' },
1119
- { base: 'Lj', letters: '\u01C8' },
1120
- { base: 'M', letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
1121
- {
1122
- base: 'N',
1123
- letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4',
1124
- },
1125
- { base: 'NJ', letters: '\u01CA' },
1126
- { base: 'Nj', letters: '\u01CB' },
1127
- {
1128
- base: 'O',
1129
- letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C',
1130
- },
1131
- { base: 'OI', letters: '\u01A2' },
1132
- { base: 'OO', letters: '\uA74E' },
1133
- { base: 'OU', letters: '\u0222' },
1134
- { base: 'OE', letters: '\u008C\u0152' },
1135
- { base: 'oe', letters: '\u009C\u0153' },
1136
- {
1137
- base: 'P',
1138
- letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754',
1139
- },
1140
- { base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
1141
- {
1142
- base: 'R',
1143
- letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782',
1144
- },
1145
- {
1146
- base: 'S',
1147
- letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784',
1148
- },
1149
- {
1150
- base: 'T',
1151
- letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786',
1152
- },
1153
- { base: 'TZ', letters: '\uA728' },
1154
- {
1155
- base: 'U',
1156
- letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244',
1157
- },
1158
- { base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
1159
- { base: 'VY', letters: '\uA760' },
1160
- {
1161
- base: 'W',
1162
- letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72',
1163
- },
1164
- { base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
1165
- {
1166
- base: 'Y',
1167
- letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE',
1168
- },
1169
- {
1170
- base: 'Z',
1171
- letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762',
1172
- },
1173
- {
1174
- base: 'a',
1175
- letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250',
1176
- },
1177
- { base: 'aa', letters: '\uA733' },
1178
- { base: 'ae', letters: '\u00E6\u01FD\u01E3' },
1179
- { base: 'ao', letters: '\uA735' },
1180
- { base: 'au', letters: '\uA737' },
1181
- { base: 'av', letters: '\uA739\uA73B' },
1182
- { base: 'ay', letters: '\uA73D' },
1183
- {
1184
- base: 'b',
1185
- letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253',
1186
- },
1187
- {
1188
- base: 'c',
1189
- letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184',
1190
- },
1191
- {
1192
- base: 'd',
1193
- letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A',
1194
- },
1195
- { base: 'dz', letters: '\u01F3\u01C6' },
1196
- {
1197
- base: 'e',
1198
- letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD',
1199
- },
1200
- { base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
1201
- {
1202
- base: 'g',
1203
- letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F',
1204
- },
1205
- {
1206
- base: 'h',
1207
- letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265',
1208
- },
1209
- { base: 'hv', letters: '\u0195' },
1210
- {
1211
- base: 'i',
1212
- letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131',
1213
- },
1214
- { base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
1215
- {
1216
- base: 'k',
1217
- letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3',
1218
- },
1219
- {
1220
- base: 'l',
1221
- letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747',
1222
- },
1223
- { base: 'lj', letters: '\u01C9' },
1224
- { base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
1225
- {
1226
- base: 'n',
1227
- letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5',
1228
- },
1229
- { base: 'nj', letters: '\u01CC' },
1230
- {
1231
- base: 'o',
1232
- letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275',
1233
- },
1234
- { base: 'oi', letters: '\u01A3' },
1235
- { base: 'ou', letters: '\u0223' },
1236
- { base: 'oo', letters: '\uA74F' },
1237
- {
1238
- base: 'p',
1239
- letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755',
1240
- },
1241
- { base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
1242
- {
1243
- base: 'r',
1244
- letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783',
1245
- },
1246
- {
1247
- base: 's',
1248
- letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B',
1249
- },
1250
- {
1251
- base: 't',
1252
- letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787',
1253
- },
1254
- { base: 'tz', letters: '\uA729' },
1255
- {
1256
- base: 'u',
1257
- letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289',
1258
- },
1259
- { base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
1260
- { base: 'vy', letters: '\uA761' },
1261
- {
1262
- base: 'w',
1263
- letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73',
1264
- },
1265
- { base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
1266
- {
1267
- base: 'y',
1268
- letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF',
1269
- },
1270
- {
1271
- base: 'z',
1272
- letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763',
1273
- },
2564
+ /**
2565
+ * Execution type describes the way how the block is executed
2566
+ *
2567
+ * @see https://github.com/webgptorg/promptbook#execution-type
2568
+ */
2569
+ var ExecutionTypes = [
2570
+ 'PROMPT_TEMPLATE',
2571
+ 'SIMPLE_TEMPLATE',
2572
+ 'SCRIPT',
2573
+ 'PROMPT_DIALOG',
2574
+ // <- [🥻] Insert here when making new command
1274
2575
  ];
2576
+
2577
+ /**
2578
+ * Units of text measurement
2579
+ */
2580
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2581
+ /**
2582
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
2583
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
2584
+ * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
2585
+ */
2586
+
2587
+ /**
2588
+ * Removes Markdown formatting tags from a string.
2589
+ *
2590
+ * @param {string} str - The string to remove Markdown tags from.
2591
+ * @returns {string} The input string with all Markdown tags removed.
2592
+ */
2593
+ function removeMarkdownFormatting(str) {
2594
+ // Remove bold formatting
2595
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
2596
+ // Remove italic formatting
2597
+ str = str.replace(/\*(.*?)\*/g, '$1');
2598
+ // Remove code formatting
2599
+ str = str.replace(/`(.*?)`/g, '$1');
2600
+ return str;
2601
+ }
2602
+
1275
2603
  /**
1276
- * Map of letters from diacritic variant to diacritless variant
1277
- * Contains lowercase and uppercase separatelly
2604
+ * Function parseNumber will parse number from string
1278
2605
  *
1279
- * > "á" => "a"
1280
- * > "ě" => "e"
1281
- * > "Ă" => "A"
1282
- * > ...
2606
+ * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
2607
+ * Note: it also works only with decimal numbers
2608
+ *
2609
+ * @returns parsed number
2610
+ * @throws {PromptbookSyntaxError} if the value is not a number
2611
+ *
2612
+ * @private within the parseCommand
1283
2613
  */
1284
- var DIACRITIC_VARIANTS_LETTERS = {};
1285
- // tslint:disable-next-line: prefer-for-of
1286
- for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
1287
- var letters = defaultDiacriticsRemovalMap[i].letters;
1288
- // tslint:disable-next-line: prefer-for-of
1289
- for (var j = 0; j < letters.length; j++) {
1290
- DIACRITIC_VARIANTS_LETTERS[letters[j]] = defaultDiacriticsRemovalMap[i].base;
2614
+ function parseNumber(value) {
2615
+ var originalValue = value;
2616
+ if (typeof value === 'number') {
2617
+ value = value.toString(); // <- TODO: Maybe more efficient way to do this
2618
+ }
2619
+ if (typeof value !== 'string') {
2620
+ return 0;
2621
+ }
2622
+ value = value.trim();
2623
+ if (value.startsWith('+')) {
2624
+ return parseNumber(value.substring(1));
2625
+ }
2626
+ if (value.startsWith('-')) {
2627
+ var number = parseNumber(value.substring(1));
2628
+ if (number === 0) {
2629
+ return 0; // <- Note: To prevent -0
2630
+ }
2631
+ return -number;
2632
+ }
2633
+ value = value.replace(/,/g, '.');
2634
+ value = value.toUpperCase();
2635
+ if (value === '') {
2636
+ return 0;
2637
+ }
2638
+ if (value === '♾' || value.startsWith('INF')) {
2639
+ return Infinity;
2640
+ }
2641
+ if (value.includes('/')) {
2642
+ var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
2643
+ var numerator = parseNumber(numerator_);
2644
+ var denominator = parseNumber(denominator_);
2645
+ if (denominator === 0) {
2646
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
2647
+ }
2648
+ return numerator / denominator;
2649
+ }
2650
+ if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
2651
+ return 0;
2652
+ }
2653
+ if (value.includes('E')) {
2654
+ var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
2655
+ return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
2656
+ }
2657
+ if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
2658
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
2659
+ }
2660
+ var num = parseFloat(value);
2661
+ if (isNaN(num)) {
2662
+ throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
1291
2663
  }
2664
+ return num;
1292
2665
  }
1293
- // <- TODO: [🍓] Put to maker function to save execution time if not needed
1294
- /*
1295
- @see https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
1296
- Licensed under the Apache License, Version 2.0 (the "License");
1297
- you may not use this file except in compliance with the License.
1298
- You may obtain a copy of the License at
1299
-
1300
- http://www.apache.org/licenses/LICENSE-2.0
1301
-
1302
- Unless required by applicable law or agreed to in writing, software
1303
- distributed under the License is distributed on an "AS IS" BASIS,
1304
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1305
- See the License for the specific language governing permissions and
1306
- limitations under the License.
1307
- */
2666
+ /**
2667
+ * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
2668
+ */
1308
2669
 
1309
2670
  /**
2671
+ * Parses one line of ul/ol to command
2672
+ *
2673
+ * @returns parsed command object
2674
+ * @throws {PromptbookSyntaxError} if the command is invalid
1310
2675
  *
2676
+ * @private within the promptbookStringToJson
1311
2677
  */
1312
- function removeDiacritics(input) {
1313
- /*eslint no-control-regex: "off"*/
1314
- return input.replace(/[^\u0000-\u007E]/g, function (a) {
1315
- return DIACRITIC_VARIANTS_LETTERS[a] || a;
1316
- });
1317
- }
1318
-
1319
- /* tslint:disable */
1320
- function normalizeToKebabCase(sentence) {
2678
+ function parseCommand(listItem) {
1321
2679
  var e_1, _a;
1322
- sentence = removeDiacritics(sentence);
1323
- var charType;
1324
- var lastCharType = 'OTHER';
1325
- var normalizedName = '';
1326
- try {
1327
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1328
- var char = sentence_1_1.value;
1329
- var normalizedChar = void 0;
1330
- if (/^[a-z]$/.test(char)) {
1331
- charType = 'LOWERCASE';
1332
- normalizedChar = char;
2680
+ if (listItem.includes('\n') || listItem.includes('\r')) {
2681
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
2682
+ }
2683
+ var type = listItem.trim();
2684
+ type = type.split('`').join('');
2685
+ type = type.split('"').join('');
2686
+ type = type.split("'").join('');
2687
+ type = type.split('~').join('');
2688
+ type = type.split('[').join('');
2689
+ type = type.split(']').join('');
2690
+ type = type.split('(').join('');
2691
+ type = type.split(')').join('');
2692
+ type = normalizeTo_SCREAMING_CASE(type);
2693
+ type = type.split('DIALOGUE').join('DIALOG');
2694
+ var listItemParts = listItem
2695
+ .split(' ')
2696
+ .map(function (part) { return part.trim(); })
2697
+ .filter(function (item) { return item !== ''; })
2698
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
2699
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
2700
+ .map(removeMarkdownFormatting);
2701
+ if (type.startsWith('URL') ||
2702
+ type.startsWith('PTBK_URL') ||
2703
+ type.startsWith('PTBKURL') ||
2704
+ type.startsWith('PROMPTBOOK_URL') ||
2705
+ type.startsWith('PROMPTBOOKURL') ||
2706
+ type.startsWith('HTTPS')) {
2707
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
2708
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
2709
+ }
2710
+ var promptbookUrlString = listItemParts.pop();
2711
+ var promptbookUrl = new URL(promptbookUrlString);
2712
+ if (promptbookUrl.protocol !== 'https:') {
2713
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
2714
+ }
2715
+ if (promptbookUrl.hash !== '') {
2716
+ throw new PromptbookSyntaxError(spaceTrim$1("\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 ")));
2717
+ }
2718
+ return {
2719
+ type: 'PROMPTBOOK_URL',
2720
+ promptbookUrl: promptbookUrl,
2721
+ };
2722
+ }
2723
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
2724
+ if (listItemParts.length !== 2) {
2725
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
2726
+ }
2727
+ var promptbookVersion = listItemParts.pop();
2728
+ // TODO: Validate version
2729
+ return {
2730
+ type: 'PROMPTBOOK_VERSION',
2731
+ promptbookVersion: promptbookVersion,
2732
+ };
2733
+ }
2734
+ else if (type.startsWith('EXECUTE') ||
2735
+ type.startsWith('EXEC') ||
2736
+ type.startsWith('PROMPT_DIALOG') ||
2737
+ type.startsWith('SIMPLE_TEMPLATE')) {
2738
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
2739
+ if (executionTypes.length !== 1) {
2740
+ throw new PromptbookSyntaxError(spaceTrim$1(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 "); }));
2741
+ }
2742
+ return {
2743
+ type: 'EXECUTE',
2744
+ executionType: executionTypes[0],
2745
+ };
2746
+ }
2747
+ else if (type.startsWith('MODEL')) {
2748
+ // TODO: Make this more elegant and dynamically
2749
+ if (type.startsWith('MODEL_VARIANT')) {
2750
+ if (type === 'MODEL_VARIANT_CHAT') {
2751
+ return {
2752
+ type: 'MODEL',
2753
+ key: 'modelVariant',
2754
+ value: 'CHAT',
2755
+ };
1333
2756
  }
1334
- else if (/^[A-Z]$/.test(char)) {
1335
- charType = 'UPPERCASE';
1336
- normalizedChar = char.toLowerCase();
2757
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
2758
+ return {
2759
+ type: 'MODEL',
2760
+ key: 'modelVariant',
2761
+ value: 'COMPLETION',
2762
+ };
2763
+ }
2764
+ else {
2765
+ throw new PromptbookSyntaxError(spaceTrim$1(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 "); }));
2766
+ }
2767
+ }
2768
+ if (type.startsWith('MODEL_NAME')) {
2769
+ return {
2770
+ type: 'MODEL',
2771
+ key: 'modelName',
2772
+ value: listItemParts.pop(),
2773
+ };
2774
+ }
2775
+ else {
2776
+ throw new PromptbookSyntaxError(spaceTrim$1(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 "); }));
2777
+ }
2778
+ }
2779
+ else if (type.startsWith('PARAM') ||
2780
+ type.startsWith('INPUT_PARAM') ||
2781
+ type.startsWith('OUTPUT_PARAM') ||
2782
+ listItem.startsWith('{') ||
2783
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
2784
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
2785
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2786
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2787
+ }
2788
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2789
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
2790
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
2791
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
2792
+ }
2793
+ var isInput = type.startsWith('INPUT');
2794
+ var isOutput = type.startsWith('OUTPUT');
2795
+ if (listItem.startsWith('> {')) {
2796
+ isInput = false;
2797
+ isOutput = false;
2798
+ }
2799
+ return {
2800
+ type: 'PARAMETER',
2801
+ parameterName: parameterName,
2802
+ parameterDescription: parameterDescription.trim() || null,
2803
+ isInput: isInput,
2804
+ isOutput: isOutput,
2805
+ };
2806
+ }
2807
+ else if (type.startsWith('JOKER')) {
2808
+ if (listItemParts.length !== 2) {
2809
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
2810
+ }
2811
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
2812
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2813
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2814
+ }
2815
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2816
+ var parameterName = parametersMatch.groups.parameterName;
2817
+ return {
2818
+ type: 'JOKER',
2819
+ parameterName: parameterName,
2820
+ };
2821
+ }
2822
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
2823
+ if (listItemParts.length !== 2) {
2824
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
2825
+ }
2826
+ var functionName = listItemParts.pop();
2827
+ return {
2828
+ type: 'POSTPROCESS',
2829
+ functionName: functionName,
2830
+ };
2831
+ }
2832
+ else if (type.startsWith('EXPECT_JSON')) {
2833
+ return {
2834
+ type: 'EXPECT_FORMAT',
2835
+ format: 'JSON',
2836
+ };
2837
+ // [🥤]
2838
+ }
2839
+ else if (type.startsWith('EXPECT')) {
2840
+ try {
2841
+ listItemParts.shift();
2842
+ var sign = void 0;
2843
+ var signRaw = listItemParts.shift();
2844
+ if (/^exact/i.test(signRaw)) {
2845
+ sign = 'EXACTLY';
1337
2846
  }
1338
- else if (/^[0-9]$/.test(char)) {
1339
- charType = 'NUMBER';
1340
- normalizedChar = char;
2847
+ else if (/^min/i.test(signRaw)) {
2848
+ sign = 'MINIMUM';
1341
2849
  }
1342
- else if (/^\/$/.test(char)) {
1343
- charType = 'SLASH';
1344
- normalizedChar = char;
2850
+ else if (/^max/i.test(signRaw)) {
2851
+ sign = 'MAXIMUM';
1345
2852
  }
1346
2853
  else {
1347
- charType = 'OTHER';
1348
- normalizedChar = '-';
2854
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
1349
2855
  }
1350
- if (charType !== lastCharType &&
1351
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1352
- !(lastCharType === 'NUMBER') &&
1353
- !(charType === 'NUMBER')) {
1354
- normalizedName += '-';
2856
+ var amountRaw = listItemParts.shift();
2857
+ var amount = parseNumber(amountRaw);
2858
+ if (amount < 0) {
2859
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
1355
2860
  }
1356
- normalizedName += normalizedChar;
1357
- lastCharType = charType;
2861
+ if (amount !== Math.floor(amount)) {
2862
+ throw new PromptbookSyntaxError('Amount must be whole number');
2863
+ }
2864
+ var unitRaw = listItemParts.shift();
2865
+ var unit = undefined;
2866
+ try {
2867
+ 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()) {
2868
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
2869
+ var existingUnitText = existingUnit;
2870
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
2871
+ if (existingUnitText === 'CHARACTER') {
2872
+ existingUnitText = 'CHAR';
2873
+ }
2874
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
2875
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
2876
+ if (unit !== undefined) {
2877
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
2878
+ }
2879
+ unit = existingUnit;
2880
+ }
2881
+ }
2882
+ }
2883
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2884
+ finally {
2885
+ try {
2886
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
2887
+ }
2888
+ finally { if (e_1) throw e_1.error; }
2889
+ }
2890
+ if (unit === undefined) {
2891
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
2892
+ }
2893
+ return {
2894
+ type: 'EXPECT_AMOUNT',
2895
+ sign: sign,
2896
+ unit: unit,
2897
+ amount: amount,
2898
+ };
1358
2899
  }
1359
- }
1360
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1361
- finally {
1362
- try {
1363
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
2900
+ catch (error) {
2901
+ if (!(error instanceof Error)) {
2902
+ throw error;
2903
+ }
2904
+ throw new PromptbookSyntaxError(spaceTrim$1("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1364
2905
  }
1365
- finally { if (e_1) throw e_1.error; }
2906
+ /*
2907
+ } else if (type.startsWith('__________________')) {
2908
+ // <- [🥻] Insert here when making new command
2909
+ */
2910
+ }
2911
+ else {
2912
+ throw new PromptbookSyntaxError(spaceTrim$1("\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 ")));
1366
2913
  }
1367
- normalizedName = normalizedName.split(/-+/g).join('-');
1368
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1369
- normalizedName = normalizedName.replace(/^-/, '');
1370
- normalizedName = normalizedName.replace(/-$/, '');
1371
- return normalizedName;
1372
2914
  }
1373
2915
 
1374
2916
  /**
@@ -1427,7 +2969,10 @@ function promptbookStringToJson(promptbookString, options) {
1427
2969
  knowledge: [],
1428
2970
  };
1429
2971
  if (!llmTools) return [3 /*break*/, 2];
1430
- return [4 /*yield*/, prepareKnowledgeFromMarkdown()];
2972
+ return [4 /*yield*/, prepareKnowledgeFromMarkdown({
2973
+ content: 'Roses are red, violets are blue, programmers use Promptbook, users too',
2974
+ llmTools: llmTools,
2975
+ })];
1431
2976
  case 1:
1432
2977
  knowledge = _e.sent();
1433
2978
  console.info('!!!! knowledge', knowledge);
@@ -1445,7 +2990,7 @@ function promptbookStringToJson(promptbookString, options) {
1445
2990
  existingParameter.description &&
1446
2991
  existingParameter.description !== parameterDescription &&
1447
2992
  parameterDescription) {
1448
- throw new PromptbookSyntaxError(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 "); }));
2993
+ throw new PromptbookSyntaxError(spaceTrim$1(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 "); }));
1449
2994
  }
1450
2995
  if (existingParameter) {
1451
2996
  if (parameterDescription) {
@@ -1464,7 +3009,7 @@ function promptbookStringToJson(promptbookString, options) {
1464
3009
  markdownStructure = markdownToMarkdownStructure(promptbookString);
1465
3010
  markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
1466
3011
  if (markdownStructureDeepness !== 2) {
1467
- throw new PromptbookSyntaxError(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 ")));
3012
+ throw new PromptbookSyntaxError(spaceTrim$1("\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 ")));
1468
3013
  }
1469
3014
  promptbookJson.title = markdownStructure.title;
1470
3015
  description = markdownStructure.content;
@@ -1472,7 +3017,7 @@ function promptbookStringToJson(promptbookString, options) {
1472
3017
  description = description.split(/^```.*^```/gms).join('');
1473
3018
  //Note: Remove lists and return statement
1474
3019
  description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1475
- description = spaceTrim(description);
3020
+ description = spaceTrim$1(description);
1476
3021
  if (description === '') {
1477
3022
  description = undefined;
1478
3023
  }
@@ -1587,13 +3132,13 @@ function promptbookStringToJson(promptbookString, options) {
1587
3132
  throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
1588
3133
  }
1589
3134
  else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
1590
- throw new PromptbookSyntaxError(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 "); }));
3135
+ throw new PromptbookSyntaxError(spaceTrim$1(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 "); }));
1591
3136
  }
1592
3137
  }
1593
3138
  var lastLine = section.content.split('\n').pop();
1594
3139
  var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1595
3140
  if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1596
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
3141
+ throw new PromptbookSyntaxError(spaceTrim$1(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1597
3142
  // TODO: Show code of invalid sections each time + DRY
1598
3143
  section.content
1599
3144
  .split('\n')
@@ -1607,7 +3152,7 @@ function promptbookStringToJson(promptbookString, options) {
1607
3152
  description_1 = description_1.split(/^```.*^```/gms).join('');
1608
3153
  //Note: Remove lists and return statement
1609
3154
  description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1610
- description_1 = spaceTrim(description_1);
3155
+ description_1 = spaceTrim$1(description_1);
1611
3156
  if (description_1 === '') {
1612
3157
  description_1 = undefined;
1613
3158
  }
@@ -1624,7 +3169,7 @@ function promptbookStringToJson(promptbookString, options) {
1624
3169
  if (templateModelRequirements.modelVariant === undefined) {
1625
3170
  templateModelRequirements.modelVariant = 'CHAT';
1626
3171
  }
1627
- promptbookJson.promptTemplates.push({
3172
+ var template = {
1628
3173
  name: titleToName(section.title),
1629
3174
  title: section.title,
1630
3175
  description: description_1,
@@ -1638,7 +3183,12 @@ function promptbookStringToJson(promptbookString, options) {
1638
3183
  contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1639
3184
  content: content,
1640
3185
  resultingParameterName: resultingParameterName,
1641
- });
3186
+ };
3187
+ if (executionType !== 'PROMPT_TEMPLATE') {
3188
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3189
+ delete template.modelRequirements;
3190
+ }
3191
+ promptbookJson.promptTemplates.push(template);
1642
3192
  };
1643
3193
  try {
1644
3194
  for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
@@ -1665,6 +3215,505 @@ function promptbookStringToJson(promptbookString, options) {
1665
3215
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1666
3216
  */
1667
3217
 
3218
+ /**
3219
+ * This error indicates that the promptbook library cannot be propperly loaded
3220
+ */
3221
+ var PromptbookLibraryError = /** @class */ (function (_super) {
3222
+ __extends(PromptbookLibraryError, _super);
3223
+ function PromptbookLibraryError(message) {
3224
+ var _this = _super.call(this, message) || this;
3225
+ _this.name = 'PromptbookLibraryError';
3226
+ Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
3227
+ return _this;
3228
+ }
3229
+ return PromptbookLibraryError;
3230
+ }(Error));
3231
+
3232
+ /**
3233
+ * Constructs Promptbook from async sources
3234
+ * It can be one of the following:
3235
+ * - Promise of array of PromptbookJson or PromptbookString
3236
+ * - Factory function that returns Promise of array of PromptbookJson or PromptbookString
3237
+ *
3238
+ * Note: This is useful as internal tool for other constructor functions like
3239
+ * `createLibraryFromUrl` or `createLibraryFromDirectory`
3240
+ * Consider using those functions instead of this one
3241
+ *
3242
+ * Note: The function does NOT return promise it returns the library directly which waits for the sources to be resolved
3243
+ * when error occurs in given promise or factory function, it is thrown during `listPromptbooks` or `getPromptbookByUrl` call
3244
+ *
3245
+ * Note: Consider using `createLibraryFromDirectory` or `createLibraryFromUrl`
3246
+ *
3247
+ * @param promptbookSourcesPromiseOrFactory
3248
+ * @returns PromptbookLibrary
3249
+ * @deprecated Do not use, it will became internal tool for other constructor functions
3250
+ */
3251
+ function createLibraryFromPromise(promptbookSourcesPromiseOrFactory) {
3252
+ var library;
3253
+ function forSources() {
3254
+ return __awaiter(this, void 0, void 0, function () {
3255
+ var promptbookSources;
3256
+ return __generator(this, function (_a) {
3257
+ switch (_a.label) {
3258
+ case 0:
3259
+ if (typeof promptbookSourcesPromiseOrFactory === 'function') {
3260
+ // Note: Calling factory function only once despite multiple calls to resolveSources
3261
+ promptbookSourcesPromiseOrFactory = promptbookSourcesPromiseOrFactory();
3262
+ }
3263
+ return [4 /*yield*/, promptbookSourcesPromiseOrFactory];
3264
+ case 1:
3265
+ promptbookSources = _a.sent();
3266
+ library = createLibraryFromJson.apply(void 0, __spreadArray([], __read(promptbookSources), false));
3267
+ return [2 /*return*/];
3268
+ }
3269
+ });
3270
+ });
3271
+ }
3272
+ function listPromptbooks() {
3273
+ return __awaiter(this, void 0, void 0, function () {
3274
+ return __generator(this, function (_a) {
3275
+ switch (_a.label) {
3276
+ case 0: return [4 /*yield*/, forSources()];
3277
+ case 1:
3278
+ _a.sent();
3279
+ return [2 /*return*/, /* not await */ library.listPromptbooks()];
3280
+ }
3281
+ });
3282
+ });
3283
+ }
3284
+ function getPromptbookByUrl(url) {
3285
+ return __awaiter(this, void 0, void 0, function () {
3286
+ return __generator(this, function (_a) {
3287
+ switch (_a.label) {
3288
+ case 0: return [4 /*yield*/, forSources()];
3289
+ case 1:
3290
+ _a.sent();
3291
+ return [2 /*return*/, /* not await */ library.getPromptbookByUrl(url)];
3292
+ }
3293
+ });
3294
+ });
3295
+ }
3296
+ function isResponsibleForPrompt(prompt) {
3297
+ return __awaiter(this, void 0, void 0, function () {
3298
+ return __generator(this, function (_a) {
3299
+ switch (_a.label) {
3300
+ case 0: return [4 /*yield*/, forSources()];
3301
+ case 1:
3302
+ _a.sent();
3303
+ return [2 /*return*/, /* not await */ library.isResponsibleForPrompt(prompt)];
3304
+ }
3305
+ });
3306
+ });
3307
+ }
3308
+ return {
3309
+ listPromptbooks: listPromptbooks,
3310
+ getPromptbookByUrl: getPromptbookByUrl,
3311
+ isResponsibleForPrompt: isResponsibleForPrompt,
3312
+ };
3313
+ }
3314
+
3315
+ /**
3316
+ * Constructs Promptbook from given directory
3317
+ *
3318
+ * Note: Works only in Node.js environment because it reads the file system
3319
+ *
3320
+ * @param path - path to the directory with promptbooks
3321
+ * @param options - Misc options for the library
3322
+ * @returns PromptbookLibrary
3323
+ */
3324
+ function createLibraryFromDirectory(path, options) {
3325
+ return __awaiter(this, void 0, void 0, function () {
3326
+ var makedLibraryFilePath, makedLibraryFileExists, _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, _e, isCrashOnError, library;
3327
+ var _this = this;
3328
+ return __generator(this, function (_f) {
3329
+ switch (_f.label) {
3330
+ case 0:
3331
+ if (!isRunningInNode()) {
3332
+ throw new Error('Function `createLibraryFromDirectory` can only be run in Node.js environment because it reads the file system.');
3333
+ }
3334
+ makedLibraryFilePath = join(path, "".concat(PROMPTBOOK_MAKED_BASE_FILENAME, ".json"));
3335
+ return [4 /*yield*/, access(makedLibraryFilePath, constants.R_OK)
3336
+ .then(function () { return true; })
3337
+ .catch(function () { return false; })];
3338
+ case 1:
3339
+ makedLibraryFileExists = _f.sent();
3340
+ if (!makedLibraryFileExists) {
3341
+ console.info(colors.yellow("Tip: Prebuild your promptbook library (file with supposed prebuild ".concat(makedLibraryFilePath, " not found) with CLI util \"promptbook make\" to speed up the library creation.")));
3342
+ }
3343
+ else {
3344
+ colors.green("Using your prebuild promptbook library ".concat(makedLibraryFilePath));
3345
+ // TODO: !!!!! Implement;
3346
+ }
3347
+ _a = options || {}, _b = _a.isRecursive, isRecursive = _b === void 0 ? true : _b, _c = _a.isVerbose, isVerbose = _c === void 0 ? false : _c, _d = _a.isLazyLoaded, isLazyLoaded = _d === void 0 ? false : _d, _e = _a.isCrashOnError, isCrashOnError = _e === void 0 ? true : _e;
3348
+ library = createLibraryFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
3349
+ var fileNames, promptbooks, _loop_1, fileNames_1, fileNames_1_1, fileName, e_1_1;
3350
+ var e_1, _a;
3351
+ return __generator(this, function (_b) {
3352
+ switch (_b.label) {
3353
+ case 0:
3354
+ if (isVerbose) {
3355
+ console.info("Creating promptbook library from path ".concat(path.split('\\').join('/')));
3356
+ }
3357
+ return [4 /*yield*/, listAllFiles(path, isRecursive)];
3358
+ case 1:
3359
+ fileNames = _b.sent();
3360
+ promptbooks = [];
3361
+ _loop_1 = function (fileName) {
3362
+ var promptbook, promptbookString, _c, _d, error_1, wrappedErrorMessage;
3363
+ return __generator(this, function (_e) {
3364
+ switch (_e.label) {
3365
+ case 0:
3366
+ _e.trys.push([0, 7, , 8]);
3367
+ promptbook = null;
3368
+ if (!fileName.endsWith('.ptbk.md')) return [3 /*break*/, 3];
3369
+ return [4 /*yield*/, readFile(fileName, 'utf8')];
3370
+ case 1:
3371
+ promptbookString = (_e.sent());
3372
+ return [4 /*yield*/, promptbookStringToJson(promptbookString)];
3373
+ case 2:
3374
+ promptbook = _e.sent();
3375
+ return [3 /*break*/, 6];
3376
+ case 3:
3377
+ if (!fileName.endsWith('.ptbk.json')) return [3 /*break*/, 5];
3378
+ if (isVerbose) {
3379
+ console.info("Loading ".concat(fileName.split('\\').join('/')));
3380
+ }
3381
+ _d = (_c = JSON).parse;
3382
+ return [4 /*yield*/, readFile(fileName, 'utf8')];
3383
+ case 4:
3384
+ // TODO: Handle non-valid JSON files
3385
+ promptbook = _d.apply(_c, [_e.sent()]);
3386
+ return [3 /*break*/, 6];
3387
+ case 5:
3388
+ if (isVerbose) {
3389
+ console.info("Skipping file ".concat(fileName.split('\\').join('/')));
3390
+ }
3391
+ _e.label = 6;
3392
+ case 6:
3393
+ // ---
3394
+ if (promptbook !== null) {
3395
+ if (!promptbook.promptbookUrl) {
3396
+ if (isVerbose) {
3397
+ console.info("Not loading ".concat(fileName.split('\\').join('/'), " - missing URL"));
3398
+ }
3399
+ }
3400
+ else {
3401
+ if (isVerbose) {
3402
+ console.info("Loading ".concat(fileName.split('\\').join('/')));
3403
+ }
3404
+ if (!isCrashOnError) {
3405
+ // Note: Validate promptbook to check if it is logically correct to not crash on invalid promptbooks
3406
+ // But be handled in current try-catch block
3407
+ validatePromptbook(promptbook);
3408
+ }
3409
+ // Note: [🦄] Promptbook with same url uniqueness will be checked automatically in SimplePromptbookLibrary
3410
+ promptbooks.push(promptbook);
3411
+ }
3412
+ }
3413
+ return [3 /*break*/, 8];
3414
+ case 7:
3415
+ error_1 = _e.sent();
3416
+ if (!(error_1 instanceof Error)) {
3417
+ throw error_1;
3418
+ }
3419
+ wrappedErrorMessage = spaceTrim(function (block) { return "\n Error during loading promptbook from file ".concat(fileName.split('\\').join('/'), ":\n\n ").concat(block(error_1.message), "\n\n "); });
3420
+ if (isCrashOnError) {
3421
+ throw new PromptbookLibraryError(wrappedErrorMessage);
3422
+ }
3423
+ console.error(wrappedErrorMessage);
3424
+ return [3 /*break*/, 8];
3425
+ case 8: return [2 /*return*/];
3426
+ }
3427
+ });
3428
+ };
3429
+ _b.label = 2;
3430
+ case 2:
3431
+ _b.trys.push([2, 7, 8, 9]);
3432
+ fileNames_1 = __values(fileNames), fileNames_1_1 = fileNames_1.next();
3433
+ _b.label = 3;
3434
+ case 3:
3435
+ if (!!fileNames_1_1.done) return [3 /*break*/, 6];
3436
+ fileName = fileNames_1_1.value;
3437
+ return [5 /*yield**/, _loop_1(fileName)];
3438
+ case 4:
3439
+ _b.sent();
3440
+ _b.label = 5;
3441
+ case 5:
3442
+ fileNames_1_1 = fileNames_1.next();
3443
+ return [3 /*break*/, 3];
3444
+ case 6: return [3 /*break*/, 9];
3445
+ case 7:
3446
+ e_1_1 = _b.sent();
3447
+ e_1 = { error: e_1_1 };
3448
+ return [3 /*break*/, 9];
3449
+ case 8:
3450
+ try {
3451
+ if (fileNames_1_1 && !fileNames_1_1.done && (_a = fileNames_1.return)) _a.call(fileNames_1);
3452
+ }
3453
+ finally { if (e_1) throw e_1.error; }
3454
+ return [7 /*endfinally*/];
3455
+ case 9: return [2 /*return*/, promptbooks];
3456
+ }
3457
+ });
3458
+ }); });
3459
+ if (!(isLazyLoaded === false)) return [3 /*break*/, 3];
3460
+ return [4 /*yield*/, library.listPromptbooks()];
3461
+ case 2:
3462
+ _f.sent();
3463
+ _f.label = 3;
3464
+ case 3: return [2 /*return*/, library];
3465
+ }
3466
+ });
3467
+ });
3468
+ }
3469
+ /**
3470
+ * Reads all files in the directory
3471
+ *
3472
+ * @param path
3473
+ * @param isRecursive
3474
+ * @returns List of all files in the directory
3475
+ * @private internal function for `createLibraryFromDirectory`
3476
+ */
3477
+ function listAllFiles(path, isRecursive) {
3478
+ return __awaiter(this, void 0, void 0, function () {
3479
+ var dirents, fileNames, _a, _b, dirent, subPath, _c, _d, _e, _f, e_2_1;
3480
+ var e_2, _g;
3481
+ return __generator(this, function (_h) {
3482
+ switch (_h.label) {
3483
+ case 0: return [4 /*yield*/, readdir(path, {
3484
+ withFileTypes: true /* Note: This is not working: recursive: isRecursive */,
3485
+ })];
3486
+ case 1:
3487
+ dirents = _h.sent();
3488
+ fileNames = dirents.filter(function (dirent) { return dirent.isFile(); }).map(function (_a) {
3489
+ var name = _a.name;
3490
+ return join(path, name);
3491
+ });
3492
+ if (!isRecursive) return [3 /*break*/, 9];
3493
+ _h.label = 2;
3494
+ case 2:
3495
+ _h.trys.push([2, 7, 8, 9]);
3496
+ _a = __values(dirents.filter(function (dirent) { return dirent.isDirectory(); })), _b = _a.next();
3497
+ _h.label = 3;
3498
+ case 3:
3499
+ if (!!_b.done) return [3 /*break*/, 6];
3500
+ dirent = _b.value;
3501
+ subPath = join(path, dirent.name);
3502
+ _d = (_c = fileNames.push).apply;
3503
+ _e = [fileNames];
3504
+ _f = [[]];
3505
+ return [4 /*yield*/, listAllFiles(subPath, isRecursive)];
3506
+ case 4:
3507
+ _d.apply(_c, _e.concat([__spreadArray.apply(void 0, _f.concat([__read.apply(void 0, [(_h.sent())]), false]))]));
3508
+ _h.label = 5;
3509
+ case 5:
3510
+ _b = _a.next();
3511
+ return [3 /*break*/, 3];
3512
+ case 6: return [3 /*break*/, 9];
3513
+ case 7:
3514
+ e_2_1 = _h.sent();
3515
+ e_2 = { error: e_2_1 };
3516
+ return [3 /*break*/, 9];
3517
+ case 8:
3518
+ try {
3519
+ if (_b && !_b.done && (_g = _a.return)) _g.call(_a);
3520
+ }
3521
+ finally { if (e_2) throw e_2.error; }
3522
+ return [7 /*endfinally*/];
3523
+ case 9: return [2 /*return*/, fileNames];
3524
+ }
3525
+ });
3526
+ });
3527
+ }
3528
+ /**
3529
+ * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
3530
+ */
3531
+
3532
+ /**
3533
+ * Converts PromptbookLibrary to serialized JSON
3534
+ *
3535
+ * Note: Functions `libraryToJson` and `createLibraryFromJson` are complementary
3536
+ */
3537
+ function libraryToJson(library) {
3538
+ return __awaiter(this, void 0, void 0, function () {
3539
+ var promptbookUrls, promptbooks;
3540
+ return __generator(this, function (_a) {
3541
+ switch (_a.label) {
3542
+ case 0: return [4 /*yield*/, library.listPromptbooks()];
3543
+ case 1:
3544
+ promptbookUrls = _a.sent();
3545
+ return [4 /*yield*/, Promise.all(promptbookUrls.map(function (url) { return library.getPromptbookByUrl(url); }))];
3546
+ case 2:
3547
+ promptbooks = _a.sent();
3548
+ return [2 /*return*/, promptbooks];
3549
+ }
3550
+ });
3551
+ });
3552
+ }
3553
+
3554
+ /**
3555
+ * Initializes `make` command for Promptbook CLI utilities
3556
+ *
3557
+ * @private part of `promptbookCli`
3558
+ */
3559
+ function initializeMake(program) {
3560
+ var _this = this;
3561
+ var helloCommand = program.command('make');
3562
+ helloCommand.description(spaceTrim("\n Makes a new promptbook library in given folder\n "));
3563
+ helloCommand.argument('<path>', 'Path to promptbook directory');
3564
+ helloCommand.option('--project-name', "Name of the project for whom library is", 'Project');
3565
+ helloCommand.option('-f, --format <format>', spaceTrim("\n Output format of builded library \"javascript\", \"typescript\" or \"json\"\n\n Note: You can use multiple formats separated by comma\n "), 'javascript' /* <- Note: [🏳‍🌈] */);
3566
+ helloCommand.option('--no-validation', "Do not validate logic of promptbooks in library", true);
3567
+ helloCommand.option('--validation', "Types of validations separated by comma (options \"logic\",\"imports\")", 'logic,imports');
3568
+ helloCommand.option('--verbose', "Is verbose", false);
3569
+ // TODO: !!! Auto-detect AI api keys + explicit api keys as argv
3570
+ helloCommand.action(function (path, _a) {
3571
+ var projectName = _a.projectName, format = _a.format, validation = _a.validation, verbose = _a.verbose;
3572
+ return __awaiter(_this, void 0, void 0, function () {
3573
+ var formats, validations, library, validations_1, validations_1_1, validation_1, _b, _c, promptbookUrl, promptbook, e_1_1, e_2_1, libraryJson, libraryJsonString, saveFile;
3574
+ var e_2, _d, e_1, _e;
3575
+ var _this = this;
3576
+ return __generator(this, function (_f) {
3577
+ switch (_f.label) {
3578
+ case 0:
3579
+ console.info('!!!', { projectName: projectName, path: path, format: format, validation: validation, verbose: verbose });
3580
+ formats = (format || '')
3581
+ .split(',')
3582
+ .map(function (_) { return _.trim(); })
3583
+ .filter(function (_) { return _ !== ''; });
3584
+ validations = (validation || '')
3585
+ .split(',')
3586
+ .map(function (_) { return _.trim(); })
3587
+ .filter(function (_) { return _ !== ''; });
3588
+ return [4 /*yield*/, createLibraryFromDirectory(path, {
3589
+ isVerbose: verbose,
3590
+ isRecursive: true,
3591
+ })];
3592
+ case 1:
3593
+ library = _f.sent();
3594
+ _f.label = 2;
3595
+ case 2:
3596
+ _f.trys.push([2, 14, 15, 16]);
3597
+ validations_1 = __values(validations), validations_1_1 = validations_1.next();
3598
+ _f.label = 3;
3599
+ case 3:
3600
+ if (!!validations_1_1.done) return [3 /*break*/, 13];
3601
+ validation_1 = validations_1_1.value;
3602
+ _f.label = 4;
3603
+ case 4:
3604
+ _f.trys.push([4, 10, 11, 12]);
3605
+ e_1 = void 0;
3606
+ return [4 /*yield*/, library.listPromptbooks()];
3607
+ case 5:
3608
+ _b = (__values.apply(void 0, [_f.sent()])), _c = _b.next();
3609
+ _f.label = 6;
3610
+ case 6:
3611
+ if (!!_c.done) return [3 /*break*/, 9];
3612
+ promptbookUrl = _c.value;
3613
+ return [4 /*yield*/, library.getPromptbookByUrl(promptbookUrl)];
3614
+ case 7:
3615
+ promptbook = _f.sent();
3616
+ if (validation_1 === 'logic') {
3617
+ validatePromptbook(promptbook);
3618
+ if (verbose) {
3619
+ console.info(colors.cyan("Validated logic of ".concat(promptbook.promptbookUrl)));
3620
+ }
3621
+ }
3622
+ _f.label = 8;
3623
+ case 8:
3624
+ _c = _b.next();
3625
+ return [3 /*break*/, 6];
3626
+ case 9: return [3 /*break*/, 12];
3627
+ case 10:
3628
+ e_1_1 = _f.sent();
3629
+ e_1 = { error: e_1_1 };
3630
+ return [3 /*break*/, 12];
3631
+ case 11:
3632
+ try {
3633
+ if (_c && !_c.done && (_e = _b.return)) _e.call(_b);
3634
+ }
3635
+ finally { if (e_1) throw e_1.error; }
3636
+ return [7 /*endfinally*/];
3637
+ case 12:
3638
+ validations_1_1 = validations_1.next();
3639
+ return [3 /*break*/, 3];
3640
+ case 13: return [3 /*break*/, 16];
3641
+ case 14:
3642
+ e_2_1 = _f.sent();
3643
+ e_2 = { error: e_2_1 };
3644
+ return [3 /*break*/, 16];
3645
+ case 15:
3646
+ try {
3647
+ if (validations_1_1 && !validations_1_1.done && (_d = validations_1.return)) _d.call(validations_1);
3648
+ }
3649
+ finally { if (e_2) throw e_2.error; }
3650
+ return [7 /*endfinally*/];
3651
+ case 16: return [4 /*yield*/, libraryToJson(library)];
3652
+ case 17:
3653
+ libraryJson = _f.sent();
3654
+ libraryJsonString = JSON.stringify(libraryJson);
3655
+ saveFile = function (extension, content) { return __awaiter(_this, void 0, void 0, function () {
3656
+ var filePath;
3657
+ return __generator(this, function (_a) {
3658
+ switch (_a.label) {
3659
+ case 0:
3660
+ filePath = join(path, "promptbook-library.".concat(extension));
3661
+ return [4 /*yield*/, writeFile(filePath, content, 'utf-8')];
3662
+ case 1:
3663
+ _a.sent();
3664
+ // Note: Log despite of verbose mode
3665
+ console.info(colors.green("Maked ".concat(filePath.split('\\').join('/'))));
3666
+ return [2 /*return*/];
3667
+ }
3668
+ });
3669
+ }); };
3670
+ if (!formats.includes('json')) return [3 /*break*/, 19];
3671
+ return [4 /*yield*/, saveFile('json', libraryJsonString + '\n')];
3672
+ case 18:
3673
+ _f.sent();
3674
+ _f.label = 19;
3675
+ case 19:
3676
+ if (!formats.includes('javascript')) return [3 /*break*/, 21];
3677
+ return [4 /*yield*/, saveFile('js', spaceTrim("\n import { createLibraryFromJson } from '@promptbook/core';\n\n /**\n * Promptbook library for ".concat(projectName, "\n *\n * @private internal cache for `getPromptbookLibrary`\n */\n let promptbookLibrary = null;\n\n\n /**\n * Get promptbook library for ").concat(projectName, "\n *\n * @returns {PromptbookLibrary} Library of promptbooks for ").concat(projectName, "\n * @generated by `@promptbook/cli`\n */\n export function getPromptbookLibrary(){\n if(promptbookLibrary===null){\n promptbookLibrary = createLibraryFromJson(").concat(libraryJsonString.substring(1, libraryJsonString.length - 1), ");\n }\n\n return promptbookLibrary;\n }\n ") + '\n'))];
3678
+ case 20:
3679
+ _f.sent();
3680
+ _f.label = 21;
3681
+ case 21:
3682
+ if (!formats.includes('typescript')) return [3 /*break*/, 23];
3683
+ return [4 /*yield*/, saveFile('ts', spaceTrim("\n import { createLibraryFromJson } from '@promptbook/core';\n import type { PromptbookLibrary } from '@promptbook/types';\n\n /**\n * Promptbook library for ".concat(projectName, "\n *\n * @private internal cache for `getPromptbookLibrary`\n */\n let promptbookLibrary: null | PromptbookLibrary = null;\n\n\n /**\n * Get promptbook library for ").concat(projectName, "\n *\n * @returns {PromptbookLibrary} Library of promptbooks for ").concat(projectName, "\n * @generated by `@promptbook/cli`\n */\n export function getPromptbookLibrary(): PromptbookLibrary{\n if(promptbookLibrary===null){\n promptbookLibrary = createLibraryFromJson(").concat(libraryJsonString.substring(1, libraryJsonString.length - 1), ");\n }\n\n return promptbookLibrary;\n }\n ") + '\n'))];
3684
+ case 22:
3685
+ _f.sent();
3686
+ _f.label = 23;
3687
+ case 23:
3688
+ process.exit(0);
3689
+ return [2 /*return*/];
3690
+ }
3691
+ });
3692
+ });
3693
+ });
3694
+ }
3695
+
3696
+ /**
3697
+ * Add or modify an auto-generated section in a markdown file
3698
+ *
3699
+ * @private within the library
3700
+ */
3701
+ function addAutoGeneratedSection(content, options) {
3702
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
3703
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
3704
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
3705
+ var sectionMatch = content.match(sectionRegex);
3706
+ if (sectionMatch) {
3707
+ return content.replace(sectionRegex, spaceTrim$1(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
3708
+ }
3709
+ var placeForSection = removeContentComments(content).match(/^##.*$/im);
3710
+ if (!placeForSection) {
3711
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
3712
+ }
3713
+ var _a = __read(placeForSection, 1), heading = _a[0];
3714
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
3715
+ }
3716
+
1668
3717
  /* tslint:disable */
1669
3718
  function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1670
3719
  var e_1, _a;
@@ -1741,7 +3790,7 @@ function renderPromptbookMermaid(promptbookJson, options) {
1741
3790
  }
1742
3791
  return normalizeTo_camelCase('template-' + titleToName(template.title));
1743
3792
  };
1744
- var promptbookMermaid = spaceTrim(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
3793
+ var promptbookMermaid = spaceTrim$1(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
1745
3794
  .flatMap(function (_a) {
1746
3795
  var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
1747
3796
  return __spreadArray([
@@ -1797,7 +3846,7 @@ function prettifyPromptbookString(promptbookString, options) {
1797
3846
  return { href: "#".concat(promptTemplate.name), title: promptTemplate.title };
1798
3847
  },
1799
3848
  });
1800
- promptbookMermaidBlock = spaceTrim(function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
3849
+ promptbookMermaidBlock = spaceTrim$1(function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
1801
3850
  promptbookString = addAutoGeneratedSection(promptbookString, {
1802
3851
  sectionName: 'Graph',
1803
3852
  sectionContent: promptbookMermaidBlock,
@@ -1818,117 +3867,106 @@ function prettifyPromptbookString(promptbookString, options) {
1818
3867
  */
1819
3868
 
1820
3869
  /**
1821
- * Runs CLI script for prettifying promptbooks
3870
+ * Initializes `prettify` command for Promptbook CLI utilities
3871
+ *
3872
+ * @private part of `promptbookCli`
3873
+ */
3874
+ function initializePrettify(program) {
3875
+ var _this = this;
3876
+ var prettifyCommand = program.command('prettify');
3877
+ prettifyCommand.description(spaceTrim("\n Iterates over promptbooks and does multiple enhancing operations on them:\n\n 1) Adds Mermaid graph\n 2) Prettifies the markdown\n "));
3878
+ prettifyCommand.argument('<filesGlob>', 'Promptbooks to prettify as glob pattern');
3879
+ prettifyCommand.option('-i, --ignore <glob>', "Ignore as glob pattern");
3880
+ prettifyCommand.action(function (filesGlob, _a) {
3881
+ var ignore = _a.ignore;
3882
+ return __awaiter(_this, void 0, void 0, function () {
3883
+ var filePaths, filePaths_1, filePaths_1_1, filePath, promptbookMarkdown, error_1, e_1_1;
3884
+ var e_1, _b;
3885
+ return __generator(this, function (_c) {
3886
+ switch (_c.label) {
3887
+ case 0: return [4 /*yield*/, glob(filesGlob, { ignore: ignore })];
3888
+ case 1:
3889
+ filePaths = _c.sent();
3890
+ _c.label = 2;
3891
+ case 2:
3892
+ _c.trys.push([2, 11, 12, 13]);
3893
+ filePaths_1 = __values(filePaths), filePaths_1_1 = filePaths_1.next();
3894
+ _c.label = 3;
3895
+ case 3:
3896
+ if (!!filePaths_1_1.done) return [3 /*break*/, 10];
3897
+ filePath = filePaths_1_1.value;
3898
+ if (!filePath.endsWith('.ptbk.md')) {
3899
+ console.warn(colors.yellow("Skipping prettify of non-promptbook ".concat(filePath)));
3900
+ return [3 /*break*/, 9];
3901
+ }
3902
+ return [4 /*yield*/, readFile(filePath, 'utf-8')];
3903
+ case 4:
3904
+ promptbookMarkdown = (_c.sent());
3905
+ _c.label = 5;
3906
+ case 5:
3907
+ _c.trys.push([5, 8, , 9]);
3908
+ return [4 /*yield*/, prettifyPromptbookString(promptbookMarkdown, {
3909
+ isGraphAdded: true,
3910
+ isPrettifyed: true,
3911
+ // <- [🕌]
3912
+ })];
3913
+ case 6:
3914
+ promptbookMarkdown = _c.sent();
3915
+ return [4 /*yield*/, writeFile(filePath, promptbookMarkdown)];
3916
+ case 7:
3917
+ _c.sent();
3918
+ console.info(colors.green("Prettify ".concat(filePath)));
3919
+ return [3 /*break*/, 9];
3920
+ case 8:
3921
+ error_1 = _c.sent();
3922
+ if (!(error_1 instanceof Error)) {
3923
+ throw error_1;
3924
+ }
3925
+ console.info(colors.red("Prettify ".concat(error_1.name, " ").concat(filePath)));
3926
+ console.error(colors.bgRed(error_1.name));
3927
+ console.error(error_1);
3928
+ process.exit(1);
3929
+ return [3 /*break*/, 9];
3930
+ case 9:
3931
+ filePaths_1_1 = filePaths_1.next();
3932
+ return [3 /*break*/, 3];
3933
+ case 10: return [3 /*break*/, 13];
3934
+ case 11:
3935
+ e_1_1 = _c.sent();
3936
+ e_1 = { error: e_1_1 };
3937
+ return [3 /*break*/, 13];
3938
+ case 12:
3939
+ try {
3940
+ if (filePaths_1_1 && !filePaths_1_1.done && (_b = filePaths_1.return)) _b.call(filePaths_1);
3941
+ }
3942
+ finally { if (e_1) throw e_1.error; }
3943
+ return [7 /*endfinally*/];
3944
+ case 13:
3945
+ process.exit(0);
3946
+ return [2 /*return*/];
3947
+ }
3948
+ });
3949
+ });
3950
+ });
3951
+ }
3952
+
3953
+ /**
3954
+ * Runs CLI utilities of Promptbook package
1822
3955
  */
1823
- function prettifyPromptbookStringCli() {
3956
+ function promptbookCli() {
1824
3957
  return __awaiter(this, void 0, void 0, function () {
1825
- var program, prettifyCommand, helloCommand;
1826
- var _this = this;
3958
+ var program;
1827
3959
  return __generator(this, function (_a) {
1828
3960
  if (!isRunningInNode()) {
1829
- throw new Error(spaceTrim("\n Function prettifyPromptbookStringCli is initiator of CLI script and should be run in Node.js environment.\n\n - In browser use prettifyPromptbookString.\n\n "));
3961
+ throw new Error(spaceTrim$1("\n Function promptbookCli is initiator of CLI script and should be run in Node.js environment.\n\n - In browser use function exported from `@promptbook/utils` or `@promptbook/core` directly, for example `prettifyPromptbookString`.\n\n "));
1830
3962
  }
1831
3963
  program = new commander.Command();
1832
3964
  program.name('promptbook');
1833
3965
  program.version(PROMPTBOOK_VERSION);
1834
- program.description(spaceTrim("\n Promptbook utilities\n "));
1835
- prettifyCommand = program.command('prettify');
1836
- prettifyCommand.description(spaceTrim("\n Iterates over promptbooks and does multiple enhancing operations on them:\n 1) Adds Mermaid graph\n 2) Prettifies the markdown\n "));
1837
- prettifyCommand.argument('<filesGlob>', 'Promptbooks to prettify as glob pattern');
1838
- prettifyCommand.option('-i, --ignore <glob>', "Ignore as glob pattern");
1839
- prettifyCommand.action(function (filesGlob, _a) {
1840
- var ignore = _a.ignore;
1841
- return __awaiter(_this, void 0, void 0, function () {
1842
- var filePaths, filePaths_1, filePaths_1_1, filePath, promptbookMarkdown, error_1, e_1_1;
1843
- var e_1, _b;
1844
- return __generator(this, function (_c) {
1845
- switch (_c.label) {
1846
- case 0: return [4 /*yield*/, glob(filesGlob, { ignore: ignore })];
1847
- case 1:
1848
- filePaths = _c.sent();
1849
- _c.label = 2;
1850
- case 2:
1851
- _c.trys.push([2, 11, 12, 13]);
1852
- filePaths_1 = __values(filePaths), filePaths_1_1 = filePaths_1.next();
1853
- _c.label = 3;
1854
- case 3:
1855
- if (!!filePaths_1_1.done) return [3 /*break*/, 10];
1856
- filePath = filePaths_1_1.value;
1857
- if (!filePath.endsWith('.ptbk.md')) {
1858
- console.warn(colors.yellow("Skipping prettify of non-promptbook ".concat(filePath)));
1859
- return [3 /*break*/, 9];
1860
- }
1861
- return [4 /*yield*/, readFile(filePath, 'utf-8')];
1862
- case 4:
1863
- promptbookMarkdown = (_c.sent());
1864
- _c.label = 5;
1865
- case 5:
1866
- _c.trys.push([5, 8, , 9]);
1867
- return [4 /*yield*/, prettifyPromptbookString(promptbookMarkdown, {
1868
- isGraphAdded: true,
1869
- isPrettifyed: true,
1870
- // <- [🕌]
1871
- })];
1872
- case 6:
1873
- promptbookMarkdown = _c.sent();
1874
- return [4 /*yield*/, writeFile(filePath, promptbookMarkdown)];
1875
- case 7:
1876
- _c.sent();
1877
- console.info(colors.green("Prettify ".concat(filePath)));
1878
- return [3 /*break*/, 9];
1879
- case 8:
1880
- error_1 = _c.sent();
1881
- if (!(error_1 instanceof Error)) {
1882
- throw error_1;
1883
- }
1884
- console.info(colors.red("Prettify ".concat(error_1.name, " ").concat(filePath)));
1885
- console.error(colors.bgRed(error_1.name));
1886
- console.error(error_1);
1887
- process.exit(1);
1888
- return [3 /*break*/, 9];
1889
- case 9:
1890
- filePaths_1_1 = filePaths_1.next();
1891
- return [3 /*break*/, 3];
1892
- case 10: return [3 /*break*/, 13];
1893
- case 11:
1894
- e_1_1 = _c.sent();
1895
- e_1 = { error: e_1_1 };
1896
- return [3 /*break*/, 13];
1897
- case 12:
1898
- try {
1899
- if (filePaths_1_1 && !filePaths_1_1.done && (_b = filePaths_1.return)) _b.call(filePaths_1);
1900
- }
1901
- finally { if (e_1) throw e_1.error; }
1902
- return [7 /*endfinally*/];
1903
- case 13:
1904
- process.exit(0);
1905
- return [2 /*return*/];
1906
- }
1907
- });
1908
- });
1909
- });
1910
- helloCommand = program.command('hello');
1911
- helloCommand.description(spaceTrim("\n Just command for testing\n "));
1912
- helloCommand.argument('<name>', 'Your name');
1913
- helloCommand.option('-g, --greeting <greeting>', "Greeting", 'Hello');
1914
- helloCommand.action(function (name, _a) {
1915
- var greeting = _a.greeting;
1916
- return __awaiter(_this, void 0, void 0, function () {
1917
- return __generator(this, function (_b) {
1918
- switch (_b.label) {
1919
- case 0:
1920
- console.info(colors.cyan("".concat(greeting, " ").concat(name)));
1921
- return [4 /*yield*/, forTime(1000)];
1922
- case 1:
1923
- _b.sent();
1924
- console.info(colors.rainbow("Nice to meet you!"));
1925
- process.exit(0);
1926
- return [2 /*return*/];
1927
- }
1928
- });
1929
- });
1930
- });
1931
- //------
3966
+ program.description(spaceTrim$1("\n Promptbook utilities for enhancing workflow with promptbooks\n "));
3967
+ initializeHello(program);
3968
+ initializeMake(program);
3969
+ initializePrettify(program);
1932
3970
  program.parse(process.argv);
1933
3971
  return [2 /*return*/];
1934
3972
  });
@@ -1944,10 +3982,10 @@ function prettifyPromptbookStringCli() {
1944
3982
  /**
1945
3983
  * Hidden utilities which should not be used by external consumers.
1946
3984
  */
1947
- var __ = {
3985
+ var __CLI = {
1948
3986
  // Note: [🥠]
1949
- prettifyPromptbookStringCli: prettifyPromptbookStringCli,
3987
+ __initialize: promptbookCli,
1950
3988
  };
1951
3989
 
1952
- export { PROMPTBOOK_VERSION, __ };
3990
+ export { PROMPTBOOK_VERSION, __CLI };
1953
3991
  //# sourceMappingURL=index.es.js.map