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