@promptbook/utils 0.41.4 → 0.41.102

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 (360) hide show
  1. package/bin/promptbook-cli.js +6 -0
  2. package/esm/index.es.js +1719 -1681
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/_packages/core.index.d.ts +20 -20
  5. package/esm/typings/_packages/execute-javascript.index.d.ts +3 -3
  6. package/esm/typings/_packages/openai.index.d.ts +3 -3
  7. package/esm/typings/_packages/remote-client.index.d.ts +4 -4
  8. package/esm/typings/_packages/remote-server.index.d.ts +3 -3
  9. package/esm/typings/_packages/types.index.d.ts +27 -27
  10. package/esm/typings/_packages/utils.index.d.ts +38 -38
  11. package/esm/typings/_packages/wizzard.index.d.ts +5 -5
  12. package/esm/typings/config.d.ts +4 -4
  13. package/esm/typings/conversion/prettify/PrettifyOptions.d.ts +7 -7
  14. package/esm/typings/conversion/prettify/prettifyPromptbookString.d.ts +11 -10
  15. package/esm/typings/conversion/prettify/prettifyPromptbookStringCli.d.ts +9 -9
  16. package/esm/typings/conversion/promptbookStringToJson.d.ts +13 -13
  17. package/esm/typings/conversion/test/_importPromptbook.d.ts +12 -12
  18. package/esm/typings/conversion/test/promptbookStringToJson-syntaxErrors.test.d.ts +1 -1
  19. package/esm/typings/conversion/test/promptbookStringToJson.test.d.ts +1 -1
  20. package/esm/typings/conversion/test/validatePromptbookJson-logicErrors.test.d.ts +1 -1
  21. package/esm/typings/conversion/test/validatePromptbookJson.d.ts +26 -26
  22. package/esm/typings/conversion/test/validatePromptbookJson.test.d.ts +1 -1
  23. package/esm/typings/conversion/utils/extractVariables.d.ts +10 -10
  24. package/esm/typings/conversion/utils/extractVariables.test.d.ts +1 -1
  25. package/esm/typings/conversion/utils/parseCommand.d.ts +8 -8
  26. package/esm/typings/conversion/utils/parseCommand.test.d.ts +4 -4
  27. package/esm/typings/conversion/utils/parseNumber.d.ts +12 -12
  28. package/esm/typings/conversion/utils/parseNumber.test.d.ts +1 -1
  29. package/esm/typings/errors/ExpectError.d.ts +9 -9
  30. package/esm/typings/errors/NotFoundError.d.ts +7 -7
  31. package/esm/typings/errors/PromptbookExecutionError.d.ts +7 -7
  32. package/esm/typings/errors/PromptbookLogicError.d.ts +7 -7
  33. package/esm/typings/errors/PromptbookReferenceError.d.ts +7 -7
  34. package/esm/typings/errors/PromptbookSyntaxError.d.ts +7 -7
  35. package/esm/typings/errors/UnexpectedError.d.ts +7 -7
  36. package/esm/typings/execution/CommonExecutionToolsOptions.d.ts +9 -9
  37. package/esm/typings/execution/ExecutionTools.d.ts +25 -25
  38. package/esm/typings/execution/NaturalExecutionTools.d.ts +23 -23
  39. package/esm/typings/execution/PromptResult.d.ts +74 -74
  40. package/esm/typings/execution/PromptbookExecutor.d.ts +39 -39
  41. package/esm/typings/execution/ScriptExecutionTools.d.ts +37 -37
  42. package/esm/typings/execution/UserInterfaceTools.d.ts +45 -45
  43. package/esm/typings/execution/assertsExecutionSuccessful.d.ts +11 -11
  44. package/esm/typings/execution/createPromptbookExecutor.d.ts +41 -41
  45. package/esm/typings/execution/plugins/natural-execution-tools/mocked/MockedEchoNaturalExecutionTools.d.ts +22 -22
  46. package/esm/typings/execution/plugins/natural-execution-tools/mocked/joker.test.d.ts +4 -4
  47. package/esm/typings/execution/plugins/natural-execution-tools/mocked/mocked-chat.test.d.ts +4 -4
  48. package/esm/typings/execution/plugins/natural-execution-tools/mocked/mocked-completion.test.d.ts +4 -4
  49. package/esm/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionTools.d.ts +28 -28
  50. package/esm/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +16 -16
  51. package/esm/typings/execution/plugins/natural-execution-tools/openai/computeOpenaiUsage.d.ts +3 -3
  52. package/esm/typings/execution/plugins/natural-execution-tools/remote/RemoteNaturalExecutionTools.d.ts +35 -35
  53. package/esm/typings/execution/plugins/natural-execution-tools/remote/RemoteNaturalExecutionToolsOptions.d.ts +23 -23
  54. package/esm/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Error.d.ts +11 -11
  55. package/esm/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Progress.d.ts +12 -12
  56. package/esm/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Request.d.ts +17 -17
  57. package/esm/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Response.d.ts +12 -12
  58. package/esm/typings/execution/plugins/natural-execution-tools/remote/interfaces/RemoteServerOptions.d.ts +27 -27
  59. package/esm/typings/execution/plugins/natural-execution-tools/remote/startRemoteServer.d.ts +17 -17
  60. package/esm/typings/execution/plugins/script-execution-tools/custom-function-async.test.ts.test.d.ts +1 -1
  61. package/esm/typings/execution/plugins/script-execution-tools/custom-function-missing.test.d.ts +1 -1
  62. package/esm/typings/execution/plugins/script-execution-tools/custom-function-with-dependencies.test.d.ts +1 -1
  63. package/esm/typings/execution/plugins/script-execution-tools/custom-function.test.d.ts +1 -1
  64. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.d.ts +20 -20
  65. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.test.d.ts +4 -4
  66. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionTools.d.ts +20 -20
  67. package/esm/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions.d.ts +22 -22
  68. package/esm/typings/execution/plugins/script-execution-tools/javascript/utils/preserve.d.ts +11 -11
  69. package/esm/typings/execution/plugins/script-execution-tools/postprocessing.test.d.ts +1 -1
  70. package/esm/typings/execution/plugins/script-execution-tools/python/PythonExecutionTools.d.ts +15 -15
  71. package/esm/typings/execution/plugins/script-execution-tools/script-execution-errors.test.d.ts +1 -1
  72. package/esm/typings/execution/plugins/script-execution-tools/script-execution-tools.test.d.ts +1 -1
  73. package/esm/typings/execution/plugins/script-execution-tools/typescript/TypescriptExecutionTools.d.ts +15 -15
  74. package/esm/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceTools.d.ts +14 -14
  75. package/esm/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceToolsOptions.d.ts +12 -12
  76. package/esm/typings/execution/plugins/user-interface-execution-tools/simple-prompt/SimplePromptInterfaceTools.d.ts +16 -16
  77. package/esm/typings/execution/plugins/user-interface-execution-tools/user-interface-execution-tools.test.d.ts +1 -1
  78. package/esm/typings/execution/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +4 -4
  79. package/esm/typings/execution/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +9 -9
  80. package/esm/typings/execution/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +5 -5
  81. package/esm/typings/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +11 -11
  82. package/esm/typings/execution/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +4 -4
  83. package/esm/typings/execution/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +1 -1
  84. package/esm/typings/execution/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +1 -1
  85. package/esm/typings/execution/translation/automatic-translate/translateMessages.d.ts +5 -5
  86. package/esm/typings/execution/utils/replaceParameters.d.ts +12 -12
  87. package/esm/typings/execution/utils/replaceParameters.test.d.ts +1 -1
  88. package/esm/typings/library/PromptbookLibrary.d.ts +25 -25
  89. package/esm/typings/library/SimplePromptbookLibrary.d.ts +35 -35
  90. package/esm/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +5 -5
  91. package/esm/typings/library/constructors/createPromptbookLibraryFromList.d.ts +5 -5
  92. package/esm/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +7 -7
  93. package/esm/typings/library/constructors/createPromptbookLibraryFromSources.d.ts +16 -16
  94. package/esm/typings/library/constructors/createPromptbookSublibrary.d.ts +6 -6
  95. package/esm/typings/types/Command.d.ts +98 -98
  96. package/esm/typings/types/ExecutionTypes.d.ts +13 -13
  97. package/esm/typings/types/ModelRequirements.d.ts +41 -41
  98. package/esm/typings/types/Parameters.d.ts +14 -14
  99. package/esm/typings/types/Prompt.d.ts +41 -41
  100. package/esm/typings/types/PromptbookJson/PromptTemplateJson.d.ts +126 -126
  101. package/esm/typings/types/PromptbookJson/PromptTemplateParameterJson.d.ts +25 -25
  102. package/esm/typings/types/PromptbookJson/PromptbookJson.d.ts +51 -51
  103. package/esm/typings/types/PromptbookString.d.ts +12 -12
  104. package/esm/typings/types/ScriptLanguage.d.ts +9 -9
  105. package/esm/typings/types/TaskProgress.d.ts +42 -42
  106. package/esm/typings/types/execution-report/ExecutionReportJson.d.ts +56 -56
  107. package/esm/typings/types/execution-report/ExecutionReportString.d.ts +16 -16
  108. package/esm/typings/types/execution-report/ExecutionReportStringOptions.d.ts +21 -21
  109. package/esm/typings/types/execution-report/config.d.ts +8 -8
  110. package/esm/typings/types/execution-report/countWorkingDuration.d.ts +7 -7
  111. package/esm/typings/types/execution-report/countWorkingDuration.test.d.ts +1 -1
  112. package/esm/typings/types/execution-report/executionReportJsonToString.d.ts +11 -11
  113. package/esm/typings/types/execution-report/executionReportJsonToString.test.d.ts +1 -1
  114. package/esm/typings/types/typeAliasEmoji.d.ts +9 -9
  115. package/esm/typings/types/typeAliases.d.ts +432 -432
  116. package/esm/typings/utils/FromtoItems.d.ts +19 -19
  117. package/esm/typings/utils/emojis.d.ts +22 -22
  118. package/esm/typings/utils/expectation-counters/countCharacters.d.ts +5 -5
  119. package/esm/typings/utils/expectation-counters/countCharacters.test.d.ts +1 -1
  120. package/esm/typings/utils/expectation-counters/countLines.d.ts +5 -5
  121. package/esm/typings/utils/expectation-counters/countLines.test.d.ts +1 -1
  122. package/esm/typings/utils/expectation-counters/countPages.d.ts +5 -5
  123. package/esm/typings/utils/expectation-counters/countPages.test.d.ts +1 -1
  124. package/esm/typings/utils/expectation-counters/countParagraphs.d.ts +5 -5
  125. package/esm/typings/utils/expectation-counters/countParagraphs.test.d.ts +1 -1
  126. package/esm/typings/utils/expectation-counters/countSentences.d.ts +5 -5
  127. package/esm/typings/utils/expectation-counters/countSentences.test.d.ts +1 -1
  128. package/esm/typings/utils/expectation-counters/countWords.d.ts +5 -5
  129. package/esm/typings/utils/expectation-counters/countWords.test.d.ts +1 -1
  130. package/esm/typings/utils/expectation-counters/index.d.ts +5 -5
  131. package/esm/typings/utils/extractParameters.d.ts +10 -10
  132. package/esm/typings/utils/extractParameters.test.d.ts +1 -1
  133. package/esm/typings/utils/formatNumber.d.ts +6 -6
  134. package/esm/typings/utils/formatNumber.test.d.ts +1 -1
  135. package/esm/typings/utils/getCurrentIsoDate.d.ts +7 -7
  136. package/esm/typings/utils/isRunningInWhatever.d.ts +12 -12
  137. package/esm/typings/utils/isValidJsonString.d.ts +4 -4
  138. package/esm/typings/utils/isValidJsonString.test.d.ts +1 -1
  139. package/esm/typings/utils/just.d.ts +10 -10
  140. package/esm/typings/utils/markdown/addAutoGeneratedSection.d.ts +10 -10
  141. package/esm/typings/utils/markdown/addAutoGeneratedSection.test.d.ts +1 -1
  142. package/esm/typings/utils/markdown/createMarkdownChart.d.ts +41 -41
  143. package/esm/typings/utils/markdown/createMarkdownChart.test.d.ts +1 -1
  144. package/esm/typings/utils/markdown/createMarkdownTable.d.ts +7 -7
  145. package/esm/typings/utils/markdown/createMarkdownTable.test.d.ts +1 -1
  146. package/esm/typings/utils/markdown/escapeMarkdownBlock.d.ts +6 -6
  147. package/esm/typings/utils/markdown/escapeMarkdownBlock.test.d.ts +1 -1
  148. package/esm/typings/utils/markdown/extractAllBlocksFromMarkdown.d.ts +27 -27
  149. package/esm/typings/utils/markdown/extractAllBlocksFromMarkdown.test.d.ts +1 -1
  150. package/esm/typings/utils/markdown/extractAllListItemsFromMarkdown.d.ts +13 -13
  151. package/esm/typings/utils/markdown/extractAllListItemsFromMarkdown.test.d.ts +1 -1
  152. package/esm/typings/utils/markdown/extractOneBlockFromMarkdown.d.ts +19 -19
  153. package/esm/typings/utils/markdown/extractOneBlockFromMarkdown.test.d.ts +1 -1
  154. package/esm/typings/utils/markdown/prettifyMarkdown.d.ts +8 -8
  155. package/esm/typings/utils/markdown/prettifyMarkdown.test.d.ts +1 -1
  156. package/esm/typings/utils/markdown/removeContentComments.d.ts +8 -8
  157. package/esm/typings/utils/markdown/removeContentComments.test.d.ts +1 -1
  158. package/esm/typings/utils/markdown/removeMarkdownFormatting.d.ts +8 -8
  159. package/esm/typings/utils/markdown/removeMarkdownFormatting.test.d.ts +1 -1
  160. package/esm/typings/utils/markdown-json/MarkdownStructure.d.ts +25 -25
  161. package/esm/typings/utils/markdown-json/countMarkdownStructureDeepness.d.ts +7 -7
  162. package/esm/typings/utils/markdown-json/countMarkdownStructureDeepness.test.d.ts +1 -1
  163. package/esm/typings/utils/markdown-json/markdownToMarkdownStructure.d.ts +13 -13
  164. package/esm/typings/utils/markdown-json/markdownToMarkdownStructure.test.d.ts +1 -1
  165. package/esm/typings/utils/postprocessing/extractBlock.d.ts +12 -12
  166. package/esm/typings/utils/removeEmojis.d.ts +7 -7
  167. package/esm/typings/utils/removeEmojis.test.d.ts +1 -1
  168. package/esm/typings/utils/removeQuotes.d.ts +13 -13
  169. package/esm/typings/utils/removeQuotes.test.d.ts +1 -1
  170. package/esm/typings/utils/trimCodeBlock.d.ts +8 -8
  171. package/esm/typings/utils/trimCodeBlock.test.d.ts +1 -1
  172. package/esm/typings/utils/trimEndOfCodeBlock.d.ts +7 -7
  173. package/esm/typings/utils/trimEndOfCodeBlock.test.d.ts +1 -1
  174. package/esm/typings/utils/unwrapResult.d.ts +36 -36
  175. package/esm/typings/utils/unwrapResult.test.d.ts +1 -1
  176. package/esm/typings/utils/validators/url/isValidUrl.d.ts +7 -7
  177. package/esm/typings/utils/validators/url/isValidUrl.test.d.ts +1 -1
  178. package/esm/typings/version.d.ts +5 -5
  179. package/esm/typings/wizzard/Wizzard.d.ts +4 -4
  180. package/esm/typings/wizzard/sample.d.ts +6 -6
  181. package/package.json +9 -7
  182. package/umd/index.umd.js +1722 -1685
  183. package/umd/index.umd.js.map +1 -1
  184. package/umd/typings/_packages/core.index.d.ts +20 -20
  185. package/umd/typings/_packages/execute-javascript.index.d.ts +3 -3
  186. package/umd/typings/_packages/openai.index.d.ts +3 -3
  187. package/umd/typings/_packages/remote-client.index.d.ts +4 -4
  188. package/umd/typings/_packages/remote-server.index.d.ts +3 -3
  189. package/umd/typings/_packages/types.index.d.ts +27 -27
  190. package/umd/typings/_packages/utils.index.d.ts +38 -38
  191. package/umd/typings/_packages/wizzard.index.d.ts +5 -5
  192. package/umd/typings/config.d.ts +4 -4
  193. package/umd/typings/conversion/prettify/PrettifyOptions.d.ts +7 -7
  194. package/umd/typings/conversion/prettify/prettifyPromptbookString.d.ts +11 -10
  195. package/umd/typings/conversion/prettify/prettifyPromptbookStringCli.d.ts +9 -9
  196. package/umd/typings/conversion/promptbookStringToJson.d.ts +13 -13
  197. package/umd/typings/conversion/test/_importPromptbook.d.ts +12 -12
  198. package/umd/typings/conversion/test/promptbookStringToJson-syntaxErrors.test.d.ts +1 -1
  199. package/umd/typings/conversion/test/promptbookStringToJson.test.d.ts +1 -1
  200. package/umd/typings/conversion/test/validatePromptbookJson-logicErrors.test.d.ts +1 -1
  201. package/umd/typings/conversion/test/validatePromptbookJson.d.ts +26 -26
  202. package/umd/typings/conversion/test/validatePromptbookJson.test.d.ts +1 -1
  203. package/umd/typings/conversion/utils/extractVariables.d.ts +10 -10
  204. package/umd/typings/conversion/utils/extractVariables.test.d.ts +1 -1
  205. package/umd/typings/conversion/utils/parseCommand.d.ts +8 -8
  206. package/umd/typings/conversion/utils/parseCommand.test.d.ts +4 -4
  207. package/umd/typings/conversion/utils/parseNumber.d.ts +12 -12
  208. package/umd/typings/conversion/utils/parseNumber.test.d.ts +1 -1
  209. package/umd/typings/errors/ExpectError.d.ts +9 -9
  210. package/umd/typings/errors/NotFoundError.d.ts +7 -7
  211. package/umd/typings/errors/PromptbookExecutionError.d.ts +7 -7
  212. package/umd/typings/errors/PromptbookLogicError.d.ts +7 -7
  213. package/umd/typings/errors/PromptbookReferenceError.d.ts +7 -7
  214. package/umd/typings/errors/PromptbookSyntaxError.d.ts +7 -7
  215. package/umd/typings/errors/UnexpectedError.d.ts +7 -7
  216. package/umd/typings/execution/CommonExecutionToolsOptions.d.ts +9 -9
  217. package/umd/typings/execution/ExecutionTools.d.ts +25 -25
  218. package/umd/typings/execution/NaturalExecutionTools.d.ts +23 -23
  219. package/umd/typings/execution/PromptResult.d.ts +74 -74
  220. package/umd/typings/execution/PromptbookExecutor.d.ts +39 -39
  221. package/umd/typings/execution/ScriptExecutionTools.d.ts +37 -37
  222. package/umd/typings/execution/UserInterfaceTools.d.ts +45 -45
  223. package/umd/typings/execution/assertsExecutionSuccessful.d.ts +11 -11
  224. package/umd/typings/execution/createPromptbookExecutor.d.ts +41 -41
  225. package/umd/typings/execution/plugins/natural-execution-tools/mocked/MockedEchoNaturalExecutionTools.d.ts +22 -22
  226. package/umd/typings/execution/plugins/natural-execution-tools/mocked/joker.test.d.ts +4 -4
  227. package/umd/typings/execution/plugins/natural-execution-tools/mocked/mocked-chat.test.d.ts +4 -4
  228. package/umd/typings/execution/plugins/natural-execution-tools/mocked/mocked-completion.test.d.ts +4 -4
  229. package/umd/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionTools.d.ts +28 -28
  230. package/umd/typings/execution/plugins/natural-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +16 -16
  231. package/umd/typings/execution/plugins/natural-execution-tools/openai/computeOpenaiUsage.d.ts +3 -3
  232. package/umd/typings/execution/plugins/natural-execution-tools/remote/RemoteNaturalExecutionTools.d.ts +35 -35
  233. package/umd/typings/execution/plugins/natural-execution-tools/remote/RemoteNaturalExecutionToolsOptions.d.ts +23 -23
  234. package/umd/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Error.d.ts +11 -11
  235. package/umd/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Progress.d.ts +12 -12
  236. package/umd/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Request.d.ts +17 -17
  237. package/umd/typings/execution/plugins/natural-execution-tools/remote/interfaces/Promptbook_Server_Response.d.ts +12 -12
  238. package/umd/typings/execution/plugins/natural-execution-tools/remote/interfaces/RemoteServerOptions.d.ts +27 -27
  239. package/umd/typings/execution/plugins/natural-execution-tools/remote/startRemoteServer.d.ts +17 -17
  240. package/umd/typings/execution/plugins/script-execution-tools/custom-function-async.test.ts.test.d.ts +1 -1
  241. package/umd/typings/execution/plugins/script-execution-tools/custom-function-missing.test.d.ts +1 -1
  242. package/umd/typings/execution/plugins/script-execution-tools/custom-function-with-dependencies.test.d.ts +1 -1
  243. package/umd/typings/execution/plugins/script-execution-tools/custom-function.test.d.ts +1 -1
  244. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.d.ts +20 -20
  245. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptEvalExecutionTools.test.d.ts +4 -4
  246. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionTools.d.ts +20 -20
  247. package/umd/typings/execution/plugins/script-execution-tools/javascript/JavascriptExecutionToolsOptions.d.ts +22 -22
  248. package/umd/typings/execution/plugins/script-execution-tools/javascript/utils/preserve.d.ts +11 -11
  249. package/umd/typings/execution/plugins/script-execution-tools/postprocessing.test.d.ts +1 -1
  250. package/umd/typings/execution/plugins/script-execution-tools/python/PythonExecutionTools.d.ts +15 -15
  251. package/umd/typings/execution/plugins/script-execution-tools/script-execution-errors.test.d.ts +1 -1
  252. package/umd/typings/execution/plugins/script-execution-tools/script-execution-tools.test.d.ts +1 -1
  253. package/umd/typings/execution/plugins/script-execution-tools/typescript/TypescriptExecutionTools.d.ts +15 -15
  254. package/umd/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceTools.d.ts +14 -14
  255. package/umd/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceToolsOptions.d.ts +12 -12
  256. package/umd/typings/execution/plugins/user-interface-execution-tools/simple-prompt/SimplePromptInterfaceTools.d.ts +16 -16
  257. package/umd/typings/execution/plugins/user-interface-execution-tools/user-interface-execution-tools.test.d.ts +1 -1
  258. package/umd/typings/execution/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +4 -4
  259. package/umd/typings/execution/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +9 -9
  260. package/umd/typings/execution/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +5 -5
  261. package/umd/typings/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +11 -11
  262. package/umd/typings/execution/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +4 -4
  263. package/umd/typings/execution/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +1 -1
  264. package/umd/typings/execution/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +1 -1
  265. package/umd/typings/execution/translation/automatic-translate/translateMessages.d.ts +5 -5
  266. package/umd/typings/execution/utils/replaceParameters.d.ts +12 -12
  267. package/umd/typings/execution/utils/replaceParameters.test.d.ts +1 -1
  268. package/umd/typings/library/PromptbookLibrary.d.ts +25 -25
  269. package/umd/typings/library/SimplePromptbookLibrary.d.ts +35 -35
  270. package/umd/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +5 -5
  271. package/umd/typings/library/constructors/createPromptbookLibraryFromList.d.ts +5 -5
  272. package/umd/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +7 -7
  273. package/umd/typings/library/constructors/createPromptbookLibraryFromSources.d.ts +16 -16
  274. package/umd/typings/library/constructors/createPromptbookSublibrary.d.ts +6 -6
  275. package/umd/typings/types/Command.d.ts +98 -98
  276. package/umd/typings/types/ExecutionTypes.d.ts +13 -13
  277. package/umd/typings/types/ModelRequirements.d.ts +41 -41
  278. package/umd/typings/types/Parameters.d.ts +14 -14
  279. package/umd/typings/types/Prompt.d.ts +41 -41
  280. package/umd/typings/types/PromptbookJson/PromptTemplateJson.d.ts +126 -126
  281. package/umd/typings/types/PromptbookJson/PromptTemplateParameterJson.d.ts +25 -25
  282. package/umd/typings/types/PromptbookJson/PromptbookJson.d.ts +51 -51
  283. package/umd/typings/types/PromptbookString.d.ts +12 -12
  284. package/umd/typings/types/ScriptLanguage.d.ts +9 -9
  285. package/umd/typings/types/TaskProgress.d.ts +42 -42
  286. package/umd/typings/types/execution-report/ExecutionReportJson.d.ts +56 -56
  287. package/umd/typings/types/execution-report/ExecutionReportString.d.ts +16 -16
  288. package/umd/typings/types/execution-report/ExecutionReportStringOptions.d.ts +21 -21
  289. package/umd/typings/types/execution-report/config.d.ts +8 -8
  290. package/umd/typings/types/execution-report/countWorkingDuration.d.ts +7 -7
  291. package/umd/typings/types/execution-report/countWorkingDuration.test.d.ts +1 -1
  292. package/umd/typings/types/execution-report/executionReportJsonToString.d.ts +11 -11
  293. package/umd/typings/types/execution-report/executionReportJsonToString.test.d.ts +1 -1
  294. package/umd/typings/types/typeAliasEmoji.d.ts +9 -9
  295. package/umd/typings/types/typeAliases.d.ts +432 -432
  296. package/umd/typings/utils/FromtoItems.d.ts +19 -19
  297. package/umd/typings/utils/emojis.d.ts +22 -22
  298. package/umd/typings/utils/expectation-counters/countCharacters.d.ts +5 -5
  299. package/umd/typings/utils/expectation-counters/countCharacters.test.d.ts +1 -1
  300. package/umd/typings/utils/expectation-counters/countLines.d.ts +5 -5
  301. package/umd/typings/utils/expectation-counters/countLines.test.d.ts +1 -1
  302. package/umd/typings/utils/expectation-counters/countPages.d.ts +5 -5
  303. package/umd/typings/utils/expectation-counters/countPages.test.d.ts +1 -1
  304. package/umd/typings/utils/expectation-counters/countParagraphs.d.ts +5 -5
  305. package/umd/typings/utils/expectation-counters/countParagraphs.test.d.ts +1 -1
  306. package/umd/typings/utils/expectation-counters/countSentences.d.ts +5 -5
  307. package/umd/typings/utils/expectation-counters/countSentences.test.d.ts +1 -1
  308. package/umd/typings/utils/expectation-counters/countWords.d.ts +5 -5
  309. package/umd/typings/utils/expectation-counters/countWords.test.d.ts +1 -1
  310. package/umd/typings/utils/expectation-counters/index.d.ts +5 -5
  311. package/umd/typings/utils/extractParameters.d.ts +10 -10
  312. package/umd/typings/utils/extractParameters.test.d.ts +1 -1
  313. package/umd/typings/utils/formatNumber.d.ts +6 -6
  314. package/umd/typings/utils/formatNumber.test.d.ts +1 -1
  315. package/umd/typings/utils/getCurrentIsoDate.d.ts +7 -7
  316. package/umd/typings/utils/isRunningInWhatever.d.ts +12 -12
  317. package/umd/typings/utils/isValidJsonString.d.ts +4 -4
  318. package/umd/typings/utils/isValidJsonString.test.d.ts +1 -1
  319. package/umd/typings/utils/just.d.ts +10 -10
  320. package/umd/typings/utils/markdown/addAutoGeneratedSection.d.ts +10 -10
  321. package/umd/typings/utils/markdown/addAutoGeneratedSection.test.d.ts +1 -1
  322. package/umd/typings/utils/markdown/createMarkdownChart.d.ts +41 -41
  323. package/umd/typings/utils/markdown/createMarkdownChart.test.d.ts +1 -1
  324. package/umd/typings/utils/markdown/createMarkdownTable.d.ts +7 -7
  325. package/umd/typings/utils/markdown/createMarkdownTable.test.d.ts +1 -1
  326. package/umd/typings/utils/markdown/escapeMarkdownBlock.d.ts +6 -6
  327. package/umd/typings/utils/markdown/escapeMarkdownBlock.test.d.ts +1 -1
  328. package/umd/typings/utils/markdown/extractAllBlocksFromMarkdown.d.ts +27 -27
  329. package/umd/typings/utils/markdown/extractAllBlocksFromMarkdown.test.d.ts +1 -1
  330. package/umd/typings/utils/markdown/extractAllListItemsFromMarkdown.d.ts +13 -13
  331. package/umd/typings/utils/markdown/extractAllListItemsFromMarkdown.test.d.ts +1 -1
  332. package/umd/typings/utils/markdown/extractOneBlockFromMarkdown.d.ts +19 -19
  333. package/umd/typings/utils/markdown/extractOneBlockFromMarkdown.test.d.ts +1 -1
  334. package/umd/typings/utils/markdown/prettifyMarkdown.d.ts +8 -8
  335. package/umd/typings/utils/markdown/prettifyMarkdown.test.d.ts +1 -1
  336. package/umd/typings/utils/markdown/removeContentComments.d.ts +8 -8
  337. package/umd/typings/utils/markdown/removeContentComments.test.d.ts +1 -1
  338. package/umd/typings/utils/markdown/removeMarkdownFormatting.d.ts +8 -8
  339. package/umd/typings/utils/markdown/removeMarkdownFormatting.test.d.ts +1 -1
  340. package/umd/typings/utils/markdown-json/MarkdownStructure.d.ts +25 -25
  341. package/umd/typings/utils/markdown-json/countMarkdownStructureDeepness.d.ts +7 -7
  342. package/umd/typings/utils/markdown-json/countMarkdownStructureDeepness.test.d.ts +1 -1
  343. package/umd/typings/utils/markdown-json/markdownToMarkdownStructure.d.ts +13 -13
  344. package/umd/typings/utils/markdown-json/markdownToMarkdownStructure.test.d.ts +1 -1
  345. package/umd/typings/utils/postprocessing/extractBlock.d.ts +12 -12
  346. package/umd/typings/utils/removeEmojis.d.ts +7 -7
  347. package/umd/typings/utils/removeEmojis.test.d.ts +1 -1
  348. package/umd/typings/utils/removeQuotes.d.ts +13 -13
  349. package/umd/typings/utils/removeQuotes.test.d.ts +1 -1
  350. package/umd/typings/utils/trimCodeBlock.d.ts +8 -8
  351. package/umd/typings/utils/trimCodeBlock.test.d.ts +1 -1
  352. package/umd/typings/utils/trimEndOfCodeBlock.d.ts +7 -7
  353. package/umd/typings/utils/trimEndOfCodeBlock.test.d.ts +1 -1
  354. package/umd/typings/utils/unwrapResult.d.ts +36 -36
  355. package/umd/typings/utils/unwrapResult.test.d.ts +1 -1
  356. package/umd/typings/utils/validators/url/isValidUrl.d.ts +7 -7
  357. package/umd/typings/utils/validators/url/isValidUrl.test.d.ts +1 -1
  358. package/umd/typings/version.d.ts +5 -5
  359. package/umd/typings/wizzard/Wizzard.d.ts +4 -4
  360. package/umd/typings/wizzard/sample.d.ts +6 -6
