@promptbook/markitdown 0.84.0-9 → 0.84.0

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 (43) hide show
  1. package/README.md +21 -9
  2. package/esm/index.es.js +173 -71
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/cli.index.d.ts +4 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +12 -2
  6. package/esm/typings/src/_packages/deepseek.index.d.ts +8 -0
  7. package/esm/typings/src/_packages/types.index.d.ts +2 -0
  8. package/esm/typings/src/_packages/utils.index.d.ts +2 -0
  9. package/esm/typings/src/_packages/wizzard.index.d.ts +4 -0
  10. package/esm/typings/src/cli/cli-commands/about.d.ts +4 -1
  11. package/esm/typings/src/cli/cli-commands/hello.d.ts +3 -1
  12. package/esm/typings/src/cli/cli-commands/list-models.d.ts +3 -1
  13. package/esm/typings/src/cli/cli-commands/list-scrapers.d.ts +13 -0
  14. package/esm/typings/src/cli/cli-commands/make.d.ts +3 -1
  15. package/esm/typings/src/cli/cli-commands/prettify.d.ts +3 -1
  16. package/esm/typings/src/cli/cli-commands/run.d.ts +3 -1
  17. package/esm/typings/src/cli/cli-commands/runInteractiveChatbot.d.ts +1 -1
  18. package/esm/typings/src/cli/cli-commands/test-command.d.ts +3 -1
  19. package/esm/typings/src/config.d.ts +27 -1
  20. package/esm/typings/src/conversion/compilePipelineOnRemoteServer.d.ts +1 -1
  21. package/esm/typings/src/execution/FilesystemTools.d.ts +1 -1
  22. package/esm/typings/src/execution/assertsExecutionSuccessful.d.ts +3 -1
  23. package/esm/typings/src/llm-providers/_common/register/$registeredLlmToolsMessage.d.ts +9 -0
  24. package/esm/typings/src/llm-providers/deepseek/DeepseekExecutionToolsOptions.d.ts +9 -0
  25. package/esm/typings/src/llm-providers/deepseek/createDeepseekExecutionTools.d.ts +14 -0
  26. package/esm/typings/src/llm-providers/deepseek/register-configuration.d.ts +14 -0
  27. package/esm/typings/src/llm-providers/deepseek/register-constructor.d.ts +15 -0
  28. package/esm/typings/src/pipeline/book-notation.d.ts +3 -2
  29. package/esm/typings/src/pipeline/prompt-notation.d.ts +18 -5
  30. package/esm/typings/src/prepare/preparePipelineOnRemoteServer.d.ts +1 -1
  31. package/esm/typings/src/remote-server/socket-types/_subtypes/PromptbookServer_Identification.d.ts +5 -2
  32. package/esm/typings/src/utils/editable/edit-pipeline-string/deflatePipeline.test.d.ts +1 -0
  33. package/esm/typings/src/utils/editable/utils/isFlatPipeline.test.d.ts +1 -0
  34. package/esm/typings/src/utils/environment/$isRunningInBrowser.d.ts +3 -0
  35. package/esm/typings/src/utils/environment/$isRunningInJest.d.ts +3 -0
  36. package/esm/typings/src/utils/environment/$isRunningInNode.d.ts +3 -0
  37. package/esm/typings/src/utils/environment/$isRunningInWebWorker.d.ts +3 -0
  38. package/esm/typings/src/utils/files/mimeTypeToExtension.d.ts +10 -0
  39. package/esm/typings/src/utils/files/mimeTypeToExtension.test.d.ts +1 -0
  40. package/esm/typings/src/wizzard/wizzard.d.ts +7 -1
  41. package/package.json +9 -16
  42. package/umd/index.umd.js +176 -74
  43. package/umd/index.umd.js.map +1 -1
