langium-tools 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1171 -0
  2. package/dist/base/arrays.d.ts +6 -0
  3. package/dist/base/arrays.js +34 -0
  4. package/dist/base/document-errors.d.ts +56 -0
  5. package/dist/base/document-errors.js +198 -0
  6. package/dist/base/document-issues.d.ts +178 -0
  7. package/dist/base/document-issues.js +306 -0
  8. package/dist/base/index.d.ts +4 -0
  9. package/dist/base/index.js +4 -0
  10. package/dist/base/marker-parser.d.ts +36 -0
  11. package/dist/base/marker-parser.js +51 -0
  12. package/dist/base/string.d.ts +89 -0
  13. package/dist/base/string.js +104 -0
  14. package/dist/generator/generated-content-manager.d.ts +207 -0
  15. package/dist/generator/generated-content-manager.js +242 -0
  16. package/dist/generator/index.d.ts +2 -0
  17. package/dist/generator/index.js +2 -0
  18. package/dist/generator/tools.d.ts +9 -0
  19. package/dist/generator/tools.js +12 -0
  20. package/dist/index.d.ts +4 -0
  21. package/dist/index.js +4 -0
  22. package/dist/lang/index.d.ts +1 -0
  23. package/dist/lang/index.js +1 -0
  24. package/dist/lang/java/common.d.ts +1 -0
  25. package/dist/lang/java/common.js +3 -0
  26. package/dist/lang/java/generator-tools.d.ts +37 -0
  27. package/dist/lang/java/generator-tools.js +48 -0
  28. package/dist/lang/java/import-manager.d.ts +61 -0
  29. package/dist/lang/java/import-manager.js +88 -0
  30. package/dist/lang/java/index.d.ts +3 -0
  31. package/dist/lang/java/index.js +3 -0
  32. package/dist/testing/common.d.ts +1 -0
  33. package/dist/testing/common.js +5 -0
  34. package/dist/testing/generator-testing.d.ts +56 -0
  35. package/dist/testing/generator-testing.js +184 -0
  36. package/dist/testing/index.d.ts +4 -0
  37. package/dist/testing/index.js +4 -0
  38. package/dist/testing/matchers.d.ts +209 -0
  39. package/dist/testing/matchers.js +306 -0
  40. package/dist/testing/parser-tools.d.ts +19 -0
  41. package/dist/testing/parser-tools.js +18 -0
  42. package/package.json +59 -0
  43. package/src/base/arrays.ts +40 -0
  44. package/src/base/document-issues.ts +430 -0
  45. package/src/base/index.ts +4 -0
  46. package/src/base/marker-parser.ts +96 -0
  47. package/src/base/string.ts +117 -0
  48. package/src/generator/generated-content-manager.ts +368 -0
  49. package/src/generator/index.ts +2 -0
  50. package/src/generator/tools.ts +14 -0
  51. package/src/index.ts +5 -0
  52. package/src/lang/index.ts +1 -0
  53. package/src/lang/java/common.ts +4 -0
  54. package/src/lang/java/generator-tools.ts +59 -0
  55. package/src/lang/java/import-manager.ts +98 -0
  56. package/src/lang/java/index.ts +3 -0
  57. package/src/testing/common.ts +5 -0
  58. package/src/testing/generator-testing.ts +266 -0
  59. package/src/testing/index.ts +4 -0
  60. package/src/testing/matchers.ts +503 -0
  61. package/src/testing/parser-tools.ts +34 -0