package/esm/index.es.js CHANGED
@@ -6,6 +6,7 @@ import colors from 'colors';
6
6
  import commander from 'commander';
7
7
  import { writeFile, readFile } from 'fs/promises';
8
8
  import glob from 'glob-promise';
9
+ import { forTime } from 'waitasecond';
9
10
  import moment from 'moment';
10
11
 
11
12
  /*! *****************************************************************************
@@ -127,1784 +128,1821 @@ function __spreadArray(to, from, pack) {
127
128
  return to.concat(ar || Array.prototype.slice.call(from));
128
129
  }
129
130
 
130
- /**
131
- * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
132
- */
133
- var PromptbookSyntaxError = /** @class */ (function (_super) {
134
- __extends(PromptbookSyntaxError, _super);
135
- function PromptbookSyntaxError(message) {
136
- var _this = _super.call(this, message) || this;
137
- _this.name = 'PromptbookSyntaxError';
138
- Object.setPrototypeOf(_this, PromptbookSyntaxError.prototype);
139
- return _this;
140
- }
141
- return PromptbookSyntaxError;
131
+ /**
132
+ * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
133
+ */
134
+ var PromptbookSyntaxError = /** @class */ (function (_super) {
135
+ __extends(PromptbookSyntaxError, _super);
136
+ function PromptbookSyntaxError(message) {
137
+ var _this = _super.call(this, message) || this;
138
+ _this.name = 'PromptbookSyntaxError';
139
+ Object.setPrototypeOf(_this, PromptbookSyntaxError.prototype);
140
+ return _this;
141
+ }
142
+ return PromptbookSyntaxError;
142
143
  }(Error));
143
144
 
144
- /**
145
- * Supported script languages
146
- */
145
+ /**
146
+ * Supported script languages
147
+ */
147
148
  var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
148
149
 
149
- /**
150
- * Parses the template and returns the list of all parameter names
151
- *
152
- * @param template the template with parameters in {curly} braces
153
- * @returns the list of parameter names
154
- *
155
- * @private within the library
156
- */
157
- function extractParameters(template) {
158
- var e_1, _a;
159
- var matches = template.matchAll(/{\w+}/g);
160
- var parameterNames = [];
161
- try {
162
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
163
- var match = matches_1_1.value;
164
- var parameterName = match[0].slice(1, -1);
165
- if (!parameterNames.includes(parameterName)) {
166
- parameterNames.push(parameterName);
167
- }
168
- }
169
- }
170
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
171
- finally {
172
- try {
173
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
174
- }
175
- finally { if (e_1) throw e_1.error; }
176
- }
177
- return parameterNames;
150
+ /**
151
+ * Parses the template and returns the list of all parameter names
152
+ *
153
+ * @param template the template with parameters in {curly} braces
154
+ * @returns the list of parameter names
155
+ *
156
+ * @private within the library
157
+ */
158
+ function extractParameters(template) {
159
+ var e_1, _a;
160
+ var matches = template.matchAll(/{\w+}/g);
161
+ var parameterNames = [];
162
+ try {
163
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
164
+ var match = matches_1_1.value;
165
+ var parameterName = match[0].slice(1, -1);
166
+ if (!parameterNames.includes(parameterName)) {
167
+ parameterNames.push(parameterName);
168
+ }
169
+ }
170
+ }
171
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
172
+ finally {
173
+ try {
174
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
175
+ }
176
+ finally { if (e_1) throw e_1.error; }
177
+ }
178
+ return parameterNames;
178
179
  }
179
180
 
180
- /**
181
- * Computes the deepness of the markdown structure.
182
- *
183
- * @private within the library
184
- */
185
- function countMarkdownStructureDeepness(markdownStructure) {
186
- var e_1, _a;
187
- var maxDeepness = 0;
188
- try {
189
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
190
- var section = _c.value;
191
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
192
- }
193
- }
194
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
195
- finally {
196
- try {
197
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
198
- }
199
- finally { if (e_1) throw e_1.error; }
200
- }
201
- return maxDeepness + 1;
181
+ /**
182
+ * Computes the deepness of the markdown structure.
183
+ *
184
+ * @private within the library
185
+ */
186
+ function countMarkdownStructureDeepness(markdownStructure) {
187
+ var e_1, _a;
188
+ var maxDeepness = 0;
189
+ try {
190
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
191
+ var section = _c.value;
192
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
193
+ }
194
+ }
195
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
196
+ finally {
197
+ try {
198
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
199
+ }
200
+ finally { if (e_1) throw e_1.error; }
201
+ }
202
+ return maxDeepness + 1;
202
203
  }
203
204
 
204
- /**
205
- * The maximum number of iterations for a loops
206
- */
205
+ /**
206
+ * The maximum number of iterations for a loops
207
+ */
207
208
  var LOOP_LIMIT = 1000;
208
209
 
