@promptbook/core 0.44.0-1 โ†’ 0.44.0-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.es.js CHANGED
@@ -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.
@@ -122,85 +123,6 @@ function __spreadArray(to, from, pack) {
122
123
  return to.concat(ar || Array.prototype.slice.call(from));
123
124
  }
124
125
 
125
- /**
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
126
  /**
205
127
  * This error type indicates that the error should not happen and its last check before crashing with some other error
206
128
  */
@@ -215,218 +137,6 @@ var UnexpectedError = /** @class */ (function (_super) {
215
137
  return UnexpectedError;
216
138
  }(Error));
217
139
 
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
140
  /**
431
141
  * Removes HTML or Markdown comments from a string.
432
142
  *
@@ -438,94 +148,18 @@ function removeContentComments(content) {
438
148
  }
439
149
 
440
150
  /**
441
- * The version of the Promptbook library
442
- */
443
- var PROMPTBOOK_VERSION = '0.44.0-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 "); }));
489
- }
490
- return variables;
491
- }
492
-
493
- /**
494
- * Execution type describes the way how the block is executed
495
- *
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
512
- */
513
-
514
- /**
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
@@ -608,6 +242,11 @@ var PromptbookExecutionError = /** @class */ (function (_super) {
608
242
  return PromptbookExecutionError;
609
243
  }(Error));
610
244
 
245
+ /**
246
+ * The maximum number of iterations for a loops
247
+ */
248
+ var LOOP_LIMIT = 1000;
249
+
611
250
  /**
612
251
  * This error occurs during the parameter replacement in the template
613
252
  *
@@ -1030,6 +669,150 @@ function isValidJsonString(value) {
1030
669
  }
1031
670
  }
1032
671
 
672
+ /**
673
+ * Makes first letter of a string uppercase
674
+ *
675
+ */
676
+ function capitalize(word) {
677
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
678
+ }
679
+
680
+ /**
681
+ * Extracts all code blocks from markdown.
682
+ *
683
+ * Note: There are 3 simmilar function:
684
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
685
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
686
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
687
+ *
688
+ * @param markdown any valid markdown
689
+ * @returns code blocks with language and content
690
+ *
691
+ */
692
+ function extractAllBlocksFromMarkdown(markdown) {
693
+ var e_1, _a;
694
+ var codeBlocks = [];
695
+ var lines = markdown.split('\n');
696
+ var currentCodeBlock = null;
697
+ try {
698
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
699
+ var line = lines_1_1.value;
700
+ if (line.startsWith('```')) {
701
+ var language = line.slice(3).trim() || null;
702
+ if (currentCodeBlock === null) {
703
+ currentCodeBlock = { language: language, content: '' };
704
+ }
705
+ else {
706
+ if (language !== null) {
707
+ // [๐ŸŒป]
708
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
709
+ }
710
+ codeBlocks.push(currentCodeBlock);
711
+ currentCodeBlock = null;
712
+ }
713
+ }
714
+ else if (currentCodeBlock !== null) {
715
+ if (currentCodeBlock.content !== '') {
716
+ currentCodeBlock.content += '\n';
717
+ }
718
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
719
+ }
720
+ }
721
+ }
722
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
723
+ finally {
724
+ try {
725
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
726
+ }
727
+ finally { if (e_1) throw e_1.error; }
728
+ }
729
+ if (currentCodeBlock !== null) {
730
+ // [๐ŸŒป]
731
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
732
+ }
733
+ return codeBlocks;
734
+ }
735
+
736
+ /**
737
+ * Utility function to extract all list items from markdown
738
+ *
739
+ * Note: It works with both ul and ol
740
+ * Note: It omits list items in code blocks
741
+ * Note: It flattens nested lists
742
+ * Note: It can not work with html syntax and comments
743
+ *
744
+ * @param markdown any valid markdown
745
+ * @returns
746
+ */
747
+ function extractAllListItemsFromMarkdown(markdown) {
748
+ var e_1, _a;
749
+ var lines = markdown.split('\n');
750
+ var listItems = [];
751
+ var isInCodeBlock = false;
752
+ try {
753
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
754
+ var line = lines_1_1.value;
755
+ var trimmedLine = line.trim();
756
+ if (trimmedLine.startsWith('```')) {
757
+ isInCodeBlock = !isInCodeBlock;
758
+ }
759
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
760
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
761
+ listItems.push(listItem);
762
+ }
763
+ }
764
+ }
765
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
766
+ finally {
767
+ try {
768
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
769
+ }
770
+ finally { if (e_1) throw e_1.error; }
771
+ }
772
+ return listItems;
773
+ }
774
+
775
+ /**
776
+ * Extracts exactly ONE code block from markdown.
777
+ *
778
+ * Note: If there are multiple or no code blocks the function throws an error
779
+ *
780
+ * Note: There are 3 simmilar function:
781
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
782
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
783
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
784
+ *
785
+ * @param markdown any valid markdown
786
+ * @returns code block with language and content
787
+ */
788
+ function extractOneBlockFromMarkdown(markdown) {
789
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
790
+ if (codeBlocks.length !== 1) {
791
+ // TODO: Report more specific place where the error happened
792
+ throw new Error(/* <- [๐ŸŒป] */ 'There should be exactly one code block in the markdown');
793
+ }
794
+ return codeBlocks[0];
795
+ }
796
+ /***
797
+ * TODO: [๐ŸŒป] !!! Decide of this is internal util, external util OR validator/postprocessor
798
+ */
799
+
800
+ /**
801
+ * Removes Markdown formatting tags from a string.
802
+ *
803
+ * @param {string} str - The string to remove Markdown tags from.
804
+ * @returns {string} The input string with all Markdown tags removed.
805
+ */
806
+ function removeMarkdownFormatting(str) {
807
+ // Remove bold formatting
808
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
809
+ // Remove italic formatting
810
+ str = str.replace(/\*(.*?)\*/g, '$1');
811
+ // Remove code formatting
812
+ str = str.replace(/`(.*?)`/g, '$1');
813
+ return str;
814
+ }
815
+
1033
816
  /* tslint:disable */