@@ -0,0 +1,430 @@
1
+ import "./string.js";
2
+ import { LangiumDocument } from "langium";
3
+ import { DiagnosticSeverity } from "vscode-languageserver";
4
+ import type { IToken } from 'chevrotain';
5
+ import { EOL } from "node:os";
6
+
7
+ /**
8
+ * Represents the source of a document issue.
9
+ *
10
+ * - `LEXER`: Issues originating from the lexer (tokenization errors).
11
+ * - `PARSER`: Issues originating from the parser (syntax errors).
12
+ * - `VALIDATION`: Issues originating from validation (semantic errors).
13
+ */
14
+ export enum DocumentIssueSource {
15
+ LEXER = "LEXER",
16
+ PARSER = "PARSER",
17
+ VALIDATION = "VALIDATION",
18
+ }
19
+
20
+ /**
21
+ * Represents the severity level of a document issue.
22
+ *
23
+ * - `ERROR`: Critical issue that prevents further processing.
24
+ * - `WARNING`: Issue that may lead to problems but does not prevent processing.
25
+ * - `INFORMATION`: Informational message.
26
+ * - `HINT`: Suggestion to improve the document.
27
+ * - `UNKNOWN`: Severity is unknown.
28
+ */
29
+ export enum DocumentIssueSeverity {
30
+ ERROR = "ERROR",
31
+ WARNING = "WARNING",
32
+ INFORMATION = "INFO",
33
+ HINT = "HINT",
34
+ UNKNOWN = "-"
35
+ }
36
+
37
+ /**
38
+ * Represents an issue in a document, such as a syntax error or a validation issue.
39
+ * The issue can be associated with a specific source, such as the lexer, parser, or validation.
40
+ */
41
+ export type DocumentIssue = {
42
+ /** The source of the issue (lexer, parser, or validation). */
43
+ source: DocumentIssueSource;
44
+ /** The severity level of the issue. */
45
+ severity: DocumentIssueSeverity;
46
+ /** The message describing the issue. */
47
+ message: string;
48
+ /**
49
+ * 0-based absolute position of the beginning of the marker
50
+ */
51
+ startOffset?: number,
52
+
53
+ /**
54
+ * 0-based line number of the beginning of the marker
55
+ */
56
+ startLine?: number,
57
+ /**
58
+ * 0-based column of the beginning of the marker
59
+ */
60
+ startColumn?: number,
61
+
62
+ /**
63
+ * 0-based absolute position of the character _after_ the end of the marker.
64
+ * (0-based position of the last character + 1)
65
+ *
66
+ * This allows representation of the 0-length markers as "startPos == endPos".
67
+ * In this case endLine and endColumn should be ignored.
68
+ */
69
+ endOffset?: number,
70
+ /**
71
+ * 0-based line of the end of the marker
72
+ */
73
+ endLine?: number,
74
+ /**
75
+ * 0-based Position of the character _after_ the end of the marker.
76
+ * (1-based position of the last character + 1)
77
+ */
78
+ endColumn?: number,
79
+ };
80
+
81
+ /**
82
+ * Represents a summary of document issues.
83
+ *
84
+ * Contains counts of errors and non-error issues, as well as formatted summary and message strings.
85
+ */
86
+ export type DocumentIssueSummary = {
87
+ /** Total number of issues found in the document. */
88
+ countTotal: number;
89
+ /** Number of issues with severity `ERROR`. */
90
+ countErrors: number;
91
+ /** Number of issues with severity other than `ERROR`. */
92
+ countNonErrors: number;
93
+ /** A brief summary string of the issues. */
94
+ summary: string;
95
+ /** A detailed message string listing all issues. */
96
+ message: string;
97
+ };
98
+
99
+ /**
100
+ * Parameters for filtering document issues.
101
+ */
102
+ export interface GetDocumentIssuesParams {
103
+ /**
104
+ * If `true`, non-error diagnostics (warnings, information, hints) are skipped.
105
+ * Defaults to `false`.
106
+ */
107
+ skipNonErrorDiagnostics?: boolean;
108
+
109
+ /**
110
+ * If `true`, lexer errors are skipped.
111
+ * Defaults to `false`.
112
+ */
113
+ skipLexerErrors?: boolean;
114
+
115
+ /**
116
+ * If `true`, parser errors are skipped.
117
+ * Defaults to `false`.
118
+ */
119
+ skipParserErrors?: boolean;
120
+
121
+ /**
122
+ * If `true`, validation issues are skipped.
123
+ * Defaults to `false`.
124
+ */
125
+ skipValidation?: boolean;
126
+ }
127
+
128
+ /**
129
+ * Maps a `DiagnosticSeverity` from the language server protocol to a `DocumentIssueSeverity`.
130
+ *
131
+ * @param severity - The `DiagnosticSeverity` to map.
132
+ * @returns The corresponding `DocumentIssueSeverity`.
133
+ */
134
+ function mapSeverity(severity?: DiagnosticSeverity): DocumentIssueSeverity {
135
+ if (!severity) {
136
+ return DocumentIssueSeverity.UNKNOWN;
137
+ }
138
+ switch (severity) {
139
+ case DiagnosticSeverity.Error:
140
+ return DocumentIssueSeverity.ERROR;
141
+ case DiagnosticSeverity.Warning:
142
+ return DocumentIssueSeverity.WARNING;
143
+ case DiagnosticSeverity.Information:
144
+ return DocumentIssueSeverity.INFORMATION;
145
+ case DiagnosticSeverity.Hint:
146
+ return DocumentIssueSeverity.HINT;
147
+ default:
148
+ throw new Error(`Unknown DiagnosticSeverity: ${severity}`);
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Retrieves all issues from a Langium document, optionally filtering based on provided parameters.
154
+ *
155
+ * @param document - The Langium document to extract issues from.
156
+ * @param params - Optional parameters to filter issues.
157
+ * @returns An array of `DocumentIssue` representing the issues in the document.
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const issues = getDocumentIssues(document, { skipNonErrorDiagnostics: true });
162
+ * ```
163
+ */
164
+ export function getDocumentIssues(
165
+ document: LangiumDocument,
166
+ params?: GetDocumentIssuesParams
167
+ ): DocumentIssue[] {
168
+ const {
169
+ skipNonErrorDiagnostics = false,
170
+ skipLexerErrors = false,
171
+ skipParserErrors = false,
172
+ skipValidation = false,
173
+ } = params || {};
174
+
175
+ const issues: DocumentIssue[] = [];
176
+ if (!skipLexerErrors) {
177
+ document.parseResult.lexerErrors.forEach((lexerIssue) => {
178
+ issues.push({
179
+ source: DocumentIssueSource.LEXER,
180
+ message: lexerIssue.message,
181
+ severity: DocumentIssueSeverity.ERROR,
182
+ startOffset: lexerIssue.offset,
183
+ startLine: plus(lexerIssue.line, -1),
184
+ startColumn: plus(lexerIssue.column, -1),
185
+ });
186
+ });
187
+ }
188
+
189
+ if (!skipParserErrors) {
190
+ document.parseResult.parserErrors.forEach((parserError) => {
191
+ // Try to get the previous token from the internal Chevrotain structure to get a better position
192
+ const previousToken = (parserError as unknown as { previousToken: IToken })?.previousToken as IToken;
193
+ issues.push({
194
+ source: DocumentIssueSource.PARSER,
195
+ severity: DocumentIssueSeverity.ERROR,
196
+ message: parserError.message,
197
+ startOffset: firstDefinedNumber(parserError.token.startOffset, previousToken?.startOffset),
198
+ startLine: plus(firstDefinedNumber(parserError.token.startLine, previousToken?.startLine), -1),
199
+ startColumn: plus(firstDefinedNumber(parserError.token.startColumn, previousToken?.startColumn), -1),
200
+
201
+ // Unrelieable end position returned by Chevrotain (24.09.2024)
202
+ // endOffset: firstDefinedNumber(parserError.token.endOffset, previousToken?.endOffset),
203
+ // endLine: plus(firstDefinedNumber(parserError.token.endLine, previousToken?.endLine), -1),
204
+ // endColumn: plus(firstDefinedNumber(parserError.token.endColumn, previousToken?.endColumn), 1),
205
+ });
206
+ });
207
+ }
208
+
209
+ if (!skipValidation) {
210
+ document.diagnostics?.forEach((diagnostic) => {
211
+ if (!skipNonErrorDiagnostics || diagnostic.severity === DiagnosticSeverity.Error) {
212
+ issues.push({
213
+ source: DocumentIssueSource.VALIDATION,
214
+ severity: mapSeverity(diagnostic.severity),
215
+ message: diagnostic.message,
216
+ startLine: diagnostic.range.start.line,
217
+ startColumn: diagnostic.range.start.character,
218
+ endLine: diagnostic.range.end.line,
219
+ endColumn: diagnostic.range.end.character,
220
+ });
221
+ }
222
+ });
223
+ }
224
+
225
+ return issues;
226
+ }
227
+
228
+ /**
229
+ * Generates a summary of issues in a Langium document.
230
+ *
231
+ * @param document - The Langium document to summarize issues from.
232
+ * @param params - Optional parameters to filter issues.
233
+ * @returns A `DocumentIssueSummary` containing counts and formatted messages.
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * const summary = getDocumentIssueSummary(document);
238
+ * console.log(summary.summary);
239
+ * console.log(summary.message);
240
+ * ```
241
+ */
242
+ export function getDocumentIssueSummary(
243
+ document: LangiumDocument,
244
+ params?: GetDocumentIssuesParams
245
+ ): DocumentIssueSummary {
246
+ const issues = getDocumentIssues(document, params);
247
+ return getDocumentIssueSummaryFromIssues(issues);
248
+ }
249
+
250
+ /**
251
+ * Generates a summary of issues from a list of `DocumentIssue`.
252
+ *
253
+ * @param issues - An array of `DocumentIssue`.
254
+ * @returns A `DocumentIssueSummary` containing counts and formatted messages.
255
+ *
256
+ * @example
257
+ * ```typescript
258
+ * const issues: DocumentIssue[] = [ ... ];
259
+ * const summary = getDocumentIssueSummaryFromIssues(issues);
260
+ * console.log(summary.summary);
261
+ * console.log(summary.message);
262
+ * ```
263
+ */
264
+ export function getDocumentIssueSummaryFromIssues(
265
+ issues: DocumentIssue[]
266
+ ): DocumentIssueSummary {
267
+ let countErrors = 0;
268
+ let countNonErrors = 0;
269
+ const messageList: string[] = [];
270
+ const summaryList: string[] = [];
271
+
272
+ const issueSourceMap = new Map<DocumentIssueSource, string[]>();
273
+ for (const issue of issues) {
274
+ if (issue.severity === DocumentIssueSeverity.ERROR) {
275
+ countErrors += 1;
276
+ } else {
277
+ countNonErrors += 1;
278
+ }
279
+ if (!issueSourceMap.has(issue.source)) {
280
+ issueSourceMap.set(issue.source, []);
281
+ }
282
+ issueSourceMap.get(issue.source)!.push(documentIssueToString(issue));
283
+ }
284
+
285
+ for (const source of [
286
+ DocumentIssueSource.LEXER,
287
+ DocumentIssueSource.PARSER,
288
+ DocumentIssueSource.VALIDATION,
289
+ ]) {
290
+ const issueList = issueSourceMap.get(source);
291
+ if (issueList) {
292
+ if (source === DocumentIssueSource.VALIDATION) {
293
+ const summaryParts: string[] = [];
294
+ if (issueList.length > countNonErrors) {
295
+ summaryParts.push(`${issueList.length - countNonErrors} error diagnostic(s)`);
296
+ }
297
+ if (countNonErrors > 0) {
298
+ summaryParts.push(`${countNonErrors} non-error diagnostic(s)`);
299
+ }
300
+ summaryList.push(summaryParts.join(', '));
301
+ } else {
302
+ summaryList.push(`${issueList.length} ${source.toLowerCase()} error(s)`);
303
+ }
304
+ const sourceName = (source === DocumentIssueSource.VALIDATION) ? "diagnostics" : `${source.toLowerCase()} errors`;
305
+ messageList.push(`${sourceName.toFirstUpper()}:`);
306
+ messageList.push(...issueList);
307
+ }
308
+ }
309
+
310
+ if (summaryList.length === 0) {
311
+ summaryList.push('No errors');
312
+ }
313
+
314
+ const summaryString = summaryList.join(', ');
315
+ if (messageList.length > 0) {
316
+ messageList.push('');
317
+ messageList.push(summaryString);
318
+ }
319
+ const messageString = messageList.join(EOL);
320
+ return {
321
+ countTotal: countErrors + countNonErrors,
322
+ countErrors: countErrors,
323
+ countNonErrors: countNonErrors,
324
+ summary: summaryString,
325
+ message: messageString,
326
+ };
327
+ }
328
+
329
+ /**
330
+ * Converts a `DocumentIssue` to a formatted string.
331
+ *
332
+ * @param issue - The `DocumentIssue` to format.
333
+ * @returns A string representation of the issue.
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * const issue: DocumentIssue = { ... };
338
+ * const issueStr = documentIssueToString(issue);
339
+ * console.log(issueStr);
340
+ * ```
341
+ */
342
+ export function documentIssueToString(issue: DocumentIssue): string {
343
+ const severity = issue.severity.toLowerCase().toFirstUpper();
344
+ return `${severity}${at(issue)} - ${issue.message}`;
345
+ }
346
+
347
+ /**
348
+ * Converts a `DiagnosticSeverity` to a string representation.
349
+ *
350
+ * @param severity - The `DiagnosticSeverity` to convert.
351
+ * @returns A string representing the severity.
352
+ */
353
+ export function severityToString(
354
+ severity: DiagnosticSeverity | number | undefined
355
+ ): string {
356
+ switch (severity) {
357
+ case DiagnosticSeverity.Error:
358
+ return 'Error';
359
+ case DiagnosticSeverity.Warning:
360
+ return 'Warning';
361
+ case DiagnosticSeverity.Information:
362
+ return 'Information';
363
+ case DiagnosticSeverity.Hint:
364
+ return 'Hint';
365
+ default:
366
+ return 'Unknown';
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Formats the position information of a `DocumentIssue`.
372
+ *
373
+ * @param issue - The `DocumentIssue` containing position information.
374
+ * @returns A formatted string representing the position (e.g., " at 4:13-20").
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const positionStr = at(issue);
379
+ * console.log(positionStr); // Output: " at 4:13-20"
380
+ * ```
381
+ */
382
+ function at(issue: DocumentIssue): string {
383
+ let result = '';
384
+ if (issue.startLine !== undefined && !isNaN(issue.startLine)) {
385
+ result += ` at ${issue.startLine + 1}`;
386
+ if (issue.startColumn !== undefined && !isNaN(issue.startColumn)) {
387
+ result += `:${issue.startColumn + 1}`;
388
+ if (
389
+ issue.endLine !== undefined &&
390
+ !isNaN(issue.endLine) &&
391
+ issue.endColumn !== undefined &&
392
+ !isNaN(issue.endColumn)
393
+ ) {
394
+ if (issue.startLine !== issue.endLine) {
395
+ result += `-${issue.endLine + 1}:${issue.endColumn}`;
396
+ } else {
397
+ result += `-${issue.endColumn}`;
398
+ }
399
+ }
400
+ }
401
+ }
402
+ return result;
403
+ }
404
+
405
+ /**
406
+ * Returns the first meaningful (non-null, non-NaN) value from two options.
407
+ *
408
+ * @param a - The first number to consider.
409
+ * @param b - The second number to consider.
410
+ * @returns The first meaningful number, or `undefined` if both are `null` or `NaN`.
411
+ */
412
+ function firstDefinedNumber(a?: number, b?: number): number | undefined {
413
+ if (a != null && !Number.isNaN(a)) {
414
+ return a;
415
+ }
416
+ if (b != null && !Number.isNaN(b)) {
417
+ return b;
418
+ }
419
+ return undefined;
420
+ }
421
+
422
+ /**
423
+ * Add two numbers, returning `undefined` if either is `null` or `undefined`.
424
+ */
425
+ function plus(a?: number, b?: number): number | undefined {
426
+ if (a != null && b != null) {
427
+ return a + b;
428
+ }
429
+ return undefined;
430
+ }
@@ -0,0 +1,4 @@
1
+ export * from './string.js';
2
+ export * from './document-issues.js';
3
+ export * from './marker-parser.js';
4
+ export * from './arrays.js';
@@ -0,0 +1,96 @@
1
+ import escapeStringRegexp from "escape-string-regexp";
2
+
3
+ export type MarkerPosition = {
4
+ /**
5
+ * 0-based absolute position of the beginning of the marker
6
+ */
7
+ startOffset: number,
8
+
9
+ /**
10
+ * 0-based line number of the beginning of the marker
11
+ */
12
+ startLine: number,
13
+ /**
14
+ * 0-based column of the beginning of the marker
15
+ */
16
+ startColumn: number,
17
+
18
+ /**
19
+ * 0-based absolute position of the character _after_ the end of the marker.
20
+ * (0-based position of the last character + 1)
21
+ *
22
+ * This allows representation of the 0-length markers as "startPos == endPos".
23
+ * In this case endLine and endColumn should be ignored.
24
+ */
25
+ endOffset: number,
26
+ /**
27
+ * 0-based line of the end of the marker
28
+ */
29
+ endLine: number,
30
+ /**
31
+ * 0-based Position of the character _after_ the end of the marker.
32
+ * (1-based position of the last character + 1)
33
+ */
34
+ endColumn: number,
35
+ }
36
+
37
+ export type ParseMarkedTextResult = {
38
+ text: string,
39
+ markers: Array<MarkerPosition>
40
+ }
41
+
42
+ export function parseMarkedText(text: string, beginMarker: string = "<<{|", endMarker: string = "|}>>"): ParseMarkedTextResult {
43
+ const tokenRegex = new RegExp(`(${escapeStringRegexp(beginMarker)})|(${escapeStringRegexp(endMarker)})|(\r?\n)`, 'g');
44
+ const TOKEN_BEGIN_MARKER = 1;
45
+ const TOKEN_END_MERKER = 2;
46
+ const TOKEN_LN = 3;
47
+
48
+ const positions: MarkerPosition[] = [];
49
+ const originalParts: string[] = [];
50
+ let openMarker: { line: number; column: number; pos: number } | null = null;
51
+
52
+ let lastIndex = 0;
53
+ let currentColumn = 0;
54
+ let currentLine = 0;
55
+ let currentPos = 0;
56
+
57
+ let match;
58
+ while ((match = tokenRegex.exec(text))) {
59
+ currentColumn += match.index - lastIndex;
60
+ currentPos += match.index - lastIndex;
61
+ originalParts.push(text.slice(lastIndex, match.index));
62
+ lastIndex = tokenRegex.lastIndex;
63
+
64
+ if (match[TOKEN_BEGIN_MARKER] && !openMarker) {
65
+ openMarker = {
66
+ line: currentLine,
67
+ column: currentColumn,
68
+ pos: currentPos
69
+ };
70
+ }
71
+ if (match[TOKEN_END_MERKER] && openMarker) {
72
+ positions.push({
73
+ startOffset: openMarker.pos,
74
+ startLine: openMarker.line,
75
+ startColumn: openMarker.column,
76
+ endOffset: currentPos,
77
+ endLine: currentLine,
78
+ endColumn: currentColumn,
79
+ });
80
+ openMarker = null;
81
+ }
82
+ if (match[TOKEN_LN]) {
83
+ currentLine += 1;
84
+ currentColumn = 0;
85
+ // Add token to output
86
+ currentPos += tokenRegex.lastIndex - match.index;
87
+ originalParts.push(text.slice(match.index, tokenRegex.lastIndex));
88
+ }
89
+ }
90
+ originalParts.push(text.slice(lastIndex));
91
+
92
+ return {
93
+ text: originalParts.join(""),
94
+ markers: positions
95
+ };
96
+ }
@@ -0,0 +1,117 @@
1
+ import { expandToNode, toString } from "langium/generate";
2
+
3
+ /**
4
+ * Converts the first character of a string to upper case.
5
+ * Example: "hello" -> "Hello"
6
+ *
7
+ * @param s The string to convert.
8
+ * @returns The converted string.
9
+ */
10
+ export function toFirstUpper<T extends string | undefined>(s: T): T {
11
+ if (s === undefined) {
12
+ return undefined as T;
13
+ }
14
+ return s.charAt(0).toUpperCase() + s.slice(1) as T;
15
+ }
16
+
17
+ /**
18
+ * Converts the first character of a string to upper case.
19
+ * Example: "hello" -> "Hello"
20
+ *
21
+ * @param s The string to convert.
22
+ * @returns The converted string.
23
+ */
24
+ export function toFirstLower<T extends string | undefined>(s: T): T {
25
+ if (s === undefined) {
26
+ return undefined as T;
27
+ }
28
+ return s.charAt(0).toLowerCase() + s.slice(1) as T;
29
+ }
30
+
31
+ declare global {
32
+ interface String {
33
+ toFirstUpper(): string;
34
+ toFirstLower(): string;
35
+ }
36
+ }
37
+
38
+ String.prototype.toFirstUpper = function (): string {
39
+ return toFirstUpper(this as string);
40
+ };
41
+ String.prototype.toFirstLower = function (): string {
42
+ return toFirstLower(this as string);
43
+ };
44
+
45
+ /**
46
+ * Formats a multi-line template literal by adjusting indentation and preserving line breaks.
47
+ *
48
+ * This function ensures consistent formatting of multi-line strings, which is particularly
49
+ * useful for defining code blocks or text outputs. It uses Platform newlines (e.g. `\r\n` on Windows).
50
+ *
51
+ * The indentation of dynamically inserted placeholders (`${...}`) will be adjusted to match
52
+ * the indentation level of the placeholder itself. This feature is especially useful for code
53
+ * generation scenarios, where nested structures or varying indentation levels are needed.
54
+ *
55
+ * ### Example
56
+ * ```typescript
57
+ * const text = adjusted`
58
+ * ${cmds}
59
+ * if (sayAgain) {
60
+ * ${cmds}
61
+ * }
62
+ * `;
63
+ *
64
+ * // Output (without `|`):
65
+ * // |console.log('Hello,');
66
+ * // |console.log('World!');
67
+ * // |if (sayAgain) {
68
+ * // | console.log('Hello,');
69
+ * // | console.log('World!');
70
+ * // |}
71
+ * ```
72
+ *
73
+ * @param staticParts The static (literal) parts of the template string.
74
+ * @param substitutions The dynamic parts of the template string, which will be injected into the corresponding placeholders in `staticParts`.
75
+ * @returns A formatted string with fixed indentation and Unix-style line breaks (`\n`), without carriage return characters (`\r`).
76
+ */
77
+ export function adjusted(staticParts: TemplateStringsArray, ...substitutions: unknown[]): string {
78
+ return toString(expandToNode(staticParts, ...substitutions));
79
+ }
80
+
81
+
82
+ /**
83
+ * Formats a multi-line template literal by adjusting indentation and preserving line breaks.
84
+ *
85
+ * This function ensures consistent formatting of multi-line strings, which is particularly
86
+ * useful for defining code blocks or text outputs. It uses Unix-style newlines (`\n`), making
87
+ * it system independent.
88
+ *
89
+ * The indentation of dynamically inserted placeholders (`${...}`) will be adjusted to match
90
+ * the indentation level of the placeholder itself. This feature is especially useful for code
91
+ * generation scenarios, where nested structures or varying indentation levels are needed.
92
+ *
93
+ * ### Example
94
+ * ```typescript
95
+ * const text = adjusted`
96
+ * ${cmds}
97
+ * if (sayAgain) {
98
+ * ${cmds}
99
+ * }
100
+ * `;
101
+ *
102
+ * // Output (without `|`):
103
+ * // |console.log('Hello,');
104
+ * // |console.log('World!');
105
+ * // |if (sayAgain) {
106
+ * // | console.log('Hello,');
107
+ * // | console.log('World!');
108
+ * // |}
109
+ * ```
110
+ *
111
+ * @param staticParts The static (literal) parts of the template string.
112
+ * @param substitutions The dynamic parts of the template string, which will be injected into the corresponding placeholders in `staticParts`.
113
+ * @returns A formatted string with fixed indentation and Unix-style line breaks (`\n`), without carriage return characters (`\r`).
114
+ */
115
+ export function adjustedUnix(staticParts: TemplateStringsArray, ...substitutions: unknown[]): string {
116
+ return adjusted(staticParts, substitutions).replace(/\r/g, '');
117
+ }