@promptbook/node 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
@@ -1,17 +1,17 @@
1
1
  import colors from 'colors';
2
2
  import { stat, access, constants, readFile, writeFile, readdir, mkdir, unlink } from 'fs/promises';
3
- import { join, basename, dirname } from 'path';
3
+ import { basename, join, dirname } from 'path';
4
4
  import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
5
5
  import { format } from 'prettier';
6
6
  import parserHtml from 'prettier/parser-html';
7
7
  import { forTime } from 'waitasecond';
8
8
  import { unparse, parse } from 'papaparse';
9
- import { SHA256 } from 'crypto-js';
10
9
  import hexEncoder from 'crypto-js/enc-hex';
10
+ import sha256 from 'crypto-js/sha256';
11
+ import { SHA256 } from 'crypto-js';
11
12
  import { lookup } from 'mime-types';
12
13
  import { spawn } from 'child_process';
13
14
  import * as dotenv from 'dotenv';
14
- import sha256 from 'crypto-js/sha256';
15
15
 
16
16
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
17
17
  /**
@@ -27,7 +27,7 @@ var BOOK_LANGUAGE_VERSION = '1.0.0';
27
27
  * @generated
28
28
  * @see https://github.com/webgptorg/promptbook
29
29
  */
30
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-9';
30
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0-11';
31
31
  /**
32
32
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
33
33
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -262,6 +262,15 @@ var DEFAULT_MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
262
262
  * @public exported from `@promptbook/core`
263
263
  */
264
264
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
265
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
266
+ /**
267
+ * Where to store the temporary downloads
268
+ *
269
+ * Note: When the folder does not exist, it is created recursively
270
+ *
271
+ * @public exported from `@promptbook/core`
272
+ */
273
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
265
274
  /**
266
275
  * Where to store the scrape cache
267
276
  *
@@ -317,22 +326,94 @@ true);
317
326
  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"}];
318
327
 
319
328
  /**
320
- * Function isValidJsonString will tell you if the string is valid JSON or not
329
+ * Checks if value is valid email
321
330
  *
322
331
  * @public exported from `@promptbook/utils`
323
332
  */
324
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
325
- try {
326
- JSON.parse(value);
333
+ function isValidEmail(email) {
334
+ if (typeof email !== 'string') {
335
+ return false;
336
+ }
337
+ if (email.split('\n').length > 1) {
338
+ return false;
339
+ }
340
+ return /^.+@.+\..+$/.test(email);
341
+ }
342
+
343
+ /**
344
+ * Tests if given string is valid URL.
345
+ *
346
+ * Note: This does not check if the file exists only if the path is valid
347
+ * @public exported from `@promptbook/utils`
348
+ */
349
+ function isValidFilePath(filename) {
350
+ if (typeof filename !== 'string') {
351
+ return false;
352
+ }
353
+ if (filename.split('\n').length > 1) {
354
+ return false;
355
+ }
356
+ if (filename.split(' ').length >
357
+ 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
358
+ return false;
359
+ }
360
+ var filenameSlashes = filename.split('\\').join('/');
361
+ // Absolute Unix path: /hello.txt
362
+ if (/^(\/)/i.test(filenameSlashes)) {
363
+ // console.log(filename, 'Absolute Unix path: /hello.txt');
327
364
  return true;
328
365
  }
329
- catch (error) {
330
- if (!(error instanceof Error)) {
331
- throw error;
366
+ // Absolute Windows path: /hello.txt
367
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
368
+ // console.log(filename, 'Absolute Windows path: /hello.txt');
369
+ return true;
370
+ }
371
+ // Relative path: ./hello.txt
372
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
373
+ // console.log(filename, 'Relative path: ./hello.txt');
374
+ return true;
375
+ }
376
+ // Allow paths like foo/hello
377
+ if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
378
+ // console.log(filename, 'Allow paths like foo/hello');
379
+ return true;
380
+ }
381
+ // Allow paths like hello.book
382
+ if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
383
+ // console.log(filename, 'Allow paths like hello.book');
384
+ return true;
385
+ }
386
+ return false;
387
+ }
388
+ /**
389
+ * TODO: [🍏] Implement for MacOs
390
+ */
391
+
392
+ /**
393
+ * Tests if given string is valid URL.
394
+ *
395
+ * Note: Dataurl are considered perfectly valid.
396
+ * Note: There are two simmilar functions:
397
+ * - `isValidUrl` which tests any URL
398
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
399
+ *
400
+ * @public exported from `@promptbook/utils`
401
+ */
402
+ function isValidUrl(url) {
403
+ if (typeof url !== 'string') {
404
+ return false;
405
+ }
406
+ try {
407
+ if (url.startsWith('blob:')) {
408
+ url = url.replace(/^blob:/, '');
332
409
  }
333
- if (error.message.includes('Unexpected token')) {
410
+ var urlObject = new URL(url /* because fail is handled */);
411
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
334
412
  return false;
335
413
  }
414
+ return true;
415
+ }
416
+ catch (error) {
336
417
  return false;
337
418
  }
338
419
  }
