@promptbook/core 0.44.0-0 → 0.44.0-10

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 (37) hide show
  1. package/esm/index.es.js +745 -603
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/_packages/core.index.d.ts +2 -1
  4. package/esm/typings/_packages/utils.index.d.ts +21 -11
  5. package/esm/typings/config.d.ts +4 -0
  6. package/esm/typings/errors/PromptbookNotFoundError.d.ts +7 -0
  7. package/esm/typings/errors/{ExpectError.d.ts → _ExpectError.d.ts} +1 -0
  8. package/esm/typings/execution/plugins/natural-execution-tools/mocked/MockedEchoNaturalExecutionTools.d.ts +1 -1
  9. package/esm/typings/execution/plugins/natural-execution-tools/mocked/MockedFackedNaturalExecutionTools.d.ts +19 -0
  10. package/esm/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.d.ts +11 -0
  11. package/esm/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.test.d.ts +1 -0
  12. package/esm/typings/execution/plugins/natural-execution-tools/mocked/faked-completion.test.d.ts +1 -0
  13. package/esm/typings/execution/utils/checkExpectations.d.ts +25 -0
  14. package/esm/typings/execution/utils/checkExpectations.test.d.ts +1 -0
  15. package/esm/typings/types/Prompt.d.ts +8 -0
  16. package/esm/typings/types/PromptbookJson/PromptTemplateJson.d.ts +13 -4
  17. package/esm/typings/utils/expectation-counters/countSentences.d.ts +4 -0
  18. package/package.json +2 -1
  19. package/umd/index.umd.js +748 -606
  20. package/umd/index.umd.js.map +1 -1
  21. package/umd/typings/_packages/core.index.d.ts +2 -1
  22. package/umd/typings/_packages/utils.index.d.ts +21 -11
  23. package/umd/typings/config.d.ts +4 -0
  24. package/umd/typings/errors/PromptbookNotFoundError.d.ts +7 -0
  25. package/umd/typings/errors/{ExpectError.d.ts → _ExpectError.d.ts} +1 -0
  26. package/umd/typings/execution/plugins/natural-execution-tools/mocked/MockedEchoNaturalExecutionTools.d.ts +1 -1
  27. package/umd/typings/execution/plugins/natural-execution-tools/mocked/MockedFackedNaturalExecutionTools.d.ts +19 -0
  28. package/umd/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.d.ts +11 -0
  29. package/umd/typings/execution/plugins/natural-execution-tools/mocked/fakeTextToExpectations.test.d.ts +1 -0
  30. package/umd/typings/execution/plugins/natural-execution-tools/mocked/faked-completion.test.d.ts +1 -0
  31. package/umd/typings/execution/utils/checkExpectations.d.ts +25 -0
  32. package/umd/typings/execution/utils/checkExpectations.test.d.ts +1 -0
  33. package/umd/typings/types/Prompt.d.ts +8 -0
  34. package/umd/typings/types/PromptbookJson/PromptTemplateJson.d.ts +13 -4
  35. package/umd/typings/utils/expectation-counters/countSentences.d.ts +4 -0
  36. package/esm/typings/errors/NotFoundError.d.ts +0 -7
  37. package/umd/typings/errors/NotFoundError.d.ts +0 -7
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim));
5
- })(this, (function (exports, spaceTrim) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment'), require('lorem-ipsum')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment', 'lorem-ipsum'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, null, null, null, global.loremIpsum));
5
+ })(this, (function (exports, spaceTrim, prettier, parserHtml, moment, loremIpsum) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -128,409 +128,42 @@
128
128
  }
129
129
 
130
130
  /**
131
- * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
132
- */
133
- var PromptbookSyntaxError = /** @class */ (function (_super) {
134
- __extends(PromptbookSyntaxError, _super);
135
- function PromptbookSyntaxError(message) {
136
- var _this = _super.call(this, message) || this;
137
- _this.name = 'PromptbookSyntaxError';
138
- Object.setPrototypeOf(_this, PromptbookSyntaxError.prototype);
139
- return _this;
140
- }
141
- return PromptbookSyntaxError;
142
- }(Error));
143
-
144
- /**
145
- * Supported script languages
146
- */
147
- var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
148
-
149
- /**
150
- * Parses the template and returns the list of all parameter names
151
- *
152
- * @param template the template with parameters in {curly} braces
153
- * @returns the list of parameter names
154
- *
155
- * @private within the library
156
- */
157
- function extractParameters(template) {
158
- var e_1, _a;
159
- var matches = template.matchAll(/{\w+}/g);
160
- var parameterNames = [];
161
- try {
162
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
163
- var match = matches_1_1.value;
164
- var parameterName = match[0].slice(1, -1);
165
- if (!parameterNames.includes(parameterName)) {
166
- parameterNames.push(parameterName);
167
- }
168
- }
169
- }
170
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
171
- finally {
172
- try {
173
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
174
- }
175
- finally { if (e_1) throw e_1.error; }
176
- }
177
- return parameterNames;
178
- }
179
-
180
- /**
181
- * Computes the deepness of the markdown structure.
182
- *
183
- * @private within the library
184
- */
185
- function countMarkdownStructureDeepness(markdownStructure) {
186
- var e_1, _a;
187
- var maxDeepness = 0;
188
- try {
189
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
190
- var section = _c.value;
191
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
192
- }
193
- }
194
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
195
- finally {
196
- try {
197
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
198
- }
199
- finally { if (e_1) throw e_1.error; }
200
- }
201
- return maxDeepness + 1;
202
- }
203
-
204
- /**
205
- * The maximum number of iterations for a loops
206
- */
207
- var LOOP_LIMIT = 1000;
208
-
209
- /**
210
- * This error type indicates that the error should not happen and its last check before crashing with some other error
211
- */
212
- var UnexpectedError = /** @class */ (function (_super) {
213
- __extends(UnexpectedError, _super);
214
- function UnexpectedError(message) {
215
- var _this = _super.call(this, spaceTrim__default["default"](function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
216
- _this.name = 'UnexpectedError';
217
- Object.setPrototypeOf(_this, UnexpectedError.prototype);
218
- return _this;
219
- }
220
- return UnexpectedError;
221
- }(Error));
222
-
223
- /**
224
- * Parse a markdown string into a MarkdownStructure object.
225
- *
226
- * Note: This function does work with code blocks
227
- * Note: This function does not work with markdown comments
228
- *
229
- * @param markdown The markdown string to parse.
230
- * @returns The MarkdownStructure object.
231
- *
232
- * @private within the library
233
- */
234
- function markdownToMarkdownStructure(markdown) {
235
- var e_1, _a;
236
- var lines = markdown.split('\n');
237
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
238
- var current = root;
239
- var isInsideCodeBlock = false;
240
- try {
241
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
242
- var line = lines_1_1.value;
243
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
244
- if (isInsideCodeBlock || !headingMatch) {
245
- if (line.startsWith('```')) {
246
- isInsideCodeBlock = !isInsideCodeBlock;
247
- }
248
- current.contentLines.push(line);
249
- }
250
- else {
251
- var level = headingMatch.groups.mark.length;
252
- var title = headingMatch.groups.title.trim();
253
- var parent_1 = void 0;
254
- if (level > current.level) {
255
- // Note: Going deeper (next section is child of current)
256
- parent_1 = current;
257
- }
258
- else {
259
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
260
- parent_1 = current;
261
- var loopLimit = LOOP_LIMIT;
262
- while (parent_1.level !== level - 1) {
263
- if (loopLimit-- < 0) {
264
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
265
- }
266
- if (parent_1.parent === null /* <- Note: We are in root */) {
267
- // [🌻]
268
- throw new Error(spaceTrim__default["default"]("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
269
- }
270
- parent_1 = parent_1.parent;
271
- }
272
- }
273
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
274
- parent_1.sections.push(section);
275
- current = section;
276
- }
277
- }
278
- }
279
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
280
- finally {
281
- try {
282
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
283
- }
284
- finally { if (e_1) throw e_1.error; }
285
- }
286
- if (root.sections.length === 1) {
287
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
288
- return markdownStructure;
289
- }
290
- // [🌻]
291
- throw new Error('The markdown file must have exactly one top-level section.');
292
- // return root;
293
- }
294
- /**
295
- * @private
296
- */
297
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
298
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
299
- return {
300
- level: level,
301
- title: title,
302
- content: spaceTrim__default["default"](contentLines.join('\n')),
303
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
304
- };
305
- }
306
-
307
- /**
308
- * Utility function to extract all list items from markdown
309
- *
310
- * Note: It works with both ul and ol
311
- * Note: It omits list items in code blocks
312
- * Note: It flattens nested lists
313
- * Note: It can not work with html syntax and comments
314
- *
315
- * @param markdown any valid markdown
316
- * @returns
317
- */
318
- function extractAllListItemsFromMarkdown(markdown) {
319
- var e_1, _a;
320
- var lines = markdown.split('\n');
321
- var listItems = [];
322
- var isInCodeBlock = false;
323
- try {
324
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
325
- var line = lines_1_1.value;
326
- var trimmedLine = line.trim();
327
- if (trimmedLine.startsWith('```')) {
328
- isInCodeBlock = !isInCodeBlock;
329
- }
330
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
331
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
332
- listItems.push(listItem);
333
- }
334
- }
335
- }
336
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
337
- finally {
338
- try {
339
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
340
- }
341
- finally { if (e_1) throw e_1.error; }
342
- }
343
- return listItems;
344
- }
345
-
346
- /**
347
- * Makes first letter of a string uppercase
348
- *
349
- */
350
- function capitalize(word) {
351
- return word.substring(0, 1).toUpperCase() + word.substring(1);
352
- }
353
-
354
- /**
355
- * Extracts all code blocks from markdown.
356
- *
357
- * Note: There are 3 simmilar function:
358
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
359
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
360
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
361
- *
362
- * @param markdown any valid markdown
363
- * @returns code blocks with language and content
364
- *
365
- */
366
- function extractAllBlocksFromMarkdown(markdown) {
367
- var e_1, _a;
368
- var codeBlocks = [];
369
- var lines = markdown.split('\n');
370
- var currentCodeBlock = null;
371
- try {
372
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
373
- var line = lines_1_1.value;
374
- if (line.startsWith('```')) {
375
- var language = line.slice(3).trim() || null;
376
- if (currentCodeBlock === null) {
377
- currentCodeBlock = { language: language, content: '' };
378
- }
379
- else {
380
- if (language !== null) {
381
- // [🌻]
382
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
383
- }
384
- codeBlocks.push(currentCodeBlock);
385
- currentCodeBlock = null;
386
- }
387
- }
388
- else if (currentCodeBlock !== null) {
389
- if (currentCodeBlock.content !== '') {
390
- currentCodeBlock.content += '\n';
391
- }
392
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
393
- }
394
- }
395
- }
396
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
397
- finally {
398
- try {
399
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
400
- }
401
- finally { if (e_1) throw e_1.error; }
402
- }
403
- if (currentCodeBlock !== null) {
404
- // [🌻]
405
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
406
- }
407
- return codeBlocks;
408
- }
409
-
410
- /**
411
- * Extracts exactly ONE code block from markdown.
412
- *
413
- * Note: If there are multiple or no code blocks the function throws an error
414
- *
415
- * Note: There are 3 simmilar function:
416
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
417
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
418
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
419
- *
420
- * @param markdown any valid markdown
421
- * @returns code block with language and content
422
- */
423
- function extractOneBlockFromMarkdown(markdown) {
424
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
425
- if (codeBlocks.length !== 1) {
426
- // TODO: Report more specific place where the error happened
427
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
428
- }
429
- return codeBlocks[0];
430
- }
431
- /***
432
- * TODO: [🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
433
- */
434
-
435
- /**
436
- * Removes HTML or Markdown comments from a string.
437
- *
438
- * @param {string} content - The string to remove comments from.
439
- * @returns {string} The input string with all comments removed.
440
- */
441
- function removeContentComments(content) {
442
- return spaceTrim__default["default"](content.replace(/<!--(.*?)-->/gs, ''));
443
- }
444
-
445
- /**
446
- * The version of the Promptbook library
447
- */
448
- var PROMPTBOOK_VERSION = '0.43.0';
449
-
450
- /**
451
- * Parses the given script and returns the list of all used variables that are not defined in the script
452
- *
453
- * @param script from which to extract the variables
454
- * @returns the list of variable names
455
- * @throws {PromptbookSyntaxError} if the script is invalid
456
- *
457
- * @private within the promptbookStringToJson
458
- */
459
- function extractVariables(script) {
460
- var variables = [];
461
- script = "(()=>{".concat(script, "})()");
462
- try {
463
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
464
- try {
465
- eval(script);
466
- }
467
- catch (error) {
468
- if (!(error instanceof ReferenceError)) {
469
- throw error;
470
- }
471
- var undefinedName = error.message.split(' ')[0];
472
- /*
473
- Note: Remapping error
474
- From: [ReferenceError: thing is not defined],
475
- To: [Error: Parameter {thing} is not defined],
476
- */
477
- if (!undefinedName) {
478
- throw error;
479
- }
480
- if (script.includes(undefinedName + '(')) {
481
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
482
- }
483
- else {
484
- variables.push(undefinedName);
485
- script = "const ".concat(undefinedName, " = '';") + script;
486
- }
487
- }
488
- }
489
- catch (error) {
490
- if (!(error instanceof Error)) {
491
- throw error;
492
- }
493
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
131
+ * This error type indicates that the error should not happen and its last check before crashing with some other error
132
+ */
133
+ var UnexpectedError = /** @class */ (function (_super) {
134
+ __extends(UnexpectedError, _super);
135
+ function UnexpectedError(message) {
136
+ var _this = _super.call(this, spaceTrim__default["default"](function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
137
+ _this.name = 'UnexpectedError';
138
+ Object.setPrototypeOf(_this, UnexpectedError.prototype);
139
+ return _this;
494
140
  }
495
- return variables;
496
- }
141
+ return UnexpectedError;
142
+ }(Error));
497
143
 
498
144
  /**
499
- * Execution type describes the way how the block is executed
145
+ * Removes HTML or Markdown comments from a string.
500
146
  *
501
- * @see https://github.com/webgptorg/promptbook#execution-type
502
- */
503
- var ExecutionTypes = [
504
- 'PROMPT_TEMPLATE',
505
- 'SIMPLE_TEMPLATE',
506
- 'SCRIPT',
507
- 'PROMPT_DIALOG',
508
- // <- [🥻] Insert here when making new command
509
- ];
510
-
511
- /**
512
- * Units of text measurement
513
- */
514
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
515
- /**
516
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
147
+ * @param {string} content - The string to remove comments from.
148
+ * @returns {string} The input string with all comments removed.
517
149
  */
150
+ function removeContentComments(content) {
151
+ return spaceTrim__default["default"](content.replace(/<!--(.*?)-->/gs, ''));
152
+ }
518
153
 
519
154
  /**
520
- * Removes Markdown formatting tags from a string.
521
- *
522
- * @param {string} str - The string to remove Markdown tags from.
523
- * @returns {string} The input string with all Markdown tags removed.
155
+ * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
524
156
  */
525
- function removeMarkdownFormatting(str) {
526
- // Remove bold formatting
527
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
528
- // Remove italic formatting
529
- str = str.replace(/\*(.*?)\*/g, '$1');
530
- // Remove code formatting
531
- str = str.replace(/`(.*?)`/g, '$1');
532
- return str;
533
- }
157
+ var PromptbookSyntaxError = /** @class */ (function (_super) {
158
+ __extends(PromptbookSyntaxError, _super);
159
+ function PromptbookSyntaxError(message) {
160
+ var _this = _super.call(this, message) || this;
161
+ _this.name = 'PromptbookSyntaxError';
162
+ Object.setPrototypeOf(_this, PromptbookSyntaxError.prototype);
163
+ return _this;
164
+ }
165
+ return PromptbookSyntaxError;
166
+ }(Error));
534
167
 
535
168
  /**
536
169
  * Function parseNumber will parse number from string
@@ -614,81 +247,22 @@
614
247
  }(Error));
615
248
 
616
249
  /**
617
- * This error occurs during the parameter replacement in the template
250
+ * This error occurs when some expectation is not met in the execution of the pipeline
618
251
  *
619
- * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
252
+ * @private Always catched and rethrown as `PromptbookExecutionError`
253
+ * Note: This is a kindof subtype of PromptbookExecutionError
620
254
  */
621
- var TemplateError = /** @class */ (function (_super) {
622
- __extends(TemplateError, _super);
623
- function TemplateError(message) {
255
+ var ExpectError = /** @class */ (function (_super) {
256
+ __extends(ExpectError, _super);
257
+ function ExpectError(message) {
624
258
  var _this = _super.call(this, message) || this;
625
- _this.name = 'TemplateError';
626
- Object.setPrototypeOf(_this, TemplateError.prototype);
259
+ _this.name = 'ExpectError';
260
+ Object.setPrototypeOf(_this, ExpectError.prototype);
627
261
  return _this;
628
262
  }
629
- return TemplateError;
263
+ return ExpectError;
630
264
  }(Error));
631
265
 
632
- /**
633
- * Replaces parameters in template with values from parameters object
634
- *
635
- * @param template the template with parameters in {curly} braces
636
- * @param parameters the object with parameters
637
- * @returns the template with replaced parameters
638
- * @throws {TemplateError} if parameter is not defined, not closed, or not opened
639
- *
640
- * @private within the createPromptbookExecutor
641
- */
642
- function replaceParameters(template, parameters) {
643
- var replacedTemplate = template;
644
- var match;
645
- var loopLimit = LOOP_LIMIT;
646
- var _loop_1 = function () {
647
- if (loopLimit-- < 0) {
648
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
649
- }
650
- var precol = match.groups.precol;
651
- var parameterName = match.groups.parameterName;
652
- if (parameterName === '') {
653
- return "continue";
654
- }
655
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
656
- throw new TemplateError('Parameter is already opened or not closed');
657
- }
658
- if (parameters[parameterName] === undefined) {
659
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
660
- }
661
- var parameterValue = parameters[parameterName];
662
- if (parameterValue === undefined) {
663
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
664
- }
665
- parameterValue = parameterValue.toString();
666
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
667
- parameterValue = parameterValue
668
- .split('\n')
669
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
670
- .join('\n');
671
- }
672
- replacedTemplate =
673
- replacedTemplate.substring(0, match.index + precol.length) +
674
- parameterValue +
675
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
676
- };
677
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
678
- .exec(replacedTemplate))) {
679
- _loop_1();
680
- }
681
- // [💫] Check if there are parameters that are not closed properly
682
- if (/{\w+$/.test(replacedTemplate)) {
683
- throw new TemplateError('Parameter is not closed');
684
- }
685
- // [💫] Check if there are parameters that are not opened properly
686
- if (/^\w+}/.test(replacedTemplate)) {
687
- throw new TemplateError('Parameter is not opened');
688
- }
689
- return replacedTemplate;
690
- }
691
-
692
266
  /**
693
267
  * Counts number of characters in the text
694
268
  */
@@ -729,11 +303,17 @@
729
303
  return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
730
304
  }
731
305
 
306
+ /**
307
+ * Split text into sentences
308
+ */
309
+ function splitIntoSentences(text) {
310
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
311
+ }
732
312
  /**
733
313
  * Counts number of sentences in the text
734
314
  */
735
315
  function countSentences(text) {
736
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; }).length;
316
+ return splitIntoSentences(text).length;
737
317
  }
