@kubohiroya/turbowarp-http-server 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,1619 +7,1619 @@
7
7
  (function (Scratch) {
8
8
  'use strict';
9
9
 
10
- //#region src/config.ts
11
- var extensionConfig = {
12
- id: "kubohiroyaturbowarphttpserver",
13
- slug: "turbowarp-http-server",
14
- name: "TurboWarp-HTTP-Server",
15
- description: "Connect TurboWarp blocks to an HTTP bridge server over WebSocket.",
16
- author: "Hiroya Kubo",
17
- license: "MPL-2.0",
18
- unsandboxed: true,
19
- docsURI: "https://kubohiroya.github.io/turbowarp-http-server/",
20
- blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMDAvc3ZnIiB2aWV3Qm94PSIwIDAgNDggNDgiPjxyZWN0IHg9IjYiIHk9IjEwIiB3aWR0aD0iMzYiIGhlaWdodD0iMjgiIHJ4PSI0IiBmaWxsPSIjMjU2M0VCIi8+PHBhdGggZD0iTTEyIDE4aDI0TTExIDI0aDE0TTExIDMwaDIwIiBzdHJva2U9IiNGRkYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIzMCIgcj0iMyIgZmlsbD0iIzIyQzU1RSIvPjwvc3ZnPg=="
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-http-server/schemas/block-editor-fixed-inputs.schema.json",
56
- $defs: {
57
- "changeHandlerVariable": {
58
- "type": "object",
59
- "properties": { "AMOUNT": { "type": "number" } },
60
- "required": ["AMOUNT"],
61
- "additionalProperties": true
62
- },
63
- "setHttpStatus": {
64
- "type": "object",
65
- "properties": { "STATUS": { "type": "number" } },
66
- "required": ["STATUS"],
67
- "additionalProperties": true
68
- },
69
- "respondWithNamedBody": {
70
- "type": "object",
71
- "properties": {
72
- "KIND": {
73
- "type": "string",
74
- "enum": [
75
- "structured",
76
- "document",
77
- "binary",
78
- "asset"
79
- ]
80
- },
81
- "SCOPE": {
82
- "type": "string",
83
- "enum": ["target", "project"]
84
- },
85
- "REPRESENTATION": {
86
- "type": "string",
87
- "enum": [
88
- "json",
89
- "yaml",
90
- "html",
91
- "markdown",
92
- "raw"
93
- ]
94
- },
95
- "MAX_BYTES": {
96
- "type": "number",
97
- "minimum": 1,
98
- "exclusiveMaximum": 9007199254740992
99
- }
100
- },
101
- "required": [
102
- "KIND",
103
- "SCOPE",
104
- "REPRESENTATION",
105
- "MAX_BYTES"
106
- ],
107
- "additionalProperties": true
108
- },
109
- "markdownHeading": {
110
- "type": "object",
111
- "properties": { "LEVEL": { "type": "number" } },
112
- "required": ["LEVEL"],
113
- "additionalProperties": true
114
- }
115
- }
116
- };
117
- //#endregion
118
- //#region src/fixed-input-schema.ts
119
- var repository$1 = "turbowarp-http-server";
120
- /** The owner JSON document is canonical; this selects a primitive field fragment. */
121
- function fixedInputBundle(opcode, argument) {
122
- const source = {
123
- repository: repository$1,
124
- path: "schemas/block-editor-fixed-inputs.schema.json",
125
- symbol: `#/$defs/${opcode}/properties/${argument}`
126
- };
127
- const blocks = block_editor_fixed_inputs_schema_default.$defs;
128
- return {
129
- identity: {
130
- ownerId: repository$1,
131
- contractId: opcode,
132
- revision: "fixed-inputs-v1",
133
- variantId: argument
134
- },
135
- dialect: "2020-12",
136
- root: {
137
- retrievalUri: block_editor_fixed_inputs_schema_default.$id,
138
- document: blocks[opcode].properties[argument],
139
- artifact: {
140
- role: "canonical-schema",
141
- source
142
- }
143
- },
144
- resources: [],
145
- provenance: {
146
- canonicalSources: [source, {
147
- repository: repository$1,
148
- path: "src/extension.ts",
149
- symbol: opcode
150
- }],
151
- generatedFiles: [],
152
- referenceSchemas: [],
153
- generationSources: []
154
- }
155
- };
156
- }
157
- //#endregion
158
- //#region src/fixed-input-editors.ts
159
- var extensionId = "kubohiroyaturbowarphttpserver";
160
- var repository = "turbowarp-http-server";
161
- var fields = [
162
- {
163
- "opcode": "changeHandlerVariable",
164
- "argument": "AMOUNT",
165
- "control": "number",
166
- "choices": [],
167
- "normalization": "identity",
168
- "shape": "math_number.NUM",
169
- "maxBytes": false
170
- },
171
- {
172
- "opcode": "setHttpStatus",
173
- "argument": "STATUS",
174
- "control": "number",
175
- "choices": [],
176
- "normalization": "identity",
177
- "shape": "math_number.NUM",
178
- "maxBytes": false
179
- },
180
- {
181
- "opcode": "respondWithNamedBody",
182
- "argument": "KIND",
183
- "control": "enum",
184
- "choices": [
185
- "structured",
186
- "document",
187
- "binary",
188
- "asset"
189
- ],
190
- "normalization": "lowercase",
191
- "shape": "text.TEXT",
192
- "maxBytes": false
193
- },
194
- {
195
- "opcode": "respondWithNamedBody",
196
- "argument": "SCOPE",
197
- "control": "enum",
198
- "choices": ["target", "project"],
199
- "normalization": "lowercase",
200
- "shape": "text.TEXT",
201
- "maxBytes": false
202
- },
203
- {
204
- "opcode": "respondWithNamedBody",
205
- "argument": "REPRESENTATION",
206
- "control": "enum",
207
- "choices": [
208
- "json",
209
- "yaml",
210
- "html",
211
- "markdown",
212
- "raw"
213
- ],
214
- "normalization": "lowercase",
215
- "shape": "text.TEXT",
216
- "maxBytes": false
217
- },
218
- {
219
- "opcode": "respondWithNamedBody",
220
- "argument": "MAX_BYTES",
221
- "control": "number",
222
- "choices": [],
223
- "normalization": "identity",
224
- "shape": "math_number.NUM",
225
- "maxBytes": true
226
- },
227
- {
228
- "opcode": "markdownHeading",
229
- "argument": "LEVEL",
230
- "control": "number",
231
- "choices": [],
232
- "normalization": "identity",
233
- "shape": "math_number.NUM",
234
- "maxBytes": false
235
- }
236
- ];
237
- function literalString(value) {
238
- if (typeof value !== "string") throw new TypeError("Expected a string literal.");
239
- return value;
240
- }
241
- /** Legacy nonempty finite aliases are projections; opening never creates a write. */
242
- function existingFixedNumber(value) {
243
- if (typeof value !== "string" && typeof value !== "number" || typeof value === "string" && value.trim() === "") throw new TypeError("Unavailable numeric projection.");
244
- const number = Number(value);
245
- if (!Number.isFinite(number)) throw new TypeError("Unavailable numeric projection.");
246
- return number;
247
- }
248
- function normalizeChoice(field, raw) {
249
- if (field.normalization === "lowercase") return raw.toLowerCase();
250
- if (field.normalization === "method") return raw.trim().toUpperCase();
251
- if (field.normalization === "trim") return raw.trim();
252
- if (field.normalization === "parse-format") {
253
- const lower = raw.trim().toLowerCase();
254
- return lower === "json" ? "JSON" : lower === "yaml" ? "YAML" : lower === "auto" ? "auto" : raw;
255
- }
256
- return raw;
257
- }
258
- function binding(field) {
259
- return {
260
- argument: field.argument,
261
- schemaBundle: fixedInputBundle(field.opcode, field.argument),
262
- control: {
263
- kind: field.control,
264
- ...field.control === "enum" ? { choices: field.choices.map((value) => ({ value })) } : {}
265
- },
266
- read(value) {
267
- return field.control === "number" ? existingFixedNumber(value) : normalizeChoice(field, literalString(value));
268
- },
269
- encode(value) {
270
- if (field.control === "number") {
271
- const parsed = parseFixedNumberInput(value);
272
- if (parsed.kind !== "valid") throw new TypeError("Invalid new numeric input.");
273
- return parsed.token;
274
- }
275
- const raw = literalString(value), normalized = normalizeChoice(field, raw);
276
- if (!field.choices.includes(normalized)) throw new TypeError("Unsupported fixed choice.");
277
- return field.shape === "menu-shadow" || field.shape === "direct-field-dropdown" ? normalized : raw;
278
- },
279
- validateCandidate(value) {
280
- try {
281
- if (field.control === "number") {
282
- const number = existingFixedNumber(value);
283
- if (field.maxBytes && (!Number.isSafeInteger(Math.trunc(number)) || Math.trunc(number) < 1)) return [{ message: "Invalid named body size." }];
284
- return [];
285
- }
286
- return field.choices.includes(normalizeChoice(field, literalString(value))) ? [] : [{ message: "Unsupported fixed choice." }];
287
- } catch {
288
- return [{ message: "Invalid fixed input." }];
289
- }
290
- }
291
- };
292
- }
293
- var fixedInputEditors = [...new Set(fields.map((f) => f.opcode))].map((opcode) => ({
294
- apiVersion: 1,
295
- extensionId,
296
- editorId: `${opcode}-fixed-inputs`,
297
- opcodes: [`${extensionId}_${opcode}`],
298
- contractId: `${repository}/${opcode}`,
299
- contractRevision: "fixed-inputs-v1",
300
- bindings: fields.filter((field) => field.opcode === opcode).map(binding),
301
- validationContext: () => ({
302
- consumerId: repository,
303
- nowMs: 0,
304
- settings: null
305
- })
306
- }));
307
- /** Registration follows the advertised opcode membership and the optional host capability. */
308
- function fixedInputRegistration(scratch) {
309
- const host = scratch ?? {};
310
- let active;
311
- let membership = "";
312
- const removers = [];
313
- let stopped = false;
314
- const clear = () => {
315
- host.vm?.runtime?.off?.("RUNTIME_DISPOSED", shutdown);
316
- for (const remove of removers.splice(0).reverse()) remove();
317
- active = void 0;
318
- membership = "";
319
- };
320
- const shutdown = () => {
321
- stopped = true;
322
- clear();
323
- };
324
- return {
325
- ensure(visibleOpcodes) {
326
- const api = host.gui?.blockEditors;
327
- const definitions = fixedInputEditors.filter((definition) => definition.opcodes.every((opcode) => visibleOpcodes.includes(opcode)));
328
- const key = definitions.map((definition) => definition.editorId).join(",");
329
- if (stopped || api === active && membership === key) return;
330
- clear();
331
- if (api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function" || !definitions.length) return;
332
- try {
333
- for (const definition of definitions) {
334
- const remove = api.registerFixedInputEditor.call(api, definition);
335
- if (typeof remove !== "function") throw new TypeError("Invalid fixed input cleanup.");
336
- removers.push(remove);
337
- }
338
- active = api;
339
- membership = key;
340
- host.vm?.runtime?.on?.("RUNTIME_DISPOSED", shutdown);
341
- } catch (error) {
342
- clear();
343
- throw error;
344
- }
345
- },
346
- dispose: shutdown
347
- };
348
- }
349
- var block_definitions_default = {
350
- extensionName: "TurboWarp-HTTP-Server",
351
- blocks: [
352
- {
353
- "opcode": "setServerUrl",
354
- "blockType": "COMMAND",
355
- "text": "set HTTP bridge URL to [URL]",
356
- "description": "Sets the WebSocket URL used to reach the HTTP bridge server.",
357
- "arguments": { "URL": {
358
- "type": "STRING",
359
- "defaultValue": "ws://127.0.0.1:8787/ws"
360
- } }
361
- },
362
- {
363
- "opcode": "connect",
364
- "blockType": "COMMAND",
365
- "text": "connect to HTTP bridge",
366
- "description": "Opens a WebSocket connection to the configured HTTP bridge server.",
367
- "arguments": {}
368
- },
369
- {
370
- "opcode": "disconnect",
371
- "blockType": "COMMAND",
372
- "text": "disconnect from HTTP bridge",
373
- "description": "Closes the current bridge connection.",
374
- "arguments": {}
375
- },
376
- {
377
- "opcode": "isConnected",
378
- "blockType": "BOOLEAN",
379
- "text": "HTTP bridge connected?",
380
- "description": "Reports whether the bridge WebSocket is currently open.",
381
- "arguments": {}
382
- },
383
- {
384
- "opcode": "sendText",
385
- "blockType": "COMMAND",
386
- "text": "send [MESSAGE] to HTTP bridge",
387
- "description": "Sends a text message to the connected HTTP bridge server.",
388
- "arguments": { "MESSAGE": {
389
- "type": "STRING",
390
- "defaultValue": "{\"type\":\"ping\"}"
391
- } }
392
- },
393
- {
394
- "opcode": "lastMessage",
395
- "blockType": "REPORTER",
396
- "text": "last HTTP bridge message",
397
- "description": "Returns the most recent text message received from the bridge.",
398
- "arguments": {}
399
- },
400
- {
401
- "opcode": "whenHttpRequestReceived",
402
- "blockType": "HAT",
403
- "text": "when HTTP request received",
404
- "description": "Starts a TurboWarp handler thread when the bridge receives an HTTP request.",
405
- "arguments": {}
406
- },
407
- {
408
- "opcode": "useHttpRequest",
409
- "blockType": "COMMAND",
410
- "text": "use HTTP request [ID]",
411
- "description": "Selects a pending request context by request ID.",
412
- "arguments": { "ID": {
413
- "type": "STRING",
414
- "defaultValue": "req-1"
415
- } }
416
- },
417
- {
418
- "opcode": "currentRequestId",
419
- "blockType": "REPORTER",
420
- "text": "current request ID",
421
- "description": "Returns the current HTTP request ID.",
422
- "arguments": {}
423
- },
424
- {
425
- "opcode": "currentHttpMethod",
426
- "blockType": "REPORTER",
427
- "text": "current HTTP method",
428
- "description": "Returns the current HTTP request method.",
429
- "arguments": {}
430
- },
431
- {
432
- "opcode": "currentRequestPath",
433
- "blockType": "REPORTER",
434
- "text": "current request path",
435
- "description": "Returns the current HTTP request path.",
436
- "arguments": {}
437
- },
438
- {
439
- "opcode": "currentRequestUrl",
440
- "blockType": "REPORTER",
441
- "text": "current request URL",
442
- "description": "Returns the current HTTP request URL.",
443
- "arguments": {}
444
- },
445
- {
446
- "opcode": "requestHeader",
447
- "blockType": "REPORTER",
448
- "text": "request header [NAME]",
449
- "description": "Returns the first value of a request header using case-insensitive lookup.",
450
- "arguments": { "NAME": {
451
- "type": "STRING",
452
- "defaultValue": "accept"
453
- } }
454
- },
455
- {
456
- "opcode": "queryParameter",
457
- "blockType": "REPORTER",
458
- "text": "query parameter [NAME]",
459
- "description": "Returns the first query parameter value.",
460
- "arguments": { "NAME": {
461
- "type": "STRING",
462
- "defaultValue": "q"
463
- } }
464
- },
465
- {
466
- "opcode": "pathParameter",
467
- "blockType": "REPORTER",
468
- "text": "path parameter [NAME]",
469
- "description": "Returns a route path parameter value.",
470
- "arguments": { "NAME": {
471
- "type": "STRING",
472
- "defaultValue": "id"
473
- } }
474
- },
475
- {
476
- "opcode": "currentRequestBody",
477
- "blockType": "REPORTER",
478
- "text": "current request body",
479
- "description": "Returns the current textual request body, or an empty string for non-text bodies.",
480
- "arguments": {}
481
- },
482
- {
483
- "opcode": "currentRequestContentType",
484
- "blockType": "REPORTER",
485
- "text": "current request content type",
486
- "description": "Returns the current request Content-Type header.",
487
- "arguments": {}
488
- },
489
- {
490
- "opcode": "currentRequestClientAddress",
491
- "blockType": "REPORTER",
492
- "text": "current request client address",
493
- "description": "Returns the current request client address when available.",
494
- "arguments": {}
495
- },
496
- {
497
- "opcode": "setHandlerVariable",
498
- "blockType": "COMMAND",
499
- "text": "set handler variable [NAME] to [VALUE]",
500
- "description": "Sets a request-local variable that is discarded when the current HTTP response completes.",
501
- "arguments": {
502
- "NAME": {
503
- "type": "STRING",
504
- "defaultValue": "value"
505
- },
506
- "VALUE": {
507
- "type": "STRING",
508
- "defaultValue": "0"
509
- }
510
- }
511
- },
512
- {
513
- "opcode": "changeHandlerVariable",
514
- "blockType": "COMMAND",
515
- "text": "change handler variable [NAME] by [AMOUNT]",
516
- "description": "Changes a request-local numeric variable using Scratch number conversion rules.",
517
- "arguments": {
518
- "NAME": {
519
- "type": "STRING",
520
- "defaultValue": "value"
521
- },
522
- "AMOUNT": {
523
- "type": "NUMBER",
524
- "defaultValue": 1
525
- }
526
- }
527
- },
528
- {
529
- "opcode": "handlerVariable",
530
- "blockType": "REPORTER",
531
- "text": "handler variable [NAME]",
532
- "description": "Returns a request-local handler variable, or an empty string when it does not exist.",
533
- "arguments": { "NAME": {
534
- "type": "STRING",
535
- "defaultValue": "value"
536
- } }
537
- },
538
- {
539
- "opcode": "handlerVariableExists",
540
- "blockType": "BOOLEAN",
541
- "text": "handler variable [NAME] exists?",
542
- "description": "Reports whether a request-local handler variable exists.",
543
- "arguments": { "NAME": {
544
- "type": "STRING",
545
- "defaultValue": "value"
546
- } }
547
- },
548
- {
549
- "opcode": "deleteHandlerVariable",
550
- "blockType": "COMMAND",
551
- "text": "delete handler variable [NAME]",
552
- "description": "Deletes a request-local handler variable.",
553
- "arguments": { "NAME": {
554
- "type": "STRING",
555
- "defaultValue": "value"
556
- } }
557
- },
558
- {
559
- "opcode": "clearHandlerVariables",
560
- "blockType": "COMMAND",
561
- "text": "delete all handler variables",
562
- "description": "Deletes all request-local handler variables for the current HTTP handler.",
563
- "arguments": {}
564
- },
565
- {
566
- "opcode": "listHandlerVariables",
567
- "blockType": "REPORTER",
568
- "text": "active handler variables",
569
- "description": "Returns comma-separated names of request-local handler variables.",
570
- "arguments": {}
571
- },
572
- {
573
- "opcode": "currentAuthType",
574
- "blockType": "REPORTER",
575
- "text": "current auth type",
576
- "description": "Returns the current authentication type, such as digest or oauth.",
577
- "arguments": {}
578
- },
579
- {
580
- "opcode": "currentAuthenticatedUser",
581
- "blockType": "REPORTER",
582
- "text": "current authenticated user",
583
- "description": "Returns the authenticated username or a stable user-like profile field when available.",
584
- "arguments": {}
585
- },
586
- {
587
- "opcode": "currentAuthProvider",
588
- "blockType": "REPORTER",
589
- "text": "current auth provider",
590
- "description": "Returns the authentication provider name when available.",
591
- "arguments": {}
592
- },
593
- {
594
- "opcode": "currentAuthProfileJson",
595
- "blockType": "REPORTER",
596
- "text": "current auth profile JSON",
597
- "description": "Returns the provider profile object as JSON when available.",
598
- "arguments": {}
599
- },
600
- {
601
- "opcode": "authProfileField",
602
- "blockType": "REPORTER",
603
- "text": "auth profile field [NAME]",
604
- "description": "Returns a top-level or dotted field from the provider profile object.",
605
- "arguments": { "NAME": {
606
- "type": "STRING",
607
- "defaultValue": "email"
608
- } }
609
- },
610
- {
611
- "opcode": "currentResponseStatus",
612
- "blockType": "REPORTER",
613
- "text": "current response status",
614
- "description": "Returns the response status currently being built.",
615
- "arguments": {}
616
- },
617
- {
618
- "opcode": "setHttpStatus",
619
- "blockType": "COMMAND",
620
- "text": "set HTTP status [STATUS]",
621
- "description": "Sets the current response status.",
622
- "arguments": { "STATUS": {
623
- "type": "NUMBER",
624
- "defaultValue": 200
625
- } }
626
- },
627
- {
628
- "opcode": "setResponseHeader",
629
- "blockType": "COMMAND",
630
- "text": "set response header [NAME] to [VALUE]",
631
- "description": "Sets a response header for the current request.",
632
- "arguments": {
633
- "NAME": {
634
- "type": "STRING",
635
- "defaultValue": "content-type"
636
- },
637
- "VALUE": {
638
- "type": "STRING",
639
- "defaultValue": "text/plain; charset=utf-8"
640
- }
641
- }
642
- },
643
- {
644
- "opcode": "removeResponseHeader",
645
- "blockType": "COMMAND",
646
- "text": "remove response header [NAME]",
647
- "description": "Removes a response header for the current request.",
648
- "arguments": { "NAME": {
649
- "type": "STRING",
650
- "defaultValue": "content-type"
651
- } }
652
- },
653
- {
654
- "opcode": "responseHeader",
655
- "blockType": "REPORTER",
656
- "text": "response header [NAME]",
657
- "description": "Returns the first configured response header value.",
658
- "arguments": { "NAME": {
659
- "type": "STRING",
660
- "defaultValue": "content-type"
661
- } }
662
- },
663
- {
664
- "opcode": "setResponseBody",
665
- "blockType": "COMMAND",
666
- "text": "set response body [BODY]",
667
- "description": "Sets the current response body without completing the response.",
668
- "arguments": { "BODY": {
669
- "type": "STRING",
670
- "defaultValue": "Hello"
671
- } }
672
- },
673
- {
674
- "opcode": "sendResponse",
675
- "blockType": "COMMAND",
676
- "text": "send response [BODY]",
677
- "description": "Sets the response body and completes the current request.",
678
- "arguments": { "BODY": {
679
- "type": "STRING",
680
- "defaultValue": "Hello"
681
- } }
682
- },
683
- {
684
- "opcode": "respondWithText",
685
- "blockType": "COMMAND",
686
- "text": "respond with text [BODY]",
687
- "description": "Responds with plain text.",
688
- "arguments": { "BODY": {
689
- "type": "STRING",
690
- "defaultValue": "Hello"
691
- } }
692
- },
693
- {
694
- "opcode": "respondWithHtml",
695
- "blockType": "COMMAND",
696
- "text": "respond with HTML [BODY]",
697
- "description": "Responds with HTML.",
698
- "arguments": { "BODY": {
699
- "type": "STRING",
700
- "defaultValue": "<p>Hello</p>"
701
- } }
702
- },
703
- {
704
- "opcode": "respondWithJson",
705
- "blockType": "COMMAND",
706
- "text": "respond with JSON [BODY]",
707
- "description": "Responds with JSON.",
708
- "arguments": { "BODY": {
709
- "type": "STRING",
710
- "defaultValue": "{\"ok\":true}"
711
- } }
712
- },
713
- {
714
- "opcode": "respondWithNamedBody",
715
- "blockType": "COMMAND",
716
- "text": "respond with named [NAMESPACE] [NAME] kind [KIND] scope [SCOPE] target [TARGET_ID] as [REPRESENTATION] max bytes [MAX_BYTES]",
717
- "description": "Completes the response with a named structured, document, binary, or asset snapshot resolved by the server.",
718
- "arguments": {
719
- "NAMESPACE": {
720
- "type": "STRING",
721
- "defaultValue": "asset"
722
- },
723
- "NAME": {
724
- "type": "STRING",
725
- "defaultValue": "avatar"
726
- },
727
- "KIND": {
728
- "type": "STRING",
729
- "defaultValue": "asset"
730
- },
731
- "SCOPE": {
732
- "type": "STRING",
733
- "defaultValue": "project"
734
- },
735
- "TARGET_ID": {
736
- "type": "STRING",
737
- "defaultValue": "Stage:1"
738
- },
739
- "REPRESENTATION": {
740
- "type": "STRING",
741
- "defaultValue": "raw"
742
- },
743
- "MAX_BYTES": {
744
- "type": "NUMBER",
745
- "defaultValue": 10485760
746
- }
747
- }
748
- },
749
- {
750
- "opcode": "recordHttpLog",
751
- "blockType": "COMMAND",
752
- "text": "record HTTP log [ENTRY]",
753
- "description": "Adds a structured HTTP log entry JSON string to the extension log buffer.",
754
- "arguments": { "ENTRY": {
755
- "type": "STRING",
756
- "defaultValue": "{\"method\":\"GET\",\"path\":\"/\",\"status\":200}"
757
- } }
758
- },
759
- {
760
- "opcode": "clearHttpLogs",
761
- "blockType": "COMMAND",
762
- "text": "clear HTTP logs",
763
- "description": "Clears the extension log buffer.",
764
- "arguments": {}
765
- },
766
- {
767
- "opcode": "httpLogViewerHtml",
768
- "blockType": "REPORTER",
769
- "text": "HTTP log viewer HTML",
770
- "description": "Returns a self-contained virtual-scroll HTML log viewer for buffered HTTP logs.",
771
- "arguments": {}
772
- },
773
- {
774
- "opcode": "httpLogViewerHtmlFromJson",
775
- "blockType": "REPORTER",
776
- "text": "HTTP log viewer HTML from [LOGS]",
777
- "description": "Returns a self-contained virtual-scroll HTML log viewer from a JSON array of log entries.",
778
- "arguments": { "LOGS": {
779
- "type": "STRING",
780
- "defaultValue": "[{\"method\":\"GET\",\"path\":\"/\",\"status\":200}]"
781
- } }
782
- },
783
- {
784
- "opcode": "newMarkdownDocument",
785
- "blockType": "REPORTER",
786
- "text": "new markdown document",
787
- "description": "Creates an empty Markdown builder handle.",
788
- "arguments": {}
789
- },
790
- {
791
- "opcode": "markdownHeading",
792
- "blockType": "REPORTER",
793
- "text": "markdown [DOC] with heading level [LEVEL] [TEXT]",
794
- "description": "Appends a Markdown heading and returns the same builder handle.",
795
- "arguments": {
796
- "DOC": {
797
- "type": "STRING",
798
- "defaultValue": "md:1"
799
- },
800
- "LEVEL": {
801
- "type": "NUMBER",
802
- "defaultValue": 1
803
- },
804
- "TEXT": {
805
- "type": "STRING",
806
- "defaultValue": "Title"
807
- }
808
- }
809
- },
810
- {
811
- "opcode": "markdownParagraph",
812
- "blockType": "REPORTER",
813
- "text": "markdown [DOC] with paragraph [TEXT]",
814
- "description": "Appends a Markdown paragraph and returns the same builder handle.",
815
- "arguments": {
816
- "DOC": {
817
- "type": "STRING",
818
- "defaultValue": "md:1"
819
- },
820
- "TEXT": {
821
- "type": "STRING",
822
- "defaultValue": "Hello"
823
- }
824
- }
825
- },
826
- {
827
- "opcode": "markdownBullet",
828
- "blockType": "REPORTER",
829
- "text": "markdown [DOC] with bullet [TEXT]",
830
- "description": "Appends a Markdown bullet and returns the same builder handle.",
831
- "arguments": {
832
- "DOC": {
833
- "type": "STRING",
834
- "defaultValue": "md:1"
835
- },
836
- "TEXT": {
837
- "type": "STRING",
838
- "defaultValue": "Item"
839
- }
840
- }
841
- },
842
- {
843
- "opcode": "markdownCodeBlock",
844
- "blockType": "REPORTER",
845
- "text": "markdown [DOC] with code [CODE] language [LANG]",
846
- "description": "Appends a fenced Markdown code block and returns the same builder handle.",
847
- "arguments": {
848
- "DOC": {
849
- "type": "STRING",
850
- "defaultValue": "md:1"
851
- },
852
- "CODE": {
853
- "type": "STRING",
854
- "defaultValue": "console.log('hello')"
855
- },
856
- "LANG": {
857
- "type": "STRING",
858
- "defaultValue": "js"
859
- }
860
- }
861
- },
862
- {
863
- "opcode": "renderMarkdown",
864
- "blockType": "REPORTER",
865
- "text": "render markdown [DOC]",
866
- "description": "Renders a Markdown builder handle to Markdown text.",
867
- "arguments": { "DOC": {
868
- "type": "STRING",
869
- "defaultValue": "md:1"
870
- } }
871
- },
872
- {
873
- "opcode": "newHtmlElement",
874
- "blockType": "REPORTER",
875
- "text": "new HTML element [TAG]",
876
- "description": "Creates an HTML element builder handle.",
877
- "arguments": { "TAG": {
878
- "type": "STRING",
879
- "defaultValue": "div"
880
- } }
881
- },
882
- {
883
- "opcode": "htmlText",
884
- "blockType": "REPORTER",
885
- "text": "HTML text [TEXT]",
886
- "description": "Creates an escaped HTML text node handle.",
887
- "arguments": { "TEXT": {
888
- "type": "STRING",
889
- "defaultValue": "Hello"
890
- } }
891
- },
892
- {
893
- "opcode": "htmlSetAttribute",
894
- "blockType": "REPORTER",
895
- "text": "HTML [NODE] with attribute [NAME] [VALUE]",
896
- "description": "Sets an escaped attribute on an HTML element and returns the same handle.",
897
- "arguments": {
898
- "NODE": {
899
- "type": "STRING",
900
- "defaultValue": "html:1"
901
- },
902
- "NAME": {
903
- "type": "STRING",
904
- "defaultValue": "class"
905
- },
906
- "VALUE": {
907
- "type": "STRING",
908
- "defaultValue": "content"
909
- }
910
- }
911
- },
912
- {
913
- "opcode": "htmlAppendChild",
914
- "blockType": "REPORTER",
915
- "text": "HTML [PARENT] with child [CHILD]",
916
- "description": "Appends a child node to an HTML element and returns the parent handle.",
917
- "arguments": {
918
- "PARENT": {
919
- "type": "STRING",
920
- "defaultValue": "html:1"
921
- },
922
- "CHILD": {
923
- "type": "STRING",
924
- "defaultValue": "html:2"
925
- }
926
- }
927
- },
928
- {
929
- "opcode": "renderHtml",
930
- "blockType": "REPORTER",
931
- "text": "render HTML [NODE]",
932
- "description": "Renders an HTML node handle to an HTML fragment.",
933
- "arguments": { "NODE": {
934
- "type": "STRING",
935
- "defaultValue": "html:1"
936
- } }
937
- },
938
- {
939
- "opcode": "renderHtmlDocument",
940
- "blockType": "REPORTER",
941
- "text": "render HTML document title [TITLE] body [BODY]",
942
- "description": "Renders a full HTML document from an HTML body node handle.",
943
- "arguments": {
944
- "TITLE": {
945
- "type": "STRING",
946
- "defaultValue": "Page"
947
- },
948
- "BODY": {
949
- "type": "STRING",
950
- "defaultValue": "html:1"
951
- }
952
- }
953
- }
954
- ]
955
- };
956
- //#endregion
957
- //#region src/protocol.ts
958
- function normalizeHeaderName(name) {
959
- return name.trim().toLowerCase();
960
- }
961
- function isValidHttpStatus(status) {
962
- return Number.isInteger(status) && status >= 100 && status <= 599;
963
- }
964
- function isForbiddenResponseHeader(name) {
965
- return [
966
- "connection",
967
- "content-length",
968
- "transfer-encoding",
969
- "upgrade"
970
- ].includes(normalizeHeaderName(name));
971
- }
972
- function validateHeaderName(name) {
973
- return /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name);
974
- }
975
- function validateHeaderValue(value) {
976
- return !/[\r\n]/.test(value);
977
- }
978
- function firstValue(values) {
979
- return values?.[0] ?? "";
980
- }
981
- //#endregion
982
- //#region src/extension.ts
983
- var blockDefinitions = block_definitions_default.blocks;
984
- var DEFAULT_SERVER_URL = "ws://127.0.0.1:8787/ws";
985
- var ALLOWED_HTML_TAGS = /* @__PURE__ */ new Set([
986
- "a",
987
- "article",
988
- "body",
989
- "button",
990
- "code",
991
- "dd",
992
- "div",
993
- "dl",
994
- "dt",
995
- "em",
996
- "footer",
997
- "form",
998
- "h1",
999
- "h2",
1000
- "h3",
1001
- "h4",
1002
- "h5",
1003
- "h6",
1004
- "header",
1005
- "img",
1006
- "input",
1007
- "label",
1008
- "li",
1009
- "main",
1010
- "ol",
1011
- "p",
1012
- "pre",
1013
- "section",
1014
- "span",
1015
- "strong",
1016
- "table",
1017
- "tbody",
1018
- "td",
1019
- "textarea",
1020
- "th",
1021
- "thead",
1022
- "tr",
1023
- "ul"
1024
- ]);
1025
- var VOID_HTML_TAGS = /* @__PURE__ */ new Set(["img", "input"]);
1026
- var VALID_ATTRIBUTE = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
1027
- var VALID_MARKDOWN_LANGUAGE = /^[a-zA-Z0-9_+.-]*$/;
1028
- var HTTP_REQUEST_HAT_OPCODE = `${extensionConfig.id}_whenHttpRequestReceived`;
1029
- var URL_ATTRIBUTES = /* @__PURE__ */ new Set([
1030
- "action",
1031
- "cite",
1032
- "formaction",
1033
- "href",
1034
- "poster",
1035
- "src",
1036
- "xlink:href"
1037
- ]);
1038
- var URL_LIST_ATTRIBUTES = /* @__PURE__ */ new Set(["srcset"]);
1039
- var SAFE_URL_SCHEMES = /* @__PURE__ */ new Set([
1040
- "http",
1041
- "https",
1042
- "mailto",
1043
- "tel"
1044
- ]);
1045
- var NAMED_BODY_KINDS = /* @__PURE__ */ new Set([
1046
- "structured",
1047
- "document",
1048
- "binary",
1049
- "asset"
1050
- ]);
1051
- var NAMED_BODY_SCOPES = /* @__PURE__ */ new Set(["target", "project"]);
1052
- var NAMED_BODY_REPRESENTATIONS = /* @__PURE__ */ new Set([
1053
- "json",
1054
- "yaml",
1055
- "html",
1056
- "markdown",
1057
- "raw"
1058
- ]);
1059
- var TurboWarpHttpServerExtension = class {
1060
- constructor() {
1061
- this.fixedInputs = fixedInputRegistration(typeof Scratch === "undefined" ? void 0 : Scratch);
1062
- this.serverUrl = DEFAULT_SERVER_URL;
1063
- this.socket = null;
1064
- this.lastReceivedMessage = "";
1065
- this.nextHandleId = 1;
1066
- this.httpLogs = [];
1067
- this.markdownBuilders = /* @__PURE__ */ new Map();
1068
- this.htmlNodes = /* @__PURE__ */ new Map();
1069
- this.requestContexts = /* @__PURE__ */ new Map();
1070
- this.currentRequestContextId = "";
1071
- }
1072
- dispose() {
1073
- this.fixedInputs.dispose();
1074
- }
1075
- getInfo() {
1076
- this.fixedInputs.ensure(blockDefinitions.map((block) => `${extensionConfig.id}_${block.opcode}`));
1077
- return {
1078
- id: extensionConfig.id,
1079
- name: Scratch.translate(block_definitions_default.extensionName),
1080
- docsURI: extensionConfig.docsURI,
1081
- blockIconURI: extensionConfig.blockIconURI,
1082
- blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
1083
- };
1084
- }
1085
- setServerUrl(args) {
1086
- this.serverUrl = Scratch.Cast.toString(args.URL).trim() || DEFAULT_SERVER_URL;
1087
- }
1088
- connect() {
1089
- if (this.isConnected()) return;
1090
- this.socket?.close();
1091
- const socket = new WebSocket(this.serverUrl);
1092
- this.socket = socket;
1093
- socket.addEventListener("message", (event) => {
1094
- this.lastReceivedMessage = this.stringifyMessage(event.data);
1095
- this.recordLogMessage(this.lastReceivedMessage);
1096
- this.receiveBridgeMessage(this.lastReceivedMessage);
1097
- });
1098
- socket.addEventListener("close", () => {
1099
- if (this.socket === socket) this.socket = null;
1100
- });
1101
- socket.addEventListener("error", () => {
1102
- if (this.socket === socket) this.socket = null;
1103
- });
1104
- }
1105
- disconnect() {
1106
- this.socket?.close();
1107
- this.socket = null;
1108
- }
1109
- isConnected() {
1110
- return this.socket?.readyState === WebSocket.OPEN;
1111
- }
1112
- sendText(args) {
1113
- if (!this.isConnected() || this.socket === null) return;
1114
- this.socket.send(Scratch.Cast.toString(args.MESSAGE));
1115
- }
1116
- lastMessage() {
1117
- return this.lastReceivedMessage;
1118
- }
1119
- whenHttpRequestReceived() {
1120
- return false;
1121
- }
1122
- useHttpRequest(args) {
1123
- const id = Scratch.Cast.toString(args.ID);
1124
- if (this.requestContexts.has(id)) this.currentRequestContextId = id;
1125
- }
1126
- currentRequestId() {
1127
- return this.currentContext()?.request.id ?? "";
1128
- }
1129
- currentHttpMethod() {
1130
- return this.currentContext()?.request.method ?? "";
1131
- }
1132
- currentRequestPath() {
1133
- return this.currentContext()?.request.path ?? "";
1134
- }
1135
- currentRequestUrl() {
1136
- return this.currentContext()?.request.url ?? "";
1137
- }
1138
- requestHeader(args) {
1139
- const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
1140
- return firstValue(this.currentContext()?.request.headers[name]);
1141
- }
1142
- queryParameter(args) {
1143
- return firstValue(this.currentContext()?.request.query[Scratch.Cast.toString(args.NAME)]);
1144
- }
1145
- pathParameter(args) {
1146
- return this.currentContext()?.request.pathParams[Scratch.Cast.toString(args.NAME)] ?? "";
1147
- }
1148
- currentRequestBody() {
1149
- const body = this.currentContext()?.request.body;
1150
- return body?.kind === "text" ? body.text : "";
1151
- }
1152
- currentRequestContentType() {
1153
- return this.requestHeader({ NAME: "content-type" });
1154
- }
1155
- currentRequestClientAddress() {
1156
- return this.currentContext()?.request.clientAddress ?? "";
1157
- }
1158
- setHandlerVariable(args) {
1159
- const context = this.mutableCurrentContext();
1160
- if (!context) return;
1161
- context.handlerVariables.set(Scratch.Cast.toString(args.NAME), Scratch.Cast.toString(args.VALUE));
1162
- }
1163
- changeHandlerVariable(args) {
1164
- const context = this.mutableCurrentContext();
1165
- if (!context) return;
1166
- const name = Scratch.Cast.toString(args.NAME);
1167
- const current = Scratch.Cast.toNumber(context.handlerVariables.get(name) ?? "");
1168
- context.handlerVariables.set(name, current + Scratch.Cast.toNumber(args.AMOUNT));
1169
- }
1170
- handlerVariable(args) {
1171
- return this.currentContext()?.handlerVariables.get(Scratch.Cast.toString(args.NAME)) ?? "";
1172
- }
1173
- handlerVariableExists(args) {
1174
- return this.currentContext()?.handlerVariables.has(Scratch.Cast.toString(args.NAME)) ?? false;
1175
- }
1176
- deleteHandlerVariable(args) {
1177
- this.mutableCurrentContext()?.handlerVariables.delete(Scratch.Cast.toString(args.NAME));
1178
- }
1179
- clearHandlerVariables() {
1180
- this.mutableCurrentContext()?.handlerVariables.clear();
1181
- }
1182
- listHandlerVariables() {
1183
- return Array.from(this.currentContext()?.handlerVariables.keys() ?? []).join(",");
1184
- }
1185
- currentAuthType() {
1186
- return this.currentContext()?.request.auth?.type ?? "";
1187
- }
1188
- currentAuthenticatedUser() {
1189
- const auth = this.currentContext()?.request.auth;
1190
- if (!auth) return "";
1191
- if (typeof auth.username === "string") return auth.username;
1192
- const profile = auth.profile;
1193
- return firstString(profile?.preferred_username, profile?.email, profile?.name, profile?.sub);
1194
- }
1195
- currentAuthProvider() {
1196
- return this.currentContext()?.request.auth?.provider ?? "";
1197
- }
1198
- currentAuthProfileJson() {
1199
- const profile = this.currentContext()?.request.auth?.profile;
1200
- return profile ? JSON.stringify(profile) : "";
1201
- }
1202
- authProfileField(args) {
1203
- const profile = this.currentContext()?.request.auth?.profile;
1204
- return stringifyProfileValue(readProfileField(profile, Scratch.Cast.toString(args.NAME)));
1205
- }
1206
- currentResponseStatus() {
1207
- return this.currentContext()?.response.status ?? 200;
1208
- }
1209
- setHttpStatus(args) {
1210
- const context = this.mutableCurrentContext();
1211
- if (!context) return;
1212
- const status = Math.trunc(Scratch.Cast.toNumber(args.STATUS));
1213
- if (isValidHttpStatus(status)) context.response.status = status;
1214
- }
1215
- setResponseHeader(args) {
1216
- const context = this.mutableCurrentContext();
1217
- if (!context) return;
1218
- const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
1219
- const value = Scratch.Cast.toString(args.VALUE);
1220
- if (validateHeaderName(name) && validateHeaderValue(value) && !isForbiddenResponseHeader(name)) context.response.headers[name] = [value];
1221
- }
1222
- removeResponseHeader(args) {
1223
- const context = this.mutableCurrentContext();
1224
- if (!context) return;
1225
- delete context.response.headers[normalizeHeaderName(Scratch.Cast.toString(args.NAME))];
1226
- }
1227
- responseHeader(args) {
1228
- const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
1229
- return firstValue(this.currentContext()?.response.headers[name]);
1230
- }
1231
- setResponseBody(args) {
1232
- const context = this.mutableCurrentContext();
1233
- if (!context) return;
1234
- context.response.body = {
1235
- kind: "text",
1236
- text: Scratch.Cast.toString(args.BODY)
1237
- };
1238
- }
1239
- sendResponse(args) {
1240
- const context = this.mutableCurrentContext();
1241
- if (!context) return;
1242
- context.response.body = {
1243
- kind: "text",
1244
- text: Scratch.Cast.toString(args.BODY)
1245
- };
1246
- this.completeResponse(context);
1247
- }
1248
- respondWithText(args) {
1249
- this.setResponseHeader({
1250
- NAME: "content-type",
1251
- VALUE: "text/plain; charset=utf-8"
1252
- });
1253
- this.sendResponse({ BODY: args.BODY });
1254
- }
1255
- respondWithHtml(args) {
1256
- this.setResponseHeader({
1257
- NAME: "content-type",
1258
- VALUE: "text/html; charset=utf-8"
1259
- });
1260
- this.sendResponse({ BODY: args.BODY });
1261
- }
1262
- respondWithJson(args) {
1263
- this.setResponseHeader({
1264
- NAME: "content-type",
1265
- VALUE: "application/json; charset=utf-8"
1266
- });
1267
- this.sendResponse({ BODY: args.BODY });
1268
- }
1269
- respondWithNamedBody(args) {
1270
- const context = this.mutableCurrentContext();
1271
- if (!context) return;
1272
- const kind = Scratch.Cast.toString(args.KIND).toLowerCase();
1273
- const scope = Scratch.Cast.toString(args.SCOPE).toLowerCase();
1274
- const representation = Scratch.Cast.toString(args.REPRESENTATION).toLowerCase();
1275
- const maxBytes = Math.trunc(Scratch.Cast.toNumber(args.MAX_BYTES));
1276
- if (!NAMED_BODY_KINDS.has(kind) || !NAMED_BODY_SCOPES.has(scope) || !NAMED_BODY_REPRESENTATIONS.has(representation) || !Number.isSafeInteger(maxBytes) || maxBytes < 1) {
1277
- context.response.body = {
1278
- kind: "unsupported",
1279
- reason: "invalid_named_body"
1280
- };
1281
- this.completeResponse(context);
1282
- return;
1283
- }
1284
- context.response.body = {
1285
- kind: "named",
1286
- reference: {
1287
- namespace: Scratch.Cast.toString(args.NAMESPACE),
1288
- name: Scratch.Cast.toString(args.NAME),
1289
- kind,
1290
- scope
1291
- },
1292
- representation,
1293
- ...scope === "target" ? { targetId: Scratch.Cast.toString(args.TARGET_ID) } : {},
1294
- maxBytes
1295
- };
1296
- this.completeResponse(context);
1297
- }
1298
- receiveBridgeRequestForTest(request) {
1299
- this.acceptBridgeRequest(request);
1300
- }
1301
- recordHttpLog(args) {
1302
- this.httpLogs.push(this.parseLogEntry(Scratch.Cast.toString(args.ENTRY)));
1303
- }
1304
- clearHttpLogs() {
1305
- this.httpLogs.length = 0;
1306
- }
1307
- httpLogViewerHtml() {
1308
- return this.renderLogViewer(this.httpLogs);
1309
- }
1310
- httpLogViewerHtmlFromJson(args) {
1311
- return this.renderLogViewer(this.parseLogArray(Scratch.Cast.toString(args.LOGS)));
1312
- }
1313
- newMarkdownDocument() {
1314
- const handle = this.nextHandle("md");
1315
- this.markdownBuilders.set(handle, []);
1316
- return handle;
1317
- }
1318
- markdownHeading(args) {
1319
- const handle = this.ensureMarkdownHandle(args.DOC);
1320
- const level = Math.min(6, Math.max(1, Math.trunc(Scratch.Cast.toNumber(args.LEVEL))));
1321
- this.markdownBuilders.get(handle)?.push(`${"#".repeat(level)} ${escapeMarkdownLine(Scratch.Cast.toString(args.TEXT))}`);
1322
- return handle;
1323
- }
1324
- markdownParagraph(args) {
1325
- const handle = this.ensureMarkdownHandle(args.DOC);
1326
- this.markdownBuilders.get(handle)?.push(escapeMarkdownParagraph(Scratch.Cast.toString(args.TEXT)));
1327
- return handle;
1328
- }
1329
- markdownBullet(args) {
1330
- const handle = this.ensureMarkdownHandle(args.DOC);
1331
- this.markdownBuilders.get(handle)?.push(`- ${escapeMarkdownLine(Scratch.Cast.toString(args.TEXT))}`);
1332
- return handle;
1333
- }
1334
- markdownCodeBlock(args) {
1335
- const handle = this.ensureMarkdownHandle(args.DOC);
1336
- const language = Scratch.Cast.toString(args.LANG).trim();
1337
- const safeLanguage = VALID_MARKDOWN_LANGUAGE.test(language) ? language : "";
1338
- const code = Scratch.Cast.toString(args.CODE).replace(/```/g, "`\\`\\`");
1339
- this.markdownBuilders.get(handle)?.push(`\`\`\`${safeLanguage}\n${code}\n\`\`\``);
1340
- return handle;
1341
- }
1342
- renderMarkdown(args) {
1343
- return this.markdownBuilders.get(Scratch.Cast.toString(args.DOC))?.join("\n\n") ?? "";
1344
- }
1345
- newHtmlElement(args) {
1346
- const tag = normalizeHtmlTag(Scratch.Cast.toString(args.TAG));
1347
- const handle = this.nextHandle("html");
1348
- this.htmlNodes.set(handle, {
1349
- kind: "element",
1350
- tag,
1351
- attributes: {},
1352
- children: []
1353
- });
1354
- return handle;
1355
- }
1356
- htmlText(args) {
1357
- const handle = this.nextHandle("html");
1358
- this.htmlNodes.set(handle, {
1359
- kind: "text",
1360
- text: Scratch.Cast.toString(args.TEXT)
1361
- });
1362
- return handle;
1363
- }
1364
- htmlSetAttribute(args) {
1365
- const handle = this.ensureHtmlElementHandle(args.NODE);
1366
- const node = this.htmlNodes.get(handle);
1367
- const name = Scratch.Cast.toString(args.NAME).trim();
1368
- const normalizedName = name.toLowerCase();
1369
- const value = Scratch.Cast.toString(args.VALUE);
1370
- if (node?.kind === "element" && VALID_ATTRIBUTE.test(name) && !normalizedName.startsWith("on") && isSafeAttributeValue(normalizedName, value)) node.attributes[name] = value;
1371
- return handle;
1372
- }
1373
- htmlAppendChild(args) {
1374
- const parentHandle = this.ensureHtmlElementHandle(args.PARENT);
1375
- const childHandle = Scratch.Cast.toString(args.CHILD);
1376
- const parent = this.htmlNodes.get(parentHandle);
1377
- if (parent?.kind === "element" && this.htmlNodes.has(childHandle) && parentHandle !== childHandle && !this.hasHtmlDescendant(childHandle, parentHandle, /* @__PURE__ */ new Set())) parent.children.push(childHandle);
1378
- return parentHandle;
1379
- }
1380
- renderHtml(args) {
1381
- return this.renderHtmlNode(Scratch.Cast.toString(args.NODE), /* @__PURE__ */ new Set());
1382
- }
1383
- renderHtmlDocument(args) {
1384
- return `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(Scratch.Cast.toString(args.TITLE))}</title></head><body>${this.renderHtmlNode(Scratch.Cast.toString(args.BODY), /* @__PURE__ */ new Set())}</body></html>`;
1385
- }
1386
- stringifyMessage(message) {
1387
- if (typeof message === "string") return message;
1388
- if (message instanceof ArrayBuffer) return new TextDecoder().decode(message);
1389
- return String(message);
1390
- }
1391
- receiveBridgeMessage(message) {
1392
- try {
1393
- const parsed = JSON.parse(message);
1394
- if (parsed.type === "request" && typeof parsed.id === "string") this.acceptBridgeRequest(parsed);
1395
- } catch {
1396
- return;
1397
- }
1398
- }
1399
- acceptBridgeRequest(request) {
1400
- const normalizedRequest = {
1401
- ...request,
1402
- headers: normalizeHeaderRecord(request.headers),
1403
- query: normalizeValueRecord(request.query),
1404
- pathParams: normalizePathParams(request.pathParams)
1405
- };
1406
- const auth = normalizeAuthContext(request.auth);
1407
- if (auth) normalizedRequest.auth = auth;
1408
- this.requestContexts.set(request.id, {
1409
- request: normalizedRequest,
1410
- response: {
1411
- status: 200,
1412
- headers: {},
1413
- body: { kind: "empty" },
1414
- completed: false
1415
- },
1416
- handlerVariables: /* @__PURE__ */ new Map()
1417
- });
1418
- this.currentRequestContextId = request.id;
1419
- this.startRequestHat();
1420
- }
1421
- currentContext() {
1422
- return this.requestContexts.get(this.currentRequestContextId);
1423
- }
1424
- mutableCurrentContext() {
1425
- const context = this.currentContext();
1426
- return context && !context.response.completed ? context : void 0;
1427
- }
1428
- completeResponse(context) {
1429
- if (context.response.completed) return;
1430
- context.response.completed = true;
1431
- const message = {
1432
- type: "response",
1433
- id: context.request.id,
1434
- status: context.response.status,
1435
- headers: context.response.headers,
1436
- body: context.response.body
1437
- };
1438
- this.socket?.send(JSON.stringify(message));
1439
- this.requestContexts.delete(context.request.id);
1440
- if (this.currentRequestContextId === context.request.id) this.currentRequestContextId = "";
1441
- }
1442
- recordLogMessage(message) {
1443
- const parsed = this.parseLogEntry(message);
1444
- if (isLogLike(parsed)) this.httpLogs.push(parsed);
1445
- }
1446
- startRequestHat() {
1447
- Scratch.vm?.runtime?.startHats?.(HTTP_REQUEST_HAT_OPCODE);
1448
- }
1449
- parseLogEntry(value) {
1450
- try {
1451
- return JSON.parse(value);
1452
- } catch {
1453
- return { message: value };
1454
- }
1455
- }
1456
- parseLogArray(value) {
1457
- const parsed = this.parseLogEntry(value);
1458
- return Array.isArray(parsed) ? parsed : [parsed];
1459
- }
1460
- renderLogViewer(logs) {
1461
- return `<!doctype html><html><head><meta charset="utf-8"><title>HTTP Logs</title><style>
1462
- body{margin:0;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;background:#0f172a;color:#e5e7eb}
1463
- header{height:44px;display:flex;align-items:center;padding:0 16px;background:#111827;border-bottom:1px solid #334155}
1464
- #viewport{height:calc(100vh - 45px);overflow:auto;position:relative}
1465
- #spacer{width:1px}.row{position:absolute;left:0;right:0;height:32px;display:grid;grid-template-columns:72px 84px 1fr;gap:10px;align-items:center;padding:0 12px;border-bottom:1px solid #1f2937;box-sizing:border-box;white-space:nowrap}
1466
- .status{color:#93c5fd}.method{color:#86efac}.path{overflow:hidden;text-overflow:ellipsis}
1467
- </style></head><body><header>HTTP logs <span id="count"></span></header><div id="viewport"><div id="spacer"></div><div id="rows"></div></div><script>
1468
- const logs=${JSON.stringify(logs).replace(/</g, "\\u003c")};const rowHeight=32;const viewport=document.getElementById('viewport');const spacer=document.getElementById('spacer');const rows=document.getElementById('rows');document.getElementById('count').textContent='('+logs.length+')';spacer.style.height=(logs.length*rowHeight)+'px';
1469
- function text(v){return v==null?'':String(v)}function render(){const top=viewport.scrollTop;const first=Math.max(0,Math.floor(top/rowHeight)-8);const visible=Math.ceil(viewport.clientHeight/rowHeight)+16;const last=Math.min(logs.length,first+visible);let html='';for(let i=first;i<last;i++){const log=logs[i]||{};const method=text(log.method||log.event||'LOG');const status=text(log.status||'');const path=text(log.path||log.resourceName||log.message||JSON.stringify(log));html+='<div class="row" style="transform:translateY('+(i*rowHeight)+'px)"><span class="method">'+escapeHtml(method)+'</span><span class="status">'+escapeHtml(status)+'</span><span class="path">'+escapeHtml(path)+'</span></div>'}rows.innerHTML=html}
1470
- function escapeHtml(value){return value.replace(/[&<>"']/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]))}viewport.addEventListener('scroll',render);render();
1471
- <\/script></body></html>`;
1472
- }
1473
- ensureMarkdownHandle(value) {
1474
- const handle = Scratch.Cast.toString(value);
1475
- if (this.markdownBuilders.has(handle)) return handle;
1476
- return this.newMarkdownDocument();
1477
- }
1478
- ensureHtmlElementHandle(value) {
1479
- const handle = Scratch.Cast.toString(value);
1480
- if (this.htmlNodes.get(handle)?.kind === "element") return handle;
1481
- return this.newHtmlElement({ TAG: "div" });
1482
- }
1483
- renderHtmlNode(handle, visiting) {
1484
- if (visiting.has(handle)) return "";
1485
- const node = this.htmlNodes.get(handle);
1486
- if (!node) return "";
1487
- if (node.kind === "text") return escapeHtml(node.text);
1488
- visiting.add(handle);
1489
- const attributes = Object.entries(node.attributes).map(([name, value]) => ` ${name}="${escapeHtml(value)}"`).join("");
1490
- if (VOID_HTML_TAGS.has(node.tag)) {
1491
- visiting.delete(handle);
1492
- return `<${node.tag}${attributes}>`;
1493
- }
1494
- const children = node.children.map((child) => this.renderHtmlNode(child, visiting)).join("");
1495
- visiting.delete(handle);
1496
- return `<${node.tag}${attributes}>${children}</${node.tag}>`;
1497
- }
1498
- hasHtmlDescendant(handle, targetHandle, visited) {
1499
- if (visited.has(handle)) return false;
1500
- visited.add(handle);
1501
- const node = this.htmlNodes.get(handle);
1502
- if (node?.kind !== "element") return false;
1503
- return node.children.some((child) => child === targetHandle || this.hasHtmlDescendant(child, targetHandle, visited));
1504
- }
1505
- nextHandle(prefix) {
1506
- const handle = `${prefix}:${this.nextHandleId}`;
1507
- this.nextHandleId += 1;
1508
- return handle;
1509
- }
1510
- toScratchBlock(block) {
1511
- return {
1512
- opcode: block.opcode,
1513
- blockType: Scratch.BlockType[block.blockType],
1514
- text: Scratch.translate(block.text),
1515
- arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
1516
- type: Scratch.ArgumentType[argument.type],
1517
- defaultValue: argument.defaultValue
1518
- }]))
1519
- };
1520
- }
1521
- };
1522
- function isLogLike(value) {
1523
- return typeof value === "object" && value !== null && !Array.isArray(value);
1524
- }
1525
- function normalizeHeaderRecord(headers) {
1526
- const normalized = {};
1527
- for (const [name, values] of Object.entries(headers ?? {})) normalized[normalizeHeaderName(name)] = values.map((value) => String(value));
1528
- return normalized;
1529
- }
1530
- function normalizeValueRecord(values) {
1531
- const normalized = {};
1532
- for (const [name, items] of Object.entries(values ?? {})) normalized[name] = items.map((value) => String(value));
1533
- return normalized;
1534
- }
1535
- function normalizePathParams(values) {
1536
- const normalized = {};
1537
- for (const [name, value] of Object.entries(values ?? {})) normalized[name] = String(value);
1538
- return normalized;
1539
- }
1540
- function normalizeAuthContext(auth) {
1541
- if (typeof auth !== "object" || auth === null || Array.isArray(auth)) return void 0;
1542
- const type = typeof auth.type === "string" ? auth.type : "";
1543
- if (!type) return void 0;
1544
- const normalized = { type };
1545
- if (typeof auth.username === "string") normalized.username = auth.username;
1546
- if (typeof auth.provider === "string") normalized.provider = auth.provider;
1547
- if (isPlainRecord(auth.profile)) normalized.profile = normalizeProfile(auth.profile);
1548
- return normalized;
1549
- }
1550
- function normalizeProfile(profile) {
1551
- return JSON.parse(JSON.stringify(profile));
1552
- }
1553
- function readProfileField(profile, path) {
1554
- if (!profile) return void 0;
1555
- const segments = path.split(".").map((segment) => segment.trim()).filter(Boolean);
1556
- if (segments.length === 0) return void 0;
1557
- let value = profile;
1558
- for (const segment of segments) {
1559
- if (!isPlainRecord(value)) return void 0;
1560
- value = value[segment];
1561
- }
1562
- return value;
1563
- }
1564
- function stringifyProfileValue(value) {
1565
- if (value === void 0 || value === null) return "";
1566
- if (typeof value === "string") return value;
1567
- if (typeof value === "number" || typeof value === "boolean") return String(value);
1568
- return JSON.stringify(value);
1569
- }
1570
- function firstString(...values) {
1571
- return values.find((value) => typeof value === "string") ?? "";
1572
- }
1573
- function isPlainRecord(value) {
1574
- return typeof value === "object" && value !== null && !Array.isArray(value);
1575
- }
1576
- function escapeMarkdownLine(value) {
1577
- return value.replace(/\\/g, "\\\\").replace(/([`*_#[\]])/g, "\\$1").replace(/\r?\n/g, " ");
1578
- }
1579
- function escapeMarkdownParagraph(value) {
1580
- return value.replace(/\\/g, "\\\\").replace(/([`*_#[\]])/g, "\\$1");
1581
- }
1582
- function normalizeHtmlTag(value) {
1583
- const tag = value.trim().toLowerCase();
1584
- return ALLOWED_HTML_TAGS.has(tag) ? tag : "div";
1585
- }
1586
- function isSafeAttributeValue(name, value) {
1587
- if (URL_LIST_ATTRIBUTES.has(name)) return isSafeUrlList(value);
1588
- if (URL_ATTRIBUTES.has(name)) return isSafeUrl(value);
1589
- return true;
1590
- }
1591
- function isSafeUrlList(value) {
1592
- return value.split(",").map((candidate) => candidate.trim().split(/\s+/, 1)[0] ?? "").every((url) => isSafeUrl(url));
1593
- }
1594
- function isSafeUrl(value) {
1595
- const trimmed = value.trim();
1596
- if (!trimmed) return true;
1597
- const normalized = stripUrlSchemeSeparators(trimmed);
1598
- const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(normalized)?.[1]?.toLowerCase();
1599
- return scheme === void 0 || SAFE_URL_SCHEMES.has(scheme);
1600
- }
1601
- function stripUrlSchemeSeparators(value) {
1602
- let result = "";
1603
- for (const character of value) {
1604
- const code = character.charCodeAt(0);
1605
- if (code <= 31 || code === 127 || /\s/.test(character)) continue;
1606
- result += character;
1607
- }
1608
- return result;
1609
- }
1610
- function escapeHtml(value) {
1611
- return value.replace(/[&<>"']/g, (character) => {
1612
- if (character === "&") return "&amp;";
1613
- if (character === "<") return "&lt;";
1614
- if (character === ">") return "&gt;";
1615
- if (character === "\"") return "&quot;";
1616
- return "&#39;";
1617
- });
1618
- }
1619
- //#endregion
1620
- //#region src/index.ts
1621
- if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1622
- Scratch.extensions.register(new TurboWarpHttpServerExtension());
1623
- //#endregion
10
+ //#region src/config.ts
11
+ var extensionConfig = {
12
+ id: "kubohiroyaturbowarphttpserver",
13
+ slug: "turbowarp-http-server",
14
+ name: "TurboWarp-HTTP-Server",
15
+ description: "Connect TurboWarp blocks to an HTTP bridge server over WebSocket.",
16
+ author: "Hiroya Kubo",
17
+ license: "MPL-2.0",
18
+ unsandboxed: true,
19
+ docsURI: "https://kubohiroya.github.io/turbowarp-http-server/",
20
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHBhdGggZD0iTTI4LjAgMjcuMEwyOC4wIDUuME0yOC4wIDI3LjBMNDMuNiAxMS40TTI4LjAgMjcuMEw1MC4wIDI3LjBNMjguMCAyNy4wTDQzLjYgNDIuNk0yOC4wIDI3LjBMMjguMCA0OS4wTTI4LjAgMjcuMEwxMi40IDQyLjZNMjguMCAyNy4wTDYuMCAyNy4wTTI4LjAgMjcuMEwxMi40IDExLjQiIHN0cm9rZT0iIzI1NjNFQiIgc3Ryb2tlLXdpZHRoPSIxLjA0IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48cGF0aCBkPSJNMjguMCAxMC4wTDQwLjAgMTUuMEw0NS4wIDI3LjBMNDAuMCAzOS4wTDI4LjAgNDQuMEwxNi4wIDM5LjBMMTEuMCAyNy4wTDE2LjAgMTUuMFoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzI1NjNFQiIgc3Ryb2tlLXdpZHRoPSIxLjMiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNMjIuNSAyMWgxMS41bDcgN3YxNC41YTIgMiAwIDAgMS0yIDJIMjIuNWEyIDIgMCAwIDEtMi0yVjIzYTIgMiAwIDAgMSAyLTJ6IiBmaWxsPSIjZmZmIiBzdHJva2U9IiMxNjMwNUMiIHN0cm9rZS13aWR0aD0iMi40IiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHBhdGggZD0iTTM0IDIxdjdoNyIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMTYzMDVDIiBzdHJva2Utd2lkdGg9IjIuNCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik0yNS41IDMzLjVoOS41TTI1LjUgMzkuNWg0LjUiIHN0cm9rZT0iIzE2MzA1QyIgc3Ryb2tlLXdpZHRoPSIyLjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPjxwYXRoIGQ9Ik0xNCAwVjguMCIgc3Ryb2tlPSIjMTYzMDVDIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PHBhdGggZD0iTTEyLjMgOC41TDYuMSA2LjlMMy4xIDIuOU0xNS43IDguNUwyMS45IDYuOUwyNC45IDIuOU0xMi4zIDEwLjBMNS40IDkuOUwyLjEgNi45TTE1LjcgMTAuMEwyMi42IDkuOUwyNS45IDYuOU0xMi4zIDExLjhMNS40IDExLjlMMi4xIDE0LjlNMTUuNyAxMS44TDIyLjYgMTEuOUwyNS45IDE0LjlNMTIuMyAxMy4zTDYuMSAxNC45TDMuMSAxOC45TTE1LjcgMTMuM0wyMS45IDE0LjlMMjQuOSAxOC45IiBmaWxsPSJub25lIiBzdHJva2U9IiMxNjMwNUMiIHN0cm9rZS13aWR0aD0iMS4wNSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PGNpcmNsZSBjeD0iMTQiIGN5PSIxMC45IiByPSIzLjQiIGZpbGw9IiMxNjMwNUMiLz48Y2lyY2xlIGN4PSIxNCIgY3k9IjE1LjEiIHI9IjIuMyIgZmlsbD0iIzE2MzA1QyIvPjwvc3ZnPg=="
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-http-server/schemas/block-editor-fixed-inputs.schema.json",
56
+ $defs: {
57
+ "changeHandlerVariable": {
58
+ "type": "object",
59
+ "properties": { "AMOUNT": { "type": "number" } },
60
+ "required": ["AMOUNT"],
61
+ "additionalProperties": true
62
+ },
63
+ "setHttpStatus": {
64
+ "type": "object",
65
+ "properties": { "STATUS": { "type": "number" } },
66
+ "required": ["STATUS"],
67
+ "additionalProperties": true
68
+ },
69
+ "respondWithNamedBody": {
70
+ "type": "object",
71
+ "properties": {
72
+ "KIND": {
73
+ "type": "string",
74
+ "enum": [
75
+ "structured",
76
+ "document",
77
+ "binary",
78
+ "asset"
79
+ ]
80
+ },
81
+ "SCOPE": {
82
+ "type": "string",
83
+ "enum": ["target", "project"]
84
+ },
85
+ "REPRESENTATION": {
86
+ "type": "string",
87
+ "enum": [
88
+ "json",
89
+ "yaml",
90
+ "html",
91
+ "markdown",
92
+ "raw"
93
+ ]
94
+ },
95
+ "MAX_BYTES": {
96
+ "type": "number",
97
+ "minimum": 1,
98
+ "exclusiveMaximum": 9007199254740992
99
+ }
100
+ },
101
+ "required": [
102
+ "KIND",
103
+ "SCOPE",
104
+ "REPRESENTATION",
105
+ "MAX_BYTES"
106
+ ],
107
+ "additionalProperties": true
108
+ },
109
+ "markdownHeading": {
110
+ "type": "object",
111
+ "properties": { "LEVEL": { "type": "number" } },
112
+ "required": ["LEVEL"],
113
+ "additionalProperties": true
114
+ }
115
+ }
116
+ };
117
+ //#endregion
118
+ //#region src/fixed-input-schema.ts
119
+ var repository$1 = "turbowarp-http-server";
120
+ /** The owner JSON document is canonical; this selects a primitive field fragment. */
121
+ function fixedInputBundle(opcode, argument) {
122
+ const source = {
123
+ repository: repository$1,
124
+ path: "schemas/block-editor-fixed-inputs.schema.json",
125
+ symbol: `#/$defs/${opcode}/properties/${argument}`
126
+ };
127
+ const blocks = block_editor_fixed_inputs_schema_default.$defs;
128
+ return {
129
+ identity: {
130
+ ownerId: repository$1,
131
+ contractId: opcode,
132
+ revision: "fixed-inputs-v1",
133
+ variantId: argument
134
+ },
135
+ dialect: "2020-12",
136
+ root: {
137
+ retrievalUri: block_editor_fixed_inputs_schema_default.$id,
138
+ document: blocks[opcode].properties[argument],
139
+ artifact: {
140
+ role: "canonical-schema",
141
+ source
142
+ }
143
+ },
144
+ resources: [],
145
+ provenance: {
146
+ canonicalSources: [source, {
147
+ repository: repository$1,
148
+ path: "src/extension.ts",
149
+ symbol: opcode
150
+ }],
151
+ generatedFiles: [],
152
+ referenceSchemas: [],
153
+ generationSources: []
154
+ }
155
+ };
156
+ }
157
+ //#endregion
158
+ //#region src/fixed-input-editors.ts
159
+ var extensionId = "kubohiroyaturbowarphttpserver";
160
+ var repository = "turbowarp-http-server";
161
+ var fields = [
162
+ {
163
+ "opcode": "changeHandlerVariable",
164
+ "argument": "AMOUNT",
165
+ "control": "number",
166
+ "choices": [],
167
+ "normalization": "identity",
168
+ "shape": "math_number.NUM",
169
+ "maxBytes": false
170
+ },
171
+ {
172
+ "opcode": "setHttpStatus",
173
+ "argument": "STATUS",
174
+ "control": "number",
175
+ "choices": [],
176
+ "normalization": "identity",
177
+ "shape": "math_number.NUM",
178
+ "maxBytes": false
179
+ },
180
+ {
181
+ "opcode": "respondWithNamedBody",
182
+ "argument": "KIND",
183
+ "control": "enum",
184
+ "choices": [
185
+ "structured",
186
+ "document",
187
+ "binary",
188
+ "asset"
189
+ ],
190
+ "normalization": "lowercase",
191
+ "shape": "text.TEXT",
192
+ "maxBytes": false
193
+ },
194
+ {
195
+ "opcode": "respondWithNamedBody",
196
+ "argument": "SCOPE",
197
+ "control": "enum",
198
+ "choices": ["target", "project"],
199
+ "normalization": "lowercase",
200
+ "shape": "text.TEXT",
201
+ "maxBytes": false
202
+ },
203
+ {
204
+ "opcode": "respondWithNamedBody",
205
+ "argument": "REPRESENTATION",
206
+ "control": "enum",
207
+ "choices": [
208
+ "json",
209
+ "yaml",
210
+ "html",
211
+ "markdown",
212
+ "raw"
213
+ ],
214
+ "normalization": "lowercase",
215
+ "shape": "text.TEXT",
216
+ "maxBytes": false
217
+ },
218
+ {
219
+ "opcode": "respondWithNamedBody",
220
+ "argument": "MAX_BYTES",
221
+ "control": "number",
222
+ "choices": [],
223
+ "normalization": "identity",
224
+ "shape": "math_number.NUM",
225
+ "maxBytes": true
226
+ },
227
+ {
228
+ "opcode": "markdownHeading",
229
+ "argument": "LEVEL",
230
+ "control": "number",
231
+ "choices": [],
232
+ "normalization": "identity",
233
+ "shape": "math_number.NUM",
234
+ "maxBytes": false
235
+ }
236
+ ];
237
+ function literalString(value) {
238
+ if (typeof value !== "string") throw new TypeError("Expected a string literal.");
239
+ return value;
240
+ }
241
+ /** Legacy nonempty finite aliases are projections; opening never creates a write. */
242
+ function existingFixedNumber(value) {
243
+ if (typeof value !== "string" && typeof value !== "number" || typeof value === "string" && value.trim() === "") throw new TypeError("Unavailable numeric projection.");
244
+ const number = Number(value);
245
+ if (!Number.isFinite(number)) throw new TypeError("Unavailable numeric projection.");
246
+ return number;
247
+ }
248
+ function normalizeChoice(field, raw) {
249
+ if (field.normalization === "lowercase") return raw.toLowerCase();
250
+ if (field.normalization === "method") return raw.trim().toUpperCase();
251
+ if (field.normalization === "trim") return raw.trim();
252
+ if (field.normalization === "parse-format") {
253
+ const lower = raw.trim().toLowerCase();
254
+ return lower === "json" ? "JSON" : lower === "yaml" ? "YAML" : lower === "auto" ? "auto" : raw;
255
+ }
256
+ return raw;
257
+ }
258
+ function binding(field) {
259
+ return {
260
+ argument: field.argument,
261
+ schemaBundle: fixedInputBundle(field.opcode, field.argument),
262
+ control: {
263
+ kind: field.control,
264
+ ...field.control === "enum" ? { choices: field.choices.map((value) => ({ value })) } : {}
265
+ },
266
+ read(value) {
267
+ return field.control === "number" ? existingFixedNumber(value) : normalizeChoice(field, literalString(value));
268
+ },
269
+ encode(value) {
270
+ if (field.control === "number") {
271
+ const parsed = parseFixedNumberInput(value);
272
+ if (parsed.kind !== "valid") throw new TypeError("Invalid new numeric input.");
273
+ return parsed.token;
274
+ }
275
+ const raw = literalString(value), normalized = normalizeChoice(field, raw);
276
+ if (!field.choices.includes(normalized)) throw new TypeError("Unsupported fixed choice.");
277
+ return field.shape === "menu-shadow" || field.shape === "direct-field-dropdown" ? normalized : raw;
278
+ },
279
+ validateCandidate(value) {
280
+ try {
281
+ if (field.control === "number") {
282
+ const number = existingFixedNumber(value);
283
+ if (field.maxBytes && (!Number.isSafeInteger(Math.trunc(number)) || Math.trunc(number) < 1)) return [{ message: "Invalid named body size." }];
284
+ return [];
285
+ }
286
+ return field.choices.includes(normalizeChoice(field, literalString(value))) ? [] : [{ message: "Unsupported fixed choice." }];
287
+ } catch {
288
+ return [{ message: "Invalid fixed input." }];
289
+ }
290
+ }
291
+ };
292
+ }
293
+ var fixedInputEditors = [...new Set(fields.map((f) => f.opcode))].map((opcode) => ({
294
+ apiVersion: 1,
295
+ extensionId,
296
+ editorId: `${opcode}-fixed-inputs`,
297
+ opcodes: [`${extensionId}_${opcode}`],
298
+ contractId: `${repository}/${opcode}`,
299
+ contractRevision: "fixed-inputs-v1",
300
+ bindings: fields.filter((field) => field.opcode === opcode).map(binding),
301
+ validationContext: () => ({
302
+ consumerId: repository,
303
+ nowMs: 0,
304
+ settings: null
305
+ })
306
+ }));
307
+ /** Registration follows the advertised opcode membership and the optional host capability. */
308
+ function fixedInputRegistration(scratch) {
309
+ const host = scratch ?? {};
310
+ let active;
311
+ let membership = "";
312
+ const removers = [];
313
+ let stopped = false;
314
+ const clear = () => {
315
+ host.vm?.runtime?.off?.("RUNTIME_DISPOSED", shutdown);
316
+ for (const remove of removers.splice(0).reverse()) remove();
317
+ active = void 0;
318
+ membership = "";
319
+ };
320
+ const shutdown = () => {
321
+ stopped = true;
322
+ clear();
323
+ };
324
+ return {
325
+ ensure(visibleOpcodes) {
326
+ const api = host.gui?.blockEditors;
327
+ const definitions = fixedInputEditors.filter((definition) => definition.opcodes.every((opcode) => visibleOpcodes.includes(opcode)));
328
+ const key = definitions.map((definition) => definition.editorId).join(",");
329
+ if (stopped || api === active && membership === key) return;
330
+ clear();
331
+ if (api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function" || !definitions.length) return;
332
+ try {
333
+ for (const definition of definitions) {
334
+ const remove = api.registerFixedInputEditor.call(api, definition);
335
+ if (typeof remove !== "function") throw new TypeError("Invalid fixed input cleanup.");
336
+ removers.push(remove);
337
+ }
338
+ active = api;
339
+ membership = key;
340
+ host.vm?.runtime?.on?.("RUNTIME_DISPOSED", shutdown);
341
+ } catch (error) {
342
+ clear();
343
+ throw error;
344
+ }
345
+ },
346
+ dispose: shutdown
347
+ };
348
+ }
349
+ var block_definitions_default = {
350
+ extensionName: "TurboWarp-HTTP-Server",
351
+ blocks: [
352
+ {
353
+ "opcode": "setServerUrl",
354
+ "blockType": "COMMAND",
355
+ "text": "set HTTP bridge URL to [URL]",
356
+ "description": "Sets the WebSocket URL used to reach the HTTP bridge server.",
357
+ "arguments": { "URL": {
358
+ "type": "STRING",
359
+ "defaultValue": "ws://127.0.0.1:8787/ws"
360
+ } }
361
+ },
362
+ {
363
+ "opcode": "connect",
364
+ "blockType": "COMMAND",
365
+ "text": "connect to HTTP bridge",
366
+ "description": "Opens a WebSocket connection to the configured HTTP bridge server.",
367
+ "arguments": {}
368
+ },
369
+ {
370
+ "opcode": "disconnect",
371
+ "blockType": "COMMAND",
372
+ "text": "disconnect from HTTP bridge",
373
+ "description": "Closes the current bridge connection.",
374
+ "arguments": {}
375
+ },
376
+ {
377
+ "opcode": "isConnected",
378
+ "blockType": "BOOLEAN",
379
+ "text": "HTTP bridge connected?",
380
+ "description": "Reports whether the bridge WebSocket is currently open.",
381
+ "arguments": {}
382
+ },
383
+ {
384
+ "opcode": "sendText",
385
+ "blockType": "COMMAND",
386
+ "text": "send [MESSAGE] to HTTP bridge",
387
+ "description": "Sends a text message to the connected HTTP bridge server.",
388
+ "arguments": { "MESSAGE": {
389
+ "type": "STRING",
390
+ "defaultValue": "{\"type\":\"ping\"}"
391
+ } }
392
+ },
393
+ {
394
+ "opcode": "lastMessage",
395
+ "blockType": "REPORTER",
396
+ "text": "last HTTP bridge message",
397
+ "description": "Returns the most recent text message received from the bridge.",
398
+ "arguments": {}
399
+ },
400
+ {
401
+ "opcode": "whenHttpRequestReceived",
402
+ "blockType": "HAT",
403
+ "text": "when HTTP request received",
404
+ "description": "Starts a TurboWarp handler thread when the bridge receives an HTTP request.",
405
+ "arguments": {}
406
+ },
407
+ {
408
+ "opcode": "useHttpRequest",
409
+ "blockType": "COMMAND",
410
+ "text": "use HTTP request [ID]",
411
+ "description": "Selects a pending request context by request ID.",
412
+ "arguments": { "ID": {
413
+ "type": "STRING",
414
+ "defaultValue": "req-1"
415
+ } }
416
+ },
417
+ {
418
+ "opcode": "currentRequestId",
419
+ "blockType": "REPORTER",
420
+ "text": "current request ID",
421
+ "description": "Returns the current HTTP request ID.",
422
+ "arguments": {}
423
+ },
424
+ {
425
+ "opcode": "currentHttpMethod",
426
+ "blockType": "REPORTER",
427
+ "text": "current HTTP method",
428
+ "description": "Returns the current HTTP request method.",
429
+ "arguments": {}
430
+ },
431
+ {
432
+ "opcode": "currentRequestPath",
433
+ "blockType": "REPORTER",
434
+ "text": "current request path",
435
+ "description": "Returns the current HTTP request path.",
436
+ "arguments": {}
437
+ },
438
+ {
439
+ "opcode": "currentRequestUrl",
440
+ "blockType": "REPORTER",
441
+ "text": "current request URL",
442
+ "description": "Returns the current HTTP request URL.",
443
+ "arguments": {}
444
+ },
445
+ {
446
+ "opcode": "requestHeader",
447
+ "blockType": "REPORTER",
448
+ "text": "request header [NAME]",
449
+ "description": "Returns the first value of a request header using case-insensitive lookup.",
450
+ "arguments": { "NAME": {
451
+ "type": "STRING",
452
+ "defaultValue": "accept"
453
+ } }
454
+ },
455
+ {
456
+ "opcode": "queryParameter",
457
+ "blockType": "REPORTER",
458
+ "text": "query parameter [NAME]",
459
+ "description": "Returns the first query parameter value.",
460
+ "arguments": { "NAME": {
461
+ "type": "STRING",
462
+ "defaultValue": "q"
463
+ } }
464
+ },
465
+ {
466
+ "opcode": "pathParameter",
467
+ "blockType": "REPORTER",
468
+ "text": "path parameter [NAME]",
469
+ "description": "Returns a route path parameter value.",
470
+ "arguments": { "NAME": {
471
+ "type": "STRING",
472
+ "defaultValue": "id"
473
+ } }
474
+ },
475
+ {
476
+ "opcode": "currentRequestBody",
477
+ "blockType": "REPORTER",
478
+ "text": "current request body",
479
+ "description": "Returns the current textual request body, or an empty string for non-text bodies.",
480
+ "arguments": {}
481
+ },
482
+ {
483
+ "opcode": "currentRequestContentType",
484
+ "blockType": "REPORTER",
485
+ "text": "current request content type",
486
+ "description": "Returns the current request Content-Type header.",
487
+ "arguments": {}
488
+ },
489
+ {
490
+ "opcode": "currentRequestClientAddress",
491
+ "blockType": "REPORTER",
492
+ "text": "current request client address",
493
+ "description": "Returns the current request client address when available.",
494
+ "arguments": {}
495
+ },
496
+ {
497
+ "opcode": "setHandlerVariable",
498
+ "blockType": "COMMAND",
499
+ "text": "set handler variable [NAME] to [VALUE]",
500
+ "description": "Sets a request-local variable that is discarded when the current HTTP response completes.",
501
+ "arguments": {
502
+ "NAME": {
503
+ "type": "STRING",
504
+ "defaultValue": "value"
505
+ },
506
+ "VALUE": {
507
+ "type": "STRING",
508
+ "defaultValue": "0"
509
+ }
510
+ }
511
+ },
512
+ {
513
+ "opcode": "changeHandlerVariable",
514
+ "blockType": "COMMAND",
515
+ "text": "change handler variable [NAME] by [AMOUNT]",
516
+ "description": "Changes a request-local numeric variable using Scratch number conversion rules.",
517
+ "arguments": {
518
+ "NAME": {
519
+ "type": "STRING",
520
+ "defaultValue": "value"
521
+ },
522
+ "AMOUNT": {
523
+ "type": "NUMBER",
524
+ "defaultValue": 1
525
+ }
526
+ }
527
+ },
528
+ {
529
+ "opcode": "handlerVariable",
530
+ "blockType": "REPORTER",
531
+ "text": "handler variable [NAME]",
532
+ "description": "Returns a request-local handler variable, or an empty string when it does not exist.",
533
+ "arguments": { "NAME": {
534
+ "type": "STRING",
535
+ "defaultValue": "value"
536
+ } }
537
+ },
538
+ {
539
+ "opcode": "handlerVariableExists",
540
+ "blockType": "BOOLEAN",
541
+ "text": "handler variable [NAME] exists?",
542
+ "description": "Reports whether a request-local handler variable exists.",
543
+ "arguments": { "NAME": {
544
+ "type": "STRING",
545
+ "defaultValue": "value"
546
+ } }
547
+ },
548
+ {
549
+ "opcode": "deleteHandlerVariable",
550
+ "blockType": "COMMAND",
551
+ "text": "delete handler variable [NAME]",
552
+ "description": "Deletes a request-local handler variable.",
553
+ "arguments": { "NAME": {
554
+ "type": "STRING",
555
+ "defaultValue": "value"
556
+ } }
557
+ },
558
+ {
559
+ "opcode": "clearHandlerVariables",
560
+ "blockType": "COMMAND",
561
+ "text": "delete all handler variables",
562
+ "description": "Deletes all request-local handler variables for the current HTTP handler.",
563
+ "arguments": {}
564
+ },
565
+ {
566
+ "opcode": "listHandlerVariables",
567
+ "blockType": "REPORTER",
568
+ "text": "active handler variables",
569
+ "description": "Returns comma-separated names of request-local handler variables.",
570
+ "arguments": {}
571
+ },
572
+ {
573
+ "opcode": "currentAuthType",
574
+ "blockType": "REPORTER",
575
+ "text": "current auth type",
576
+ "description": "Returns the current authentication type, such as digest or oauth.",
577
+ "arguments": {}
578
+ },
579
+ {
580
+ "opcode": "currentAuthenticatedUser",
581
+ "blockType": "REPORTER",
582
+ "text": "current authenticated user",
583
+ "description": "Returns the authenticated username or a stable user-like profile field when available.",
584
+ "arguments": {}
585
+ },
586
+ {
587
+ "opcode": "currentAuthProvider",
588
+ "blockType": "REPORTER",
589
+ "text": "current auth provider",
590
+ "description": "Returns the authentication provider name when available.",
591
+ "arguments": {}
592
+ },
593
+ {
594
+ "opcode": "currentAuthProfileJson",
595
+ "blockType": "REPORTER",
596
+ "text": "current auth profile JSON",
597
+ "description": "Returns the provider profile object as JSON when available.",
598
+ "arguments": {}
599
+ },
600
+ {
601
+ "opcode": "authProfileField",
602
+ "blockType": "REPORTER",
603
+ "text": "auth profile field [NAME]",
604
+ "description": "Returns a top-level or dotted field from the provider profile object.",
605
+ "arguments": { "NAME": {
606
+ "type": "STRING",
607
+ "defaultValue": "email"
608
+ } }
609
+ },
610
+ {
611
+ "opcode": "currentResponseStatus",
612
+ "blockType": "REPORTER",
613
+ "text": "current response status",
614
+ "description": "Returns the response status currently being built.",
615
+ "arguments": {}
616
+ },
617
+ {
618
+ "opcode": "setHttpStatus",
619
+ "blockType": "COMMAND",
620
+ "text": "set HTTP status [STATUS]",
621
+ "description": "Sets the current response status.",
622
+ "arguments": { "STATUS": {
623
+ "type": "NUMBER",
624
+ "defaultValue": 200
625
+ } }
626
+ },
627
+ {
628
+ "opcode": "setResponseHeader",
629
+ "blockType": "COMMAND",
630
+ "text": "set response header [NAME] to [VALUE]",
631
+ "description": "Sets a response header for the current request.",
632
+ "arguments": {
633
+ "NAME": {
634
+ "type": "STRING",
635
+ "defaultValue": "content-type"
636
+ },
637
+ "VALUE": {
638
+ "type": "STRING",
639
+ "defaultValue": "text/plain; charset=utf-8"
640
+ }
641
+ }
642
+ },
643
+ {
644
+ "opcode": "removeResponseHeader",
645
+ "blockType": "COMMAND",
646
+ "text": "remove response header [NAME]",
647
+ "description": "Removes a response header for the current request.",
648
+ "arguments": { "NAME": {
649
+ "type": "STRING",
650
+ "defaultValue": "content-type"
651
+ } }
652
+ },
653
+ {
654
+ "opcode": "responseHeader",
655
+ "blockType": "REPORTER",
656
+ "text": "response header [NAME]",
657
+ "description": "Returns the first configured response header value.",
658
+ "arguments": { "NAME": {
659
+ "type": "STRING",
660
+ "defaultValue": "content-type"
661
+ } }
662
+ },
663
+ {
664
+ "opcode": "setResponseBody",
665
+ "blockType": "COMMAND",
666
+ "text": "set response body [BODY]",
667
+ "description": "Sets the current response body without completing the response.",
668
+ "arguments": { "BODY": {
669
+ "type": "STRING",
670
+ "defaultValue": "Hello"
671
+ } }
672
+ },
673
+ {
674
+ "opcode": "sendResponse",
675
+ "blockType": "COMMAND",
676
+ "text": "send response [BODY]",
677
+ "description": "Sets the response body and completes the current request.",
678
+ "arguments": { "BODY": {
679
+ "type": "STRING",
680
+ "defaultValue": "Hello"
681
+ } }
682
+ },
683
+ {
684
+ "opcode": "respondWithText",
685
+ "blockType": "COMMAND",
686
+ "text": "respond with text [BODY]",
687
+ "description": "Responds with plain text.",
688
+ "arguments": { "BODY": {
689
+ "type": "STRING",
690
+ "defaultValue": "Hello"
691
+ } }
692
+ },
693
+ {
694
+ "opcode": "respondWithHtml",
695
+ "blockType": "COMMAND",
696
+ "text": "respond with HTML [BODY]",
697
+ "description": "Responds with HTML.",
698
+ "arguments": { "BODY": {
699
+ "type": "STRING",
700
+ "defaultValue": "<p>Hello</p>"
701
+ } }
702
+ },
703
+ {
704
+ "opcode": "respondWithJson",
705
+ "blockType": "COMMAND",
706
+ "text": "respond with JSON [BODY]",
707
+ "description": "Responds with JSON.",
708
+ "arguments": { "BODY": {
709
+ "type": "STRING",
710
+ "defaultValue": "{\"ok\":true}"
711
+ } }
712
+ },
713
+ {
714
+ "opcode": "respondWithNamedBody",
715
+ "blockType": "COMMAND",
716
+ "text": "respond with named [NAMESPACE] [NAME] kind [KIND] scope [SCOPE] target [TARGET_ID] as [REPRESENTATION] max bytes [MAX_BYTES]",
717
+ "description": "Completes the response with a named structured, document, binary, or asset snapshot resolved by the server.",
718
+ "arguments": {
719
+ "NAMESPACE": {
720
+ "type": "STRING",
721
+ "defaultValue": "asset"
722
+ },
723
+ "NAME": {
724
+ "type": "STRING",
725
+ "defaultValue": "avatar"
726
+ },
727
+ "KIND": {
728
+ "type": "STRING",
729
+ "defaultValue": "asset"
730
+ },
731
+ "SCOPE": {
732
+ "type": "STRING",
733
+ "defaultValue": "project"
734
+ },
735
+ "TARGET_ID": {
736
+ "type": "STRING",
737
+ "defaultValue": "Stage:1"
738
+ },
739
+ "REPRESENTATION": {
740
+ "type": "STRING",
741
+ "defaultValue": "raw"
742
+ },
743
+ "MAX_BYTES": {
744
+ "type": "NUMBER",
745
+ "defaultValue": 10485760
746
+ }
747
+ }
748
+ },
749
+ {
750
+ "opcode": "recordHttpLog",
751
+ "blockType": "COMMAND",
752
+ "text": "record HTTP log [ENTRY]",
753
+ "description": "Adds a structured HTTP log entry JSON string to the extension log buffer.",
754
+ "arguments": { "ENTRY": {
755
+ "type": "STRING",
756
+ "defaultValue": "{\"method\":\"GET\",\"path\":\"/\",\"status\":200}"
757
+ } }
758
+ },
759
+ {
760
+ "opcode": "clearHttpLogs",
761
+ "blockType": "COMMAND",
762
+ "text": "clear HTTP logs",
763
+ "description": "Clears the extension log buffer.",
764
+ "arguments": {}
765
+ },
766
+ {
767
+ "opcode": "httpLogViewerHtml",
768
+ "blockType": "REPORTER",
769
+ "text": "HTTP log viewer HTML",
770
+ "description": "Returns a self-contained virtual-scroll HTML log viewer for buffered HTTP logs.",
771
+ "arguments": {}
772
+ },
773
+ {
774
+ "opcode": "httpLogViewerHtmlFromJson",
775
+ "blockType": "REPORTER",
776
+ "text": "HTTP log viewer HTML from [LOGS]",
777
+ "description": "Returns a self-contained virtual-scroll HTML log viewer from a JSON array of log entries.",
778
+ "arguments": { "LOGS": {
779
+ "type": "STRING",
780
+ "defaultValue": "[{\"method\":\"GET\",\"path\":\"/\",\"status\":200}]"
781
+ } }
782
+ },
783
+ {
784
+ "opcode": "newMarkdownDocument",
785
+ "blockType": "REPORTER",
786
+ "text": "new markdown document",
787
+ "description": "Creates an empty Markdown builder handle.",
788
+ "arguments": {}
789
+ },
790
+ {
791
+ "opcode": "markdownHeading",
792
+ "blockType": "REPORTER",
793
+ "text": "markdown [DOC] with heading level [LEVEL] [TEXT]",
794
+ "description": "Appends a Markdown heading and returns the same builder handle.",
795
+ "arguments": {
796
+ "DOC": {
797
+ "type": "STRING",
798
+ "defaultValue": "md:1"
799
+ },
800
+ "LEVEL": {
801
+ "type": "NUMBER",
802
+ "defaultValue": 1
803
+ },
804
+ "TEXT": {
805
+ "type": "STRING",
806
+ "defaultValue": "Title"
807
+ }
808
+ }
809
+ },
810
+ {
811
+ "opcode": "markdownParagraph",
812
+ "blockType": "REPORTER",
813
+ "text": "markdown [DOC] with paragraph [TEXT]",
814
+ "description": "Appends a Markdown paragraph and returns the same builder handle.",
815
+ "arguments": {
816
+ "DOC": {
817
+ "type": "STRING",
818
+ "defaultValue": "md:1"
819
+ },
820
+ "TEXT": {
821
+ "type": "STRING",
822
+ "defaultValue": "Hello"
823
+ }
824
+ }
825
+ },
826
+ {
827
+ "opcode": "markdownBullet",
828
+ "blockType": "REPORTER",
829
+ "text": "markdown [DOC] with bullet [TEXT]",
830
+ "description": "Appends a Markdown bullet and returns the same builder handle.",
831
+ "arguments": {
832
+ "DOC": {
833
+ "type": "STRING",
834
+ "defaultValue": "md:1"
835
+ },
836
+ "TEXT": {
837
+ "type": "STRING",
838
+ "defaultValue": "Item"
839
+ }
840
+ }
841
+ },
842
+ {
843
+ "opcode": "markdownCodeBlock",
844
+ "blockType": "REPORTER",
845
+ "text": "markdown [DOC] with code [CODE] language [LANG]",
846
+ "description": "Appends a fenced Markdown code block and returns the same builder handle.",
847
+ "arguments": {
848
+ "DOC": {
849
+ "type": "STRING",
850
+ "defaultValue": "md:1"
851
+ },
852
+ "CODE": {
853
+ "type": "STRING",
854
+ "defaultValue": "console.log('hello')"
855
+ },
856
+ "LANG": {
857
+ "type": "STRING",
858
+ "defaultValue": "js"
859
+ }
860
+ }
861
+ },
862
+ {
863
+ "opcode": "renderMarkdown",
864
+ "blockType": "REPORTER",
865
+ "text": "render markdown [DOC]",
866
+ "description": "Renders a Markdown builder handle to Markdown text.",
867
+ "arguments": { "DOC": {
868
+ "type": "STRING",
869
+ "defaultValue": "md:1"
870
+ } }
871
+ },
872
+ {
873
+ "opcode": "newHtmlElement",
874
+ "blockType": "REPORTER",
875
+ "text": "new HTML element [TAG]",
876
+ "description": "Creates an HTML element builder handle.",
877
+ "arguments": { "TAG": {
878
+ "type": "STRING",
879
+ "defaultValue": "div"
880
+ } }
881
+ },
882
+ {
883
+ "opcode": "htmlText",
884
+ "blockType": "REPORTER",
885
+ "text": "HTML text [TEXT]",
886
+ "description": "Creates an escaped HTML text node handle.",
887
+ "arguments": { "TEXT": {
888
+ "type": "STRING",
889
+ "defaultValue": "Hello"
890
+ } }
891
+ },
892
+ {
893
+ "opcode": "htmlSetAttribute",
894
+ "blockType": "REPORTER",
895
+ "text": "HTML [NODE] with attribute [NAME] [VALUE]",
896
+ "description": "Sets an escaped attribute on an HTML element and returns the same handle.",
897
+ "arguments": {
898
+ "NODE": {
899
+ "type": "STRING",
900
+ "defaultValue": "html:1"
901
+ },
902
+ "NAME": {
903
+ "type": "STRING",
904
+ "defaultValue": "class"
905
+ },
906
+ "VALUE": {
907
+ "type": "STRING",
908
+ "defaultValue": "content"
909
+ }
910
+ }
911
+ },
912
+ {
913
+ "opcode": "htmlAppendChild",
914
+ "blockType": "REPORTER",
915
+ "text": "HTML [PARENT] with child [CHILD]",
916
+ "description": "Appends a child node to an HTML element and returns the parent handle.",
917
+ "arguments": {
918
+ "PARENT": {
919
+ "type": "STRING",
920
+ "defaultValue": "html:1"
921
+ },
922
+ "CHILD": {
923
+ "type": "STRING",
924
+ "defaultValue": "html:2"
925
+ }
926
+ }
927
+ },
928
+ {
929
+ "opcode": "renderHtml",
930
+ "blockType": "REPORTER",
931
+ "text": "render HTML [NODE]",
932
+ "description": "Renders an HTML node handle to an HTML fragment.",
933
+ "arguments": { "NODE": {
934
+ "type": "STRING",
935
+ "defaultValue": "html:1"
936
+ } }
937
+ },
938
+ {
939
+ "opcode": "renderHtmlDocument",
940
+ "blockType": "REPORTER",
941
+ "text": "render HTML document title [TITLE] body [BODY]",
942
+ "description": "Renders a full HTML document from an HTML body node handle.",
943
+ "arguments": {
944
+ "TITLE": {
945
+ "type": "STRING",
946
+ "defaultValue": "Page"
947
+ },
948
+ "BODY": {
949
+ "type": "STRING",
950
+ "defaultValue": "html:1"
951
+ }
952
+ }
953
+ }
954
+ ]
955
+ };
956
+ //#endregion
957
+ //#region src/protocol.ts
958
+ function normalizeHeaderName(name) {
959
+ return name.trim().toLowerCase();
960
+ }
961
+ function isValidHttpStatus(status) {
962
+ return Number.isInteger(status) && status >= 100 && status <= 599;
963
+ }
964
+ function isForbiddenResponseHeader(name) {
965
+ return [
966
+ "connection",
967
+ "content-length",
968
+ "transfer-encoding",
969
+ "upgrade"
970
+ ].includes(normalizeHeaderName(name));
971
+ }
972
+ function validateHeaderName(name) {
973
+ return /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name);
974
+ }
975
+ function validateHeaderValue(value) {
976
+ return !/[\r\n]/.test(value);
977
+ }
978
+ function firstValue(values) {
979
+ return values?.[0] ?? "";
980
+ }
981
+ //#endregion
982
+ //#region src/extension.ts
983
+ var blockDefinitions = block_definitions_default.blocks;
984
+ var DEFAULT_SERVER_URL = "ws://127.0.0.1:8787/ws";
985
+ var ALLOWED_HTML_TAGS = /* @__PURE__ */ new Set([
986
+ "a",
987
+ "article",
988
+ "body",
989
+ "button",
990
+ "code",
991
+ "dd",
992
+ "div",
993
+ "dl",
994
+ "dt",
995
+ "em",
996
+ "footer",
997
+ "form",
998
+ "h1",
999
+ "h2",
1000
+ "h3",
1001
+ "h4",
1002
+ "h5",
1003
+ "h6",
1004
+ "header",
1005
+ "img",
1006
+ "input",
1007
+ "label",
1008
+ "li",
1009
+ "main",
1010
+ "ol",
1011
+ "p",
1012
+ "pre",
1013
+ "section",
1014
+ "span",
1015
+ "strong",
1016
+ "table",
1017
+ "tbody",
1018
+ "td",
1019
+ "textarea",
1020
+ "th",
1021
+ "thead",
1022
+ "tr",
1023
+ "ul"
1024
+ ]);
1025
+ var VOID_HTML_TAGS = /* @__PURE__ */ new Set(["img", "input"]);
1026
+ var VALID_ATTRIBUTE = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
1027
+ var VALID_MARKDOWN_LANGUAGE = /^[a-zA-Z0-9_+.-]*$/;
1028
+ var HTTP_REQUEST_HAT_OPCODE = `${extensionConfig.id}_whenHttpRequestReceived`;
1029
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set([
1030
+ "action",
1031
+ "cite",
1032
+ "formaction",
1033
+ "href",
1034
+ "poster",
1035
+ "src",
1036
+ "xlink:href"
1037
+ ]);
1038
+ var URL_LIST_ATTRIBUTES = /* @__PURE__ */ new Set(["srcset"]);
1039
+ var SAFE_URL_SCHEMES = /* @__PURE__ */ new Set([
1040
+ "http",
1041
+ "https",
1042
+ "mailto",
1043
+ "tel"
1044
+ ]);
1045
+ var NAMED_BODY_KINDS = /* @__PURE__ */ new Set([
1046
+ "structured",
1047
+ "document",
1048
+ "binary",
1049
+ "asset"
1050
+ ]);
1051
+ var NAMED_BODY_SCOPES = /* @__PURE__ */ new Set(["target", "project"]);
1052
+ var NAMED_BODY_REPRESENTATIONS = /* @__PURE__ */ new Set([
1053
+ "json",
1054
+ "yaml",
1055
+ "html",
1056
+ "markdown",
1057
+ "raw"
1058
+ ]);
1059
+ var TurboWarpHttpServerExtension = class {
1060
+ constructor() {
1061
+ this.fixedInputs = fixedInputRegistration(typeof Scratch === "undefined" ? void 0 : Scratch);
1062
+ this.serverUrl = DEFAULT_SERVER_URL;
1063
+ this.socket = null;
1064
+ this.lastReceivedMessage = "";
1065
+ this.nextHandleId = 1;
1066
+ this.httpLogs = [];
1067
+ this.markdownBuilders = /* @__PURE__ */ new Map();
1068
+ this.htmlNodes = /* @__PURE__ */ new Map();
1069
+ this.requestContexts = /* @__PURE__ */ new Map();
1070
+ this.currentRequestContextId = "";
1071
+ }
1072
+ dispose() {
1073
+ this.fixedInputs.dispose();
1074
+ }
1075
+ getInfo() {
1076
+ this.fixedInputs.ensure(blockDefinitions.map((block) => `${extensionConfig.id}_${block.opcode}`));
1077
+ return {
1078
+ id: extensionConfig.id,
1079
+ name: Scratch.translate(block_definitions_default.extensionName),
1080
+ docsURI: extensionConfig.docsURI,
1081
+ blockIconURI: extensionConfig.blockIconURI,
1082
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
1083
+ };
1084
+ }
1085
+ setServerUrl(args) {
1086
+ this.serverUrl = Scratch.Cast.toString(args.URL).trim() || DEFAULT_SERVER_URL;
1087
+ }
1088
+ connect() {
1089
+ if (this.isConnected()) return;
1090
+ this.socket?.close();
1091
+ const socket = new WebSocket(this.serverUrl);
1092
+ this.socket = socket;
1093
+ socket.addEventListener("message", (event) => {
1094
+ this.lastReceivedMessage = this.stringifyMessage(event.data);
1095
+ this.recordLogMessage(this.lastReceivedMessage);
1096
+ this.receiveBridgeMessage(this.lastReceivedMessage);
1097
+ });
1098
+ socket.addEventListener("close", () => {
1099
+ if (this.socket === socket) this.socket = null;
1100
+ });
1101
+ socket.addEventListener("error", () => {
1102
+ if (this.socket === socket) this.socket = null;
1103
+ });
1104
+ }
1105
+ disconnect() {
1106
+ this.socket?.close();
1107
+ this.socket = null;
1108
+ }
1109
+ isConnected() {
1110
+ return this.socket?.readyState === WebSocket.OPEN;
1111
+ }
1112
+ sendText(args) {
1113
+ if (!this.isConnected() || this.socket === null) return;
1114
+ this.socket.send(Scratch.Cast.toString(args.MESSAGE));
1115
+ }
1116
+ lastMessage() {
1117
+ return this.lastReceivedMessage;
1118
+ }
1119
+ whenHttpRequestReceived() {
1120
+ return false;
1121
+ }
1122
+ useHttpRequest(args) {
1123
+ const id = Scratch.Cast.toString(args.ID);
1124
+ if (this.requestContexts.has(id)) this.currentRequestContextId = id;
1125
+ }
1126
+ currentRequestId() {
1127
+ return this.currentContext()?.request.id ?? "";
1128
+ }
1129
+ currentHttpMethod() {
1130
+ return this.currentContext()?.request.method ?? "";
1131
+ }
1132
+ currentRequestPath() {
1133
+ return this.currentContext()?.request.path ?? "";
1134
+ }
1135
+ currentRequestUrl() {
1136
+ return this.currentContext()?.request.url ?? "";
1137
+ }
1138
+ requestHeader(args) {
1139
+ const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
1140
+ return firstValue(this.currentContext()?.request.headers[name]);
1141
+ }
1142
+ queryParameter(args) {
1143
+ return firstValue(this.currentContext()?.request.query[Scratch.Cast.toString(args.NAME)]);
1144
+ }
1145
+ pathParameter(args) {
1146
+ return this.currentContext()?.request.pathParams[Scratch.Cast.toString(args.NAME)] ?? "";
1147
+ }
1148
+ currentRequestBody() {
1149
+ const body = this.currentContext()?.request.body;
1150
+ return body?.kind === "text" ? body.text : "";
1151
+ }
1152
+ currentRequestContentType() {
1153
+ return this.requestHeader({ NAME: "content-type" });
1154
+ }
1155
+ currentRequestClientAddress() {
1156
+ return this.currentContext()?.request.clientAddress ?? "";
1157
+ }
1158
+ setHandlerVariable(args) {
1159
+ const context = this.mutableCurrentContext();
1160
+ if (!context) return;
1161
+ context.handlerVariables.set(Scratch.Cast.toString(args.NAME), Scratch.Cast.toString(args.VALUE));
1162
+ }
1163
+ changeHandlerVariable(args) {
1164
+ const context = this.mutableCurrentContext();
1165
+ if (!context) return;
1166
+ const name = Scratch.Cast.toString(args.NAME);
1167
+ const current = Scratch.Cast.toNumber(context.handlerVariables.get(name) ?? "");
1168
+ context.handlerVariables.set(name, current + Scratch.Cast.toNumber(args.AMOUNT));
1169
+ }
1170
+ handlerVariable(args) {
1171
+ return this.currentContext()?.handlerVariables.get(Scratch.Cast.toString(args.NAME)) ?? "";
1172
+ }
1173
+ handlerVariableExists(args) {
1174
+ return this.currentContext()?.handlerVariables.has(Scratch.Cast.toString(args.NAME)) ?? false;
1175
+ }
1176
+ deleteHandlerVariable(args) {
1177
+ this.mutableCurrentContext()?.handlerVariables.delete(Scratch.Cast.toString(args.NAME));
1178
+ }
1179
+ clearHandlerVariables() {
1180
+ this.mutableCurrentContext()?.handlerVariables.clear();
1181
+ }
1182
+ listHandlerVariables() {
1183
+ return Array.from(this.currentContext()?.handlerVariables.keys() ?? []).join(",");
1184
+ }
1185
+ currentAuthType() {
1186
+ return this.currentContext()?.request.auth?.type ?? "";
1187
+ }
1188
+ currentAuthenticatedUser() {
1189
+ const auth = this.currentContext()?.request.auth;
1190
+ if (!auth) return "";
1191
+ if (typeof auth.username === "string") return auth.username;
1192
+ const profile = auth.profile;
1193
+ return firstString(profile?.preferred_username, profile?.email, profile?.name, profile?.sub);
1194
+ }
1195
+ currentAuthProvider() {
1196
+ return this.currentContext()?.request.auth?.provider ?? "";
1197
+ }
1198
+ currentAuthProfileJson() {
1199
+ const profile = this.currentContext()?.request.auth?.profile;
1200
+ return profile ? JSON.stringify(profile) : "";
1201
+ }
1202
+ authProfileField(args) {
1203
+ const profile = this.currentContext()?.request.auth?.profile;
1204
+ return stringifyProfileValue(readProfileField(profile, Scratch.Cast.toString(args.NAME)));
1205
+ }
1206
+ currentResponseStatus() {
1207
+ return this.currentContext()?.response.status ?? 200;
1208
+ }
1209
+ setHttpStatus(args) {
1210
+ const context = this.mutableCurrentContext();
1211
+ if (!context) return;
1212
+ const status = Math.trunc(Scratch.Cast.toNumber(args.STATUS));
1213
+ if (isValidHttpStatus(status)) context.response.status = status;
1214
+ }
1215
+ setResponseHeader(args) {
1216
+ const context = this.mutableCurrentContext();
1217
+ if (!context) return;
1218
+ const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
1219
+ const value = Scratch.Cast.toString(args.VALUE);
1220
+ if (validateHeaderName(name) && validateHeaderValue(value) && !isForbiddenResponseHeader(name)) context.response.headers[name] = [value];
1221
+ }
1222
+ removeResponseHeader(args) {
1223
+ const context = this.mutableCurrentContext();
1224
+ if (!context) return;
1225
+ delete context.response.headers[normalizeHeaderName(Scratch.Cast.toString(args.NAME))];
1226
+ }
1227
+ responseHeader(args) {
1228
+ const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
1229
+ return firstValue(this.currentContext()?.response.headers[name]);
1230
+ }
1231
+ setResponseBody(args) {
1232
+ const context = this.mutableCurrentContext();
1233
+ if (!context) return;
1234
+ context.response.body = {
1235
+ kind: "text",
1236
+ text: Scratch.Cast.toString(args.BODY)
1237
+ };
1238
+ }
1239
+ sendResponse(args) {
1240
+ const context = this.mutableCurrentContext();
1241
+ if (!context) return;
1242
+ context.response.body = {
1243
+ kind: "text",
1244
+ text: Scratch.Cast.toString(args.BODY)
1245
+ };
1246
+ this.completeResponse(context);
1247
+ }
1248
+ respondWithText(args) {
1249
+ this.setResponseHeader({
1250
+ NAME: "content-type",
1251
+ VALUE: "text/plain; charset=utf-8"
1252
+ });
1253
+ this.sendResponse({ BODY: args.BODY });
1254
+ }
1255
+ respondWithHtml(args) {
1256
+ this.setResponseHeader({
1257
+ NAME: "content-type",
1258
+ VALUE: "text/html; charset=utf-8"
1259
+ });
1260
+ this.sendResponse({ BODY: args.BODY });
1261
+ }
1262
+ respondWithJson(args) {
1263
+ this.setResponseHeader({
1264
+ NAME: "content-type",
1265
+ VALUE: "application/json; charset=utf-8"
1266
+ });
1267
+ this.sendResponse({ BODY: args.BODY });
1268
+ }
1269
+ respondWithNamedBody(args) {
1270
+ const context = this.mutableCurrentContext();
1271
+ if (!context) return;
1272
+ const kind = Scratch.Cast.toString(args.KIND).toLowerCase();
1273
+ const scope = Scratch.Cast.toString(args.SCOPE).toLowerCase();
1274
+ const representation = Scratch.Cast.toString(args.REPRESENTATION).toLowerCase();
1275
+ const maxBytes = Math.trunc(Scratch.Cast.toNumber(args.MAX_BYTES));
1276
+ if (!NAMED_BODY_KINDS.has(kind) || !NAMED_BODY_SCOPES.has(scope) || !NAMED_BODY_REPRESENTATIONS.has(representation) || !Number.isSafeInteger(maxBytes) || maxBytes < 1) {
1277
+ context.response.body = {
1278
+ kind: "unsupported",
1279
+ reason: "invalid_named_body"
1280
+ };
1281
+ this.completeResponse(context);
1282
+ return;
1283
+ }
1284
+ context.response.body = {
1285
+ kind: "named",
1286
+ reference: {
1287
+ namespace: Scratch.Cast.toString(args.NAMESPACE),
1288
+ name: Scratch.Cast.toString(args.NAME),
1289
+ kind,
1290
+ scope
1291
+ },
1292
+ representation,
1293
+ ...scope === "target" ? { targetId: Scratch.Cast.toString(args.TARGET_ID) } : {},
1294
+ maxBytes
1295
+ };
1296
+ this.completeResponse(context);
1297
+ }
1298
+ receiveBridgeRequestForTest(request) {
1299
+ this.acceptBridgeRequest(request);
1300
+ }
1301
+ recordHttpLog(args) {
1302
+ this.httpLogs.push(this.parseLogEntry(Scratch.Cast.toString(args.ENTRY)));
1303
+ }
1304
+ clearHttpLogs() {
1305
+ this.httpLogs.length = 0;
1306
+ }
1307
+ httpLogViewerHtml() {
1308
+ return this.renderLogViewer(this.httpLogs);
1309
+ }
1310
+ httpLogViewerHtmlFromJson(args) {
1311
+ return this.renderLogViewer(this.parseLogArray(Scratch.Cast.toString(args.LOGS)));
1312
+ }
1313
+ newMarkdownDocument() {
1314
+ const handle = this.nextHandle("md");
1315
+ this.markdownBuilders.set(handle, []);
1316
+ return handle;
1317
+ }
1318
+ markdownHeading(args) {
1319
+ const handle = this.ensureMarkdownHandle(args.DOC);
1320
+ const level = Math.min(6, Math.max(1, Math.trunc(Scratch.Cast.toNumber(args.LEVEL))));
1321
+ this.markdownBuilders.get(handle)?.push(`${"#".repeat(level)} ${escapeMarkdownLine(Scratch.Cast.toString(args.TEXT))}`);
1322
+ return handle;
1323
+ }
1324
+ markdownParagraph(args) {
1325
+ const handle = this.ensureMarkdownHandle(args.DOC);
1326
+ this.markdownBuilders.get(handle)?.push(escapeMarkdownParagraph(Scratch.Cast.toString(args.TEXT)));
1327
+ return handle;
1328
+ }
1329
+ markdownBullet(args) {
1330
+ const handle = this.ensureMarkdownHandle(args.DOC);
1331
+ this.markdownBuilders.get(handle)?.push(`- ${escapeMarkdownLine(Scratch.Cast.toString(args.TEXT))}`);
1332
+ return handle;
1333
+ }
1334
+ markdownCodeBlock(args) {
1335
+ const handle = this.ensureMarkdownHandle(args.DOC);
1336
+ const language = Scratch.Cast.toString(args.LANG).trim();
1337
+ const safeLanguage = VALID_MARKDOWN_LANGUAGE.test(language) ? language : "";
1338
+ const code = Scratch.Cast.toString(args.CODE).replace(/```/g, "`\\`\\`");
1339
+ this.markdownBuilders.get(handle)?.push(`\`\`\`${safeLanguage}\n${code}\n\`\`\``);
1340
+ return handle;
1341
+ }
1342
+ renderMarkdown(args) {
1343
+ return this.markdownBuilders.get(Scratch.Cast.toString(args.DOC))?.join("\n\n") ?? "";
1344
+ }
1345
+ newHtmlElement(args) {
1346
+ const tag = normalizeHtmlTag(Scratch.Cast.toString(args.TAG));
1347
+ const handle = this.nextHandle("html");
1348
+ this.htmlNodes.set(handle, {
1349
+ kind: "element",
1350
+ tag,
1351
+ attributes: {},
1352
+ children: []
1353
+ });
1354
+ return handle;
1355
+ }
1356
+ htmlText(args) {
1357
+ const handle = this.nextHandle("html");
1358
+ this.htmlNodes.set(handle, {
1359
+ kind: "text",
1360
+ text: Scratch.Cast.toString(args.TEXT)
1361
+ });
1362
+ return handle;
1363
+ }
1364
+ htmlSetAttribute(args) {
1365
+ const handle = this.ensureHtmlElementHandle(args.NODE);
1366
+ const node = this.htmlNodes.get(handle);
1367
+ const name = Scratch.Cast.toString(args.NAME).trim();
1368
+ const normalizedName = name.toLowerCase();
1369
+ const value = Scratch.Cast.toString(args.VALUE);
1370
+ if (node?.kind === "element" && VALID_ATTRIBUTE.test(name) && !normalizedName.startsWith("on") && isSafeAttributeValue(normalizedName, value)) node.attributes[name] = value;
1371
+ return handle;
1372
+ }
1373
+ htmlAppendChild(args) {
1374
+ const parentHandle = this.ensureHtmlElementHandle(args.PARENT);
1375
+ const childHandle = Scratch.Cast.toString(args.CHILD);
1376
+ const parent = this.htmlNodes.get(parentHandle);
1377
+ if (parent?.kind === "element" && this.htmlNodes.has(childHandle) && parentHandle !== childHandle && !this.hasHtmlDescendant(childHandle, parentHandle, /* @__PURE__ */ new Set())) parent.children.push(childHandle);
1378
+ return parentHandle;
1379
+ }
1380
+ renderHtml(args) {
1381
+ return this.renderHtmlNode(Scratch.Cast.toString(args.NODE), /* @__PURE__ */ new Set());
1382
+ }
1383
+ renderHtmlDocument(args) {
1384
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(Scratch.Cast.toString(args.TITLE))}</title></head><body>${this.renderHtmlNode(Scratch.Cast.toString(args.BODY), /* @__PURE__ */ new Set())}</body></html>`;
1385
+ }
1386
+ stringifyMessage(message) {
1387
+ if (typeof message === "string") return message;
1388
+ if (message instanceof ArrayBuffer) return new TextDecoder().decode(message);
1389
+ return String(message);
1390
+ }
1391
+ receiveBridgeMessage(message) {
1392
+ try {
1393
+ const parsed = JSON.parse(message);
1394
+ if (parsed.type === "request" && typeof parsed.id === "string") this.acceptBridgeRequest(parsed);
1395
+ } catch {
1396
+ return;
1397
+ }
1398
+ }
1399
+ acceptBridgeRequest(request) {
1400
+ const normalizedRequest = {
1401
+ ...request,
1402
+ headers: normalizeHeaderRecord(request.headers),
1403
+ query: normalizeValueRecord(request.query),
1404
+ pathParams: normalizePathParams(request.pathParams)
1405
+ };
1406
+ const auth = normalizeAuthContext(request.auth);
1407
+ if (auth) normalizedRequest.auth = auth;
1408
+ this.requestContexts.set(request.id, {
1409
+ request: normalizedRequest,
1410
+ response: {
1411
+ status: 200,
1412
+ headers: {},
1413
+ body: { kind: "empty" },
1414
+ completed: false
1415
+ },
1416
+ handlerVariables: /* @__PURE__ */ new Map()
1417
+ });
1418
+ this.currentRequestContextId = request.id;
1419
+ this.startRequestHat();
1420
+ }
1421
+ currentContext() {
1422
+ return this.requestContexts.get(this.currentRequestContextId);
1423
+ }
1424
+ mutableCurrentContext() {
1425
+ const context = this.currentContext();
1426
+ return context && !context.response.completed ? context : void 0;
1427
+ }
1428
+ completeResponse(context) {
1429
+ if (context.response.completed) return;
1430
+ context.response.completed = true;
1431
+ const message = {
1432
+ type: "response",
1433
+ id: context.request.id,
1434
+ status: context.response.status,
1435
+ headers: context.response.headers,
1436
+ body: context.response.body
1437
+ };
1438
+ this.socket?.send(JSON.stringify(message));
1439
+ this.requestContexts.delete(context.request.id);
1440
+ if (this.currentRequestContextId === context.request.id) this.currentRequestContextId = "";
1441
+ }
1442
+ recordLogMessage(message) {
1443
+ const parsed = this.parseLogEntry(message);
1444
+ if (isLogLike(parsed)) this.httpLogs.push(parsed);
1445
+ }
1446
+ startRequestHat() {
1447
+ Scratch.vm?.runtime?.startHats?.(HTTP_REQUEST_HAT_OPCODE);
1448
+ }
1449
+ parseLogEntry(value) {
1450
+ try {
1451
+ return JSON.parse(value);
1452
+ } catch {
1453
+ return { message: value };
1454
+ }
1455
+ }
1456
+ parseLogArray(value) {
1457
+ const parsed = this.parseLogEntry(value);
1458
+ return Array.isArray(parsed) ? parsed : [parsed];
1459
+ }
1460
+ renderLogViewer(logs) {
1461
+ return `<!doctype html><html><head><meta charset="utf-8"><title>HTTP Logs</title><style>
1462
+ body{margin:0;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;background:#0f172a;color:#e5e7eb}
1463
+ header{height:44px;display:flex;align-items:center;padding:0 16px;background:#111827;border-bottom:1px solid #334155}
1464
+ #viewport{height:calc(100vh - 45px);overflow:auto;position:relative}
1465
+ #spacer{width:1px}.row{position:absolute;left:0;right:0;height:32px;display:grid;grid-template-columns:72px 84px 1fr;gap:10px;align-items:center;padding:0 12px;border-bottom:1px solid #1f2937;box-sizing:border-box;white-space:nowrap}
1466
+ .status{color:#93c5fd}.method{color:#86efac}.path{overflow:hidden;text-overflow:ellipsis}
1467
+ </style></head><body><header>HTTP logs <span id="count"></span></header><div id="viewport"><div id="spacer"></div><div id="rows"></div></div><script>
1468
+ const logs=${JSON.stringify(logs).replace(/</g, "\\u003c")};const rowHeight=32;const viewport=document.getElementById('viewport');const spacer=document.getElementById('spacer');const rows=document.getElementById('rows');document.getElementById('count').textContent='('+logs.length+')';spacer.style.height=(logs.length*rowHeight)+'px';
1469
+ function text(v){return v==null?'':String(v)}function render(){const top=viewport.scrollTop;const first=Math.max(0,Math.floor(top/rowHeight)-8);const visible=Math.ceil(viewport.clientHeight/rowHeight)+16;const last=Math.min(logs.length,first+visible);let html='';for(let i=first;i<last;i++){const log=logs[i]||{};const method=text(log.method||log.event||'LOG');const status=text(log.status||'');const path=text(log.path||log.resourceName||log.message||JSON.stringify(log));html+='<div class="row" style="transform:translateY('+(i*rowHeight)+'px)"><span class="method">'+escapeHtml(method)+'</span><span class="status">'+escapeHtml(status)+'</span><span class="path">'+escapeHtml(path)+'</span></div>'}rows.innerHTML=html}
1470
+ function escapeHtml(value){return value.replace(/[&<>"']/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]))}viewport.addEventListener('scroll',render);render();
1471
+ <\/script></body></html>`;
1472
+ }
1473
+ ensureMarkdownHandle(value) {
1474
+ const handle = Scratch.Cast.toString(value);
1475
+ if (this.markdownBuilders.has(handle)) return handle;
1476
+ return this.newMarkdownDocument();
1477
+ }
1478
+ ensureHtmlElementHandle(value) {
1479
+ const handle = Scratch.Cast.toString(value);
1480
+ if (this.htmlNodes.get(handle)?.kind === "element") return handle;
1481
+ return this.newHtmlElement({ TAG: "div" });
1482
+ }
1483
+ renderHtmlNode(handle, visiting) {
1484
+ if (visiting.has(handle)) return "";
1485
+ const node = this.htmlNodes.get(handle);
1486
+ if (!node) return "";
1487
+ if (node.kind === "text") return escapeHtml(node.text);
1488
+ visiting.add(handle);
1489
+ const attributes = Object.entries(node.attributes).map(([name, value]) => ` ${name}="${escapeHtml(value)}"`).join("");
1490
+ if (VOID_HTML_TAGS.has(node.tag)) {
1491
+ visiting.delete(handle);
1492
+ return `<${node.tag}${attributes}>`;
1493
+ }
1494
+ const children = node.children.map((child) => this.renderHtmlNode(child, visiting)).join("");
1495
+ visiting.delete(handle);
1496
+ return `<${node.tag}${attributes}>${children}</${node.tag}>`;
1497
+ }
1498
+ hasHtmlDescendant(handle, targetHandle, visited) {
1499
+ if (visited.has(handle)) return false;
1500
+ visited.add(handle);
1501
+ const node = this.htmlNodes.get(handle);
1502
+ if (node?.kind !== "element") return false;
1503
+ return node.children.some((child) => child === targetHandle || this.hasHtmlDescendant(child, targetHandle, visited));
1504
+ }
1505
+ nextHandle(prefix) {
1506
+ const handle = `${prefix}:${this.nextHandleId}`;
1507
+ this.nextHandleId += 1;
1508
+ return handle;
1509
+ }
1510
+ toScratchBlock(block) {
1511
+ return {
1512
+ opcode: block.opcode,
1513
+ blockType: Scratch.BlockType[block.blockType],
1514
+ text: Scratch.translate(block.text),
1515
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
1516
+ type: Scratch.ArgumentType[argument.type],
1517
+ defaultValue: argument.defaultValue
1518
+ }]))
1519
+ };
1520
+ }
1521
+ };
1522
+ function isLogLike(value) {
1523
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1524
+ }
1525
+ function normalizeHeaderRecord(headers) {
1526
+ const normalized = {};
1527
+ for (const [name, values] of Object.entries(headers ?? {})) normalized[normalizeHeaderName(name)] = values.map((value) => String(value));
1528
+ return normalized;
1529
+ }
1530
+ function normalizeValueRecord(values) {
1531
+ const normalized = {};
1532
+ for (const [name, items] of Object.entries(values ?? {})) normalized[name] = items.map((value) => String(value));
1533
+ return normalized;
1534
+ }
1535
+ function normalizePathParams(values) {
1536
+ const normalized = {};
1537
+ for (const [name, value] of Object.entries(values ?? {})) normalized[name] = String(value);
1538
+ return normalized;
1539
+ }
1540
+ function normalizeAuthContext(auth) {
1541
+ if (typeof auth !== "object" || auth === null || Array.isArray(auth)) return void 0;
1542
+ const type = typeof auth.type === "string" ? auth.type : "";
1543
+ if (!type) return void 0;
1544
+ const normalized = { type };
1545
+ if (typeof auth.username === "string") normalized.username = auth.username;
1546
+ if (typeof auth.provider === "string") normalized.provider = auth.provider;
1547
+ if (isPlainRecord(auth.profile)) normalized.profile = normalizeProfile(auth.profile);
1548
+ return normalized;
1549
+ }
1550
+ function normalizeProfile(profile) {
1551
+ return JSON.parse(JSON.stringify(profile));
1552
+ }
1553
+ function readProfileField(profile, path) {
1554
+ if (!profile) return void 0;
1555
+ const segments = path.split(".").map((segment) => segment.trim()).filter(Boolean);
1556
+ if (segments.length === 0) return void 0;
1557
+ let value = profile;
1558
+ for (const segment of segments) {
1559
+ if (!isPlainRecord(value)) return void 0;
1560
+ value = value[segment];
1561
+ }
1562
+ return value;
1563
+ }
1564
+ function stringifyProfileValue(value) {
1565
+ if (value === void 0 || value === null) return "";
1566
+ if (typeof value === "string") return value;
1567
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1568
+ return JSON.stringify(value);
1569
+ }
1570
+ function firstString(...values) {
1571
+ return values.find((value) => typeof value === "string") ?? "";
1572
+ }
1573
+ function isPlainRecord(value) {
1574
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1575
+ }
1576
+ function escapeMarkdownLine(value) {
1577
+ return value.replace(/\\/g, "\\\\").replace(/([`*_#[\]])/g, "\\$1").replace(/\r?\n/g, " ");
1578
+ }
1579
+ function escapeMarkdownParagraph(value) {
1580
+ return value.replace(/\\/g, "\\\\").replace(/([`*_#[\]])/g, "\\$1");
1581
+ }
1582
+ function normalizeHtmlTag(value) {
1583
+ const tag = value.trim().toLowerCase();
1584
+ return ALLOWED_HTML_TAGS.has(tag) ? tag : "div";
1585
+ }
1586
+ function isSafeAttributeValue(name, value) {
1587
+ if (URL_LIST_ATTRIBUTES.has(name)) return isSafeUrlList(value);
1588
+ if (URL_ATTRIBUTES.has(name)) return isSafeUrl(value);
1589
+ return true;
1590
+ }
1591
+ function isSafeUrlList(value) {
1592
+ return value.split(",").map((candidate) => candidate.trim().split(/\s+/, 1)[0] ?? "").every((url) => isSafeUrl(url));
1593
+ }
1594
+ function isSafeUrl(value) {
1595
+ const trimmed = value.trim();
1596
+ if (!trimmed) return true;
1597
+ const normalized = stripUrlSchemeSeparators(trimmed);
1598
+ const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(normalized)?.[1]?.toLowerCase();
1599
+ return scheme === void 0 || SAFE_URL_SCHEMES.has(scheme);
1600
+ }
1601
+ function stripUrlSchemeSeparators(value) {
1602
+ let result = "";
1603
+ for (const character of value) {
1604
+ const code = character.charCodeAt(0);
1605
+ if (code <= 31 || code === 127 || /\s/.test(character)) continue;
1606
+ result += character;
1607
+ }
1608
+ return result;
1609
+ }
1610
+ function escapeHtml(value) {
1611
+ return value.replace(/[&<>"']/g, (character) => {
1612
+ if (character === "&") return "&amp;";
1613
+ if (character === "<") return "&lt;";
1614
+ if (character === ">") return "&gt;";
1615
+ if (character === "\"") return "&quot;";
1616
+ return "&#39;";
1617
+ });
1618
+ }
1619
+ //#endregion
1620
+ //#region src/index.ts
1621
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1622
+ Scratch.extensions.register(new TurboWarpHttpServerExtension());
1623
+ //#endregion
1624
1624
 
1625
1625
  })(Scratch);