@promptbook/markdown-utils 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 +271 -164
  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 +7 -14
  42. package/umd/index.umd.js +272 -165
  43. package/umd/index.umd.js.map +1 -1
package/esm/index.es.js CHANGED
@@ -2,10 +2,11 @@ import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
2
2
  import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
4
  import { forTime } from 'waitasecond';
5
- import { join, basename } from 'path';
6
- import { SHA256 } from 'crypto-js';
7
5
  import hexEncoder from 'crypto-js/enc-hex';
8
- import { lookup } from 'mime-types';
6
+ import sha256 from 'crypto-js/sha256';
7
+ import { basename, join, dirname } from 'path';
8
+ import { SHA256 } from 'crypto-js';
9
+ import { lookup, extension } from 'mime-types';
9
10
  import { unparse, parse } from 'papaparse';
10
11
 
11
12
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
@@ -22,7 +23,7 @@ var BOOK_LANGUAGE_VERSION = '1.0.0';
22
23
  * @generated
23
24
  * @see https://github.com/webgptorg/promptbook
24
25
  */
25
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-8';
26
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0-21';
26
27
  /**
27
28
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
28
29
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -360,6 +361,99 @@ function extractJsonBlock(markdown) {
360
361
 
361
362
  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"}];
362
363
 
364
+ /**
365
+ * Checks if value is valid email
366
+ *
367
+ * @public exported from `@promptbook/utils`
368
+ */
369
+ function isValidEmail(email) {
370
+ if (typeof email !== 'string') {
371
+ return false;
372
+ }
373
+ if (email.split('\n').length > 1) {
374
+ return false;
375
+ }
376
+ return /^.+@.+\..+$/.test(email);
377
+ }
378
+
379
+ /**
380
+ * Tests if given string is valid URL.
381
+ *
382
+ * Note: This does not check if the file exists only if the path is valid
383
+ * @public exported from `@promptbook/utils`
384
+ */
385
+ function isValidFilePath(filename) {
386
+ if (typeof filename !== 'string') {
387
+ return false;
388
+ }
389
+ if (filename.split('\n').length > 1) {
390
+ return false;
391
+ }
392
+ if (filename.split(' ').length >
393
+ 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
394
+ return false;
395
+ }
396
+ var filenameSlashes = filename.split('\\').join('/');
397
+ // Absolute Unix path: /hello.txt
398
+ if (/^(\/)/i.test(filenameSlashes)) {
399
+ // console.log(filename, 'Absolute Unix path: /hello.txt');
400
+ return true;
401
+ }
402
+ // Absolute Windows path: /hello.txt
403
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
404
+ // console.log(filename, 'Absolute Windows path: /hello.txt');
405
+ return true;
406
+ }
407
+ // Relative path: ./hello.txt
408
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
409
+ // console.log(filename, 'Relative path: ./hello.txt');
410
+ return true;
411
+ }
412
+ // Allow paths like foo/hello
413
+ if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
414
+ // console.log(filename, 'Allow paths like foo/hello');
415
+ return true;
416
+ }
417
+ // Allow paths like hello.book
418
+ if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
419
+ // console.log(filename, 'Allow paths like hello.book');
420
+ return true;
421
+ }
422
+ return false;
423
+ }
424
+ /**
425
+ * TODO: [🍏] Implement for MacOs
426
+ */
427
+
428
+ /**
429
+ * Tests if given string is valid URL.
430
+ *
431
+ * Note: Dataurl are considered perfectly valid.
432
+ * Note: There are two simmilar functions:
433
+ * - `isValidUrl` which tests any URL
434
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
435
+ *
436
+ * @public exported from `@promptbook/utils`
437
+ */
438
+ function isValidUrl(url) {
439
+ if (typeof url !== 'string') {
440
+ return false;
441
+ }
442
+ try {
443
+ if (url.startsWith('blob:')) {
444
+ url = url.replace(/^blob:/, '');
445
+ }
446
+ var urlObject = new URL(url /* because fail is handled */);
447
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
448
+ return false;
449
+ }
450
+ return true;
451
+ }
452
+ catch (error) {
453
+ return false;
454
+ }
455
+ }
456
+
363
457
  /**
364
458
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
365
459
  * 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.
@@ -373,6 +467,15 @@ function validatePipelineString(pipelineString) {
373
467
  if (isValidJsonString(pipelineString)) {
374
468
  throw new ParseError('Expected a book, but got a JSON string');
375
469
  }
470
+ else if (isValidUrl(pipelineString)) {
471
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
472
+ }
473
+ else if (isValidFilePath(pipelineString)) {
474
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
475
+ }
476
+ else if (isValidEmail(pipelineString)) {
477
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
478
+ }
376
479
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
377
480
  return pipelineString;
378
481
  }
@@ -673,6 +776,12 @@ var ADMIN_GITHUB_NAME = 'hejny';
673
776
  * @public exported from `@promptbook/core`
674
777
  */
