@promptbook/documents 0.89.0-1 → 0.89.0-11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +3 -1
  2. package/esm/index.es.js +154 -85
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/core.index.d.ts +16 -4
  5. package/esm/typings/src/_packages/remote-client.index.d.ts +6 -8
  6. package/esm/typings/src/_packages/remote-server.index.d.ts +6 -6
  7. package/esm/typings/src/_packages/types.index.d.ts +18 -20
  8. package/esm/typings/src/cli/cli-commands/login.d.ts +15 -0
  9. package/esm/typings/src/cli/common/$addGlobalOptionsToCommand.d.ts +7 -0
  10. package/esm/typings/src/cli/common/$provideLlmToolsForCli.d.ts +15 -0
  11. package/esm/typings/src/config.d.ts +15 -8
  12. package/esm/typings/src/errors/0-index.d.ts +6 -0
  13. package/esm/typings/src/errors/AuthenticationError.d.ts +9 -0
  14. package/esm/typings/src/errors/PromptbookFetchError.d.ts +9 -0
  15. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +2 -2
  16. package/esm/typings/src/execution/PromptResult.d.ts +2 -2
  17. package/esm/typings/src/execution/{PromptResultUsage.d.ts → Usage.d.ts} +5 -5
  18. package/esm/typings/src/execution/utils/addUsage.d.ts +2 -2
  19. package/esm/typings/src/execution/utils/computeUsageCounts.d.ts +3 -3
  20. package/esm/typings/src/execution/utils/usage-constants.d.ts +77 -60
  21. package/esm/typings/src/execution/utils/usageToHuman.d.ts +5 -5
  22. package/esm/typings/src/execution/utils/usageToWorktime.d.ts +5 -5
  23. package/esm/typings/src/llm-providers/_common/register/$provideEnvFilename.d.ts +12 -0
  24. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsConfigurationFromEnv.d.ts +2 -8
  25. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForTestingAndScriptsAndPlayground.d.ts +2 -0
  26. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForWizzardOrCli.d.ts +36 -1
  27. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsFromEnv.d.ts +1 -0
  28. package/esm/typings/src/llm-providers/_common/utils/count-total-usage/LlmExecutionToolsWithTotalUsage.d.ts +3 -3
  29. package/esm/typings/src/llm-providers/_common/utils/count-total-usage/limitTotalUsage.d.ts +2 -2
  30. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
  31. package/esm/typings/src/llm-providers/anthropic-claude/computeAnthropicClaudeUsage.d.ts +2 -2
  32. package/esm/typings/src/llm-providers/anthropic-claude/register-configuration.d.ts +1 -1
  33. package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +0 -9
  34. package/esm/typings/src/llm-providers/openai/computeOpenAiUsage.d.ts +2 -2
  35. package/esm/typings/src/pipeline/PipelineJson/PreparationJson.d.ts +2 -2
  36. package/esm/typings/src/remote-server/RemoteServer.d.ts +23 -0
  37. package/esm/typings/src/remote-server/socket-types/_subtypes/{PromptbookServer_Identification.d.ts → Identification.d.ts} +3 -3
  38. package/esm/typings/src/remote-server/socket-types/listModels/PromptbookServer_ListModels_Request.d.ts +2 -2
  39. package/esm/typings/src/remote-server/socket-types/prepare/PromptbookServer_PreparePipeline_Request.d.ts +2 -2
  40. package/esm/typings/src/remote-server/socket-types/prompt/PromptbookServer_Prompt_Request.d.ts +2 -2
  41. package/esm/typings/src/remote-server/startRemoteServer.d.ts +2 -2
  42. package/esm/typings/src/remote-server/types/RemoteClientOptions.d.ts +4 -12
  43. package/esm/typings/src/remote-server/types/RemoteServerOptions.d.ts +73 -3
  44. package/esm/typings/src/scrapers/_common/utils/{scraperFetch.d.ts → promptbookFetch.d.ts} +2 -2
  45. package/esm/typings/src/storage/env-storage/$EnvStorage.d.ts +37 -0
  46. package/esm/typings/src/types/typeAliases.d.ts +6 -0
  47. package/esm/typings/src/utils/organization/TODO_narrow.d.ts +6 -0
  48. package/package.json +2 -2
  49. package/umd/index.umd.js +154 -85
  50. package/umd/index.umd.js.map +1 -1
  51. package/esm/typings/src/playground/BrjappConnector.d.ts +0 -64
  52. package/esm/typings/src/playground/brjapp-api-schema.d.ts +0 -12879
