@promptbook/remote-server 0.89.0-9 → 0.92.0-3

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 (41) hide show
  1. package/README.md +9 -7
  2. package/esm/index.es.js +555 -426
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/servers.d.ts +40 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +10 -4
  6. package/esm/typings/src/_packages/types.index.d.ts +18 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -0
  8. package/esm/typings/src/cli/cli-commands/login.d.ts +0 -1
  9. package/esm/typings/src/cli/common/$provideLlmToolsForCli.d.ts +16 -3
  10. package/esm/typings/src/cli/test/ptbk.d.ts +1 -1
  11. package/esm/typings/src/commands/EXPECT/expectCommandParser.d.ts +2 -0
  12. package/esm/typings/src/config.d.ts +10 -19
  13. package/esm/typings/src/errors/0-index.d.ts +7 -4
  14. package/esm/typings/src/errors/PipelineExecutionError.d.ts +1 -1
  15. package/esm/typings/src/errors/WrappedError.d.ts +10 -0
  16. package/esm/typings/src/errors/assertsError.d.ts +11 -0
  17. package/esm/typings/src/execution/PromptbookFetch.d.ts +1 -1
  18. package/esm/typings/src/formats/csv/utils/isValidCsvString.d.ts +9 -0
  19. package/esm/typings/src/formats/csv/utils/isValidCsvString.test.d.ts +1 -0
  20. package/esm/typings/src/formats/json/utils/isValidJsonString.d.ts +3 -0
  21. package/esm/typings/src/formats/xml/utils/isValidXmlString.d.ts +9 -0
  22. package/esm/typings/src/formats/xml/utils/isValidXmlString.test.d.ts +1 -0
  23. package/esm/typings/src/llm-providers/_common/filterModels.d.ts +15 -0
  24. package/esm/typings/src/llm-providers/_common/register/{$provideEnvFilepath.d.ts → $provideEnvFilename.d.ts} +2 -2
  25. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsConfigurationFromEnv.d.ts +1 -1
  26. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForTestingAndScriptsAndPlayground.d.ts +1 -1
  27. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForWizzardOrCli.d.ts +11 -2
  28. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsFromEnv.d.ts +1 -1
  29. package/esm/typings/src/remote-server/openapi-types.d.ts +284 -0
  30. package/esm/typings/src/remote-server/openapi.d.ts +187 -0
  31. package/esm/typings/src/remote-server/socket-types/_subtypes/Identification.d.ts +7 -1
  32. package/esm/typings/src/remote-server/socket-types/_subtypes/identificationToPromptbookToken.d.ts +11 -0
  33. package/esm/typings/src/remote-server/socket-types/_subtypes/promptbookTokenToIdentification.d.ts +10 -0
  34. package/esm/typings/src/remote-server/startRemoteServer.d.ts +1 -2
  35. package/esm/typings/src/remote-server/types/RemoteServerOptions.d.ts +15 -9
  36. package/esm/typings/src/storage/env-storage/$EnvStorage.d.ts +40 -0
  37. package/esm/typings/src/types/typeAliases.d.ts +26 -0
  38. package/package.json +11 -7
  39. package/umd/index.umd.js +476 -329
  40. package/umd/index.umd.js.map +1 -1
  41. package/esm/typings/src/cli/test/ptbk2.d.ts +0 -5
