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