738
318
 
739
319
  var defaultDiacriticsRemovalMap = [
@@ -1010,6 +590,148 @@
1010
590
  PAGES: countPages,
1011
591
  };
1012
592
 
593
+ /**
594
+ * Function checkExpectations will check if the expectations on given value are met
595
+ *
596
+ * Note: There are two simmilar functions:
597
+ * - `checkExpectations` which throws an error if the expectations are not met
598
+ * - `isPassingExpectations` which returns a boolean
599
+ *
600
+ * @throws {ExpectError} if the expectations are not met
601
+ * @returns {void} Nothing
602
+ */
603
+ function checkExpectations(expectations, value) {
604
+ var e_1, _a;
605
+ try {
606
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
607
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
608
+ var amount = CountUtils[unit.toUpperCase()](value);
609
+ if (min && amount < min) {
610
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
611
+ } /* not else */
612
+ if (max && amount > max) {
613
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
614
+ }
615
+ }
616
+ }
617
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
618
+ finally {
619
+ try {
620
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
621
+ }
622
+ finally { if (e_1) throw e_1.error; }
623
+ }
624
+ }
625
+ /**
626
+ * Function checkExpectations will check if the expectations on given value are met
627
+ *
628
+ * Note: There are two simmilar functions:
629
+ * - `checkExpectations` which throws an error if the expectations are not met
630
+ * - `isPassingExpectations` which returns a boolean
631
+ *
632
+ * @returns {boolean} True if the expectations are met
633
+ */
634
+ function isPassingExpectations(expectations, value) {
635
+ try {
636
+ checkExpectations(expectations, value);
637
+ return true;
638
+ }
639
+ catch (error) {
640
+ if (!(error instanceof ExpectError)) {
641
+ throw error;
642
+ }
643
+ return false;
644
+ }
645
+ }
646
+ /**
647
+ * TODO: [💝] Unite object for expecting amount and format
648
+ */
649
+
650
+ /**
651
+ * The maximum number of iterations for a loops
652
+ */
653
+ var LOOP_LIMIT = 1000;
654
+ /**
655
+ * The maximum number of iterations for a loops which adds characters one by one
656
+ */
657
+ var CHARACTER_LOOP_LIMIT = 100000;
658
+
659
+ /**
660
+ * This error occurs during the parameter replacement in the template
661
+ *
662
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
663
+ */
664
+ var TemplateError = /** @class */ (function (_super) {
665
+ __extends(TemplateError, _super);
666
+ function TemplateError(message) {
667
+ var _this = _super.call(this, message) || this;
668
+ _this.name = 'TemplateError';
669
+ Object.setPrototypeOf(_this, TemplateError.prototype);
670
+ return _this;
671
+ }
672
+ return TemplateError;
673
+ }(Error));
674
+
675
+ /**
676
+ * Replaces parameters in template with values from parameters object
677
+ *
678
+ * @param template the template with parameters in {curly} braces
679
+ * @param parameters the object with parameters
680
+ * @returns the template with replaced parameters
681
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
682
+ *
683
+ * @private within the createPromptbookExecutor
684
+ */
685
+ function replaceParameters(template, parameters) {
686
+ var replacedTemplate = template;
687
+ var match;
688
+ var loopLimit = LOOP_LIMIT;
689
+ var _loop_1 = function () {
690
+ if (loopLimit-- < 0) {
691
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
692
+ }
693
+ var precol = match.groups.precol;
694
+ var parameterName = match.groups.parameterName;
695
+ if (parameterName === '') {
696
+ return "continue";
697
+ }
698
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
699
+ throw new TemplateError('Parameter is already opened or not closed');
700
+ }
701
+ if (parameters[parameterName] === undefined) {
702
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
703
+ }
704
+ var parameterValue = parameters[parameterName];
705
+ if (parameterValue === undefined) {
706
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
707
+ }
708
+ parameterValue = parameterValue.toString();
709
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
710
+ parameterValue = parameterValue
711
+ .split('\n')
712
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
713
+ .join('\n');
714
+ }
715
+ replacedTemplate =
716
+ replacedTemplate.substring(0, match.index + precol.length) +
717
+ parameterValue +
718
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
719
+ };
720
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
721
+ .exec(replacedTemplate))) {
722
+ _loop_1();
723
+ }
724
+ // [💫] Check if there are parameters that are not closed properly
725
+ if (/{\w+$/.test(replacedTemplate)) {
726
+ throw new TemplateError('Parameter is not closed');
727
+ }
728
+ // [💫] Check if there are parameters that are not opened properly
729
+ if (/^\w+}/.test(replacedTemplate)) {
730
+ throw new TemplateError('Parameter is not opened');
731
+ }
732
+ return replacedTemplate;
733
+ }
734
+
1013
735
  /**
1014
736
  * Function isValidJsonString will tell you if the string is valid JSON or not
1015
737
  */