@@ -1,10 +1,15 @@
1
+ import type { Request, Response } from 'express';
1
2
  import type { Promisable } from 'type-fest';
2
3
  import type { PipelineCollection } from '../../collection/PipelineCollection';
4
+ import { AuthenticationError } from '../../errors/AuthenticationError';
3
5
  import type { CommonToolsOptions } from '../../execution/CommonToolsOptions';
4
6
  import type { LlmExecutionTools } from '../../execution/LlmExecutionTools';
5
7
  import type { string_app_id } from '../../types/typeAliases';
8
+ import type { string_email } from '../../types/typeAliases';
9
+ import type { string_password } from '../../types/typeAliases';
6
10
  import type { string_uri } from '../../types/typeAliases';
7
11
  import type { string_user_id } from '../../types/typeAliases';
12
+ import type { Identification } from '../socket-types/_subtypes/Identification';
8
13
  /**
9
14
  * @@@
10
15
  *
@@ -16,7 +21,6 @@ import type { string_user_id } from '../../types/typeAliases';
16
21
  *
17
22
  * You can enable both modes at the same time.
18
23
  *
19
- * @public exported from `@promptbook/remote-client`
20
24
  * @public exported from `@promptbook/remote-server`
21
25
  */
22
26
  export type RemoteServerOptions<TCustomOptions> = CommonToolsOptions & {
@@ -32,8 +36,12 @@ export type RemoteServerOptions<TCustomOptions> = CommonToolsOptions & {
32
36
  * @default '/'
33
37
  * @example '/api/promptbook/'
34
38
  */
35
- readonly rootPath: string_uri;
36
- } & (AnonymousRemoteServerOptions | ApplicationRemoteServerOptions<TCustomOptions> | (AnonymousRemoteServerOptions & ApplicationRemoteServerOptions<TCustomOptions>));
39
+ readonly rootPath?: string_uri;
40
+ } & ((AnonymousRemoteServerOptions & {
41
+ readonly isApplicationModeAllowed?: false;
42
+ }) | ({
43
+ readonly isAnonymousModeAllowed?: false;
44
+ } & ApplicationRemoteServerOptions<TCustomOptions>) | (AnonymousRemoteServerOptions & ApplicationRemoteServerOptions<TCustomOptions>));
37
45
  export type AnonymousRemoteServerOptions = {
38
46
  /**
39
47
  * Enable anonymous mode
@@ -51,6 +59,18 @@ export type ApplicationRemoteServerOptions<TCustomOptions> = {
51
59
  * This is used to check validity of the prompt to prevent misuse
52
60
  */
53
61
  readonly collection: PipelineCollection;
62
+ /**
63
+ * User tries to login to the server, this function will be called verify the user and return the identification or throw an error
64
+ * This can be also doubled as a function to register the user
65
+ *
66
+ * Note: In most cases, you will return `PromptbookServer_ApplicationIdentification`
67
+ * `PromptbookServer_AnonymousIdentification` is useful only in scenarios when user stores its own api keys on the application server and
68
+ * server acts only as a api key provider
69
+ *
70
+ * Note: In most cases DO NOT THROW `AuthenticationError` but return `isSuccess: false` with message
71
+ * @throws `AuthenticationError` if the user is not allowed to login for example because of invalid credentials
72
+ */
73
+ login(loginRequest: LoginRequest): Promise<LoginResponse<TCustomOptions>>;
54
74
  /**
55
75
  * Creates llm execution tools for each client
56
76
  */
@@ -82,6 +102,56 @@ export type ApplicationRemoteServerClientOptions<TCustomOptions> = {
82
102
  */
83
103
  readonly customOptions?: TCustomOptions;
84
104
  };
105
+ /**
106
+ * Login request for the application mode
107
+ */
108
+ export type LoginRequest = {
109
+ /**
110
+ * Identifier of the application you are using
111
+ *
112
+ * Note: This is usefull when you use Promptbook remote server for multiple apps/frontends, if its used just for single app, use here just "app" or "your-app-name"
113
+ */
114
+ readonly appId: string_app_id | null;
115
+ /**
116
+ * Username (for example email) of the user
117
+ */
118
+ readonly username: string_email | string;
119
+ /**
120
+ * Password of the user
121
+ */
122
+ readonly password: string_password;
123
+ /**
124
+ * Request object from express if you want to access some request data for example headers, IP address, etc.
125
+ */
126
+ readonly rawRequest: Request;
127
+ /**
128
+ * Response object from express if you want to add some custom headers.
129
+ *
130
+ * Note: It is not recommended to use this object to send body of the response because it can confuse the client
131
+ */
132
+ readonly rawResponse: Response;
133
+ };
134
+ /**
135
+ * Login response for the application mode
136
+ */
137
+ export type LoginResponse<TCustomOptions> = {
138
+ /**
139
+ * Was the login successful
140
+ */
141
+ readonly isSuccess: boolean;
142
+ /**
143
+ * Message to display to the user, this message is always displayed
144
+ */
145
+ readonly message?: string;
146
+ /**
147
+ * Optional error if the login was not successful
148
+ */
149
+ readonly error?: AuthenticationError;
150
+ /**
151
+ * Identification of the user to be used in the future requests
152
+ */
153
+ readonly identification?: Identification<TCustomOptions>;
154
+ };
85
155
  /**
86
156
  * TODO: Constrain anonymous mode for specific models / providers
87
157
  */
@@ -2,9 +2,9 @@ import type { PromptbookFetch } from '../../../execution/PromptbookFetch';
2
2
  /**
3
3
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
4
4
  *
5
- * @private as default `fetch` function used in Promptbook scrapers
5
+ * @public exported from `@promptbook/core`
6
6
  */
7
- export declare const scraperFetch: PromptbookFetch;
7
+ export declare const promptbookFetch: PromptbookFetch;
8
8
  /**
9
9
  * TODO: [🧠] Maybe rename because it is not used only for scrapers but also in `$getCompiledBook`
10
10
  */
@@ -0,0 +1,37 @@
1
+ import type { PromptbookStorage } from '../_common/PromptbookStorage';
2
+ /**
3
+ * Stores data in .env variables (Remove !!! nonce 1)
4
+ *
5
+ * Note: `$` is used to indicate that this function is not a pure function - it uses filesystem to access `.env` file and also writes to `process.env`
6
+ *
7
+ * @private within the repository - for CLI utils
8
+ */
9
+ export declare class $EnvStorage<TItem> implements PromptbookStorage<TItem> {
10
+ private envFilename;
11
+ private $provideOrCreateEnvFile;
12
+ private transformKey;
13
+ /**
14
+ * Returns the number of key/value pairs currently present in the list associated with the object.
15
+ */
16
+ get length(): number;
17
+ /**
18
+ * Empties the list associated with the object of all key/value pairs, if there are any.
19
+ */
20
+ clear(): void;
21
+ /**
22
+ * Returns the current value associated with the given key, or null if the given key does not exist in the list associated with the object.
23
+ */
24
+ getItem(key: string): Promise<TItem | null>;
25
+ /**
26
+ * Returns the name of the nth key in the list, or null if n is greater than or equal to the number of key/value pairs in the object.
27
+ */
28
+ key(index: number): string | null;
29
+ /**
30
+ * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
31
+ */
32
+ setItem(key: string, value: TItem): Promise<void>;
33
+ /**
34
+ * Removes the key/value pair with the given key from the list associated with the object, if a key/value pair with the given key exists.
35
+ */
36
+ removeItem(key: string): void;
37
+ }
@@ -242,6 +242,12 @@ export type string_promptbook_documentation_url = `https://github.com/webgptorg/
242
242
  * For example `"towns.cz"`
243
243
  */
244
244
  export type string_domain = string;
245
+ /**
246
+ * Semantic helper
247
+ *
248
+ * For example `"https://*.pavolhejny.com/*"`
249
+ */
250
+ export type string_origin = string;
245
251
  /**
246
252
  * Semantic helper
247
253
  *
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Organizational helper to better mark the place where the more specific type is missing
3
+ *
4
+ * @private within the repository
5
+ */
6
+ export type TODO_narrow<T> = T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptbook/documents",
3
- "version": "0.89.0-1",
3
+ "version": "0.89.0-11",
4
4
  "description": "It's time for a paradigm shift. The future of software in plain English, French or Latin",
5
5
  "private": false,
6
6
  "sideEffects": false,
@@ -47,7 +47,7 @@
47
47
  "module": "./esm/index.es.js",
48
48
  "typings": "./esm/typings/src/_packages/documents.index.d.ts",
49
49
  "peerDependencies": {
50
- "@promptbook/core": "0.89.0-1"
50
+ "@promptbook/core": "0.89.0-11"
51
51
  },
52
52
  "dependencies": {
53
53
  "colors": "1.4.0",
package/umd/index.umd.js CHANGED
@@ -26,7 +26,7 @@
26
26
  * @generated
27
27
  * @see https://github.com/webgptorg/promptbook
28
28
  */
29
- const PROMPTBOOK_ENGINE_VERSION = '0.89.0-1';
29
+ const PROMPTBOOK_ENGINE_VERSION = '0.89.0-11';
30
30
  /**
31
31
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
32
32
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -160,6 +160,7 @@
160
160
  */
161
161
  const DEFAULT_MAX_EXECUTION_ATTEMPTS = 10; // <- TODO: [🤹‍♂️]
162
162
  // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
163
+ // TODO: !!!!!! Just .promptbook dir, hardocode others
163
164
  /**
164
165
  * Where to store the temporary downloads
165
166
  *
@@ -211,7 +212,7 @@
211
212
  true);
212
213
  /**
213
214
  * Note: [💞] Ignore a discrepancy between file name and entity name
214
- * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
215
+ * TODO: [🧠][🧜‍♂️] Maybe join remoteServerUrl and path into single value
215
216
  */
216
217
 
217
218
  /**
@@ -430,6 +431,7 @@
430
431
  }
431
432
  else {
432
433
  console.warn(`Command "${humanReadableCommand}" exceeded time limit of ${timeout}ms but continues running`);
434
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
433
435
  resolve('Command exceeded time limit');
434
436
  }
435
437
  });
@@ -455,6 +457,7 @@
455
457
  output.push(stderr.toString());
456
458
  if (isVerbose && stderr.toString().trim()) {
457
459
  console.warn(stderr.toString());
460
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
458
461
  }
459
462
  });
460
463
  const finishWithCode = (code) => {
@@ -466,6 +469,7 @@
466
469
  else {
467
470
  if (isVerbose) {
468
471
  console.warn(`Command "${humanReadableCommand}" exited with code ${code}`);
472
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
469
473
  }
470
474
  resolve(spaceTrim.spaceTrim(output.join('\n')));
471
475
  }
@@ -487,6 +491,7 @@
487
491
  else {
488
492
  if (isVerbose) {
489
493
  console.warn(error);
494
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
490
495
  }
491
496
  resolve(spaceTrim.spaceTrim(output.join('\n')));
492
497
  }
@@ -2302,6 +2307,19 @@
2302
2307
  }
2303
2308
  }
2304
2309
 
2310
+ /**
2311
+ * AuthenticationError is thrown from login function which is dependency of remote server
2312
+ *
2313
+ * @public exported from `@promptbook/core`
2314
+ */
2315
+ class AuthenticationError extends Error {
2316
+ constructor(message) {
2317
+ super(message);
2318
+ this.name = 'AuthenticationError';
2319
+ Object.setPrototypeOf(this, AuthenticationError.prototype);
2320
+ }
2321
+ }
2322
+
2305
2323
  /**
2306
2324
  * This error indicates that the pipeline collection cannot be propperly loaded
2307
2325
  *
@@ -2367,6 +2385,19 @@
2367
2385
  }
2368
2386
  }
2369
2387
 
2388
+ /**
2389
+ * Error thrown when a fetch request fails
2390
+ *
2391
+ * @public exported from `@promptbook/core`
2392
+ */
2393
+ class PromptbookFetchError extends Error {
2394
+ constructor(message) {
2395
+ super(message);
2396
+ this.name = 'PromptbookFetchError';
2397
+ Object.setPrototypeOf(this, PromptbookFetchError.prototype);
2398
+ }
2399
+ }
2400
+
2370
2401
  /**
2371
2402
  * Index of all custom errors
2372
2403
  *
@@ -2404,6 +2435,8 @@
2404
2435
  TypeError,
2405
2436
  URIError,
2406
2437
  AggregateError,
2438
+ AuthenticationError,
2439
+ PromptbookFetchError,
2407
2440
  /*
2408
2441
  Note: Not widely supported
2409
2442
  > InternalError,
@@ -2465,6 +2498,7 @@
2465
2498
  const { isSuccessful, errors, warnings } = executionResult;
2466
2499
  for (const warning of warnings) {
2467
2500
  console.warn(warning.message);
2501
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
2468
2502
  }
2469
2503
  if (isSuccessful === true) {
2470
2504
  return;
@@ -2602,6 +2636,10 @@
2602
2636
 
2603
2637
  Cannot serialize error with name "${name}"
2604
2638
 
2639
+ Authors of Promptbook probably forgot to add this error into the list of errors:
2640
+ https://github.com/webgptorg/promptbook/blob/main/src/errors/0-index.ts
2641
+
2642
+
2605
2643
  ${block(stack || message)}
2606
2644
 
2607
2645
  `));