675
778
  var DEFAULT_BOOK_TITLE = "\u2728 Untitled Book";
779
+ /**
780
+ * Maximum file size limit
781
+ *
782
+ * @public exported from `@promptbook/core`
783
+ */
784
+ var DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
676
785
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
677
786
  /**
678
787
  * The maximum number of iterations for a loops
@@ -706,6 +815,12 @@ var SMALL_NUMBER = 0.001;
706
815
  * @private within the repository - too low-level in comparison with other `MAX_...`
707
816
  */
708
817
  var IMMEDIATE_TIME = 10;
818
+ /**
819
+ * The maximum length of the (generated) filename
820
+ *
821
+ * @public exported from `@promptbook/core`
822
+ */
823
+ var MAX_FILENAME_LENGTH = 30;
709
824
  /**
710
825
  * Strategy for caching the intermediate results for knowledge sources
711
826
  *
@@ -725,6 +840,15 @@ var DEFAULT_MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
725
840
  * @public exported from `@promptbook/core`
726
841
  */
727
842
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
843
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
844
+ /**
845
+ * Where to store the temporary downloads
846
+ *
847
+ * Note: When the folder does not exist, it is created recursively
848
+ *
849
+ * @public exported from `@promptbook/core`
850
+ */
851
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
728
852
  /**
729
853
  * Where to store the scrape cache
730
854
  *
@@ -1207,35 +1331,6 @@ function isUrlOnPrivateNetwork(url) {
1207
1331
  return isHostnameOnPrivateNetwork(url.hostname);
1208
1332
  }
1209
1333
 
1210
- /**
1211
- * Tests if given string is valid URL.
1212
- *
1213
- * Note: Dataurl are considered perfectly valid.
1214
- * Note: There are two simmilar functions:
1215
- * - `isValidUrl` which tests any URL
1216
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1217
- *
1218
- * @public exported from `@promptbook/utils`
1219
- */
1220
- function isValidUrl(url) {
1221
- if (typeof url !== 'string') {
1222
- return false;
1223
- }
1224
- try {
1225
- if (url.startsWith('blob:')) {
1226
- url = url.replace(/^blob:/, '');
1227
- }
1228
- var urlObject = new URL(url /* because fail is handled */);
1229
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1230
- return false;
1231
- }
1232
- return true;
1233
- }
1234
- catch (error) {
1235
- return false;
1236
- }
1237
- }
1238
-
1239
1334
  /**
1240
1335
  * Tests if given string is valid pipeline URL URL.
1241
1336
  *
@@ -1990,12 +2085,28 @@ function deserializeError(error) {
1990
2085
  /**
1991
2086
  * Asserts that the execution of a Promptbook is successful
1992
2087
  *
2088
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
2089
+ *
1993
2090
  * @param executionResult - The partial result of the Promptbook execution
1994
2091
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
1995
2092
  * @public exported from `@promptbook/core`
1996
2093
  */
1997
2094
  function assertsExecutionSuccessful(executionResult) {
1998
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2095
+ var e_1, _a;
2096
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
2097
+ try {
2098
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
2099
+ var warning = warnings_1_1.value;
2100
+ console.warn(warning.message);
2101
+ }
2102
+ }
2103
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2104
+ finally {
2105
+ try {
2106
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
2107
+ }
2108
+ finally { if (e_1) throw e_1.error; }
2109
+ }
1999
2110
  if (isSuccessful === true) {
2000
2111
  return;
2001
2112
  }