@@ -1029,6 +751,150 @@
1029
751
  }
1030
752
  }
1031
753
 
754
+ /**
755
+ * Makes first letter of a string uppercase
756
+ *
757
+ */
758
+ function capitalize(word) {
759
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
760
+ }
761
+
762
+ /**
763
+ * Extracts all code blocks from markdown.
764
+ *
765
+ * Note: There are 3 simmilar function:
766
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
767
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
768
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
769
+ *
770
+ * @param markdown any valid markdown
771
+ * @returns code blocks with language and content
772
+ *
773
+ */
774
+ function extractAllBlocksFromMarkdown(markdown) {
775
+ var e_1, _a;
776
+ var codeBlocks = [];
777
+ var lines = markdown.split('\n');
778
+ var currentCodeBlock = null;
779
+ try {
780
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
781
+ var line = lines_1_1.value;
782
+ if (line.startsWith('```')) {
783
+ var language = line.slice(3).trim() || null;
784
+ if (currentCodeBlock === null) {
785
+ currentCodeBlock = { language: language, content: '' };
786
+ }
787
+ else {
788
+ if (language !== null) {
789
+ // [🌻]
790
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
791
+ }
792
+ codeBlocks.push(currentCodeBlock);
793
+ currentCodeBlock = null;
794
+ }
795
+ }
796
+ else if (currentCodeBlock !== null) {
797
+ if (currentCodeBlock.content !== '') {
798
+ currentCodeBlock.content += '\n';
799
+ }
800
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
801
+ }
802
+ }
803
+ }
804
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
805
+ finally {
806
+ try {
807
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
808
+ }
809
+ finally { if (e_1) throw e_1.error; }
810
+ }
811
+ if (currentCodeBlock !== null) {
812
+ // [🌻]
813
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
814
+ }
815
+ return codeBlocks;
816
+ }
817
+
818
+ /**
819
+ * Utility function to extract all list items from markdown
820
+ *
821
+ * Note: It works with both ul and ol
822
+ * Note: It omits list items in code blocks
823
+ * Note: It flattens nested lists
824
+ * Note: It can not work with html syntax and comments
825
+ *
826
+ * @param markdown any valid markdown
827
+ * @returns
828
+ */
829
+ function extractAllListItemsFromMarkdown(markdown) {
830
+ var e_1, _a;
831
+ var lines = markdown.split('\n');
832
+ var listItems = [];
833
+ var isInCodeBlock = false;
834
+ try {
835
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
836
+ var line = lines_1_1.value;
837
+ var trimmedLine = line.trim();
838
+ if (trimmedLine.startsWith('```')) {
839
+ isInCodeBlock = !isInCodeBlock;
840
+ }
841
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
842
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
843
+ listItems.push(listItem);
844
+ }
845
+ }
846
+ }
847
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
848
+ finally {
849
+ try {
850
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
851
+ }
852
+ finally { if (e_1) throw e_1.error; }
853
+ }
854
+ return listItems;
855
+ }
856
+
857
+ /**
858
+ * Extracts exactly ONE code block from markdown.
859
+ *
860
+ * Note: If there are multiple or no code blocks the function throws an error
861
+ *
862
+ * Note: There are 3 simmilar function:
863
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
864
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
865
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
866
+ *
867
+ * @param markdown any valid markdown
868
+ * @returns code block with language and content
869
+ */
870
+ function extractOneBlockFromMarkdown(markdown) {
871
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
872
+ if (codeBlocks.length !== 1) {
873
+ // TODO: Report more specific place where the error happened
874
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
875
+ }
876
+ return codeBlocks[0];
877
+ }
878
+ /***
879
+ * TODO: [🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
880
+ */
881
+
882
+ /**
883
+ * Removes Markdown formatting tags from a string.
884
+ *
885
+ * @param {string} str - The string to remove Markdown tags from.
886
+ * @returns {string} The input string with all Markdown tags removed.
887
+ */
888
+ function removeMarkdownFormatting(str) {
889
+ // Remove bold formatting
890
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
891
+ // Remove italic formatting
892
+ str = str.replace(/\*(.*?)\*/g, '$1');
893
+ // Remove code formatting
894
+ str = str.replace(/`(.*?)`/g, '$1');
895
+ return str;
896
+ }
897
+
1032
898
  /* tslint:disable */
