@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/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim));
5
- })(this, (function (exports, spaceTrim) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment'), require('lorem-ipsum')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment', 'lorem-ipsum'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, null, null, null, global.loremIpsum));
5
+ })(this, (function (exports, spaceTrim, prettier, parserHtml, moment, loremIpsum) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -127,85 +127,6 @@
127
127
  return to.concat(ar || Array.prototype.slice.call(from));
128
128
  }
129
129
 
130
- /**
131
- * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
132
- */
133
- var PromptbookSyntaxError = /** @class */ (function (_super) {
134
- __extends(PromptbookSyntaxError, _super);
135
- function PromptbookSyntaxError(message) {
136
- var _this = _super.call(this, message) || this;
137
- _this.name = 'PromptbookSyntaxError';
138
- Object.setPrototypeOf(_this, PromptbookSyntaxError.prototype);
139
- return _this;
140
- }
141
- return PromptbookSyntaxError;
142
- }(Error));
143
-
144
- /**
145
- * Supported script languages
146
- */
147
- var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
148
-
149
- /**
150
- * Parses the template and returns the list of all parameter names
151
- *
152
- * @param template the template with parameters in {curly} braces
153
- * @returns the list of parameter names
154
- *
155
- * @private within the library
156
- */
157
- function extractParameters(template) {
158
- var e_1, _a;
159
- var matches = template.matchAll(/{\w+}/g);
160
- var parameterNames = [];
161
- try {
162
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
163
- var match = matches_1_1.value;
164
- var parameterName = match[0].slice(1, -1);
165
- if (!parameterNames.includes(parameterName)) {
166
- parameterNames.push(parameterName);
167
- }
168
- }
169
- }
170
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
171
- finally {
172
- try {
173
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
174
- }
175
- finally { if (e_1) throw e_1.error; }
176
- }
177
- return parameterNames;
178
- }
179
-
180
- /**
181
- * Computes the deepness of the markdown structure.
182
- *
183
- * @private within the library
184
- */
185
- function countMarkdownStructureDeepness(markdownStructure) {
186
- var e_1, _a;
187
- var maxDeepness = 0;
188
- try {
189
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
190
- var section = _c.value;
191
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
192
- }
193
- }
194
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
195
- finally {
196
- try {
197
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
198
- }
199
- finally { if (e_1) throw e_1.error; }
200
- }
201
- return maxDeepness + 1;
202
- }
203
-
204
- /**
205
- * The maximum number of iterations for a loops
206
- */
207
- var LOOP_LIMIT = 1000;
208
-
209
130
  /**
210
131
  * This error type indicates that the error should not happen and its last check before crashing with some other error
211
132
  */
@@ -220,218 +141,6 @@
220
141
  return UnexpectedError;
221
142
  }(Error));
222
143
 