1034
817
  /*
1035
818
  TODO: Tests
@@ -1073,86 +856,304 @@ function normalizeTo_SCREAMING_CASE(sentence) {
1073
856
  !(charType === 'NUMBER')) {
1074
857
  normalizedName += '_';
1075
858
  }
1076
- normalizedName += normalizedChar;
1077
- lastCharType = charType;
859
+ normalizedName += normalizedChar;
860
+ lastCharType = charType;
861
+ }
862
+ }
863
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
864
+ finally {
865
+ try {
866
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
867
+ }
868
+ finally { if (e_1) throw e_1.error; }
869
+ }
870
+ normalizedName = normalizedName.replace(/_+/g, '_');
871
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
872
+ normalizedName = normalizedName.replace(/^_/, '');
873
+ normalizedName = normalizedName.replace(/_$/, '');
874
+ return normalizedName;
875
+ }
876
+ /**
877
+ * TODO: [๐ŸŒบ] Use some intermediate util splitWords
878
+ */
879
+
880
+ /* tslint:disable */
881
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
882
+ var e_1, _a;
883
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
884
+ var charType;
885
+ var lastCharType = null;
886
+ var normalizedName = '';
887
+ try {
888
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
889
+ var char = sentence_1_1.value;
890
+ var normalizedChar = void 0;
891
+ if (/^[a-z]$/.test(char)) {
892
+ charType = 'LOWERCASE';
893
+ normalizedChar = char;
894
+ }
895
+ else if (/^[A-Z]$/.test(char)) {
896
+ charType = 'UPPERCASE';
897
+ normalizedChar = char.toLowerCase();
898
+ }
899
+ else if (/^[0-9]$/.test(char)) {
900
+ charType = 'NUMBER';
901
+ normalizedChar = char;
902
+ }
903
+ else {
904
+ charType = 'OTHER';
905
+ normalizedChar = '';
906
+ }
907
+ if (!lastCharType) {
908
+ if (__firstLetterCapital) {
909
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
910
+ }
911
+ }
912
+ else if (charType !== lastCharType &&
913
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
914
+ !(lastCharType === 'NUMBER') &&
915
+ !(charType === 'NUMBER')) {
916
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [๐ŸŒบ] DRY
917
+ }
918
+ normalizedName += normalizedChar;
919
+ lastCharType = charType;
920
+ }
921
+ }
922
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
923
+ finally {
924
+ try {
925
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
926
+ }
927
+ finally { if (e_1) throw e_1.error; }
928
+ }
929
+ return normalizedName;
930
+ }
931
+ /**
932
+ * TODO: [๐ŸŒบ] Use some intermediate util splitWords
933
+ */
934
+
935
+ function normalizeTo_PascalCase(sentence) {
936
+ return normalizeTo_camelCase(sentence, true);
937
+ }
938
+
939
+ /**
940
+ * Supported script languages
941
+ */
942
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
943
+
944
+ /**
945
+ * Parses the template and returns the list of all parameter names
946
+ *
947
+ * @param template the template with parameters in {curly} braces
948
+ * @returns the list of parameter names
949
+ *
950
+ * @private within the library
951
+ */
952
+ function extractParameters(template) {
953
+ var e_1, _a;
954
+ var matches = template.matchAll(/{\w+}/g);
955
+ var parameterNames = [];
956
+ try {
957
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
958
+ var match = matches_1_1.value;
959
+ var parameterName = match[0].slice(1, -1);
960
+ if (!parameterNames.includes(parameterName)) {
961
+ parameterNames.push(parameterName);
962
+ }
1078
963
  }
1079
964
  }