1033
899
  /*
1034
900
  TODO: Tests
@@ -1079,79 +945,298 @@
1079
945
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1080
946
  finally {
1081
947
  try {
1082
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
948
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
949
+ }
950
+ finally { if (e_1) throw e_1.error; }
951
+ }
952
+ normalizedName = normalizedName.replace(/_+/g, '_');
953
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
954
+ normalizedName = normalizedName.replace(/^_/, '');
955
+ normalizedName = normalizedName.replace(/_$/, '');
956
+ return normalizedName;
957
+ }
958
+ /**
959
+ * TODO: [🌺] Use some intermediate util splitWords
960
+ */
961
+
962
+ /* tslint:disable */
963
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
964
+ var e_1, _a;
965
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
966
+ var charType;
967
+ var lastCharType = null;
968
+ var normalizedName = '';
969
+ try {
970
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
971
+ var char = sentence_1_1.value;
972
+ var normalizedChar = void 0;
973
+ if (/^[a-z]$/.test(char)) {
974
+ charType = 'LOWERCASE';
975
+ normalizedChar = char;
976
+ }
977
+ else if (/^[A-Z]$/.test(char)) {
978
+ charType = 'UPPERCASE';
979
+ normalizedChar = char.toLowerCase();
980
+ }
981
+ else if (/^[0-9]$/.test(char)) {
982
+ charType = 'NUMBER';
983
+ normalizedChar = char;
984
+ }
985
+ else {
986
+ charType = 'OTHER';
987
+ normalizedChar = '';
988
+ }
989
+ if (!lastCharType) {
990
+ if (__firstLetterCapital) {
991
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
992
+ }
993
+ }
994
+ else if (charType !== lastCharType &&
995
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
996
+ !(lastCharType === 'NUMBER') &&
997
+ !(charType === 'NUMBER')) {
998
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
999
+ }
1000
+ normalizedName += normalizedChar;
1001
+ lastCharType = charType;
1002
+ }
1003
+ }
1004
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1005
+ finally {
1006
+ try {
1007
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1008
+ }
1009
+ finally { if (e_1) throw e_1.error; }
1010
+ }
1011
+ return normalizedName;
1012
+ }
1013
+ /**
1014
+ * TODO: [🌺] Use some intermediate util splitWords
1015
+ */
1016
+
1017
+ function normalizeTo_PascalCase(sentence) {
1018
+ return normalizeTo_camelCase(sentence, true);
1019
+ }
1020
+
1021
+ /**
1022
+ * Supported script languages
1023
+ */
1024
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
1025
+
1026
+ /**
1027
+ * Parses the template and returns the list of all parameter names
1028
+ *
1029
+ * @param template the template with parameters in {curly} braces
1030
+ * @returns the list of parameter names
1031
+ *
1032
+ * @private within the library
1033
+ */
1034
+ function extractParameters(template) {
1035
+ var e_1, _a;
1036
+ var matches = template.matchAll(/{\w+}/g);
1037
+ var parameterNames = [];
1038
+ try {
1039
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
1040
+ var match = matches_1_1.value;
1041
+ var parameterName = match[0].slice(1, -1);
1042
+ if (!parameterNames.includes(parameterName)) {
1043
+ parameterNames.push(parameterName);
1044
+ }
1045
+ }
1046
+ }
1047
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1048
+ finally {
1049
+ try {
1050
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
1051
+ }
1052
+ finally { if (e_1) throw e_1.error; }
1053
+ }
1054
+ return parameterNames;
1055
+ }
1056
+
1057
+ /**
1058
+ * Computes the deepness of the markdown structure.
1059
+ *
1060
+ * @private within the library
1061
+ */
1062
+ function countMarkdownStructureDeepness(markdownStructure) {
1063
+ var e_1, _a;
1064
+ var maxDeepness = 0;
1065
+ try {
1066
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
1067
+ var section = _c.value;
1068
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
1069
+ }
1070
+ }
1071
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1072
+ finally {
1073
+ try {
1074
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1083
1075
  }
1084
1076
  finally { if (e_1) throw e_1.error; }
1085
1077
  }