209
- /**
210
- * This error type indicates that the error should not happen and its last check before crashing with some other error
211
- */
212
- var UnexpectedError = /** @class */ (function (_super) {
213
- __extends(UnexpectedError, _super);
214
- function UnexpectedError(message) {
215
- var _this = _super.call(this, spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
216
- _this.name = 'UnexpectedError';
217
- Object.setPrototypeOf(_this, UnexpectedError.prototype);
218
- return _this;
219
- }
220
- return UnexpectedError;
210
+ /**
211
+ * This error type indicates that the error should not happen and its last check before crashing with some other error
212
+ */
213
+ var UnexpectedError = /** @class */ (function (_super) {
214
+ __extends(UnexpectedError, _super);
215
+ function UnexpectedError(message) {
216
+ var _this = _super.call(this, spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
217
+ _this.name = 'UnexpectedError';
218
+ Object.setPrototypeOf(_this, UnexpectedError.prototype);
219
+ return _this;
220
+ }
221
+ return UnexpectedError;
221
222
  }(Error));
222
223
 
223
- /**
224
- * Parse a markdown string into a MarkdownStructure object.
225
- *
226
- * Note: This function does work with code blocks
227
- * Note: This function does not work with markdown comments
228
- *
229
- * @param markdown The markdown string to parse.
230
- * @returns The MarkdownStructure object.
231
- *
232
- * @private within the library
233
- */
234
- function markdownToMarkdownStructure(markdown) {
235
- var e_1, _a;
236
- var lines = markdown.split('\n');
237
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
238
- var current = root;
239
- var isInsideCodeBlock = false;
240
- try {
241
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
242
- var line = lines_1_1.value;
243
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
244
- if (isInsideCodeBlock || !headingMatch) {
245
- if (line.startsWith('```')) {
246
- isInsideCodeBlock = !isInsideCodeBlock;
247
- }
248
- current.contentLines.push(line);
249
- }
250
- else {
251
- var level = headingMatch.groups.mark.length;
252
- var title = headingMatch.groups.title.trim();
253
- var parent_1 = void 0;
254
- if (level > current.level) {
255
- // Note: Going deeper (next section is child of current)
256
- parent_1 = current;
257
- }
258
- else {
259
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
260
- parent_1 = current;
261
- var loopLimit = LOOP_LIMIT;
262
- while (parent_1.level !== level - 1) {
263
- if (loopLimit-- < 0) {
264
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
265
- }
266
- if (parent_1.parent === null /* <- Note: We are in root */) {
267
- // [🌻]
268
- throw new Error(spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
269
- }
270
- parent_1 = parent_1.parent;
271
- }
272
- }
273
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
274
- parent_1.sections.push(section);
275
- current = section;
276
- }
277
- }
278
- }
279
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
280
- finally {
281
- try {
282
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
283
- }
284
- finally { if (e_1) throw e_1.error; }
285
- }
286
- if (root.sections.length === 1) {
287
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
288
- return markdownStructure;
289
- }
290
- // [🌻]
291
- throw new Error('The markdown file must have exactly one top-level section.');
292
- // return root;
293
- }
294
- /**
295
- * @private
296
- */
297
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
298
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
299
- return {
300
- level: level,
301
- title: title,
302
- content: spaceTrim(contentLines.join('\n')),
303
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
304
- };
224
+ /**
225
+ * Parse a markdown string into a MarkdownStructure object.
226
+ *
227
+ * Note: This function does work with code blocks
228
+ * Note: This function does not work with markdown comments
229
+ *
230
+ * @param markdown The markdown string to parse.
231
+ * @returns The MarkdownStructure object.
232
+ *
233
+ * @private within the library
234
+ */
235
+ function markdownToMarkdownStructure(markdown) {
236
+ var e_1, _a;
237
+ var lines = markdown.split('\n');
238
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
239
+ var current = root;
240
+ var isInsideCodeBlock = false;
241
+ try {
242
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
243
+ var line = lines_1_1.value;
244
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
245
+ if (isInsideCodeBlock || !headingMatch) {
246
+ if (line.startsWith('```')) {
247
+ isInsideCodeBlock = !isInsideCodeBlock;
248
+ }
249
+ current.contentLines.push(line);
250
+ }
251
+ else {
252
+ var level = headingMatch.groups.mark.length;
253
+ var title = headingMatch.groups.title.trim();
254
+ var parent_1 = void 0;
255
+ if (level > current.level) {
256
+ // Note: Going deeper (next section is child of current)
257
+ parent_1 = current;
258
+ }
259
+ else {
260
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
261
+ parent_1 = current;
262
+ var loopLimit = LOOP_LIMIT;
263
+ while (parent_1.level !== level - 1) {
264
+ if (loopLimit-- < 0) {
265
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
266
+ }
267
+ if (parent_1.parent === null /* <- Note: We are in root */) {
268
+ // [🌻]
269
+ throw new Error(spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
270
+ }
271
+ parent_1 = parent_1.parent;
272
+ }
273
+ }
274
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
275
+ parent_1.sections.push(section);
276
+ current = section;
277
+ }
278
+ }
279
+ }
280
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
281
+ finally {
282
+ try {
283
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
284
+ }
285
+ finally { if (e_1) throw e_1.error; }
286
+ }
287
+ if (root.sections.length === 1) {
288
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
289
+ return markdownStructure;
290
+ }
291
+ // [🌻]
292
+ throw new Error('The markdown file must have exactly one top-level section.');
293
+ // return root;
294
+ }
295
+ /**
296
+ * @private
297
+ */
298
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
299
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
300
+ return {
301
+ level: level,
302
+ title: title,
303
+ content: spaceTrim(contentLines.join('\n')),
304
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
305
+ };
305
306
  }
306
307
 
307
- /**
308
- * Utility function to extract all list items from markdown
309
- *
310
- * Note: It works with both ul and ol
311
- * Note: It omits list items in code blocks
312
- * Note: It flattens nested lists
313
- * Note: It can not work with html syntax and comments
314
- *
315
- * @param markdown any valid markdown
316
- * @returns
317
- */
318
- function extractAllListItemsFromMarkdown(markdown) {
319
- var e_1, _a;
320
- var lines = markdown.split('\n');
321
- var listItems = [];
322
- var isInCodeBlock = false;
323
- try {
324
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
325
- var line = lines_1_1.value;
326
- var trimmedLine = line.trim();
327
- if (trimmedLine.startsWith('```')) {
328
- isInCodeBlock = !isInCodeBlock;
329
- }
330
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
331
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
332
- listItems.push(listItem);
333
- }
334
- }
335
- }
336
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
337
- finally {
338
- try {
339
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
340
- }
341
- finally { if (e_1) throw e_1.error; }
342
- }
343
- return listItems;
308
+ /**
309
+ * Utility function to extract all list items from markdown
310
+ *
311
+ * Note: It works with both ul and ol
312
+ * Note: It omits list items in code blocks
313
+ * Note: It flattens nested lists
314
+ * Note: It can not work with html syntax and comments
315
+ *
316
+ * @param markdown any valid markdown
317
+ * @returns
318
+ */
319
+ function extractAllListItemsFromMarkdown(markdown) {
320
+ var e_1, _a;
321
+ var lines = markdown.split('\n');
322
+ var listItems = [];
323
+ var isInCodeBlock = false;
324
+ try {
325
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
326
+ var line = lines_1_1.value;
327
+ var trimmedLine = line.trim();
328
+ if (trimmedLine.startsWith('```')) {
329
+ isInCodeBlock = !isInCodeBlock;
330
+ }
331
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
332
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
333
+ listItems.push(listItem);
334
+ }
335
+ }
336
+ }
337
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
338
+ finally {
339
+ try {
340
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
341
+ }
342
+ finally { if (e_1) throw e_1.error; }
343
+ }
344
+ return listItems;
344
345
  }
345
346
 
346
- /**
347
- * Extracts all code blocks from markdown.
348
- *
349
- * Note: There are 3 simmilar function:
350
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
351
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
352
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
353
- *
354
- * @param markdown any valid markdown
355
- * @returns code blocks with language and content
356
- *
357
- */
358
- function extractAllBlocksFromMarkdown(markdown) {
359
- var e_1, _a;
360
- var codeBlocks = [];
361
- var lines = markdown.split('\n');
362
- var currentCodeBlock = null;
363
- try {
364
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
365
- var line = lines_1_1.value;
366
- if (line.startsWith('```')) {
367
- var language = line.slice(3).trim() || null;
368
- if (currentCodeBlock === null) {
369
- currentCodeBlock = { language: language, content: '' };
370
- }
371
- else {
372
- if (language !== null) {
373
- // [🌻]
374
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
375
- }
376
- codeBlocks.push(currentCodeBlock);
377
- currentCodeBlock = null;
378
- }
379
- }
380
- else if (currentCodeBlock !== null) {
381
- if (currentCodeBlock.content !== '') {
382
- currentCodeBlock.content += '\n';
383
- }
384
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
385
- }
386
- }
387
- }
388
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
389
- finally {
390
- try {
391
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
392
- }
393
- finally { if (e_1) throw e_1.error; }
394
- }
395
- if (currentCodeBlock !== null) {
396
- // [🌻]
397
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
398
- }
399
- return codeBlocks;
347
+ /**
348
+ * Extracts all code blocks from markdown.
349
+ *
350
+ * Note: There are 3 simmilar function:
351
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
352
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
353
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
354
+ *
355
+ * @param markdown any valid markdown
356
+ * @returns code blocks with language and content
357
+ *
358
+ */
359
+ function extractAllBlocksFromMarkdown(markdown) {
360
+ var e_1, _a;
361
+ var codeBlocks = [];
362
+ var lines = markdown.split('\n');
363
+ var currentCodeBlock = null;
364
+ try {
365
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
366
+ var line = lines_1_1.value;
367
+ if (line.startsWith('```')) {
368
+ var language = line.slice(3).trim() || null;
369
+ if (currentCodeBlock === null) {
370
+ currentCodeBlock = { language: language, content: '' };
371
+ }
372
+ else {
373
+ if (language !== null) {
374
+ // [🌻]
375
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
376
+ }
377
+ codeBlocks.push(currentCodeBlock);
378
+ currentCodeBlock = null;
379
+ }
380
+ }
381
+ else if (currentCodeBlock !== null) {
382
+ if (currentCodeBlock.content !== '') {
383
+ currentCodeBlock.content += '\n';
384
+ }
385
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
386
+ }
387
+ }
388
+ }
389
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
390
+ finally {
391
+ try {
392
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
393
+ }
394
+ finally { if (e_1) throw e_1.error; }
395
+ }
396
+ if (currentCodeBlock !== null) {
397
+ // [🌻]
398
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
399
+ }
400
+ return codeBlocks;
400
401
  }
401
402
 
402
- /**
403
- * Extracts exactly ONE code block from markdown.
404
- *
405
- * Note: If there are multiple or no code blocks the function throws an error
406
- *
407
- * Note: There are 3 simmilar function:
408
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
409
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
410
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
411
- *
412
- * @param markdown any valid markdown
413
- * @returns code block with language and content
414
- */
415
- function extractOneBlockFromMarkdown(markdown) {
416
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
417
- if (codeBlocks.length !== 1) {
418
- // TODO: Report more specific place where the error happened
419
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
420
- }
421
- return codeBlocks[0];
422
- }
423
- /***
424
- * TODO: [🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
403
+ /**
404
+ * Extracts exactly ONE code block from markdown.
405
+ *
406
+ * Note: If there are multiple or no code blocks the function throws an error
407
+ *
408
+ * Note: There are 3 simmilar function:
409
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
410
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
411
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
412
+ *
413
+ * @param markdown any valid markdown
414
+ * @returns code block with language and content
415
+ */
416
+ function extractOneBlockFromMarkdown(markdown) {
417
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
418
+ if (codeBlocks.length !== 1) {
419
+ // TODO: Report more specific place where the error happened
420
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
421
+ }
422
+ return codeBlocks[0];
423
+ }
424
+ /***
425
+ * TODO: [🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
425
426
  */
426
427
 
427
- /**
428
- * Removes HTML or Markdown comments from a string.
429
- *
430
- * @param {string} content - The string to remove comments from.
431
- * @returns {string} The input string with all comments removed.
432
- */
433
- function removeContentComments(content) {
434
- return spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
428
+ /**
429
+ * Removes HTML or Markdown comments from a string.
430
+ *
431
+ * @param {string} content - The string to remove comments from.
432
+ * @returns {string} The input string with all comments removed.
433
+ */
434
+ function removeContentComments(content) {
435
+ return spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
435
436
  }
436
437
 
437
- /**
438
- * The version of the Promptbook library
439
- */
440
- var PROMPTBOOK_VERSION = '0.41.0';
438
+ /**
439
+ * The version of the Promptbook library
440
+ */
441
+ var PROMPTBOOK_VERSION = '0.41.101';
441
442
 
442
- /**
443
- * Parses the given script and returns the list of all used variables that are not defined in the script
444
- *
445
- * @param script from which to extract the variables
446
- * @returns the list of variable names
447
- *
448
- * @private within the promptbookStringToJson
449
- */
450
- function extractVariables(script) {
451
- var variables = [];
452
- script = "(()=>{".concat(script, "})()");
453
- try {
454
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
455
- try {
456
- eval(script);
457
- }
458
- catch (error) {
459
- if (!(error instanceof ReferenceError)) {
460
- throw error;
461
- }
462
- var undefinedName = error.message.split(' ')[0];
463
- /*
464
- Note: Remapping error
465
- From: [ReferenceError: thing is not defined],
466
- To: [Error: Parameter {thing} is not defined],
467
- */
468
- if (!undefinedName) {
469
- throw error;
470
- }
471
- if (script.includes(undefinedName + '(')) {
472
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
473
- }
474
- else {
475
- variables.push(undefinedName);
476
- script = "const ".concat(undefinedName, " = '';") + script;
477
- }
478
- }
479
- }
480
- catch (error) {
481
- if (!(error instanceof Error)) {
482
- throw error;
483
- }
484
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
485
- }
486
- return variables;
443
+ /**
444
+ * Parses the given script and returns the list of all used variables that are not defined in the script
445
+ *
446
+ * @param script from which to extract the variables
447
+ * @returns the list of variable names
448
+ *
449
+ * @private within the promptbookStringToJson
450
+ */
451
+ function extractVariables(script) {
452
+ var variables = [];
453
+ script = "(()=>{".concat(script, "})()");
454
+ try {
455
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
456
+ try {
457
+ eval(script);
458
+ }
459
+ catch (error) {
460
+ if (!(error instanceof ReferenceError)) {
461
+ throw error;
462
+ }
463
+ var undefinedName = error.message.split(' ')[0];
464
+ /*
465
+ Note: Remapping error
466
+ From: [ReferenceError: thing is not defined],
467
+ To: [Error: Parameter {thing} is not defined],
468
+ */
469
+ if (!undefinedName) {
470
+ throw error;
471
+ }
472
+ if (script.includes(undefinedName + '(')) {
473
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
474
+ }
475
+ else {
476
+ variables.push(undefinedName);
477
+ script = "const ".concat(undefinedName, " = '';") + script;
478
+ }
479
+ }
480
+ }
481
+ catch (error) {
482
+ if (!(error instanceof Error)) {
483
+ throw error;
484
+ }
485
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
486
+ }
487
+ return variables;
487
488
  }
488
489
 
489
- /**
490
- * Execution type describes the way how the block is executed
491
- *
492
- * @see https://github.com/webgptorg/promptbook#execution-type
493
- */
490
+ /**
491
+ * Execution type describes the way how the block is executed
492
+ *
493
+ * @see https://github.com/webgptorg/promptbook#execution-type
494
+ */
494
495
  var ExecutionTypes = ['PROMPT_TEMPLATE', 'SIMPLE_TEMPLATE', 'SCRIPT', 'PROMPT_DIALOG'];
495
496
 
496
- /**
497
- * Units of text measurement
498
- */
499
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
500
- /**
501
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
497
+ /**
498
+ * Units of text measurement
499
+ */
500
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
501
+ /**
502
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
502
503
  */
503
504
 
504
- /**
505
- * Removes Markdown formatting tags from a string.
506
- *
507
- * @param {string} str - The string to remove Markdown tags from.
508
- * @returns {string} The input string with all Markdown tags removed.
509
- */
510
- function removeMarkdownFormatting(str) {
511
- // Remove bold formatting
512
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
513
- // Remove italic formatting
514
- str = str.replace(/\*(.*?)\*/g, '$1');
515
- // Remove code formatting
516
- str = str.replace(/`(.*?)`/g, '$1');
517
- return str;
505
+ /**
506
+ * Removes Markdown formatting tags from a string.
507
+ *
508
+ * @param {string} str - The string to remove Markdown tags from.
509
+ * @returns {string} The input string with all Markdown tags removed.
510
+ */
511
+ function removeMarkdownFormatting(str) {
512
+ // Remove bold formatting
513
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
514
+ // Remove italic formatting
515
+ str = str.replace(/\*(.*?)\*/g, '$1');
516
+ // Remove code formatting
517
+ str = str.replace(/`(.*?)`/g, '$1');
518
+ return str;
518
519
  }
519
520
 
520
- /**
521
- * Function parseNumber will parse number from string
522
- *
523
- * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
524
- * Note: it also works only with decimal numbers
525
- *
526
- * @private within the parseCommand
527
- */
528
- function parseNumber(value) {
529
- var originalValue = value;
530
- if (typeof value === 'number') {
531
- value = value.toString(); // <- TODO: Maybe more efficient way to do this
532
- }
533
- if (typeof value !== 'string') {
534
- return 0;
535
- }
536
- value = value.trim();
537
- if (value.startsWith('+')) {
538
- return parseNumber(value.substring(1));
539
- }
540
- if (value.startsWith('-')) {
541
- var number = parseNumber(value.substring(1));
542
- if (number === 0) {
543
- return 0; // <- Note: To prevent -0
544
- }
545
- return -number;
546
- }
547
- value = value.replace(/,/g, '.');
548
- value = value.toUpperCase();
549
- if (value === '') {
550
- return 0;
551
- }
552
- if (value === '♾' || value.startsWith('INF')) {
553
- return Infinity;
554
- }
555
- if (value.includes('/')) {
556
- var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
557
- var numerator = parseNumber(numerator_);
558
- var denominator = parseNumber(denominator_);
559
- if (denominator === 0) {
560
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
561
- }
562
- return numerator / denominator;
563
- }
564
- if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
565
- return 0;
566
- }
567
- if (value.includes('E')) {
568
- var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
569
- return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
570
- }
571
- if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
572
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
573
- }
574
- var num = parseFloat(value);
575
- if (isNaN(num)) {
576
- throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
577
- }
578
- return num;
579
- }
580
- /**
581
- * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
521
+ /**
522
+ * Function parseNumber will parse number from string
523
+ *
524
+ * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
525
+ * Note: it also works only with decimal numbers
526
+ *
527
+ * @private within the parseCommand
528
+ */
529
+ function parseNumber(value) {
530
+ var originalValue = value;
531
+ if (typeof value === 'number') {
532
+ value = value.toString(); // <- TODO: Maybe more efficient way to do this
533
+ }
534
+ if (typeof value !== 'string') {
535
+ return 0;
536
+ }
537
+ value = value.trim();
538
+ if (value.startsWith('+')) {
539
+ return parseNumber(value.substring(1));
540
+ }
541
+ if (value.startsWith('-')) {
542
+ var number = parseNumber(value.substring(1));
543
+ if (number === 0) {
544
+ return 0; // <- Note: To prevent -0
545
+ }
546
+ return -number;
547
+ }
548
+ value = value.replace(/,/g, '.');
549
+ value = value.toUpperCase();
550
+ if (value === '') {
551
+ return 0;
552
+ }
553
+ if (value === '♾' || value.startsWith('INF')) {
554
+ return Infinity;
555
+ }
556
+ if (value.includes('/')) {
557
+ var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
558
+ var numerator = parseNumber(numerator_);
559
+ var denominator = parseNumber(denominator_);
560
+ if (denominator === 0) {
561
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
562
+ }
563
+ return numerator / denominator;
564
+ }
565
+ if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
566
+ return 0;
567
+ }
568
+ if (value.includes('E')) {
569
+ var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
570
+ return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
571
+ }
572
+ if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
573
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
574
+ }
575
+ var num = parseFloat(value);
576
+ if (isNaN(num)) {
577
+ throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
578
+ }
579
+ return num;
580
+ }
581
+ /**
582
+ * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
582
583
  */
583
584
 