package/umd/index.umd.js CHANGED
@@ -1,14 +1,15 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs/promises'), require('spacetrim'), require('crypto-js'), require('crypto-js/enc-hex'), require('path'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('mime-types'), require('papaparse')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'fs/promises', 'spacetrim', 'crypto-js', 'crypto-js/enc-hex', 'path', 'prettier', 'prettier/parser-html', 'waitasecond', 'mime-types', 'papaparse'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-markitdown"] = {}, global.promises, global.spaceTrim, global.cryptoJs, global.hexEncoder, global.path, global.prettier, global.parserHtml, global.waitasecond, global.mimeTypes, global.papaparse));
5
- })(this, (function (exports, promises, spaceTrim, cryptoJs, hexEncoder, path, prettier, parserHtml, waitasecond, mimeTypes, papaparse) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs/promises'), require('spacetrim'), require('crypto-js'), require('crypto-js/enc-hex'), require('path'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('crypto-js/sha256'), require('mime-types'), require('papaparse')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'fs/promises', 'spacetrim', 'crypto-js', 'crypto-js/enc-hex', 'path', 'prettier', 'prettier/parser-html', 'waitasecond', 'crypto-js/sha256', 'mime-types', 'papaparse'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-markitdown"] = {}, global.promises, global.spaceTrim, global.cryptoJs, global.hexEncoder, global.path, global.prettier, global.parserHtml, global.waitasecond, global.sha256, global.mimeTypes, global.papaparse));
5
+ })(this, (function (exports, promises, spaceTrim, cryptoJs, hexEncoder, path, prettier, parserHtml, waitasecond, sha256, mimeTypes, papaparse) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
9
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
10
10
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
11
11
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
12
+ var sha256__default = /*#__PURE__*/_interopDefaultLegacy(sha256);
12
13
 
13
14
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
14
15
  /**
@@ -24,7 +25,7 @@
24
25
  * @generated
25
26
  * @see https://github.com/webgptorg/promptbook
26
27
  */
27
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-8';
28
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0-21';
28
29
  /**
29
30
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
30
31
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -195,6 +196,12 @@
195
196
  * @public exported from `@promptbook/core`
196
197
  */
197
198
  var DEFAULT_BOOK_TITLE = "\u2728 Untitled Book";
199
+ /**
200
+ * Maximum file size limit
201
+ *
202
+ * @public exported from `@promptbook/core`
203
+ */
204
+ var DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
198
205
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
199
206
  /**
200
207
  * The maximum number of iterations for a loops
@@ -228,6 +235,12 @@
228
235
  * @private within the repository - too low-level in comparison with other `MAX_...`
229
236
  */
230
237
  var IMMEDIATE_TIME = 10;
238
+ /**
239
+ * The maximum length of the (generated) filename
240
+ *
241
+ * @public exported from `@promptbook/core`
242
+ */
243
+ var MAX_FILENAME_LENGTH = 30;
231
244
  /**
232
245
  * Strategy for caching the intermediate results for knowledge sources
233
246
  *
@@ -247,6 +260,15 @@
247
260
  * @public exported from `@promptbook/core`
248
261
  */
249
262
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
263
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
264
+ /**
265
+ * Where to store the temporary downloads
266
+ *
267
+ * Note: When the folder does not exist, it is created recursively
268
+ *
269
+ * @public exported from `@promptbook/core`
270
+ */
271
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
250
272
  /**
251
273
  * Where to store the scrape cache
252
274
  *
@@ -367,6 +389,9 @@
367
389
  * @public exported from `@promptbook/utils`
368
390
  */
369
391
  var $isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
392
+ /**
393
+ * TODO: [☑]
394
+ */
370
395
 
371
396
  /**
372
397
  * Checks if the file exists
@@ -928,24 +953,18 @@
928
953
  var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge from Markdown\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md`\n- INPUT PARAMETER `{knowledgeContent}` Markdown document content\n- OUTPUT PARAMETER `{knowledgePieces}` The knowledge JSON object\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}\n```\n\n`-> {knowledgePieces}`\n"}],sourceFile:"./books/prepare-knowledge-from-markdown.book.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Keywords\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{keywords}` Keywords separated by comma\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}\n```\n\n`-> {keywords}`\n"}],sourceFile:"./books/prepare-knowledge-keywords.book.md"},{title:"Prepare Knowledge-piece Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge-piece Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-title.book.md`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{title}` The title of the document\n\n## Knowledge\n\n- EXPECT MIN 1 WORD\n- EXPECT MAX 8 WORDS\n\n```markdown\nYou are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-knowledge-title.book.md"},{title:"Prepare Persona",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.book.md",formfactorName:"GENERIC",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Persona\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-persona.book.md`\n- INPUT PARAMETER `{availableModelNames}` List of available model names separated by comma (,)\n- INPUT PARAMETER `{personaDescription}` Description of the persona\n- OUTPUT PARAMETER `{modelRequirements}` Specific requirements for the model\n\n## Make modelRequirements\n\n- FORMAT JSON\n\n```markdown\nYou are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n\\`\\`\\`json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n\\`\\`\\`\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}\n```\n\n`-> {modelRequirements}`\n"}],sourceFile:"./books/prepare-persona.book.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-title.book.md",formfactorName:"GENERIC",parameters:[{name:"book",description:"The book to prepare the title for",isInput:true,isOutput:false},{name:"title",description:"Best title for the book",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-title",title:"Make title",content:"Make best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}",resultingParameterName:"title",expectations:{words:{min:1,max:8},lines:{min:1,max:1}},dependentParameterNames:["book"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-title.book.md`\n- INPUT PARAMETER `{book}` The book to prepare the title for\n- OUTPUT PARAMETER `{title}` Best title for the book\n\n## Make title\n\n- EXPECT MIN 1 Word\n- EXPECT MAX 8 Words\n- EXPECT EXACTLY 1 Line\n\n```markdown\nMake best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-title.book.md"}];
929
954
 
930
955
  /**
931
- * Function isValidJsonString will tell you if the string is valid JSON or not
956
+ * Checks if value is valid email
932
957
  *
933
958
  * @public exported from `@promptbook/utils`
934
959
  */
935
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
936
- try {
937
- JSON.parse(value);
938
- return true;
960
+ function isValidEmail(email) {
961
+ if (typeof email !== 'string') {
962
+ return false;
939
963
  }
940
- catch (error) {
941
- if (!(error instanceof Error)) {
942
- throw error;
943
- }
944
- if (error.message.includes('Unexpected token')) {
945
- return false;
946
- }
964
+ if (email.split('\n').length > 1) {
947
965
  return false;
948
966
  }
967
+ return /^.+@.+\..+$/.test(email);
949
968
  }
950
969
 
951
970
  /**
@@ -967,6 +986,27 @@
967
986
  * TODO: Maybe split `ParseError` and `ApplyError`
968
987
  */
969
988
 
989
+ /**
990
+ * Function isValidJsonString will tell you if the string is valid JSON or not
991
+ *
992
+ * @public exported from `@promptbook/utils`
993
+ */
994
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
995
+ try {
996
+ JSON.parse(value);
997
+ return true;
998
+ }
999
+ catch (error) {
1000
+ if (!(error instanceof Error)) {
1001
+ throw error;
1002
+ }
1003
+ if (error.message.includes('Unexpected token')) {
1004
+ return false;
1005
+ }
1006
+ return false;
1007
+ }
1008
+ }
1009
+
970
1010
  /**
971
1011
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
972
1012
  * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
@@ -980,6 +1020,15 @@
980
1020
  if (isValidJsonString(pipelineString)) {
981
1021
  throw new ParseError('Expected a book, but got a JSON string');
982
1022
  }
1023
+ else if (isValidUrl(pipelineString)) {
1024
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
1025
+ }
1026
+ else if (isValidFilePath(pipelineString)) {
1027
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
1028
+ }
1029
+ else if (isValidEmail(pipelineString)) {
1030
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
1031
+ }
983
1032
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
984
1033
  return pipelineString;
985
1034
  }
@@ -2361,12 +2410,28 @@
2361
2410
  /**
2362
2411
  * Asserts that the execution of a Promptbook is successful
2363
2412
  *
2413
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
2414
+ *
2364
2415
  * @param executionResult - The partial result of the Promptbook execution
2365
2416
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
2366
2417
  * @public exported from `@promptbook/core`
2367
2418
  */
2368
2419
  function assertsExecutionSuccessful(executionResult) {
2369
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2420
+ var e_1, _a;
2421
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
2422
+ try {
2423
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
2424
+ var warning = warnings_1_1.value;
2425
+ console.warn(warning.message);
2426
+ }
2427
+ }
2428
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2429
+ finally {
2430
+ try {
2431
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
2432
+ }
2433
+ finally { if (e_1) throw e_1.error; }
2434
+ }
2370
2435
  if (isSuccessful === true) {
2371
2436
  return;
2372
2437
  }
@@ -3003,7 +3068,7 @@
3003
3068
  if (!(error_1 instanceof Error) || error_1 instanceof UnexpectedError) {
3004
3069
  throw error_1;
3005
3070
  }
3006
- errors.push(error_1);
3071
+ errors.push({ llmExecutionTools: llmExecutionTools, error: error_1 });
3007
3072
  return [3 /*break*/, 13];
3008
3073
  case 13:
3009
3074
  _b = _a.next();
@@ -3030,7 +3095,10 @@
3030
3095
  // 2) AnthropicClaude throw PipelineExecutionError: Parameter `{knowledge}` is not defined
3031
3096
  // 3) ...
3032
3097
  spaceTrim__default["default"](function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors
3033
- .map(function (error, i) { return "".concat(i + 1, ") **").concat(error.name || 'Error', ":** ").concat(error.message); })
3098
+ .map(function (_a, i) {
3099
+ var error = _a.error, llmExecutionTools = _a.llmExecutionTools;
3100
+ return "".concat(i + 1, ") **").concat(llmExecutionTools.title, "** thrown **").concat(error.name || 'Error', ":** ").concat(error.message);
3101
+ })
3034
3102
  .join('\n')), "\n\n "); }));