package/umd/index.umd.js CHANGED
@@ -1,16 +1,34 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('express'), require('http'), require('socket.io'), require('spacetrim'), require('swagger-jsdoc'), require('swagger-ui-express'), require('waitasecond'), require('crypto'), require('child_process'), require('fs/promises'), require('path'), require('rxjs'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('crypto-js'), require('mime-types'), require('papaparse')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'express', 'http', 'socket.io', 'spacetrim', 'swagger-jsdoc', 'swagger-ui-express', 'waitasecond', 'crypto', 'child_process', 'fs/promises', 'path', 'rxjs', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'crypto-js', 'mime-types', 'papaparse'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-remote-server"] = {}, global.colors, global.express, global.http, global.socket_io, global.spaceTrim, global.swaggerJsdoc, global.swaggerUi, global.waitasecond, global.crypto, global.child_process, global.promises, global.path, global.rxjs, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.cryptoJs, global.mimeTypes, global.papaparse));
5
- })(this, (function (exports, colors, express, http, socket_io, spaceTrim, swaggerJsdoc, swaggerUi, waitasecond, crypto, child_process, promises, path, rxjs, prettier, parserHtml, hexEncoder, sha256, cryptoJs, mimeTypes, papaparse) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('express'), require('http'), require('socket.io'), require('spacetrim'), require('express-openapi-validator'), require('swagger-ui-express'), require('waitasecond'), require('crypto'), require('child_process'), require('fs/promises'), require('path'), require('rxjs'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('crypto-js'), require('mime-types'), require('papaparse')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'express', 'http', 'socket.io', 'spacetrim', 'express-openapi-validator', 'swagger-ui-express', 'waitasecond', 'crypto', 'child_process', 'fs/promises', 'path', 'rxjs', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'crypto-js', 'mime-types', 'papaparse'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-remote-server"] = {}, global.colors, global.express, global.http, global.socket_io, global.spaceTrim, global.OpenApiValidator, global.swaggerUi, global.waitasecond, global.crypto, global.child_process, global.promises, global.path, global.rxjs, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.cryptoJs, global.mimeTypes, global.papaparse));
5
+ })(this, (function (exports, colors, express, http, socket_io, spaceTrim, OpenApiValidator, swaggerUi, waitasecond, crypto, child_process, promises, path, rxjs, prettier, parserHtml, hexEncoder, sha256, cryptoJs, mimeTypes, papaparse) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
+ function _interopNamespace(e) {
10
+ if (e && e.__esModule) return e;
11
+ var n = Object.create(null);
12
+ if (e) {
13
+ Object.keys(e).forEach(function (k) {
14
+ if (k !== 'default') {
15
+ var d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: function () { return e[k]; }
19
+ });
20
+ }
21
+ });
22
+ }
23
+ n["default"] = e;
24
+ return Object.freeze(n);
25
+ }
26
+
9
27
  var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
10
28
  var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
11
29
  var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
12
30
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
13
- var swaggerJsdoc__default = /*#__PURE__*/_interopDefaultLegacy(swaggerJsdoc);
31
+ var OpenApiValidator__namespace = /*#__PURE__*/_interopNamespace(OpenApiValidator);
14
32
  var swaggerUi__default = /*#__PURE__*/_interopDefaultLegacy(swaggerUi);
15
33
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
16
34
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
@@ -30,7 +48,7 @@
30
48
  * @generated
31
49
  * @see https://github.com/webgptorg/promptbook
32
50
  */
33
- const PROMPTBOOK_ENGINE_VERSION = '0.89.0-9';
51
+ const PROMPTBOOK_ENGINE_VERSION = '0.92.0-3';
34
52
  /**
35
53
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
36
54
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -84,6 +102,7 @@
84
102
  * @public exported from `@promptbook/core`
85
103
  */
86
104
  const CLAIM = `It's time for a paradigm shift. The future of software in plain English, French or Latin`;
105
+ // <- TODO: [🐊] Pick the best claim
87
106
  /**
88
107
  * When the title is not provided, the default title is used
89
108
  *
@@ -116,6 +135,7 @@
116
135
  infinity: '(infinity; ∞)',
117
136
  negativeInfinity: '(negative infinity; -∞)',
118
137
  unserializable: '(unserializable value)',
138
+ circular: '(circular JSON)',
119
139
  };
120
140
  /**
121
141
  * Small number limit
@@ -155,7 +175,7 @@
155
175
  */
156
176
  const DEFAULT_MAX_EXECUTION_ATTEMPTS = 10; // <- TODO: [🤹‍♂️]
157
177
  // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
158
- // TODO: !!!!!! Just .promptbook dir, hardocode others
178
+ // TODO: Just `.promptbook` in config, hardcode subfolders like `download-cache` or `execution-cache`
159
179
  /**
160
180
  * Where to store the temporary downloads
161
181
  *
@@ -210,6 +230,122 @@
210
230
  * TODO: [🧠][🧜‍♂️] Maybe join remoteServerUrl and path into single value
211
231
  */
212
232
 
233
+ /**
234
+ * Make error report URL for the given error
235
+ *
236
+ * @private private within the repository
237
+ */
238
+ function getErrorReportUrl(error) {
239
+ const report = {
240
+ title: `🐜 Error report from ${NAME}`,
241
+ body: spaceTrim__default["default"]((block) => `
242
+
243
+
244
+ \`${error.name || 'Error'}\` has occurred in the [${NAME}], please look into it @${ADMIN_GITHUB_NAME}.
245
+
246
+ \`\`\`
247
+ ${block(error.message || '(no error message)')}
248
+ \`\`\`
249
+
250
+
251
+ ## More info:
252
+
253
+ - **Promptbook engine version:** ${PROMPTBOOK_ENGINE_VERSION}
254
+ - **Book language version:** ${BOOK_LANGUAGE_VERSION}
255
+ - **Time:** ${new Date().toISOString()}
256
+
257
+ <details>
258
+ <summary>Stack trace:</summary>
259
+
260
+ ## Stack trace:
261
+
262
+ \`\`\`stacktrace
263
+ ${block(error.stack || '(empty)')}
264
+ \`\`\`
265
+ </details>
266
+
267
+ `),
268
+ };
269
+ const reportUrl = new URL(`https://github.com/webgptorg/promptbook/issues/new`);
270
+ reportUrl.searchParams.set('labels', 'bug');
271
+ reportUrl.searchParams.set('assignees', ADMIN_GITHUB_NAME);
272
+ reportUrl.searchParams.set('title', report.title);
273
+ reportUrl.searchParams.set('body', report.body);
274
+ return reportUrl;
275
+ }
276
+
277
+ /**
278
+ * This error type indicates that the error should not happen and its last check before crashing with some other error
279
+ *
280
+ * @public exported from `@promptbook/core`
281
+ */
282
+ class UnexpectedError extends Error {
283
+ constructor(message) {
284
+ super(spaceTrim.spaceTrim((block) => `
285
+ ${block(message)}
286
+
287
+ Note: This error should not happen.
288
+ It's probbably a bug in the pipeline collection
289
+
290
+ Please report issue:
291
+ ${block(getErrorReportUrl(new Error(message)).href)}
292
+
293
+ Or contact us on ${ADMIN_EMAIL}
294
+
295
+ `));
296
+ this.name = 'UnexpectedError';
297
+ Object.setPrototypeOf(this, UnexpectedError.prototype);
298
+ }
299
+ }
300
+
301
+ /**
302
+ * This error type indicates that somewhere in the code non-Error object was thrown and it was wrapped into the `WrappedError`
303
+ *
304
+ * @public exported from `@promptbook/core`
305
+ */
306
+ class WrappedError extends Error {
307
+ constructor(whatWasThrown) {
308
+ const tag = `[🤮]`;
309
+ console.error(tag, whatWasThrown);
310
+ super(spaceTrim.spaceTrim(`
311
+ Non-Error object was thrown
312
+
313
+ Note: Look for ${tag} in the console for more details
314
+ Please report issue on ${ADMIN_EMAIL}
315
+ `));
316
+ this.name = 'WrappedError';
317
+ Object.setPrototypeOf(this, WrappedError.prototype);
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Helper used in catch blocks to assert that the error is an instance of `Error`
323
+ *
324
+ * @param whatWasThrown Any object that was thrown
325
+ * @returns Nothing if the error is an instance of `Error`
326
+ * @throws `WrappedError` or `UnexpectedError` if the error is not standard
327
+ *
328
+ * @private within the repository
329
+ */
330
+ function assertsError(whatWasThrown) {
331
+ // Case 1: Handle error which was rethrown as `WrappedError`
332
+ if (whatWasThrown instanceof WrappedError) {
333
+ const wrappedError = whatWasThrown;
334
+ throw wrappedError;
335
+ }
336
+ // Case 2: Handle unexpected errors
337
+ if (whatWasThrown instanceof UnexpectedError) {
338
+ const unexpectedError = whatWasThrown;
339
+ throw unexpectedError;
340
+ }
341
+ // Case 3: Handle standard errors - keep them up to consumer
342
+ if (whatWasThrown instanceof Error) {
343
+ return;
344
+ }
345
+ // Case 4: Handle non-standard errors - wrap them into `WrappedError` and throw
346
+ throw new WrappedError(whatWasThrown);
347
+ }
348
+
213
349
  /**
214
350
  * AuthenticationError is thrown from login function which is dependency of remote server
215
351
  *
@@ -254,7 +390,7 @@
254
390
  }
255
391
  }
256
392
  /**
257
- * TODO: !!!!!! Add id to all errors
393
+ * TODO: [🧠][🌂] Add id to all errors
258
394
  */
259
395
 
260
396
  /**
@@ -464,74 +600,6 @@
464
600
  }
465
601
  }
466
602
 
467
- /**
468
- * Make error report URL for the given error
469
- *
470
- * @private private within the repository
471
- */
472
- function getErrorReportUrl(error) {
473
- const report = {
474
- title: `🐜 Error report from ${NAME}`,
475
- body: spaceTrim__default["default"]((block) => `
476
-
477
-
478
- \`${error.name || 'Error'}\` has occurred in the [${NAME}], please look into it @${ADMIN_GITHUB_NAME}.
479
-
480
- \`\`\`
481
- ${block(error.message || '(no error message)')}
482
- \`\`\`
483
-
484
-
485
- ## More info:
486
-
487
- - **Promptbook engine version:** ${PROMPTBOOK_ENGINE_VERSION}
488
- - **Book language version:** ${BOOK_LANGUAGE_VERSION}
489
- - **Time:** ${new Date().toISOString()}
490
-
491
- <details>
492
- <summary>Stack trace:</summary>
493
-
494
- ## Stack trace:
495
-
496
- \`\`\`stacktrace
497
- ${block(error.stack || '(empty)')}
498
- \`\`\`
499
- </details>
500
-
501
- `),
502
- };
503
- const reportUrl = new URL(`https://github.com/webgptorg/promptbook/issues/new`);
504
- reportUrl.searchParams.set('labels', 'bug');
505
- reportUrl.searchParams.set('assignees', ADMIN_GITHUB_NAME);
506
- reportUrl.searchParams.set('title', report.title);
507
- reportUrl.searchParams.set('body', report.body);
508
- return reportUrl;
509
- }
510
-
511
- /**
512
- * This error type indicates that the error should not happen and its last check before crashing with some other error
513
- *
514
- * @public exported from `@promptbook/core`
515
- */
516
- class UnexpectedError extends Error {
517
- constructor(message) {
518
- super(spaceTrim.spaceTrim((block) => `
519
- ${block(message)}
520
-
521
- Note: This error should not happen.
522
- It's probbably a bug in the pipeline collection
523
-
524
- Please report issue:
525
- ${block(getErrorReportUrl(new Error(message)).href)}
526
-
527
- Or contact us on ${ADMIN_EMAIL}
528
-
529
- `));
530
- this.name = 'UnexpectedError';
531
- Object.setPrototypeOf(this, UnexpectedError.prototype);
532
- }
533
- }
534
-
535
603
  /**
536
604
  * Index of all custom errors
537
605
  *
@@ -552,7 +620,10 @@
552
620
  PipelineExecutionError,
553
621
  PipelineLogicError,
554
622
  PipelineUrlError,
623
+ AuthenticationError,
624
+ PromptbookFetchError,
555
625
  UnexpectedError,
626
+ WrappedError,
556
627
  // TODO: [🪑]> VersionMismatchError,
557
628
  };
558
629
  /**
@@ -569,8 +640,6 @@
569
640
  TypeError,
570
641
  URIError,
571
642
  AggregateError,
572
- AuthenticationError,
573
- PromptbookFetchError,
574
643
  /*
575
644
  Note: Not widely supported
576
645
  > InternalError,
@@ -813,9 +882,7 @@
813
882
  return result.trim();
814
883
  }
815
884
  catch (error) {
816
- if (!(error instanceof Error)) {
817
- throw error;
818
- }
885
+ assertsError(error);
819
886
  return null;
820
887
  }
821
888
  }
@@ -893,9 +960,7 @@
893
960
  return result.trim() + toExec;
894
961
  }
895
962
  catch (error) {
896
- if (!(error instanceof Error)) {
897
- throw error;
898
- }
963
+ assertsError(error);
899
964
  return null;
900
965
  }
901
966
  }
@@ -926,9 +991,7 @@
926
991
  throw new Error(`Can not locate app ${appName} on Windows.`);
927
992
  }
928
993
  catch (error) {
929
- if (!(error instanceof Error)) {
930
- throw error;
931
- }
994
+ assertsError(error);
932
995
  return null;
933
996
  }
934
997
  }
@@ -1166,9 +1229,7 @@
1166
1229
  JSON.stringify(value); // <- TODO: [0]
1167
1230
  }
1168
1231
  catch (error) {
1169
- if (!(error instanceof Error)) {
1170
- throw error;
1171
- }
1232
+ assertsError(error);
1172
1233
  throw new UnexpectedError(spaceTrim__default["default"]((block) => `
1173
1234
  \`${name}\` is not serializable
1174
1235
 
@@ -1768,6 +1829,9 @@
1768
1829
  /**
1769
1830
  * Function isValidJsonString will tell you if the string is valid JSON or not
1770
1831
  *
1832
+ * @param value The string to check
1833
+ * @returns True if the string is a valid JSON string, false otherwise
1834
+ *
1771
1835
  * @public exported from `@promptbook/utils`
1772
1836
  */
1773
1837
  function isValidJsonString(value /* <- [👨‍⚖️] */) {
@@ -1776,9 +1840,7 @@
1776
1840
  return true;
1777
1841
  }
1778
1842
  catch (error) {
1779
- if (!(error instanceof Error)) {
1780
- throw error;
1781
- }
1843
+ assertsError(error);
1782
1844
  if (error.message.includes('Unexpected token')) {
1783
1845
  return false;
1784
1846
  }
@@ -1916,8 +1978,8 @@
1916
1978
  updatedAt = new Date();
1917
1979
  errors.push(...executionResult.errors);
1918
1980
  warnings.push(...executionResult.warnings);
1919
- // <- TODO: !!! Only unique errors and warnings should be added (or filtered)
1920
- // TODO: [🧠] !!! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
1981
+ // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
1982
+ // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
1921
1983
  // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
1922
1984
  // And delete `ExecutionTask.currentValue.preparedPipeline`
1923
1985
  assertsTaskSuccessful(executionResult);
@@ -1927,6 +1989,7 @@
1927
1989
  partialResultSubject.next(executionResult);
1928
1990
  }
1929
1991
  catch (error) {
1992
+ assertsError(error);
1930
1993
  status = 'ERROR';
1931
1994
  errors.push(error);
1932
1995
  partialResultSubject.error(error);
@@ -2737,14 +2800,15 @@
2737
2800
  }
2738
2801
  }
2739
2802
  catch (error) {
2740
- if (!(error instanceof Error) || error instanceof UnexpectedError) {
2803
+ assertsError(error);
2804
+ if (error instanceof UnexpectedError) {
2741
2805
  throw error;
2742
2806
  }
2743
2807
  errors.push({ llmExecutionTools, error });
2744
2808
  }
2745
2809
  }
2746
2810
  if (errors.length === 1) {
2747
- throw errors[0];
2811
+ throw errors[0].error;
2748
2812
  }
2749
2813
  else if (errors.length > 1) {
2750
2814
  throw new PipelineExecutionError(
@@ -3585,9 +3649,7 @@
3585
3649
  return await fetch(urlOrRequest, init);
3586
3650
  }
3587
3651
  catch (error) {
3588
- if (!(error instanceof Error)) {
3589
- throw error;
3590
- }
3652
+ assertsError(error);
3591
3653
  let url;
3592
3654
  if (typeof urlOrRequest === 'string') {
3593
3655
  url = urlOrRequest;
@@ -3818,9 +3880,7 @@
3818
3880
  knowledgePreparedUnflatten[index] = pieces;
3819
3881
  }
3820
3882
  catch (error) {
3821
- if (!(error instanceof Error)) {
3822
- throw error;
3823
- }
3883
+ assertsError(error);
3824
3884
  console.warn(error);
3825
3885
  // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
3826
3886
  }
@@ -4112,13 +4172,19 @@
4112
4172
  return value.toISOString();
4113
4173
  }
4114
4174
  else {
4115
- return JSON.stringify(value);
4175
+ try {
4176
+ return JSON.stringify(value);
4177
+ }
4178
+ catch (error) {
4179
+ if (error instanceof TypeError && error.message.includes('circular structure')) {
4180
+ return VALUE_STRINGS.circular;
4181
+ }
4182
+ throw error;
4183
+ }
4116
4184
  }
4117
4185
  }
4118
4186
  catch (error) {
4119
- if (!(error instanceof Error)) {
4120
- throw error;
4121
- }
4187
+ assertsError(error);
4122
4188
  console.error(error);
4123
4189
  return VALUE_STRINGS.unserializable;
4124
4190
  }
@@ -4175,9 +4241,7 @@
4175
4241
  }
4176
4242
  }