@@ -2643,30 +2681,42 @@
2643
2681
  await Promise.all(tasks);
2644
2682
  }
2645
2683
 
2684
+ /**
2685
+ * Represents the uncertain value
2686
+ *
2687
+ * @public exported from `@promptbook/core`
2688
+ */
2689
+ const ZERO_VALUE = $deepFreeze({ value: 0 });
2690
+ /**
2691
+ * Represents the uncertain value
2692
+ *
2693
+ * @public exported from `@promptbook/core`
2694
+ */
2695
+ const UNCERTAIN_ZERO_VALUE = $deepFreeze({ value: 0, isUncertain: true });
2646
2696
  /**
2647
2697
  * Represents the usage with no resources consumed
2648
2698
  *
2649
2699
  * @public exported from `@promptbook/core`
2650
2700
  */
2651
2701
  const ZERO_USAGE = $deepFreeze({
2652
- price: { value: 0 },
2702
+ price: ZERO_VALUE,
2653
2703
  input: {
2654
- tokensCount: { value: 0 },
2655
- charactersCount: { value: 0 },
2656
- wordsCount: { value: 0 },
2657
- sentencesCount: { value: 0 },
2658
- linesCount: { value: 0 },
2659
- paragraphsCount: { value: 0 },
2660
- pagesCount: { value: 0 },
2704
+ tokensCount: ZERO_VALUE,
2705
+ charactersCount: ZERO_VALUE,
2706
+ wordsCount: ZERO_VALUE,
2707
+ sentencesCount: ZERO_VALUE,
2708
+ linesCount: ZERO_VALUE,
2709
+ paragraphsCount: ZERO_VALUE,
2710
+ pagesCount: ZERO_VALUE,
2661
2711
  },
2662
2712
  output: {
2663
- tokensCount: { value: 0 },
2664
- charactersCount: { value: 0 },
2665
- wordsCount: { value: 0 },
2666
- sentencesCount: { value: 0 },
2667
- linesCount: { value: 0 },
2668
- paragraphsCount: { value: 0 },
2669
- pagesCount: { value: 0 },
2713
+ tokensCount: ZERO_VALUE,
2714
+ charactersCount: ZERO_VALUE,
2715
+ wordsCount: ZERO_VALUE,
2716
+ sentencesCount: ZERO_VALUE,
2717
+ linesCount: ZERO_VALUE,
2718
+ paragraphsCount: ZERO_VALUE,
2719
+ pagesCount: ZERO_VALUE,
2670
2720
  },
2671
2721
  });