1086
- normalizedName = normalizedName.replace(/_+/g, '_');
1087
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
1088
- normalizedName = normalizedName.replace(/^_/, '');
1089
- normalizedName = normalizedName.replace(/_$/, '');
1090
- return normalizedName;
1078
+ return maxDeepness + 1;
1091
1079
  }
1080
+
1092
1081
  /**
1093
- * TODO: [🌺] Use some intermediate util splitWords
1082
+ * Parse a markdown string into a MarkdownStructure object.
1083
+ *
1084
+ * Note: This function does work with code blocks
1085
+ * Note: This function does not work with markdown comments
1086
+ *
1087
+ * @param markdown The markdown string to parse.
1088
+ * @returns The MarkdownStructure object.
1089
+ *
1090
+ * @private within the library
1094
1091
  */
1095
-
1096
- /* tslint:disable */
1097
- function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1092
+ function markdownToMarkdownStructure(markdown) {
1098
1093
  var e_1, _a;
1099
- if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1100
- var charType;
1101
- var lastCharType = null;
1102
- var normalizedName = '';
1094
+ var lines = markdown.split('\n');
1095
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
1096
+ var current = root;
1097
+ var isInsideCodeBlock = false;
1103
1098
  try {
1104
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1105
- var char = sentence_1_1.value;
1106
- var normalizedChar = void 0;
1107
- if (/^[a-z]$/.test(char)) {
1108
- charType = 'LOWERCASE';
1109
- normalizedChar = char;
1110
- }
1111
- else if (/^[A-Z]$/.test(char)) {
1112
- charType = 'UPPERCASE';
1113
- normalizedChar = char.toLowerCase();
1114
- }
1115
- else if (/^[0-9]$/.test(char)) {
1116
- charType = 'NUMBER';
1117
- normalizedChar = char;
1099
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
1100
+ var line = lines_1_1.value;
1101
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
1102
+ if (isInsideCodeBlock || !headingMatch) {
1103
+ if (line.startsWith('```')) {
1104
+ isInsideCodeBlock = !isInsideCodeBlock;
1105
+ }
1106
+ current.contentLines.push(line);
1118
1107
  }
1119
1108
  else {
1120
- charType = 'OTHER';
1121
- normalizedChar = '';
1122
- }
1123
- if (!lastCharType) {
1124
- if (__firstLetterCapital) {
1125
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1109
+ var level = headingMatch.groups.mark.length;
1110
+ var title = headingMatch.groups.title.trim();
1111
+ var parent_1 = void 0;
1112
+ if (level > current.level) {
1113
+ // Note: Going deeper (next section is child of current)
1114
+ parent_1 = current;
1126
1115
  }
1116
+ else {
1117
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
1118
+ parent_1 = current;
1119
+ var loopLimit = LOOP_LIMIT;
1120
+ while (parent_1.level !== level - 1) {
1121
+ if (loopLimit-- < 0) {
1122
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
1123
+ }
1124
+ if (parent_1.parent === null /* <- Note: We are in root */) {
1125
+ // [🌻]
1126
+ throw new Error(spaceTrim__default["default"]("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
1127
+ }
1128
+ parent_1 = parent_1.parent;
1129
+ }
1130
+ }
1131
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
1132
+ parent_1.sections.push(section);
1133
+ current = section;
1127
1134
  }
1128
- else if (charType !== lastCharType &&
1129
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1130
- !(lastCharType === 'NUMBER') &&
1131
- !(charType === 'NUMBER')) {
1132
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1133
- }
1134
- normalizedName += normalizedChar;
1135
- lastCharType = charType;
1136
1135
  }
1137
1136
  }
1138
1137
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1139
1138
  finally {
1140
1139
  try {
1141
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1140
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
1142
1141
  }
1143
1142
  finally { if (e_1) throw e_1.error; }
1144
1143
  }
1145
- return normalizedName;
1144
+ if (root.sections.length === 1) {
1145
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
1146
+ return markdownStructure;
1147
+ }
1148
+ // [🌻]
1149
+ throw new Error('The markdown file must have exactly one top-level section.');
1150
+ // return root;
1146
1151
  }
1147
1152
  /**
1148
- * TODO: [🌺] Use some intermediate util splitWords
1153
+ * @private
1149
1154
  */
1155
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
1156
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
1157
+ return {
1158
+ level: level,
1159
+ title: title,
1160
+ content: spaceTrim__default["default"](contentLines.join('\n')),
1161
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
1162
+ };
1163
+ }
1150
1164
 
1151
- function normalizeTo_PascalCase(sentence) {
1152
- return normalizeTo_camelCase(sentence, true);
1165
+ /**
1166
+ * The version of the Promptbook library
1167
+ */
1168
+ var PROMPTBOOK_VERSION = '0.44.0-9';
1169
+
1170
+ /**
1171
+ * Parses the given script and returns the list of all used variables that are not defined in the script
1172
+ *
1173
+ * @param script from which to extract the variables
1174
+ * @returns the list of variable names
1175
+ * @throws {PromptbookSyntaxError} if the script is invalid
1176
+ *
1177
+ * @private within the promptbookStringToJson
1178
+ */
1179
+ function extractVariables(script) {
1180
+ var variables = [];
1181
+ script = "(()=>{".concat(script, "})()");
1182
+ try {
1183
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
1184
+ try {
1185
+ eval(script);
1186
+ }
1187
+ catch (error) {
1188
+ if (!(error instanceof ReferenceError)) {
1189
+ throw error;
1190
+ }
1191
+ var undefinedName = error.message.split(' ')[0];
1192
+ /*
1193
+ Note: Remapping error
1194
+ From: [ReferenceError: thing is not defined],
1195
+ To: [Error: Parameter {thing} is not defined],
1196
+ */
1197
+ if (!undefinedName) {
1198
+ throw error;
1199
+ }
1200
+ if (script.includes(undefinedName + '(')) {
1201
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
1202
+ }
1203
+ else {
1204
+ variables.push(undefinedName);
1205
+ script = "const ".concat(undefinedName, " = '';") + script;
1206
+ }
1207
+ }
1208
+ }
1209
+ catch (error) {
1210
+ if (!(error instanceof Error)) {
1211
+ throw error;
1212
+ }
1213
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
1214
+ }
1215
+ return variables;
1153
1216
  }
1154
1217
 
1218
+ /**
1219
+ * Execution type describes the way how the block is executed
1220
+ *
1221
+ * @see https://github.com/webgptorg/promptbook#execution-type
1222
+ */
1223
+ var ExecutionTypes = [
1224
+ 'PROMPT_TEMPLATE',
1225
+ 'SIMPLE_TEMPLATE',
1226
+ 'SCRIPT',
1227
+ 'PROMPT_DIALOG',
1228
+ // <- [🥻] Insert here when making new command
1229
+ ];
1230
+
1231
+ /**
1232
+ * Units of text measurement
1233
+ */
1234
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
1235
+ /**
1236
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
1237
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
1238
+ */
1239
+
1155
1240
  /**
1156
1241
  * Parses one line of ul/ol to command
1157
1242
  *
@@ -1645,7 +1730,7 @@
1645
1730
  executionType: executionType,
1646
1731
  jokers: jokers,
1647
1732
  postprocessing: postprocessing,
1648
- expectAmount: expectAmount,
1733
+ expectations: expectAmount,
1649
1734
  expectFormat: expectFormat,
1650
1735
  modelRequirements: templateModelRequirements,
1651
1736
  contentLanguage: executionType === 'SCRIPT' ? language : undefined,
@@ -1787,7 +1872,7 @@
1787
1872
  }
1788
1873
  if (template.jokers && template.jokers.length > 0) {
1789
1874
  if (!template.expectFormat &&
1790
- !template.expectAmount /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1875
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1791
1876
  throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
1792
1877
  }
1793
1878
  try {
@@ -1806,9 +1891,9 @@
1806
1891
  finally { if (e_3) throw e_3.error; }
1807
1892
  }
1808
1893
  }
1809
- if (template.expectAmount) {
1894
+ if (template.expectations) {
1810
1895
  try {
1811
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectAmount))), _m = _l.next(); !_m.done; _m = _l.next()) {
1896
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1812
1897
  var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1813
1898
  if (min !== undefined && max !== undefined && min > max) {
1814
1899
  throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
@@ -1889,22 +1974,6 @@
1889
1974
  * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
1890
1975
  */
1891
1976
 
1892
- /**
1893
- * This error occurs when some expectation is not met in the execution of the pipeline
1894
- *
1895
- * Note: This is a kindof subtype of PromptbookExecutionError
1896
- */
1897
- var ExpectError = /** @class */ (function (_super) {
1898
- __extends(ExpectError, _super);
1899
- function ExpectError(message) {
1900
- var _this = _super.call(this, message) || this;
1901
- _this.name = 'ExpectError';
1902
- Object.setPrototypeOf(_this, ExpectError.prototype);
1903
- return _this;
1904
- }
1905
- return ExpectError;
1906
- }(Error));
1907
-
1908
1977
  /**
1909
1978
  * Creates executor function from promptbook and execution tools.
1910
1979
  *
@@ -1919,10 +1988,10 @@
1919
1988
  var promptbookExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1920
1989
  function executeSingleTemplate(currentTemplate) {
1921
1990
  return __awaiter(this, void 0, void 0, function () {
1922
- var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, _j, _k, _l, unit, _m, max, min, amount, error_4;
1923
- var e_2, _o, e_4, _p, e_3, _q, e_5, _r, _s;
1924
- return __generator(this, function (_t) {
1925
- switch (_t.label) {
1991
+ var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, error_4;
1992
+ var e_2, _j, e_4, _k, e_3, _l, _m;
1993
+ return __generator(this, function (_o) {
1994
+ switch (_o.label) {
1926
1995
  case 0:
1927
1996
  name = "promptbook-executor-frame-".concat(currentTemplate.name);
1928
1997
  title = currentTemplate.title;
@@ -1939,8 +2008,8 @@
1939
2008
  // <- [3]
1940
2009
  })];
1941
2010
  case 1:
1942
- _t.sent();
1943
- _t.label = 2;
2011
+ _o.sent();
2012
+ _o.label = 2;
1944
2013
  case 2:
1945
2014
  result = null;
1946
2015
  resultString = null;
@@ -1948,7 +2017,7 @@
1948
2017
  maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1949
2018
  jokers = currentTemplate.jokers || [];
1950
2019
  attempt = -jokers.length;
1951
- _t.label = 3;
2020
+ _o.label = 3;
1952
2021
  case 3:
1953
2022
  if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1954
2023
  isJokerAttempt = attempt < 0;
@@ -1965,9 +2034,9 @@
1965
2034
  }
1966
2035
  resultString = parametersToPass[joker];
1967
2036
  }
1968
- _t.label = 4;
2037
+ _o.label = 4;
1969
2038
  case 4:
1970
- _t.trys.push([4, 45, 46, 47]);
2039
+ _o.trys.push([4, 45, 46, 47]);
1971
2040
  if (!!isJokerAttempt) return [3 /*break*/, 27];
1972
2041
  _a = currentTemplate.executionType;
1973
2042
  switch (_a) {
@@ -1989,6 +2058,7 @@
1989
2058
  parameters: parametersToPass,
1990
2059
  content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1991
2060
  modelRequirements: currentTemplate.modelRequirements,
2061
+ expectations: currentTemplate.expectations,
1992
2062
  };
1993
2063
  _b = currentTemplate.modelRequirements.modelVariant;
1994
2064
  switch (_b) {
@@ -1998,14 +2068,14 @@
1998
2068
  return [3 /*break*/, 11];
1999
2069
  case 7: return [4 /*yield*/, tools.natural.gptChat(prompt)];
2000
2070
  case 8:
2001
- chatThread = _t.sent();
2071
+ chatThread = _o.sent();
2002
2072
  // TODO: [🍬] Destroy chatThread
2003
2073
  result = chatThread;
2004
2074
  resultString = chatThread.content;
2005
2075
  return [3 /*break*/, 12];
2006
2076
  case 9: return [4 /*yield*/, tools.natural.gptComplete(prompt)];
2007
2077
  case 10:
2008
- completionResult = _t.sent();
2078
+ completionResult = _o.sent();
2009
2079
  result = completionResult;
2010
2080
  resultString = completionResult.content;
2011
2081
  return [3 /*break*/, 12];
@@ -2020,27 +2090,27 @@
2020
2090
  }
2021
2091
  // TODO: DRY [1]
2022
2092
  scriptExecutionErrors = [];
2023
- _t.label = 14;
2093
+ _o.label = 14;
2024
2094
  case 14:
2025
- _t.trys.push([14, 21, 22, 23]);
2095
+ _o.trys.push([14, 21, 22, 23]);
2026
2096
  _c = (e_2 = void 0, __values(tools.script)), _d = _c.next();
2027
- _t.label = 15;
2097
+ _o.label = 15;
2028
2098
  case 15:
2029
2099
  if (!!_d.done) return [3 /*break*/, 20];
2030
2100
  scriptTools = _d.value;
2031
- _t.label = 16;
2101
+ _o.label = 16;
2032
2102
  case 16:
2033
- _t.trys.push([16, 18, , 19]);
2103
+ _o.trys.push([16, 18, , 19]);
2034
2104
  return [4 /*yield*/, scriptTools.execute({
2035
2105
  scriptLanguage: currentTemplate.contentLanguage,
2036
2106
  script: currentTemplate.content,
2037
2107
  parameters: parametersToPass,
2038
2108
  })];
2039
2109
  case 17:
2040
- resultString = _t.sent();
2110
+ resultString = _o.sent();
2041
2111
  return [3 /*break*/, 20];
2042
2112
  case 18:
2043
- error_2 = _t.sent();
2113
+ error_2 = _o.sent();
2044
2114
  if (!(error_2 instanceof Error)) {
2045
2115
  throw error_2;
2046
2116
  }
@@ -2051,12 +2121,12 @@
2051
2121
  return [3 /*break*/, 15];
2052
2122
  case 20: return [3 /*break*/, 23];
2053
2123
  case 21:
2054
- e_2_1 = _t.sent();
2124
+ e_2_1 = _o.sent();
2055
2125
  e_2 = { error: e_2_1 };
2056
2126
  return [3 /*break*/, 23];
2057
2127
  case 22:
2058
2128
  try {
2059
- if (_d && !_d.done && (_o = _c.return)) _o.call(_c);
2129
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
2060
2130
  }
2061
2131
  finally { if (e_2) throw e_2.error; }
2062
2132
  return [7 /*endfinally*/];
@@ -2082,46 +2152,46 @@
2082
2152
  })];