4177
4243
  catch (error) {
4178
- if (!(error instanceof Error)) {
4179
- throw error;
4180
- }
4244
+ assertsError(error);
4181
4245
  throw new ParseError(spaceTrim.spaceTrim((block) => `
4182
4246
  Can not extract variables from the script
4183
4247
  ${block(error.stack || error.message)}
@@ -4296,6 +4360,28 @@
4296
4360
  // encoding: 'utf-8',
4297
4361
  });
4298
4362
 
4363
+ /**
4364
+ * Function to check if a string is valid CSV
4365
+ *
4366
+ * @param value The string to check
4367
+ * @returns True if the string is a valid CSV string, false otherwise
4368
+ *
4369
+ * @public exported from `@promptbook/utils`
4370
+ */
4371
+ function isValidCsvString(value) {
4372
+ try {
4373
+ // A simple check for CSV format: at least one comma and no invalid characters
4374
+ if (value.includes(',') && /^[\w\s,"']+$/.test(value)) {
4375
+ return true;
4376
+ }
4377
+ return false;
4378
+ }
4379
+ catch (error) {
4380
+ assertsError(error);
4381
+ return false;
4382
+ }
4383
+ }
4384
+
4299
4385
  /**
4300
4386
  * Definition for CSV spreadsheet
4301
4387
  *
@@ -4306,7 +4392,7 @@
4306
4392
  formatName: 'CSV',
4307
4393
  aliases: ['SPREADSHEET', 'TABLE'],
4308
4394
  isValid(value, settings, schema) {
4309
- return true;
4395
+ return isValidCsvString(value);
4310
4396
  },
4311
4397
  canBeValid(partialValue, settings, schema) {
4312
4398
  return true;
@@ -4460,6 +4546,30 @@
4460
4546
  * TODO: [🏢] Allow to expect something inside each item of list and other formats
4461
4547
  */
4462
4548
 
4549
+ /**
4550
+ * Function to check if a string is valid XML
4551
+ *
4552
+ * @param value
4553
+ * @returns True if the string is a valid XML string, false otherwise
4554
+ *
4555
+ * @public exported from `@promptbook/utils`
4556
+ */
4557
+ function isValidXmlString(value) {
4558
+ try {
4559
+ const parser = new DOMParser();
4560
+ const parsedDocument = parser.parseFromString(value, 'application/xml');
4561
+ const parserError = parsedDocument.getElementsByTagName('parsererror');
4562
+ if (parserError.length > 0) {
4563
+ return false;
4564
+ }
4565
+ return true;
4566
+ }
4567
+ catch (error) {
4568
+ assertsError(error);
4569
+ return false;
4570
+ }
4571
+ }
4572
+
4463
4573
  /**
4464
4574
  * Definition for XML format
4465
4575
  *
@@ -4469,7 +4579,7 @@
4469
4579
  formatName: 'XML',
4470
4580
  mimeType: 'application/xml',
4471
4581
  isValid(value, settings, schema) {
4472
- return true;
4582
+ return isValidXmlString(value);
4473
4583
  },
4474
4584
  canBeValid(partialValue, settings, schema) {
4475
4585
  return true;
@@ -5059,9 +5169,7 @@
5059
5169
  break scripts;
5060
5170
  }
5061
5171
  catch (error) {
5062
- if (!(error instanceof Error)) {
5063
- throw error;
5064
- }
5172
+ assertsError(error);
5065
5173
  if (error instanceof UnexpectedError) {
5066
5174
  throw error;
5067
5175
  }
@@ -5131,9 +5239,7 @@
5131
5239
  break scripts;
5132
5240
  }
5133
5241
  catch (error) {
5134
- if (!(error instanceof Error)) {
5135
- throw error;
5136
- }
5242
+ assertsError(error);
5137
5243
  if (error instanceof UnexpectedError) {
5138
5244
  throw error;
5139
5245
  }
@@ -5754,9 +5860,7 @@
5754
5860
  await Promise.all(resolving);
5755
5861
  }
5756
5862
  catch (error /* <- Note: [3] */) {
5757
- if (!(error instanceof Error)) {
5758
- throw error;
5759
- }
5863
+ assertsError(error);
5760
5864
  // Note: No need to rethrow UnexpectedError
5761
5865
  // if (error instanceof UnexpectedError) {
5762
5866
  // Note: Count usage, [🧠] Maybe put to separate function executionReportJsonToUsage + DRY [🤹‍♂️]
@@ -6658,9 +6762,7 @@
6658
6762
  }
6659
6763
  }
6660
6764
  catch (error) {
6661
- if (!(error instanceof Error)) {
6662
- throw error;
6663
- }
6765
+ assertsError(error);
6664
6766
  if (error instanceof ReferenceError) {
6665
6767
  const undefinedName = error.message.split(' ')[0];
6666
6768
  /*
@@ -6740,6 +6842,198 @@
6740
6842
  * Note: [🟢] Code in this file should never be never released in packages that could be imported into browser environment
6741
6843
  */
6742
6844
 
6845
+ // TODO: !!!! List running services from REMOTE_SERVER_URLS
6846
+ // TODO: !!!! Import directly from YML
6847
+ /**
6848
+ * @private !!!! Decide how to expose this
6849
+ */
6850
+ const openapiJson = {
6851
+ openapi: '3.0.0',
6852
+ info: {
6853
+ title: 'Promptbook Remote Server API (!!!! From TS)',
6854
+ version: '1.0.0',
6855
+ description: 'API documentation for the Promptbook Remote Server',
6856
+ },
6857
+ paths: {
6858
+ '/': {
6859
+ get: {
6860
+ summary: 'Get server details',
6861
+ description: 'Returns details about the Promptbook server.',
6862
+ responses: {
6863
+ '200': {
6864
+ description: 'Server details in markdown format.',
6865
+ },
6866
+ },
6867
+ },
6868
+ },
6869
+ '/login': {
6870
+ post: {
6871
+ summary: 'Login to the server',
6872
+ description: 'Login to the server and get identification.',
6873
+ requestBody: {
6874
+ required: true,
6875
+ content: {
6876
+ 'application/json': {
6877
+ schema: {
6878
+ type: 'object',
6879
+ properties: {
6880
+ username: {
6881
+ type: 'string',
6882
+ },
6883
+ password: {
6884
+ type: 'string',
6885
+ },
6886
+ appId: {
6887
+ type: 'string',
6888
+ },
6889
+ },
6890
+ },
6891
+ },
6892
+ },
6893
+ },
6894
+ responses: {
6895
+ '200': {
6896
+ description: 'Successful login',
6897
+ content: {
6898
+ 'application/json': {
6899
+ schema: {
6900
+ type: 'object',
6901
+ properties: {
6902
+ identification: {
6903
+ type: 'object',
6904
+ },
6905
+ },
6906
+ },
6907
+ },
6908
+ },
6909
+ },
6910
+ },
6911
+ },
6912
+ },
6913
+ '/books': {
6914
+ get: {
6915
+ summary: 'List all books',
6916
+ description: 'Returns a list of all available books in the collection.',
6917
+ responses: {
6918
+ '200': {
6919
+ description: 'A list of books.',
6920
+ content: {
6921
+ 'application/json': {
6922
+ schema: {
6923
+ type: 'array',
6924
+ items: {
6925
+ type: 'string',
6926
+ },
6927
+ },
6928
+ },
6929
+ },
6930
+ },
6931
+ },
6932
+ },
6933
+ },
6934
+ '/books/{bookId}': {
6935
+ get: {
6936
+ summary: 'Get book content',
6937
+ description: 'Returns the content of a specific book.',
6938
+ parameters: [
6939
+ {
6940
+ in: 'path',
6941
+ name: 'bookId',
6942
+ required: true,
6943
+ schema: {
6944
+ type: 'string',
6945
+ },
6946
+ description: 'The ID of the book to retrieve.',
6947
+ },
6948
+ ],
6949
+ responses: {
6950
+ '200': {
6951
+ description: 'The content of the book.',
6952
+ content: {
6953
+ 'text/markdown': {
6954
+ schema: {
6955
+ type: 'string',
6956
+ },
6957
+ },
6958
+ },
6959
+ },
6960
+ '404': {
6961
+ description: 'Book not found.',
6962
+ },
6963
+ },
6964
+ },
6965
+ },
6966
+ '/executions': {
6967
+ get: {
6968
+ summary: 'List all executions',
6969
+ description: 'Returns a list of all running execution tasks.',
6970
+ responses: {
6971
+ '200': {
6972
+ description: 'A list of execution tasks.',
6973
+ content: {
6974
+ 'application/json': {
6975
+ schema: {
6976
+ type: 'array',
6977
+ items: {
6978
+ type: 'object',
6979
+ },
6980
+ },
6981
+ },
6982
+ },
6983
+ },
6984
+ },
6985
+ },
6986
+ },
6987
+ '/executions/new': {
6988
+ post: {
6989
+ summary: 'Start a new execution',
6990
+ description: 'Starts a new execution task for a given pipeline.',
6991
+ requestBody: {
6992
+ required: true,
6993
+ content: {
6994
+ 'application/json': {
6995
+ schema: {
6996
+ type: 'object',
6997
+ properties: {
6998
+ pipelineUrl: {
6999
+ type: 'string',
7000
+ },
7001
+ inputParameters: {
7002
+ type: 'object',
7003
+ },
7004
+ identification: {
7005
+ type: 'object',
7006
+ },
7007
+ },
7008
+ },
7009
+ },
7010
+ },
7011
+ },
7012
+ responses: {
7013
+ '200': {
7014
+ description: 'The newly created execution task.',
7015
+ content: {
7016
+ 'application/json': {
7017
+ schema: {
7018
+ type: 'object',
7019
+ },
7020
+ },
7021
+ },
7022
+ },
7023
+ '400': {
7024
+ description: 'Invalid input.',
7025
+ },
7026
+ },
7027
+ },
7028
+ },
7029
+ },
7030
+ components: {},
7031
+ tags: [],
7032
+ };
7033
+ /**
7034
+ * Note: [💞] Ignore a discrepancy between file name and entity name
7035
+ */
7036
+
6743
7037
  /**
6744
7038
  * Remote server is a proxy server that uses its execution tools internally and exposes the executor interface externally.
6745
7039
  *
@@ -6750,7 +7044,7 @@
6750
7044
  * @public exported from `@promptbook/remote-server`
6751
7045
  */
6752
7046
  function startRemoteServer(options) {
6753
- const { port, collection, createLlmExecutionTools, isAnonymousModeAllowed, isApplicationModeAllowed, isVerbose = DEFAULT_IS_VERBOSE, login, } = {
7047
+ const { port, collection, createLlmExecutionTools, createExecutionTools, isAnonymousModeAllowed, isApplicationModeAllowed, isVerbose = DEFAULT_IS_VERBOSE, login, } = {
6754
7048
  isAnonymousModeAllowed: false,
6755
7049
  isApplicationModeAllowed: false,
6756
7050
  collection: null,
@@ -6758,22 +7052,6 @@
6758
7052
  login: null,
6759
7053
  ...options,
6760
7054
  };
6761
- // <- TODO: [🦪] Some helper type to be able to use discriminant union types with destructuring
6762
- let { rootPath = '/' } = options;
6763
- if (!rootPath.startsWith('/')) {
6764
- rootPath = `/${rootPath}`;
6765
- } /* not else */
6766
- if (rootPath.endsWith('/')) {
6767
- rootPath = rootPath.slice(0, -1);
6768
- } /* not else */
6769
- if (rootPath === '/') {
6770
- rootPath = '';
6771
- }
6772
- const socketioPath = '/' +
6773
- `${rootPath}/socket.io`
6774
- .split('/')
6775
- .filter((part) => part !== '')
6776
- .join('/');
6777
7055
  const startupDate = new Date();
6778
7056
  async function getExecutionToolsFromIdentification(identification) {
6779
7057
  if (identification === null || identification === undefined) {
@@ -6796,23 +7074,25 @@
6796
7074
  }
6797
7075
  else if (isAnonymous === false && createLlmExecutionTools !== null) {
6798
7076
  // Note: Application mode
6799
- const { appId, userId, customOptions } = identification;
6800
- llm = await createLlmExecutionTools({
6801
- appId,
6802
- userId,
6803
- customOptions,
6804
- });
7077
+ llm = await createLlmExecutionTools(identification);
6805
7078
  }
6806
7079
  else {
6807
7080
  throw new PipelineExecutionError(`You must provide either llmToolsConfiguration or non-anonymous mode must be propperly configured`);
6808
7081
  }
6809
- const fs = $provideFilesystemForNode();
6810
- const executables = await $provideExecutablesForNode();
7082
+ const customExecutionTools = createExecutionTools ? await createExecutionTools(identification) : {};
7083
+ const fs = customExecutionTools.fs || $provideFilesystemForNode();
7084
+ const executables = customExecutionTools.executables || (await $provideExecutablesForNode());
7085
+ const scrapers = customExecutionTools.scrapers || (await $provideScrapersForNode({ fs, llm, executables }));
7086
+ const script = customExecutionTools.script || (await $provideScriptingForNode({}));
7087
+ const fetch = customExecutionTools.fetch || promptbookFetch;
7088
+ const userInterface = customExecutionTools.userInterface || undefined;
6811
7089
  const tools = {
6812
7090
  llm,
6813
7091
  fs,
6814
- scrapers: await $provideScrapersForNode({ fs, llm, executables }),
6815
- script: await $provideScriptingForNode({}),
7092
+ scrapers,
7093
+ script,
7094
+ fetch,
7095
+ userInterface,
6816
7096
  };
6817
7097
  return tools;
6818
7098
  }
@@ -6822,39 +7102,27 @@
6822
7102
  response.setHeader('X-Powered-By', 'Promptbook engine');
6823
7103
  next();
6824
7104
  });
6825
- const swaggerOptions = {
6826
- definition: {
6827
- openapi: '3.0.0',
6828
- info: {
6829
- title: 'Promptbook Remote Server API',
6830
- version: '1.0.0',
6831
- description: 'API documentation for the Promptbook Remote Server',
6832
- },
6833
- servers: [
6834
- {
6835
- url: `http://localhost:${port}${rootPath}`,
6836
- // <- TODO: !!!!! Probbably: Pass `remoteServerUrl` instead of `port` and `rootPath`
6837
- },
6838
- ],
7105
+ // TODO: !!!! Expose openapiJson to consumer and also allow to add new routes
7106
+ app.use(OpenApiValidator__namespace.middleware({
7107
+ apiSpec: openapiJson,
7108
+ ignorePaths(path) {
7109
+ return path.startsWith('/api-docs') || path.startsWith('/swagger') || path.startsWith('/openapi');
6839
7110
  },
6840
- apis: ['./src/remote-server/**/*.ts'], // Adjust path as needed
6841
- };
6842
- const swaggerSpec = swaggerJsdoc__default["default"](swaggerOptions);
6843
- app.use([`/api-docs`, `${rootPath}/api-docs`], swaggerUi__default["default"].serve, swaggerUi__default["default"].setup(swaggerSpec));
7111
+ validateRequests: true,
7112
+ validateResponses: true,
7113
+ }));
7114
+ app.use([`/api-docs`, `/swagger`], swaggerUi__default["default"].serve, swaggerUi__default["default"].setup(openapiJson, {
7115
+ // customCss: '.swagger-ui .topbar { display: none }',
7116
+ // customSiteTitle: 'BRJ API',
7117
+ // customfavIcon: 'https://brj.app/favicon.ico',
7118
+ }));
7119
+ app.get(`/openapi`, (request, response) => {
7120
+ response.json(openapiJson);
7121
+ });
6844
7122
  const runningExecutionTasks = [];