223
- /**
224
- * Parse a markdown string into a MarkdownStructure object.
225
- *
226
- * Note: This function does work with code blocks
227
- * Note: This function does not work with markdown comments
228
- *
229
- * @param markdown The markdown string to parse.
230
- * @returns The MarkdownStructure object.
231
- *
232
- * @private within the library
233
- */
234
- function markdownToMarkdownStructure(markdown) {
235
- var e_1, _a;
236
- var lines = markdown.split('\n');
237
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
238
- var current = root;
239
- var isInsideCodeBlock = false;
240
- try {
241
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
242
- var line = lines_1_1.value;
243
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
244
- if (isInsideCodeBlock || !headingMatch) {
245
- if (line.startsWith('```')) {
246
- isInsideCodeBlock = !isInsideCodeBlock;
247
- }
248
- current.contentLines.push(line);
249
- }
250
- else {
251
- var level = headingMatch.groups.mark.length;
252
- var title = headingMatch.groups.title.trim();
253
- var parent_1 = void 0;
254
- if (level > current.level) {
255
- // Note: Going deeper (next section is child of current)
256
- parent_1 = current;
257
- }
258
- else {
259
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
260
- parent_1 = current;
261
- var loopLimit = LOOP_LIMIT;
262
- while (parent_1.level !== level - 1) {
263
- if (loopLimit-- < 0) {
264
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
265
- }
266
- if (parent_1.parent === null /* <- Note: We are in root */) {
267
- // [๐ŸŒป]
268
- throw new Error(spaceTrim__default["default"]("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
269
- }
270
- parent_1 = parent_1.parent;
271
- }
272
- }
273
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
274
- parent_1.sections.push(section);
275
- current = section;
276
- }
277
- }
278
- }
279
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
280
- finally {
281
- try {
282
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
283
- }
284
- finally { if (e_1) throw e_1.error; }
285
- }
286
- if (root.sections.length === 1) {
287
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
288
- return markdownStructure;
289
- }
290
- // [๐ŸŒป]
291
- throw new Error('The markdown file must have exactly one top-level section.');
292
- // return root;
293
- }
294
- /**
295
- * @private
296
- */
297
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
298
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
299
- return {
300
- level: level,
301
- title: title,
302
- content: spaceTrim__default["default"](contentLines.join('\n')),
303
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
304
- };
305
- }
306
-
307
- /**
308
- * Utility function to extract all list items from markdown
309
- *
310
- * Note: It works with both ul and ol
311
- * Note: It omits list items in code blocks
312
- * Note: It flattens nested lists
313
- * Note: It can not work with html syntax and comments
314
- *
315
- * @param markdown any valid markdown
316
- * @returns
317
- */
318
- function extractAllListItemsFromMarkdown(markdown) {
319
- var e_1, _a;
320
- var lines = markdown.split('\n');
321
- var listItems = [];
322
- var isInCodeBlock = false;
323
- try {
324
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
325
- var line = lines_1_1.value;
326
- var trimmedLine = line.trim();
327
- if (trimmedLine.startsWith('```')) {
328
- isInCodeBlock = !isInCodeBlock;
329
- }
330
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
331
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
332
- listItems.push(listItem);
333
- }
334
- }
335
- }
336
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
337
- finally {
338
- try {
339
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
340
- }
341
- finally { if (e_1) throw e_1.error; }
342
- }
343
- return listItems;
344
- }
345
-
346
- /**
347
- * Makes first letter of a string uppercase
348
- *
349
- */
350
- function capitalize(word) {
351
- return word.substring(0, 1).toUpperCase() + word.substring(1);
352
- }
353
-
354
- /**
355
- * Extracts all code blocks from markdown.
356
- *
357
- * Note: There are 3 simmilar function:
358
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
359
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
360
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
361
- *
362
- * @param markdown any valid markdown
363
- * @returns code blocks with language and content
364
- *
365
- */
366
- function extractAllBlocksFromMarkdown(markdown) {
367
- var e_1, _a;
368
- var codeBlocks = [];
369
- var lines = markdown.split('\n');
370
- var currentCodeBlock = null;
371
- try {
372
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
373
- var line = lines_1_1.value;
374
- if (line.startsWith('```')) {
375
- var language = line.slice(3).trim() || null;
376
- if (currentCodeBlock === null) {
377
- currentCodeBlock = { language: language, content: '' };
378
- }
379
- else {
380
- if (language !== null) {
381
- // [๐ŸŒป]
382
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
383
- }
384
- codeBlocks.push(currentCodeBlock);
385
- currentCodeBlock = null;
386
- }
387
- }
388
- else if (currentCodeBlock !== null) {
389
- if (currentCodeBlock.content !== '') {
390
- currentCodeBlock.content += '\n';
391
- }
392
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
393
- }
394
- }
395
- }
396
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
397
- finally {
398
- try {
399
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
400
- }
401
- finally { if (e_1) throw e_1.error; }
402
- }
403
- if (currentCodeBlock !== null) {
404
- // [๐ŸŒป]
405
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
406
- }
407
- return codeBlocks;
408
- }
409
-
410
- /**
411
- * Extracts exactly ONE code block from markdown.
412
- *
413
- * Note: If there are multiple or no code blocks the function throws an error
414
- *
415
- * Note: There are 3 simmilar function:
416
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
417
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
418
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
419
- *
420
- * @param markdown any valid markdown
421
- * @returns code block with language and content
422
- */
423
- function extractOneBlockFromMarkdown(markdown) {
424
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
425
- if (codeBlocks.length !== 1) {
426
- // TODO: Report more specific place where the error happened
427
- throw new Error(/* <- [๐ŸŒป] */ 'There should be exactly one code block in the markdown');
428
- }
429
- return codeBlocks[0];
430
- }
431
- /***
432
- * TODO: [๐ŸŒป] !!! Decide of this is internal util, external util OR validator/postprocessor
433
- */
434
-
435
144
  /**
436
145
  * Removes HTML or Markdown comments from a string.
437
146
  *
@@ -443,94 +152,18 @@
443
152
  }
444
153
 
445
154
  /**
446
- * The version of the Promptbook library
447
- */
448
- var PROMPTBOOK_VERSION = '0.44.0-0';
449
-
450
- /**
451
- * Parses the given script and returns the list of all used variables that are not defined in the script
452
- *
453
- * @param script from which to extract the variables
454
- * @returns the list of variable names
455
- * @throws {PromptbookSyntaxError} if the script is invalid
456
- *
457
- * @private within the promptbookStringToJson
458
- */
459
- function extractVariables(script) {
460
- var variables = [];
461
- script = "(()=>{".concat(script, "})()");
462
- try {
463
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
464
- try {
465
- eval(script);
466
- }
467
- catch (error) {
468
- if (!(error instanceof ReferenceError)) {
469
- throw error;
470
- }
471
- var undefinedName = error.message.split(' ')[0];
472
- /*
473
- Note: Remapping error
474
- From: [ReferenceError: thing is not defined],
475
- To: [Error: Parameter {thing} is not defined],
476
- */
477
- if (!undefinedName) {
478
- throw error;
479
- }
480
- if (script.includes(undefinedName + '(')) {
481
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
482
- }
483
- else {
484
- variables.push(undefinedName);
485
- script = "const ".concat(undefinedName, " = '';") + script;
486
- }
487
- }
488
- }
489
- catch (error) {
490
- if (!(error instanceof Error)) {
491
- throw error;
492
- }
493
- throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
494
- }
495
- return variables;
496
- }
497
-
498
- /**
499
- * Execution type describes the way how the block is executed
500
- *
501
- * @see https://github.com/webgptorg/promptbook#execution-type
502
- */
503
- var ExecutionTypes = [
504
- 'PROMPT_TEMPLATE',
505
- 'SIMPLE_TEMPLATE',
506
- 'SCRIPT',
507
- 'PROMPT_DIALOG',
508
- // <- [๐Ÿฅป] Insert here when making new command
509
- ];
510
-
511
- /**
512
- * Units of text measurement
513
- */
514
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
515
- /**
516
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
517
- */
518
-
519
- /**
520
- * Removes Markdown formatting tags from a string.
521
- *
522
- * @param {string} str - The string to remove Markdown tags from.
523
- * @returns {string} The input string with all Markdown tags removed.
155
+ * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
524
156
  */