2083
2153
  case 25:
2084
2154
  // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
2085
- resultString = _t.sent();
2155
+ resultString = _o.sent();
2086
2156
  return [3 /*break*/, 27];
2087
2157
  case 26: throw new PromptbookExecutionError(
2088
2158
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
2089
2159
  "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
2090
2160
  case 27:
2091
2161
  if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
2092
- _t.label = 28;
2162
+ _o.label = 28;
2093
2163
  case 28:
2094
- _t.trys.push([28, 42, 43, 44]);
2164
+ _o.trys.push([28, 42, 43, 44]);
2095
2165
  _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
2096
- _t.label = 29;
2166
+ _o.label = 29;
2097
2167
  case 29:
2098
2168
  if (!!_f.done) return [3 /*break*/, 41];
2099
2169
  functionName = _f.value;
2100
2170
  // TODO: DRY [1]
2101
2171
  scriptExecutionErrors = [];
2102
2172
  postprocessingError = null;
2103
- _t.label = 30;
2173
+ _o.label = 30;
2104
2174
  case 30:
2105
- _t.trys.push([30, 37, 38, 39]);
2175
+ _o.trys.push([30, 37, 38, 39]);
2106
2176
  _g = (e_3 = void 0, __values(tools.script)), _h = _g.next();
2107
- _t.label = 31;
2177
+ _o.label = 31;
2108
2178
  case 31:
2109
2179
  if (!!_h.done) return [3 /*break*/, 36];
2110
2180
  scriptTools = _h.value;
2111
- _t.label = 32;
2181
+ _o.label = 32;
2112
2182
  case 32:
2113
- _t.trys.push([32, 34, , 35]);
2183
+ _o.trys.push([32, 34, , 35]);
2114
2184
  return [4 /*yield*/, scriptTools.execute({
2115
2185
  scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
2116
2186
  script: "".concat(functionName, "(resultString)"),
2117
2187
  parameters: __assign(__assign({}, parametersToPass), { resultString: resultString || '' }),
2118
2188
  })];
2119
2189
  case 33:
2120
- resultString = _t.sent();
2190
+ resultString = _o.sent();
2121
2191
  postprocessingError = null;
2122
2192
  return [3 /*break*/, 36];
2123
2193
  case 34:
2124
- error_3 = _t.sent();
2194
+ error_3 = _o.sent();
2125
2195
  if (!(error_3 instanceof Error)) {
2126
2196
  throw error_3;
2127
2197
  }
@@ -2133,12 +2203,12 @@
2133
2203
  return [3 /*break*/, 31];
2134
2204
  case 36: return [3 /*break*/, 39];
2135
2205
  case 37:
2136
- e_3_1 = _t.sent();
2206
+ e_3_1 = _o.sent();
2137
2207
  e_3 = { error: e_3_1 };
2138
2208
  return [3 /*break*/, 39];
2139
2209
  case 38:
2140
2210
  try {
2141
- if (_h && !_h.done && (_q = _g.return)) _q.call(_g);
2211
+ if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
2142
2212
  }
2143
2213
  finally { if (e_3) throw e_3.error; }
2144
2214
  return [7 /*endfinally*/];
@@ -2146,22 +2216,23 @@
2146
2216
  if (postprocessingError) {
2147
2217
  throw postprocessingError;
2148
2218
  }
2149
- _t.label = 40;
2219
+ _o.label = 40;
2150
2220
  case 40:
2151
2221
  _f = _e.next();
2152
2222
  return [3 /*break*/, 29];
2153
2223
  case 41: return [3 /*break*/, 44];
2154
2224
  case 42:
2155
- e_4_1 = _t.sent();
2225
+ e_4_1 = _o.sent();
2156
2226
  e_4 = { error: e_4_1 };
2157
2227
  return [3 /*break*/, 44];
2158
2228
  case 43:
2159
2229
  try {
2160
- if (_f && !_f.done && (_p = _e.return)) _p.call(_e);
2230
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
2161
2231
  }
2162
2232
  finally { if (e_4) throw e_4.error; }
2163
2233
  return [7 /*endfinally*/];
2164
2234
  case 44:
2235
+ // TODO: [💝] Unite object for expecting amount and format
2165
2236
  if (currentTemplate.expectFormat) {
2166
2237
  if (currentTemplate.expectFormat === 'JSON') {
2167
2238
  if (!isValidJsonString(resultString || '')) {
@@ -2169,30 +2240,13 @@
2169
2240
  }
2170
2241
  }
2171
2242
  }
2172
- if (currentTemplate.expectAmount) {
2173
- try {
2174
- for (_j = (e_5 = void 0, __values(Object.entries(currentTemplate.expectAmount))), _k = _j.next(); !_k.done; _k = _j.next()) {
2175
- _l = __read(_k.value, 2), unit = _l[0], _m = _l[1], max = _m.max, min = _m.min;
2176
- amount = CountUtils[unit.toUpperCase()](resultString || '');
2177
- if (min && amount < min) {
2178
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
2179
- } /* not else */
2180
- if (max && amount > max) {
2181
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
2182
- }
2183
- }
2184
- }
2185
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
2186
- finally {
2187
- try {
2188
- if (_k && !_k.done && (_r = _j.return)) _r.call(_j);
2189
- }
2190
- finally { if (e_5) throw e_5.error; }
2191
- }
2243
+ // TODO: [💝] Unite object for expecting amount and format
2244
+ if (currentTemplate.expectations) {
2245
+ checkExpectations(currentTemplate.expectations, resultString || '');
2192
2246
  }
2193
2247
  return [3 /*break*/, 49];
2194
2248
  case 45:
2195
- error_4 = _t.sent();
2249
+ error_4 = _o.sent();
2196
2250
  if (!(error_4 instanceof ExpectError)) {
2197
2251
  throw error_4;
2198
2252
  }
@@ -2211,6 +2265,7 @@
2211
2265
  title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
2212
2266
  content: prompt.content,
2213
2267
  modelRequirements: prompt.modelRequirements,
2268
+ expectations: prompt.expectations,
2214
2269
  // <- Note: Do want to pass ONLY wanted information to the report
2215
2270
  },
2216
2271
  result: result || undefined,
@@ -2220,9 +2275,9 @@
2220
2275
  return [7 /*endfinally*/];
2221
2276
  case 47:
2222
2277
  if (expectError !== null && attempt === maxAttempts - 1) {
2223
- throw new PromptbookExecutionError(spaceTrim__default["default"](function (block) { return "\n Natural execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n "); }));
2278
+ throw new PromptbookExecutionError(spaceTrim__default["default"](function (block) { return "\n Natural execution failed ".concat(maxExecutionAttempts, "x\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n\n Last result:\n ").concat(resultString, "\n "); }));
2224
2279
  }