@@ -2632,7 +2743,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2632
2743
  if (!(error_1 instanceof Error) || error_1 instanceof UnexpectedError) {
2633
2744
  throw error_1;
2634
2745
  }
2635
- errors.push(error_1);
2746
+ errors.push({ llmExecutionTools: llmExecutionTools, error: error_1 });
2636
2747
  return [3 /*break*/, 13];
2637
2748
  case 13:
2638
2749
  _b = _a.next();
@@ -2659,7 +2770,10 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2659
2770
  // 2) AnthropicClaude throw PipelineExecutionError: Parameter `{knowledge}` is not defined
2660
2771
  // 3) ...
2661
2772
  spaceTrim(function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors
2662
- .map(function (error, i) { return "".concat(i + 1, ") **").concat(error.name || 'Error', ":** ").concat(error.message); })
2773
+ .map(function (_a, i) {
2774
+ var error = _a.error, llmExecutionTools = _a.llmExecutionTools;
2775
+ return "".concat(i + 1, ") **").concat(llmExecutionTools.title, "** thrown **").concat(error.name || 'Error', ":** ").concat(error.message);
2776
+ })
2663
2777
  .join('\n')), "\n\n "); }));
2664
2778
  }
2665
2779
  else if (this.llmExecutionTools.length === 0) {
@@ -3445,6 +3559,15 @@ function knowledgeSourceContentToName(knowledgeSourceContent) {
3445
3559
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
3446
3560
  */
3447
3561
 
3562
+ /**
3563
+ * @@@
3564
+ *
3565
+ * @private for `FileCacheStorage`
3566
+ */
3567
+ function nameToSubfolderPath(name) {
3568
+ return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
3569
+ }
3570
+
3448
3571
  /**
3449
3572
  * Convert file extension to mime type
3450
3573
  *
@@ -3501,53 +3624,55 @@ function isFileExisting(filename, fs) {
3501
3624
  */
3502
3625
 
3503
3626
  /**
3504
- * Tests if given string is valid URL.
3627
+ * Convert mime type to file extension
3505
3628
  *
3506
- * Note: This does not check if the file exists only if the path is valid
3629
+ * Note: If the mime type is invalid, `null` is returned
3630
+ *
3631
+ * @private within the repository
3632
+ */
3633
+ function mimeTypeToExtension(value) {
3634
+ return extension(value) || null;
3635
+ }
3636
+
3637
+ /**
3638
+ * Removes emojis from a string and fix whitespaces
3639
+ *
3640
+ * @param text with emojis
3641
+ * @returns text without emojis
3507
3642
  * @public exported from `@promptbook/utils`
3508
3643
  */
3509
- function isValidFilePath(filename) {
3510
- if (typeof filename !== 'string') {
3511
- return false;
3512
- }
3513
- if (filename.split('\n').length > 1) {
3514
- return false;
3515
- }
3516
- if (filename.split(' ').length >
3517
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
3518
- return false;
3519
- }
3520
- var filenameSlashes = filename.split('\\').join('/');
3521
- // Absolute Unix path: /hello.txt
3522
- if (/^(\/)/i.test(filenameSlashes)) {
3523
- // console.log(filename, 'Absolute Unix path: /hello.txt');
3524
- return true;
3525
- }
3526
- // Absolute Windows path: /hello.txt
3527
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
3528
- // console.log(filename, 'Absolute Windows path: /hello.txt');
3529
- return true;
3530
- }
3531
- // Relative path: ./hello.txt
3532
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
3533
- // console.log(filename, 'Relative path: ./hello.txt');
3534
- return true;
3535
- }
3536
- // Allow paths like foo/hello
3537
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
3538
- // console.log(filename, 'Allow paths like foo/hello');
3539
- return true;
3540
- }
3541
- // Allow paths like hello.book
3542
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
3543
- // console.log(filename, 'Allow paths like hello.book');
3544
- return true;
3545
- }
3546
- return false;
3644
+ function removeEmojis(text) {
3645
+ // Replace emojis (and also ZWJ sequence) with hyphens
3646
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3647
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3648
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
3649
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
3650
+ return text;
3547
3651
  }
