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,306 @@
1
+ import "./string.js";
2
+ import { DiagnosticSeverity } from "vscode-languageserver";
3
+ import { EOL } from "node:os";
4
+ /**
5
+ * Represents the source of a document issue.
6
+ *
7
+ * - `LEXER`: Issues originating from the lexer (tokenization errors).
8
+ * - `PARSER`: Issues originating from the parser (syntax errors).
9
+ * - `VALIDATION`: Issues originating from validation (semantic errors).
10
+ */
11
+ export var DocumentIssueSource;
12
+ (function (DocumentIssueSource) {
13
+ DocumentIssueSource["LEXER"] = "LEXER";
14
+ DocumentIssueSource["PARSER"] = "PARSER";
15
+ DocumentIssueSource["VALIDATION"] = "VALIDATION";
16
+ })(DocumentIssueSource || (DocumentIssueSource = {}));
17
+ /**
18
+ * Represents the severity level of a document issue.
19
+ *
20
+ * - `ERROR`: Critical issue that prevents further processing.
21
+ * - `WARNING`: Issue that may lead to problems but does not prevent processing.
22
+ * - `INFORMATION`: Informational message.
23
+ * - `HINT`: Suggestion to improve the document.
24
+ * - `UNKNOWN`: Severity is unknown.
25
+ */
26
+ export var DocumentIssueSeverity;
27
+ (function (DocumentIssueSeverity) {
28
+ DocumentIssueSeverity["ERROR"] = "ERROR";
29
+ DocumentIssueSeverity["WARNING"] = "WARNING";
30
+ DocumentIssueSeverity["INFORMATION"] = "INFO";
31
+ DocumentIssueSeverity["HINT"] = "HINT";
32
+ DocumentIssueSeverity["UNKNOWN"] = "-";
33
+ })(DocumentIssueSeverity || (DocumentIssueSeverity = {}));
34
+ /**
35
+ * Maps a `DiagnosticSeverity` from the language server protocol to a `DocumentIssueSeverity`.
36
+ *
37
+ * @param severity - The `DiagnosticSeverity` to map.
38
+ * @returns The corresponding `DocumentIssueSeverity`.
39
+ */
40
+ function mapSeverity(severity) {
41
+ if (!severity) {
42
+ return DocumentIssueSeverity.UNKNOWN;
43
+ }
44
+ switch (severity) {
45
+ case DiagnosticSeverity.Error:
46
+ return DocumentIssueSeverity.ERROR;
47
+ case DiagnosticSeverity.Warning:
48
+ return DocumentIssueSeverity.WARNING;
49
+ case DiagnosticSeverity.Information:
50
+ return DocumentIssueSeverity.INFORMATION;
51
+ case DiagnosticSeverity.Hint:
52
+ return DocumentIssueSeverity.HINT;
53
+ default:
54
+ throw new Error(`Unknown DiagnosticSeverity: ${severity}`);
55
+ }
56
+ }
57
+ /**
58
+ * Retrieves all issues from a Langium document, optionally filtering based on provided parameters.
59
+ *
60
+ * @param document - The Langium document to extract issues from.
61
+ * @param params - Optional parameters to filter issues.
62
+ * @returns An array of `DocumentIssue` representing the issues in the document.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const issues = getDocumentIssues(document, { skipNonErrorDiagnostics: true });
67
+ * ```
68
+ */
69
+ export function getDocumentIssues(document, params) {
70
+ var _a;
71
+ const { skipNonErrorDiagnostics = false, skipLexerErrors = false, skipParserErrors = false, skipValidation = false, } = params || {};
72
+ const issues = [];
73
+ if (!skipLexerErrors) {
74
+ document.parseResult.lexerErrors.forEach((lexerIssue) => {
75
+ issues.push({
76
+ source: DocumentIssueSource.LEXER,
77
+ message: lexerIssue.message,
78
+ severity: DocumentIssueSeverity.ERROR,
79
+ startOffset: lexerIssue.offset,
80
+ startLine: plus(lexerIssue.line, -1),
81
+ startColumn: plus(lexerIssue.column, -1),
82
+ });
83
+ });
84
+ }
85
+ if (!skipParserErrors) {
86
+ document.parseResult.parserErrors.forEach((parserError) => {
87
+ // Try to get the previous token from the internal Chevrotain structure to get a better position
88
+ const previousToken = parserError === null || parserError === void 0 ? void 0 : parserError.previousToken;
89
+ issues.push({
90
+ source: DocumentIssueSource.PARSER,
91
+ severity: DocumentIssueSeverity.ERROR,
92
+ message: parserError.message,
93
+ startOffset: firstDefinedNumber(parserError.token.startOffset, previousToken === null || previousToken === void 0 ? void 0 : previousToken.startOffset),
94
+ startLine: plus(firstDefinedNumber(parserError.token.startLine, previousToken === null || previousToken === void 0 ? void 0 : previousToken.startLine), -1),
95
+ startColumn: plus(firstDefinedNumber(parserError.token.startColumn, previousToken === null || previousToken === void 0 ? void 0 : previousToken.startColumn), -1),
96
+ // Unrelieable end position returned by Chevrotain (24.09.2024)
97
+ // endOffset: firstDefinedNumber(parserError.token.endOffset, previousToken?.endOffset),
98
+ // endLine: plus(firstDefinedNumber(parserError.token.endLine, previousToken?.endLine), -1),
99
+ // endColumn: plus(firstDefinedNumber(parserError.token.endColumn, previousToken?.endColumn), 1),
100
+ });
101
+ });
102
+ }
103
+ if (!skipValidation) {
104
+ (_a = document.diagnostics) === null || _a === void 0 ? void 0 : _a.forEach((diagnostic) => {
105
+ if (!skipNonErrorDiagnostics || diagnostic.severity === DiagnosticSeverity.Error) {
106
+ issues.push({
107
+ source: DocumentIssueSource.VALIDATION,
108
+ severity: mapSeverity(diagnostic.severity),
109
+ message: diagnostic.message,
110
+ startLine: diagnostic.range.start.line,
111
+ startColumn: diagnostic.range.start.character,
112
+ endLine: diagnostic.range.end.line,
113
+ endColumn: diagnostic.range.end.character,
114
+ });
115
+ }
116
+ });
117
+ }
118
+ return issues;
119
+ }
120
+ /**
121
+ * Generates a summary of issues in a Langium document.
122
+ *
123
+ * @param document - The Langium document to summarize issues from.
124
+ * @param params - Optional parameters to filter issues.
125
+ * @returns A `DocumentIssueSummary` containing counts and formatted messages.
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * const summary = getDocumentIssueSummary(document);
130
+ * console.log(summary.summary);
131
+ * console.log(summary.message);
132
+ * ```
133
+ */
134
+ export function getDocumentIssueSummary(document, params) {
135
+ const issues = getDocumentIssues(document, params);
136
+ return getDocumentIssueSummaryFromIssues(issues);
137
+ }
138
+ /**
139
+ * Generates a summary of issues from a list of `DocumentIssue`.
140
+ *
141
+ * @param issues - An array of `DocumentIssue`.
142
+ * @returns A `DocumentIssueSummary` containing counts and formatted messages.
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * const issues: DocumentIssue[] = [ ... ];
147
+ * const summary = getDocumentIssueSummaryFromIssues(issues);
148
+ * console.log(summary.summary);
149
+ * console.log(summary.message);
150
+ * ```
151
+ */
152
+ export function getDocumentIssueSummaryFromIssues(issues) {
153
+ let countErrors = 0;
154
+ let countNonErrors = 0;
155
+ const messageList = [];
156
+ const summaryList = [];
157
+ const issueSourceMap = new Map();
158
+ for (const issue of issues) {
159
+ if (issue.severity === DocumentIssueSeverity.ERROR) {
160
+ countErrors += 1;
161
+ }
162
+ else {
163
+ countNonErrors += 1;
164
+ }
165
+ if (!issueSourceMap.has(issue.source)) {
166
+ issueSourceMap.set(issue.source, []);
167
+ }
168
+ issueSourceMap.get(issue.source).push(documentIssueToString(issue));
169
+ }
170
+ for (const source of [
171
+ DocumentIssueSource.LEXER,
172
+ DocumentIssueSource.PARSER,
173
+ DocumentIssueSource.VALIDATION,
174
+ ]) {
175
+ const issueList = issueSourceMap.get(source);
176
+ if (issueList) {
177
+ if (source === DocumentIssueSource.VALIDATION) {
178
+ const summaryParts = [];
179
+ if (issueList.length > countNonErrors) {
180
+ summaryParts.push(`${issueList.length - countNonErrors} error diagnostic(s)`);
181
+ }
182
+ if (countNonErrors > 0) {
183
+ summaryParts.push(`${countNonErrors} non-error diagnostic(s)`);
184
+ }
185
+ summaryList.push(summaryParts.join(', '));
186
+ }
187
+ else {
188
+ summaryList.push(`${issueList.length} ${source.toLowerCase()} error(s)`);
189
+ }
190
+ const sourceName = (source === DocumentIssueSource.VALIDATION) ? "diagnostics" : `${source.toLowerCase()} errors`;
191
+ messageList.push(`${sourceName.toFirstUpper()}:`);
192
+ messageList.push(...issueList);
193
+ }
194
+ }
195
+ if (summaryList.length === 0) {
196
+ summaryList.push('No errors');
197
+ }
198
+ const summaryString = summaryList.join(', ');
199
+ if (messageList.length > 0) {
200
+ messageList.push('');
201
+ messageList.push(summaryString);
202
+ }
203
+ const messageString = messageList.join(EOL);
204
+ return {
205
+ countTotal: countErrors + countNonErrors,
206
+ countErrors: countErrors,
207
+ countNonErrors: countNonErrors,
208
+ summary: summaryString,
209
+ message: messageString,
210
+ };
211
+ }
212
+ /**
213
+ * Converts a `DocumentIssue` to a formatted string.
214
+ *
215
+ * @param issue - The `DocumentIssue` to format.
216
+ * @returns A string representation of the issue.
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * const issue: DocumentIssue = { ... };
221
+ * const issueStr = documentIssueToString(issue);
222
+ * console.log(issueStr);
223
+ * ```
224
+ */
225
+ export function documentIssueToString(issue) {
226
+ const severity = issue.severity.toLowerCase().toFirstUpper();
227
+ return `${severity}${at(issue)} - ${issue.message}`;
228
+ }
229
+ /**
230
+ * Converts a `DiagnosticSeverity` to a string representation.
231
+ *
232
+ * @param severity - The `DiagnosticSeverity` to convert.
233
+ * @returns A string representing the severity.
234
+ */
235
+ export function severityToString(severity) {
236
+ switch (severity) {
237
+ case DiagnosticSeverity.Error:
238
+ return 'Error';
239
+ case DiagnosticSeverity.Warning:
240
+ return 'Warning';
241
+ case DiagnosticSeverity.Information:
242
+ return 'Information';
243
+ case DiagnosticSeverity.Hint:
244
+ return 'Hint';
245
+ default:
246
+ return 'Unknown';
247
+ }
248
+ }
249
+ /**
250
+ * Formats the position information of a `DocumentIssue`.
251
+ *
252
+ * @param issue - The `DocumentIssue` containing position information.
253
+ * @returns A formatted string representing the position (e.g., " at 4:13-20").
254
+ *
255
+ * @example
256
+ * ```typescript
257
+ * const positionStr = at(issue);
258
+ * console.log(positionStr); // Output: " at 4:13-20"
259
+ * ```
260
+ */
261
+ function at(issue) {
262
+ let result = '';
263
+ if (issue.startLine !== undefined && !isNaN(issue.startLine)) {
264
+ result += ` at ${issue.startLine + 1}`;
265
+ if (issue.startColumn !== undefined && !isNaN(issue.startColumn)) {
266
+ result += `:${issue.startColumn + 1}`;
267
+ if (issue.endLine !== undefined &&
268
+ !isNaN(issue.endLine) &&
269
+ issue.endColumn !== undefined &&
270
+ !isNaN(issue.endColumn)) {
271
+ if (issue.startLine !== issue.endLine) {
272
+ result += `-${issue.endLine + 1}:${issue.endColumn}`;
273
+ }
274
+ else {
275
+ result += `-${issue.endColumn}`;
276
+ }
277
+ }
278
+ }
279
+ }
280
+ return result;
281
+ }
282
+ /**
283
+ * Returns the first meaningful (non-null, non-NaN) value from two options.
284
+ *
285
+ * @param a - The first number to consider.
286
+ * @param b - The second number to consider.
287
+ * @returns The first meaningful number, or `undefined` if both are `null` or `NaN`.
288
+ */
289
+ function firstDefinedNumber(a, b) {
290
+ if (a != null && !Number.isNaN(a)) {
291
+ return a;
292
+ }
293
+ if (b != null && !Number.isNaN(b)) {
294
+ return b;
295
+ }
296
+ return undefined;
297
+ }
298
+ /**
299
+ * Add two numbers, returning `undefined` if either is `null` or `undefined`.
300
+ */
301
+ function plus(a, b) {
302
+ if (a != null && b != null) {
303
+ return a + b;
304
+ }
305
+ return undefined;
306
+ }
@@ -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,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,36 @@
1
+ export type MarkerPosition = {
2
+ /**
3
+ * 0-based absolute position of the beginning of the marker
4
+ */
5
+ startOffset: number;
6
+ /**
7
+ * 0-based line number of the beginning of the marker
8
+ */
9
+ startLine: number;
10
+ /**
11
+ * 0-based column of the beginning of the marker
12
+ */
13
+ startColumn: number;
14
+ /**
15
+ * 0-based absolute position of the character _after_ the end of the marker.
16
+ * (0-based position of the last character + 1)
17
+ *
18
+ * This allows representation of the 0-length markers as "startPos == endPos".
19
+ * In this case endLine and endColumn should be ignored.
20
+ */
21
+ endOffset: number;
22
+ /**
23
+ * 0-based line of the end of the marker
24
+ */
25
+ endLine: number;
26
+ /**
27
+ * 0-based Position of the character _after_ the end of the marker.
28
+ * (1-based position of the last character + 1)
29
+ */
30
+ endColumn: number;
31
+ };
32
+ export type ParseMarkedTextResult = {
33
+ text: string;
34
+ markers: Array<MarkerPosition>;
35
+ };
36
+ export declare function parseMarkedText(text: string, beginMarker?: string, endMarker?: string): ParseMarkedTextResult;
@@ -0,0 +1,51 @@
1
+ import escapeStringRegexp from "escape-string-regexp";
2
+ export function parseMarkedText(text, beginMarker = "<<{|", endMarker = "|}>>") {
3
+ const tokenRegex = new RegExp(`(${escapeStringRegexp(beginMarker)})|(${escapeStringRegexp(endMarker)})|(\r?\n)`, 'g');
4
+ const TOKEN_BEGIN_MARKER = 1;
5
+ const TOKEN_END_MERKER = 2;
6
+ const TOKEN_LN = 3;
7
+ const positions = [];
8
+ const originalParts = [];
9
+ let openMarker = null;
10
+ let lastIndex = 0;
11
+ let currentColumn = 0;
12
+ let currentLine = 0;
13
+ let currentPos = 0;
14
+ let match;
15
+ while ((match = tokenRegex.exec(text))) {
16
+ currentColumn += match.index - lastIndex;
17
+ currentPos += match.index - lastIndex;
18
+ originalParts.push(text.slice(lastIndex, match.index));
19
+ lastIndex = tokenRegex.lastIndex;
20
+ if (match[TOKEN_BEGIN_MARKER] && !openMarker) {
21
+ openMarker = {
22
+ line: currentLine,
23
+ column: currentColumn,
24
+ pos: currentPos
25
+ };
26
+ }
27
+ if (match[TOKEN_END_MERKER] && openMarker) {
28
+ positions.push({
29
+ startOffset: openMarker.pos,
30
+ startLine: openMarker.line,
31
+ startColumn: openMarker.column,
32
+ endOffset: currentPos,
33
+ endLine: currentLine,
34
+ endColumn: currentColumn,
35
+ });
36
+ openMarker = null;
37
+ }
38
+ if (match[TOKEN_LN]) {
39
+ currentLine += 1;
40
+ currentColumn = 0;
41
+ // Add token to output
42
+ currentPos += tokenRegex.lastIndex - match.index;
43
+ originalParts.push(text.slice(match.index, tokenRegex.lastIndex));
44
+ }
45
+ }
46
+ originalParts.push(text.slice(lastIndex));
47
+ return {
48
+ text: originalParts.join(""),
49
+ markers: positions
50
+ };
51
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Converts the first character of a string to upper case.
3
+ * Example: "hello" -> "Hello"
4
+ *
5
+ * @param s The string to convert.
6
+ * @returns The converted string.
7
+ */
8
+ export declare function toFirstUpper<T extends string | undefined>(s: T): T;
9
+ /**
10
+ * Converts the first character of a string to upper case.
11
+ * Example: "hello" -> "Hello"
12
+ *
13
+ * @param s The string to convert.
14
+ * @returns The converted string.
15
+ */
16
+ export declare function toFirstLower<T extends string | undefined>(s: T): T;
17
+ declare global {
18
+ interface String {
19
+ toFirstUpper(): string;
20
+ toFirstLower(): string;
21
+ }
22
+ }
23
+ /**
24
+ * Formats a multi-line template literal by adjusting indentation and preserving line breaks.
25
+ *
26
+ * This function ensures consistent formatting of multi-line strings, which is particularly
27
+ * useful for defining code blocks or text outputs. It uses Platform newlines (e.g. `\r\n` on Windows).
28
+ *
29
+ * The indentation of dynamically inserted placeholders (`${...}`) will be adjusted to match
30
+ * the indentation level of the placeholder itself. This feature is especially useful for code
31
+ * generation scenarios, where nested structures or varying indentation levels are needed.
32
+ *
33
+ * ### Example
34
+ * ```typescript
35
+ * const text = adjusted`
36
+ * ${cmds}
37
+ * if (sayAgain) {
38
+ * ${cmds}
39
+ * }
40
+ * `;
41
+ *
42
+ * // Output (without `|`):
43
+ * // |console.log('Hello,');
44
+ * // |console.log('World!');
45
+ * // |if (sayAgain) {
46
+ * // | console.log('Hello,');
47
+ * // | console.log('World!');
48
+ * // |}
49
+ * ```
50
+ *
51
+ * @param staticParts The static (literal) parts of the template string.
52
+ * @param substitutions The dynamic parts of the template string, which will be injected into the corresponding placeholders in `staticParts`.
53
+ * @returns A formatted string with fixed indentation and Unix-style line breaks (`\n`), without carriage return characters (`\r`).
54
+ */
55
+ export declare function adjusted(staticParts: TemplateStringsArray, ...substitutions: unknown[]): string;
56
+ /**
57
+ * Formats a multi-line template literal by adjusting indentation and preserving line breaks.
58
+ *
59
+ * This function ensures consistent formatting of multi-line strings, which is particularly
60
+ * useful for defining code blocks or text outputs. It uses Unix-style newlines (`\n`), making
61
+ * it system independent.
62
+ *
63
+ * The indentation of dynamically inserted placeholders (`${...}`) will be adjusted to match
64
+ * the indentation level of the placeholder itself. This feature is especially useful for code
65
+ * generation scenarios, where nested structures or varying indentation levels are needed.
66
+ *
67
+ * ### Example
68
+ * ```typescript
69
+ * const text = adjusted`
70
+ * ${cmds}
71
+ * if (sayAgain) {
72
+ * ${cmds}
73
+ * }
74
+ * `;
75
+ *
76
+ * // Output (without `|`):
77
+ * // |console.log('Hello,');
78
+ * // |console.log('World!');
79
+ * // |if (sayAgain) {
80
+ * // | console.log('Hello,');
81
+ * // | console.log('World!');
82
+ * // |}
83
+ * ```
84
+ *
85
+ * @param staticParts The static (literal) parts of the template string.
86
+ * @param substitutions The dynamic parts of the template string, which will be injected into the corresponding placeholders in `staticParts`.
87
+ * @returns A formatted string with fixed indentation and Unix-style line breaks (`\n`), without carriage return characters (`\r`).
88
+ */
89
+ export declare function adjustedUnix(staticParts: TemplateStringsArray, ...substitutions: unknown[]): string;
@@ -0,0 +1,104 @@
1
+ import { expandToNode, toString } from "langium/generate";
2
+ /**
3
+ * Converts the first character of a string to upper case.
4
+ * Example: "hello" -> "Hello"
5
+ *
6
+ * @param s The string to convert.
7
+ * @returns The converted string.
8
+ */
9
+ export function toFirstUpper(s) {
10
+ if (s === undefined) {
11
+ return undefined;
12
+ }
13
+ return s.charAt(0).toUpperCase() + s.slice(1);
14
+ }
15
+ /**
16
+ * Converts the first character of a string to upper case.
17
+ * Example: "hello" -> "Hello"
18
+ *
19
+ * @param s The string to convert.
20
+ * @returns The converted string.
21
+ */
22
+ export function toFirstLower(s) {
23
+ if (s === undefined) {
24
+ return undefined;
25
+ }
26
+ return s.charAt(0).toLowerCase() + s.slice(1);
27
+ }
28
+ String.prototype.toFirstUpper = function () {
29
+ return toFirstUpper(this);
30
+ };
31
+ String.prototype.toFirstLower = function () {
32
+ return toFirstLower(this);
33
+ };
34
+ /**
35
+ * Formats a multi-line template literal by adjusting indentation and preserving line breaks.
36
+ *
37
+ * This function ensures consistent formatting of multi-line strings, which is particularly
38
+ * useful for defining code blocks or text outputs. It uses Platform newlines (e.g. `\r\n` on Windows).
39
+ *
40
+ * The indentation of dynamically inserted placeholders (`${...}`) will be adjusted to match
41
+ * the indentation level of the placeholder itself. This feature is especially useful for code
42
+ * generation scenarios, where nested structures or varying indentation levels are needed.
43
+ *
44
+ * ### Example
45
+ * ```typescript
46
+ * const text = adjusted`
47
+ * ${cmds}
48
+ * if (sayAgain) {
49
+ * ${cmds}
50
+ * }
51
+ * `;
52
+ *
53
+ * // Output (without `|`):
54
+ * // |console.log('Hello,');
55
+ * // |console.log('World!');
56
+ * // |if (sayAgain) {
57
+ * // | console.log('Hello,');
58
+ * // | console.log('World!');
59
+ * // |}
60
+ * ```
61
+ *
62
+ * @param staticParts The static (literal) parts of the template string.
63
+ * @param substitutions The dynamic parts of the template string, which will be injected into the corresponding placeholders in `staticParts`.
64
+ * @returns A formatted string with fixed indentation and Unix-style line breaks (`\n`), without carriage return characters (`\r`).
65
+ */
66
+ export function adjusted(staticParts, ...substitutions) {
67
+ return toString(expandToNode(staticParts, ...substitutions));
68
+ }
69
+ /**
70
+ * Formats a multi-line template literal by adjusting indentation and preserving line breaks.
71
+ *
72
+ * This function ensures consistent formatting of multi-line strings, which is particularly
73
+ * useful for defining code blocks or text outputs. It uses Unix-style newlines (`\n`), making
74
+ * it system independent.
75
+ *
76
+ * The indentation of dynamically inserted placeholders (`${...}`) will be adjusted to match
77
+ * the indentation level of the placeholder itself. This feature is especially useful for code
78
+ * generation scenarios, where nested structures or varying indentation levels are needed.
79
+ *
80
+ * ### Example
81
+ * ```typescript
82
+ * const text = adjusted`
83
+ * ${cmds}
84
+ * if (sayAgain) {
85
+ * ${cmds}
86
+ * }
87
+ * `;
88
+ *
89
+ * // Output (without `|`):
90
+ * // |console.log('Hello,');
91
+ * // |console.log('World!');
92
+ * // |if (sayAgain) {
93
+ * // | console.log('Hello,');
94
+ * // | console.log('World!');
95
+ * // |}
96
+ * ```
97
+ *
98
+ * @param staticParts The static (literal) parts of the template string.
99
+ * @param substitutions The dynamic parts of the template string, which will be injected into the corresponding placeholders in `staticParts`.
100
+ * @returns A formatted string with fixed indentation and Unix-style line breaks (`\n`), without carriage return characters (`\r`).
101
+ */
102
+ export function adjustedUnix(staticParts, ...substitutions) {
103
+ return adjusted(staticParts, substitutions).replace(/\r/g, '');
104
+ }