2225
- _t.label = 48;
2280
+ _o.label = 48;
2226
2281
  case 48:
2227
2282
  attempt++;
2228
2283
  return [3 /*break*/, 3];
@@ -2242,7 +2297,7 @@
2242
2297
  // <- [3]
2243
2298
  });
2244
2299
  }
2245
- parametersToPass = __assign(__assign({}, parametersToPass), (_s = {}, _s[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _s));
2300
+ parametersToPass = __assign(__assign({}, parametersToPass), (_m = {}, _m[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _m));
2246
2301
  return [2 /*return*/];
2247
2302
  }
2248
2303
  });
@@ -2446,8 +2501,94 @@
2446
2501
  return MockedEchoNaturalExecutionTools;
2447
2502
  }());
2448
2503
  /**
2449
- * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}
2504
+ * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}, same as replace params
2505
+ */
2506
+
2507
+ /**
2508
+ * Gets the expectations and creates a fake text that meets the expectations
2509
+ *
2510
+ * @private internal util for MockedFackedNaturalExecutionTools
2511
+ */
2512
+ function $fakeTextToExpectations(expectations) {
2513
+ var lorem = new loremIpsum.LoremIpsum({
2514
+ wordsPerSentence: { min: 5, max: 15 },
2515
+ sentencesPerParagraph: { min: 5, max: 15 },
2516
+ });
2517
+ var loremText = '';
2518
+ var text = '';
2519
+ for (var loopLimit = CHARACTER_LOOP_LIMIT; loopLimit-- > 0;) {
2520
+ if (isPassingExpectations(expectations, text)) {
2521
+ return text;
2522
+ }
2523
+ if (loremText === '') {
2524
+ loremText = lorem.generateParagraphs(1) + '\n\n';
2525
+ }
2526
+ text += loremText.substring(0, 1);
2527
+ loremText = loremText.substring(1);
2528
+ }
2529
+ throw new Error(spaceTrim__default["default"](function (block) { return "\n Can not generate fake text to met the expectations\n\n Loop limit reached\n The expectations:\n ".concat(block(JSON.stringify(expectations, null, 4)), "\n\n The draft text:\n ").concat(block(text), "\n\n "); }));
2530
+ }
2531
+ /**
2532
+ * TODO: Implement better
2533
+ * TODO: [💝] Unite object for expecting amount and format - use here also a format
2534
+ */
2535
+
2536
+ /**
2537
+ * Mocked execution Tools for just faking expected responses for testing purposes
2450
2538
  */