3652
+
3548
3653
  /**
3549
- * TODO: [🍏] Implement for MacOs
3654
+ * @@@
3655
+ *
3656
+ * @param value @@@
3657
+ * @returns @@@
3658
+ * @example @@@
3659
+ * @public exported from `@promptbook/utils`
3550
3660
  */
3661
+ function titleToName(value) {
3662
+ if (isValidUrl(value)) {
3663
+ value = value.replace(/^https?:\/\//, '');
3664
+ value = value.replace(/\.html$/, '');
3665
+ }
3666
+ else if (isValidFilePath(value)) {
3667
+ value = basename(value);
3668
+ // Note: Keeping extension in the name
3669
+ }
3670
+ value = value.split('/').join('-');
3671
+ value = removeEmojis(value);
3672
+ value = normalizeToKebabCase(value);
3673
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
3674
+ return value;
3675
+ }
3551
3676
 
3552
3677
  /**
3553
3678
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
@@ -3584,9 +3709,9 @@ var scraperFetch = function (url, init) { return __awaiter(void 0, void 0, void
3584
3709
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3585
3710
  var _a;
3586
3711
  return __awaiter(this, void 0, void 0, function () {
3587
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
3588
- return __generator(this, function (_f) {
3589
- switch (_f.label) {
3712
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, basename, hash, rootDirname_1, filepath, fileContent, _f, _g, filename_1, fileExtension, mimeType;
3713
+ return __generator(this, function (_h) {
3714
+ switch (_h.label) {
3590
3715
  case 0:
3591
3716
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
3592
3717
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
@@ -3595,54 +3720,76 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3595
3720
  if (!name) {
3596
3721
  name = knowledgeSourceContentToName(knowledgeSourceContent);
3597
3722
  }
3598
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
3723
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
3599
3724
  url = knowledgeSourceContent;
3600
3725
  return [4 /*yield*/, fetch(url)];
3601
3726
  case 1:
3602
- response_1 = _f.sent();
3727
+ response_1 = _h.sent();
3603
3728
  mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