@@ -356,6 +437,27 @@ var ParseError = /** @class */ (function (_super) {
356
437
  * TODO: Maybe split `ParseError` and `ApplyError`
357
438
  */
358
439
 
440
+ /**
441
+ * Function isValidJsonString will tell you if the string is valid JSON or not
442
+ *
443
+ * @public exported from `@promptbook/utils`
444
+ */
445
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
446
+ try {
447
+ JSON.parse(value);
448
+ return true;
449
+ }
450
+ catch (error) {
451
+ if (!(error instanceof Error)) {
452
+ throw error;
453
+ }
454
+ if (error.message.includes('Unexpected token')) {
455
+ return false;
456
+ }
457
+ return false;
458
+ }
459
+ }
460
+
359
461
  /**
360
462
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
361
463
  * 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.
@@ -369,6 +471,15 @@ function validatePipelineString(pipelineString) {
369
471
  if (isValidJsonString(pipelineString)) {
370
472
  throw new ParseError('Expected a book, but got a JSON string');
371
473
  }
474
+ else if (isValidUrl(pipelineString)) {
475
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
476
+ }
477
+ else if (isValidFilePath(pipelineString)) {
478
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
479
+ }
480
+ else if (isValidEmail(pipelineString)) {
481
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
482
+ }
372
483
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
373
484
  return pipelineString;
374
485
  }
@@ -1062,35 +1173,6 @@ function isUrlOnPrivateNetwork(url) {
1062
1173
  return isHostnameOnPrivateNetwork(url.hostname);
1063
1174
  }
1064
1175
 
1065
- /**
1066
- * Tests if given string is valid URL.
1067
- *
1068
- * Note: Dataurl are considered perfectly valid.
1069
- * Note: There are two simmilar functions:
1070
- * - `isValidUrl` which tests any URL
1071
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1072
- *
1073
- * @public exported from `@promptbook/utils`
1074
- */
1075
- function isValidUrl(url) {
1076
- if (typeof url !== 'string') {
1077
- return false;
1078
- }
1079
- try {
1080
- if (url.startsWith('blob:')) {
1081
- url = url.replace(/^blob:/, '');
1082
- }
1083
- var urlObject = new URL(url /* because fail is handled */);
1084
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1085
- return false;
1086
- }
1087
- return true;
1088
- }
1089
- catch (error) {
1090
- return false;
1091
- }
1092
- }
1093
-
1094
1176
  /**
1095
1177
  * Tests if given string is valid pipeline URL URL.
1096
1178
  *
@@ -1845,12 +1927,28 @@ function deserializeError(error) {
1845
1927
  /**
1846
1928
  * Asserts that the execution of a Promptbook is successful
1847
1929
  *
1930
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
1931
+ *
1848
1932
  * @param executionResult - The partial result of the Promptbook execution
1849
1933
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
1850
1934
  * @public exported from `@promptbook/core`
1851
1935
  */
