@promptbook/remote-server 0.84.0-10 → 0.84.0-12

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.
package/esm/index.es.js CHANGED
@@ -4,13 +4,14 @@ import { Server } from 'socket.io';
4
4
  import spaceTrim$1, { spaceTrim } from 'spacetrim';
5
5
  import { spawn } from 'child_process';
6
6
  import { forTime } from 'waitasecond';
7
- import { stat, access, constants, readFile, writeFile, readdir } from 'fs/promises';
8
- import { join } from 'path';
7
+ import { stat, access, constants, readFile, writeFile, readdir, mkdir } from 'fs/promises';
8
+ import { join, basename, dirname } from 'path';
9
9
  import { format } from 'prettier';
10
10
  import parserHtml from 'prettier/parser-html';
11
11
  import { unparse, parse } from 'papaparse';
12
- import { SHA256 } from 'crypto-js';
13
12
  import hexEncoder from 'crypto-js/enc-hex';
13
+ import sha256 from 'crypto-js/sha256';
14
+ import { SHA256 } from 'crypto-js';
14
15
  import { lookup } from 'mime-types';
15
16
 
16
17
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
@@ -27,7 +28,7 @@ var BOOK_LANGUAGE_VERSION = '1.0.0';
27
28
  * @generated
28
29
  * @see https://github.com/webgptorg/promptbook
29
30
  */
30
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-9';
31
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0-11';
31
32
  /**
32
33
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
33
34
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -231,6 +232,12 @@ var SMALL_NUMBER = 0.001;
231
232
  * @private within the repository - too low-level in comparison with other `MAX_...`
232
233
  */
233
234
  var IMMEDIATE_TIME = 10;
235
+ /**
236
+ * The maximum length of the (generated) filename
237
+ *
238
+ * @public exported from `@promptbook/core`
239
+ */
240
+ var MAX_FILENAME_LENGTH = 30;
234
241
  /**
235
242
  * Strategy for caching the intermediate results for knowledge sources
236
243
  *
@@ -250,6 +257,15 @@ var DEFAULT_MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
250
257
  * @public exported from `@promptbook/core`
251
258
  */
