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