1080
965
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1081
966
  finally {
1082
967
  try {
1083
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
968
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
1084
969
  }
1085
970
  finally { if (e_1) throw e_1.error; }
1086
971
  }
1087
- normalizedName = normalizedName.replace(/_+/g, '_');
1088
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
1089
- normalizedName = normalizedName.replace(/^_/, '');
1090
- normalizedName = normalizedName.replace(/_$/, '');
1091
- return normalizedName;
972
+ return parameterNames;
1092
973
  }
974
+
1093
975
  /**
1094
- * TODO: [๐ŸŒบ] Use some intermediate util splitWords
976
+ * Computes the deepness of the markdown structure.
977
+ *
978
+ * @private within the library
1095
979
  */
980
+ function countMarkdownStructureDeepness(markdownStructure) {
981
+ var e_1, _a;
982
+ var maxDeepness = 0;
983
+ try {
984
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
985
+ var section = _c.value;
986
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
987
+ }
988
+ }
989
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
990
+ finally {
991
+ try {
992
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
993
+ }
994
+ finally { if (e_1) throw e_1.error; }
995
+ }
996
+ return maxDeepness + 1;
997
+ }
1096
998
 
1097
- /* tslint:disable */
1098
- function normalizeTo_camelCase(sentence, __firstLetterCapital) {
999
+ /**
1000
+ * Parse a markdown string into a MarkdownStructure object.
1001
+ *
1002
+ * Note: This function does work with code blocks
1003
+ * Note: This function does not work with markdown comments
1004
+ *
1005
+ * @param markdown The markdown string to parse.
1006
+ * @returns The MarkdownStructure object.
1007
+ *
1008
+ * @private within the library
1009
+ */
1010
+ function markdownToMarkdownStructure(markdown) {
1099
1011
  var e_1, _a;
1100
- if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1101
- var charType;
1102
- var lastCharType = null;
1103
- var normalizedName = '';
1012
+ var lines = markdown.split('\n');
1013
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
1014
+ var current = root;
1015
+ var isInsideCodeBlock = false;
1104
1016
  try {
1105
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1106
- var char = sentence_1_1.value;
1107
- var normalizedChar = void 0;
1108
- if (/^[a-z]$/.test(char)) {
1109
- charType = 'LOWERCASE';
1110
- normalizedChar = char;
1111
- }
1112
- else if (/^[A-Z]$/.test(char)) {
1113
- charType = 'UPPERCASE';
1114
- normalizedChar = char.toLowerCase();
1115
- }
1116
- else if (/^[0-9]$/.test(char)) {
1117
- charType = 'NUMBER';
1118
- normalizedChar = char;
1017
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
1018
+ var line = lines_1_1.value;
1019
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
1020
+ if (isInsideCodeBlock || !headingMatch) {
1021
+ if (line.startsWith('```')) {
1022
+ isInsideCodeBlock = !isInsideCodeBlock;
1023
+ }
1024
+ current.contentLines.push(line);
1119
1025
  }
1120
1026
  else {
1121
- charType = 'OTHER';
1122
- normalizedChar = '';
1123
- }
1124
- if (!lastCharType) {
1125
- if (__firstLetterCapital) {
1126
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1027
+ var level = headingMatch.groups.mark.length;
1028
+ var title = headingMatch.groups.title.trim();
1029
+ var parent_1 = void 0;
1030
+ if (level > current.level) {
1031
+ // Note: Going deeper (next section is child of current)
1032
+ parent_1 = current;
1127
1033
  }
1034
+ else {
1035
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
1036
+ parent_1 = current;
1037
+ var loopLimit = LOOP_LIMIT;
1038
+ while (parent_1.level !== level - 1) {
1039
+ if (loopLimit-- < 0) {
1040
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
1041
+ }
1042
+ if (parent_1.parent === null /* <- Note: We are in root */) {
1043
+ // [๐ŸŒป]
1044
+ throw new Error(spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
1045
+ }
1046
+ parent_1 = parent_1.parent;
1047
+ }
1048
+ }
1049
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
1050
+ parent_1.sections.push(section);
1051
+ current = section;
1128
1052
  }
1129
- else if (charType !== lastCharType &&
1130
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1131
- !(lastCharType === 'NUMBER') &&
1132
- !(charType === 'NUMBER')) {
1133
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [๐ŸŒบ] DRY
1134
- }
1135
- normalizedName += normalizedChar;
1136
- lastCharType = charType;
1137
1053
  }
1138
1054
  }
1139
1055
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1140
1056
  finally {
1141
1057
  try {
1142
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1058
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
1143
1059
  }
1144
1060
  finally { if (e_1) throw e_1.error; }
1145
1061
  }
1146
- return normalizedName;
1062
+ if (root.sections.length === 1) {
1063
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
1064
+ return markdownStructure;
1065
+ }
1066
+ // [๐ŸŒป]
1067
+ throw new Error('The markdown file must have exactly one top-level section.');
1068
+ // return root;
1147
1069
  }
1148
1070
  /**
1149
- * TODO: [๐ŸŒบ] Use some intermediate util splitWords
1071
+ * @private
1150
1072
  */
1073
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
1074
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
1075
+ return {
1076
+ level: level,
1077
+ title: title,
1078
+ content: spaceTrim(contentLines.join('\n')),
1079
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
1080
+ };
1081
+ }
1151
1082
 
1152
- function normalizeTo_PascalCase(sentence) {
1153
- return normalizeTo_camelCase(sentence, true);
1083
+ /**
1084
+ * The version of the Promptbook library
1085
+ */
1086
+ var PROMPTBOOK_VERSION = '0.44.0-1';
1087
+
1088
+ /**
1089
+ * Parses the given script and returns the list of all used variables that are not defined in the script
1090
+ *
1091
+ * @param script from which to extract the variables
1092
+ * @returns the list of variable names
1093
+ * @throws {PromptbookSyntaxError} if the script is invalid
1094
+ *
1095
+ * @private within the promptbookStringToJson
1096
+ */
1097
+ function extractVariables(script) {
1098
+ var variables = [];
1099
+ script = "(()=>{".concat(script, "})()");
1100
+ try {
1101
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
1102
+ try {
1103
+ eval(script);
1104
+ }
1105
+ catch (error) {
1106
+ if (!(error instanceof ReferenceError)) {
1107
+ throw error;
1108
+ }
1109
+ var undefinedName = error.message.split(' ')[0];
1110
+ /*
1111
+ Note: Remapping error
1112
+ From: [ReferenceError: thing is not defined],
1113
+ To: [Error: Parameter {thing} is not defined],
1114
+ */
1115
+ if (!undefinedName) {
1116
+ throw error;
1117
+ }
1118
+ if (script.includes(undefinedName + '(')) {
1119
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
1120
+ }
1121
+ else {
1122
+ variables.push(undefinedName);
1123
+ script = "const ".concat(undefinedName, " = '';") + script;
1124
+ }
1125
+ }
1126
+ }
1127
+ catch (error) {
1128
+ if (!(error instanceof Error)) {
1129
+ throw error;
1130
+ }
1131
+ 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 "); }));
1132
+ }
1133
+ return variables;
1154
1134
  }
1155
1135
 
1136
+ /**
1137
+ * Execution type describes the way how the block is executed
1138
+ *
1139
+ * @see https://github.com/webgptorg/promptbook#execution-type
1140
+ */
1141
+ var ExecutionTypes = [
1142
+ 'PROMPT_TEMPLATE',
1143
+ 'SIMPLE_TEMPLATE',
1144
+ 'SCRIPT',
1145
+ 'PROMPT_DIALOG',
1146
+ // <- [๐Ÿฅป] Insert here when making new command
1147
+ ];
1148
+
1149
+ /**
1150
+ * Units of text measurement
1151
+ */
1152
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
1153
+ /**
1154
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
1155
+ */
1156
+
1156
1157
  /**
1157
1158
  * Parses one line of ul/ol to command
1158
1159
  *
@@ -1646,7 +1647,7 @@ function promptbookStringToJson(promptbookString) {
1646
1647
  executionType: executionType,
1647
1648
  jokers: jokers,
1648
1649
  postprocessing: postprocessing,
1649
- expectAmount: expectAmount,
1650
+ expectations: expectAmount,
1650
1651
  expectFormat: expectFormat,
1651
1652
  modelRequirements: templateModelRequirements,
1652
1653
  contentLanguage: executionType === 'SCRIPT' ? language : undefined,
@@ -1788,7 +1789,7 @@ function validatePromptbookJson(promptbook) {
1788
1789
  }
1789
1790
  if (template.jokers && template.jokers.length > 0) {
1790
1791
  if (!template.expectFormat &&
1791
- !template.expectAmount /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1792
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1792
1793
  throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
1793
1794
  }
1794
1795
  try {
@@ -1807,9 +1808,9 @@ function validatePromptbookJson(promptbook) {
1807
1808
  finally { if (e_3) throw e_3.error; }
1808
1809
  }
1809
1810
  }
1810
- if (template.expectAmount) {
1811
+ if (template.expectations) {
1811
1812
  try {
1812
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectAmount))), _m = _l.next(); !_m.done; _m = _l.next()) {
1813
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1813
1814
  var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1814
1815
  if (min !== undefined && max !== undefined && min > max) {
1815
1816
  throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
@@ -1991,6 +1992,7 @@ function createPromptbookExecutor(options) {
1991
1992
  parameters: parametersToPass,
1992
1993
  content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1993
1994
  modelRequirements: currentTemplate.modelRequirements,
1995
+ expectations: currentTemplate.expectations,
1994
1996
  };
1995
1997
  _b = currentTemplate.modelRequirements.modelVariant;
1996
1998
  switch (_b) {
@@ -2171,9 +2173,9 @@ function createPromptbookExecutor(options) {
2171
2173
  }
2172
2174
  }
2173
2175
  }
2174
- if (currentTemplate.expectAmount) {
2176
+ if (currentTemplate.expectations) {
2175
2177
  try {
2176
- for (_j = (e_5 = void 0, __values(Object.entries(currentTemplate.expectAmount))), _k = _j.next(); !_k.done; _k = _j.next()) {
2178
+ for (_j = (e_5 = void 0, __values(Object.entries(currentTemplate.expectations))), _k = _j.next(); !_k.done; _k = _j.next()) {
2177
2179
  _l = __read(_k.value, 2), unit = _l[0], _m = _l[1], max = _m.max, min = _m.min;
2178
2180
  amount = CountUtils[unit.toUpperCase()](resultString || '');
2179
2181
  if (min && amount < min) {
@@ -2213,6 +2215,7 @@ function createPromptbookExecutor(options) {
2213
2215
  title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
2214
2216
  content: prompt.content,
2215
2217
  modelRequirements: prompt.modelRequirements,
2218
+ expectations: prompt.expectations,
2216
2219
  // <- Note: Do want to pass ONLY wanted information to the report
2217
2220
  },
2218
2221
  result: result || undefined,
@@ -2448,8 +2451,79 @@ var MockedEchoNaturalExecutionTools = /** @class */ (function () {
2448
2451
  return MockedEchoNaturalExecutionTools;
2449
2452
  }());
2450
2453
  /**
2451
- * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}
2454
+ * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}, same as replace params
2455
+ */
2456
+
2457
+ /**
2458
+ * Gets the expectations and creates a fake text that meets the expectations
2459
+ *
2460
+ * @private internal util for MockedFackedNaturalExecutionTools
2461
+ */
2462
+ function $fakeTextToExpectations(expectations) {
2463
+ var lorem = new LoremIpsum({
2464
+ sentencesPerParagraph: {
2465
+ max: 8,
2466
+ min: 4,
2467
+ },
2468
+ wordsPerSentence: {
2469
+ max: 16,
2470
+ min: 4,
2471
+ },
2472
+ });
2473
+ // TODO: !!! Really use the expectations to generate the text
2474
+ return lorem.generateSentences(5);
2475
+ }
2476
+
2477
+ /**
2478
+ * Mocked execution Tools for just faking expected responses for testing purposes
2452
2479
  */
2480
+ var MockedFackedNaturalExecutionTools = /** @class */ (function () {
2481
+ function MockedFackedNaturalExecutionTools(options) {
2482
+ this.options = options;
2483
+ }
2484
+ /**
2485
+ * Fakes chat model
2486
+ */
2487
+ MockedFackedNaturalExecutionTools.prototype.gptChat = function (prompt) {
2488
+ return __awaiter(this, void 0, void 0, function () {
2489
+ return __generator(this, function (_a) {
2490
+ if (this.options.isVerbose) {
2491
+ console.info('๐Ÿ’ฌ Mocked faked call');
2492
+ }
2493
+ return [2 /*return*/, {
2494
+ content: $fakeTextToExpectations(prompt.expectations || {
2495
+ sentences: { min: 1, max: 1 },
2496
+ }),
2497
+ model: 'mocked-facked',
2498
+ timing: {
2499
+ start: getCurrentIsoDate(),
2500
+ complete: getCurrentIsoDate(),
2501
+ },
2502
+ usage: {
2503
+ price: 0,
2504
+ inputTokens: 0,
2505
+ outputTokens: 0,
2506
+ },
2507
+ rawResponse: {
2508
+ note: 'This is mocked echo',
2509
+ },
2510
+ // <- [๐Ÿคนโ€โ™‚๏ธ]
2511
+ }];
2512
+ });
2513
+ });
2514
+ };
2515
+ /**
2516
+ * Fakes completion model
2517
+ */
2518
+ MockedFackedNaturalExecutionTools.prototype.gptComplete = function (prompt) {
2519
+ return __awaiter(this, void 0, void 0, function () {
2520
+ return __generator(this, function (_a) {
2521
+ return [2 /*return*/, this.gptChat(prompt)];
2522
+ });
2523
+ });
2524
+ };
2525
+ return MockedFackedNaturalExecutionTools;
2526
+ }());
2453
2527
 
2454
2528
  /**
2455
2529
  * Delagates the user interaction to a async callback function
@@ -2794,5 +2868,5 @@ function createPromptbookSublibrary(library, predicate) {
2794
2868
  * TODO: !!! Annotate all + all to README and samples
2795
2869
  */
2796
2870
 
2797
- export { CallbackInterfaceTools, ExecutionTypes, MockedEchoNaturalExecutionTools, PROMPTBOOK_VERSION, SimplePromptInterfaceTools, SimplePromptbookLibrary, createPromptbookExecutor, createPromptbookLibraryFromPromise, createPromptbookLibraryFromSources, createPromptbookSublibrary, promptbookStringToJson, validatePromptbookJson };
2871
+ export { CallbackInterfaceTools, ExecutionTypes, MockedEchoNaturalExecutionTools, MockedFackedNaturalExecutionTools, PROMPTBOOK_VERSION, SimplePromptInterfaceTools, SimplePromptbookLibrary, createPromptbookExecutor, createPromptbookLibraryFromPromise, createPromptbookLibraryFromSources, createPromptbookSublibrary, promptbookStringToJson, validatePromptbookJson };
2798
2872
  //# sourceMappingURL=index.es.js.map