2539
+ var MockedFackedNaturalExecutionTools = /** @class */ (function () {
2540
+ function MockedFackedNaturalExecutionTools(options) {
2541
+ this.options = options;
2542
+ }
2543
+ /**
2544
+ * Fakes chat model
2545
+ */
2546
+ MockedFackedNaturalExecutionTools.prototype.gptChat = function (prompt) {
2547
+ return __awaiter(this, void 0, void 0, function () {
2548
+ var content, result;
2549
+ return __generator(this, function (_a) {
2550
+ if (this.options.isVerbose) {
2551
+ console.info('💬 Mocked faked prompt', prompt);
2552
+ }
2553
+ content = $fakeTextToExpectations(prompt.expectations || {
2554
+ sentences: { min: 1, max: 1 },
2555
+ });
2556
+ result = {
2557
+ content: content,
2558
+ model: 'mocked-facked',
2559
+ timing: {
2560
+ start: getCurrentIsoDate(),
2561
+ complete: getCurrentIsoDate(),
2562
+ },
2563
+ usage: {
2564
+ price: 0,
2565
+ inputTokens: 0,
2566
+ outputTokens: 0,
2567
+ },
2568
+ rawResponse: {
2569
+ note: 'This is mocked echo',
2570
+ },
2571
+ // <- [🤹‍♂️]
2572
+ };
2573
+ if (this.options.isVerbose) {
2574
+ console.info('💬 Mocked faked result', result);
2575
+ }
2576
+ return [2 /*return*/, result];
2577
+ });
2578
+ });
2579
+ };
2580
+ /**
2581
+ * Fakes completion model
2582
+ */
2583
+ MockedFackedNaturalExecutionTools.prototype.gptComplete = function (prompt) {
2584
+ return __awaiter(this, void 0, void 0, function () {
2585
+ return __generator(this, function (_a) {
2586
+ return [2 /*return*/, this.gptChat(prompt)];
2587
+ });
2588
+ });
2589
+ };
2590
+ return MockedFackedNaturalExecutionTools;
2591
+ }());
2451
2592
 
2452
2593
  /**
2453
2594
  * Delagates the user interaction to a async callback function
@@ -2511,17 +2652,17 @@
2511
2652
  }());
2512
2653
 
2513
2654
  /**
2514
- * This error indicates that the requested resource (for example promptbook in the library ) was not found
2655
+ * This error indicates that promptbook not found in the library
2515
2656
  */
2516
- var NotFoundError = /** @class */ (function (_super) {
2517
- __extends(NotFoundError, _super);
2518
- function NotFoundError(message) {
2657
+ var PromptbookNotFoundError = /** @class */ (function (_super) {
2658
+ __extends(PromptbookNotFoundError, _super);
2659
+ function PromptbookNotFoundError(message) {
2519
2660
  var _this = _super.call(this, message) || this;
2520
- _this.name = 'NotFoundError';
2521
- Object.setPrototypeOf(_this, NotFoundError.prototype);
2661
+ _this.name = 'PromptbookNotFoundError';
2662
+ Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
2522
2663
  return _this;
2523
2664
  }
2524
- return NotFoundError;
2665
+ return PromptbookNotFoundError;
2525
2666
  }(Error));
2526
2667
 
2527
2668
  /**
@@ -2592,7 +2733,7 @@
2592
2733
  var _this = this;
2593
2734
  var promptbook = this.library.get(url);
2594
2735
  if (!promptbook) {
2595
- throw new NotFoundError(spaceTrim__default["default"](function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2736
+ throw new PromptbookNotFoundError(spaceTrim__default["default"](function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2596
2737
  .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2597
2738
  .join('\n')), "\n\n "); }));
2598
2739
  }
@@ -2742,7 +2883,7 @@
2742
2883
  switch (_b.label) {
2743
2884
  case 0:
2744
2885
  if (!!predicate(url)) return [3 /*break*/, 2];
2745
- _a = NotFoundError.bind;
2886
+ _a = PromptbookNotFoundError.bind;
2746
2887
  return [4 /*yield*/, spaceTrim__default["default"](function (block) { return __awaiter(_this, void 0, void 0, function () {
2747
2888
  var _a, _b, _c, _d, _e, _f;
2748
2889
  return __generator(this, function (_g) {
@@ -2759,7 +2900,7 @@
2759
2900
  }
2760
2901
  });
2761
2902
  }); })];
2762
- case 1: throw new (_a.apply(NotFoundError, [void 0, _b.sent()]))();
2903
+ case 1: throw new (_a.apply(PromptbookNotFoundError, [void 0, _b.sent()]))();
2763
2904
  case 2: return [4 /*yield*/, library.getPromptbookByUrl(url)];
2764
2905
  case 3:
2765
2906
  promptbook = _b.sent();
@@ -2795,6 +2936,7 @@
2795
2936
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
2796
2937
  exports.ExecutionTypes = ExecutionTypes;
2797
2938
  exports.MockedEchoNaturalExecutionTools = MockedEchoNaturalExecutionTools;
2939
+ exports.MockedFackedNaturalExecutionTools = MockedFackedNaturalExecutionTools;
2798
2940
  exports.PROMPTBOOK_VERSION = PROMPTBOOK_VERSION;
2799
2941
  exports.SimplePromptInterfaceTools = SimplePromptInterfaceTools;
2800
2942
  exports.SimplePromptbookLibrary = SimplePromptbookLibrary;