1852
1936
  function assertsExecutionSuccessful(executionResult) {
1853
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
1937
+ var e_1, _a;
1938
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
1939
+ try {
1940
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
1941
+ var warning = warnings_1_1.value;
1942
+ console.warn(warning.message);
1943
+ }
1944
+ }
1945
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1946
+ finally {
1947
+ try {
1948
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
1949
+ }
1950
+ finally { if (e_1) throw e_1.error; }
1951
+ }
1854
1952
  if (isSuccessful === true) {
1855
1953
  return;
1856
1954
  }
@@ -5224,6 +5322,22 @@ function $registeredScrapersMessage(availableScrapers) {
5224
5322
  * TODO: [®] DRY Register logic
5225
5323
  */
5226
5324
 
5325
+ /**
5326
+ * Removes emojis from a string and fix whitespaces
5327
+ *
5328
+ * @param text with emojis
5329
+ * @returns text without emojis
5330
+ * @public exported from `@promptbook/utils`
5331
+ */
5332
+ function removeEmojis(text) {
5333
+ // Replace emojis (and also ZWJ sequence) with hyphens
5334
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
5335
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
5336
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
5337
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
5338
+ return text;
5339
+ }
5340
+
5227
5341
  /**
5228
5342
  * @@@
5229
5343
  *
@@ -5286,6 +5400,30 @@ function normalizeToKebabCase(text) {
5286
5400
  * Note: [💞] Ignore a discrepancy between file name and entity name
5287
5401
  */
5288
5402
 
5403
+ /**
5404
+ * @@@
5405
+ *
5406
+ * @param value @@@
5407
+ * @returns @@@
5408
+ * @example @@@
5409
+ * @public exported from `@promptbook/utils`
5410
+ */
5411
+ function titleToName(value) {
5412
+ if (isValidUrl(value)) {
5413
+ value = value.replace(/^https?:\/\//, '');
5414
+ value = value.replace(/\.html$/, '');
5415
+ }
5416
+ else if (isValidFilePath(value)) {
5417
+ value = basename(value);
5418
+ // Note: Keeping extension in the name
5419
+ }
5420
+ value = value.split('/').join('-');
5421
+ value = removeEmojis(value);
5422
+ value = normalizeToKebabCase(value);
5423
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
5424
+ return value;
5425
+ }
5426
+
5289
5427
  /**
5290
5428
  * Creates unique name for the source
5291
5429
  *
@@ -5307,6 +5445,15 @@ function knowledgeSourceContentToName(knowledgeSourceContent) {
5307
5445
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
5308
5446
  */
5309
5447
 
5448
+ /**
5449
+ * @@@
5450
+ *
5451
+ * @private for `FileCacheStorage`
5452
+ */
5453
+ function nameToSubfolderPath(name) {
5454
+ return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
5455
+ }
5456
+
5310
5457
  /**
5311
5458
  * Convert file extension to mime type
5312
5459
  *
@@ -5362,55 +5509,6 @@ function isFileExisting(filename, fs) {
5362
5509
  * TODO: [🖇] What about symlinks?
5363
5510
  */
5364
5511
 
5365
- /**
5366
- * Tests if given string is valid URL.
5367
- *
5368
- * Note: This does not check if the file exists only if the path is valid
5369
- * @public exported from `@promptbook/utils`
5370
- */
5371
- function isValidFilePath(filename) {
5372
- if (typeof filename !== 'string') {
5373
- return false;
5374
- }
5375
- if (filename.split('\n').length > 1) {
5376
- return false;
5377
- }
5378
- if (filename.split(' ').length >
5379
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
5380
- return false;
5381
- }
5382
- var filenameSlashes = filename.split('\\').join('/');
5383
- // Absolute Unix path: /hello.txt
5384
- if (/^(\/)/i.test(filenameSlashes)) {
5385
- // console.log(filename, 'Absolute Unix path: /hello.txt');
5386
- return true;
5387
- }
5388
- // Absolute Windows path: /hello.txt
5389
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
5390
- // console.log(filename, 'Absolute Windows path: /hello.txt');
5391
- return true;
5392
- }
5393
- // Relative path: ./hello.txt
5394
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
5395
- // console.log(filename, 'Relative path: ./hello.txt');
5396
- return true;
5397
- }
5398
- // Allow paths like foo/hello
5399
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
5400
- // console.log(filename, 'Allow paths like foo/hello');
5401
- return true;
5402
- }
5403
- // Allow paths like hello.book
5404
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
5405
- // console.log(filename, 'Allow paths like hello.book');
5406
- return true;
5407
- }
5408
- return false;
5409
- }
5410
- /**
5411
- * TODO: [🍏] Implement for MacOs
5412
- */
5413
-
5414
5512
  /**
5415
5513
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
5416
5514
  *
@@ -5446,10 +5544,11 @@ var scraperFetch = function (url, init) { return __awaiter(void 0, void 0, void
5446
5544
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5447
5545
  var _a;
5448
5546
  return __awaiter(this, void 0, void 0, function () {
5449
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
5450
- return __generator(this, function (_f) {
5451
- switch (_f.label) {
5547
+ 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;
5548
+ return __generator(this, function (_l) {
5549
+ switch (_l.label) {
5452
5550
  case 0:
5551
+ console.log('!!! makeKnowledgeSourceHandler', knowledgeSource);
5453
5552
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
5454
5553
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
5455
5554
  name = knowledgeSource.name;
@@ -5457,54 +5556,32 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5457
5556
  if (!name) {
5458
5557
  name = knowledgeSourceContentToName(knowledgeSourceContent);
5459
5558
  }
5460
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
5559
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
5461
5560
  url = knowledgeSourceContent;
5462
5561
  return [4 /*yield*/, fetch(url)];