584
- /**
585
- * Parses one line of ul/ol to command
586
- *
587
- * @private within the promptbookStringToJson
588
- */
589
- function parseCommand(listItem) {
590
- var e_1, _a;
591
- if (listItem.includes('\n') || listItem.includes('\r')) {
592
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
593
- }
594
- var type = listItem.trim();
595
- type = type.split('`').join('');
596
- type = type.split('"').join('');
597
- type = type.split("'").join('');
598
- type = type.split('~').join('');
599
- type = type.split('[').join('');
600
- type = type.split(']').join('');
601
- type = type.split('(').join('');
602
- type = type.split(')').join('');
603
- type = normalizeTo_SCREAMING_CASE(type);
604
- type = type.split('DIALOGUE').join('DIALOG');
605
- var listItemParts = listItem
606
- .split(' ')
607
- .map(function (part) { return part.trim(); })
608
- .filter(function (item) { return item !== ''; })
609
- .filter(function (item) { return !/^PTBK$/i.test(item); })
610
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
611
- .map(removeMarkdownFormatting);
612
- if (type.startsWith('URL') ||
613
- type.startsWith('PTBK_URL') ||
614
- type.startsWith('PTBKURL') ||
615
- type.startsWith('PROMPTBOOK_URL') ||
616
- type.startsWith('PROMPTBOOKURL') ||
617
- type.startsWith('HTTPS')) {
618
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
619
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
620
- }
621
- var promptbookUrlString = listItemParts.pop();
622
- var promptbookUrl = new URL(promptbookUrlString);
623
- if (promptbookUrl.protocol !== 'https:') {
624
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
625
- }
626
- if (promptbookUrl.hash !== '') {
627
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
628
- }
629
- return {
630
- type: 'PROMPTBOOK_URL',
631
- promptbookUrl: promptbookUrl,
632
- };
633
- }
634
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
635
- if (listItemParts.length !== 2) {
636
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
637
- }
638
- var promptbookVersion = listItemParts.pop();
639
- // TODO: Validate version
640
- return {
641
- type: 'PROMPTBOOK_VERSION',
642
- promptbookVersion: promptbookVersion,
643
- };
644
- }
645
- else if (type.startsWith('EXECUTE') ||
646
- type.startsWith('EXEC') ||
647
- type.startsWith('PROMPT_DIALOG') ||
648
- type.startsWith('SIMPLE_TEMPLATE')) {
649
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
650
- if (executionTypes.length !== 1) {
651
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
652
- }
653
- return {
654
- type: 'EXECUTE',
655
- executionType: executionTypes[0],
656
- };
657
- }
658
- else if (type.startsWith('MODEL')) {
659
- // TODO: Make this more elegant and dynamically
660
- if (type.startsWith('MODEL_VARIANT')) {
661
- if (type === 'MODEL_VARIANT_CHAT') {
662
- return {
663
- type: 'MODEL',
664
- key: 'modelVariant',
665
- value: 'CHAT',
666
- };
667
- }
668
- else if (type === 'MODEL_VARIANT_COMPLETION') {
669
- return {
670
- type: 'MODEL',
671
- key: 'modelVariant',
672
- value: 'COMPLETION',
673
- };
674
- }
675
- else {
676
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
677
- }
678
- }
679
- if (type.startsWith('MODEL_NAME')) {
680
- return {
681
- type: 'MODEL',
682
- key: 'modelName',
683
- value: listItemParts.pop(),
684
- };
685
- }
686
- else {
687
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
688
- }
689
- }
690
- else if (type.startsWith('PARAM') ||
691
- type.startsWith('INPUT_PARAM') ||
692
- type.startsWith('OUTPUT_PARAM') ||
693
- listItem.startsWith('{') ||
694
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
695
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
696
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
697
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
698
- }
699
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
700
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
701
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
702
- throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
703
- }
704
- var isInput = type.startsWith('INPUT');
705
- var isOutput = type.startsWith('OUTPUT');
706
- return {
707
- type: 'PARAMETER',
708
- parameterName: parameterName,
709
- parameterDescription: parameterDescription.trim() || null,
710
- isInput: isInput,
711
- isOutput: isOutput,
712
- };
713
- }
714
- else if (type.startsWith('JOKER')) {
715
- if (listItemParts.length !== 2) {
716
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
717
- }
718
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
719
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
720
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
721
- }
722
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
723
- var parameterName = parametersMatch.groups.parameterName;
724
- return {
725
- type: 'JOKER',
726
- parameterName: parameterName,
727
- };
728
- }
729
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
730
- if (listItemParts.length !== 2) {
731
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
732
- }
733
- var functionName = listItemParts.pop();
734
- return {
735
- type: 'POSTPROCESS',
736
- functionName: functionName,
737
- };
738
- }
739
- else if (type.startsWith('EXPECT_JSON')) {
740
- return {
741
- type: 'EXPECT_FORMAT',
742
- format: 'JSON',
743
- };
744
- // [🥤]
745
- }
746
- else if (type.startsWith('EXPECT')) {
747
- try {
748
- listItemParts.shift();
749
- var sign = void 0;
750
- var signRaw = listItemParts.shift();
751
- if (/^exact/i.test(signRaw)) {
752
- sign = 'EXACTLY';
753
- }
754
- else if (/^min/i.test(signRaw)) {
755
- sign = 'MINIMUM';
756
- }
757
- else if (/^max/i.test(signRaw)) {
758
- sign = 'MAXIMUM';
759
- }
760
- else {
761
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\""));
762
- }
763
- var amountRaw = listItemParts.shift();
764
- var amount = parseNumber(amountRaw);
765
- if (amount < 0) {
766
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
767
- }
768
- if (amount !== Math.floor(amount)) {
769
- throw new PromptbookSyntaxError('Amount must be whole number');
770
- }
771
- var unitRaw = listItemParts.shift();
772
- var unit = undefined;
773
- try {
774
- 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()) {
775
- var existingUnit = EXPECTATION_UNITS_1_1.value;
776
- var existingUnitText = existingUnit;
777
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
778
- if (existingUnitText === 'CHARACTER') {
779
- existingUnitText = 'CHAR';
780
- }
781
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
782
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
783
- if (unit !== undefined) {
784
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
785
- }
786
- unit = existingUnit;
787
- }
788
- }
789
- }
790
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
791
- finally {
792
- try {
793
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
794
- }
795
- finally { if (e_1) throw e_1.error; }
796
- }
797
- if (unit === undefined) {
798
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
799
- }
800
- return {
801
- type: 'EXPECT_AMOUNT',
802
- sign: sign,
803
- unit: unit,
804
- amount: amount,
805
- };
806
- }
807
- catch (error) {
808
- if (!(error instanceof Error)) {
809
- throw error;
810
- }
811
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
812
- }
813
- }
814
- else {
815
- throw new PromptbookSyntaxError(spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - Execute\n - Model\n - Parameter\n - INPUT PARAMETER\n - OUTPUT PARAMETER\n - PROMPTBOOK VERSION\n ")));
816
- }
585
+ /**
586
+ * Parses one line of ul/ol to command
587
+ *
588
+ * @private within the promptbookStringToJson
589
+ */
590
+ function parseCommand(listItem) {
591
+ var e_1, _a;
592
+ if (listItem.includes('\n') || listItem.includes('\r')) {
593
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
594
+ }
595
+ var type = listItem.trim();
596
+ type = type.split('`').join('');
597
+ type = type.split('"').join('');
598
+ type = type.split("'").join('');
599
+ type = type.split('~').join('');
600
+ type = type.split('[').join('');
601
+ type = type.split(']').join('');
602
+ type = type.split('(').join('');
603
+ type = type.split(')').join('');
604
+ type = normalizeTo_SCREAMING_CASE(type);
605
+ type = type.split('DIALOGUE').join('DIALOG');
606
+ var listItemParts = listItem
607
+ .split(' ')
608
+ .map(function (part) { return part.trim(); })
609
+ .filter(function (item) { return item !== ''; })
610
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
611
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
612
+ .map(removeMarkdownFormatting);
613
+ if (type.startsWith('URL') ||
614
+ type.startsWith('PTBK_URL') ||
615
+ type.startsWith('PTBKURL') ||
616
+ type.startsWith('PROMPTBOOK_URL') ||
617
+ type.startsWith('PROMPTBOOKURL') ||
618
+ type.startsWith('HTTPS')) {
619
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
620
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
621
+ }
622
+ var promptbookUrlString = listItemParts.pop();
623
+ var promptbookUrl = new URL(promptbookUrlString);
624
+ if (promptbookUrl.protocol !== 'https:') {
625
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
626
+ }
627
+ if (promptbookUrl.hash !== '') {
628
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
629
+ }
630
+ return {
631
+ type: 'PROMPTBOOK_URL',
632
+ promptbookUrl: promptbookUrl,
633
+ };
634
+ }
635
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
636
+ if (listItemParts.length !== 2) {
637
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
638
+ }
639
+ var promptbookVersion = listItemParts.pop();
640
+ // TODO: Validate version
641
+ return {
642
+ type: 'PROMPTBOOK_VERSION',
643
+ promptbookVersion: promptbookVersion,
644
+ };
645
+ }
646
+ else if (type.startsWith('EXECUTE') ||
647
+ type.startsWith('EXEC') ||
648
+ type.startsWith('PROMPT_DIALOG') ||
649
+ type.startsWith('SIMPLE_TEMPLATE')) {
650
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
651
+ if (executionTypes.length !== 1) {
652
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
653
+ }
654
+ return {
655
+ type: 'EXECUTE',
656
+ executionType: executionTypes[0],
657
+ };
658
+ }
659
+ else if (type.startsWith('MODEL')) {
660
+ // TODO: Make this more elegant and dynamically
661
+ if (type.startsWith('MODEL_VARIANT')) {
662
+ if (type === 'MODEL_VARIANT_CHAT') {
663
+ return {
664
+ type: 'MODEL',
665
+ key: 'modelVariant',
666
+ value: 'CHAT',
667
+ };
668
+ }
669
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
670
+ return {
671
+ type: 'MODEL',
672
+ key: 'modelVariant',
673
+ value: 'COMPLETION',
674
+ };
675
+ }
676
+ else {
677
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
678
+ }
679
+ }
680
+ if (type.startsWith('MODEL_NAME')) {
681
+ return {
682
+ type: 'MODEL',
683
+ key: 'modelName',
684
+ value: listItemParts.pop(),
685
+ };
686
+ }
687
+ else {
688
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
689
+ }
690
+ }
691
+ else if (type.startsWith('PARAM') ||
692
+ type.startsWith('INPUT_PARAM') ||
693
+ type.startsWith('OUTPUT_PARAM') ||
694
+ listItem.startsWith('{') ||
695
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
696
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
697
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
698
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
699
+ }
700
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
701
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
702
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
703
+ throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
704
+ }
705
+ var isInput = type.startsWith('INPUT');
706
+ var isOutput = type.startsWith('OUTPUT');
707
+ return {
708
+ type: 'PARAMETER',
709
+ parameterName: parameterName,
710
+ parameterDescription: parameterDescription.trim() || null,
711
+ isInput: isInput,
712
+ isOutput: isOutput,
713
+ };
714
+ }
715
+ else if (type.startsWith('JOKER')) {
716
+ if (listItemParts.length !== 2) {
717
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
718
+ }
719
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
720
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
721
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
722
+ }
723
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
724
+ var parameterName = parametersMatch.groups.parameterName;
725
+ return {
726
+ type: 'JOKER',
727
+ parameterName: parameterName,
728
+ };
729
+ }
730
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
731
+ if (listItemParts.length !== 2) {
732
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
733
+ }
734
+ var functionName = listItemParts.pop();
735
+ return {
736
+ type: 'POSTPROCESS',
737
+ functionName: functionName,
738
+ };
739
+ }
740
+ else if (type.startsWith('EXPECT_JSON')) {
741
+ return {
742
+ type: 'EXPECT_FORMAT',
743
+ format: 'JSON',
744
+ };
745
+ // [🥤]
746
+ }
747
+ else if (type.startsWith('EXPECT')) {
748
+ try {
749
+ listItemParts.shift();
750
+ var sign = void 0;
751
+ var signRaw = listItemParts.shift();
752
+ if (/^exact/i.test(signRaw)) {
753
+ sign = 'EXACTLY';
754
+ }
755
+ else if (/^min/i.test(signRaw)) {
756
+ sign = 'MINIMUM';
757
+ }
758
+ else if (/^max/i.test(signRaw)) {
759
+ sign = 'MAXIMUM';
760
+ }
761
+ else {
762
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\""));
763
+ }
764
+ var amountRaw = listItemParts.shift();
765
+ var amount = parseNumber(amountRaw);
766
+ if (amount < 0) {
767
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
768
+ }
769
+ if (amount !== Math.floor(amount)) {
770
+ throw new PromptbookSyntaxError('Amount must be whole number');
771
+ }
772
+ var unitRaw = listItemParts.shift();
773
+ var unit = undefined;
774
+ try {
775
+ 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()) {
776
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
777
+ var existingUnitText = existingUnit;
778
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
779
+ if (existingUnitText === 'CHARACTER') {
780
+ existingUnitText = 'CHAR';
781
+ }
782
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
783
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
784
+ if (unit !== undefined) {
785
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
786
+ }
787
+ unit = existingUnit;
788
+ }
789
+ }
790
+ }
791
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
792
+ finally {
793
+ try {
794
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
795
+ }
796
+ finally { if (e_1) throw e_1.error; }
797
+ }
798
+ if (unit === undefined) {
799
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
800
+ }
801
+ return {
802
+ type: 'EXPECT_AMOUNT',
803
+ sign: sign,
804
+ unit: unit,
805
+ amount: amount,
806
+ };
807
+ }
808
+ catch (error) {
809
+ if (!(error instanceof Error)) {
810
+ throw error;
811
+ }
812
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
813
+ }
814
+ }
815
+ else {
816
+ throw new PromptbookSyntaxError(spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - Execute\n - Model\n - Parameter\n - INPUT PARAMETER\n - OUTPUT PARAMETER\n - PROMPTBOOK VERSION\n ")));
817
+ }
817
818
  }
818
819
 