6845
7123
  // <- TODO: [🤬] Identify the users
6846
7124
  // TODO: [🧠] Do here some garbage collection of finished tasks
6847
- /**
6848
- * @swagger
6849
- * /:
6850
- * get:
6851
- * summary: Get server details
6852
- * description: Returns details about the Promptbook server.
6853
- * responses:
6854
- * 200:
6855
- * description: Server details in markdown format.
6856
- */
6857
- app.get(['/', rootPath], async (request, response) => {
7125
+ app.get('/', async (request, response) => {
6858
7126
  var _a;
6859
7127
  if ((_a = request.url) === null || _a === void 0 ? void 0 : _a.includes('socket.io')) {
6860
7128
  return;
@@ -6873,8 +7141,6 @@
6873
7141
  ## Details
6874
7142
 
6875
7143
  **Server port:** ${port}
6876
- **Server root path:** ${rootPath}
6877
- **Socket.io path:** ${socketioPath}
6878
7144
  **Startup date:** ${startupDate.toISOString()}
6879
7145
  **Anonymouse mode:** ${isAnonymousModeAllowed ? 'enabled' : 'disabled'}
6880
7146
  **Application mode:** ${isApplicationModeAllowed ? 'enabled' : 'disabled'}
@@ -6913,38 +7179,7 @@
6913
7179
  https://github.com/webgptorg/promptbook
6914
7180
  `));
6915
7181
  });
6916
- /**
6917
- * @swagger
6918
- *
6919
- * /login:
6920
- * post:
6921
- * summary: Login to the server
6922
- * description: Login to the server and get identification.
6923
- * requestBody:
6924
- * required: true
6925
- * content:
6926
- * application/json:
6927
- * schema:
6928
- * type: object
6929
- * properties:
6930
- * username:
6931
- * type: string
6932
- * password:
6933
- * type: string
6934
- * appId:
6935
- * type: string
6936
- * responses:
6937
- * 200:
6938
- * description: Successful login
6939
- * content:
6940
- * application/json:
6941
- * schema:
6942
- * type: object
6943
- * properties:
6944
- * identification:
6945
- * type: object
6946
- */
6947
- app.post([`/login`, `${rootPath}/login`], async (request, response) => {
7182
+ app.post(`/login`, async (request, response) => {
6948
7183
  if (!isApplicationModeAllowed || login === null) {
6949
7184
  response.status(400).send('Application mode is not allowed');
6950
7185
  return;
@@ -6969,9 +7204,7 @@
6969
7204
  return;
6970
7205
  }
6971
7206
  catch (error) {
6972
- if (!(error instanceof Error)) {
6973
- throw error;
6974
- }
7207
+ assertsError(error);
6975
7208
  if (error instanceof AuthenticationError) {
6976
7209
  response.status(401).send({
6977
7210
  isSuccess: false,
@@ -6986,23 +7219,7 @@
6986
7219
  response.status(400).send({ error: serializeError(error) });
6987
7220
  }
6988
7221
  });
6989
- /**
6990
- * @swagger
6991
- * /books:
6992
- * get:
6993
- * summary: List all books
6994
- * description: Returns a list of all available books in the collection.
6995
- * responses:
6996
- * 200:
6997
- * description: A list of books.
6998
- * content:
6999
- * application/json:
7000
- * schema:
7001
- * type: array
7002
- * items:
7003
- * type: string
7004
- */
7005
- app.get([`/books`, `${rootPath}/books`], async (request, response) => {
7222
+ app.get(`/books`, async (request, response) => {
7006
7223
  if (collection === null) {
7007
7224
  response.status(500).send('No collection available');
7008
7225
  return;
@@ -7012,30 +7229,7 @@
7012
7229
  response.send(pipelines);
7013
7230
  });
7014
7231
  // TODO: [🧠] Is it secure / good idea to expose source codes of hosted books
7015
- /**
7016
- * @swagger
7017
- * /books/{bookId}:
7018
- * get:
7019
- * summary: Get book content
7020
- * description: Returns the content of a specific book.
7021
- * parameters:
7022
- * - in: path
7023
- * name: bookId
7024
- * required: true
7025
- * schema:
7026
- * type: string
7027
- * description: The ID of the book to retrieve.
7028
- * responses:
7029
- * 200:
7030
- * description: The content of the book.
7031
- * content:
7032
- * text/markdown:
7033
- * schema:
7034
- * type: string
7035
- * 404:
7036
- * description: Book not found.
7037
- */
7038
- app.get([`/books/*`, `${rootPath}/books/*`], async (request, response) => {
7232
+ app.get(`/books/*`, async (request, response) => {
7039
7233
  try {
7040
7234
  if (collection === null) {
7041
7235
  response.status(500).send('No collection nor books available');
@@ -7054,9 +7248,7 @@
7054
7248
  .send(source.content);
7055
7249
  }
7056
7250
  catch (error) {
7057
- if (!(error instanceof Error)) {
7058
- throw error;
7059
- }
7251
+ assertsError(error);
7060
7252
  response
7061
7253
  .status(404)
7062
7254
  .send({ error: serializeError(error) });
@@ -7089,26 +7281,10 @@
7089
7281
  };
7090
7282
  }
7091
7283
  }
7092
- /**
7093
- * @swagger
7094
- * /executions:
7095
- * get:
7096
- * summary: List all executions
7097
- * description: Returns a list of all running execution tasks.
7098
- * responses:
7099
- * 200:
7100
- * description: A list of execution tasks.
7101
- * content:
7102
- * application/json:
7103
- * schema:
7104
- * type: array
7105
- * items:
7106
- * type: object
7107
- */
7108
- app.get([`/executions`, `${rootPath}/executions`], async (request, response) => {
7109
- response.send(runningExecutionTasks.map((runningExecutionTask) => exportExecutionTask(runningExecutionTask, false)));
7284
+ app.get(`/executions`, async (request, response) => {
7285
+ response.send(runningExecutionTasks.map((runningExecutionTask) => exportExecutionTask(runningExecutionTask, false)) /* <- TODO: satisfies paths['/executions']['get']['responses']['200']['content']['application/json'] */);
7110
7286
  });
7111
- app.get([`/executions/last`, `${rootPath}/executions/last`], async (request, response) => {
7287
+ app.get(`/executions/last`, async (request, response) => {
7112
7288
  // TODO: [🤬] Filter only for user
7113
7289
  if (runningExecutionTasks.length === 0) {
7114
7290
  response.status(404).send('No execution tasks found');
@@ -7117,7 +7293,7 @@
7117
7293
  const lastExecutionTask = runningExecutionTasks[runningExecutionTasks.length - 1];
7118
7294
  response.send(exportExecutionTask(lastExecutionTask, true));
7119
7295
  });
7120
- app.get([`/executions/:taskId`, `${rootPath}/executions/:taskId`], async (request, response) => {
7296
+ app.get(`/executions/:taskId`, async (request, response) => {
7121
7297
  const { taskId } = request.params;
7122
7298
  // TODO: [🤬] Filter only for user
7123
7299
  const executionTask = runningExecutionTasks.find((executionTask) => executionTask.taskId === taskId);
@@ -7129,39 +7305,12 @@
7129
7305
  }
7130
7306
  response.send(exportExecutionTask(executionTask, true));
7131
7307
  });
7132
- /**
7133
- * @swagger
7134
- * /executions/new:
7135
- * post:
7136
- * summary: Start a new execution
7137
- * description: Starts a new execution task for a given pipeline.
7138
- * requestBody:
7139
- * required: true
7140
- * content:
7141
- * application/json:
7142
- * schema:
7143
- * type: object
7144
- * properties:
7145
- * pipelineUrl:
7146
- * type: string
7147
- * inputParameters:
7148
- * type: object
7149
- * identification:
7150
- * type: object
7151
- * responses:
7152
- * 200:
7153
- * description: The newly created execution task.
7154
- * content:
7155
- * application/json:
7156
- * schema:
7157
- * type: object
7158
- * 400:
7159
- * description: Invalid input.
7160
- */
7161
- app.post([`/executions/new`, `${rootPath}/executions/new`], async (request, response) => {
7308
+ app.post(`/executions/new`, async (request, response) => {
7162
7309
  try {
7163
7310
  const { inputParameters, identification /* <- [🤬] */ } = request.body;
7164
- const pipelineUrl = request.body.pipelineUrl || request.body.book;
7311
+ const pipelineUrl = request.body
7312
+ .pipelineUrl /* <- TODO: as paths['/executions/new']['post']['requestBody']['content']['application/json'] */ ||
7313
+ request.body.book;
7165
7314
  // TODO: [🧠] Check `pipelineUrl` and `inputParameters` here or it should be responsibility of `collection.getPipelineByUrl` and `pipelineExecutor`
7166
7315
  const pipeline = await (collection === null || collection === void 0 ? void 0 : collection.getPipelineByUrl(pipelineUrl));
7167
7316
  if (pipeline === undefined) {
@@ -7175,7 +7324,7 @@
7175
7324
  await waitasecond.forTime(10);
7176
7325
  // <- Note: Wait for a while to wait for quick responses or sudden but asynchronous errors
7177
7326
  // <- TODO: Put this into configuration
7178
- response.send(executionTask);
7327
+ response.send(executionTask /* <- TODO: satisfies paths['/executions/new']['post']['responses']['200']['content']['application/json'] */);
7179
7328
  /*/
7180
7329
  executionTask.asObservable().subscribe({
7181
7330
  next(partialResult) {
@@ -7195,19 +7344,24 @@
7195
7344
  */
7196
7345
  }
7197
7346
  catch (error) {
7198
- if (!(error instanceof Error)) {
7199
- throw error;
7200
- }
7347
+ assertsError(error);
7201
7348
  response.status(400).send({ error: serializeError(error) });
7202
7349
  }
7203
7350
  });
7351
+ /**
7352
+ * Catch-all handler for unmatched routes
7353
+ */
7354
+ app.use((request, response) => {
7355
+ response.status(404).send(`URL "${request.originalUrl}" was not found on Promptbook server.`);
7356
+ });
7204
7357
  const httpServer = http__default["default"].createServer(app);
7205
7358
  const server = new socket_io.Server(httpServer, {
7206
- path: socketioPath,
7207
- transports: [/*'websocket', <- TODO: [🌬] Make websocket transport work */ 'polling'],
7359
+ path: '/socket.io',
7360
+ transports: ['polling', 'websocket' /*, <- TODO: [🌬] Allow to pass `transports`, add 'webtransport' */],
7208
7361
  cors: {
7209
7362
  origin: '*',
7210
7363
  methods: ['GET', 'POST'],
7364
+ // <- TODO: [🌡] Allow to pass
7211
7365
  },
7212
7366
  });
7213
7367
  server.on('connection', (socket) => {
@@ -7261,9 +7415,7 @@
7261
7415
  socket.emit('prompt-response', { promptResult } /* <- Note: [🤛] */);
7262
7416
  }
7263
7417
  catch (error) {
7264
- if (!(error instanceof Error)) {
7265
- throw error;
7266
- }
7418
+ assertsError(error);
7267
7419
  socket.emit('error', serializeError(error) /* <- Note: [🤛] */);
7268
7420
  }
7269
7421
  finally {
@@ -7285,9 +7437,7 @@
7285
7437
  socket.emit('listModels-response', { models } /* <- Note: [🤛] */);
7286
7438
  }
7287
7439
  catch (error) {
7288
- if (!(error instanceof Error)) {
7289
- throw error;
7290
- }
7440
+ assertsError(error);
7291
7441
  socket.emit('error', serializeError(error));
7292
7442
  }
7293
7443
  finally {
@@ -7308,9 +7458,7 @@
7308
7458
  socket.emit('preparePipeline-response', { preparedPipeline } /* <- Note: [🤛] */);
7309
7459
  }
7310
7460
  catch (error) {
7311
- if (!(error instanceof Error)) {
7312
- throw error;
7313
- }
7461
+ assertsError(error);
7314
7462
  socket.emit('error', serializeError(error));
7315
7463
  // <- TODO: [🚋] There is a problem with the remote server handling errors and sending them back to the client
7316
7464
  }
@@ -7358,8 +7506,7 @@
7358
7506
  };
7359
7507
  }
7360
7508
  /**
7361
- * TODO: !! Add CORS and security - probbably via `helmet`
7362
- * TODO: [👩🏾‍🤝‍🧑🏾] Allow to pass custom fetch function here - PromptbookFetch
7509
+ * TODO: [🌡] Add CORS and security - probbably via `helmet`
7363
7510
  * TODO: Split this file into multiple functions - handler for each request
7364
7511
  * TODO: Maybe use `$exportJson`
7365
7512
  * TODO: [🧠][🛍] Maybe not `isAnonymous: boolean` BUT `mode: 'ANONYMOUS'|'COLLECTION'`