252
259
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
260
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
261
+ /**
262
+ * Where to store the temporary downloads
263
+ *
264
+ * Note: When the folder does not exist, it is created recursively
265
+ *
266
+ * @public exported from `@promptbook/core`
267
+ */
268
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
253
269
  /**
254
270
  * Where to store the scrape cache
255
271
  *
@@ -858,6 +874,7 @@ function $provideFilesystemForNode(options) {
858
874
  readFile: readFile,
859
875
  writeFile: writeFile,
860
876
  readdir: readdir,
877
+ mkdir: mkdir,
861
878
  };
862
879
  }
863
880
  /**
@@ -1757,6 +1774,99 @@ function createLlmToolsFromConfiguration(configuration, options) {
1757
1774
 
1758
1775
  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"}];
1759
1776
 
1777
+ /**
1778
+ * Checks if value is valid email
1779
+ *
1780
+ * @public exported from `@promptbook/utils`
1781
+ */
1782
+ function isValidEmail(email) {
1783
+ if (typeof email !== 'string') {
1784
+ return false;
1785
+ }
1786
+ if (email.split('\n').length > 1) {
1787
+ return false;
1788
+ }
1789
+ return /^.+@.+\..+$/.test(email);
1790
+ }
1791
+
1792
+ /**
1793
+ * Tests if given string is valid URL.
1794
+ *
1795
+ * Note: This does not check if the file exists only if the path is valid
1796
+ * @public exported from `@promptbook/utils`
1797
+ */
1798
+ function isValidFilePath(filename) {
1799
+ if (typeof filename !== 'string') {
1800
+ return false;
1801
+ }
1802
+ if (filename.split('\n').length > 1) {
1803
+ return false;
1804
+ }
1805
+ if (filename.split(' ').length >
1806
+ 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
1807
+ return false;
1808
+ }
1809
+ var filenameSlashes = filename.split('\\').join('/');
1810
+ // Absolute Unix path: /hello.txt
1811
+ if (/^(\/)/i.test(filenameSlashes)) {
1812
+ // console.log(filename, 'Absolute Unix path: /hello.txt');
1813
+ return true;
1814
+ }
1815
+ // Absolute Windows path: /hello.txt
1816
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
1817
+ // console.log(filename, 'Absolute Windows path: /hello.txt');
1818
+ return true;
1819
+ }
1820
+ // Relative path: ./hello.txt
1821
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
1822
+ // console.log(filename, 'Relative path: ./hello.txt');
1823
+ return true;
1824
+ }
1825
+ // Allow paths like foo/hello
1826
+ if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
1827
+ // console.log(filename, 'Allow paths like foo/hello');
1828
+ return true;
1829
+ }
1830
+ // Allow paths like hello.book
1831
+ if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
1832
+ // console.log(filename, 'Allow paths like hello.book');
1833
+ return true;
1834
+ }
1835
+ return false;
1836
+ }
1837
+ /**
1838
+ * TODO: [🍏] Implement for MacOs
1839
+ */
1840
+
1841
+ /**
1842
+ * Tests if given string is valid URL.
1843
+ *
1844
+ * Note: Dataurl are considered perfectly valid.
1845
+ * Note: There are two simmilar functions:
1846
+ * - `isValidUrl` which tests any URL
1847
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1848
+ *
1849
+ * @public exported from `@promptbook/utils`
1850
+ */
1851
+ function isValidUrl(url) {
1852
+ if (typeof url !== 'string') {
1853
+ return false;
1854
+ }
1855
+ try {
1856
+ if (url.startsWith('blob:')) {
1857
+ url = url.replace(/^blob:/, '');
1858
+ }
1859
+ var urlObject = new URL(url /* because fail is handled */);
1860
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1861
+ return false;
1862
+ }
1863
+ return true;
1864
+ }
1865
+ catch (error) {
1866
+ return false;
1867
+ }
1868
+ }
1869
+
1760
1870
  /**
1761
1871
  * Function isValidJsonString will tell you if the string is valid JSON or not
1762
1872
  *
@@ -1791,6 +1901,15 @@ function validatePipelineString(pipelineString) {
1791
1901
  if (isValidJsonString(pipelineString)) {
1792
1902
  throw new ParseError('Expected a book, but got a JSON string');
1793
1903
  }
1904
+ else if (isValidUrl(pipelineString)) {
1905
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
1906
+ }
1907
+ else if (isValidFilePath(pipelineString)) {
1908
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
1909
+ }
1910
+ else if (isValidEmail(pipelineString)) {
1911
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
1912
+ }
1794
1913
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
1795
1914
  return pipelineString;
1796
1915
  }
@@ -2434,35 +2553,6 @@ function isUrlOnPrivateNetwork(url) {
2434
2553
  return isHostnameOnPrivateNetwork(url.hostname);
2435
2554
  }
2436
2555
 
2437
- /**
2438
- * Tests if given string is valid URL.
2439
- *
2440
- * Note: Dataurl are considered perfectly valid.
2441
- * Note: There are two simmilar functions:
2442
- * - `isValidUrl` which tests any URL
2443
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
2444
- *
2445
- * @public exported from `@promptbook/utils`
2446
- */
2447
- function isValidUrl(url) {
2448
- if (typeof url !== 'string') {
2449
- return false;
2450
- }
2451
- try {
2452
- if (url.startsWith('blob:')) {
2453
- url = url.replace(/^blob:/, '');
2454
- }
2455
- var urlObject = new URL(url /* because fail is handled */);
2456
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
2457
- return false;
2458
- }
2459
- return true;
2460
- }
2461
- catch (error) {
2462
- return false;
2463
- }
2464
- }
2465
-
2466
2556
  /**
2467
2557
  * Tests if given string is valid pipeline URL URL.
2468
2558
  *
@@ -2962,12 +3052,28 @@ function deserializeError(error) {
2962
3052
  /**
2963
3053
  * Asserts that the execution of a Promptbook is successful
2964
3054
  *
3055
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
3056
+ *
2965
3057
  * @param executionResult - The partial result of the Promptbook execution
2966
3058
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
2967
3059
  * @public exported from `@promptbook/core`
2968
3060
  */
2969
3061
  function assertsExecutionSuccessful(executionResult) {
2970
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
3062
+ var e_1, _a;
3063
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
3064
+ try {
3065
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
3066
+ var warning = warnings_1_1.value;
3067
+ console.warn(warning.message);
3068
+ }
3069
+ }
3070
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3071
+ finally {
3072
+ try {
3073
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
3074
+ }
3075
+ finally { if (e_1) throw e_1.error; }
3076
+ }
2971
3077
  if (isSuccessful === true) {
2972
3078
  return;
2973
3079
  }