2672
2722
  /**
@@ -2675,24 +2725,24 @@
2675
2725
  * @public exported from `@promptbook/core`
2676
2726
  */
2677
2727
  $deepFreeze({
2678
- price: { value: 0, isUncertain: true },
2728
+ price: UNCERTAIN_ZERO_VALUE,
2679
2729
  input: {
2680
- tokensCount: { value: 0, isUncertain: true },
2681
- charactersCount: { value: 0, isUncertain: true },
2682
- wordsCount: { value: 0, isUncertain: true },
2683
- sentencesCount: { value: 0, isUncertain: true },
2684
- linesCount: { value: 0, isUncertain: true },
2685
- paragraphsCount: { value: 0, isUncertain: true },
2686
- pagesCount: { value: 0, isUncertain: true },
2730
+ tokensCount: UNCERTAIN_ZERO_VALUE,
2731
+ charactersCount: UNCERTAIN_ZERO_VALUE,
2732
+ wordsCount: UNCERTAIN_ZERO_VALUE,
2733
+ sentencesCount: UNCERTAIN_ZERO_VALUE,
2734
+ linesCount: UNCERTAIN_ZERO_VALUE,
2735
+ paragraphsCount: UNCERTAIN_ZERO_VALUE,
2736
+ pagesCount: UNCERTAIN_ZERO_VALUE,
2687
2737
  },
2688
2738
  output: {
2689
- tokensCount: { value: 0, isUncertain: true },
2690
- charactersCount: { value: 0, isUncertain: true },
2691
- wordsCount: { value: 0, isUncertain: true },
2692
- sentencesCount: { value: 0, isUncertain: true },
2693
- linesCount: { value: 0, isUncertain: true },
2694
- paragraphsCount: { value: 0, isUncertain: true },
2695
- pagesCount: { value: 0, isUncertain: true },
2739
+ tokensCount: UNCERTAIN_ZERO_VALUE,
2740
+ charactersCount: UNCERTAIN_ZERO_VALUE,
2741
+ wordsCount: UNCERTAIN_ZERO_VALUE,
2742
+ sentencesCount: UNCERTAIN_ZERO_VALUE,
2743
+ linesCount: UNCERTAIN_ZERO_VALUE,
2744
+ paragraphsCount: UNCERTAIN_ZERO_VALUE,
2745
+ pagesCount: UNCERTAIN_ZERO_VALUE,
2696
2746
  },
2697
2747
  });