3035
3103
  }
3036
3104
  else if (this.llmExecutionTools.length === 0) {
@@ -3512,6 +3580,17 @@
3512
3580
  return match ? match[1].toLowerCase() : null;
3513
3581
  }
3514
3582
 
3583
+ /**
3584
+ * Convert mime type to file extension
3585
+ *
3586
+ * Note: If the mime type is invalid, `null` is returned
3587
+ *
3588
+ * @private within the repository
3589
+ */
3590
+ function mimeTypeToExtension(value) {
3591
+ return mimeTypes.extension(value) || null;
3592
+ }
3593
+
3515
3594
  /**
3516
3595
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
3517
3596
  *
@@ -3547,9 +3626,9 @@
3547
3626
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3548
3627
  var _a;
3549
3628
  return __awaiter(this, void 0, void 0, function () {
3550
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
3551
- return __generator(this, function (_f) {
3552
- switch (_f.label) {
3629
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, basename, hash, rootDirname_1, filepath, fileContent, _f, _g, filename_1, fileExtension, mimeType;
3630
+ return __generator(this, function (_h) {
3631
+ switch (_h.label) {
3553
3632
  case 0:
3554
3633
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
3555
3634
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
@@ -3558,54 +3637,76 @@
3558
3637
  if (!name) {
3559
3638
  name = knowledgeSourceContentToName(knowledgeSourceContent);
3560
3639
  }
3561
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
3640
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
3562
3641
  url = knowledgeSourceContent;
3563
3642
  return [4 /*yield*/, fetch(url)];