5463
5562
  case 1:
5464
- response_1 = _f.sent();
5465
- mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5466
- return [2 /*return*/, {
5467
- source: name,
5468
- filename: null,
5469
- url: url,
5470
- mimeType: mimeType,
5471
- /*
5472
- TODO: [🥽]
5473
- > async asBlob() {
5474
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5475
- > const content = await response.blob();
5476
- > return content;
5477
- > },
5478
- */
5479
- asJson: function () {
5480
- return __awaiter(this, void 0, void 0, function () {
5481
- var content;
5482
- return __generator(this, function (_a) {
5483
- switch (_a.label) {
5484
- case 0: return [4 /*yield*/, response_1.json()];
5485
- case 1:
5486
- content = _a.sent();
5487
- return [2 /*return*/, content];
5488
- }
5489
- });
5490
- });
5491
- },
5492
- asText: function () {
5493
- return __awaiter(this, void 0, void 0, function () {
5494
- var content;
5495
- return __generator(this, function (_a) {
5496
- switch (_a.label) {
5497
- case 0: return [4 /*yield*/, response_1.text()];
5498
- case 1:
5499
- content = _a.sent();
5500
- return [2 /*return*/, content];
5501
- }
5502
- });
5503
- });
5504
- },
5505
- }];
5563
+ response = _l.sent();
5564
+ mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5565
+ filename = url.split('/').pop() || titleToName(url);
5566
+ hash = sha256(hexEncoder.parse(url)).toString( /* hex */);
5567
+ rootDirname_1 = join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
5568
+ 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));
5569
+ return [4 /*yield*/, tools.fs.mkdir(dirname(join(rootDirname_1, filepath)), { recursive: true })];
5506
5570
  case 2:
5507
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
5571
+ _l.sent();
5572
+ _g = (_f = tools.fs).writeFile;
5573
+ _h = [join(rootDirname_1, filepath)];
5574
+ _k = (_j = Buffer).from;
5575
+ return [4 /*yield*/, response.arrayBuffer()];
5576
+ case 3: return [4 /*yield*/, _g.apply(_f, _h.concat([_k.apply(_j, [_l.sent()])]))];
5577
+ case 4:
5578
+ _l.sent();
5579
+ // TODO: !!!!!!!! Check the file security
5580
+ // TODO: !!!!!!!! Check the file size (if it is not too big)
5581
+ // TODO: !!!!!!!! Delete the file
5582
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
5583
+ case 5:
5584
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
5508
5585
  if (tools.fs === undefined) {
5509
5586
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
5510
5587
  // <- TODO: [🧠] What is the best error type here`
@@ -5517,8 +5594,8 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5517
5594
  fileExtension = getFileExtension(filename_1);
5518
5595
  mimeType = extensionToMimeType(fileExtension || '');
5519
5596
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
5520
- case 3:
5521
- if (!(_f.sent())) {
5597
+ case 6:
5598
+ if (!(_l.sent())) {
5522
5599
  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 "); }));
5523
5600
  }
5524
5601
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -5564,7 +5641,7 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5564
5641
  });
5565
5642
  },
5566
5643
  }];
5567
- case 4: return [2 /*return*/, {
5644
+ case 7: return [2 /*return*/, {
5568
5645
  source: name,
5569
5646
  filename: null,
5570
5647
  url: null,
@@ -6675,22 +6752,6 @@ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
6675
6752
  * TODO: [🌺] Use some intermediate util splitWords
6676
6753
  */
6677
6754
 
6678
- /**
6679
- * Removes emojis from a string and fix whitespaces
6680
- *
6681
- * @param text with emojis
6682
- * @returns text without emojis
6683
- * @public exported from `@promptbook/utils`
6684
- */
6685
- function removeEmojis(text) {
6686
- // Replace emojis (and also ZWJ sequence) with hyphens
6687
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
6688
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
6689
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
6690
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
6691
- return text;
6692
- }
6693
-
6694
6755
  /**
6695
6756
  * Removes quotes from a string
6696
6757
  *
@@ -8882,30 +8943,6 @@ function flattenMarkdown(markdown) {
8882
8943
  * NOW we are working just with markdown string and its good enough
8883
8944
  */
8884
8945
 
8885
- /**
8886
- * @@@
8887
- *
8888
- * @param value @@@
8889
- * @returns @@@
8890
- * @example @@@
8891
- * @public exported from `@promptbook/utils`
8892
- */
8893
- function titleToName(value) {
8894
- if (isValidUrl(value)) {
8895
- value = value.replace(/^https?:\/\//, '');
8896
- value = value.replace(/\.html$/, '');
8897
- }
8898
- else if (isValidFilePath(value)) {
8899
- value = basename(value);
8900
- // Note: Keeping extension in the name
8901
- }
8902
- value = value.split('/').join('-');
8903
- value = removeEmojis(value);
8904
- value = normalizeToKebabCase(value);
8905
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
8906
- return value;
8907
- }
8908
-
8909
8946
  /**
8910
8947
  * Compile pipeline from string (markdown) format to JSON format synchronously
8911
8948
  *
@@ -9638,6 +9675,7 @@ function $provideFilesystemForNode(options) {
9638
9675
  readFile: readFile,
9639
9676
  writeFile: writeFile,
9640
9677
  readdir: readdir,
9678
+ mkdir: mkdir,
9641
9679
  };
9642
9680
  }
9643
9681
  /**
@@ -11256,15 +11294,6 @@ function stringifyPipelineJson(pipeline) {
11256
11294
  * TODO: [🍙] Make some standard order of json properties
11257
11295
  */
11258
11296
 
11259
- /**
11260
- * @@@
11261
- *
11262
- * @private for `FileCacheStorage`
11263
- */
11264
- function nameToSubfolderPath(name) {
11265
- return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
11266
- }
11267
-
11268
11297
  /**
11269
11298
  * @@@
11270
11299
  *