@@ -5893,6 +5999,22 @@ function $registeredScrapersMessage(availableScrapers) {
5893
5999
  * TODO: [®] DRY Register logic
5894
6000
  */
5895
6001
 
6002
+ /**
6003
+ * Removes emojis from a string and fix whitespaces
6004
+ *
6005
+ * @param text with emojis
6006
+ * @returns text without emojis
6007
+ * @public exported from `@promptbook/utils`
6008
+ */
6009
+ function removeEmojis(text) {
6010
+ // Replace emojis (and also ZWJ sequence) with hyphens
6011
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
6012
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
6013
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
6014
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
6015
+ return text;
6016
+ }
6017
+
5896
6018
  /**
5897
6019
  * @@@
5898
6020
  *
@@ -5955,6 +6077,30 @@ function normalizeToKebabCase(text) {
5955
6077
  * Note: [💞] Ignore a discrepancy between file name and entity name
5956
6078
  */
5957
6079
 
6080
+ /**
6081
+ * @@@
6082
+ *
6083
+ * @param value @@@
6084
+ * @returns @@@
6085
+ * @example @@@
6086
+ * @public exported from `@promptbook/utils`
6087
+ */
6088
+ function titleToName(value) {
6089
+ if (isValidUrl(value)) {
6090
+ value = value.replace(/^https?:\/\//, '');
6091
+ value = value.replace(/\.html$/, '');
6092
+ }
6093
+ else if (isValidFilePath(value)) {
6094
+ value = basename(value);
6095
+ // Note: Keeping extension in the name
6096
+ }
6097
+ value = value.split('/').join('-');
6098
+ value = removeEmojis(value);
6099
+ value = normalizeToKebabCase(value);
6100
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
6101
+ return value;
6102
+ }
6103
+
5958
6104
  /**
5959
6105
  * Creates unique name for the source
5960
6106
  *
@@ -5976,6 +6122,15 @@ function knowledgeSourceContentToName(knowledgeSourceContent) {
5976
6122
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
5977
6123
  */
5978
6124
 
6125
+ /**
6126
+ * @@@
6127
+ *
6128
+ * @private for `FileCacheStorage`
6129
+ */
6130
+ function nameToSubfolderPath(name) {
6131
+ return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
6132
+ }
6133
+
5979
6134
  /**
5980
6135
  * Convert file extension to mime type
5981
6136
  *
@@ -6031,55 +6186,6 @@ function isFileExisting(filename, fs) {
6031
6186
  * TODO: [🖇] What about symlinks?
6032
6187
  */
6033
6188
 
6034
- /**
6035
- * Tests if given string is valid URL.
6036
- *
6037
- * Note: This does not check if the file exists only if the path is valid
6038
- * @public exported from `@promptbook/utils`
6039
- */
6040
- function isValidFilePath(filename) {
6041
- if (typeof filename !== 'string') {
6042
- return false;
6043
- }
6044
- if (filename.split('\n').length > 1) {
6045
- return false;
6046
- }
6047
- if (filename.split(' ').length >
6048
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
6049
- return false;
6050
- }
6051
- var filenameSlashes = filename.split('\\').join('/');
6052
- // Absolute Unix path: /hello.txt
6053
- if (/^(\/)/i.test(filenameSlashes)) {
6054
- // console.log(filename, 'Absolute Unix path: /hello.txt');
6055
- return true;
6056
- }
6057
- // Absolute Windows path: /hello.txt
6058
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
6059
- // console.log(filename, 'Absolute Windows path: /hello.txt');
6060
- return true;
6061
- }
6062
- // Relative path: ./hello.txt
6063
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
6064
- // console.log(filename, 'Relative path: ./hello.txt');
6065
- return true;
6066
- }
6067
- // Allow paths like foo/hello
6068
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
6069
- // console.log(filename, 'Allow paths like foo/hello');
6070
- return true;
6071
- }
6072
- // Allow paths like hello.book
6073
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
6074
- // console.log(filename, 'Allow paths like hello.book');
6075
- return true;
6076
- }
6077
- return false;
6078
- }
6079
- /**
6080
- * TODO: [🍏] Implement for MacOs
6081
- */
6082
-
6083
6189
  /**
6084
6190
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
6085
6191
  *
@@ -6115,10 +6221,11 @@ var scraperFetch = function (url, init) { return __awaiter(void 0, void 0, void
6115
6221
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
6116
6222
  var _a;
6117
6223
  return __awaiter(this, void 0, void 0, function () {
6118
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
6119
- return __generator(this, function (_f) {
6120
- switch (_f.label) {
6224
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response, mimeType, filename, hash, rootDirname_1, filepath, _f, _g, _h, _j, _k, filename_1, fileExtension, mimeType;
6225
+ return __generator(this, function (_l) {
6226
+ switch (_l.label) {
6121
6227
  case 0:
6228
+ console.log('!!! makeKnowledgeSourceHandler', knowledgeSource);
6122
6229
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
6123
6230
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
6124
6231
  name = knowledgeSource.name;
@@ -6126,54 +6233,32 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
6126
6233
  if (!name) {
6127
6234
  name = knowledgeSourceContentToName(knowledgeSourceContent);
6128
6235
  }
6129
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
6236
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
6130
6237
  url = knowledgeSourceContent;
6131
6238
  return [4 /*yield*/, fetch(url)];
