@kubohiroya/turbowarp-markdown 0.2.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.
@@ -0,0 +1,194 @@
1
+ import {extensionConfig} from './config';
2
+ import definitions from './block-definitions.json';
3
+ import {
4
+ bold,
5
+ code,
6
+ codeBlock,
7
+ concat,
8
+ formatValidationResult,
9
+ getLastRenderValidationErrorText,
10
+ getLastRenderValidationErrors,
11
+ heading,
12
+ isValid,
13
+ italic,
14
+ link,
15
+ listItem,
16
+ orderedList,
17
+ paragraph,
18
+ quote,
19
+ render,
20
+ renderWithValidation,
21
+ text,
22
+ unorderedList,
23
+ validate,
24
+ type MarkdownFragment
25
+ } from './markdown';
26
+
27
+ type BlockTypeName = 'REPORTER' | 'BOOLEAN';
28
+ type ArgumentTypeName = 'STRING' | 'NUMBER';
29
+
30
+ interface DefinitionArgument {
31
+ type: ArgumentTypeName;
32
+ defaultValue: string | number;
33
+ }
34
+
35
+ interface BlockDefinition {
36
+ opcode: string;
37
+ blockType: BlockTypeName;
38
+ text: string;
39
+ description: string;
40
+ arguments: Record<string, DefinitionArgument>;
41
+ }
42
+
43
+ const SERIALIZED_PREFIX = 'turbowarp-markdown:v1:';
44
+ const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
45
+
46
+ export class MarkdownExtension implements TurboWarpExtension {
47
+ public getInfo(): Record<string, unknown> {
48
+ return {
49
+ id: extensionConfig.id,
50
+ name: Scratch.translate(definitions.extensionName),
51
+ docsURI: extensionConfig.docsURI,
52
+ blockIconURI: extensionConfig.blockIconURI,
53
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
54
+ };
55
+ }
56
+
57
+ public text(args: {TEXT: unknown}): string {
58
+ return encode(text(Scratch.Cast.toString(args.TEXT)));
59
+ }
60
+
61
+ public bold(args: {CONTENT: unknown}): string {
62
+ return encode(bold(decodeOrText(args.CONTENT)));
63
+ }
64
+
65
+ public italic(args: {CONTENT: unknown}): string {
66
+ return encode(italic(decodeOrText(args.CONTENT)));
67
+ }
68
+
69
+ public link(args: {CONTENT: unknown; URL: unknown}): string {
70
+ return encode(link(decodeOrText(args.CONTENT), Scratch.Cast.toString(args.URL)));
71
+ }
72
+
73
+ public code(args: {TEXT: unknown}): string {
74
+ return encode(code(Scratch.Cast.toString(args.TEXT)));
75
+ }
76
+
77
+ public heading(args: {LEVEL: unknown; CONTENT: unknown}): string {
78
+ return encode(heading(Scratch.Cast.toNumber(args.LEVEL), decodeOrText(args.CONTENT)));
79
+ }
80
+
81
+ public paragraph(args: {CONTENT: unknown}): string {
82
+ return encode(paragraph(decodeOrText(args.CONTENT)));
83
+ }
84
+
85
+ public quote(args: {CONTENT: unknown}): string {
86
+ return encode(quote(decodeOrText(args.CONTENT)));
87
+ }
88
+
89
+ public codeBlock(args: {TEXT: unknown; LANGUAGE: unknown}): string {
90
+ return encode(codeBlock(Scratch.Cast.toString(args.TEXT), Scratch.Cast.toString(args.LANGUAGE)));
91
+ }
92
+
93
+ public listItem(args: {CONTENT: unknown}): string {
94
+ return encode(listItem(decodeOrText(args.CONTENT)));
95
+ }
96
+
97
+ public unorderedList(args: {ITEMS: unknown}): string {
98
+ return encode(unorderedList(decodeOrText(args.ITEMS)));
99
+ }
100
+
101
+ public orderedList(args: {ITEMS: unknown}): string {
102
+ return encode(orderedList(decodeOrText(args.ITEMS)));
103
+ }
104
+
105
+ public concat(args: {LEFT: unknown; RIGHT: unknown}): string {
106
+ return encode(concat(decodeOrText(args.LEFT), decodeOrText(args.RIGHT)));
107
+ }
108
+
109
+ public render(args: {FRAGMENT: unknown}): string {
110
+ return render(decodeOrText(args.FRAGMENT));
111
+ }
112
+
113
+ public renderWithValidation(args: {FRAGMENT: unknown}): string {
114
+ return renderWithValidation(decodeOrText(args.FRAGMENT));
115
+ }
116
+
117
+ public lastValidationErrors(): string {
118
+ return getLastRenderValidationErrorText();
119
+ }
120
+
121
+ public lastRenderHasValidationErrors(): boolean {
122
+ return getLastRenderValidationErrors().length > 0;
123
+ }
124
+
125
+ public validateMarkdown(args: {FRAGMENT: unknown}): string {
126
+ return formatValidationResult(validate(decodeOrText(args.FRAGMENT)));
127
+ }
128
+
129
+ public isValidMarkdown(args: {FRAGMENT: unknown}): boolean {
130
+ return isValid(decodeOrText(args.FRAGMENT));
131
+ }
132
+
133
+ private toScratchBlock(block: BlockDefinition): Record<string, unknown> {
134
+ return {
135
+ opcode: block.opcode,
136
+ blockType: Scratch.BlockType[block.blockType],
137
+ text: Scratch.translate(block.text),
138
+ arguments: Object.fromEntries(
139
+ Object.entries(block.arguments).map(([name, argument]) => [
140
+ name,
141
+ {
142
+ type: Scratch.ArgumentType[argument.type],
143
+ defaultValue: argument.defaultValue
144
+ }
145
+ ])
146
+ )
147
+ };
148
+ }
149
+ }
150
+
151
+ function encode(fragment: MarkdownFragment): string {
152
+ return `${SERIALIZED_PREFIX}${JSON.stringify(fragment)}`;
153
+ }
154
+
155
+ function decodeOrText(value: unknown): MarkdownFragment {
156
+ const raw = Scratch.Cast.toString(value);
157
+ if (!raw.startsWith(SERIALIZED_PREFIX)) return text(raw);
158
+ return parseFragment(raw.slice(SERIALIZED_PREFIX.length));
159
+ }
160
+
161
+ function parseFragment(json: string): MarkdownFragment {
162
+ const parsed = JSON.parse(json) as MarkdownFragment;
163
+ if (!isFragment(parsed)) throw new TypeError('Invalid serialized Markdown fragment.');
164
+ return parsed;
165
+ }
166
+
167
+ function isFragment(value: unknown): value is MarkdownFragment {
168
+ if (typeof value !== 'object' || value === null) return false;
169
+ const record = value as Record<string, unknown>;
170
+ if (record.kind === 'empty') return true;
171
+ if (record.kind === 'text' || record.kind === 'code') return typeof record.value === 'string';
172
+ if (record.kind === 'bold' || record.kind === 'italic' || record.kind === 'paragraph') {
173
+ return isFragment(record.content);
174
+ }
175
+ if (record.kind === 'link') {
176
+ return typeof record.url === 'string' && isFragment(record.content);
177
+ }
178
+ if (record.kind === 'heading') {
179
+ return typeof record.level === 'number' && isFragment(record.content);
180
+ }
181
+ if (record.kind === 'quote' || record.kind === 'listItem') return isFragment(record.content);
182
+ if (record.kind === 'codeBlock') {
183
+ return typeof record.language === 'string' && typeof record.value === 'string';
184
+ }
185
+ if (record.kind === 'list') {
186
+ return (
187
+ typeof record.ordered === 'boolean' &&
188
+ Array.isArray(record.items) &&
189
+ record.items.every(isFragment)
190
+ );
191
+ }
192
+ if (record.kind === 'sequence') return Array.isArray(record.children) && record.children.every(isFragment);
193
+ return false;
194
+ }
@@ -0,0 +1,25 @@
1
+ interface TurboWarpExtension {
2
+ getInfo(): Record<string, unknown>;
3
+ }
4
+
5
+ interface ScratchTranslate {
6
+ (text: string): string;
7
+ (message: {default: string; description?: string}, placeholders?: Record<string, string | number>): string;
8
+ }
9
+
10
+ interface ScratchApi {
11
+ extensions: {
12
+ unsandboxed: boolean;
13
+ register(extension: TurboWarpExtension): void;
14
+ };
15
+ BlockType: Record<'COMMAND' | 'REPORTER' | 'BOOLEAN' | 'HAT', string>;
16
+ ArgumentType: Record<'STRING' | 'NUMBER' | 'BOOLEAN', string>;
17
+ Cast: {
18
+ toString(value: unknown): string;
19
+ toNumber(value: unknown): number;
20
+ toBoolean(value: unknown): boolean;
21
+ };
22
+ translate: ScratchTranslate;
23
+ }
24
+
25
+ declare const Scratch: ScratchApi;
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ import {extensionConfig} from './config.js';
2
+ import {MarkdownExtension} from './extension.js';
3
+
4
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) {
5
+ throw new Error(`${extensionConfig.name} must run unsandboxed.`);
6
+ }
7
+
8
+ Scratch.extensions.register(new MarkdownExtension());
@@ -0,0 +1,407 @@
1
+ export type MarkdownFragment =
2
+ | MarkdownText
3
+ | MarkdownEmphasis
4
+ | MarkdownLink
5
+ | MarkdownCode
6
+ | MarkdownHeading
7
+ | MarkdownParagraph
8
+ | MarkdownQuote
9
+ | MarkdownCodeBlock
10
+ | MarkdownList
11
+ | MarkdownListItem
12
+ | MarkdownSequence
13
+ | MarkdownEmpty;
14
+
15
+ export interface MarkdownText {
16
+ readonly kind: 'text';
17
+ readonly value: string;
18
+ }
19
+
20
+ export interface MarkdownEmphasis {
21
+ readonly kind: 'bold' | 'italic';
22
+ readonly content: MarkdownFragment;
23
+ }
24
+
25
+ export interface MarkdownLink {
26
+ readonly kind: 'link';
27
+ readonly content: MarkdownFragment;
28
+ readonly url: string;
29
+ }
30
+
31
+ export interface MarkdownCode {
32
+ readonly kind: 'code';
33
+ readonly value: string;
34
+ }
35
+
36
+ export interface MarkdownHeading {
37
+ readonly kind: 'heading';
38
+ readonly level: number;
39
+ readonly content: MarkdownFragment;
40
+ }
41
+
42
+ export interface MarkdownParagraph {
43
+ readonly kind: 'paragraph';
44
+ readonly content: MarkdownFragment;
45
+ }
46
+
47
+ export interface MarkdownQuote {
48
+ readonly kind: 'quote';
49
+ readonly content: MarkdownFragment;
50
+ }
51
+
52
+ export interface MarkdownCodeBlock {
53
+ readonly kind: 'codeBlock';
54
+ readonly language: string;
55
+ readonly value: string;
56
+ }
57
+
58
+ export interface MarkdownList {
59
+ readonly kind: 'list';
60
+ readonly ordered: boolean;
61
+ readonly items: readonly MarkdownFragment[];
62
+ }
63
+
64
+ export interface MarkdownListItem {
65
+ readonly kind: 'listItem';
66
+ readonly content: MarkdownFragment;
67
+ }
68
+
69
+ export interface MarkdownSequence {
70
+ readonly kind: 'sequence';
71
+ readonly children: readonly MarkdownFragment[];
72
+ }
73
+
74
+ export interface MarkdownEmpty {
75
+ readonly kind: 'empty';
76
+ }
77
+
78
+ export type MarkdownValidationSeverity = 'error' | 'warning';
79
+
80
+ export interface MarkdownValidationIssue {
81
+ readonly severity: MarkdownValidationSeverity;
82
+ readonly path: string;
83
+ readonly message: string;
84
+ }
85
+
86
+ export interface MarkdownValidationResult {
87
+ readonly valid: boolean;
88
+ readonly issues: readonly MarkdownValidationIssue[];
89
+ }
90
+
91
+ export const empty: MarkdownEmpty = {kind: 'empty'};
92
+
93
+ const SAFE_URL_PATTERN = /^(?:https?:|mailto:|tel:|\/|\.\/|\.\.\/|#|\?|$)/iu;
94
+ let lastRenderValidationResult: MarkdownValidationResult = {valid: true, issues: []};
95
+
96
+ export function text(value: string): MarkdownText {
97
+ return {kind: 'text', value};
98
+ }
99
+
100
+ export function bold(content: MarkdownFragment | string): MarkdownEmphasis {
101
+ return {kind: 'bold', content: normalizeContent(content)};
102
+ }
103
+
104
+ export function italic(content: MarkdownFragment | string): MarkdownEmphasis {
105
+ return {kind: 'italic', content: normalizeContent(content)};
106
+ }
107
+
108
+ export function link(content: MarkdownFragment | string, url: string): MarkdownLink {
109
+ validateSafeUrl(url);
110
+ return {kind: 'link', content: normalizeContent(content), url};
111
+ }
112
+
113
+ export function code(value: string): MarkdownCode {
114
+ return {kind: 'code', value};
115
+ }
116
+
117
+ export function heading(level: number, content: MarkdownFragment | string): MarkdownHeading {
118
+ return {kind: 'heading', level: clampHeadingLevel(level), content: normalizeContent(content)};
119
+ }
120
+
121
+ export function paragraph(content: MarkdownFragment | string): MarkdownParagraph {
122
+ return {kind: 'paragraph', content: normalizeContent(content)};
123
+ }
124
+
125
+ export function quote(content: MarkdownFragment | string): MarkdownQuote {
126
+ return {kind: 'quote', content: normalizeContent(content)};
127
+ }
128
+
129
+ export function codeBlock(value: string, language = ''): MarkdownCodeBlock {
130
+ return {kind: 'codeBlock', language: sanitizeLanguage(language), value};
131
+ }
132
+
133
+ export function listItem(content: MarkdownFragment | string): MarkdownListItem {
134
+ return {kind: 'listItem', content: normalizeContent(content)};
135
+ }
136
+
137
+ export function unorderedList(items: MarkdownFragment | string): MarkdownList {
138
+ return {kind: 'list', ordered: false, items: normalizeItems(items)};
139
+ }
140
+
141
+ export function orderedList(items: MarkdownFragment | string): MarkdownList {
142
+ return {kind: 'list', ordered: true, items: normalizeItems(items)};
143
+ }
144
+
145
+ export function concat(left: MarkdownFragment, right: MarkdownFragment): MarkdownFragment {
146
+ const children = [...flattenSequence(left), ...flattenSequence(right)].filter(
147
+ (child) => child.kind !== 'empty'
148
+ );
149
+ if (children.length === 0) return empty;
150
+ if (children.length === 1) return children[0] ?? empty;
151
+ return {kind: 'sequence', children};
152
+ }
153
+
154
+ export function render(fragment: MarkdownFragment): string {
155
+ return renderDocument(fragment);
156
+ }
157
+
158
+ export function renderWithValidation(fragment: MarkdownFragment): string {
159
+ lastRenderValidationResult = validate(fragment);
160
+ return renderDocument(fragment);
161
+ }
162
+
163
+ export function validate(fragment: MarkdownFragment): MarkdownValidationResult {
164
+ const issues: MarkdownValidationIssue[] = [];
165
+ validateFragment(fragment, '$', [], issues);
166
+ if (fragment.kind === 'empty') {
167
+ issues.push({severity: 'warning', path: '$', message: 'Markdown fragment is empty.'});
168
+ }
169
+ return {
170
+ valid: issues.every((issue) => issue.severity !== 'error'),
171
+ issues
172
+ };
173
+ }
174
+
175
+ export function isValid(fragment: MarkdownFragment): boolean {
176
+ return validate(fragment).valid;
177
+ }
178
+
179
+ export function getLastRenderValidationResult(): MarkdownValidationResult {
180
+ return lastRenderValidationResult;
181
+ }
182
+
183
+ export function getLastRenderValidationErrors(): readonly MarkdownValidationIssue[] {
184
+ return lastRenderValidationResult.issues.filter((issue) => issue.severity === 'error');
185
+ }
186
+
187
+ export function formatValidationResult(result: MarkdownValidationResult): string {
188
+ if (result.issues.length === 0) return 'valid';
189
+ return result.issues
190
+ .map((issue) => `${issue.severity}: ${issue.path}: ${issue.message}`)
191
+ .join('\n');
192
+ }
193
+
194
+ export function formatValidationErrors(issues: readonly MarkdownValidationIssue[]): string {
195
+ if (issues.length === 0) return '';
196
+ return issues.map((issue) => `${issue.path}: ${issue.message}`).join('\n');
197
+ }
198
+
199
+ export function getLastRenderValidationErrorText(): string {
200
+ return formatValidationErrors(getLastRenderValidationErrors());
201
+ }
202
+
203
+ export function normalizeContent(content: MarkdownFragment | string): MarkdownFragment {
204
+ return typeof content === 'string' ? text(content) : content;
205
+ }
206
+
207
+ function validateFragment(
208
+ fragment: MarkdownFragment,
209
+ path: string,
210
+ ancestors: readonly MarkdownFragment[],
211
+ issues: MarkdownValidationIssue[]
212
+ ): void {
213
+ const parent = ancestors[ancestors.length - 1];
214
+ const inlineAncestor = ancestors.find((ancestor) => ['bold', 'italic', 'link'].includes(ancestor.kind));
215
+
216
+ if (!isInline(fragment) && inlineAncestor !== undefined) {
217
+ issues.push({
218
+ severity: 'error',
219
+ path,
220
+ message: `${fragment.kind} cannot be nested inside ${inlineAncestor.kind}.`
221
+ });
222
+ }
223
+
224
+ if (fragment.kind === 'listItem' && parent?.kind !== 'list') {
225
+ issues.push({severity: 'error', path, message: 'listItem must be inside a list.'});
226
+ }
227
+
228
+ validateWarnings(fragment, path, issues);
229
+
230
+ for (const [index, child] of childFragments(fragment).entries()) {
231
+ validateFragment(child, `${path}.children[${index}]`, [...ancestors, fragment], issues);
232
+ }
233
+ }
234
+
235
+ function validateWarnings(
236
+ fragment: MarkdownFragment,
237
+ path: string,
238
+ issues: MarkdownValidationIssue[]
239
+ ): void {
240
+ if (fragment.kind === 'heading' && isEmptyish(fragment.content)) {
241
+ issues.push({severity: 'warning', path, message: 'heading should have content.'});
242
+ }
243
+ if (fragment.kind === 'paragraph' && isEmptyish(fragment.content)) {
244
+ issues.push({severity: 'warning', path, message: 'paragraph is empty.'});
245
+ }
246
+ if (fragment.kind === 'link' && isEmptyish(fragment.content)) {
247
+ issues.push({severity: 'warning', path, message: 'link should have visible content.'});
248
+ }
249
+ if (fragment.kind === 'link' && fragment.url.trim().length === 0) {
250
+ issues.push({severity: 'warning', path, message: 'link should have a destination URL.'});
251
+ }
252
+ if (fragment.kind === 'list' && fragment.items.length === 0) {
253
+ issues.push({severity: 'warning', path, message: 'list should contain at least one item.'});
254
+ }
255
+ }
256
+
257
+ function childFragments(fragment: MarkdownFragment): readonly MarkdownFragment[] {
258
+ switch (fragment.kind) {
259
+ case 'bold':
260
+ case 'italic':
261
+ case 'link':
262
+ case 'heading':
263
+ case 'paragraph':
264
+ case 'quote':
265
+ case 'listItem':
266
+ return [fragment.content];
267
+ case 'list':
268
+ return fragment.items;
269
+ case 'sequence':
270
+ return fragment.children;
271
+ default:
272
+ return [];
273
+ }
274
+ }
275
+
276
+ function isEmptyish(fragment: MarkdownFragment): boolean {
277
+ if (fragment.kind === 'empty') return true;
278
+ if (fragment.kind === 'text' || fragment.kind === 'code') return fragment.value.length === 0;
279
+ if (fragment.kind === 'sequence') return fragment.children.every(isEmptyish);
280
+ return false;
281
+ }
282
+
283
+ function renderDocument(fragment: MarkdownFragment): string {
284
+ if (fragment.kind === 'empty') return '';
285
+ if (fragment.kind === 'sequence') {
286
+ if (fragment.children.every((child) => isInline(child) || child.kind === 'sequence')) {
287
+ return renderInline(fragment);
288
+ }
289
+ return fragment.children.map(renderDocument).filter(Boolean).join('\n\n');
290
+ }
291
+ if (isInline(fragment)) return renderInline(fragment);
292
+ return renderBlock(fragment);
293
+ }
294
+
295
+ function renderBlock(fragment: MarkdownFragment): string {
296
+ switch (fragment.kind) {
297
+ case 'heading':
298
+ return `${'#'.repeat(fragment.level)} ${renderInlineish(fragment.content)}`;
299
+ case 'paragraph':
300
+ return renderInlineish(fragment.content);
301
+ case 'quote':
302
+ return renderDocument(fragment.content)
303
+ .split('\n')
304
+ .map((line) => (line.length === 0 ? '>' : `> ${line}`))
305
+ .join('\n');
306
+ case 'codeBlock':
307
+ return renderCodeBlock(fragment);
308
+ case 'list':
309
+ return fragment.items
310
+ .map((item, index) => renderListItem(item, fragment.ordered ? `${index + 1}.` : '-'))
311
+ .join('\n');
312
+ case 'listItem':
313
+ return renderInlineish(fragment.content);
314
+ default:
315
+ return renderDocument(fragment);
316
+ }
317
+ }
318
+
319
+ function renderInline(fragment: MarkdownFragment): string {
320
+ switch (fragment.kind) {
321
+ case 'text':
322
+ return escapeMarkdownText(fragment.value);
323
+ case 'bold':
324
+ return `**${renderInlineish(fragment.content)}**`;
325
+ case 'italic':
326
+ return `*${renderInlineish(fragment.content)}*`;
327
+ case 'link':
328
+ return `[${renderInlineish(fragment.content)}](${escapeUrl(fragment.url)})`;
329
+ case 'code':
330
+ return renderInlineCode(fragment.value);
331
+ case 'sequence':
332
+ return fragment.children.map(renderInlineish).join('');
333
+ case 'empty':
334
+ return '';
335
+ default:
336
+ return renderBlock(fragment);
337
+ }
338
+ }
339
+
340
+ function renderInlineish(fragment: MarkdownFragment): string {
341
+ return isInline(fragment) || fragment.kind === 'sequence' ? renderInline(fragment) : renderBlock(fragment);
342
+ }
343
+
344
+ function renderCodeBlock(fragment: MarkdownCodeBlock): string {
345
+ const fence = longestBacktickRun(fragment.value) >= 3 ? '````' : '```';
346
+ const language = fragment.language.length > 0 ? fragment.language : '';
347
+ return `${fence}${language}\n${fragment.value}\n${fence}`;
348
+ }
349
+
350
+ function renderInlineCode(value: string): string {
351
+ const fence = '`'.repeat(Math.max(1, longestBacktickRun(value) + 1));
352
+ const needsPadding = value.startsWith('`') || value.endsWith('`') || value.includes('\n');
353
+ const content = needsPadding ? ` ${value} ` : value;
354
+ return `${fence}${content}${fence}`;
355
+ }
356
+
357
+ function renderListItem(fragment: MarkdownFragment, marker: string): string {
358
+ const content = fragment.kind === 'listItem' ? fragment.content : fragment;
359
+ const rendered = renderDocument(content);
360
+ const [first = '', ...rest] = rendered.split('\n');
361
+ const padding = ' '.repeat(marker.length + 1);
362
+ return [`${marker} ${first}`, ...rest.map((line) => `${padding}${line}`)].join('\n');
363
+ }
364
+
365
+ function normalizeItems(items: MarkdownFragment | string): readonly MarkdownFragment[] {
366
+ const fragment = normalizeContent(items);
367
+ if (fragment.kind === 'sequence') return fragment.children;
368
+ if (fragment.kind === 'empty') return [];
369
+ return [fragment];
370
+ }
371
+
372
+ function flattenSequence(fragment: MarkdownFragment): readonly MarkdownFragment[] {
373
+ if (fragment.kind === 'sequence') return fragment.children.flatMap(flattenSequence);
374
+ return [fragment];
375
+ }
376
+
377
+ function isInline(fragment: MarkdownFragment): boolean {
378
+ return ['text', 'bold', 'italic', 'link', 'code', 'empty'].includes(fragment.kind);
379
+ }
380
+
381
+ function clampHeadingLevel(level: number): number {
382
+ if (!Number.isFinite(level)) return 1;
383
+ return Math.min(6, Math.max(1, Math.trunc(level)));
384
+ }
385
+
386
+ function sanitizeLanguage(language: string): string {
387
+ return language.trim().replace(/[^a-zA-Z0-9_+.-]/gu, '');
388
+ }
389
+
390
+ function validateSafeUrl(value: string): void {
391
+ const trimmed = value.trim();
392
+ if (!SAFE_URL_PATTERN.test(trimmed)) {
393
+ throw new TypeError(`Unsafe URL value: ${value}`);
394
+ }
395
+ }
396
+
397
+ function escapeMarkdownText(value: string): string {
398
+ return value.replace(/([\\`*_{}[\]()#+\-.!<>|])/gu, '\\$1');
399
+ }
400
+
401
+ function escapeUrl(value: string): string {
402
+ return value.trim().replace(/\)/gu, '%29').replace(/\s/gu, '%20');
403
+ }
404
+
405
+ function longestBacktickRun(value: string): number {
406
+ return Math.max(0, ...Array.from(value.matchAll(/`+/gu), (match) => match[0]?.length ?? 0));
407
+ }