3564
3643
  case 1:
3565
- response_1 = _f.sent();
3644
+ response_1 = _h.sent();
3566
3645
  mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
3567
- return [2 /*return*/, {
3568
- source: name,
3569
- filename: null,
3570
- url: url,
3571
- mimeType: mimeType,
3572
- /*
3573
- TODO: [🥽]
3574
- > async asBlob() {
3575
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3576
- > const content = await response.blob();
3577
- > return content;
3578
- > },
3579
- */
3580
- asJson: function () {
3581
- return __awaiter(this, void 0, void 0, function () {
3582
- var content;
3583
- return __generator(this, function (_a) {
3584
- switch (_a.label) {
3585
- case 0: return [4 /*yield*/, response_1.json()];
3586
- case 1:
3587
- content = _a.sent();
3588
- return [2 /*return*/, content];
3589
- }
3646
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
3647
+ return [2 /*return*/, {
3648
+ source: name,
3649
+ filename: null,
3650
+ url: url,
3651
+ mimeType: mimeType,
3652
+ /*
3653
+ TODO: [🥽]
3654
+ > async asBlob() {
3655
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3656
+ > const content = await response.blob();
3657
+ > return content;
3658
+ > },
3659
+ */
3660
+ asJson: function () {
3661
+ return __awaiter(this, void 0, void 0, function () {
3662
+ var content;
3663
+ return __generator(this, function (_a) {
3664
+ switch (_a.label) {
3665
+ case 0: return [4 /*yield*/, response_1.json()];
3666
+ case 1:
3667
+ content = _a.sent();
3668
+ return [2 /*return*/, content];
3669
+ }
3670
+ });
3590
3671
  });
3591
- });
3592
- },
3593
- asText: function () {
3594
- return __awaiter(this, void 0, void 0, function () {
3595
- var content;
3596
- return __generator(this, function (_a) {
3597
- switch (_a.label) {
3598
- case 0: return [4 /*yield*/, response_1.text()];
3599
- case 1:
3600
- content = _a.sent();
3601
- return [2 /*return*/, content];
3602
- }
3672
+ },
3673
+ asText: function () {
3674
+ return __awaiter(this, void 0, void 0, function () {
3675
+ var content;
3676
+ return __generator(this, function (_a) {
3677
+ switch (_a.label) {
3678
+ case 0: return [4 /*yield*/, response_1.text()];
3679
+ case 1:
3680
+ content = _a.sent();
3681
+ return [2 /*return*/, content];
3682
+ }
3683
+ });
3603
3684
  });
3604
- });
3605
- },
3606
- }];
3685
+ },
3686
+ }];
3687
+ }
3688
+ basename = url.split('/').pop() || titleToName(url);
3689
+ hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
3690
+ rootDirname_1 = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
3691
+ filepath = path.join.apply(void 0, __spreadArray(__spreadArray([], __read(nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */)), false), ["".concat(basename.substring(0, MAX_FILENAME_LENGTH), ".").concat(mimeTypeToExtension(mimeType))], false));
3692
+ return [4 /*yield*/, tools.fs.mkdir(path.dirname(path.join(rootDirname_1, filepath)), { recursive: true })];
3607
3693
  case 2:
3608
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
3694
+ _h.sent();
3695
+ _g = (_f = Buffer).from;
3696
+ return [4 /*yield*/, response_1.arrayBuffer()];
3697
+ case 3:
3698
+ fileContent = _g.apply(_f, [_h.sent()]);
3699
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
3700
+ throw new LimitReachedError("File is too large (".concat(Math.round(fileContent.length / 1024 / 1024), "MB). Maximum allowed size is ").concat(Math.round(DEFAULT_MAX_FILE_SIZE / 1024 / 1024), "MB."));
3701
+ }
3702
+ return [4 /*yield*/, tools.fs.writeFile(path.join(rootDirname_1, filepath), fileContent)];
3703
+ case 4:
3704
+ _h.sent();
3705
+ // TODO: [💵] Check the file security
3706
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
3707
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
3708
+ case 5:
3709
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
3609
3710
  if (tools.fs === undefined) {
3610
3711
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
3611
3712
  // <- TODO: [🧠] What is the best error type here`
@@ -3618,8 +3719,8 @@
3618
3719
  fileExtension = getFileExtension(filename_1);
3619
3720
  mimeType = extensionToMimeType(fileExtension || '');
3620
3721
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
3621
- case 3:
3622
- if (!(_f.sent())) {
3722
+ case 6:
3723
+ if (!(_h.sent())) {
3623
3724
  throw new NotFoundError(spaceTrim__default["default"](function (block) { return "\n Can not make source handler for file which does not exist:\n\n File:\n ".concat(block(knowledgeSourceContent), "\n\n Full file path:\n ").concat(block(filename_1), "\n "); }));
3624
3725
  }
3625
3726
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -3665,7 +3766,7 @@
3665
3766
  });
3666
3767
  },