819
- /**
820
- * Parse promptbook from string format to JSON format
821
- *
822
- * Note: This function does not validate logic of the pipeline only the syntax
823
- */
824
- function promptbookStringToJson(promptbookString) {
825
- var e_1, _a, e_2, _b;
826
- var promptbookJson = {
827
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
828
- title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
829
- promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
830
- promptbookVersion: PROMPTBOOK_VERSION,
831
- description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
832
- parameters: [],
833
- promptTemplates: [],
834
- };
835
- // =============================================================
836
- // Note: 1️⃣ Normalization of the PROMPTBOOK string
837
- promptbookString = removeContentComments(promptbookString);
838
- promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
839
- promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
840
- // =============================================================
841
- ///Note: 2️⃣ Function for adding parameters
842
- var addParam = function (parameterCommand) {
843
- var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
844
- var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
845
- if (existingParameter &&
846
- existingParameter.description &&
847
- existingParameter.description !== parameterDescription &&
848
- parameterDescription) {
849
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
850
- }
851
- if (existingParameter) {
852
- if (parameterDescription) {
853
- existingParameter.description = parameterDescription;
854
- }
855
- }
856
- else {
857
- promptbookJson.parameters.push({
858
- name: parameterName,
859
- description: parameterDescription || undefined,
860
- isInput: isInput,
861
- isOutput: isOutput,
862
- });
863
- }
864
- };
865
- // =============================================================
866
- // Note: 3️⃣ Parse the dynamic part - the template pipeline
867
- var markdownStructure = markdownToMarkdownStructure(promptbookString);
868
- var markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
869
- if (markdownStructureDeepness !== 2) {
870
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
871
- }
872
- promptbookJson.title = markdownStructure.title;
873
- // TODO: [1] DRY description
874
- var description = markdownStructure.content;
875
- // Note: Remove codeblocks
876
- description = description.split(/^```.*^```/gms).join('');
877
- //Note: Remove lists and return statement
878
- description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
879
- description = spaceTrim(description);
880
- if (description === '') {
881
- description = undefined;
882
- }
883
- promptbookJson.description = description;
884
- var defaultModelRequirements = {};
885
- var listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
886
- try {
887
- for (var listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
888
- var listItem = listItems_1_1.value;
889
- var command = parseCommand(listItem);
890
- switch (command.type) {
891
- case 'PROMPTBOOK_URL':
892
- promptbookJson.promptbookUrl = command.promptbookUrl.href;
893
- break;
894
- case 'PROMPTBOOK_VERSION':
895
- promptbookJson.promptbookVersion = command.promptbookVersion;
896
- break;
897
- case 'MODEL':
898
- defaultModelRequirements[command.key] = command.value;
899
- break;
900
- case 'PARAMETER':
901
- addParam(command);
902
- break;
903
- default:
904
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
905
- }
906
- }
907
- }
908
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
909
- finally {
910
- try {
911
- if (listItems_1_1 && !listItems_1_1.done && (_a = listItems_1.return)) _a.call(listItems_1);
912
- }
913
- finally { if (e_1) throw e_1.error; }
914
- }
915
- var _loop_1 = function (section) {
916
- var e_3, _e, e_4, _f, e_5, _g;
917
- // TODO: Parse prompt template description (the content out of the codeblock and lists)
918
- var templateModelRequirements = __assign({}, defaultModelRequirements);
919
- var listItems_3 = extractAllListItemsFromMarkdown(section.content);
920
- var dependentParameterNames = [];
921
- var executionType = 'PROMPT_TEMPLATE';
922
- var jokers = [];
923
- var postprocessing = [];
924
- var expectAmount = {};
925
- var expectFormat = undefined;
926
- var isExecutionTypeChanged = false;
927
- try {
928
- for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
929
- var listItem = listItems_2_1.value;
930
- var command = parseCommand(listItem);
931
- switch (command.type) {
932
- case 'JOKER':
933
- jokers.push(command.parameterName);
934
- dependentParameterNames.push(command.parameterName);
935
- break;
936
- case 'EXECUTE':
937
- if (isExecutionTypeChanged) {
938
- throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
939
- }
940
- executionType = command.executionType;
941
- isExecutionTypeChanged = true;
942
- break;
943
- case 'MODEL':
944
- templateModelRequirements[command.key] = command.value;
945
- break;
946
- case 'PARAMETER':
947
- // Note: This is just for detecting resulitng parameter name
948
- addParam(command);
949
- break;
950
- case 'POSTPROCESS':
951
- postprocessing.push(command.functionName);
952
- break;
953
- case 'EXPECT_AMOUNT':
954
- // eslint-disable-next-line no-case-declarations
955
- var unit = command.unit.toLowerCase();
956
- expectAmount[unit] = expectAmount[unit] || {};
957
- if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
958
- if (expectAmount[unit].min !== undefined) {
959
- throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
960
- }
961
- expectAmount[unit].min = command.amount;
962
- } /* not else */
963
- if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
964
- if (expectAmount[unit].max !== undefined) {
965
- throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
966
- }
967
- expectAmount[unit].max = command.amount;
968
- }
969
- break;
970
- case 'EXPECT_FORMAT':
971
- if (expectFormat !== undefined && command.format !== expectFormat) {
972
- throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
973
- }
974
- expectFormat = command.format;
975
- break;
976
- default:
977
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
978
- }
979
- }
980
- }
981
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
982
- finally {
983
- try {
984
- if (listItems_2_1 && !listItems_2_1.done && (_e = listItems_2.return)) _e.call(listItems_2);
985
- }
986
- finally { if (e_3) throw e_3.error; }
987
- }
988
- var _h = extractOneBlockFromMarkdown(section.content), language = _h.language, content = _h.content;
989
- if (executionType === 'SCRIPT') {
990
- if (!language) {
991
- throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
992
- }
993
- else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
994
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
995
- }
996
- }
997
- var lastLine = section.content.split('\n').pop();
998
- var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
999
- if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1000
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1001
- // TODO: Show code of invalid sections each time + DRY
1002
- section.content
1003
- .split('\n')
1004
- .map(function (line) { return "> ".concat(line); })
1005
- .join('\n')), "\n "); }));
1006
- }
1007
- var resultingParameterName = match.groups.resultingParamName;
1008
- // TODO: [1] DRY description
1009
- var description_1 = section.content;
1010
- // Note: Remove codeblocks
1011
- description_1 = description_1.split(/^```.*^```/gms).join('');
1012
- //Note: Remove lists and return statement
1013
- description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1014
- description_1 = spaceTrim(description_1);
1015
- if (description_1 === '') {
1016
- description_1 = undefined;
1017
- }
1018
- if (Object.keys(jokers).length === 0) {
1019
- jokers = undefined;
1020
- }
1021
- if (Object.keys(expectAmount).length === 0) {
1022
- expectAmount = undefined;
1023
- }
1024
- if (Object.keys(postprocessing).length === 0) {
1025
- postprocessing = undefined;
1026
- }
1027
- try {
1028
- for (var _j = (e_4 = void 0, __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(section.title)), false), __read(extractParameters(description_1 || '')), false), __read(extractParameters(content)), false))), _k = _j.next(); !_k.done; _k = _j.next()) {
1029
- var parameterName = _k.value;
1030
- dependentParameterNames.push(parameterName);
1031
- }
1032
- }
1033
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1034
- finally {
1035
- try {
1036
- if (_k && !_k.done && (_f = _j.return)) _f.call(_j);
1037
- }
1038
- finally { if (e_4) throw e_4.error; }
1039
- }
1040
- if (executionType === 'SCRIPT') {
1041
- try {
1042
- for (var _l = (e_5 = void 0, __values(extractVariables(content))), _m = _l.next(); !_m.done; _m = _l.next()) {
1043
- var parameterName = _m.value;
1044
- dependentParameterNames.push(parameterName);
1045
- }
1046
- }
1047
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
1048
- finally {
1049
- try {
1050
- if (_m && !_m.done && (_g = _l.return)) _g.call(_l);
1051
- }
1052
- finally { if (e_5) throw e_5.error; }
1053
- }
1054
- }
1055
- dependentParameterNames = __spreadArray([], __read(new Set(dependentParameterNames)), false);
1056
- promptbookJson.promptTemplates.push({
1057
- name: normalizeTo_PascalCase(section.title),
1058
- title: section.title,
1059
- description: description_1,
1060
- dependentParameterNames: dependentParameterNames,
1061
- executionType: executionType,
1062
- jokers: jokers,
1063
- postprocessing: postprocessing,
1064
- expectAmount: expectAmount,
1065
- expectFormat: expectFormat,
1066
- modelRequirements: templateModelRequirements,
1067
- contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1068
- content: content,
1069
- resultingParameterName: resultingParameterName,
1070
- });
1071
- };
1072
- try {
1073
- for (var _c = __values(markdownStructure.sections), _d = _c.next(); !_d.done; _d = _c.next()) {
1074
- var section = _d.value;
1075
- _loop_1(section);
1076
- }
1077
- }
1078
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1079
- finally {
1080
- try {
1081
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1082
- }
1083
- finally { if (e_2) throw e_2.error; }
1084
- }
1085
- // =============================================================
1086
- return promptbookJson;
1087
- }
1088
- /**
1089
- * TODO: Report here line/column of error
1090
- * TODO: Use spaceTrim more effectively
1091
- * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
820
+ /**
821
+ * Parse promptbook from string format to JSON format
822
+ *
823
+ * Note: This function does not validate logic of the pipeline only the syntax
824
+ */
825
+ function promptbookStringToJson(promptbookString) {
826
+ var e_1, _a, e_2, _b;
827
+ var promptbookJson = {
828
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
829
+ title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
830
+ promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
831
+ promptbookVersion: PROMPTBOOK_VERSION,
832
+ description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
833
+ parameters: [],
834
+ promptTemplates: [],
835
+ };
836
+ // =============================================================
837
+ // Note: 1️⃣ Normalization of the PROMPTBOOK string
838
+ promptbookString = removeContentComments(promptbookString);
839
+ promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
840
+ promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
841
+ // =============================================================
842
+ ///Note: 2️⃣ Function for adding parameters
843
+ var addParam = function (parameterCommand) {
844
+ var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
845
+ var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
846
+ if (existingParameter &&
847
+ existingParameter.description &&
848
+ existingParameter.description !== parameterDescription &&
849
+ parameterDescription) {
850
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
851
+ }
852
+ if (existingParameter) {
853
+ if (parameterDescription) {
854
+ existingParameter.description = parameterDescription;
855
+ }
856
+ }
857
+ else {
858
+ promptbookJson.parameters.push({
859
+ name: parameterName,
860
+ description: parameterDescription || undefined,
861
+ isInput: isInput,
862
+ isOutput: isOutput,
863
+ });
864
+ }
865
+ };
866
+ // =============================================================
867
+ // Note: 3️⃣ Parse the dynamic part - the template pipeline
868
+ var markdownStructure = markdownToMarkdownStructure(promptbookString);
869
+ var markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
870
+ if (markdownStructureDeepness !== 2) {
871
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
872
+ }
873
+ promptbookJson.title = markdownStructure.title;
874
+ // TODO: [1] DRY description
875
+ var description = markdownStructure.content;
876
+ // Note: Remove codeblocks
877
+ description = description.split(/^```.*^```/gms).join('');
878
+ //Note: Remove lists and return statement
879
+ description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
880
+ description = spaceTrim(description);
881
+ if (description === '') {
882
+ description = undefined;
883
+ }
884
+ promptbookJson.description = description;
885
+ var defaultModelRequirements = {};
886
+ var listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
887
+ try {
888
+ for (var listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
889
+ var listItem = listItems_1_1.value;
890
+ var command = parseCommand(listItem);
891
+ switch (command.type) {
892
+ case 'PROMPTBOOK_URL':
893
+ promptbookJson.promptbookUrl = command.promptbookUrl.href;
894
+ break;
895
+ case 'PROMPTBOOK_VERSION':
896
+ promptbookJson.promptbookVersion = command.promptbookVersion;
897
+ break;
898
+ case 'MODEL':
899
+ defaultModelRequirements[command.key] = command.value;
900
+ break;
901
+ case 'PARAMETER':
902
+ addParam(command);
903
+ break;
904
+ default:
905
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
906
+ }
907
+ }
908
+ }
909
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
910
+ finally {
911
+ try {
912
+ if (listItems_1_1 && !listItems_1_1.done && (_a = listItems_1.return)) _a.call(listItems_1);
913
+ }
914
+ finally { if (e_1) throw e_1.error; }
915
+ }
916
+ var _loop_1 = function (section) {
917
+ var e_3, _e, e_4, _f, e_5, _g;
918
+ // TODO: Parse prompt template description (the content out of the codeblock and lists)
919
+ var templateModelRequirements = __assign({}, defaultModelRequirements);
920
+ var listItems_3 = extractAllListItemsFromMarkdown(section.content);
921
+ var dependentParameterNames = [];
922
+ var executionType = 'PROMPT_TEMPLATE';
923
+ var jokers = [];
924
+ var postprocessing = [];
925
+ var expectAmount = {};
926
+ var expectFormat = undefined;
927
+ var isExecutionTypeChanged = false;
928
+ try {
929
+ for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
930
+ var listItem = listItems_2_1.value;
931
+ var command = parseCommand(listItem);
932
+ switch (command.type) {
933
+ case 'JOKER':
934
+ jokers.push(command.parameterName);
935
+ dependentParameterNames.push(command.parameterName);
936
+ break;
937
+ case 'EXECUTE':
938
+ if (isExecutionTypeChanged) {
939
+ throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
940
+ }
941
+ executionType = command.executionType;
942
+ isExecutionTypeChanged = true;
943
+ break;
944
+ case 'MODEL':
945
+ templateModelRequirements[command.key] = command.value;
946
+ break;
947
+ case 'PARAMETER':
948
+ // Note: This is just for detecting resulitng parameter name
949
+ addParam(command);
950
+ break;
951
+ case 'POSTPROCESS':
952
+ postprocessing.push(command.functionName);
953
+ break;
954
+ case 'EXPECT_AMOUNT':
955
+ // eslint-disable-next-line no-case-declarations
956
+ var unit = command.unit.toLowerCase();
957
+ expectAmount[unit] = expectAmount[unit] || {};
958
+ if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
959
+ if (expectAmount[unit].min !== undefined) {
960
+ throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
961
+ }
962
+ expectAmount[unit].min = command.amount;
963
+ } /* not else */
964
+ if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
965
+ if (expectAmount[unit].max !== undefined) {
966
+ throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
967
+ }
968
+ expectAmount[unit].max = command.amount;
969
+ }
970
+ break;
971
+ case 'EXPECT_FORMAT':
972
+ if (expectFormat !== undefined && command.format !== expectFormat) {
973
+ throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
974
+ }
975
+ expectFormat = command.format;
976
+ break;
977
+ default:
978
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
979
+ }
980
+ }
981
+ }
982
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
983
+ finally {
984
+ try {
985
+ if (listItems_2_1 && !listItems_2_1.done && (_e = listItems_2.return)) _e.call(listItems_2);
986
+ }
987
+ finally { if (e_3) throw e_3.error; }
988
+ }
989
+ var _h = extractOneBlockFromMarkdown(section.content), language = _h.language, content = _h.content;
990
+ if (executionType === 'SCRIPT') {
991
+ if (!language) {
992
+ throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
993
+ }
994
+ else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
995
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
996
+ }
997
+ }
998
+ var lastLine = section.content.split('\n').pop();
999
+ var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1000
+ if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1001
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1002
+ // TODO: Show code of invalid sections each time + DRY
1003
+ section.content
1004
+ .split('\n')
1005
+ .map(function (line) { return "> ".concat(line); })
1006
+ .join('\n')), "\n "); }));
1007
+ }
1008
+ var resultingParameterName = match.groups.resultingParamName;
1009
+ // TODO: [1] DRY description
1010
+ var description_1 = section.content;
1011
+ // Note: Remove codeblocks
1012
+ description_1 = description_1.split(/^```.*^```/gms).join('');
1013
+ //Note: Remove lists and return statement
1014
+ description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1015
+ description_1 = spaceTrim(description_1);
1016
+ if (description_1 === '') {
1017
+ description_1 = undefined;
1018
+ }
1019
+ if (Object.keys(jokers).length === 0) {
1020
+ jokers = undefined;
1021
+ }
1022
+ if (Object.keys(expectAmount).length === 0) {
1023
+ expectAmount = undefined;
1024
+ }
1025
+ if (Object.keys(postprocessing).length === 0) {
1026
+ postprocessing = undefined;
1027
+ }
1028
+ try {
1029
+ for (var _j = (e_4 = void 0, __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(section.title)), false), __read(extractParameters(description_1 || '')), false), __read(extractParameters(content)), false))), _k = _j.next(); !_k.done; _k = _j.next()) {
1030
+ var parameterName = _k.value;
1031
+ dependentParameterNames.push(parameterName);
1032
+ }
1033
+ }
1034
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1035
+ finally {
1036
+ try {
1037
+ if (_k && !_k.done && (_f = _j.return)) _f.call(_j);
1038
+ }
1039
+ finally { if (e_4) throw e_4.error; }
1040
+ }
1041
+ if (executionType === 'SCRIPT') {
1042
+ try {
1043
+ for (var _l = (e_5 = void 0, __values(extractVariables(content))), _m = _l.next(); !_m.done; _m = _l.next()) {
1044
+ var parameterName = _m.value;
1045
+ dependentParameterNames.push(parameterName);
1046
+ }
1047
+ }
1048
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
1049
+ finally {
1050
+ try {
1051
+ if (_m && !_m.done && (_g = _l.return)) _g.call(_l);
1052
+ }
1053
+ finally { if (e_5) throw e_5.error; }
1054
+ }
1055
+ }
1056
+ dependentParameterNames = __spreadArray([], __read(new Set(dependentParameterNames)), false);
1057
+ promptbookJson.promptTemplates.push({
1058
+ name: normalizeTo_PascalCase(section.title),
1059
+ title: section.title,
1060
+ description: description_1,
1061
+ dependentParameterNames: dependentParameterNames,
1062
+ executionType: executionType,
1063
+ jokers: jokers,
1064
+ postprocessing: postprocessing,
1065
+ expectAmount: expectAmount,
1066
+ expectFormat: expectFormat,
1067
+ modelRequirements: templateModelRequirements,
1068
+ contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1069
+ content: content,
1070
+ resultingParameterName: resultingParameterName,
1071
+ });
1072
+ };
1073
+ try {
1074
+ for (var _c = __values(markdownStructure.sections), _d = _c.next(); !_d.done; _d = _c.next()) {
1075
+ var section = _d.value;
1076
+ _loop_1(section);
1077
+ }
1078
+ }
1079
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1080
+ finally {
1081
+ try {
1082
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1083
+ }
1084
+ finally { if (e_2) throw e_2.error; }
1085
+ }
1086
+ // =============================================================
1087
+ return promptbookJson;
1088
+ }
1089
+ /**
1090
+ * TODO: Report here line/column of error
1091
+ * TODO: Use spaceTrim more effectively
1092
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1092
1093
  */
1093
1094
 
1094
- /**
1095
- * Add or modify an auto-generated section in a markdown file
1096
- *
1097
- * @private within the library
1098
- */
1099
- function addAutoGeneratedSection(content, options) {
1100
- var sectionName = options.sectionName, sectionContent = options.sectionContent;
1101
- var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1102
- var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1103
- var sectionMatch = content.match(sectionRegex);
1104
- if (sectionMatch) {
1105
- return content.replace(sectionRegex, spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1106
- }
1107
- var placeForSection = content.match(/^##.*$/im);
1108
- if (!placeForSection) {
1109
- throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1110
- }
1111
- var _a = __read(placeForSection, 1), heading = _a[0];
1112
- return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1095
+ /**
1096
+ * Add or modify an auto-generated section in a markdown file
1097
+ *
1098
+ * @private within the library
1099
+ */
1100
+ function addAutoGeneratedSection(content, options) {
1101
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
1102
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1103
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1104
+ var sectionMatch = content.match(sectionRegex);
1105
+ if (sectionMatch) {
1106
+ return content.replace(sectionRegex, spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1107
+ }
1108
+ var placeForSection = content.match(/^##.*$/im);
1109
+ if (!placeForSection) {
1110
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1111
+ }
1112
+ var _a = __read(placeForSection, 1), heading = _a[0];
1113
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1113
1114
  }
1114
1115
 
1115
- /**
1116
- * Prettify the html code
1117
- *
1118
- * @param html raw html code
1119
- * @returns formatted html code
1120
- */
1121
- function prettifyMarkdown(html) {
1122
- try {
1123
- return format(html, {
1124
- parser: 'markdown',
1125
- plugins: [parserHtml],
1126
- // TODO: DRY - make some import or auto-copy of .prettierrc
1127
- endOfLine: 'lf',
1128
- tabWidth: 4,
1129
- singleQuote: true,
1130
- trailingComma: 'all',
1131
- arrowParens: 'always',
1132
- printWidth: 120,
1133
- htmlWhitespaceSensitivity: 'ignore',
1134
- jsxBracketSameLine: false,
1135
- bracketSpacing: true,
1136
- });
1137
- }
1138
- catch (error) {
1139
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1140
- error: error,
1141
- html: html,
1142
- });
1143
- return html;
1144
- }
1116
+ /**
1117
+ * Prettify the html code
1118
+ *
1119
+ * @param html raw html code
1120
+ * @returns formatted html code
1121
+ */
1122
+ function prettifyMarkdown(html) {
1123
+ try {
1124
+ return format(html, {
1125
+ parser: 'markdown',
1126
+ plugins: [parserHtml],
1127
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1128
+ endOfLine: 'lf',
1129
+ tabWidth: 4,
1130
+ singleQuote: true,
1131
+ trailingComma: 'all',
1132
+ arrowParens: 'always',
1133
+ printWidth: 120,
1134
+ htmlWhitespaceSensitivity: 'ignore',
1135
+ jsxBracketSameLine: false,
1136
+ bracketSpacing: true,
1137
+ });
1138
+ }
1139
+ catch (error) {
1140
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1141
+ error: error,
1142
+ html: html,
1143
+ });
1144
+ return html;
1145
+ }
1145
1146
  }
1146
1147
 
1147
- /**
1148
- * !!!
1149
- */
1150
- function prettifyPromptbookString(promptbookString, options) {
1151
- var isGraphAdded = options.isGraphAdded, isPrettifyed = options.isPrettifyed;
1152
- if (isGraphAdded) {
1153
- var promptbookJson_1 = promptbookStringToJson(promptbookString);
1154
- var parameterNameToTemplateName_1 = function (parameterName) {
1155
- var parameter = promptbookJson_1.parameters.find(function (parameter) { return parameter.name === parameterName; });
1156
- if (!parameter) {
1157
- throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
1158
- }
1159
- if (parameter.isInput) {
1160
- return 'input';
1161
- }
1162
- var template = promptbookJson_1.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
1163
- if (!template) {
1164
- throw new Error("Could not find template for {".concat(parameterName, "}"));
1165
- }
1166
- return 'template' + normalizeTo_PascalCase(template.title);
1167
- };
1168
- var promptbookMermaid_1 = 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_1.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson_1.promptTemplates
1169
- .flatMap(function (_a) {
1170
- var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
1171
- return __spreadArray([
1172
- "".concat(parameterNameToTemplateName_1(resultingParameterName), "(").concat(title, ")")
1173
- ], __read(dependentParameterNames.map(function (dependentParameterName) {
1174
- return "".concat(parameterNameToTemplateName_1(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName_1(resultingParameterName));
1175
- })), false);
1176
- })
1177
- .join('\n')), "\n\n ").concat(block(promptbookJson_1.parameters
1178
- .filter(function (_a) {
1179
- var isOutput = _a.isOutput;
1180
- return isOutput;
1181
- })
1182
- .map(function (_a) {
1183
- var name = _a.name;
1184
- return "".concat(parameterNameToTemplateName_1(name), "--\"{").concat(name, "}\"-->output");
1185
- })
1186
- .join('\n')), "\n output((Output)):::output\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n\n\n "); });
1187
- var promptbookMermaidBlock = spaceTrim(function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
1188
- promptbookString = addAutoGeneratedSection(promptbookString, {
1189
- sectionName: 'Graph',
1190
- sectionContent: promptbookMermaidBlock,
1191
- });
1192
- }
1193
- if (isPrettifyed) {
1194
- promptbookString = prettifyMarkdown(promptbookString);
1195
- }
1196
- return promptbookString;
1197
- }
1198
- /**
1199
- * TODO: [🧠] Should this be here OR in other folder
1200
- * TODO: [🕌] When more than 2 functionalities, split into separate functions
1148
+ /**
1149
+ * !!!
1150
+ */
1151
+ function prettifyPromptbookString(promptbookString, options) {
1152
+ var isGraphAdded = options.isGraphAdded, isPrettifyed = options.isPrettifyed;
1153
+ if (isGraphAdded) {
1154
+ var promptbookJson_1 = promptbookStringToJson(promptbookString);
1155
+ var parameterNameToTemplateName_1 = function (parameterName) {
1156
+ var parameter = promptbookJson_1.parameters.find(function (parameter) { return parameter.name === parameterName; });
1157
+ if (!parameter) {
1158
+ throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
1159
+ }
1160
+ if (parameter.isInput) {
1161
+ return 'input';
1162
+ }
1163
+ var template = promptbookJson_1.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
1164
+ if (!template) {
1165
+ throw new Error("Could not find template for {".concat(parameterName, "}"));
1166
+ }
1167
+ return 'template' + normalizeTo_PascalCase(template.title);
1168
+ };
1169
+ var promptbookMermaid_1 = 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_1.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson_1.promptTemplates
1170
+ .flatMap(function (_a) {
1171
+ var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
1172
+ return __spreadArray([
1173
+ "".concat(parameterNameToTemplateName_1(resultingParameterName), "(").concat(title, ")")
1174
+ ], __read(dependentParameterNames.map(function (dependentParameterName) {
1175
+ return "".concat(parameterNameToTemplateName_1(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName_1(resultingParameterName));
1176
+ })), false);
1177
+ })
1178
+ .join('\n')), "\n\n ").concat(block(promptbookJson_1.parameters
1179
+ .filter(function (_a) {
1180
+ var isOutput = _a.isOutput;
1181
+ return isOutput;
1182
+ })
1183
+ .map(function (_a) {
1184
+ var name = _a.name;
1185
+ return "".concat(parameterNameToTemplateName_1(name), "--\"{").concat(name, "}\"-->output");
1186
+ })
1187
+ .join('\n')), "\n output((Output)):::output\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n\n\n "); });
1188
+ var promptbookMermaidBlock = spaceTrim(function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
1189
+ promptbookString = addAutoGeneratedSection(promptbookString, {
1190
+ sectionName: 'Graph',
1191
+ sectionContent: promptbookMermaidBlock,
1192
+ });
1193
+ }
1194
+ if (isPrettifyed) {
1195
+ promptbookString = prettifyMarkdown(promptbookString);
1196
+ }
1197
+ return promptbookString;
1198
+ }
1199
+ /**
1200
+ * TODO: Maybe use some Mermaid library instead of string templating
1201
+ * TODO: [🧠] Should this be here OR in other folder
1202
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
1201
1203
  */
1202
1204
 
1203
- /**
1204
- * Detects if the code is running in a browser environment in main thread (Not in a web worker)
1205
- */
1206
- new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1207
- /**
1208
- * Detects if the code is running in a Node.js environment
1209
- */
1210
- var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1211
- /**
1212
- * Detects if the code is running in a web worker
1213
- */
1205
+ /**
1206
+ * Detects if the code is running in a browser environment in main thread (Not in a web worker)
1207
+ */
1208
+ new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1209
+ /**
1210
+ * Detects if the code is running in a Node.js environment
1211
+ */
1212
+ var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1213
+ /**
1214
+ * Detects if the code is running in a web worker
1215
+ */
1214
1216
  new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
1215
1217
 