2698
2748
  /**
@@ -2980,6 +3030,7 @@
2980
3030
  `);
2981
3031
  // TODO: [🟥] Detect browser / node and make it colorfull
2982
3032
  console.warn(warningMessage);
3033
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
2983
3034
  /*
2984
3035
  return {
2985
3036
  async listModels() {
@@ -3355,17 +3406,24 @@
3355
3406
  /**
3356
3407
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
3357
3408
  *
3358
- * @private as default `fetch` function used in Promptbook scrapers
3409
+ * @public exported from `@promptbook/core`
3359
3410
  */
3360
- const scraperFetch = async (url, init) => {
3411
+ const promptbookFetch = async (urlOrRequest, init) => {
3361
3412
  try {
3362
- return await fetch(url, init);
3413
+ return await fetch(urlOrRequest, init);
3363
3414
  }
3364
3415
  catch (error) {
3365
3416
  if (!(error instanceof Error)) {
3366
3417
  throw error;
3367
3418
  }
3368
- throw new KnowledgeScrapeError(spaceTrim__default["default"]((block) => `
3419
+ let url;
3420
+ if (typeof urlOrRequest === 'string') {
3421
+ url = urlOrRequest;
3422
+ }
3423
+ else if (urlOrRequest instanceof Request) {
3424
+ url = urlOrRequest.url;
3425
+ }
3426
+ throw new PromptbookFetchError(spaceTrim__default["default"]((block) => `
3369
3427
  Can not fetch "${url}"
3370
3428
 
3371
3429
  Fetch error:
@@ -3386,7 +3444,7 @@
3386
3444
  async function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3387
3445
  // console.log('!! makeKnowledgeSourceHandler', knowledgeSource);
3388
3446
  var _a;
3389
- const { fetch = scraperFetch } = tools;
3447
+ const { fetch = promptbookFetch } = tools;
3390
3448
  const { knowledgeSourceContent } = knowledgeSource;
3391
3449
  let { name } = knowledgeSource;
3392
3450
  const { rootDirname = null,
@@ -3527,63 +3585,73 @@
3527
3585
  const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT, rootDirname, isVerbose = DEFAULT_IS_VERBOSE } = options;
3528
3586
  const knowledgePreparedUnflatten = new Array(knowledgeSources.length);
3529
3587
  await forEachAsync(knowledgeSources, { maxParallelCount }, async (knowledgeSource, index) => {
3530
- let partialPieces = null;
3531
- const sourceHandler = await makeKnowledgeSourceHandler(knowledgeSource, tools, { rootDirname, isVerbose });
3532
- const scrapers = arrayableToArray(tools.scrapers);
3533
- for (const scraper of scrapers) {
3534
- if (!scraper.metadata.mimeTypes.includes(sourceHandler.mimeType)
3535
- // <- TODO: [🦔] Implement mime-type wildcards
3536
- ) {
3537
- continue;
3538
- }
3539
- const partialPiecesUnchecked = await scraper.scrape(sourceHandler);
3540
- if (partialPiecesUnchecked !== null) {
3541
- partialPieces = [...partialPiecesUnchecked];
3542
- // <- TODO: [🪓] Here should be no need for spreading new array, just `partialPieces = partialPiecesUnchecked`
3543
- break;
3544
- }
3545
- console.warn(spaceTrim__default["default"]((block) => `
3546
- Cannot scrape knowledge from source despite the scraper \`${scraper.metadata.className}\` supports the mime type "${sourceHandler.mimeType}".
3588
+ try {
3589
+ let partialPieces = null;
3590
+ const sourceHandler = await makeKnowledgeSourceHandler(knowledgeSource, tools, { rootDirname, isVerbose });
3591
+ const scrapers = arrayableToArray(tools.scrapers);
3592
+ for (const scraper of scrapers) {
3593
+ if (!scraper.metadata.mimeTypes.includes(sourceHandler.mimeType)
3594
+ // <- TODO: [🦔] Implement mime-type wildcards
3595
+ ) {
3596
+ continue;
3597
+ }
3598
+ const partialPiecesUnchecked = await scraper.scrape(sourceHandler);
3599
+ if (partialPiecesUnchecked !== null) {
3600
+ partialPieces = [...partialPiecesUnchecked];
3601
+ // <- TODO: [🪓] Here should be no need for spreading new array, just `partialPieces = partialPiecesUnchecked`
3602
+ break;
3603
+ }
3604
+ console.warn(spaceTrim__default["default"]((block) => `
3605
+ Cannot scrape knowledge from source despite the scraper \`${scraper.metadata.className}\` supports the mime type "${sourceHandler.mimeType}".
3547
3606
 
3548
- The source:
3549
- ${block(knowledgeSource.knowledgeSourceContent
3550
- .split('\n')
3551
- .map((line) => `> ${line}`)
3552
- .join('\n'))}
3607
+ The source:
3608
+ ${block(knowledgeSource.knowledgeSourceContent
3609
+ .split('\n')
3610
+ .map((line) => `> ${line}`)
3611
+ .join('\n'))}
3553
3612
 
3554
- ${block($registeredScrapersMessage(scrapers))}
3613
+ ${block($registeredScrapersMessage(scrapers))}
3555
3614
 
3556
3615
 
3557
- `));
3558
- }
3559
- if (partialPieces === null) {
3560
- throw new KnowledgeScrapeError(spaceTrim__default["default"]((block) => `
3561
- Cannot scrape knowledge
3616
+ `));
3617
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
3618
+ }
3619
+ if (partialPieces === null) {
3620
+ throw new KnowledgeScrapeError(spaceTrim__default["default"]((block) => `
3621
+ Cannot scrape knowledge
3562
3622
 
3563
- The source:
3564
- > ${block(knowledgeSource.knowledgeSourceContent
3565
- .split('\n')
3566
- .map((line) => `> ${line}`)
3567
- .join('\n'))}
3623
+ The source:
3624
+ > ${block(knowledgeSource.knowledgeSourceContent
3625
+ .split('\n')
3626
+ .map((line) => `> ${line}`)
3627
+ .join('\n'))}
3568
3628
 
3569
- No scraper found for the mime type "${sourceHandler.mimeType}"
3629
+ No scraper found for the mime type "${sourceHandler.mimeType}"
3570
3630
 
3571
- ${block($registeredScrapersMessage(scrapers))}
3631
+ ${block($registeredScrapersMessage(scrapers))}
3572
3632
 
3573
3633
 
3574
- `));
3634
+ `));
3635
+ }
3636
+ const pieces = partialPieces.map((partialPiece) => ({
3637
+ ...partialPiece,
3638
+ sources: [
3639
+ {
3640
+ name: knowledgeSource.name,
3641
+ // line, column <- TODO: [☀]
3642
+ // <- TODO: [❎]
3643
+ },
3644
+ ],
3645
+ }));
3646
+ knowledgePreparedUnflatten[index] = pieces;
3647
+ }
3648
+ catch (error) {
3649
+ if (!(error instanceof Error)) {
3650
+ throw error;
3651
+ }
3652
+ console.warn(error);
3653
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
3575
3654
  }
3576
- const pieces = partialPieces.map((partialPiece) => ({
3577
- ...partialPiece,
3578
- sources: [
3579
- {
3580
- name: knowledgeSource.name,
3581
- // line, column <- TODO: [☀]
3582
- // <- TODO: [❎]
3583
- },
3584
- ],
3585
- }));
3586
- knowledgePreparedUnflatten[index] = pieces;
3587
3655
  });
3588
3656
  const knowledgePrepared = knowledgePreparedUnflatten.flat();
3589
3657
  return knowledgePrepared;
@@ -4001,7 +4069,7 @@
4001
4069
  if (parameterNames.has(subparameterName)) {
4002
4070
  parameterNames.delete(subparameterName);
4003
4071
  parameterNames.add(foreach.parameterName);
4004
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
4072
+ // <- TODO: [🏮] Warn/logic error when `subparameterName` not used
4005
4073
  }
4006
4074
  }
4007
4075
  }
@@ -5597,6 +5665,7 @@
5597
5665
 
5598
5666
  @see more at https://ptbk.io/prepare-pipeline
5599
5667
  `));
5668
+ // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
5600
5669
  }
5601
5670
  let runCount = 0;
5602
5671
  const pipelineExecutorWithCallback = async (inputParameters, onProgress) => {