525
- function removeMarkdownFormatting(str) {
526
- // Remove bold formatting
527
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
528
- // Remove italic formatting
529
- str = str.replace(/\*(.*?)\*/g, '$1');
530
- // Remove code formatting
531
- str = str.replace(/`(.*?)`/g, '$1');
532
- return str;
533
- }
157
+ var PromptbookSyntaxError = /** @class */ (function (_super) {
158
+ __extends(PromptbookSyntaxError, _super);
159
+ function PromptbookSyntaxError(message) {
160
+ var _this = _super.call(this, message) || this;
161
+ _this.name = 'PromptbookSyntaxError';
162
+ Object.setPrototypeOf(_this, PromptbookSyntaxError.prototype);
163
+ return _this;
164
+ }
165
+ return PromptbookSyntaxError;
166
+ }(Error));
534
167
 
535
168
  /**
536
169
  * Function parseNumber will parse number from string
@@ -613,6 +246,11 @@
613
246
  return PromptbookExecutionError;
614
247
  }(Error));
615
248
 
249
+ /**
250
+ * The maximum number of iterations for a loops
251
+ */
252
+ var LOOP_LIMIT = 1000;
253
+
616
254
  /**
617
255
  * This error occurs during the parameter replacement in the template
618
256
  *
@@ -1035,6 +673,150 @@
1035
673
  }
1036
674
  }
1037
675
 
676
+ /**
677
+ * Makes first letter of a string uppercase
678
+ *
679
+ */
680
+ function capitalize(word) {
681
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
682
+ }
683
+
684
+ /**
685
+ * Extracts all code blocks from markdown.
686
+ *
687
+ * Note: There are 3 simmilar function:
688
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
689
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
690
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
691
+ *
692
+ * @param markdown any valid markdown
693
+ * @returns code blocks with language and content
694
+ *
695
+ */
696
+ function extractAllBlocksFromMarkdown(markdown) {
697
+ var e_1, _a;
698
+ var codeBlocks = [];
699
+ var lines = markdown.split('\n');
700
+ var currentCodeBlock = null;
701
+ try {
702
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
703
+ var line = lines_1_1.value;
704
+ if (line.startsWith('```')) {
705
+ var language = line.slice(3).trim() || null;
706
+ if (currentCodeBlock === null) {
707
+ currentCodeBlock = { language: language, content: '' };
708
+ }
709
+ else {
710
+ if (language !== null) {
711
+ // [๐ŸŒป]
712
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
713
+ }
714
+ codeBlocks.push(currentCodeBlock);
715
+ currentCodeBlock = null;
716
+ }
717
+ }
718
+ else if (currentCodeBlock !== null) {
719
+ if (currentCodeBlock.content !== '') {
720
+ currentCodeBlock.content += '\n';
721
+ }
722
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
723
+ }
724
+ }
725
+ }
726
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
727
+ finally {
728
+ try {
729
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
730
+ }
731
+ finally { if (e_1) throw e_1.error; }
732
+ }
733
+ if (currentCodeBlock !== null) {
734
+ // [๐ŸŒป]
735
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
736
+ }
737
+ return codeBlocks;
738
+ }
739
+
740
+ /**
741
+ * Utility function to extract all list items from markdown
742
+ *
743
+ * Note: It works with both ul and ol
744
+ * Note: It omits list items in code blocks
745
+ * Note: It flattens nested lists
746
+ * Note: It can not work with html syntax and comments
747
+ *
748
+ * @param markdown any valid markdown
749
+ * @returns
750
+ */
751
+ function extractAllListItemsFromMarkdown(markdown) {
752
+ var e_1, _a;
753
+ var lines = markdown.split('\n');
754
+ var listItems = [];
755
+ var isInCodeBlock = false;
756
+ try {
757
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
758
+ var line = lines_1_1.value;
759
+ var trimmedLine = line.trim();
760
+ if (trimmedLine.startsWith('```')) {
761
+ isInCodeBlock = !isInCodeBlock;
762
+ }
763
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
764
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
765
+ listItems.push(listItem);
766
+ }
767
+ }
768
+ }
769
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
770
+ finally {
771
+ try {
772
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
773
+ }
774
+ finally { if (e_1) throw e_1.error; }
775
+ }
776
+ return listItems;
777
+ }
778
+
779
+ /**
780
+ * Extracts exactly ONE code block from markdown.
781
+ *
782
+ * Note: If there are multiple or no code blocks the function throws an error
783
+ *
784
+ * Note: There are 3 simmilar function:
785
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
786
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
787
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
788
+ *
789
+ * @param markdown any valid markdown
790
+ * @returns code block with language and content
791
+ */
792
+ function extractOneBlockFromMarkdown(markdown) {
793
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
794
+ if (codeBlocks.length !== 1) {
795
+ // TODO: Report more specific place where the error happened
796
+ throw new Error(/* <- [๐ŸŒป] */ 'There should be exactly one code block in the markdown');
797
+ }
798
+ return codeBlocks[0];
799
+ }
800
+ /***
801
+ * TODO: [๐ŸŒป] !!! Decide of this is internal util, external util OR validator/postprocessor
802
+ */
803
+
804
+ /**
805
+ * Removes Markdown formatting tags from a string.
806
+ *
807
+ * @param {string} str - The string to remove Markdown tags from.
808
+ * @returns {string} The input string with all Markdown tags removed.
809
+ */
810
+ function removeMarkdownFormatting(str) {
811
+ // Remove bold formatting
812
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
813
+ // Remove italic formatting
814
+ str = str.replace(/\*(.*?)\*/g, '$1');
815
+ // Remove code formatting
816
+ str = str.replace(/`(.*?)`/g, '$1');
817
+ return str;
818
+ }
819
+
1038
820
  /* tslint:disable */