6132
6239
  case 1:
6133
- response_1 = _f.sent();
6134
- mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
6135
- return [2 /*return*/, {
6136
- source: name,
6137
- filename: null,
6138
- url: url,
6139
- mimeType: mimeType,
6140
- /*
6141
- TODO: [🥽]
6142
- > async asBlob() {
6143
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
6144
- > const content = await response.blob();
6145
- > return content;
6146
- > },
6147
- */
6148
- asJson: function () {
6149
- return __awaiter(this, void 0, void 0, function () {
6150
- var content;
6151
- return __generator(this, function (_a) {
6152
- switch (_a.label) {
6153
- case 0: return [4 /*yield*/, response_1.json()];
6154
- case 1:
6155
- content = _a.sent();
6156
- return [2 /*return*/, content];
6157
- }
6158
- });
6159
- });
6160
- },
6161
- asText: function () {
6162
- return __awaiter(this, void 0, void 0, function () {
6163
- var content;
6164
- return __generator(this, function (_a) {
6165
- switch (_a.label) {
6166
- case 0: return [4 /*yield*/, response_1.text()];
6167
- case 1:
6168
- content = _a.sent();
6169
- return [2 /*return*/, content];
6170
- }
6171
- });
6172
- });
6173
- },
6174
- }];
6240
+ response = _l.sent();
6241
+ mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
6242
+ filename = url.split('/').pop() || titleToName(url);
6243
+ hash = sha256(hexEncoder.parse(url)).toString( /* hex */);
6244
+ rootDirname_1 = join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
6245
+ filepath = join.apply(void 0, __spreadArray(__spreadArray([], __read(nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */)), false), ["".concat(filename.substring(0, MAX_FILENAME_LENGTH), ".pdf")], false));
6246
+ return [4 /*yield*/, tools.fs.mkdir(dirname(join(rootDirname_1, filepath)), { recursive: true })];
6175
6247
  case 2:
6176
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
6248
+ _l.sent();
6249
+ _g = (_f = tools.fs).writeFile;
6250
+ _h = [join(rootDirname_1, filepath)];
6251
+ _k = (_j = Buffer).from;
6252
+ return [4 /*yield*/, response.arrayBuffer()];
6253
+ case 3: return [4 /*yield*/, _g.apply(_f, _h.concat([_k.apply(_j, [_l.sent()])]))];
6254
+ case 4:
6255
+ _l.sent();
6256
+ // TODO: !!!!!!!! Check the file security
6257
+ // TODO: !!!!!!!! Check the file size (if it is not too big)
6258
+ // TODO: !!!!!!!! Delete the file
6259
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
6260
+ case 5:
6261
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
6177
6262
  if (tools.fs === undefined) {
6178
6263
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
6179
6264
  // <- TODO: [🧠] What is the best error type here`
@@ -6186,8 +6271,8 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
6186
6271
  fileExtension = getFileExtension(filename_1);
6187
6272
  mimeType = extensionToMimeType(fileExtension || '');
6188
6273
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
6189
- case 3:
6190
- if (!(_f.sent())) {
6274
+ case 6:
6275
+ if (!(_l.sent())) {
6191
6276
  throw new NotFoundError(spaceTrim$1(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 "); }));
6192
6277
  }
6193
6278
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -6233,7 +6318,7 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
6233
6318
  });
6234
6319
  },
6235
6320
  }];
6236
- case 4: return [2 /*return*/, {
6321
+ case 7: return [2 /*return*/, {
6237
6322
  source: name,
6238
6323
  filename: null,
6239
6324
  url: null,