@promptbook/utils 0.41.2 → 0.41.4

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,14 +1,17 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('moment'), require('n12'), require('prettier'), require('prettier/parser-html')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'moment', 'n12', 'prettier', 'prettier/parser-html'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-utils"] = {}, global.spaceTrim, global.moment, global.n12, global.prettier, global.parserHtml));
5
- })(this, (function (exports, spaceTrim, moment, n12, prettier, parserHtml) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('n12'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('colors'), require('commander'), require('fs/promises'), require('glob-promise'), require('moment')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'n12', 'spacetrim', 'prettier', 'prettier/parser-html', 'colors', 'commander', 'fs/promises', 'glob-promise', 'moment'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-utils"] = {}, global.n12, global.spaceTrim, global.prettier, global.parserHtml, global.colors, global.commander, global.promises, global.glob, global.moment));
5
+ })(this, (function (exports, n12, spaceTrim, prettier, parserHtml, colors, commander, promises, glob, moment) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
9
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
10
- var moment__default = /*#__PURE__*/_interopDefaultLegacy(moment);
11
10
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
11
+ var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
12
+ var commander__default = /*#__PURE__*/_interopDefaultLegacy(commander);
13
+ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
14
+ var moment__default = /*#__PURE__*/_interopDefaultLegacy(moment);
12
15
 
13
16
  /*! *****************************************************************************
14
17
  Copyright (c) Microsoft Corporation.
@@ -52,6 +55,44 @@
52
55
  return __assign.apply(this, arguments);
53
56
  };
54
57
 
58
+ function __awaiter(thisArg, _arguments, P, generator) {
59
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
60
+ return new (P || (P = Promise))(function (resolve, reject) {
61
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
62
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
63
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
64
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
65
+ });
66
+ }
67
+
68
+ function __generator(thisArg, body) {
69
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
70
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
71
+ function verb(n) { return function (v) { return step([n, v]); }; }
72
+ function step(op) {
73
+ if (f) throw new TypeError("Generator is already executing.");
74
+ while (_) try {
75
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
76
+ if (y = 0, t) op = [op[0] & 2, t.value];
77
+ switch (op[0]) {
78
+ case 0: case 1: t = op; break;
79
+ case 4: _.label++; return { value: op[1], done: false };
80
+ case 5: _.label++; y = op[1]; op = [0]; continue;
81
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
82
+ default:
83
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
84
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
85
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
86
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
87
+ if (t[2]) _.ops.pop();
88
+ _.trys.pop(); continue;
89
+ }
90
+ op = body.call(thisArg, _);
91
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
92
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
93
+ }
94
+ }
95
+
55
96
  function __values(o) {
56
97
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
57
98
  if (m) return m.call(o);
@@ -105,6 +146,382 @@
105
146
  return PromptbookSyntaxError;
106
147
  }(Error));
107
148
 
149
+ /**
150
+ * Supported script languages
151
+ */
152
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
153
+
154
+ /**
155
+ * Parses the template and returns the list of all parameter names
156
+ *
157
+ * @param template the template with parameters in {curly} braces
158
+ * @returns the list of parameter names
159
+ *
160
+ * @private within the library
161
+ */
162
+ function extractParameters(template) {
163
+ var e_1, _a;
164
+ var matches = template.matchAll(/{\w+}/g);
165
+ var parameterNames = [];
166
+ try {
167
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
168
+ var match = matches_1_1.value;
169
+ var parameterName = match[0].slice(1, -1);
170
+ if (!parameterNames.includes(parameterName)) {
171
+ parameterNames.push(parameterName);
172
+ }
173
+ }
174
+ }
175
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
176
+ finally {
177
+ try {
178
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
179
+ }
180
+ finally { if (e_1) throw e_1.error; }
181
+ }
182
+ return parameterNames;
183
+ }
184
+
185
+ /**
186
+ * Computes the deepness of the markdown structure.
187
+ *
188
+ * @private within the library
189
+ */
190
+ function countMarkdownStructureDeepness(markdownStructure) {
191
+ var e_1, _a;
192
+ var maxDeepness = 0;
193
+ try {
194
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
195
+ var section = _c.value;
196
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
197
+ }
198
+ }
199
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
200
+ finally {
201
+ try {
202
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
203
+ }
204
+ finally { if (e_1) throw e_1.error; }
205
+ }
206
+ return maxDeepness + 1;
207
+ }
208
+
209
+ /**
210
+ * The maximum number of iterations for a loops
211
+ */
212
+ var LOOP_LIMIT = 1000;
213
+
214
+ /**
215
+ * This error type indicates that the error should not happen and its last check before crashing with some other error
216
+ */
217
+ var UnexpectedError = /** @class */ (function (_super) {
218
+ __extends(UnexpectedError, _super);
219
+ function UnexpectedError(message) {
220
+ var _this = _super.call(this, spaceTrim__default["default"](function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
221
+ _this.name = 'UnexpectedError';
222
+ Object.setPrototypeOf(_this, UnexpectedError.prototype);
223
+ return _this;
224
+ }
225
+ return UnexpectedError;
226
+ }(Error));
227
+
228
+ /**
229
+ * Parse a markdown string into a MarkdownStructure object.
230
+ *
231
+ * Note: This function does work with code blocks
232
+ * Note: This function does not work with markdown comments
233
+ *
234
+ * @param markdown The markdown string to parse.
235
+ * @returns The MarkdownStructure object.
236
+ *
237
+ * @private within the library
238
+ */
239
+ function markdownToMarkdownStructure(markdown) {
240
+ var e_1, _a;
241
+ var lines = markdown.split('\n');
242
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
243
+ var current = root;
244
+ var isInsideCodeBlock = false;
245
+ try {
246
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
247
+ var line = lines_1_1.value;
248
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
249
+ if (isInsideCodeBlock || !headingMatch) {
250
+ if (line.startsWith('```')) {
251
+ isInsideCodeBlock = !isInsideCodeBlock;
252
+ }
253
+ current.contentLines.push(line);
254
+ }
255
+ else {
256
+ var level = headingMatch.groups.mark.length;
257
+ var title = headingMatch.groups.title.trim();
258
+ var parent_1 = void 0;
259
+ if (level > current.level) {
260
+ // Note: Going deeper (next section is child of current)
261
+ parent_1 = current;
262
+ }
263
+ else {
264
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
265
+ parent_1 = current;
266
+ var loopLimit = LOOP_LIMIT;
267
+ while (parent_1.level !== level - 1) {
268
+ if (loopLimit-- < 0) {
269
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
270
+ }
271
+ if (parent_1.parent === null /* <- Note: We are in root */) {
272
+ // [🌻]
273
+ 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 "));
274
+ }
275
+ parent_1 = parent_1.parent;
276
+ }
277
+ }
278
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
279
+ parent_1.sections.push(section);
280
+ current = section;
281
+ }
282
+ }
283
+ }
284
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
285
+ finally {
286
+ try {
287
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
288
+ }
289
+ finally { if (e_1) throw e_1.error; }
290
+ }
291
+ if (root.sections.length === 1) {
292
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
293
+ return markdownStructure;
294
+ }
295
+ // [🌻]
296
+ throw new Error('The markdown file must have exactly one top-level section.');
297
+ // return root;
298
+ }
299
+ /**
300
+ * @private
301
+ */
302
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
303
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
304
+ return {
305
+ level: level,
306
+ title: title,
307
+ content: spaceTrim__default["default"](contentLines.join('\n')),
308
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
309
+ };
310
+ }
311
+
312
+ /**
313
+ * Utility function to extract all list items from markdown
314
+ *
315
+ * Note: It works with both ul and ol
316
+ * Note: It omits list items in code blocks
317
+ * Note: It flattens nested lists
318
+ * Note: It can not work with html syntax and comments
319
+ *
320
+ * @param markdown any valid markdown
321
+ * @returns
322
+ */
323
+ function extractAllListItemsFromMarkdown(markdown) {
324
+ var e_1, _a;
325
+ var lines = markdown.split('\n');
326
+ var listItems = [];
327
+ var isInCodeBlock = false;
328
+ try {
329
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
330
+ var line = lines_1_1.value;
331
+ var trimmedLine = line.trim();
332
+ if (trimmedLine.startsWith('```')) {
333
+ isInCodeBlock = !isInCodeBlock;
334
+ }
335
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
336
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
337
+ listItems.push(listItem);
338
+ }
339
+ }
340
+ }
341
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
342
+ finally {
343
+ try {
344
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
345
+ }
346
+ finally { if (e_1) throw e_1.error; }
347
+ }
348
+ return listItems;
349
+ }
350
+
351
+ /**
352
+ * Extracts all code blocks from markdown.
353
+ *
354
+ * Note: There are 3 simmilar function:
355
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
356
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
357
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
358
+ *
359
+ * @param markdown any valid markdown
360
+ * @returns code blocks with language and content
361
+ *
362
+ */
363
+ function extractAllBlocksFromMarkdown(markdown) {
364
+ var e_1, _a;
365
+ var codeBlocks = [];
366
+ var lines = markdown.split('\n');
367
+ var currentCodeBlock = null;
368
+ try {
369
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
370
+ var line = lines_1_1.value;
371
+ if (line.startsWith('```')) {
372
+ var language = line.slice(3).trim() || null;
373
+ if (currentCodeBlock === null) {
374
+ currentCodeBlock = { language: language, content: '' };
375
+ }
376
+ else {
377
+ if (language !== null) {
378
+ // [🌻]
379
+ throw new Error("".concat(n12.capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
380
+ }
381
+ codeBlocks.push(currentCodeBlock);
382
+ currentCodeBlock = null;
383
+ }
384
+ }
385
+ else if (currentCodeBlock !== null) {
386
+ if (currentCodeBlock.content !== '') {
387
+ currentCodeBlock.content += '\n';
388
+ }
389
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
390
+ }
391
+ }
392
+ }
393
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
394
+ finally {
395
+ try {
396
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
397
+ }
398
+ finally { if (e_1) throw e_1.error; }
399
+ }
400
+ if (currentCodeBlock !== null) {
401
+ // [🌻]
402
+ throw new Error("".concat(n12.capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
403
+ }
404
+ return codeBlocks;
405
+ }
406
+
407
+ /**
408
+ * Extracts exactly ONE code block from markdown.
409
+ *
410
+ * Note: If there are multiple or no code blocks the function throws an error
411
+ *
412
+ * Note: There are 3 simmilar function:
413
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
414
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
415
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
416
+ *
417
+ * @param markdown any valid markdown
418
+ * @returns code block with language and content
419
+ */
420
+ function extractOneBlockFromMarkdown(markdown) {
421
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
422
+ if (codeBlocks.length !== 1) {
423
+ // TODO: Report more specific place where the error happened
424
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
425
+ }
426
+ return codeBlocks[0];
427
+ }
428
+ /***
429
+ * TODO: [🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
430
+ */
431
+
432
+ /**
433
+ * Removes HTML or Markdown comments from a string.
434
+ *
435
+ * @param {string} content - The string to remove comments from.
436
+ * @returns {string} The input string with all comments removed.
437
+ */
438
+ function removeContentComments(content) {
439
+ return spaceTrim__default["default"](content.replace(/<!--(.*?)-->/gs, ''));
440
+ }
441
+
442
+ /**
443
+ * The version of the Promptbook library
444
+ */
445
+ var PROMPTBOOK_VERSION = '0.41.0';
446
+
447
+ /**
448
+ * Parses the given script and returns the list of all used variables that are not defined in the script
449
+ *
450
+ * @param script from which to extract the variables
451
+ * @returns the list of variable names
452
+ *
453
+ * @private within the promptbookStringToJson
454
+ */
455
+ function extractVariables(script) {
456
+ var variables = [];
457
+ script = "(()=>{".concat(script, "})()");
458
+ try {
459
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
460
+ try {
461
+ eval(script);
462
+ }
463
+ catch (error) {
464
+ if (!(error instanceof ReferenceError)) {
465
+ throw error;
466
+ }
467
+ var undefinedName = error.message.split(' ')[0];
468
+ /*
469
+ Note: Remapping error
470
+ From: [ReferenceError: thing is not defined],
471
+ To: [Error: Parameter {thing} is not defined],
472
+ */
473
+ if (!undefinedName) {
474
+ throw error;
475
+ }
476
+ if (script.includes(undefinedName + '(')) {
477
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
478
+ }
479
+ else {
480
+ variables.push(undefinedName);
481
+ script = "const ".concat(undefinedName, " = '';") + script;
482
+ }
483
+ }
484
+ }
485
+ catch (error) {
486
+ if (!(error instanceof Error)) {
487
+ throw error;
488
+ }
489
+ 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 "); }));
490
+ }
491
+ return variables;
492
+ }
493
+
494
+ /**
495
+ * Execution type describes the way how the block is executed
496
+ *
497
+ * @see https://github.com/webgptorg/promptbook#execution-type
498
+ */
499
+ var ExecutionTypes = ['PROMPT_TEMPLATE', 'SIMPLE_TEMPLATE', 'SCRIPT', 'PROMPT_DIALOG'];
500
+
501
+ /**
502
+ * Units of text measurement
503
+ */
504
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'PARAGRAPHS', 'LINES', 'PAGES'];
505
+ /**
506
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
507
+ */
508
+
509
+ /**
510
+ * Removes Markdown formatting tags from a string.
511
+ *
512
+ * @param {string} str - The string to remove Markdown tags from.
513
+ * @returns {string} The input string with all Markdown tags removed.
514
+ */
515
+ function removeMarkdownFormatting(str) {
516
+ // Remove bold formatting
517
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
518
+ // Remove italic formatting
519
+ str = str.replace(/\*(.*?)\*/g, '$1');
520
+ // Remove code formatting
521
+ str = str.replace(/`(.*?)`/g, '$1');
522
+ return str;
523
+ }
524
+
108
525
  /**
109
526
  * Function parseNumber will parse number from string
110
527
  *
@@ -149,24 +566,741 @@
149
566
  }
150
567
  return numerator / denominator;
151
568
  }
152
- if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
153
- return 0;
569
+ if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
570
+ return 0;
571
+ }
572
+ if (value.includes('E')) {
573
+ var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
574
+ return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
575
+ }
576
+ if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
577
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
578
+ }
579
+ var num = parseFloat(value);
580
+ if (isNaN(num)) {
581
+ throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
582
+ }
583
+ return num;
584
+ }
585
+ /**
586
+ * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
587
+ */
588
+
589
+ /**
590
+ * Parses one line of ul/ol to command
591
+ *
592
+ * @private within the promptbookStringToJson
593
+ */
594
+ function parseCommand(listItem) {
595
+ var e_1, _a;
596
+ if (listItem.includes('\n') || listItem.includes('\r')) {
597
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
598
+ }
599
+ var type = listItem.trim();
600
+ type = type.split('`').join('');
601
+ type = type.split('"').join('');
602
+ type = type.split("'").join('');
603
+ type = type.split('~').join('');
604
+ type = type.split('[').join('');
605
+ type = type.split(']').join('');
606
+ type = type.split('(').join('');
607
+ type = type.split(')').join('');
608
+ type = n12.normalizeTo_SCREAMING_CASE(type);
609
+ type = type.split('DIALOGUE').join('DIALOG');
610
+ var listItemParts = listItem
611
+ .split(' ')
612
+ .map(function (part) { return part.trim(); })
613
+ .filter(function (item) { return item !== ''; })
614
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
615
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
616
+ .map(removeMarkdownFormatting);
617
+ if (type.startsWith('URL') ||
618
+ type.startsWith('PTBK_URL') ||
619
+ type.startsWith('PTBKURL') ||
620
+ type.startsWith('PROMPTBOOK_URL') ||
621
+ type.startsWith('PROMPTBOOKURL') ||
622
+ type.startsWith('HTTPS')) {
623
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
624
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
625
+ }
626
+ var promptbookUrlString = listItemParts.pop();
627
+ var promptbookUrl = new URL(promptbookUrlString);
628
+ if (promptbookUrl.protocol !== 'https:') {
629
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
630
+ }
631
+ if (promptbookUrl.hash !== '') {
632
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
633
+ }
634
+ return {
635
+ type: 'PROMPTBOOK_URL',
636
+ promptbookUrl: promptbookUrl,
637
+ };
638
+ }
639
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
640
+ if (listItemParts.length !== 2) {
641
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
642
+ }
643
+ var promptbookVersion = listItemParts.pop();
644
+ // TODO: Validate version
645
+ return {
646
+ type: 'PROMPTBOOK_VERSION',
647
+ promptbookVersion: promptbookVersion,
648
+ };
649
+ }
650
+ else if (type.startsWith('EXECUTE') ||
651
+ type.startsWith('EXEC') ||
652
+ type.startsWith('PROMPT_DIALOG') ||
653
+ type.startsWith('SIMPLE_TEMPLATE')) {
654
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
655
+ if (executionTypes.length !== 1) {
656
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
657
+ }
658
+ return {
659
+ type: 'EXECUTE',
660
+ executionType: executionTypes[0],
661
+ };
662
+ }
663
+ else if (type.startsWith('MODEL')) {
664
+ // TODO: Make this more elegant and dynamically
665
+ if (type.startsWith('MODEL_VARIANT')) {
666
+ if (type === 'MODEL_VARIANT_CHAT') {
667
+ return {
668
+ type: 'MODEL',
669
+ key: 'modelVariant',
670
+ value: 'CHAT',
671
+ };
672
+ }
673
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
674
+ return {
675
+ type: 'MODEL',
676
+ key: 'modelVariant',
677
+ value: 'COMPLETION',
678
+ };
679
+ }
680
+ else {
681
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
682
+ }
683
+ }
684
+ if (type.startsWith('MODEL_NAME')) {
685
+ return {
686
+ type: 'MODEL',
687
+ key: 'modelName',
688
+ value: listItemParts.pop(),
689
+ };
690
+ }
691
+ else {
692
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
693
+ }
694
+ }
695
+ else if (type.startsWith('PARAM') ||
696
+ type.startsWith('INPUT_PARAM') ||
697
+ type.startsWith('OUTPUT_PARAM') ||
698
+ listItem.startsWith('{') ||
699
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
700
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
701
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
702
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
703
+ }
704
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
705
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
706
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
707
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
708
+ }
709
+ var isInput = type.startsWith('INPUT');
710
+ var isOutput = type.startsWith('OUTPUT');
711
+ return {
712
+ type: 'PARAMETER',
713
+ parameterName: parameterName,
714
+ parameterDescription: parameterDescription.trim() || null,
715
+ isInput: isInput,
716
+ isOutput: isOutput,
717
+ };
718
+ }
719
+ else if (type.startsWith('JOKER')) {
720
+ if (listItemParts.length !== 2) {
721
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
722
+ }
723
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
724
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
725
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
726
+ }
727
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
728
+ var parameterName = parametersMatch.groups.parameterName;
729
+ return {
730
+ type: 'JOKER',
731
+ parameterName: parameterName,
732
+ };
733
+ }
734
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
735
+ if (listItemParts.length !== 2) {
736
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
737
+ }
738
+ var functionName = listItemParts.pop();
739
+ return {
740
+ type: 'POSTPROCESS',
741
+ functionName: functionName,
742
+ };
743
+ }
744
+ else if (type.startsWith('EXPECT_JSON')) {
745
+ return {
746
+ type: 'EXPECT_FORMAT',
747
+ format: 'JSON',
748
+ };
749
+ // [🥤]
750
+ }
751
+ else if (type.startsWith('EXPECT')) {
752
+ try {
753
+ listItemParts.shift();
754
+ var sign = void 0;
755
+ var signRaw = listItemParts.shift();
756
+ if (/^exact/i.test(signRaw)) {
757
+ sign = 'EXACTLY';
758
+ }
759
+ else if (/^min/i.test(signRaw)) {
760
+ sign = 'MINIMUM';
761
+ }
762
+ else if (/^max/i.test(signRaw)) {
763
+ sign = 'MAXIMUM';
764
+ }
765
+ else {
766
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\""));
767
+ }
768
+ var amountRaw = listItemParts.shift();
769
+ var amount = parseNumber(amountRaw);
770
+ if (amount < 0) {
771
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
772
+ }
773
+ if (amount !== Math.floor(amount)) {
774
+ throw new PromptbookSyntaxError('Amount must be whole number');
775
+ }
776
+ var unitRaw = listItemParts.shift();
777
+ var unit = undefined;
778
+ try {
779
+ for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
780
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
781
+ var existingUnitText = existingUnit;
782
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
783
+ if (existingUnitText === 'CHARACTER') {
784
+ existingUnitText = 'CHAR';
785
+ }
786
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
787
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
788
+ if (unit !== undefined) {
789
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
790
+ }
791
+ unit = existingUnit;
792
+ }
793
+ }
794
+ }
795
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
796
+ finally {
797
+ try {
798
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
799
+ }
800
+ finally { if (e_1) throw e_1.error; }
801
+ }
802
+ if (unit === undefined) {
803
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
804
+ }
805
+ return {
806
+ type: 'EXPECT_AMOUNT',
807
+ sign: sign,
808
+ unit: unit,
809
+ amount: amount,
810
+ };
811
+ }
812
+ catch (error) {
813
+ if (!(error instanceof Error)) {
814
+ throw error;
815
+ }
816
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
817
+ }
818
+ }
819
+ else {
820
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - Execute\n - Model\n - Parameter\n - INPUT PARAMETER\n - OUTPUT PARAMETER\n - PROMPTBOOK VERSION\n ")));
821
+ }
822
+ }
823
+
824
+ /**
825
+ * Parse promptbook from string format to JSON format
826
+ *
827
+ * Note: This function does not validate logic of the pipeline only the syntax
828
+ */
829
+ function promptbookStringToJson(promptbookString) {
830
+ var e_1, _a, e_2, _b;
831
+ var promptbookJson = {
832
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
833
+ title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
834
+ promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
835
+ promptbookVersion: PROMPTBOOK_VERSION,
836
+ description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
837
+ parameters: [],
838
+ promptTemplates: [],
839
+ };
840
+ // =============================================================
841
+ // Note: 1️⃣ Normalization of the PROMPTBOOK string
842
+ promptbookString = removeContentComments(promptbookString);
843
+ promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
844
+ promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
845
+ // =============================================================
846
+ ///Note: 2️⃣ Function for adding parameters
847
+ var addParam = function (parameterCommand) {
848
+ var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
849
+ var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
850
+ if (existingParameter &&
851
+ existingParameter.description &&
852
+ existingParameter.description !== parameterDescription &&
853
+ parameterDescription) {
854
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
855
+ }
856
+ if (existingParameter) {
857
+ if (parameterDescription) {
858
+ existingParameter.description = parameterDescription;
859
+ }
860
+ }
861
+ else {
862
+ promptbookJson.parameters.push({
863
+ name: parameterName,
864
+ description: parameterDescription || undefined,
865
+ isInput: isInput,
866
+ isOutput: isOutput,
867
+ });
868
+ }
869
+ };
870
+ // =============================================================
871
+ // Note: 3️⃣ Parse the dynamic part - the template pipeline
872
+ var markdownStructure = markdownToMarkdownStructure(promptbookString);
873
+ var markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
874
+ if (markdownStructureDeepness !== 2) {
875
+ throw new PromptbookSyntaxError(spaceTrim__default["default"]("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
876
+ }
877
+ promptbookJson.title = markdownStructure.title;
878
+ // TODO: [1] DRY description
879
+ var description = markdownStructure.content;
880
+ // Note: Remove codeblocks
881
+ description = description.split(/^```.*^```/gms).join('');
882
+ //Note: Remove lists and return statement
883
+ description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
884
+ description = spaceTrim__default["default"](description);
885
+ if (description === '') {
886
+ description = undefined;
887
+ }
888
+ promptbookJson.description = description;
889
+ var defaultModelRequirements = {};
890
+ var listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
891
+ try {
892
+ for (var listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
893
+ var listItem = listItems_1_1.value;
894
+ var command = parseCommand(listItem);
895
+ switch (command.type) {
896
+ case 'PROMPTBOOK_URL':
897
+ promptbookJson.promptbookUrl = command.promptbookUrl.href;
898
+ break;
899
+ case 'PROMPTBOOK_VERSION':
900
+ promptbookJson.promptbookVersion = command.promptbookVersion;
901
+ break;
902
+ case 'MODEL':
903
+ defaultModelRequirements[command.key] = command.value;
904
+ break;
905
+ case 'PARAMETER':
906
+ addParam(command);
907
+ break;
908
+ default:
909
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
910
+ }
911
+ }
912
+ }
913
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
914
+ finally {
915
+ try {
916
+ if (listItems_1_1 && !listItems_1_1.done && (_a = listItems_1.return)) _a.call(listItems_1);
917
+ }
918
+ finally { if (e_1) throw e_1.error; }
919
+ }
920
+ var _loop_1 = function (section) {
921
+ var e_3, _e, e_4, _f, e_5, _g;
922
+ // TODO: Parse prompt template description (the content out of the codeblock and lists)
923
+ var templateModelRequirements = __assign({}, defaultModelRequirements);
924
+ var listItems_3 = extractAllListItemsFromMarkdown(section.content);
925
+ var dependentParameterNames = [];
926
+ var executionType = 'PROMPT_TEMPLATE';
927
+ var jokers = [];
928
+ var postprocessing = [];
929
+ var expectAmount = {};
930
+ var expectFormat = undefined;
931
+ var isExecutionTypeChanged = false;
932
+ try {
933
+ for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
934
+ var listItem = listItems_2_1.value;
935
+ var command = parseCommand(listItem);
936
+ switch (command.type) {
937
+ case 'JOKER':
938
+ jokers.push(command.parameterName);
939
+ dependentParameterNames.push(command.parameterName);
940
+ break;
941
+ case 'EXECUTE':
942
+ if (isExecutionTypeChanged) {
943
+ throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
944
+ }
945
+ executionType = command.executionType;
946
+ isExecutionTypeChanged = true;
947
+ break;
948
+ case 'MODEL':
949
+ templateModelRequirements[command.key] = command.value;
950
+ break;
951
+ case 'PARAMETER':
952
+ // Note: This is just for detecting resulitng parameter name
953
+ addParam(command);
954
+ break;
955
+ case 'POSTPROCESS':
956
+ postprocessing.push(command.functionName);
957
+ break;
958
+ case 'EXPECT_AMOUNT':
959
+ // eslint-disable-next-line no-case-declarations
960
+ var unit = command.unit.toLowerCase();
961
+ expectAmount[unit] = expectAmount[unit] || {};
962
+ if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
963
+ if (expectAmount[unit].min !== undefined) {
964
+ throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
965
+ }
966
+ expectAmount[unit].min = command.amount;
967
+ } /* not else */
968
+ if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
969
+ if (expectAmount[unit].max !== undefined) {
970
+ throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
971
+ }
972
+ expectAmount[unit].max = command.amount;
973
+ }
974
+ break;
975
+ case 'EXPECT_FORMAT':
976
+ if (expectFormat !== undefined && command.format !== expectFormat) {
977
+ throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
978
+ }
979
+ expectFormat = command.format;
980
+ break;
981
+ default:
982
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
983
+ }
984
+ }
985
+ }
986
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
987
+ finally {
988
+ try {
989
+ if (listItems_2_1 && !listItems_2_1.done && (_e = listItems_2.return)) _e.call(listItems_2);
990
+ }
991
+ finally { if (e_3) throw e_3.error; }
992
+ }
993
+ var _h = extractOneBlockFromMarkdown(section.content), language = _h.language, content = _h.content;
994
+ if (executionType === 'SCRIPT') {
995
+ if (!language) {
996
+ throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
997
+ }
998
+ else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
999
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
1000
+ }
1001
+ }
1002
+ var lastLine = section.content.split('\n').pop();
1003
+ var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1004
+ if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1005
+ throw new PromptbookSyntaxError(spaceTrim__default["default"](function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1006
+ // TODO: Show code of invalid sections each time + DRY
1007
+ section.content
1008
+ .split('\n')
1009
+ .map(function (line) { return "> ".concat(line); })
1010
+ .join('\n')), "\n "); }));
1011
+ }
1012
+ var resultingParameterName = match.groups.resultingParamName;
1013
+ // TODO: [1] DRY description
1014
+ var description_1 = section.content;
1015
+ // Note: Remove codeblocks
1016
+ description_1 = description_1.split(/^```.*^```/gms).join('');
1017
+ //Note: Remove lists and return statement
1018
+ description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1019
+ description_1 = spaceTrim__default["default"](description_1);
1020
+ if (description_1 === '') {
1021
+ description_1 = undefined;
1022
+ }
1023
+ if (Object.keys(jokers).length === 0) {
1024
+ jokers = undefined;
1025
+ }
1026
+ if (Object.keys(expectAmount).length === 0) {
1027
+ expectAmount = undefined;
1028
+ }
1029
+ if (Object.keys(postprocessing).length === 0) {
1030
+ postprocessing = undefined;
1031
+ }
1032
+ try {
1033
+ for (var _j = (e_4 = void 0, __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(section.title)), false), __read(extractParameters(description_1 || '')), false), __read(extractParameters(content)), false))), _k = _j.next(); !_k.done; _k = _j.next()) {
1034
+ var parameterName = _k.value;
1035
+ dependentParameterNames.push(parameterName);
1036
+ }
1037
+ }
1038
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1039
+ finally {
1040
+ try {
1041
+ if (_k && !_k.done && (_f = _j.return)) _f.call(_j);
1042
+ }
1043
+ finally { if (e_4) throw e_4.error; }
1044
+ }
1045
+ if (executionType === 'SCRIPT') {
1046
+ try {
1047
+ for (var _l = (e_5 = void 0, __values(extractVariables(content))), _m = _l.next(); !_m.done; _m = _l.next()) {
1048
+ var parameterName = _m.value;
1049
+ dependentParameterNames.push(parameterName);
1050
+ }
1051
+ }
1052
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
1053
+ finally {
1054
+ try {
1055
+ if (_m && !_m.done && (_g = _l.return)) _g.call(_l);
1056
+ }
1057
+ finally { if (e_5) throw e_5.error; }
1058
+ }
1059
+ }
1060
+ dependentParameterNames = __spreadArray([], __read(new Set(dependentParameterNames)), false);
1061
+ promptbookJson.promptTemplates.push({
1062
+ name: n12.normalizeTo_PascalCase(section.title),
1063
+ title: section.title,
1064
+ description: description_1,
1065
+ dependentParameterNames: dependentParameterNames,
1066
+ executionType: executionType,
1067
+ jokers: jokers,
1068
+ postprocessing: postprocessing,
1069
+ expectAmount: expectAmount,
1070
+ expectFormat: expectFormat,
1071
+ modelRequirements: templateModelRequirements,
1072
+ contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1073
+ content: content,
1074
+ resultingParameterName: resultingParameterName,
1075
+ });
1076
+ };
1077
+ try {
1078
+ for (var _c = __values(markdownStructure.sections), _d = _c.next(); !_d.done; _d = _c.next()) {
1079
+ var section = _d.value;
1080
+ _loop_1(section);
1081
+ }
1082
+ }
1083
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1084
+ finally {
1085
+ try {
1086
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1087
+ }
1088
+ finally { if (e_2) throw e_2.error; }
1089
+ }
1090
+ // =============================================================
1091
+ return promptbookJson;
1092
+ }
1093
+ /**
1094
+ * TODO: Report here line/column of error
1095
+ * TODO: Use spaceTrim more effectively
1096
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1097
+ */
1098
+
1099
+ /**
1100
+ * Add or modify an auto-generated section in a markdown file
1101
+ *
1102
+ * @private within the library
1103
+ */
1104
+ function addAutoGeneratedSection(content, options) {
1105
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
1106
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1107
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1108
+ var sectionMatch = content.match(sectionRegex);
1109
+ if (sectionMatch) {
1110
+ return content.replace(sectionRegex, spaceTrim__default["default"](function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1111
+ }
1112
+ var placeForSection = content.match(/^##.*$/im);
1113
+ if (!placeForSection) {
1114
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
154
1115
  }
155
- if (value.includes('E')) {
156
- var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
157
- return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
1116
+ var _a = __read(placeForSection, 1), heading = _a[0];
1117
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1118
+ }
1119
+
1120
+ /**
1121
+ * Prettify the html code
1122
+ *
1123
+ * @param html raw html code
1124
+ * @returns formatted html code
1125
+ */
1126
+ function prettifyMarkdown(html) {
1127
+ try {
1128
+ return prettier.format(html, {
1129
+ parser: 'markdown',
1130
+ plugins: [parserHtml__default["default"]],
1131
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1132
+ endOfLine: 'lf',
1133
+ tabWidth: 4,
1134
+ singleQuote: true,
1135
+ trailingComma: 'all',
1136
+ arrowParens: 'always',
1137
+ printWidth: 120,
1138
+ htmlWhitespaceSensitivity: 'ignore',
1139
+ jsxBracketSameLine: false,
1140
+ bracketSpacing: true,
1141
+ });
158
1142
  }
159
- if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
160
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
1143
+ catch (error) {
1144
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1145
+ error: error,
1146
+ html: html,
1147
+ });
1148
+ return html;
161
1149
  }
162
- var num = parseFloat(value);
163
- if (isNaN(num)) {
164
- throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
1150
+ }
1151
+
1152
+ /**
1153
+ * !!!
1154
+ */
1155
+ function prettifyPromptbookString(promptbookString, options) {
1156
+ var isGraphAdded = options.isGraphAdded, isPrettifyed = options.isPrettifyed;
1157
+ if (isGraphAdded) {
1158
+ var promptbookJson_1 = promptbookStringToJson(promptbookString);
1159
+ var parameterNameToTemplateName_1 = function (parameterName) {
1160
+ var parameter = promptbookJson_1.parameters.find(function (parameter) { return parameter.name === parameterName; });
1161
+ if (!parameter) {
1162
+ throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
1163
+ }
1164
+ if (parameter.isInput) {
1165
+ return 'input';
1166
+ }
1167
+ var template = promptbookJson_1.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
1168
+ if (!template) {
1169
+ throw new Error("Could not find template for {".concat(parameterName, "}"));
1170
+ }
1171
+ return 'template' + n12.normalizeTo_PascalCase(template.title);
1172
+ };
1173
+ var promptbookMermaid_1 = spaceTrim__default["default"](function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson_1.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson_1.promptTemplates
1174
+ .flatMap(function (_a) {
1175
+ var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
1176
+ return __spreadArray([
1177
+ "".concat(parameterNameToTemplateName_1(resultingParameterName), "(").concat(title, ")")
1178
+ ], __read(dependentParameterNames.map(function (dependentParameterName) {
1179
+ return "".concat(parameterNameToTemplateName_1(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName_1(resultingParameterName));
1180
+ })), false);
1181
+ })
1182
+ .join('\n')), "\n\n ").concat(block(promptbookJson_1.parameters
1183
+ .filter(function (_a) {
1184
+ var isOutput = _a.isOutput;
1185
+ return isOutput;
1186
+ })
1187
+ .map(function (_a) {
1188
+ var name = _a.name;
1189
+ return "".concat(parameterNameToTemplateName_1(name), "--\"{").concat(name, "}\"-->output");
1190
+ })
1191
+ .join('\n')), "\n output((Output)):::output\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n\n\n "); });
1192
+ var promptbookMermaidBlock = spaceTrim__default["default"](function (block) { return "\n ```mermaid\n ".concat(block(promptbookMermaid_1), "\n ```\n "); });
1193
+ promptbookString = addAutoGeneratedSection(promptbookString, {
1194
+ sectionName: 'Graph',
1195
+ sectionContent: promptbookMermaidBlock,
1196
+ });
165
1197
  }
166
- return num;
1198
+ if (isPrettifyed) {
1199
+ promptbookString = prettifyMarkdown(promptbookString);
1200
+ }
1201
+ return promptbookString;
167
1202
  }
168
1203
  /**
169
- * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
1204
+ * TODO: [🧠] Should this be here OR in other folder
1205
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
1206
+ */
1207
+
1208
+ /**
1209
+ * Detects if the code is running in a browser environment in main thread (Not in a web worker)
1210
+ */
1211
+ new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1212
+ /**
1213
+ * Detects if the code is running in a Node.js environment
1214
+ */
1215
+ var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1216
+ /**
1217
+ * Detects if the code is running in a web worker
1218
+ */
1219
+ new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
1220
+
1221
+ /**
1222
+ * !!! Initialize
1223
+ */
1224
+ function prettifyPromptbookStringCli() {
1225
+ return __awaiter(this, void 0, void 0, function () {
1226
+ var program, filesGlob, filePaths, filePaths_1, filePaths_1_1, filePath, promptbookMarkdown, error_1, e_1_1;
1227
+ var e_1, _a;
1228
+ return __generator(this, function (_b) {
1229
+ switch (_b.label) {
1230
+ case 0:
1231
+ if (!isRunningInNode()) {
1232
+ throw new Error(spaceTrim__default["default"]("\n Function prettifyPromptbookStringCli is initiator of CLI script and should be run in Node.js environment.\n\n - In browser use prettifyPromptbookString.\n\n "));
1233
+ }
1234
+ program = new commander__default["default"].Command();
1235
+ program.version(PROMPTBOOK_VERSION);
1236
+ program.argument('<filesGlob>', 'Promptbooks to prettify');
1237
+ program.parse(process.argv);
1238
+ filesGlob = program.options.filesGlob;
1239
+ return [4 /*yield*/, glob__default["default"](filesGlob)];
1240
+ case 1:
1241
+ filePaths = _b.sent();
1242
+ _b.label = 2;
1243
+ case 2:
1244
+ _b.trys.push([2, 10, 11, 12]);
1245
+ filePaths_1 = __values(filePaths), filePaths_1_1 = filePaths_1.next();
1246
+ _b.label = 3;
1247
+ case 3:
1248
+ if (!!filePaths_1_1.done) return [3 /*break*/, 9];
1249
+ filePath = filePaths_1_1.value;
1250
+ if (!filePath.endsWith('.ptbk.md')) {
1251
+ console.warn(colors__default["default"].yellow("Skipping prettify of non-promptbook ".concat(filePath)));
1252
+ return [3 /*break*/, 8];
1253
+ }
1254
+ return [4 /*yield*/, promises.readFile(filePath, 'utf-8')];
1255
+ case 4:
1256
+ promptbookMarkdown = (_b.sent());
1257
+ _b.label = 5;
1258
+ case 5:
1259
+ _b.trys.push([5, 7, , 8]);
1260
+ promptbookMarkdown = prettifyPromptbookString(promptbookMarkdown, {
1261
+ isGraphAdded: true,
1262
+ isPrettifyed: true,
1263
+ // <- [🕌]
1264
+ });
1265
+ return [4 /*yield*/, promises.writeFile(filePath, promptbookMarkdown)];
1266
+ case 6:
1267
+ _b.sent();
1268
+ console.info(colors__default["default"].america("Prettify ".concat(filePath)));
1269
+ return [3 /*break*/, 8];
1270
+ case 7:
1271
+ error_1 = _b.sent();
1272
+ if (!(error_1 instanceof Error)) {
1273
+ throw error_1;
1274
+ }
1275
+ console.info(colors__default["default"].bgWhite('========================='));
1276
+ console.info(colors__default["default"].red("Prettify error ".concat(filePath)));
1277
+ console.error(colors__default["default"].bgRed(error_1.name));
1278
+ console.error(error_1);
1279
+ console.info(colors__default["default"].bgWhite('========================='));
1280
+ return [3 /*break*/, 8];
1281
+ case 8:
1282
+ filePaths_1_1 = filePaths_1.next();
1283
+ return [3 /*break*/, 3];
1284
+ case 9: return [3 /*break*/, 12];
1285
+ case 10:
1286
+ e_1_1 = _b.sent();
1287
+ e_1 = { error: e_1_1 };
1288
+ return [3 /*break*/, 12];
1289
+ case 11:
1290
+ try {
1291
+ if (filePaths_1_1 && !filePaths_1_1.done && (_a = filePaths_1.return)) _a.call(filePaths_1);
1292
+ }
1293
+ finally { if (e_1) throw e_1.error; }
1294
+ return [7 /*endfinally*/];
1295
+ case 12: return [2 /*return*/];
1296
+ }
1297
+ });
1298
+ });
1299
+ }
1300
+ /**
1301
+ * TODO: [🥠] Do not export to utils directly, its just for CLI script
1302
+ * TODO: [🌰] Use just prettifyPromptbookStringCli
1303
+ * Note: 11:11
170
1304
  */
171
1305
 
172
1306
  /**
@@ -340,38 +1474,6 @@
340
1474
  return value.replace(/```/g, '\\`\\`\\`');
341
1475
  }
342
1476
 
343
- /**
344
- * Prettify the html code
345
- *
346
- * @param html raw html code
347
- * @returns formatted html code
348
- */
349
- function prettifyMarkdown(html) {
350
- try {
351
- return prettier.format(html, {
352
- parser: 'markdown',
353
- plugins: [parserHtml__default["default"]],
354
- // TODO: DRY - make some import or auto-copy of .prettierrc
355
- endOfLine: 'lf',
356
- tabWidth: 4,
357
- singleQuote: true,
358
- trailingComma: 'all',
359
- arrowParens: 'always',
360
- printWidth: 120,
361
- htmlWhitespaceSensitivity: 'ignore',
362
- jsxBracketSameLine: false,
363
- bracketSpacing: true,
364
- });
365
- }
366
- catch (error) {
367
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
368
- error: error,
369
- html: html,
370
- });
371
- return html;
372
- }
373
- }
374
-
375
1477
  /**
376
1478
  * The thresholds for the relative time in the `moment` library.
377
1479
  *
@@ -659,152 +1761,6 @@
659
1761
  }
660
1762
  }
661
1763
 
662
- /**
663
- * Extracts all code blocks from markdown.
664
- *
665
- * Note: There are 3 simmilar function:
666
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
667
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
668
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
669
- *
670
- * @param markdown any valid markdown
671
- * @returns code blocks with language and content
672
- *
673
- */
674
- function extractAllBlocksFromMarkdown(markdown) {
675
- var e_1, _a;
676
- var codeBlocks = [];
677
- var lines = markdown.split('\n');
678
- var currentCodeBlock = null;
679
- try {
680
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
681
- var line = lines_1_1.value;
682
- if (line.startsWith('```')) {
683
- var language = line.slice(3).trim() || null;
684
- if (currentCodeBlock === null) {
685
- currentCodeBlock = { language: language, content: '' };
686
- }
687
- else {
688
- if (language !== null) {
689
- // [🌻]
690
- throw new Error("".concat(n12.capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
691
- }
692
- codeBlocks.push(currentCodeBlock);
693
- currentCodeBlock = null;
694
- }
695
- }
696
- else if (currentCodeBlock !== null) {
697
- if (currentCodeBlock.content !== '') {
698
- currentCodeBlock.content += '\n';
699
- }
700
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
701
- }
702
- }
703
- }
704
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
705
- finally {
706
- try {
707
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
708
- }
709
- finally { if (e_1) throw e_1.error; }
710
- }
711
- if (currentCodeBlock !== null) {
712
- // [🌻]
713
- throw new Error("".concat(n12.capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
714
- }
715
- return codeBlocks;
716
- }
717
-
718
- /**
719
- * Utility function to extract all list items from markdown
720
- *
721
- * Note: It works with both ul and ol
722
- * Note: It omits list items in code blocks
723
- * Note: It flattens nested lists
724
- * Note: It can not work with html syntax and comments
725
- *
726
- * @param markdown any valid markdown
727
- * @returns
728
- */
729
- function extractAllListItemsFromMarkdown(markdown) {
730
- var e_1, _a;
731
- var lines = markdown.split('\n');
732
- var listItems = [];
733
- var isInCodeBlock = false;
734
- try {
735
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
736
- var line = lines_1_1.value;
737
- var trimmedLine = line.trim();
738
- if (trimmedLine.startsWith('```')) {
739
- isInCodeBlock = !isInCodeBlock;
740
- }
741
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
742
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
743
- listItems.push(listItem);
744
- }
745
- }
746
- }
747
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
748
- finally {
749
- try {
750
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
751
- }
752
- finally { if (e_1) throw e_1.error; }
753
- }
754
- return listItems;
755
- }
756
-
757
- /**
758
- * Extracts exactly ONE code block from markdown.
759
- *
760
- * Note: If there are multiple or no code blocks the function throws an error
761
- *
762
- * Note: There are 3 simmilar function:
763
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
764
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
765
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
766
- *
767
- * @param markdown any valid markdown
768
- * @returns code block with language and content
769
- */
770
- function extractOneBlockFromMarkdown(markdown) {
771
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
772
- if (codeBlocks.length !== 1) {
773
- // TODO: Report more specific place where the error happened
774
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
775
- }
776
- return codeBlocks[0];
777
- }
778
- /***
779
- * TODO: [🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
780
- */
781
-
782
- /**
783
- * Removes HTML or Markdown comments from a string.
784
- *
785
- * @param {string} content - The string to remove comments from.
786
- * @returns {string} The input string with all comments removed.
787
- */
788
- function removeContentComments(content) {
789
- return spaceTrim__default["default"](content.replace(/<!--(.*?)-->/gs, ''));
790
- }
791
-
792
- /**
793
- * Removes Markdown formatting tags from a string.
794
- *
795
- * @param {string} str - The string to remove Markdown tags from.
796
- * @returns {string} The input string with all Markdown tags removed.
797
- */
798
- function removeMarkdownFormatting(str) {
799
- // Remove bold formatting
800
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
801
- // Remove italic formatting
802
- str = str.replace(/\*(.*?)\*/g, '$1');
803
- // Remove code formatting
804
- str = str.replace(/`(.*?)`/g, '$1');
805
- return str;
806
- }
807
-
808
1764
  /**
809
1765
  * Extracts code block from markdown.
810
1766
  *
@@ -945,8 +1901,20 @@
945
1901
  * TODO: [🧠] Should this also unwrap the (parenthesis)
946
1902
  */
947
1903
 
1904
+ /**
1905
+ * Hidden utilities which should not be used by external consumers.
1906
+ */
1907
+ var __ = {
1908
+ // Note: [🥠]
1909
+ prettifyPromptbookStringCli: prettifyPromptbookStringCli,
1910
+ };
1911
+ /**
1912
+ * TODO: [🧠] Maybe create some indipendent package like `markdown-tools` from both here exported and @private utilities
1913
+ */
1914
+
948
1915
  exports.CountUtils = CountUtils;
949
1916
  exports.ExecutionReportStringOptionsDefaults = ExecutionReportStringOptionsDefaults;
1917
+ exports.__ = __;
950
1918
  exports.assertsExecutionSuccessful = assertsExecutionSuccessful;
951
1919
  exports.countCharacters = countCharacters;
952
1920
  exports.countLines = countLines;
@@ -961,6 +1929,7 @@
961
1929
  exports.extractOneBlockFromMarkdown = extractOneBlockFromMarkdown;
962
1930
  exports.isValidJsonString = isValidJsonString;
963
1931
  exports.parseNumber = parseNumber;
1932
+ exports.prettifyPromptbookString = prettifyPromptbookString;
964
1933
  exports.removeContentComments = removeContentComments;
965
1934
  exports.removeEmojis = removeEmojis;
966
1935
  exports.removeMarkdownFormatting = removeMarkdownFormatting;