1039
821
  /*
1040
822
  TODO: Tests
@@ -1078,86 +860,304 @@
1078
860
  !(charType === 'NUMBER')) {
1079
861
  normalizedName += '_';
1080
862
  }
1081
- normalizedName += normalizedChar;
1082
- lastCharType = charType;
863
+ normalizedName += normalizedChar;
864
+ lastCharType = charType;
865
+ }
866
+ }
867
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
868
+ finally {
869
+ try {
870
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
871
+ }
872
+ finally { if (e_1) throw e_1.error; }
873
+ }
874
+ normalizedName = normalizedName.replace(/_+/g, '_');
875
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
876
+ normalizedName = normalizedName.replace(/^_/, '');
877
+ normalizedName = normalizedName.replace(/_$/, '');
878
+ return normalizedName;
879
+ }
880
+ /**
881
+ * TODO: [๐ŸŒบ] Use some intermediate util splitWords
882
+ */
883
+
884
+ /* tslint:disable */
885
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
886
+ var e_1, _a;
887
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
888
+ var charType;
889
+ var lastCharType = null;
890
+ var normalizedName = '';
891
+ try {
892
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
893
+ var char = sentence_1_1.value;
894
+ var normalizedChar = void 0;
895
+ if (/^[a-z]$/.test(char)) {
896
+ charType = 'LOWERCASE';
897
+ normalizedChar = char;
898
+ }
899
+ else if (/^[A-Z]$/.test(char)) {
900
+ charType = 'UPPERCASE';
901
+ normalizedChar = char.toLowerCase();
902
+ }
903
+ else if (/^[0-9]$/.test(char)) {
904
+ charType = 'NUMBER';
905
+ normalizedChar = char;
906
+ }
907
+ else {
908
+ charType = 'OTHER';
909
+ normalizedChar = '';
910
+ }
911
+ if (!lastCharType) {
912
+ if (__firstLetterCapital) {
913
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
914
+ }
915
+ }
916
+ else if (charType !== lastCharType &&
917
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
918
+ !(lastCharType === 'NUMBER') &&
919
+ !(charType === 'NUMBER')) {
920
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [๐ŸŒบ] DRY
921
+ }
922
+ normalizedName += normalizedChar;
923
+ lastCharType = charType;
924
+ }
925
+ }
926
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
927
+ finally {
928
+ try {
929
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
930
+ }
931
+ finally { if (e_1) throw e_1.error; }
932
+ }
933
+ return normalizedName;
934
+ }
935
+ /**
936
+ * TODO: [๐ŸŒบ] Use some intermediate util splitWords
937
+ */
938
+
939
+ function normalizeTo_PascalCase(sentence) {
940
+ return normalizeTo_camelCase(sentence, true);
941
+ }
942
+
943
+ /**
944
+ * Supported script languages
945
+ */
946
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
947
+
948
+ /**
949
+ * Parses the template and returns the list of all parameter names
950
+ *
951
+ * @param template the template with parameters in {curly} braces
952
+ * @returns the list of parameter names
953
+ *
954
+ * @private within the library
955
+ */
956
+ function extractParameters(template) {
957
+ var e_1, _a;
958
+ var matches = template.matchAll(/{\w+}/g);
959
+ var parameterNames = [];
960
+ try {
961
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
962
+ var match = matches_1_1.value;
963
+ var parameterName = match[0].slice(1, -1);
964
+ if (!parameterNames.includes(parameterName)) {
965
+ parameterNames.push(parameterName);
966
+ }
1083
967
  }
1084
968
  }