3604
- return [2 /*return*/, {
3605
- source: name,
3606
- filename: null,
3607
- url: url,
3608
- mimeType: mimeType,
3609
- /*
3610
- TODO: [🥽]
3611
- > async asBlob() {
3612
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3613
- > const content = await response.blob();
3614
- > return content;
3615
- > },
3616
- */
3617
- asJson: function () {
3618
- return __awaiter(this, void 0, void 0, function () {
3619
- var content;
3620
- return __generator(this, function (_a) {
3621
- switch (_a.label) {
3622
- case 0: return [4 /*yield*/, response_1.json()];
3623
- case 1:
3624
- content = _a.sent();
3625
- return [2 /*return*/, content];
3626
- }
3729
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
3730
+ return [2 /*return*/, {
3731
+ source: name,
3732
+ filename: null,
3733
+ url: url,
3734
+ mimeType: mimeType,
3735
+ /*
3736
+ TODO: [🥽]
3737
+ > async asBlob() {
3738
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3739
+ > const content = await response.blob();
3740
+ > return content;
3741
+ > },
3742
+ */
3743
+ asJson: function () {
3744
+ return __awaiter(this, void 0, void 0, function () {
3745
+ var content;
3746
+ return __generator(this, function (_a) {
3747
+ switch (_a.label) {
3748
+ case 0: return [4 /*yield*/, response_1.json()];
3749
+ case 1:
3750
+ content = _a.sent();
3751
+ return [2 /*return*/, content];
3752
+ }
3753
+ });
3627
3754
  });
3628
- });
3629
- },
3630
- asText: function () {
3631
- return __awaiter(this, void 0, void 0, function () {
3632
- var content;
3633
- return __generator(this, function (_a) {
3634
- switch (_a.label) {
3635
- case 0: return [4 /*yield*/, response_1.text()];
3636
- case 1:
3637
- content = _a.sent();
3638
- return [2 /*return*/, content];
3639
- }
3755
+ },
3756
+ asText: function () {
3757
+ return __awaiter(this, void 0, void 0, function () {
3758
+ var content;
3759
+ return __generator(this, function (_a) {
3760
+ switch (_a.label) {
3761
+ case 0: return [4 /*yield*/, response_1.text()];
3762
+ case 1:
3763
+ content = _a.sent();
3764
+ return [2 /*return*/, content];
3765
+ }
3766
+ });
3640
3767
  });
3641
- });
3642
- },
3643
- }];
3768
+ },
3769
+ }];
3770
+ }
3771
+ basename = url.split('/').pop() || titleToName(url);
3772
+ hash = sha256(hexEncoder.parse(url)).toString( /* hex */);
3773
+ rootDirname_1 = join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
3774
+ filepath = 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));
3775
+ return [4 /*yield*/, tools.fs.mkdir(dirname(join(rootDirname_1, filepath)), { recursive: true })];
3644
3776
  case 2:
3645
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
3777
+ _h.sent();
3778
+ _g = (_f = Buffer).from;
3779
+ return [4 /*yield*/, response_1.arrayBuffer()];
3780
+ case 3:
3781
+ fileContent = _g.apply(_f, [_h.sent()]);
3782
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
3783
+ 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."));
3784
+ }
3785
+ return [4 /*yield*/, tools.fs.writeFile(join(rootDirname_1, filepath), fileContent)];
3786
+ case 4:
3787
+ _h.sent();
3788
+ // TODO: [💵] Check the file security
3789
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
3790
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
3791
+ case 5:
3792
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
3646
3793
  if (tools.fs === undefined) {
3647
3794
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
3648
3795
  // <- TODO: [🧠] What is the best error type here`
@@ -3655,8 +3802,8 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3655
3802
  fileExtension = getFileExtension(filename_1);
3656
3803
  mimeType = extensionToMimeType(fileExtension || '');
3657
3804
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
3658
- case 3:
3659
- if (!(_f.sent())) {
3805
+ case 6:
3806
+ if (!(_h.sent())) {
3660
3807
  throw new NotFoundError(spaceTrim(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 "); }));
3661
3808
  }
3662
3809
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -3702,7 +3849,7 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3702
3849
  });
3703
3850
  },
3704
3851
  }];
3705
- case 4: return [2 /*return*/, {
3852
+ case 7: return [2 /*return*/, {
3706
3853
  source: name,
3707
3854
  filename: null,
3708
3855
  url: null,
@@ -5932,46 +6079,6 @@ function createPipelineExecutor(options) {
5932
6079
  * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5933
6080
  */
5934
6081
 
5935
- /**
5936
- * Removes emojis from a string and fix whitespaces
5937
- *
5938
- * @param text with emojis
5939
- * @returns text without emojis
5940
- * @public exported from `@promptbook/utils`
5941
- */
5942
- function removeEmojis(text) {
5943
- // Replace emojis (and also ZWJ sequence) with hyphens
5944
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
5945
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
5946
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
5947
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
5948
- return text;
5949
- }
5950
-
5951
- /**
5952
- * @@@
5953
- *
5954
- * @param value @@@
5955
- * @returns @@@
5956
- * @example @@@
5957
- * @public exported from `@promptbook/utils`
5958
- */
5959
- function titleToName(value) {
5960
- if (isValidUrl(value)) {
5961
- value = value.replace(/^https?:\/\//, '');
5962
- value = value.replace(/\.html$/, '');
5963
- }
5964
- else if (isValidFilePath(value)) {
5965
- value = basename(value);
5966
- // Note: Keeping extension in the name
5967
- }
5968
- value = value.split('/').join('-');
5969
- value = removeEmojis(value);
5970
- value = normalizeToKebabCase(value);
5971
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
5972
- return value;
5973
- }
5974
-
5975
6082
  /**
5976
6083
  * Metadata of the scraper
5977
6084
  *