1216
- /**
1217
- * !!! Initialize
1218
- */
1219
- function prettifyPromptbookStringCli() {
1220
- return __awaiter(this, void 0, void 0, function () {
1221
- var program, filesGlob, filePaths, filePaths_1, filePaths_1_1, filePath, promptbookMarkdown, error_1, e_1_1;
1222
- var e_1, _a;
1223
- return __generator(this, function (_b) {
1224
- switch (_b.label) {
1225
- case 0:
1226
- if (!isRunningInNode()) {
1227
- throw new Error(spaceTrim("\n Function prettifyPromptbookStringCli is initiator of CLI script and should be run in Node.js environment.\n\n - In browser use prettifyPromptbookString.\n\n "));
1228
- }
1229
- program = new commander.Command();
1230
- program.version(PROMPTBOOK_VERSION);
1231
- program.argument('<filesGlob>', 'Promptbooks to prettify');
1232
- program.parse(process.argv);
1233
- filesGlob = program.options.filesGlob;
1234
- return [4 /*yield*/, glob(filesGlob)];
1235
- case 1:
1236
- filePaths = _b.sent();
1237
- _b.label = 2;
1238
- case 2:
1239
- _b.trys.push([2, 10, 11, 12]);
1240
- filePaths_1 = __values(filePaths), filePaths_1_1 = filePaths_1.next();
1241
- _b.label = 3;
1242
- case 3:
1243
- if (!!filePaths_1_1.done) return [3 /*break*/, 9];
1244
- filePath = filePaths_1_1.value;
1245
- if (!filePath.endsWith('.ptbk.md')) {
1246
- console.warn(colors.yellow("Skipping prettify of non-promptbook ".concat(filePath)));
1247
- return [3 /*break*/, 8];
1248
- }
1249
- return [4 /*yield*/, readFile(filePath, 'utf-8')];
1250
- case 4:
1251
- promptbookMarkdown = (_b.sent());
1252
- _b.label = 5;
1253
- case 5:
1254
- _b.trys.push([5, 7, , 8]);
1255
- promptbookMarkdown = prettifyPromptbookString(promptbookMarkdown, {
1256
- isGraphAdded: true,
1257
- isPrettifyed: true,
1258
- // <- [🕌]
1259
- });
1260
- return [4 /*yield*/, writeFile(filePath, promptbookMarkdown)];
1261
- case 6:
1262
- _b.sent();
1263
- console.info(colors.america("Prettify ".concat(filePath)));
1264
- return [3 /*break*/, 8];
1265
- case 7:
1266
- error_1 = _b.sent();
1267
- if (!(error_1 instanceof Error)) {
1268
- throw error_1;
1269
- }
1270
- console.info(colors.bgWhite('========================='));
1271
- console.info(colors.red("Prettify error ".concat(filePath)));
1272
- console.error(colors.bgRed(error_1.name));
1273
- console.error(error_1);
1274
- console.info(colors.bgWhite('========================='));
1275
- return [3 /*break*/, 8];
1276
- case 8:
1277
- filePaths_1_1 = filePaths_1.next();
1278
- return [3 /*break*/, 3];
1279
- case 9: return [3 /*break*/, 12];
1280
- case 10:
1281
- e_1_1 = _b.sent();
1282
- e_1 = { error: e_1_1 };
1283
- return [3 /*break*/, 12];
1284
- case 11:
1285
- try {
1286
- if (filePaths_1_1 && !filePaths_1_1.done && (_a = filePaths_1.return)) _a.call(filePaths_1);
1287
- }
1288
- finally { if (e_1) throw e_1.error; }
1289
- return [7 /*endfinally*/];
1290
- case 12: return [2 /*return*/];
1291
- }
1292
- });
1293
- });
1294
- }
1295
- /**
1296
- * TODO: [🥠] Do not export to utils directly, its just for CLI script
1297
- * TODO: [🌰] Use just prettifyPromptbookStringCli
1298
- * Note: 11:11
1218
+ /**
1219
+ * !!! Initialize
1220
+ */
1221
+ function prettifyPromptbookStringCli() {
1222
+ return __awaiter(this, void 0, void 0, function () {
1223
+ var program, prettifyCommand, helloCommand;
1224
+ var _this = this;
1225
+ return __generator(this, function (_a) {
1226
+ if (!isRunningInNode()) {
1227
+ throw new Error(spaceTrim("\n Function prettifyPromptbookStringCli is initiator of CLI script and should be run in Node.js environment.\n\n - In browser use prettifyPromptbookString.\n\n "));
1228
+ }
1229
+ program = new commander.Command();
1230
+ program.name('promptbook');
1231
+ program.version(PROMPTBOOK_VERSION);
1232
+ program.description(spaceTrim("\n Promptbook utilities\n "));
1233
+ prettifyCommand = program.command('prettify');
1234
+ prettifyCommand.description(spaceTrim("\n Iterates over promptbooks and does multiple enhancing operations on them:\n 1) Adds Mermaid graph\n 2) Prettifies the markdown\n "));
1235
+ prettifyCommand.argument('<filesGlob>', 'Promptbooks to prettify as glob pattern');
1236
+ prettifyCommand.option('-i, --ignore <glob>', "Ignore as glob pattern");
1237
+ prettifyCommand.action(function (filesGlob, _a) {
1238
+ var ignore = _a.ignore;
1239
+ return __awaiter(_this, void 0, void 0, function () {
1240
+ var filePaths, filePaths_1, filePaths_1_1, filePath, promptbookMarkdown, error_1, e_1_1;
1241
+ var e_1, _b;
1242
+ return __generator(this, function (_c) {
1243
+ switch (_c.label) {
1244
+ case 0: return [4 /*yield*/, glob(filesGlob, { ignore: ignore })];
1245
+ case 1:
1246
+ filePaths = _c.sent();
1247
+ _c.label = 2;
1248
+ case 2:
1249
+ _c.trys.push([2, 10, 11, 12]);
1250
+ filePaths_1 = __values(filePaths), filePaths_1_1 = filePaths_1.next();
1251
+ _c.label = 3;
1252
+ case 3:
1253
+ if (!!filePaths_1_1.done) return [3 /*break*/, 9];
1254
+ filePath = filePaths_1_1.value;
1255
+ if (!filePath.endsWith('.ptbk.md')) {
1256
+ console.warn(colors.yellow("Skipping prettify of non-promptbook ".concat(filePath)));
1257
+ return [3 /*break*/, 8];
1258
+ }
1259
+ return [4 /*yield*/, readFile(filePath, 'utf-8')];
1260
+ case 4:
1261
+ promptbookMarkdown = (_c.sent());
1262
+ _c.label = 5;
1263
+ case 5:
1264
+ _c.trys.push([5, 7, , 8]);
1265
+ promptbookMarkdown = prettifyPromptbookString(promptbookMarkdown, {
1266
+ isGraphAdded: true,
1267
+ isPrettifyed: true,
1268
+ // <- [🕌]
1269
+ });
1270
+ return [4 /*yield*/, writeFile(filePath, promptbookMarkdown)];
1271
+ case 6:
1272
+ _c.sent();
1273
+ console.info(colors.green("Prettify ".concat(filePath)));
1274
+ return [3 /*break*/, 8];
1275
+ case 7:
1276
+ error_1 = _c.sent();
1277
+ if (!(error_1 instanceof Error)) {
1278
+ throw error_1;
1279
+ }
1280
+ console.info(colors.red("Prettify ".concat(error_1.name, " ").concat(filePath)));
1281
+ console.error(colors.bgRed(error_1.name));
1282
+ console.error(error_1);
1283
+ process.exit(1);
1284
+ return [3 /*break*/, 8];
1285
+ case 8:
1286
+ filePaths_1_1 = filePaths_1.next();
1287
+ return [3 /*break*/, 3];
1288
+ case 9: return [3 /*break*/, 12];
1289
+ case 10:
1290
+ e_1_1 = _c.sent();
1291
+ e_1 = { error: e_1_1 };
1292
+ return [3 /*break*/, 12];
1293
+ case 11:
1294
+ try {
1295
+ if (filePaths_1_1 && !filePaths_1_1.done && (_b = filePaths_1.return)) _b.call(filePaths_1);
1296
+ }
1297
+ finally { if (e_1) throw e_1.error; }
1298
+ return [7 /*endfinally*/];
1299
+ case 12:
1300
+ process.exit(0);
1301
+ return [2 /*return*/];
1302
+ }
1303
+ });
1304
+ });
1305
+ });
1306
+ helloCommand = program.command('hello');
1307
+ helloCommand.description(spaceTrim("\n Just command for testing\n "));
1308
+ helloCommand.argument('<name>', 'Your name');
1309
+ helloCommand.option('-g, --greeting <greeting>', "Greeting", 'Hello');
1310
+ helloCommand.action(function (name, _a) {
1311
+ var greeting = _a.greeting;
1312
+ return __awaiter(_this, void 0, void 0, function () {
1313
+ return __generator(this, function (_b) {
1314
+ switch (_b.label) {
1315
+ case 0:
1316
+ console.info(colors.cyan("".concat(greeting, " ").concat(name)));
1317
+ return [4 /*yield*/, forTime(1000)];
1318
+ case 1:
1319
+ _b.sent();
1320
+ console.info(colors.rainbow("Nice to meet you!"));
1321
+ process.exit(0);
1322
+ return [2 /*return*/];
1323
+ }
1324
+ });
1325
+ });
1326
+ });
1327
+ //------
1328
+ program.parse(process.argv);
1329
+ return [2 /*return*/];
1330
+ });
1331
+ });
1332
+ }
1333
+ /**
1334
+ * TODO: [🥠] Do not export to utils directly, its just for CLI script
1335
+ * TODO: [🕌] When more functionalities, rename
1336
+ * Note: 11:11
1299
1337
  */
1300
1338
 
1301
- /**
1302
- * This error indicates errors during the execution of the promptbook
1303
- */
1304
- var PromptbookExecutionError = /** @class */ (function (_super) {
1305
- __extends(PromptbookExecutionError, _super);
1306
- function PromptbookExecutionError(message) {
1307
- var _this = _super.call(this, message) || this;
1308
- _this.name = 'PromptbookExecutionError';
1309
- Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
1310
- return _this;
1311
- }
1312
- return PromptbookExecutionError;
1339
+ /**
1340
+ * This error indicates errors during the execution of the promptbook
1341
+ */
1342
+ var PromptbookExecutionError = /** @class */ (function (_super) {
1343
+ __extends(PromptbookExecutionError, _super);
1344
+ function PromptbookExecutionError(message) {
1345
+ var _this = _super.call(this, message) || this;
1346
+ _this.name = 'PromptbookExecutionError';
1347
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
1348
+ return _this;
1349
+ }
1350
+ return PromptbookExecutionError;
1313
1351
  }(Error));
1314
1352
 
1315
- /**
1316
- * Asserts that the execution of a promptnook is successful
1317
- *
1318
- * @param executionResult - The partial result of the promptnook execution
1319
- * @throws Error - If the execution is not successful or if multiple errors occurred
1320
- */
1321
- function assertsExecutionSuccessful(executionResult) {
1322
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
1323
- if (isSuccessful === true) {
1324
- return;
1325
- }
1326
- if (errors.length === 0) {
1327
- throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
1328
- }
1329
- else if (errors.length === 1) {
1330
- throw errors[0];
1331
- }
1332
- else {
1333
- throw new PromptbookExecutionError(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 "); }));
1334
- }
1335
- }
1336
- /**
1337
- * TODO: [🧠] Can this return type be better typed than void
1353
+ /**
1354
+ * Asserts that the execution of a promptnook is successful
1355
+ *
1356
+ * @param executionResult - The partial result of the promptnook execution
1357
+ * @throws Error - If the execution is not successful or if multiple errors occurred
1358
+ */
1359
+ function assertsExecutionSuccessful(executionResult) {
1360
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
1361
+ if (isSuccessful === true) {
1362
+ return;
1363
+ }
1364
+ if (errors.length === 0) {
1365
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
1366
+ }
1367
+ else if (errors.length === 1) {
1368
+ throw errors[0];
1369
+ }
1370
+ else {
1371
+ throw new PromptbookExecutionError(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 "); }));
1372
+ }
1373
+ }
1374
+ /**
1375
+ * TODO: [🧠] Can this return type be better typed than void
1338
1376
  */
1339
1377
 
1340
- /**
1341
- * Default options for generating an execution report string
1342
- */
1343
- var ExecutionReportStringOptionsDefaults = {
1344
- taxRate: 0,
1345
- chartsWidth: 36,
1378
+ /**
1379
+ * Default options for generating an execution report string
1380
+ */
1381
+ var ExecutionReportStringOptionsDefaults = {
1382
+ taxRate: 0,
1383
+ chartsWidth: 36,
1346
1384
  };
1347
1385
 
1348
- /**
1349
- * Format either small or big number
1350
- *
1351
- * @private within the library
1352
- */
1353
- function formatNumber(value) {
1354
- if (value === 0) {
1355
- return '0';
1356
- }
1357
- for (var exponent = 0; exponent < 15; exponent++) {
1358
- var factor = Math.pow(10, exponent);
1359
- var valueRounded = Math.round(value * factor) / factor;
1360
- if (Math.abs(value - valueRounded) / value <
1361
- 0.001 /* <- TODO: Pass as option, pass to executionReportJsonToString as option */) {
1362
- return valueRounded.toFixed(exponent);
1363
- }
1364
- }
1365
- return value.toString();
1386
+ /**
1387
+ * Format either small or big number
1388
+ *
1389
+ * @private within the library
1390
+ */
1391
+ function formatNumber(value) {
1392
+ if (value === 0) {
1393
+ return '0';
1394
+ }
1395
+ for (var exponent = 0; exponent < 15; exponent++) {
1396
+ var factor = Math.pow(10, exponent);
1397
+ var valueRounded = Math.round(value * factor) / factor;
1398
+ if (Math.abs(value - valueRounded) / value <
1399
+ 0.001 /* <- TODO: Pass as option, pass to executionReportJsonToString as option */) {
1400
+ return valueRounded.toFixed(exponent);
1401
+ }
1402
+ }
1403
+ return value.toString();
1366
1404
  }
1367
1405
 
1368
- /**
1369
- * Returns the same value that is passed as argument.
1370
- * No side effects.
1371
- *
1372
- * Note: It can be usefull for leveling indentation
1373
- *
1374
- * @param value any values
1375
- * @returns the same values
1376
- */
1377
- function just(value) {
1378
- if (value === undefined) {
1379
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1380
- return undefined;
1381
- }
1382
- return value;
1406
+ /**
1407
+ * Returns the same value that is passed as argument.
1408
+ * No side effects.
1409
+ *
1410
+ * Note: It can be usefull for leveling indentation
1411
+ *
1412
+ * @param value any values
1413
+ * @returns the same values
1414
+ */
1415
+ function just(value) {
1416
+ if (value === undefined) {
1417
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1418
+ return undefined;
1419
+ }
1420
+ return value;
1383
1421
  }
1384
1422
 
1385
- /**
1386
- * Removes emojis from a string and fix whitespaces
1387
- *
1388
- * @param text with emojis
1389
- * @returns text without emojis
1390
- */
1391
- function removeEmojis(text) {
1392
- // Replace emojis (and also ZWJ sequence) with hyphens
1393
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1394
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1395
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1396
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
1397
- return text;
1423
+ /**
1424
+ * Removes emojis from a string and fix whitespaces
1425
+ *
1426
+ * @param text with emojis
1427
+ * @returns text without emojis
1428
+ */
1429
+ function removeEmojis(text) {
1430
+ // Replace emojis (and also ZWJ sequence) with hyphens
1431
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1432
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1433
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1434
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
1435
+ return text;
1398
1436
  }
1399
1437
 
1400
- /**
1401
- * Create a markdown table from a 2D array of strings
1402
- *
1403
- * @private within the library
1404
- */
1405
- function createMarkdownTable(table) {
1406
- var columnWidths = table.reduce(function (widths, row) {
1407
- row.forEach(function (cell, columnIndex) {
1408
- var cellLength = cell.length;
1409
- if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
1410
- widths[columnIndex] = cellLength;
1411
- }
1412
- });
1413
- return widths;
1414
- }, []);
1415
- var header = "| ".concat(table[0]
1416
- .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
1417
- .join(' | '), " |");
1418
- var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
1419
- var rows = table.slice(1).map(function (row) {
1420
- var paddedRow = row.map(function (cell, columnIndex) {
1421
- return cell.padEnd(columnWidths[columnIndex]);
1422
- });
1423
- return "| ".concat(paddedRow.join(' | '), " |");
1424
- });
1425
- return __spreadArray([header, separator], __read(rows), false).join('\n');
1438
+ /**
1439
+ * Create a markdown table from a 2D array of strings
1440
+ *
1441
+ * @private within the library
1442
+ */
1443
+ function createMarkdownTable(table) {
1444
+ var columnWidths = table.reduce(function (widths, row) {
1445
+ row.forEach(function (cell, columnIndex) {
1446
+ var cellLength = cell.length;
1447
+ if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
1448
+ widths[columnIndex] = cellLength;
1449
+ }
1450
+ });
1451
+ return widths;
1452
+ }, []);
1453
+ var header = "| ".concat(table[0]
1454
+ .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
1455
+ .join(' | '), " |");
1456
+ var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
1457
+ var rows = table.slice(1).map(function (row) {
1458
+ var paddedRow = row.map(function (cell, columnIndex) {
1459
+ return cell.padEnd(columnWidths[columnIndex]);
1460
+ });
1461
+ return "| ".concat(paddedRow.join(' | '), " |");
1462
+ });
1463
+ return __spreadArray([header, separator], __read(rows), false).join('\n');
1426
1464
  }
1427
1465
 
1428
- /**
1429
- * Function createMarkdownChart will draw a chart in markdown from ⬛+🟦 tiles
1430
- *
1431
- * @private within the library
1432
- */
1433
- function createMarkdownChart(options) {
1434
- var e_1, _a;
1435
- var nameHeader = options.nameHeader, valueHeader = options.valueHeader, items = options.items, width = options.width, unitName = options.unitName;
1436
- var from = Math.min.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.from; })), false));
1437
- var to = Math.max.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.to; })), false));
1438
- var scale = width / (to - from);
1439
- var table = [[nameHeader, valueHeader]];
1440
- try {
1441
- for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
1442
- var item = items_1_1.value;
1443
- var before = Math.round((item.from - from) * scale);
1444
- var during = Math.round((item.to - item.from) * scale);
1445
- var after = width - before - during;
1446
- table.push([removeEmojis(item.title).trim(), '░'.repeat(before) + '█'.repeat(during) + '░'.repeat(after)]);
1447
- }
1448
- }
1449
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1450
- finally {
1451
- try {
1452
- if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
1453
- }
1454
- finally { if (e_1) throw e_1.error; }
1455
- }
1456
- var legend = "_Note: Each \u2588 represents ".concat(formatNumber(1 / scale), " ").concat(unitName, ", width of ").concat(valueHeader.toLowerCase(), " is ").concat(formatNumber(to - from), " ").concat(unitName, " = ").concat(width, " squares_");
1457
- return createMarkdownTable(table) + '\n\n' + legend;
1458
- }
1459
- /**
1460
- * TODO: Maybe use Mermain Gant Diagrams
1461
- * @see https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/
1466
+ /**
1467
+ * Function createMarkdownChart will draw a chart in markdown from ⬛+🟦 tiles
1468
+ *
1469
+ * @private within the library
1470
+ */
1471
+ function createMarkdownChart(options) {
1472
+ var e_1, _a;
1473
+ var nameHeader = options.nameHeader, valueHeader = options.valueHeader, items = options.items, width = options.width, unitName = options.unitName;
1474
+ var from = Math.min.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.from; })), false));
1475
+ var to = Math.max.apply(Math, __spreadArray([], __read(items.map(function (item) { return item.to; })), false));
1476
+ var scale = width / (to - from);
1477
+ var table = [[nameHeader, valueHeader]];
1478
+ try {
1479
+ for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
1480
+ var item = items_1_1.value;
1481
+ var before = Math.round((item.from - from) * scale);
1482
+ var during = Math.round((item.to - item.from) * scale);
1483
+ var after = width - before - during;
1484
+ table.push([removeEmojis(item.title).trim(), '░'.repeat(before) + '█'.repeat(during) + '░'.repeat(after)]);
1485
+ }
1486
+ }
1487
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1488
+ finally {
1489
+ try {
1490
+ if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
1491
+ }
1492
+ finally { if (e_1) throw e_1.error; }
1493
+ }
1494
+ var legend = "_Note: Each \u2588 represents ".concat(formatNumber(1 / scale), " ").concat(unitName, ", width of ").concat(valueHeader.toLowerCase(), " is ").concat(formatNumber(to - from), " ").concat(unitName, " = ").concat(width, " squares_");
1495
+ return createMarkdownTable(table) + '\n\n' + legend;
1496
+ }
1497
+ /**
1498
+ * TODO: Maybe use Mermain Gant Diagrams
1499
+ * @see https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/
1462
1500
  */
