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