@kubohiroya/turbowarp-markdown 0.2.1 → 0.4.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.
@@ -7,848 +7,848 @@
7
7
  (function (Scratch) {
8
8
  'use strict';
9
9
 
10
- //#region src/config.ts
11
- var extensionConfig = {
12
- id: "kubohiroyamarkdown",
13
- slug: "turbowarp-markdown",
14
- name: "TurboWarp Markdown",
15
- description: "Build Markdown documents with immutable reporter blocks.",
16
- author: "Hiroya Kubo",
17
- license: "MPL-2.0",
18
- unsandboxed: false,
19
- docsURI: "https://kubohiroya.github.io/turbowarp-markdown/",
20
- blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNiIgeT0iOCIgd2lkdGg9IjM2IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzJGNjM4NiIvPjxwYXRoIGQ9Ik0xMyAzMFYxOGw1IDcgNS03djEyTTMwIDE4djEyTTI2IDMwaDgiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZmZmZiIgc3Ryb2tlLXdpZHRoPSIzIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4="
21
- };
22
- //#endregion
23
- //#region node_modules/.pnpm/@kubohiroya+turbowarp-extension-data-editor@0.2.1_react@18.3.1/node_modules/@kubohiroya/turbowarp-extension-data-editor/dist/fixed-input-schema.js
24
- var numberToken = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/u;
25
- var invalidNumber = Object.freeze({
26
- kind: "invalid",
27
- code: "fixed-number-input-invalid"
28
- });
29
- /**
30
- * Parse a NEW numeric draft according to NP-finite-new-input-v1.
31
- * Never apply this to opening/no-op raw values or use it as an owner validator.
32
- * Keep the validated token so negative zero, precision and exponent spelling survive.
33
- */
34
- function parseFixedNumberInput(input) {
35
- if (typeof input === "number") {
36
- if (!Number.isFinite(input)) return invalidNumber;
37
- return Object.freeze({
38
- kind: "valid",
39
- token: Object.is(input, -0) ? "-0" : String(input),
40
- value: input
41
- });
42
- }
43
- if (typeof input !== "string") return invalidNumber;
44
- const token = input.trim();
45
- if (!numberToken.test(token)) return invalidNumber;
46
- const value = Number(token);
47
- return Number.isFinite(value) ? Object.freeze({
48
- kind: "valid",
49
- token,
50
- value
51
- }) : invalidNumber;
52
- }
53
- var block_editor_fixed_inputs_schema_default = {
54
- $schema: "https://json-schema.org/draft/2020-12/schema",
55
- $id: "https://kubohiroya.github.io/turbowarp-markdown/schemas/block-editor-fixed-inputs.schema.json",
56
- $defs: { "heading": {
57
- "type": "object",
58
- "properties": { "LEVEL": { "type": "number" } },
59
- "required": ["LEVEL"],
60
- "additionalProperties": true
61
- } }
62
- };
63
- //#endregion
64
- //#region src/fixed-input-schema.ts
65
- var repository$1 = "turbowarp-markdown";
66
- /** The owner JSON document is canonical; this selects a primitive field fragment. */
67
- function fixedInputBundle(opcode, argument) {
68
- const source = {
69
- repository: repository$1,
70
- path: "schemas/block-editor-fixed-inputs.schema.json",
71
- symbol: `#/$defs/${opcode}/properties/${argument}`
72
- };
73
- const blocks = block_editor_fixed_inputs_schema_default.$defs;
74
- return {
75
- identity: {
76
- ownerId: repository$1,
77
- contractId: opcode,
78
- revision: "fixed-inputs-v1",
79
- variantId: argument
80
- },
81
- dialect: "2020-12",
82
- root: {
83
- retrievalUri: block_editor_fixed_inputs_schema_default.$id,
84
- document: blocks[opcode].properties[argument],
85
- artifact: {
86
- role: "canonical-schema",
87
- source
88
- }
89
- },
90
- resources: [],
91
- provenance: {
92
- canonicalSources: [source, {
93
- repository: repository$1,
94
- path: "src/extension.ts",
95
- symbol: opcode
96
- }],
97
- generatedFiles: [],
98
- referenceSchemas: [],
99
- generationSources: []
100
- }
101
- };
102
- }
103
- //#endregion
104
- //#region src/fixed-input-editors.ts
105
- var extensionId = "kubohiroyamarkdown";
106
- var repository = "turbowarp-markdown";
107
- var fields = [{
108
- "opcode": "heading",
109
- "argument": "LEVEL",
110
- "control": "number",
111
- "choices": [],
112
- "normalization": "identity",
113
- "shape": "math_number.NUM",
114
- "maxBytes": false
115
- }];
116
- function literalString(value) {
117
- if (typeof value !== "string") throw new TypeError("Expected a string literal.");
118
- return value;
119
- }
120
- /** Legacy nonempty finite aliases are projections; opening never creates a write. */
121
- function existingFixedNumber(value) {
122
- if (typeof value !== "string" && typeof value !== "number" || typeof value === "string" && value.trim() === "") throw new TypeError("Unavailable numeric projection.");
123
- const number = Number(value);
124
- if (!Number.isFinite(number)) throw new TypeError("Unavailable numeric projection.");
125
- return number;
126
- }
127
- function normalizeChoice(field, raw) {
128
- if (field.normalization === "lowercase") return raw.toLowerCase();
129
- if (field.normalization === "method") return raw.trim().toUpperCase();
130
- if (field.normalization === "trim") return raw.trim();
131
- if (field.normalization === "parse-format") {
132
- const lower = raw.trim().toLowerCase();
133
- return lower === "json" ? "JSON" : lower === "yaml" ? "YAML" : lower === "auto" ? "auto" : raw;
134
- }
135
- return raw;
136
- }
137
- function binding(field) {
138
- return {
139
- argument: field.argument,
140
- schemaBundle: fixedInputBundle(field.opcode, field.argument),
141
- control: {
142
- kind: field.control,
143
- ...field.control === "enum" ? { choices: field.choices.map((value) => ({ value })) } : {}
144
- },
145
- read(value) {
146
- return field.control === "number" ? existingFixedNumber(value) : normalizeChoice(field, literalString(value));
147
- },
148
- encode(value) {
149
- if (field.control === "number") {
150
- const parsed = parseFixedNumberInput(value);
151
- if (parsed.kind !== "valid") throw new TypeError("Invalid new numeric input.");
152
- return parsed.token;
153
- }
154
- const raw = literalString(value), normalized = normalizeChoice(field, raw);
155
- if (!field.choices.includes(normalized)) throw new TypeError("Unsupported fixed choice.");
156
- return field.shape === "menu-shadow" || field.shape === "direct-field-dropdown" ? normalized : raw;
157
- },
158
- validateCandidate(value) {
159
- try {
160
- if (field.control === "number") {
161
- const number = existingFixedNumber(value);
162
- if (field.maxBytes && (!Number.isSafeInteger(Math.trunc(number)) || Math.trunc(number) < 1)) return [{ message: "Invalid named body size." }];
163
- return [];
164
- }
165
- return field.choices.includes(normalizeChoice(field, literalString(value))) ? [] : [{ message: "Unsupported fixed choice." }];
166
- } catch {
167
- return [{ message: "Invalid fixed input." }];
168
- }
169
- }
170
- };
171
- }
172
- var fixedInputEditors = [...new Set(fields.map((f) => f.opcode))].map((opcode) => ({
173
- apiVersion: 1,
174
- extensionId,
175
- editorId: `${opcode}-fixed-inputs`,
176
- opcodes: [`${extensionId}_${opcode}`],
177
- contractId: `${repository}/${opcode}`,
178
- contractRevision: "fixed-inputs-v1",
179
- bindings: fields.filter((field) => field.opcode === opcode).map(binding),
180
- validationContext: () => ({
181
- consumerId: repository,
182
- nowMs: 0,
183
- settings: null
184
- })
185
- }));
186
- /** Registration follows the advertised opcode membership and the optional host capability. */
187
- function fixedInputRegistration(scratch) {
188
- const host = scratch ?? {};
189
- let active;
190
- let membership = "";
191
- const removers = [];
192
- let stopped = false;
193
- const clear = () => {
194
- host.vm?.runtime?.off?.("RUNTIME_DISPOSED", shutdown);
195
- for (const remove of removers.splice(0).reverse()) remove();
196
- active = void 0;
197
- membership = "";
198
- };
199
- const shutdown = () => {
200
- stopped = true;
201
- clear();
202
- };
203
- return {
204
- ensure(visibleOpcodes) {
205
- const api = host.gui?.blockEditors;
206
- const definitions = fixedInputEditors.filter((definition) => definition.opcodes.every((opcode) => visibleOpcodes.includes(opcode)));
207
- const key = definitions.map((definition) => definition.editorId).join(",");
208
- if (stopped || api === active && membership === key) return;
209
- clear();
210
- if (api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function" || !definitions.length) return;
211
- try {
212
- for (const definition of definitions) {
213
- const remove = api.registerFixedInputEditor.call(api, definition);
214
- if (typeof remove !== "function") throw new TypeError("Invalid fixed input cleanup.");
215
- removers.push(remove);
216
- }
217
- active = api;
218
- membership = key;
219
- host.vm?.runtime?.on?.("RUNTIME_DISPOSED", shutdown);
220
- } catch (error) {
221
- clear();
222
- throw error;
223
- }
224
- },
225
- dispose: shutdown
226
- };
227
- }
228
- var block_definitions_default = {
229
- extensionName: "TurboWarp Markdown",
230
- blocks: [
231
- {
232
- "opcode": "text",
233
- "blockType": "REPORTER",
234
- "text": "text [TEXT]",
235
- "description": "Creates escaped Markdown text.",
236
- "arguments": { "TEXT": {
237
- "type": "STRING",
238
- "defaultValue": "Hello *world*"
239
- } }
240
- },
241
- {
242
- "opcode": "bold",
243
- "blockType": "REPORTER",
244
- "text": "bold [CONTENT]",
245
- "description": "Creates bold inline Markdown content.",
246
- "arguments": { "CONTENT": {
247
- "type": "STRING",
248
- "defaultValue": "important"
249
- } }
250
- },
251
- {
252
- "opcode": "italic",
253
- "blockType": "REPORTER",
254
- "text": "italic [CONTENT]",
255
- "description": "Creates italic inline Markdown content.",
256
- "arguments": { "CONTENT": {
257
- "type": "STRING",
258
- "defaultValue": "note"
259
- } }
260
- },
261
- {
262
- "opcode": "link",
263
- "blockType": "REPORTER",
264
- "text": "link [CONTENT] URL [URL]",
265
- "description": "Creates a Markdown link with a conservatively validated destination.",
266
- "arguments": {
267
- "CONTENT": {
268
- "type": "STRING",
269
- "defaultValue": "TurboWarp"
270
- },
271
- "URL": {
272
- "type": "STRING",
273
- "defaultValue": "https://turbowarp.org/"
274
- }
275
- }
276
- },
277
- {
278
- "opcode": "code",
279
- "blockType": "REPORTER",
280
- "text": "code [TEXT]",
281
- "description": "Creates inline code content.",
282
- "arguments": { "TEXT": {
283
- "type": "STRING",
284
- "defaultValue": "status"
285
- } }
286
- },
287
- {
288
- "opcode": "heading",
289
- "blockType": "REPORTER",
290
- "text": "heading [LEVEL] [CONTENT]",
291
- "description": "Creates a heading with the level clamped to 1 through 6.",
292
- "arguments": {
293
- "LEVEL": {
294
- "type": "NUMBER",
295
- "defaultValue": 1
296
- },
297
- "CONTENT": {
298
- "type": "STRING",
299
- "defaultValue": "Sensor"
300
- }
301
- }
302
- },
303
- {
304
- "opcode": "paragraph",
305
- "blockType": "REPORTER",
306
- "text": "paragraph [CONTENT]",
307
- "description": "Creates a paragraph block.",
308
- "arguments": { "CONTENT": {
309
- "type": "STRING",
310
- "defaultValue": "ready"
311
- } }
312
- },
313
- {
314
- "opcode": "quote",
315
- "blockType": "REPORTER",
316
- "text": "quote [CONTENT]",
317
- "description": "Creates a block quote.",
318
- "arguments": { "CONTENT": {
319
- "type": "STRING",
320
- "defaultValue": "quoted"
321
- } }
322
- },
323
- {
324
- "opcode": "codeBlock",
325
- "blockType": "REPORTER",
326
- "text": "code block [TEXT] language [LANGUAGE]",
327
- "description": "Creates a fenced code block.",
328
- "arguments": {
329
- "TEXT": {
330
- "type": "STRING",
331
- "defaultValue": "console.log('ok')"
332
- },
333
- "LANGUAGE": {
334
- "type": "STRING",
335
- "defaultValue": "js"
336
- }
337
- }
338
- },
339
- {
340
- "opcode": "listItem",
341
- "blockType": "REPORTER",
342
- "text": "list item [CONTENT]",
343
- "description": "Creates a list item fragment.",
344
- "arguments": { "CONTENT": {
345
- "type": "STRING",
346
- "defaultValue": "item"
347
- } }
348
- },
349
- {
350
- "opcode": "unorderedList",
351
- "blockType": "REPORTER",
352
- "text": "unordered list [ITEMS]",
353
- "description": "Creates an unordered list from item fragments.",
354
- "arguments": { "ITEMS": {
355
- "type": "STRING",
356
- "defaultValue": ""
357
- } }
358
- },
359
- {
360
- "opcode": "orderedList",
361
- "blockType": "REPORTER",
362
- "text": "ordered list [ITEMS]",
363
- "description": "Creates an ordered list from item fragments.",
364
- "arguments": { "ITEMS": {
365
- "type": "STRING",
366
- "defaultValue": ""
367
- } }
368
- },
369
- {
370
- "opcode": "concat",
371
- "blockType": "REPORTER",
372
- "text": "[LEFT] followed by [RIGHT]",
373
- "description": "Creates a new Markdown fragment sequence without mutating either input.",
374
- "arguments": {
375
- "LEFT": {
376
- "type": "STRING",
377
- "defaultValue": ""
378
- },
379
- "RIGHT": {
380
- "type": "STRING",
381
- "defaultValue": ""
382
- }
383
- }
384
- },
385
- {
386
- "opcode": "render",
387
- "blockType": "REPORTER",
388
- "text": "render Markdown [FRAGMENT]",
389
- "description": "Renders a Markdown fragment to final Markdown text without updating stored validation errors.",
390
- "arguments": { "FRAGMENT": {
391
- "type": "STRING",
392
- "defaultValue": ""
393
- } }
394
- },
395
- {
396
- "opcode": "renderWithValidation",
397
- "blockType": "REPORTER",
398
- "text": "render Markdown with validation [FRAGMENT]",
399
- "description": "Validates a Markdown fragment, stores any validation errors, and renders final Markdown text.",
400
- "arguments": { "FRAGMENT": {
401
- "type": "STRING",
402
- "defaultValue": ""
403
- } }
404
- },
405
- {
406
- "opcode": "lastValidationErrors",
407
- "blockType": "REPORTER",
408
- "text": "last Markdown validation errors",
409
- "description": "Returns validation errors stored by the most recent render Markdown with validation block.",
410
- "arguments": {}
411
- },
412
- {
413
- "opcode": "lastRenderHasValidationErrors",
414
- "blockType": "BOOLEAN",
415
- "text": "last rendered Markdown has validation errors?",
416
- "description": "Reports whether the most recent validated Markdown render stored validation errors.",
417
- "arguments": {}
418
- },
419
- {
420
- "opcode": "validateMarkdown",
421
- "blockType": "REPORTER",
422
- "text": "validate Markdown [FRAGMENT]",
423
- "description": "Returns simple validation diagnostics for a Markdown fragment.",
424
- "arguments": { "FRAGMENT": {
425
- "type": "STRING",
426
- "defaultValue": ""
427
- } }
428
- },
429
- {
430
- "opcode": "isValidMarkdown",
431
- "blockType": "BOOLEAN",
432
- "text": "Markdown [FRAGMENT] is valid?",
433
- "description": "Reports whether simple validation found no Markdown errors.",
434
- "arguments": { "FRAGMENT": {
435
- "type": "STRING",
436
- "defaultValue": ""
437
- } }
438
- }
439
- ]
440
- };
441
- //#endregion
442
- //#region src/markdown.ts
443
- var empty = { kind: "empty" };
444
- var SAFE_URL_PATTERN = /^(?:https?:|mailto:|tel:|\/|\.\/|\.\.\/|#|\?|$)/iu;
445
- var lastRenderValidationResult = {
446
- valid: true,
447
- issues: []
448
- };
449
- function text(value) {
450
- return {
451
- kind: "text",
452
- value
453
- };
454
- }
455
- function bold(content) {
456
- return {
457
- kind: "bold",
458
- content: normalizeContent(content)
459
- };
460
- }
461
- function italic(content) {
462
- return {
463
- kind: "italic",
464
- content: normalizeContent(content)
465
- };
466
- }
467
- function link(content, url) {
468
- validateSafeUrl(url);
469
- return {
470
- kind: "link",
471
- content: normalizeContent(content),
472
- url
473
- };
474
- }
475
- function code(value) {
476
- return {
477
- kind: "code",
478
- value
479
- };
480
- }
481
- function heading(level, content) {
482
- return {
483
- kind: "heading",
484
- level: clampHeadingLevel(level),
485
- content: normalizeContent(content)
486
- };
487
- }
488
- function paragraph(content) {
489
- return {
490
- kind: "paragraph",
491
- content: normalizeContent(content)
492
- };
493
- }
494
- function quote(content) {
495
- return {
496
- kind: "quote",
497
- content: normalizeContent(content)
498
- };
499
- }
500
- function codeBlock(value, language = "") {
501
- return {
502
- kind: "codeBlock",
503
- language: sanitizeLanguage(language),
504
- value
505
- };
506
- }
507
- function listItem(content) {
508
- return {
509
- kind: "listItem",
510
- content: normalizeContent(content)
511
- };
512
- }
513
- function unorderedList(items) {
514
- return {
515
- kind: "list",
516
- ordered: false,
517
- items: normalizeItems(items)
518
- };
519
- }
520
- function orderedList(items) {
521
- return {
522
- kind: "list",
523
- ordered: true,
524
- items: normalizeItems(items)
525
- };
526
- }
527
- function concat(left, right) {
528
- const children = [...flattenSequence(left), ...flattenSequence(right)].filter((child) => child.kind !== "empty");
529
- if (children.length === 0) return empty;
530
- if (children.length === 1) return children[0] ?? empty;
531
- return {
532
- kind: "sequence",
533
- children
534
- };
535
- }
536
- function render(fragment) {
537
- return renderDocument(fragment);
538
- }
539
- function renderWithValidation(fragment) {
540
- lastRenderValidationResult = validate(fragment);
541
- return renderDocument(fragment);
542
- }
543
- function validate(fragment) {
544
- const issues = [];
545
- validateFragment(fragment, "$", [], issues);
546
- if (fragment.kind === "empty") issues.push({
547
- severity: "warning",
548
- path: "$",
549
- message: "Markdown fragment is empty."
550
- });
551
- return {
552
- valid: issues.every((issue) => issue.severity !== "error"),
553
- issues
554
- };
555
- }
556
- function isValid(fragment) {
557
- return validate(fragment).valid;
558
- }
559
- function getLastRenderValidationErrors() {
560
- return lastRenderValidationResult.issues.filter((issue) => issue.severity === "error");
561
- }
562
- function formatValidationResult(result) {
563
- if (result.issues.length === 0) return "valid";
564
- return result.issues.map((issue) => `${issue.severity}: ${issue.path}: ${issue.message}`).join("\n");
565
- }
566
- function formatValidationErrors(issues) {
567
- if (issues.length === 0) return "";
568
- return issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
569
- }
570
- function getLastRenderValidationErrorText() {
571
- return formatValidationErrors(getLastRenderValidationErrors());
572
- }
573
- function normalizeContent(content) {
574
- return typeof content === "string" ? text(content) : content;
575
- }
576
- function validateFragment(fragment, path, ancestors, issues) {
577
- const parent = ancestors[ancestors.length - 1];
578
- const inlineAncestor = ancestors.find((ancestor) => [
579
- "bold",
580
- "italic",
581
- "link"
582
- ].includes(ancestor.kind));
583
- if (!isInline(fragment) && inlineAncestor !== void 0) issues.push({
584
- severity: "error",
585
- path,
586
- message: `${fragment.kind} cannot be nested inside ${inlineAncestor.kind}.`
587
- });
588
- if (fragment.kind === "listItem" && parent?.kind !== "list") issues.push({
589
- severity: "error",
590
- path,
591
- message: "listItem must be inside a list."
592
- });
593
- validateWarnings(fragment, path, issues);
594
- for (const [index, child] of childFragments(fragment).entries()) validateFragment(child, `${path}.children[${index}]`, [...ancestors, fragment], issues);
595
- }
596
- function validateWarnings(fragment, path, issues) {
597
- if (fragment.kind === "heading" && isEmptyish(fragment.content)) issues.push({
598
- severity: "warning",
599
- path,
600
- message: "heading should have content."
601
- });
602
- if (fragment.kind === "paragraph" && isEmptyish(fragment.content)) issues.push({
603
- severity: "warning",
604
- path,
605
- message: "paragraph is empty."
606
- });
607
- if (fragment.kind === "link" && isEmptyish(fragment.content)) issues.push({
608
- severity: "warning",
609
- path,
610
- message: "link should have visible content."
611
- });
612
- if (fragment.kind === "link" && fragment.url.trim().length === 0) issues.push({
613
- severity: "warning",
614
- path,
615
- message: "link should have a destination URL."
616
- });
617
- if (fragment.kind === "list" && fragment.items.length === 0) issues.push({
618
- severity: "warning",
619
- path,
620
- message: "list should contain at least one item."
621
- });
622
- }
623
- function childFragments(fragment) {
624
- switch (fragment.kind) {
625
- case "bold":
626
- case "italic":
627
- case "link":
628
- case "heading":
629
- case "paragraph":
630
- case "quote":
631
- case "listItem": return [fragment.content];
632
- case "list": return fragment.items;
633
- case "sequence": return fragment.children;
634
- default: return [];
635
- }
636
- }
637
- function isEmptyish(fragment) {
638
- if (fragment.kind === "empty") return true;
639
- if (fragment.kind === "text" || fragment.kind === "code") return fragment.value.length === 0;
640
- if (fragment.kind === "sequence") return fragment.children.every(isEmptyish);
641
- return false;
642
- }
643
- function renderDocument(fragment) {
644
- if (fragment.kind === "empty") return "";
645
- if (fragment.kind === "sequence") {
646
- if (fragment.children.every((child) => isInline(child) || child.kind === "sequence")) return renderInline(fragment);
647
- return fragment.children.map(renderDocument).filter(Boolean).join("\n\n");
648
- }
649
- if (isInline(fragment)) return renderInline(fragment);
650
- return renderBlock(fragment);
651
- }
652
- function renderBlock(fragment) {
653
- switch (fragment.kind) {
654
- case "heading": return `${"#".repeat(fragment.level)} ${renderInlineish(fragment.content)}`;
655
- case "paragraph": return renderInlineish(fragment.content);
656
- case "quote": return renderDocument(fragment.content).split("\n").map((line) => line.length === 0 ? ">" : `> ${line}`).join("\n");
657
- case "codeBlock": return renderCodeBlock(fragment);
658
- case "list": return fragment.items.map((item, index) => renderListItem(item, fragment.ordered ? `${index + 1}.` : "-")).join("\n");
659
- case "listItem": return renderInlineish(fragment.content);
660
- default: return renderDocument(fragment);
661
- }
662
- }
663
- function renderInline(fragment) {
664
- switch (fragment.kind) {
665
- case "text": return escapeMarkdownText(fragment.value);
666
- case "bold": return `**${renderInlineish(fragment.content)}**`;
667
- case "italic": return `*${renderInlineish(fragment.content)}*`;
668
- case "link": return `[${renderInlineish(fragment.content)}](${escapeUrl(fragment.url)})`;
669
- case "code": return renderInlineCode(fragment.value);
670
- case "sequence": return fragment.children.map(renderInlineish).join("");
671
- case "empty": return "";
672
- default: return renderBlock(fragment);
673
- }
674
- }
675
- function renderInlineish(fragment) {
676
- return isInline(fragment) || fragment.kind === "sequence" ? renderInline(fragment) : renderBlock(fragment);
677
- }
678
- function renderCodeBlock(fragment) {
679
- const fence = longestBacktickRun(fragment.value) >= 3 ? "````" : "```";
680
- return `${fence}${fragment.language.length > 0 ? fragment.language : ""}\n${fragment.value}\n${fence}`;
681
- }
682
- function renderInlineCode(value) {
683
- const fence = "`".repeat(Math.max(1, longestBacktickRun(value) + 1));
684
- return `${fence}${value.startsWith("`") || value.endsWith("`") || value.includes("\n") ? ` ${value} ` : value}${fence}`;
685
- }
686
- function renderListItem(fragment, marker) {
687
- const [first = "", ...rest] = renderDocument(fragment.kind === "listItem" ? fragment.content : fragment).split("\n");
688
- const padding = " ".repeat(marker.length + 1);
689
- return [`${marker} ${first}`, ...rest.map((line) => `${padding}${line}`)].join("\n");
690
- }
691
- function normalizeItems(items) {
692
- const fragment = normalizeContent(items);
693
- if (fragment.kind === "sequence") return fragment.children;
694
- if (fragment.kind === "empty") return [];
695
- return [fragment];
696
- }
697
- function flattenSequence(fragment) {
698
- if (fragment.kind === "sequence") return fragment.children.flatMap(flattenSequence);
699
- return [fragment];
700
- }
701
- function isInline(fragment) {
702
- return [
703
- "text",
704
- "bold",
705
- "italic",
706
- "link",
707
- "code",
708
- "empty"
709
- ].includes(fragment.kind);
710
- }
711
- function clampHeadingLevel(level) {
712
- if (!Number.isFinite(level)) return 1;
713
- return Math.min(6, Math.max(1, Math.trunc(level)));
714
- }
715
- function sanitizeLanguage(language) {
716
- return language.trim().replace(/[^a-zA-Z0-9_+.-]/gu, "");
717
- }
718
- function validateSafeUrl(value) {
719
- const trimmed = value.trim();
720
- if (!SAFE_URL_PATTERN.test(trimmed)) throw new TypeError(`Unsafe URL value: ${value}`);
721
- }
722
- function escapeMarkdownText(value) {
723
- return value.replace(/([\\`*_{}[\]()#+\-.!<>|])/gu, "\\$1");
724
- }
725
- function escapeUrl(value) {
726
- return value.trim().replace(/\)/gu, "%29").replace(/\s/gu, "%20");
727
- }
728
- function longestBacktickRun(value) {
729
- return Math.max(0, ...Array.from(value.matchAll(/`+/gu), (match) => match[0]?.length ?? 0));
730
- }
731
- //#endregion
732
- //#region src/extension.ts
733
- var SERIALIZED_PREFIX = "turbowarp-markdown:v1:";
734
- var blockDefinitions = block_definitions_default.blocks;
735
- var MarkdownExtension = class {
736
- constructor() {
737
- this.fixedInputs = fixedInputRegistration(typeof Scratch === "undefined" ? void 0 : Scratch);
738
- }
739
- dispose() {
740
- this.fixedInputs.dispose();
741
- }
742
- getInfo() {
743
- this.fixedInputs.ensure(blockDefinitions.map((block) => `${extensionConfig.id}_${block.opcode}`));
744
- return {
745
- id: extensionConfig.id,
746
- name: Scratch.translate(block_definitions_default.extensionName),
747
- docsURI: extensionConfig.docsURI,
748
- blockIconURI: extensionConfig.blockIconURI,
749
- blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
750
- };
751
- }
752
- text(args) {
753
- return encode(text(Scratch.Cast.toString(args.TEXT)));
754
- }
755
- bold(args) {
756
- return encode(bold(decodeOrText(args.CONTENT)));
757
- }
758
- italic(args) {
759
- return encode(italic(decodeOrText(args.CONTENT)));
760
- }
761
- link(args) {
762
- return encode(link(decodeOrText(args.CONTENT), Scratch.Cast.toString(args.URL)));
763
- }
764
- code(args) {
765
- return encode(code(Scratch.Cast.toString(args.TEXT)));
766
- }
767
- heading(args) {
768
- return encode(heading(Scratch.Cast.toNumber(args.LEVEL), decodeOrText(args.CONTENT)));
769
- }
770
- paragraph(args) {
771
- return encode(paragraph(decodeOrText(args.CONTENT)));
772
- }
773
- quote(args) {
774
- return encode(quote(decodeOrText(args.CONTENT)));
775
- }
776
- codeBlock(args) {
777
- return encode(codeBlock(Scratch.Cast.toString(args.TEXT), Scratch.Cast.toString(args.LANGUAGE)));
778
- }
779
- listItem(args) {
780
- return encode(listItem(decodeOrText(args.CONTENT)));
781
- }
782
- unorderedList(args) {
783
- return encode(unorderedList(decodeOrText(args.ITEMS)));
784
- }
785
- orderedList(args) {
786
- return encode(orderedList(decodeOrText(args.ITEMS)));
787
- }
788
- concat(args) {
789
- return encode(concat(decodeOrText(args.LEFT), decodeOrText(args.RIGHT)));
790
- }
791
- render(args) {
792
- return render(decodeOrText(args.FRAGMENT));
793
- }
794
- renderWithValidation(args) {
795
- return renderWithValidation(decodeOrText(args.FRAGMENT));
796
- }
797
- lastValidationErrors() {
798
- return getLastRenderValidationErrorText();
799
- }
800
- lastRenderHasValidationErrors() {
801
- return getLastRenderValidationErrors().length > 0;
802
- }
803
- validateMarkdown(args) {
804
- return formatValidationResult(validate(decodeOrText(args.FRAGMENT)));
805
- }
806
- isValidMarkdown(args) {
807
- return isValid(decodeOrText(args.FRAGMENT));
808
- }
809
- toScratchBlock(block) {
810
- return {
811
- opcode: block.opcode,
812
- blockType: Scratch.BlockType[block.blockType],
813
- text: Scratch.translate(block.text),
814
- arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
815
- type: Scratch.ArgumentType[argument.type],
816
- defaultValue: argument.defaultValue
817
- }]))
818
- };
819
- }
820
- };
821
- function encode(fragment) {
822
- return `${SERIALIZED_PREFIX}${JSON.stringify(fragment)}`;
823
- }
824
- function decodeOrText(value) {
825
- const raw = Scratch.Cast.toString(value);
826
- if (!raw.startsWith(SERIALIZED_PREFIX)) return text(raw);
827
- return parseFragment(raw.slice(22));
828
- }
829
- function parseFragment(json) {
830
- const parsed = JSON.parse(json);
831
- if (!isFragment(parsed)) throw new TypeError("Invalid serialized Markdown fragment.");
832
- return parsed;
833
- }
834
- function isFragment(value) {
835
- if (typeof value !== "object" || value === null) return false;
836
- const record = value;
837
- if (record.kind === "empty") return true;
838
- if (record.kind === "text" || record.kind === "code") return typeof record.value === "string";
839
- if (record.kind === "bold" || record.kind === "italic" || record.kind === "paragraph") return isFragment(record.content);
840
- if (record.kind === "link") return typeof record.url === "string" && isFragment(record.content);
841
- if (record.kind === "heading") return typeof record.level === "number" && isFragment(record.content);
842
- if (record.kind === "quote" || record.kind === "listItem") return isFragment(record.content);
843
- if (record.kind === "codeBlock") return typeof record.language === "string" && typeof record.value === "string";
844
- if (record.kind === "list") return typeof record.ordered === "boolean" && Array.isArray(record.items) && record.items.every(isFragment);
845
- if (record.kind === "sequence") return Array.isArray(record.children) && record.children.every(isFragment);
846
- return false;
847
- }
848
- //#endregion
849
- //#region src/index.ts
850
- if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
851
- Scratch.extensions.register(new MarkdownExtension());
852
- //#endregion
10
+ //#region src/config.ts
11
+ var extensionConfig = {
12
+ id: "kubohiroyamarkdown",
13
+ slug: "turbowarp-markdown",
14
+ name: "TurboWarp Markdown",
15
+ description: "Build Markdown documents with immutable reporter blocks.",
16
+ author: "Hiroya Kubo",
17
+ license: "MPL-2.0",
18
+ unsandboxed: false,
19
+ docsURI: "https://kubohiroya.github.io/turbowarp-markdown/",
20
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNiIgeT0iOCIgd2lkdGg9IjM2IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzJGNjM4NiIvPjxwYXRoIGQ9Ik0xMyAzMFYxOGw1IDcgNS03djEyTTI3LjUgMjB2MTBNMjcuNSAyMGgyLjVhNSA1IDAgMCAxIDAgMTBoLTIuNSIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmZmZmIiBzdHJva2Utd2lkdGg9IjMiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjwvc3ZnPg=="
21
+ };
22
+ //#endregion
23
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-extension-data-editor@0.4.0_react@18.3.1/node_modules/@kubohiroya/turbowarp-extension-data-editor/dist/fixed-input-schema.js
24
+ var numberToken = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/u;
25
+ var invalidNumber = Object.freeze({
26
+ kind: "invalid",
27
+ code: "fixed-number-input-invalid"
28
+ });
29
+ /**
30
+ * Parse a NEW numeric draft according to NP-finite-new-input-v1.
31
+ * Never apply this to opening/no-op raw values or use it as an owner validator.
32
+ * Keep the validated token so negative zero, precision and exponent spelling survive.
33
+ */
34
+ function parseFixedNumberInput(input) {
35
+ if (typeof input === "number") {
36
+ if (!Number.isFinite(input)) return invalidNumber;
37
+ return Object.freeze({
38
+ kind: "valid",
39
+ token: Object.is(input, -0) ? "-0" : String(input),
40
+ value: input
41
+ });
42
+ }
43
+ if (typeof input !== "string") return invalidNumber;
44
+ const token = input.trim();
45
+ if (!numberToken.test(token)) return invalidNumber;
46
+ const value = Number(token);
47
+ return Number.isFinite(value) ? Object.freeze({
48
+ kind: "valid",
49
+ token,
50
+ value
51
+ }) : invalidNumber;
52
+ }
53
+ var block_editor_fixed_inputs_schema_default = {
54
+ $schema: "https://json-schema.org/draft/2020-12/schema",
55
+ $id: "https://kubohiroya.github.io/turbowarp-markdown/schemas/block-editor-fixed-inputs.schema.json",
56
+ $defs: { "heading": {
57
+ "type": "object",
58
+ "properties": { "LEVEL": { "type": "number" } },
59
+ "required": ["LEVEL"],
60
+ "additionalProperties": true
61
+ } }
62
+ };
63
+ //#endregion
64
+ //#region src/fixed-input-schema.ts
65
+ var repository$1 = "turbowarp-markdown";
66
+ /** The owner JSON document is canonical; this selects a primitive field fragment. */
67
+ function fixedInputBundle(opcode, argument) {
68
+ const source = {
69
+ repository: repository$1,
70
+ path: "schemas/block-editor-fixed-inputs.schema.json",
71
+ symbol: `#/$defs/${opcode}/properties/${argument}`
72
+ };
73
+ const blocks = block_editor_fixed_inputs_schema_default.$defs;
74
+ return {
75
+ identity: {
76
+ ownerId: repository$1,
77
+ contractId: opcode,
78
+ revision: "fixed-inputs-v1",
79
+ variantId: argument
80
+ },
81
+ dialect: "2020-12",
82
+ root: {
83
+ retrievalUri: block_editor_fixed_inputs_schema_default.$id,
84
+ document: blocks[opcode].properties[argument],
85
+ artifact: {
86
+ role: "canonical-schema",
87
+ source
88
+ }
89
+ },
90
+ resources: [],
91
+ provenance: {
92
+ canonicalSources: [source, {
93
+ repository: repository$1,
94
+ path: "src/extension.ts",
95
+ symbol: opcode
96
+ }],
97
+ generatedFiles: [],
98
+ referenceSchemas: [],
99
+ generationSources: []
100
+ }
101
+ };
102
+ }
103
+ //#endregion
104
+ //#region src/fixed-input-editors.ts
105
+ var extensionId = "kubohiroyamarkdown";
106
+ var repository = "turbowarp-markdown";
107
+ var fields = [{
108
+ "opcode": "heading",
109
+ "argument": "LEVEL",
110
+ "control": "number",
111
+ "choices": [],
112
+ "normalization": "identity",
113
+ "shape": "math_number.NUM",
114
+ "maxBytes": false
115
+ }];
116
+ function literalString(value) {
117
+ if (typeof value !== "string") throw new TypeError("Expected a string literal.");
118
+ return value;
119
+ }
120
+ /** Legacy nonempty finite aliases are projections; opening never creates a write. */
121
+ function existingFixedNumber(value) {
122
+ if (typeof value !== "string" && typeof value !== "number" || typeof value === "string" && value.trim() === "") throw new TypeError("Unavailable numeric projection.");
123
+ const number = Number(value);
124
+ if (!Number.isFinite(number)) throw new TypeError("Unavailable numeric projection.");
125
+ return number;
126
+ }
127
+ function normalizeChoice(field, raw) {
128
+ if (field.normalization === "lowercase") return raw.toLowerCase();
129
+ if (field.normalization === "method") return raw.trim().toUpperCase();
130
+ if (field.normalization === "trim") return raw.trim();
131
+ if (field.normalization === "parse-format") {
132
+ const lower = raw.trim().toLowerCase();
133
+ return lower === "json" ? "JSON" : lower === "yaml" ? "YAML" : lower === "auto" ? "auto" : raw;
134
+ }
135
+ return raw;
136
+ }
137
+ function binding(field) {
138
+ return {
139
+ argument: field.argument,
140
+ schemaBundle: fixedInputBundle(field.opcode, field.argument),
141
+ control: {
142
+ kind: field.control,
143
+ ...field.control === "enum" ? { choices: field.choices.map((value) => ({ value })) } : {}
144
+ },
145
+ read(value) {
146
+ return field.control === "number" ? existingFixedNumber(value) : normalizeChoice(field, literalString(value));
147
+ },
148
+ encode(value) {
149
+ if (field.control === "number") {
150
+ const parsed = parseFixedNumberInput(value);
151
+ if (parsed.kind !== "valid") throw new TypeError("Invalid new numeric input.");
152
+ return parsed.token;
153
+ }
154
+ const raw = literalString(value), normalized = normalizeChoice(field, raw);
155
+ if (!field.choices.includes(normalized)) throw new TypeError("Unsupported fixed choice.");
156
+ return field.shape === "menu-shadow" || field.shape === "direct-field-dropdown" ? normalized : raw;
157
+ },
158
+ validateCandidate(value) {
159
+ try {
160
+ if (field.control === "number") {
161
+ const number = existingFixedNumber(value);
162
+ if (field.maxBytes && (!Number.isSafeInteger(Math.trunc(number)) || Math.trunc(number) < 1)) return [{ message: "Invalid named body size." }];
163
+ return [];
164
+ }
165
+ return field.choices.includes(normalizeChoice(field, literalString(value))) ? [] : [{ message: "Unsupported fixed choice." }];
166
+ } catch {
167
+ return [{ message: "Invalid fixed input." }];
168
+ }
169
+ }
170
+ };
171
+ }
172
+ var fixedInputEditors = [...new Set(fields.map((f) => f.opcode))].map((opcode) => ({
173
+ apiVersion: 1,
174
+ extensionId,
175
+ editorId: `${opcode}-fixed-inputs`,
176
+ opcodes: [`${extensionId}_${opcode}`],
177
+ contractId: `${repository}/${opcode}`,
178
+ contractRevision: "fixed-inputs-v1",
179
+ bindings: fields.filter((field) => field.opcode === opcode).map(binding),
180
+ validationContext: () => ({
181
+ consumerId: repository,
182
+ nowMs: 0,
183
+ settings: null
184
+ })
185
+ }));
186
+ /** Registration follows the advertised opcode membership and the optional host capability. */
187
+ function fixedInputRegistration(scratch) {
188
+ const host = scratch ?? {};
189
+ let active;
190
+ let membership = "";
191
+ const removers = [];
192
+ let stopped = false;
193
+ const clear = () => {
194
+ host.vm?.runtime?.off?.("RUNTIME_DISPOSED", shutdown);
195
+ for (const remove of removers.splice(0).reverse()) remove();
196
+ active = void 0;
197
+ membership = "";
198
+ };
199
+ const shutdown = () => {
200
+ stopped = true;
201
+ clear();
202
+ };
203
+ return {
204
+ ensure(visibleOpcodes) {
205
+ const api = host.gui?.blockEditors;
206
+ const definitions = fixedInputEditors.filter((definition) => definition.opcodes.every((opcode) => visibleOpcodes.includes(opcode)));
207
+ const key = definitions.map((definition) => definition.editorId).join(",");
208
+ if (stopped || api === active && membership === key) return;
209
+ clear();
210
+ if (api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function" || !definitions.length) return;
211
+ try {
212
+ for (const definition of definitions) {
213
+ const remove = api.registerFixedInputEditor.call(api, definition);
214
+ if (typeof remove !== "function") throw new TypeError("Invalid fixed input cleanup.");
215
+ removers.push(remove);
216
+ }
217
+ active = api;
218
+ membership = key;
219
+ host.vm?.runtime?.on?.("RUNTIME_DISPOSED", shutdown);
220
+ } catch (error) {
221
+ clear();
222
+ throw error;
223
+ }
224
+ },
225
+ dispose: shutdown
226
+ };
227
+ }
228
+ var block_definitions_default = {
229
+ extensionName: "TurboWarp Markdown",
230
+ blocks: [
231
+ {
232
+ "opcode": "text",
233
+ "blockType": "REPORTER",
234
+ "text": "text [TEXT]",
235
+ "description": "Creates escaped Markdown text.",
236
+ "arguments": { "TEXT": {
237
+ "type": "STRING",
238
+ "defaultValue": "Hello *world*"
239
+ } }
240
+ },
241
+ {
242
+ "opcode": "bold",
243
+ "blockType": "REPORTER",
244
+ "text": "bold [CONTENT]",
245
+ "description": "Creates bold inline Markdown content.",
246
+ "arguments": { "CONTENT": {
247
+ "type": "STRING",
248
+ "defaultValue": "important"
249
+ } }
250
+ },
251
+ {
252
+ "opcode": "italic",
253
+ "blockType": "REPORTER",
254
+ "text": "italic [CONTENT]",
255
+ "description": "Creates italic inline Markdown content.",
256
+ "arguments": { "CONTENT": {
257
+ "type": "STRING",
258
+ "defaultValue": "note"
259
+ } }
260
+ },
261
+ {
262
+ "opcode": "link",
263
+ "blockType": "REPORTER",
264
+ "text": "link [CONTENT] URL [URL]",
265
+ "description": "Creates a Markdown link with a conservatively validated destination.",
266
+ "arguments": {
267
+ "CONTENT": {
268
+ "type": "STRING",
269
+ "defaultValue": "TurboWarp"
270
+ },
271
+ "URL": {
272
+ "type": "STRING",
273
+ "defaultValue": "https://turbowarp.org/"
274
+ }
275
+ }
276
+ },
277
+ {
278
+ "opcode": "code",
279
+ "blockType": "REPORTER",
280
+ "text": "code [TEXT]",
281
+ "description": "Creates inline code content.",
282
+ "arguments": { "TEXT": {
283
+ "type": "STRING",
284
+ "defaultValue": "status"
285
+ } }
286
+ },
287
+ {
288
+ "opcode": "heading",
289
+ "blockType": "REPORTER",
290
+ "text": "heading [LEVEL] [CONTENT]",
291
+ "description": "Creates a heading with the level clamped to 1 through 6.",
292
+ "arguments": {
293
+ "LEVEL": {
294
+ "type": "NUMBER",
295
+ "defaultValue": 1
296
+ },
297
+ "CONTENT": {
298
+ "type": "STRING",
299
+ "defaultValue": "Sensor"
300
+ }
301
+ }
302
+ },
303
+ {
304
+ "opcode": "paragraph",
305
+ "blockType": "REPORTER",
306
+ "text": "paragraph [CONTENT]",
307
+ "description": "Creates a paragraph block.",
308
+ "arguments": { "CONTENT": {
309
+ "type": "STRING",
310
+ "defaultValue": "ready"
311
+ } }
312
+ },
313
+ {
314
+ "opcode": "quote",
315
+ "blockType": "REPORTER",
316
+ "text": "quote [CONTENT]",
317
+ "description": "Creates a block quote.",
318
+ "arguments": { "CONTENT": {
319
+ "type": "STRING",
320
+ "defaultValue": "quoted"
321
+ } }
322
+ },
323
+ {
324
+ "opcode": "codeBlock",
325
+ "blockType": "REPORTER",
326
+ "text": "code block [TEXT] language [LANGUAGE]",
327
+ "description": "Creates a fenced code block.",
328
+ "arguments": {
329
+ "TEXT": {
330
+ "type": "STRING",
331
+ "defaultValue": "console.log('ok')"
332
+ },
333
+ "LANGUAGE": {
334
+ "type": "STRING",
335
+ "defaultValue": "js"
336
+ }
337
+ }
338
+ },
339
+ {
340
+ "opcode": "listItem",
341
+ "blockType": "REPORTER",
342
+ "text": "list item [CONTENT]",
343
+ "description": "Creates a list item fragment.",
344
+ "arguments": { "CONTENT": {
345
+ "type": "STRING",
346
+ "defaultValue": "item"
347
+ } }
348
+ },
349
+ {
350
+ "opcode": "unorderedList",
351
+ "blockType": "REPORTER",
352
+ "text": "unordered list [ITEMS]",
353
+ "description": "Creates an unordered list from item fragments.",
354
+ "arguments": { "ITEMS": {
355
+ "type": "STRING",
356
+ "defaultValue": ""
357
+ } }
358
+ },
359
+ {
360
+ "opcode": "orderedList",
361
+ "blockType": "REPORTER",
362
+ "text": "ordered list [ITEMS]",
363
+ "description": "Creates an ordered list from item fragments.",
364
+ "arguments": { "ITEMS": {
365
+ "type": "STRING",
366
+ "defaultValue": ""
367
+ } }
368
+ },
369
+ {
370
+ "opcode": "concat",
371
+ "blockType": "REPORTER",
372
+ "text": "[LEFT] followed by [RIGHT]",
373
+ "description": "Creates a new Markdown fragment sequence without mutating either input.",
374
+ "arguments": {
375
+ "LEFT": {
376
+ "type": "STRING",
377
+ "defaultValue": ""
378
+ },
379
+ "RIGHT": {
380
+ "type": "STRING",
381
+ "defaultValue": ""
382
+ }
383
+ }
384
+ },
385
+ {
386
+ "opcode": "render",
387
+ "blockType": "REPORTER",
388
+ "text": "render Markdown [FRAGMENT]",
389
+ "description": "Renders a Markdown fragment to final Markdown text without updating stored validation errors.",
390
+ "arguments": { "FRAGMENT": {
391
+ "type": "STRING",
392
+ "defaultValue": ""
393
+ } }
394
+ },
395
+ {
396
+ "opcode": "renderWithValidation",
397
+ "blockType": "REPORTER",
398
+ "text": "render Markdown with validation [FRAGMENT]",
399
+ "description": "Validates a Markdown fragment, stores any validation errors, and renders final Markdown text.",
400
+ "arguments": { "FRAGMENT": {
401
+ "type": "STRING",
402
+ "defaultValue": ""
403
+ } }
404
+ },
405
+ {
406
+ "opcode": "lastValidationErrors",
407
+ "blockType": "REPORTER",
408
+ "text": "last Markdown validation errors",
409
+ "description": "Returns validation errors stored by the most recent render Markdown with validation block.",
410
+ "arguments": {}
411
+ },
412
+ {
413
+ "opcode": "lastRenderHasValidationErrors",
414
+ "blockType": "BOOLEAN",
415
+ "text": "last rendered Markdown has validation errors?",
416
+ "description": "Reports whether the most recent validated Markdown render stored validation errors.",
417
+ "arguments": {}
418
+ },
419
+ {
420
+ "opcode": "validateMarkdown",
421
+ "blockType": "REPORTER",
422
+ "text": "validate Markdown [FRAGMENT]",
423
+ "description": "Returns simple validation diagnostics for a Markdown fragment.",
424
+ "arguments": { "FRAGMENT": {
425
+ "type": "STRING",
426
+ "defaultValue": ""
427
+ } }
428
+ },
429
+ {
430
+ "opcode": "isValidMarkdown",
431
+ "blockType": "BOOLEAN",
432
+ "text": "Markdown [FRAGMENT] is valid?",
433
+ "description": "Reports whether simple validation found no Markdown errors.",
434
+ "arguments": { "FRAGMENT": {
435
+ "type": "STRING",
436
+ "defaultValue": ""
437
+ } }
438
+ }
439
+ ]
440
+ };
441
+ //#endregion
442
+ //#region src/markdown.ts
443
+ var empty = { kind: "empty" };
444
+ var SAFE_URL_PATTERN = /^(?:https?:|mailto:|tel:|\/|\.\/|\.\.\/|#|\?|$)/iu;
445
+ var lastRenderValidationResult = {
446
+ valid: true,
447
+ issues: []
448
+ };
449
+ function text(value) {
450
+ return {
451
+ kind: "text",
452
+ value
453
+ };
454
+ }
455
+ function bold(content) {
456
+ return {
457
+ kind: "bold",
458
+ content: normalizeContent(content)
459
+ };
460
+ }
461
+ function italic(content) {
462
+ return {
463
+ kind: "italic",
464
+ content: normalizeContent(content)
465
+ };
466
+ }
467
+ function link(content, url) {
468
+ validateSafeUrl(url);
469
+ return {
470
+ kind: "link",
471
+ content: normalizeContent(content),
472
+ url
473
+ };
474
+ }
475
+ function code(value) {
476
+ return {
477
+ kind: "code",
478
+ value
479
+ };
480
+ }
481
+ function heading(level, content) {
482
+ return {
483
+ kind: "heading",
484
+ level: clampHeadingLevel(level),
485
+ content: normalizeContent(content)
486
+ };
487
+ }
488
+ function paragraph(content) {
489
+ return {
490
+ kind: "paragraph",
491
+ content: normalizeContent(content)
492
+ };
493
+ }
494
+ function quote(content) {
495
+ return {
496
+ kind: "quote",
497
+ content: normalizeContent(content)
498
+ };
499
+ }
500
+ function codeBlock(value, language = "") {
501
+ return {
502
+ kind: "codeBlock",
503
+ language: sanitizeLanguage(language),
504
+ value
505
+ };
506
+ }
507
+ function listItem(content) {
508
+ return {
509
+ kind: "listItem",
510
+ content: normalizeContent(content)
511
+ };
512
+ }
513
+ function unorderedList(items) {
514
+ return {
515
+ kind: "list",
516
+ ordered: false,
517
+ items: normalizeItems(items)
518
+ };
519
+ }
520
+ function orderedList(items) {
521
+ return {
522
+ kind: "list",
523
+ ordered: true,
524
+ items: normalizeItems(items)
525
+ };
526
+ }
527
+ function concat(left, right) {
528
+ const children = [...flattenSequence(left), ...flattenSequence(right)].filter((child) => child.kind !== "empty");
529
+ if (children.length === 0) return empty;
530
+ if (children.length === 1) return children[0] ?? empty;
531
+ return {
532
+ kind: "sequence",
533
+ children
534
+ };
535
+ }
536
+ function render(fragment) {
537
+ return renderDocument(fragment);
538
+ }
539
+ function renderWithValidation(fragment) {
540
+ lastRenderValidationResult = validate(fragment);
541
+ return renderDocument(fragment);
542
+ }
543
+ function validate(fragment) {
544
+ const issues = [];
545
+ validateFragment(fragment, "$", [], issues);
546
+ if (fragment.kind === "empty") issues.push({
547
+ severity: "warning",
548
+ path: "$",
549
+ message: "Markdown fragment is empty."
550
+ });
551
+ return {
552
+ valid: issues.every((issue) => issue.severity !== "error"),
553
+ issues
554
+ };
555
+ }
556
+ function isValid(fragment) {
557
+ return validate(fragment).valid;
558
+ }
559
+ function getLastRenderValidationErrors() {
560
+ return lastRenderValidationResult.issues.filter((issue) => issue.severity === "error");
561
+ }
562
+ function formatValidationResult(result) {
563
+ if (result.issues.length === 0) return "valid";
564
+ return result.issues.map((issue) => `${issue.severity}: ${issue.path}: ${issue.message}`).join("\n");
565
+ }
566
+ function formatValidationErrors(issues) {
567
+ if (issues.length === 0) return "";
568
+ return issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
569
+ }
570
+ function getLastRenderValidationErrorText() {
571
+ return formatValidationErrors(getLastRenderValidationErrors());
572
+ }
573
+ function normalizeContent(content) {
574
+ return typeof content === "string" ? text(content) : content;
575
+ }
576
+ function validateFragment(fragment, path, ancestors, issues) {
577
+ const parent = ancestors[ancestors.length - 1];
578
+ const inlineAncestor = ancestors.find((ancestor) => [
579
+ "bold",
580
+ "italic",
581
+ "link"
582
+ ].includes(ancestor.kind));
583
+ if (!isInline(fragment) && inlineAncestor !== void 0) issues.push({
584
+ severity: "error",
585
+ path,
586
+ message: `${fragment.kind} cannot be nested inside ${inlineAncestor.kind}.`
587
+ });
588
+ if (fragment.kind === "listItem" && parent?.kind !== "list") issues.push({
589
+ severity: "error",
590
+ path,
591
+ message: "listItem must be inside a list."
592
+ });
593
+ validateWarnings(fragment, path, issues);
594
+ for (const [index, child] of childFragments(fragment).entries()) validateFragment(child, `${path}.children[${index}]`, [...ancestors, fragment], issues);
595
+ }
596
+ function validateWarnings(fragment, path, issues) {
597
+ if (fragment.kind === "heading" && isEmptyish(fragment.content)) issues.push({
598
+ severity: "warning",
599
+ path,
600
+ message: "heading should have content."
601
+ });
602
+ if (fragment.kind === "paragraph" && isEmptyish(fragment.content)) issues.push({
603
+ severity: "warning",
604
+ path,
605
+ message: "paragraph is empty."
606
+ });
607
+ if (fragment.kind === "link" && isEmptyish(fragment.content)) issues.push({
608
+ severity: "warning",
609
+ path,
610
+ message: "link should have visible content."
611
+ });
612
+ if (fragment.kind === "link" && fragment.url.trim().length === 0) issues.push({
613
+ severity: "warning",
614
+ path,
615
+ message: "link should have a destination URL."
616
+ });
617
+ if (fragment.kind === "list" && fragment.items.length === 0) issues.push({
618
+ severity: "warning",
619
+ path,
620
+ message: "list should contain at least one item."
621
+ });
622
+ }
623
+ function childFragments(fragment) {
624
+ switch (fragment.kind) {
625
+ case "bold":
626
+ case "italic":
627
+ case "link":
628
+ case "heading":
629
+ case "paragraph":
630
+ case "quote":
631
+ case "listItem": return [fragment.content];
632
+ case "list": return fragment.items;
633
+ case "sequence": return fragment.children;
634
+ default: return [];
635
+ }
636
+ }
637
+ function isEmptyish(fragment) {
638
+ if (fragment.kind === "empty") return true;
639
+ if (fragment.kind === "text" || fragment.kind === "code") return fragment.value.length === 0;
640
+ if (fragment.kind === "sequence") return fragment.children.every(isEmptyish);
641
+ return false;
642
+ }
643
+ function renderDocument(fragment) {
644
+ if (fragment.kind === "empty") return "";
645
+ if (fragment.kind === "sequence") {
646
+ if (fragment.children.every((child) => isInline(child) || child.kind === "sequence")) return renderInline(fragment);
647
+ return fragment.children.map(renderDocument).filter(Boolean).join("\n\n");
648
+ }
649
+ if (isInline(fragment)) return renderInline(fragment);
650
+ return renderBlock(fragment);
651
+ }
652
+ function renderBlock(fragment) {
653
+ switch (fragment.kind) {
654
+ case "heading": return `${"#".repeat(fragment.level)} ${renderInlineish(fragment.content)}`;
655
+ case "paragraph": return renderInlineish(fragment.content);
656
+ case "quote": return renderDocument(fragment.content).split("\n").map((line) => line.length === 0 ? ">" : `> ${line}`).join("\n");
657
+ case "codeBlock": return renderCodeBlock(fragment);
658
+ case "list": return fragment.items.map((item, index) => renderListItem(item, fragment.ordered ? `${index + 1}.` : "-")).join("\n");
659
+ case "listItem": return renderInlineish(fragment.content);
660
+ default: return renderDocument(fragment);
661
+ }
662
+ }
663
+ function renderInline(fragment) {
664
+ switch (fragment.kind) {
665
+ case "text": return escapeMarkdownText(fragment.value);
666
+ case "bold": return `**${renderInlineish(fragment.content)}**`;
667
+ case "italic": return `*${renderInlineish(fragment.content)}*`;
668
+ case "link": return `[${renderInlineish(fragment.content)}](${escapeUrl(fragment.url)})`;
669
+ case "code": return renderInlineCode(fragment.value);
670
+ case "sequence": return fragment.children.map(renderInlineish).join("");
671
+ case "empty": return "";
672
+ default: return renderBlock(fragment);
673
+ }
674
+ }
675
+ function renderInlineish(fragment) {
676
+ return isInline(fragment) || fragment.kind === "sequence" ? renderInline(fragment) : renderBlock(fragment);
677
+ }
678
+ function renderCodeBlock(fragment) {
679
+ const fence = longestBacktickRun(fragment.value) >= 3 ? "````" : "```";
680
+ return `${fence}${fragment.language.length > 0 ? fragment.language : ""}\n${fragment.value}\n${fence}`;
681
+ }
682
+ function renderInlineCode(value) {
683
+ const fence = "`".repeat(Math.max(1, longestBacktickRun(value) + 1));
684
+ return `${fence}${value.startsWith("`") || value.endsWith("`") || value.includes("\n") ? ` ${value} ` : value}${fence}`;
685
+ }
686
+ function renderListItem(fragment, marker) {
687
+ const [first = "", ...rest] = renderDocument(fragment.kind === "listItem" ? fragment.content : fragment).split("\n");
688
+ const padding = " ".repeat(marker.length + 1);
689
+ return [`${marker} ${first}`, ...rest.map((line) => `${padding}${line}`)].join("\n");
690
+ }
691
+ function normalizeItems(items) {
692
+ const fragment = normalizeContent(items);
693
+ if (fragment.kind === "sequence") return fragment.children;
694
+ if (fragment.kind === "empty") return [];
695
+ return [fragment];
696
+ }
697
+ function flattenSequence(fragment) {
698
+ if (fragment.kind === "sequence") return fragment.children.flatMap(flattenSequence);
699
+ return [fragment];
700
+ }
701
+ function isInline(fragment) {
702
+ return [
703
+ "text",
704
+ "bold",
705
+ "italic",
706
+ "link",
707
+ "code",
708
+ "empty"
709
+ ].includes(fragment.kind);
710
+ }
711
+ function clampHeadingLevel(level) {
712
+ if (!Number.isFinite(level)) return 1;
713
+ return Math.min(6, Math.max(1, Math.trunc(level)));
714
+ }
715
+ function sanitizeLanguage(language) {
716
+ return language.trim().replace(/[^a-zA-Z0-9_+.-]/gu, "");
717
+ }
718
+ function validateSafeUrl(value) {
719
+ const trimmed = value.trim();
720
+ if (!SAFE_URL_PATTERN.test(trimmed)) throw new TypeError(`Unsafe URL value: ${value}`);
721
+ }
722
+ function escapeMarkdownText(value) {
723
+ return value.replace(/([\\`*_{}[\]()#+\-.!<>|])/gu, "\\$1");
724
+ }
725
+ function escapeUrl(value) {
726
+ return value.trim().replace(/\)/gu, "%29").replace(/\s/gu, "%20");
727
+ }
728
+ function longestBacktickRun(value) {
729
+ return Math.max(0, ...Array.from(value.matchAll(/`+/gu), (match) => match[0]?.length ?? 0));
730
+ }
731
+ //#endregion
732
+ //#region src/extension.ts
733
+ var SERIALIZED_PREFIX = "turbowarp-markdown:v1:";
734
+ var blockDefinitions = block_definitions_default.blocks;
735
+ var MarkdownExtension = class {
736
+ constructor() {
737
+ this.fixedInputs = fixedInputRegistration(typeof Scratch === "undefined" ? void 0 : Scratch);
738
+ }
739
+ dispose() {
740
+ this.fixedInputs.dispose();
741
+ }
742
+ getInfo() {
743
+ this.fixedInputs.ensure(blockDefinitions.map((block) => `${extensionConfig.id}_${block.opcode}`));
744
+ return {
745
+ id: extensionConfig.id,
746
+ name: Scratch.translate(block_definitions_default.extensionName),
747
+ docsURI: extensionConfig.docsURI,
748
+ blockIconURI: extensionConfig.blockIconURI,
749
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
750
+ };
751
+ }
752
+ text(args) {
753
+ return encode(text(Scratch.Cast.toString(args.TEXT)));
754
+ }
755
+ bold(args) {
756
+ return encode(bold(decodeOrText(args.CONTENT)));
757
+ }
758
+ italic(args) {
759
+ return encode(italic(decodeOrText(args.CONTENT)));
760
+ }
761
+ link(args) {
762
+ return encode(link(decodeOrText(args.CONTENT), Scratch.Cast.toString(args.URL)));
763
+ }
764
+ code(args) {
765
+ return encode(code(Scratch.Cast.toString(args.TEXT)));
766
+ }
767
+ heading(args) {
768
+ return encode(heading(Scratch.Cast.toNumber(args.LEVEL), decodeOrText(args.CONTENT)));
769
+ }
770
+ paragraph(args) {
771
+ return encode(paragraph(decodeOrText(args.CONTENT)));
772
+ }
773
+ quote(args) {
774
+ return encode(quote(decodeOrText(args.CONTENT)));
775
+ }
776
+ codeBlock(args) {
777
+ return encode(codeBlock(Scratch.Cast.toString(args.TEXT), Scratch.Cast.toString(args.LANGUAGE)));
778
+ }
779
+ listItem(args) {
780
+ return encode(listItem(decodeOrText(args.CONTENT)));
781
+ }
782
+ unorderedList(args) {
783
+ return encode(unorderedList(decodeOrText(args.ITEMS)));
784
+ }
785
+ orderedList(args) {
786
+ return encode(orderedList(decodeOrText(args.ITEMS)));
787
+ }
788
+ concat(args) {
789
+ return encode(concat(decodeOrText(args.LEFT), decodeOrText(args.RIGHT)));
790
+ }
791
+ render(args) {
792
+ return render(decodeOrText(args.FRAGMENT));
793
+ }
794
+ renderWithValidation(args) {
795
+ return renderWithValidation(decodeOrText(args.FRAGMENT));
796
+ }
797
+ lastValidationErrors() {
798
+ return getLastRenderValidationErrorText();
799
+ }
800
+ lastRenderHasValidationErrors() {
801
+ return getLastRenderValidationErrors().length > 0;
802
+ }
803
+ validateMarkdown(args) {
804
+ return formatValidationResult(validate(decodeOrText(args.FRAGMENT)));
805
+ }
806
+ isValidMarkdown(args) {
807
+ return isValid(decodeOrText(args.FRAGMENT));
808
+ }
809
+ toScratchBlock(block) {
810
+ return {
811
+ opcode: block.opcode,
812
+ blockType: Scratch.BlockType[block.blockType],
813
+ text: Scratch.translate(block.text),
814
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
815
+ type: Scratch.ArgumentType[argument.type],
816
+ defaultValue: argument.defaultValue
817
+ }]))
818
+ };
819
+ }
820
+ };
821
+ function encode(fragment) {
822
+ return `${SERIALIZED_PREFIX}${JSON.stringify(fragment)}`;
823
+ }
824
+ function decodeOrText(value) {
825
+ const raw = Scratch.Cast.toString(value);
826
+ if (!raw.startsWith(SERIALIZED_PREFIX)) return text(raw);
827
+ return parseFragment(raw.slice(22));
828
+ }
829
+ function parseFragment(json) {
830
+ const parsed = JSON.parse(json);
831
+ if (!isFragment(parsed)) throw new TypeError("Invalid serialized Markdown fragment.");
832
+ return parsed;
833
+ }
834
+ function isFragment(value) {
835
+ if (typeof value !== "object" || value === null) return false;
836
+ const record = value;
837
+ if (record.kind === "empty") return true;
838
+ if (record.kind === "text" || record.kind === "code") return typeof record.value === "string";
839
+ if (record.kind === "bold" || record.kind === "italic" || record.kind === "paragraph") return isFragment(record.content);
840
+ if (record.kind === "link") return typeof record.url === "string" && isFragment(record.content);
841
+ if (record.kind === "heading") return typeof record.level === "number" && isFragment(record.content);
842
+ if (record.kind === "quote" || record.kind === "listItem") return isFragment(record.content);
843
+ if (record.kind === "codeBlock") return typeof record.language === "string" && typeof record.value === "string";
844
+ if (record.kind === "list") return typeof record.ordered === "boolean" && Array.isArray(record.items) && record.items.every(isFragment);
845
+ if (record.kind === "sequence") return Array.isArray(record.children) && record.children.every(isFragment);
846
+ return false;
847
+ }
848
+ //#endregion
849
+ //#region src/index.ts
850
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
851
+ Scratch.extensions.register(new MarkdownExtension());
852
+ //#endregion
853
853
 
854
854
  })(Scratch);