1463
1501
 
1464
- /**
1465
- * Function escapeMarkdownBlock will escape markdown block if needed
1466
- * It is useful when you want have block in block
1467
- */
1468
- function escapeMarkdownBlock(value) {
1469
- return value.replace(/```/g, '\\`\\`\\`');
1502
+ /**
1503
+ * Function escapeMarkdownBlock will escape markdown block if needed
1504
+ * It is useful when you want have block in block
1505
+ */
1506
+ function escapeMarkdownBlock(value) {
1507
+ return value.replace(/```/g, '\\`\\`\\`');
1470
1508
  }
1471
1509
 
1472
- /**
1473
- * The thresholds for the relative time in the `moment` library.
1474
- *
1475
- * @see https://momentjscom.readthedocs.io/en/latest/moment/07-customization/13-relative-time-threshold/
1476
- */
1477
- var MOMENT_ARG_THRESHOLDS = {
1478
- ss: 3, // <- least number of seconds to be counted in seconds, minus 1. Must be set after setting the `s` unit or without setting the `s` unit.
1510
+ /**
1511
+ * The thresholds for the relative time in the `moment` library.
1512
+ *
1513
+ * @see https://momentjscom.readthedocs.io/en/latest/moment/07-customization/13-relative-time-threshold/
1514
+ */
1515
+ var MOMENT_ARG_THRESHOLDS = {
1516
+ ss: 3, // <- least number of seconds to be counted in seconds, minus 1. Must be set after setting the `s` unit or without setting the `s` unit.
1479
1517
  };
1480
1518
 
1481
- /**
1482
- * Count the duration of working time
1483
- *
1484
- * @private within the library
1485
- */
1486
- function countWorkingDuration(items) {
1487
- var e_1, _a;
1488
- var steps = Array.from(new Set(items.flatMap(function (item) { return [item.from, item.to]; })));
1489
- steps.sort(function (a, b) { return a - b; });
1490
- var intervals = steps.map(function (step, index) { return [step, steps[index + 1] || 0]; }).slice(0, -1);
1491
- var duration = 0;
1492
- var _loop_1 = function (interval) {
1493
- var _b = __read(interval, 2), from = _b[0], to = _b[1];
1494
- if (items.some(function (item) { return item.from < to && item.to > from; })) {
1495
- duration += to - from;
1496
- }
1497
- };
1498
- try {
1499
- for (var intervals_1 = __values(intervals), intervals_1_1 = intervals_1.next(); !intervals_1_1.done; intervals_1_1 = intervals_1.next()) {
1500
- var interval = intervals_1_1.value;
1501
- _loop_1(interval);
1502
- }
1503
- }
1504
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1505
- finally {
1506
- try {
1507
- if (intervals_1_1 && !intervals_1_1.done && (_a = intervals_1.return)) _a.call(intervals_1);
1508
- }
1509
- finally { if (e_1) throw e_1.error; }
1510
- }
1511
- return duration;
1519
+ /**
1520
+ * Count the duration of working time
1521
+ *
1522
+ * @private within the library
1523
+ */
1524
+ function countWorkingDuration(items) {
1525
+ var e_1, _a;
1526
+ var steps = Array.from(new Set(items.flatMap(function (item) { return [item.from, item.to]; })));
1527
+ steps.sort(function (a, b) { return a - b; });
1528
+ var intervals = steps.map(function (step, index) { return [step, steps[index + 1] || 0]; }).slice(0, -1);
1529
+ var duration = 0;
1530
+ var _loop_1 = function (interval) {
1531
+ var _b = __read(interval, 2), from = _b[0], to = _b[1];
1532
+ if (items.some(function (item) { return item.from < to && item.to > from; })) {
1533
+ duration += to - from;
1534
+ }
1535
+ };
1536
+ try {
1537
+ for (var intervals_1 = __values(intervals), intervals_1_1 = intervals_1.next(); !intervals_1_1.done; intervals_1_1 = intervals_1.next()) {
1538
+ var interval = intervals_1_1.value;
1539
+ _loop_1(interval);
1540
+ }
1541
+ }
1542
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1543
+ finally {
1544
+ try {
1545
+ if (intervals_1_1 && !intervals_1_1.done && (_a = intervals_1.return)) _a.call(intervals_1);
1546
+ }
1547
+ finally { if (e_1) throw e_1.error; }
1548
+ }
1549
+ return duration;
1512
1550
  }
1513
1551
 
1514
- /**
1515
- * Converts execution report from JSON to string format
1516
- */
1517
- function executionReportJsonToString(executionReportJson, options) {
1518
- var e_1, _a;
1519
- var _b, _c, _d, _e, _f, _g;
1520
- var _h = __assign(__assign({}, ExecutionReportStringOptionsDefaults), (options || {})), taxRate = _h.taxRate, chartsWidth = _h.chartsWidth;
1521
- var executionReportString = spaceTrim(function (block) { return "\n # ".concat(executionReportJson.title || 'Execution report', "\n\n ").concat(block(executionReportJson.description || ''), "\n "); });
1522
- var headerList = [];
1523
- if (executionReportJson.promptbookUrl) {
1524
- headerList.push("PROMPTBOOK URL ".concat(executionReportJson.promptbookUrl));
1525
- }
1526
- headerList.push("PROMPTBOOK VERSION ".concat(executionReportJson.promptbookUsedVersion) +
1527
- (!executionReportJson.promptbookRequestedVersion
1528
- ? ''
1529
- : " *(requested ".concat(executionReportJson.promptbookRequestedVersion, ")*")));
1530
- if (executionReportJson.promptExecutions.length !== 0) {
1531
- // TODO: What if startedAt OR/AND completedAt is not defined?
1532
- var startedAt = moment(Math.min.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
1533
- .filter(function (promptExecution) { var _a, _b; return (_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start; })
1534
- .map(function (promptExecution) { return moment(promptExecution.result.timing.start).valueOf(); })), false)));
1535
- var completedAt = moment(Math.max.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
1536
- .filter(function (promptExecution) { var _a, _b; return (_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.complete; })
1537
- .map(function (promptExecution) { return moment(promptExecution.result.timing.complete).valueOf(); })), false)));
1538
- var timingItems = executionReportJson.promptExecutions.map(function (promptExecution) {
1539
- var _a, _b, _c, _d;
1540
- return ({
1541
- title: promptExecution.prompt.title,
1542
- from: moment((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start).valueOf() / 1000,
1543
- to: moment((_d = (_c = promptExecution.result) === null || _c === void 0 ? void 0 : _c.timing) === null || _d === void 0 ? void 0 : _d.complete).valueOf() / 1000,
1544
- });
1545
- });
1546
- var costItems = executionReportJson.promptExecutions
1547
- .filter(function (promptExecution) { var _a, _b; return typeof ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) === 'number'; })
1548
- .map(function (promptExecution) {
1549
- var _a, _b;
1550
- return ({
1551
- title: promptExecution.prompt.title,
1552
- from: 0,
1553
- to: ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) * (1 + taxRate),
1554
- });
1555
- });
1556
- var duration = moment.duration(completedAt.diff(startedAt));
1557
- var naturalDuration = moment.duration(countWorkingDuration(timingItems) * 1000);
1558
- var executionsWithKnownCost = executionReportJson.promptExecutions.filter(function (promptExecution) { var _a, _b; return (((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) || 'UNKNOWN') !== 'UNKNOWN'; });
1559
- var cost = executionsWithKnownCost.reduce(function (cost, promptExecution) { return cost + (promptExecution.result.usage.price || 0); }, 0);
1560
- headerList.push("STARTED AT ".concat(moment(startedAt).format("YYYY-MM-DD HH:mm:ss")));
1561
- headerList.push("COMPLETED AT ".concat(moment(completedAt).format("YYYY-MM-DD HH:mm:ss")));
1562
- headerList.push("TOTAL DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
1563
- headerList.push("TOTAL NATURAL DURATION ".concat(naturalDuration.humanize(MOMENT_ARG_THRESHOLDS)));
1564
- headerList.push("TOTAL COST $".concat(formatNumber(cost * (1 + taxRate))) +
1565
- (executionsWithKnownCost.length === executionReportJson.promptExecutions.length
1566
- ? ''
1567
- : " *(Some cost is unknown)*") +
1568
- (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
1569
- executionReportString += '\n\n' + headerList.map(function (header) { return "- ".concat(header); }).join('\n');
1570
- executionReportString +=
1571
- '\n\n' +
1572
- '## 🗃 Index' +
1573
- '\n\n' +
1574
- executionReportJson.promptExecutions
1575
- .map(function (promptExecution) {
1576
- // TODO: Make some better system to convert hedings to links
1577
- var hash = normalizeToKebabCase(promptExecution.prompt.title);
1578
- if (/^\s*\p{Extended_Pictographic}/u.test(promptExecution.prompt.title)) {
1579
- hash = '-' + hash;
1580
- }
1581
- // TODO: Make working hash link for the template in md + pdf
1582
- return "- [".concat(promptExecution.prompt.title, "](#").concat(hash, ")");
1583
- })
1584
- .join('\n');
1585
- executionReportString +=
1586
- '\n\n' +
1587
- '## ⌚ Time chart' +
1588
- '\n\n' +
1589
- createMarkdownChart({
1590
- nameHeader: 'Template',
1591
- valueHeader: 'Timeline',
1592
- items: timingItems,
1593
- width: chartsWidth,
1594
- unitName: 'seconds',
1595
- });
1596
- executionReportString +=
1597
- '\n\n' +
1598
- '## 💸 Cost chart' +
1599
- '\n\n' +
1600
- createMarkdownChart({
1601
- nameHeader: 'Template',
1602
- valueHeader: 'Cost',
1603
- items: costItems,
1604
- width: chartsWidth,
1605
- unitName: 'USD',
1606
- });
1607
- }
1608
- else {
1609
- headerList.push("TOTAL COST $0 *(Nothing executed)*");
1610
- }
1611
- var _loop_1 = function (promptExecution) {
1612
- executionReportString += '\n\n\n\n' + "## ".concat(promptExecution.prompt.title);
1613
- var templateList = [];
1614
- // TODO: What if startedAt OR/AND completedAt is not defined?
1615
- var startedAt = moment((_c = (_b = promptExecution.result) === null || _b === void 0 ? void 0 : _b.timing) === null || _c === void 0 ? void 0 : _c.start);
1616
- var completedAt = moment((_e = (_d = promptExecution.result) === null || _d === void 0 ? void 0 : _d.timing) === null || _e === void 0 ? void 0 : _e.complete);
1617
- var duration = moment.duration(completedAt.diff(startedAt));
1618
- // Not need here:
1619
- // > templateList.push(`STARTED AT ${moment(startedAt).calendar()}`);
1620
- templateList.push("DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
1621
- if (typeof ((_g = (_f = promptExecution.result) === null || _f === void 0 ? void 0 : _f.usage) === null || _g === void 0 ? void 0 : _g.price) === 'number') {
1622
- templateList.push("COST $".concat(formatNumber(promptExecution.result.usage.price * (1 + taxRate))) +
1623
- (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
1624
- }
1625
- else {
1626
- templateList.push("COST UNKNOWN");
1627
- }
1628
- executionReportString += '\n\n' + templateList.map(function (header) { return "- ".concat(header); }).join('\n');
1629
- /*
1630
- - MODEL VARIANT ${promptExecution.prompt.modelRequirements.modelVariant}
1631
- - MODEL NAME \`${promptExecution.result?.model}\` (requested \`${
1632
- promptExecution.prompt.modelRequirements.modelName
1633
-
1634
- */
1635
- if (just(true)) {
1636
- executionReportString +=
1637
- '\n\n\n\n' +
1638
- spaceTrim(function (block) { return "\n\n ### Prompt\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.prompt.content)), "\n ```\n\n "); });
1639
- }
1640
- if (promptExecution.result && promptExecution.result.content) {
1641
- executionReportString +=
1642
- '\n\n\n\n' +
1643
- spaceTrim(function (block) { return "\n\n ### Result\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.result.content)), "\n ```\n "); });
1644
- }
1645
- if (promptExecution.error && promptExecution.error.message) {
1646
- executionReportString +=
1647
- '\n\n\n\n' +
1648
- spaceTrim(function (block) { return "\n\n ### Error\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.error.message)), "\n ```\n\n "); });
1649
- }
1650
- };
1651
- try {
1652
- for (var _j = __values(executionReportJson.promptExecutions), _k = _j.next(); !_k.done; _k = _j.next()) {
1653
- var promptExecution = _k.value;
1654
- _loop_1(promptExecution);
1655
- }
1656
- }
1657
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1658
- finally {
1659
- try {
1660
- if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
1661
- }
1662
- finally { if (e_1) throw e_1.error; }
1663
- }
1664
- executionReportString = prettifyMarkdown(executionReportString);
1665
- return executionReportString;
1666
- }
1667
- /**
1668
- * TODO: Add mermaid chart for every report
1669
- * TODO: [🧠] Allow to filter out some parts of the report by options
1552
+ /**
1553
+ * Converts execution report from JSON to string format
1670
1554
  */
1555
+ function executionReportJsonToString(executionReportJson, options) {
1556
+ var e_1, _a;
1557
+ var _b, _c, _d, _e, _f, _g;
1558
+ var _h = __assign(__assign({}, ExecutionReportStringOptionsDefaults), (options || {})), taxRate = _h.taxRate, chartsWidth = _h.chartsWidth;
1559
+ var executionReportString = spaceTrim(function (block) { return "\n # ".concat(executionReportJson.title || 'Execution report', "\n\n ").concat(block(executionReportJson.description || ''), "\n "); });
1560
+ var headerList = [];
1561
+ if (executionReportJson.promptbookUrl) {
1562
+ headerList.push("PROMPTBOOK URL ".concat(executionReportJson.promptbookUrl));
1563
+ }
1564
+ headerList.push("PROMPTBOOK VERSION ".concat(executionReportJson.promptbookUsedVersion) +
1565
+ (!executionReportJson.promptbookRequestedVersion
1566
+ ? ''
1567
+ : " *(requested ".concat(executionReportJson.promptbookRequestedVersion, ")*")));
1568
+ if (executionReportJson.promptExecutions.length !== 0) {
1569
+ // TODO: What if startedAt OR/AND completedAt is not defined?
1570
+ var startedAt = moment(Math.min.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
1571
+ .filter(function (promptExecution) { var _a, _b; return (_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start; })
1572
+ .map(function (promptExecution) { return moment(promptExecution.result.timing.start).valueOf(); })), false)));
1573
+ var completedAt = moment(Math.max.apply(Math, __spreadArray([], __read(executionReportJson.promptExecutions
1574
+ .filter(function (promptExecution) { var _a, _b; return (_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.complete; })
1575
+ .map(function (promptExecution) { return moment(promptExecution.result.timing.complete).valueOf(); })), false)));
1576
+ var timingItems = executionReportJson.promptExecutions.map(function (promptExecution) {
1577
+ var _a, _b, _c, _d;
1578
+ return ({
1579
+ title: promptExecution.prompt.title,
1580
+ from: moment((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.timing) === null || _b === void 0 ? void 0 : _b.start).valueOf() / 1000,
1581
+ to: moment((_d = (_c = promptExecution.result) === null || _c === void 0 ? void 0 : _c.timing) === null || _d === void 0 ? void 0 : _d.complete).valueOf() / 1000,
1582
+ });
1583
+ });
1584
+ var costItems = executionReportJson.promptExecutions
1585
+ .filter(function (promptExecution) { var _a, _b; return typeof ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) === 'number'; })
1586
+ .map(function (promptExecution) {
1587
+ var _a, _b;
1588
+ return ({
1589
+ title: promptExecution.prompt.title,
1590
+ from: 0,
1591
+ to: ((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) * (1 + taxRate),
1592
+ });
1593
+ });
1594
+ var duration = moment.duration(completedAt.diff(startedAt));
1595
+ var naturalDuration = moment.duration(countWorkingDuration(timingItems) * 1000);
1596
+ var executionsWithKnownCost = executionReportJson.promptExecutions.filter(function (promptExecution) { var _a, _b; return (((_b = (_a = promptExecution.result) === null || _a === void 0 ? void 0 : _a.usage) === null || _b === void 0 ? void 0 : _b.price) || 'UNKNOWN') !== 'UNKNOWN'; });
1597
+ var cost = executionsWithKnownCost.reduce(function (cost, promptExecution) { return cost + (promptExecution.result.usage.price || 0); }, 0);
1598
+ headerList.push("STARTED AT ".concat(moment(startedAt).format("YYYY-MM-DD HH:mm:ss")));
1599
+ headerList.push("COMPLETED AT ".concat(moment(completedAt).format("YYYY-MM-DD HH:mm:ss")));
1600
+ headerList.push("TOTAL DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
1601
+ headerList.push("TOTAL NATURAL DURATION ".concat(naturalDuration.humanize(MOMENT_ARG_THRESHOLDS)));
1602
+ headerList.push("TOTAL COST $".concat(formatNumber(cost * (1 + taxRate))) +
1603
+ (executionsWithKnownCost.length === executionReportJson.promptExecutions.length
1604
+ ? ''
1605
+ : " *(Some cost is unknown)*") +
1606
+ (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
1607
+ executionReportString += '\n\n' + headerList.map(function (header) { return "- ".concat(header); }).join('\n');
1608
+ executionReportString +=
1609
+ '\n\n' +
1610
+ '## 🗃 Index' +
1611
+ '\n\n' +
1612
+ executionReportJson.promptExecutions
1613
+ .map(function (promptExecution) {
1614
+ // TODO: Make some better system to convert hedings to links
1615
+ var hash = normalizeToKebabCase(promptExecution.prompt.title);
1616
+ if (/^\s*\p{Extended_Pictographic}/u.test(promptExecution.prompt.title)) {
1617
+ hash = '-' + hash;
1618
+ }
1619
+ // TODO: Make working hash link for the template in md + pdf
1620
+ return "- [".concat(promptExecution.prompt.title, "](#").concat(hash, ")");
1621
+ })
1622
+ .join('\n');
1623
+ executionReportString +=
1624
+ '\n\n' +
1625
+ '## ⌚ Time chart' +
1626
+ '\n\n' +
1627
+ createMarkdownChart({
1628
+ nameHeader: 'Template',
1629
+ valueHeader: 'Timeline',
1630
+ items: timingItems,
1631
+ width: chartsWidth,
1632
+ unitName: 'seconds',
1633
+ });
1634
+ executionReportString +=
1635
+ '\n\n' +
1636
+ '## 💸 Cost chart' +
1637
+ '\n\n' +
1638
+ createMarkdownChart({
1639
+ nameHeader: 'Template',
1640
+ valueHeader: 'Cost',
1641
+ items: costItems,
1642
+ width: chartsWidth,
1643
+ unitName: 'USD',
1644
+ });
1645
+ }
1646
+ else {
1647
+ headerList.push("TOTAL COST $0 *(Nothing executed)*");
1648
+ }
1649
+ var _loop_1 = function (promptExecution) {
1650
+ executionReportString += '\n\n\n\n' + "## ".concat(promptExecution.prompt.title);
1651
+ var templateList = [];
1652
+ // TODO: What if startedAt OR/AND completedAt is not defined?
1653
+ var startedAt = moment((_c = (_b = promptExecution.result) === null || _b === void 0 ? void 0 : _b.timing) === null || _c === void 0 ? void 0 : _c.start);
1654
+ var completedAt = moment((_e = (_d = promptExecution.result) === null || _d === void 0 ? void 0 : _d.timing) === null || _e === void 0 ? void 0 : _e.complete);
1655
+ var duration = moment.duration(completedAt.diff(startedAt));
1656
+ // Not need here:
1657
+ // > templateList.push(`STARTED AT ${moment(startedAt).calendar()}`);
1658
+ templateList.push("DURATION ".concat(duration.humanize(MOMENT_ARG_THRESHOLDS)));
1659
+ if (typeof ((_g = (_f = promptExecution.result) === null || _f === void 0 ? void 0 : _f.usage) === null || _g === void 0 ? void 0 : _g.price) === 'number') {
1660
+ templateList.push("COST $".concat(formatNumber(promptExecution.result.usage.price * (1 + taxRate))) +
1661
+ (taxRate !== 0 ? " *(with tax ".concat(taxRate * 100, "%)*") : ''));
1662
+ }
1663
+ else {
1664
+ templateList.push("COST UNKNOWN");
1665
+ }
1666
+ executionReportString += '\n\n' + templateList.map(function (header) { return "- ".concat(header); }).join('\n');
1667
+ /*
1668
+ - MODEL VARIANT ${promptExecution.prompt.modelRequirements.modelVariant}
1669
+ - MODEL NAME \`${promptExecution.result?.model}\` (requested \`${
1670
+ promptExecution.prompt.modelRequirements.modelName
1671
1671
 
1672
- /**
1673
- * Counts number of characters in the text
1674
- */
1675
- function countCharacters(text) {
1676
- // Remove null characters
1677
- text = text.replace(/\0/g, '');
1678
- // Replace emojis (and also ZWJ sequence) with hyphens
1679
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1680
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1681
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
1682
- return text.length;
1672
+ */
1673
+ if (just(true)) {
1674
+ executionReportString +=
1675
+ '\n\n\n\n' +
1676
+ spaceTrim(function (block) { return "\n\n ### Prompt\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.prompt.content)), "\n ```\n\n "); });
1677
+ }
1678
+ if (promptExecution.result && promptExecution.result.content) {
1679
+ executionReportString +=
1680
+ '\n\n\n\n' +
1681
+ spaceTrim(function (block) { return "\n\n ### Result\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.result.content)), "\n ```\n "); });
1682
+ }
1683
+ if (promptExecution.error && promptExecution.error.message) {
1684
+ executionReportString +=
1685
+ '\n\n\n\n' +
1686
+ spaceTrim(function (block) { return "\n\n ### Error\n\n ```\n ".concat(block(escapeMarkdownBlock(promptExecution.error.message)), "\n ```\n\n "); });
1687
+ }
1688
+ };
1689
+ try {
1690
+ for (var _j = __values(executionReportJson.promptExecutions), _k = _j.next(); !_k.done; _k = _j.next()) {
1691
+ var promptExecution = _k.value;
1692
+ _loop_1(promptExecution);
1693
+ }
1694
+ }
1695
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1696
+ finally {
1697
+ try {
1698
+ if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
1699
+ }
1700
+ finally { if (e_1) throw e_1.error; }
1701
+ }
1702
+ executionReportString = prettifyMarkdown(executionReportString);
1703
+ return executionReportString;
1683
1704
  }
1705
+ /**
1706
+ * TODO: Add mermaid chart for every report
1707
+ * TODO: [🧠] Allow to filter out some parts of the report by options
1708
+ */
1684
1709
 
1685
- /**
1686
- * Counts number of lines in the text
1687
- */
1688
- function countLines(text) {
1689
- if (text === '') {
1690
- return 0;
1691
- }
1692
- return text.split('\n').length;
1710
+ /**
1711
+ * Counts number of characters in the text
1712
+ */
1713
+ function countCharacters(text) {
1714
+ // Remove null characters
1715
+ text = text.replace(/\0/g, '');
1716
+ // Replace emojis (and also ZWJ sequence) with hyphens
1717
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1718
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1719
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
1720
+ return text.length;
1721
+ }
1722
+
1723
+ /**
1724
+ * Counts number of lines in the text
1725
+ */
1726
+ function countLines(text) {
1727
+ if (text === '') {
1728
+ return 0;
1729
+ }
1730
+ return text.split('\n').length;
1693
1731
  }
1694
1732
 
1695
- /**
1696
- * Counts number of pages in the text
1697
- */
1698
- function countPages(text) {
1699
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
1700
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
1701
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
1702
- return pageCount;
1733
+ /**
1734
+ * Counts number of pages in the text
1735
+ */
1736
+ function countPages(text) {
1737
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
1738
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
1739
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
1740
+ return pageCount;
1703
1741
  }
1704
1742
 
1705
- /**
1706
- * Counts number of paragraphs in the text
1707
- */
1708
- function countParagraphs(text) {
1709
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
1743
+ /**
1744
+ * Counts number of paragraphs in the text
1745
+ */
1746
+ function countParagraphs(text) {
1747
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
1710
1748
  }
1711
1749
 
1712
- /**
1713
- * Counts number of sentences in the text
1714
- */
1715
- function countSentences(text) {
1716
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; }).length;
1750
+ /**
1751
+ * Counts number of sentences in the text
1752
+ */
1753
+ function countSentences(text) {
1754
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; }).length;
1717
1755
  }
1718
1756
 
1719
- /**
1720
- * Counts number of words in the text
1721
- */
1722
- function countWords(text) {
1723
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
1724
- text = removeDiacritics(text);
1725
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
1757
+ /**
1758
+ * Counts number of words in the text
1759
+ */
1760
+ function countWords(text) {
1761
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
1762
+ text = removeDiacritics(text);
1763
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
1726
1764
  }
1727
1765
 
1728
- /**
1729
- * Index of all counter functions
1730
- */
1731
- var CountUtils = {
1732
- CHARACTERS: countCharacters,
1733
- WORDS: countWords,
1734
- SENTENCES: countSentences,
1735
- PARAGRAPHS: countParagraphs,
1736
- LINES: countLines,
1737
- PAGES: countPages,
1766
+ /**
1767
+ * Index of all counter functions
1768
+ */
1769
+ var CountUtils = {
1770
+ CHARACTERS: countCharacters,
1771
+ WORDS: countWords,
1772
+ SENTENCES: countSentences,
1773
+ PARAGRAPHS: countParagraphs,
1774
+ LINES: countLines,
1775
+ PAGES: countPages,
1738
1776
  };
1739
1777
 
1740
- /**
1741
- * Function isValidJsonString will tell you if the string is valid JSON or not
1742
- */
1743
- function isValidJsonString(value) {
1744
- try {
1745
- JSON.parse(value);
1746
- return true;
1747
- }
1748
- catch (error) {
1749
- if (!(error instanceof Error)) {
1750
- throw error;
1751
- }
1752
- if (error.message.includes('Unexpected token')) {
1753
- return false;
1754
- }
1755
- return false;
1756
- }
1778
+ /**
1779
+ * Function isValidJsonString will tell you if the string is valid JSON or not
1780
+ */
1781
+ function isValidJsonString(value) {
1782
+ try {
1783
+ JSON.parse(value);
1784
+ return true;
1785
+ }
1786
+ catch (error) {
1787
+ if (!(error instanceof Error)) {
1788
+ throw error;
1789
+ }
1790
+ if (error.message.includes('Unexpected token')) {
1791
+ return false;
1792
+ }
1793
+ return false;
1794
+ }
1757
1795
  }
1758
1796
 
1759
- /**
1760
- * Extracts code block from markdown.
1761
- *
1762
- * Note: If there are multiple or no code blocks the function throws an error
1763
- *
1764
- * Note: There are 3 simmilar function:
1765
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
1766
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
1767
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
1768
- */
1769
- function extractBlock(markdown) {
1770
- var content = extractOneBlockFromMarkdown(markdown).content;
1771
- return content;
1772
- }
1797
+ /**
1798
+ * Extracts code block from markdown.
1799
+ *
1800
+ * Note: If there are multiple or no code blocks the function throws an error
1801
+ *
1802
+ * Note: There are 3 simmilar function:
1803
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
1804
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
1805
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
1806
+ */
1807
+ function extractBlock(markdown) {
1808
+ var content = extractOneBlockFromMarkdown(markdown).content;
1809
+ return content;
1810
+ }
1773
1811
  //
1774
1812
 
1775
- /**
1776
- * Removes quotes from a string
1777
- *
1778
- * Tip: This is very usefull for post-processing of the result of the LLM model
1779
- * Note: This function removes only the same quotes from the beginning and the end of the string
1780
- * Note: There are two simmilar functions:
1781
- * - `removeQuotes` which removes only bounding quotes
1782
- * - `unwrapResult` which removes whole introduce sentence
1783
- *
1784
- * @param text optionally quoted text
1785
- * @returns text without quotes
1786
- */
1787
- function removeQuotes(text) {
1788
- if (text.startsWith('"') && text.endsWith('"')) {
1789
- return text.slice(1, -1);
1790
- }
1791
- if (text.startsWith('\'') && text.endsWith('\'')) {
1792
- return text.slice(1, -1);
1793
- }
1794
- return text;
1813
+ /**
1814
+ * Removes quotes from a string
1815
+ *
1816
+ * Tip: This is very usefull for post-processing of the result of the LLM model
1817
+ * Note: This function removes only the same quotes from the beginning and the end of the string
1818
+ * Note: There are two simmilar functions:
1819
+ * - `removeQuotes` which removes only bounding quotes
1820
+ * - `unwrapResult` which removes whole introduce sentence
1821
+ *
1822
+ * @param text optionally quoted text
1823
+ * @returns text without quotes
1824
+ */
1825
+ function removeQuotes(text) {
1826
+ if (text.startsWith('"') && text.endsWith('"')) {
1827
+ return text.slice(1, -1);
1828
+ }
1829
+ if (text.startsWith('\'') && text.endsWith('\'')) {
1830
+ return text.slice(1, -1);
1831
+ }
1832
+ return text;
1795
1833
  }
1796
1834
 
1797
- /**
1798
- * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
1799
- *
1800
- * Note: This is usefull for post-processing of the result of the chat LLM model
1801
- * when the model wraps the result in the (markdown) code block.
1802
- *
1803
- */
1804
- function trimCodeBlock(value) {
1805
- value = spaceTrim(value);
1806
- if (!/^```[a-z]*(.*)```$/is.test(value)) {
1807
- return value;
1808
- }
1809
- value = value.replace(/^```[a-z]*/i, '');
1810
- value = value.replace(/```$/i, '');
1811
- value = spaceTrim(value);
1812
- return value;
1835
+ /**
1836
+ * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
1837
+ *
1838
+ * Note: This is usefull for post-processing of the result of the chat LLM model
1839
+ * when the model wraps the result in the (markdown) code block.
1840
+ *
1841
+ */
1842
+ function trimCodeBlock(value) {
1843
+ value = spaceTrim(value);
1844
+ if (!/^```[a-z]*(.*)```$/is.test(value)) {
1845
+ return value;
1846
+ }
1847
+ value = value.replace(/^```[a-z]*/i, '');
1848
+ value = value.replace(/```$/i, '');
1849
+ value = spaceTrim(value);
1850
+ return value;
1813
1851
  }
1814
1852
 
1815
- /**
1816
- * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
1817
- *
1818
- * Note: This is usefull for post-processing of the result of the completion LLM model
1819
- * if you want to start code block in the prompt but you don't want to end it in the result.
1820
- */
1821
- function trimEndOfCodeBlock(value) {
1822
- value = spaceTrim(value);
1823
- value = value.replace(/```$/g, '');
1824
- value = spaceTrim(value);
1825
- return value;
1853
+ /**
1854
+ * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
1855
+ *
1856
+ * Note: This is usefull for post-processing of the result of the completion LLM model
1857
+ * if you want to start code block in the prompt but you don't want to end it in the result.
1858
+ */
1859
+ function trimEndOfCodeBlock(value) {
1860
+ value = spaceTrim(value);
1861
+ value = value.replace(/```$/g, '');
1862
+ value = spaceTrim(value);
1863
+ return value;
1826
1864
  }
1827
1865
 
1828
- /**
1829
- * Removes quotes and optional introduce text from a string
1830
- *
1831
- * Tip: This is very usefull for post-processing of the result of the LLM model
1832
- * Note: This function trims the text and removes whole introduce sentence if it is present
1833
- * Note: There are two simmilar functions:
1834
- * - `removeQuotes` which removes only bounding quotes
1835
- * - `unwrapResult` which removes whole introduce sentence
1836
- *
1837
- * @param text optionally quoted text
1838
- * @returns text without quotes
1839
- */
1840
- function unwrapResult(text, options) {
1841
- var _a = options || {}, _b = _a.isTrimmed, isTrimmed = _b === void 0 ? true : _b, _c = _a.isIntroduceSentenceRemoved, isIntroduceSentenceRemoved = _c === void 0 ? true : _c;
1842
- var trimmedText = text;
1843
- // Remove leading and trailing spaces and newlines
1844
- if (isTrimmed) {
1845
- trimmedText = spaceTrim(trimmedText);
1846
- }
1847
- var processedText = trimmedText;
1848
- if (isIntroduceSentenceRemoved) {
1849
- var introduceSentenceRegex = /^[a-zěščřžýáíéúů:\s]*:\s*/i;
1850
- if (introduceSentenceRegex.test(text)) {
1851
- // Remove the introduce sentence and quotes by replacing it with an empty string
1852
- processedText = processedText.replace(introduceSentenceRegex, '');
1853
- }
1854
- processedText = spaceTrim(processedText);
1855
- }
1856
- if (processedText.length < 3) {
1857
- return trimmedText;
1858
- }
1859
- if (processedText.includes('\n')) {
1860
- return trimmedText;
1861
- }
1862
- // Remove the quotes by extracting the substring without the first and last characters
1863
- var unquotedText = processedText.slice(1, -1);
1864
- // Check if the text starts and ends with quotes
1865
- if ([
1866
- ['"', '"'],
1867
- ["'", "'"],
1868
- ['`', '`'],
1869
- ['*', '*'],
1870
- ['_', '_'],
1871
- ['„', '“'],
1872
- ['«', '»'] /* <- QUOTES to config */,
1873
- ].some(function (_a) {
1874
- var _b = __read(_a, 2), startQuote = _b[0], endQuote = _b[1];
1875
- if (!processedText.startsWith(startQuote)) {
1876
- return false;
1877
- }
1878
- if (!processedText.endsWith(endQuote)) {
1879
- return false;
1880
- }
1881
- if (unquotedText.includes(startQuote) && !unquotedText.includes(endQuote)) {
1882
- return false;
1883
- }
1884
- if (!unquotedText.includes(startQuote) && unquotedText.includes(endQuote)) {
1885
- return false;
1886
- }
1887
- return true;
1888
- })) {
1889
- return unwrapResult(unquotedText, { isTrimmed: false, isIntroduceSentenceRemoved: false });
1890
- }
1891
- else {
1892
- return processedText;
1893
- }
1894
- }
1895
- /**
1896
- * TODO: [🧠] Should this also unwrap the (parenthesis)
1866
+ /**
1867
+ * Removes quotes and optional introduce text from a string
1868
+ *
1869
+ * Tip: This is very usefull for post-processing of the result of the LLM model
1870
+ * Note: This function trims the text and removes whole introduce sentence if it is present
1871
+ * Note: There are two simmilar functions:
1872
+ * - `removeQuotes` which removes only bounding quotes
1873
+ * - `unwrapResult` which removes whole introduce sentence
1874
+ *
1875
+ * @param text optionally quoted text
1876
+ * @returns text without quotes
1877
+ */
1878
+ function unwrapResult(text, options) {
1879
+ var _a = options || {}, _b = _a.isTrimmed, isTrimmed = _b === void 0 ? true : _b, _c = _a.isIntroduceSentenceRemoved, isIntroduceSentenceRemoved = _c === void 0 ? true : _c;
1880
+ var trimmedText = text;
1881
+ // Remove leading and trailing spaces and newlines
1882
+ if (isTrimmed) {
1883
+ trimmedText = spaceTrim(trimmedText);
1884
+ }
1885
+ var processedText = trimmedText;
1886
+ if (isIntroduceSentenceRemoved) {
1887
+ var introduceSentenceRegex = /^[a-zěščřžýáíéúů:\s]*:\s*/i;
1888
+ if (introduceSentenceRegex.test(text)) {
1889
+ // Remove the introduce sentence and quotes by replacing it with an empty string
1890
+ processedText = processedText.replace(introduceSentenceRegex, '');
1891
+ }
1892
+ processedText = spaceTrim(processedText);
1893
+ }
1894
+ if (processedText.length < 3) {
1895
+ return trimmedText;
1896
+ }
1897
+ if (processedText.includes('\n')) {
1898
+ return trimmedText;
1899
+ }
1900
+ // Remove the quotes by extracting the substring without the first and last characters
1901
+ var unquotedText = processedText.slice(1, -1);
1902
+ // Check if the text starts and ends with quotes
1903
+ if ([
1904
+ ['"', '"'],
1905
+ ["'", "'"],
1906
+ ['`', '`'],
1907
+ ['*', '*'],
1908
+ ['_', '_'],
1909
+ ['„', '“'],
1910
+ ['«', '»'] /* <- QUOTES to config */,
1911
+ ].some(function (_a) {
1912
+ var _b = __read(_a, 2), startQuote = _b[0], endQuote = _b[1];
1913
+ if (!processedText.startsWith(startQuote)) {
1914
+ return false;
1915
+ }
1916
+ if (!processedText.endsWith(endQuote)) {
1917
+ return false;
1918
+ }
1919
+ if (unquotedText.includes(startQuote) && !unquotedText.includes(endQuote)) {
1920
+ return false;
1921
+ }
1922
+ if (!unquotedText.includes(startQuote) && unquotedText.includes(endQuote)) {
1923
+ return false;
1924
+ }
1925
+ return true;
1926
+ })) {
1927
+ return unwrapResult(unquotedText, { isTrimmed: false, isIntroduceSentenceRemoved: false });
1928
+ }
1929
+ else {
1930
+ return processedText;
1931
+ }
1932
+ }
1933
+ /**
1934
+ * TODO: [🧠] Should this also unwrap the (parenthesis)
1897
1935
  */
1898
1936
 
1899
- /**
1900
- * Hidden utilities which should not be used by external consumers.
1901
- */
1902
- var __ = {
1903
- // Note: [🥠]
1904
- prettifyPromptbookStringCli: prettifyPromptbookStringCli,
1905
- };
1906
- /**
1907
- * TODO: [🧠] Maybe create some indipendent package like `markdown-tools` from both here exported and @private utilities
1937
+ /**
1938
+ * Hidden utilities which should not be used by external consumers.
1939
+ */
1940
+ var __ = {
1941
+ // Note: [🥠]
1942
+ prettifyPromptbookStringCli: prettifyPromptbookStringCli,
1943
+ };
1944
+ /**
1945
+ * TODO: [🧠] Maybe create some indipendent package like `markdown-tools` from both here exported and @private utilities
1908
1946
  */
1909
1947
 
1910
1948
  export { CountUtils, ExecutionReportStringOptionsDefaults, __, assertsExecutionSuccessful, countCharacters, countLines, countPages, countParagraphs, countSentences, countWords, executionReportJsonToString, extractAllBlocksFromMarkdown, extractAllListItemsFromMarkdown, extractBlock, extractOneBlockFromMarkdown, isValidJsonString, parseNumber, prettifyPromptbookString, removeContentComments, removeEmojis, removeMarkdownFormatting, removeQuotes, trimCodeBlock, trimEndOfCodeBlock, unwrapResult };