3667
3768
  }];
3668
- case 4: return [2 /*return*/, {
3769
+ case 7: return [2 /*return*/, {
3669
3770
  source: name,
3670
3771
  filename: null,
3671
3772
  url: null,
@@ -6221,7 +6322,7 @@
6221
6322
  className: 'MarkitdownScraper',
6222
6323
  mimeTypes: [
6223
6324
  'application/pdf',
6224
- // TODO: Make priority for scrapers and than allow all mime types here:
6325
+ // TODO: [💵] Make priority for scrapers and than analyze which mime-types can Markitdown scrape and allow all mime types here:
6225
6326
  // 'text/html',
6226
6327
  // 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
6227
6328
  ],
@@ -6257,10 +6358,10 @@
6257
6358
  this.tools = tools;
6258
6359
  this.options = options;
6259
6360
  this.markdownScraper = new MarkdownScraper(tools, options);
6361
+ // Note: Module `markitdown-ts` has no types available, so it is imported using `require`
6260
6362
  // eslint-disable-next-line @typescript-eslint/no-var-requires
6261
6363
  var MarkItDown = require('markitdown-ts').MarkItDown;
6262
- // <- TODO: !!! Use Markitdown directly not through this package
6263
- // <- Note: !!!!!!!
6364
+ // <- TODO: [🍀] Use Markitdown directly not through this package
6264
6365
  this.markitdown = new MarkItDown();
6265
6366
  }
6266
6367
  Object.defineProperty(MarkitdownScraper.prototype, "metadata", {
@@ -6305,12 +6406,12 @@
6305
6406
  case 2:
6306
6407
  if (!!(_f.sent())) return [3 /*break*/, 5];
6307
6408
  src = source.filename || source.url || null;
6308
- console.log('!!!', { src: src, source: source, cacheFilehandler: cacheFilehandler });
6409
+ // console.log('!!', { src, source, cacheFilehandler });
6309
6410
  if (src === null) {
6310
6411
  throw new UnexpectedError('Source has no filename or url');
6311
6412
  }
6312
6413
  return [4 /*yield*/, this.markitdown.convert(src, {
6313
- // TODO: !!!!!! Pass when sacraping Youtube
6414
+ // TODO: Pass when sacraping Youtube
6314
6415
  // enableYoutubeTranscript: true,
6315
6416
  // youtubeTranscriptLanguage: 'en',
6316
6417
  })];
@@ -6318,11 +6419,12 @@
6318
6419
  result = _f.sent();
6319
6420
  if (result === null || result === undefined) {
6320
6421
  throw new Error("Markitdown could not convert the \"".concat(source.source, "\""));
6321
- // <- TODO: !!! Make MarkitdownError
6422
+ // <- TODO: [🍀] Make MarkitdownError
6322
6423
  }
6323
- console.log('!!!', { result: result, cacheFilehandler: cacheFilehandler });
6424
+ // console.log('!!', { result, cacheFilehandler });
6324
6425
  return [4 /*yield*/, this.tools.fs.writeFile(cacheFilehandler.filename, result.text_content)];
6325
6426
  case 4:
6427
+ // console.log('!!', { result, cacheFilehandler });
6326
6428
  _f.sent();
6327
6429
  _f.label = 5;
6328
6430
  case 5: return [2 /*return*/, cacheFilehandler];