1085
969
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1086
970
  finally {
1087
971
  try {
1088
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
972
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
1089
973
  }
1090
974
  finally { if (e_1) throw e_1.error; }
1091
975
  }
1092
- normalizedName = normalizedName.replace(/_+/g, '_');
1093
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
1094
- normalizedName = normalizedName.replace(/^_/, '');
1095
- normalizedName = normalizedName.replace(/_$/, '');
1096
- return normalizedName;
976
+ return parameterNames;
1097
977
  }
978
+
1098
979
  /**
1099
- * TODO: [๐ŸŒบ] Use some intermediate util splitWords
980
+ * Computes the deepness of the markdown structure.
981
+ *
982
+ * @private within the library
1100
983
  */
984
+ function countMarkdownStructureDeepness(markdownStructure) {
985
+ var e_1, _a;
986
+ var maxDeepness = 0;
987
+ try {
988
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
989
+ var section = _c.value;
990
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
991
+ }
992
+ }
993
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
994
+ finally {
995
+ try {
996
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
997
+ }
998
+ finally { if (e_1) throw e_1.error; }
999
+ }
1000
+ return maxDeepness + 1;
1001
+ }
1101
1002
 
1102
- /* tslint:disable */
1103
- function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1003
+ /**
1004
+ * Parse a markdown string into a MarkdownStructure object.
1005
+ *
1006
+ * Note: This function does work with code blocks
1007
+ * Note: This function does not work with markdown comments
1008
+ *
1009
+ * @param markdown The markdown string to parse.
1010
+ * @returns The MarkdownStructure object.
1011
+ *
1012
+ * @private within the library
1013
+ */
1014
+ function markdownToMarkdownStructure(markdown) {
1104
1015
  var e_1, _a;
1105
- if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1106
- var charType;
1107
- var lastCharType = null;
1108
- var normalizedName = '';
1016
+ var lines = markdown.split('\n');
1017
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
1018
+ var current = root;
1019
+ var isInsideCodeBlock = false;
1109
1020
  try {
1110
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1111
- var char = sentence_1_1.value;
1112
- var normalizedChar = void 0;
1113
- if (/^[a-z]$/.test(char)) {
1114
- charType = 'LOWERCASE';
1115
- normalizedChar = char;
1116
- }
1117
- else if (/^[A-Z]$/.test(char)) {
1118
- charType = 'UPPERCASE';
1119
- normalizedChar = char.toLowerCase();
1120
- }
1121
- else if (/^[0-9]$/.test(char)) {
1122
- charType = 'NUMBER';
1123
- normalizedChar = char;
1021
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
1022
+ var line = lines_1_1.value;
1023
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
1024
+ if (isInsideCodeBlock || !headingMatch) {
1025
+ if (line.startsWith('```')) {
1026
+ isInsideCodeBlock = !isInsideCodeBlock;
1027
+ }
1028
+ current.contentLines.push(line);
1124
1029
  }
1125
1030
  else {
1126
- charType = 'OTHER';
1127
- normalizedChar = '';
1128
- }
1129
- if (!lastCharType) {
1130
- if (__firstLetterCapital) {
1131
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1031
+ var level = headingMatch.groups.mark.length;
1032
+ var title = headingMatch.groups.title.trim();
1033
+ var parent_1 = void 0;
1034
+ if (level > current.level) {
1035
+ // Note: Going deeper (next section is child of current)
1036
+ parent_1 = current;
1132
1037
  }
1038
+ else {
1039
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
1040
+ parent_1 = current;
1041
+ var loopLimit = LOOP_LIMIT;
1042
+ while (parent_1.level !== level - 1) {
1043
+ if (loopLimit-- < 0) {
1044
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
1045
+ }
1046
+ if (parent_1.parent === null /* <- Note: We are in root */) {
1047
+ // [๐ŸŒป]
1048
+ throw new Error(spaceTrim__default["default"]("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
1049
+ }
1050
+ parent_1 = parent_1.parent;
1051
+ }
1052
+ }
1053
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
1054
+ parent_1.sections.push(section);
1055
+ current = section;
1133
1056
  }
1134
- else if (charType !== lastCharType &&
1135
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1136
- !(lastCharType === 'NUMBER') &&
1137
- !(charType === 'NUMBER')) {
1138
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [๐ŸŒบ] DRY
1139
- }
1140
- normalizedName += normalizedChar;
1141
- lastCharType = charType;
1142
1057
  }
1143
1058
  }
1144
1059
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1145
1060
  finally {
1146
1061
  try {
1147
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1062
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
1148
1063
  }
1149
1064
  finally { if (e_1) throw e_1.error; }
1150
1065
  }
1151
- return normalizedName;
1066
+ if (root.sections.length === 1) {
1067
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
1068
+ return markdownStructure;
1069
+ }
1070
+ // [๐ŸŒป]
1071
+ throw new Error('The markdown file must have exactly one top-level section.');
1072
+ // return root;
1152
1073
  }
1153
1074
  /**
1154
- * TODO: [๐ŸŒบ] Use some intermediate util splitWords
1075
+ * @private
1155
1076
  */
1077
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
1078
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
1079
+ return {
1080
+ level: level,
1081
+ title: title,
1082
+ content: spaceTrim__default["default"](contentLines.join('\n')),
1083
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
1084
+ };
1085
+ }
1156
1086
 
1157
- function normalizeTo_PascalCase(sentence) {
1158
- return normalizeTo_camelCase(sentence, true);
1087
+ /**
1088
+ * The version of the Promptbook library
1089
+ */
1090
+ var PROMPTBOOK_VERSION = '0.44.0-1';
1091
+
1092
+ /**
1093
+ * Parses the given script and returns the list of all used variables that are not defined in the script
1094
+ *
1095
+ * @param script from which to extract the variables
1096
+ * @returns the list of variable names
1097
+ * @throws {PromptbookSyntaxError} if the script is invalid
1098
+ *
1099
+ * @private within the promptbookStringToJson
1100
+ */
1101
+ function extractVariables(script) {
1102
+ var variables = [];
1103
+ script = "(()=>{".concat(script, "})()");
1104
+ try {
1105
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
1106
+ try {
1107
+ eval(script);
1108
+ }
1109
+ catch (error) {
1110
+ if (!(error instanceof ReferenceError)) {
1111
+ throw error;
1112
+ }
1113
+ var undefinedName = error.message.split(' ')[0];
1114
+ /*
1115
+ Note: Remapping error
1116
+ From: [ReferenceError: thing is not defined],
1117
+ To: [Error: Parameter {thing} is not defined],
1118
+ */
1119
+ if (!undefinedName) {
1120
+ throw error;
1121
+ }
1122
+ if (script.includes(undefinedName + '(')) {
1123
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
1124
+ }
1125
+ else {
1126
+ variables.push(undefinedName);
1127
+ script = "const ".concat(undefinedName, " = '';") + script;
1128
+ }
1129
+ }
1130
+ }
1131
+ catch (error) {
1132
+ if (!(error instanceof Error)) {
1133
+ throw error;
1134
+ }
1135
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
1136
+ }
1137
+ return variables;
1159
1138
  }
1160
1139
 
1140
+ /**
1141
+ * Execution type describes the way how the block is executed
1142
+ *
1143
+ * @see https://github.com/webgptorg/promptbook#execution-type
1144
+ */
1145
+ var ExecutionTypes = [
1146
+ 'PROMPT_TEMPLATE',
1147
+ 'SIMPLE_TEMPLATE',
1148
+ 'SCRIPT',
1149
+ 'PROMPT_DIALOG',
1150
+ // <- [๐Ÿฅป] Insert here when making new command
1151
+ ];
1152
+
1153
+ /**
1154
+ * Units of text measurement
1155
+ */
1156
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
1157
+ /**
1158
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
1159
+ */
1160
+
1161
1161
  /**
1162
1162
  * Parses one line of ul/ol to command
1163
1163
  *
@@ -1651,7 +1651,7 @@
1651
1651
  executionType: executionType,
1652
1652
  jokers: jokers,
1653
1653
  postprocessing: postprocessing,
1654
- expectAmount: expectAmount,
1654
+ expectations: expectAmount,
1655
1655
  expectFormat: expectFormat,
1656
1656
  modelRequirements: templateModelRequirements,
1657
1657
  contentLanguage: executionType === 'SCRIPT' ? language : undefined,
@@ -1793,7 +1793,7 @@
1793
1793
  }
1794
1794
  if (template.jokers && template.jokers.length > 0) {
1795
1795
  if (!template.expectFormat &&
1796
- !template.expectAmount /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1796
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1797
1797
  throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
1798
1798
  }
1799
1799
  try {
@@ -1812,9 +1812,9 @@
1812
1812
  finally { if (e_3) throw e_3.error; }
1813
1813
  }
1814
1814
  }
1815
- if (template.expectAmount) {
1815
+ if (template.expectations) {
1816
1816
  try {
1817
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectAmount))), _m = _l.next(); !_m.done; _m = _l.next()) {
1817
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1818
1818
  var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1819
1819
  if (min !== undefined && max !== undefined && min > max) {
1820
1820
  throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
@@ -1996,6 +1996,7 @@
1996
1996
  parameters: parametersToPass,
1997
1997
  content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1998
1998
  modelRequirements: currentTemplate.modelRequirements,
1999
+ expectations: currentTemplate.expectations,
1999
2000
  };
2000
2001
  _b = currentTemplate.modelRequirements.modelVariant;
2001
2002
  switch (_b) {
@@ -2176,9 +2177,9 @@
2176
2177
  }
2177
2178
  }
2178
2179
  }
2179
- if (currentTemplate.expectAmount) {
2180
+ if (currentTemplate.expectations) {
2180
2181
  try {
2181
- for (_j = (e_5 = void 0, __values(Object.entries(currentTemplate.expectAmount))), _k = _j.next(); !_k.done; _k = _j.next()) {
2182
+ for (_j = (e_5 = void 0, __values(Object.entries(currentTemplate.expectations))), _k = _j.next(); !_k.done; _k = _j.next()) {
2182
2183
  _l = __read(_k.value, 2), unit = _l[0], _m = _l[1], max = _m.max, min = _m.min;
2183
2184
  amount = CountUtils[unit.toUpperCase()](resultString || '');
2184
2185
  if (min && amount < min) {
@@ -2218,6 +2219,7 @@
2218
2219
  title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
2219
2220
  content: prompt.content,
2220
2221
  modelRequirements: prompt.modelRequirements,
2222
+ expectations: prompt.expectations,
2221
2223
  // <- Note: Do want to pass ONLY wanted information to the report
2222
2224
  },
2223
2225
  result: result || undefined,
@@ -2453,8 +2455,79 @@
2453
2455
  return MockedEchoNaturalExecutionTools;
2454
2456
  }());
2455
2457
  /**
2456
- * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}
2458
+ * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}, same as replace params
2459
+ */
2460
+
2461
+ /**
2462
+ * Gets the expectations and creates a fake text that meets the expectations
2463
+ *
2464
+ * @private internal util for MockedFackedNaturalExecutionTools
2465
+ */
2466
+ function $fakeTextToExpectations(expectations) {
2467
+ var lorem = new loremIpsum.LoremIpsum({
2468
+ sentencesPerParagraph: {
2469
+ max: 8,
2470
+ min: 4,
2471
+ },
2472
+ wordsPerSentence: {
2473
+ max: 16,
2474
+ min: 4,
2475
+ },
2476
+ });
2477
+ // TODO: !!! Really use the expectations to generate the text
2478
+ return lorem.generateSentences(5);
2479
+ }
2480
+
2481
+ /**
2482
+ * Mocked execution Tools for just faking expected responses for testing purposes
2457
2483
  */
2484
+ var MockedFackedNaturalExecutionTools = /** @class */ (function () {
2485
+ function MockedFackedNaturalExecutionTools(options) {
2486
+ this.options = options;
2487
+ }
2488
+ /**
2489
+ * Fakes chat model
2490
+ */
2491
+ MockedFackedNaturalExecutionTools.prototype.gptChat = function (prompt) {
2492
+ return __awaiter(this, void 0, void 0, function () {
2493
+ return __generator(this, function (_a) {
2494
+ if (this.options.isVerbose) {
2495
+ console.info('๐Ÿ’ฌ Mocked faked call');
2496
+ }
2497
+ return [2 /*return*/, {
2498
+ content: $fakeTextToExpectations(prompt.expectations || {
2499
+ sentences: { min: 1, max: 1 },
2500
+ }),
2501
+ model: 'mocked-facked',
2502
+ timing: {
2503
+ start: getCurrentIsoDate(),
2504
+ complete: getCurrentIsoDate(),
2505
+ },
2506
+ usage: {
2507
+ price: 0,
2508
+ inputTokens: 0,
2509
+ outputTokens: 0,
2510
+ },
2511
+ rawResponse: {
2512
+ note: 'This is mocked echo',
2513
+ },
2514
+ // <- [๐Ÿคนโ€โ™‚๏ธ]
2515
+ }];
2516
+ });
2517
+ });
2518
+ };
2519
+ /**
2520
+ * Fakes completion model
2521
+ */
2522
+ MockedFackedNaturalExecutionTools.prototype.gptComplete = function (prompt) {
2523
+ return __awaiter(this, void 0, void 0, function () {
2524
+ return __generator(this, function (_a) {
2525
+ return [2 /*return*/, this.gptChat(prompt)];
2526
+ });
2527
+ });
2528
+ };
2529
+ return MockedFackedNaturalExecutionTools;
2530
+ }());
2458
2531
 
2459
2532
  /**
2460
2533
  * Delagates the user interaction to a async callback function
@@ -2802,6 +2875,7 @@
2802
2875
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
2803
2876
  exports.ExecutionTypes = ExecutionTypes;
2804
2877
  exports.MockedEchoNaturalExecutionTools = MockedEchoNaturalExecutionTools;
2878
+ exports.MockedFackedNaturalExecutionTools = MockedFackedNaturalExecutionTools;
2805
2879
  exports.PROMPTBOOK_VERSION = PROMPTBOOK_VERSION;
2806
2880
  exports.SimplePromptInterfaceTools = SimplePromptInterfaceTools;
2807
2881
  exports.SimplePromptbookLibrary = SimplePromptbookLibrary;