@kubohiroya/turbowarp-named-functions 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +373 -0
- package/README.ja.md +209 -0
- package/README.md +258 -0
- package/dist/composition.js +398 -0
- package/dist/extension-manifest.json +133 -0
- package/dist/turbowarp-named-functions.js +701 -0
- package/dist/types/composition.d.ts +49 -0
- package/dist/types/config.d.ts +11 -0
- package/dist/types/extension-manifest.d.ts +30 -0
- package/dist/types/extension.d.ts +29 -0
- package/dist/types/function-dispatcher.d.ts +60 -0
- package/dist/types/function-registry.d.ts +28 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/runtime-types.d.ts +37 -0
- package/dist/types/schema-validator.d.ts +9 -0
- package/package.json +75 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/block-definitions.json +168 -0
- package/src/composition.ts +220 -0
- package/src/config.ts +12 -0
- package/src/extension-manifest.ts +149 -0
- package/src/extension.ts +200 -0
- package/src/function-dispatcher.ts +208 -0
- package/src/function-registry.ts +124 -0
- package/src/globals.d.ts +26 -0
- package/src/index.ts +14 -0
- package/src/runtime-types.ts +42 -0
- package/src/schema-validator.ts +101 -0
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
// Name: TurboWarp-Named-Functions
|
|
2
|
+
// ID: kubohiroyanamedfunctions
|
|
3
|
+
// Description: Named JSON functions that scripts can call by name, synchronously or asynchronously.
|
|
4
|
+
// By: Hiroya Kubo
|
|
5
|
+
// License: MPL-2.0
|
|
6
|
+
|
|
7
|
+
(function (Scratch) {
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
//#region src/config.ts
|
|
11
|
+
var extensionConfig = {
|
|
12
|
+
id: "kubohiroyanamedfunctions",
|
|
13
|
+
slug: "turbowarp-named-functions",
|
|
14
|
+
name: "TurboWarp-Named-Functions",
|
|
15
|
+
description: "Named JSON functions that scripts can call by name, synchronously or asynchronously.",
|
|
16
|
+
author: "Hiroya Kubo",
|
|
17
|
+
license: "MPL-2.0",
|
|
18
|
+
unsandboxed: true,
|
|
19
|
+
docsURI: "https://kubohiroya.github.io/turbowarp-named-functions/",
|
|
20
|
+
blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNCIgeT0iOCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjMyIiByeD0iNiIgZmlsbD0iIzhBNTVENyIvPjx0ZXh0IHg9IjI0IiB5PSIzMSIgZm9udC1mYW1pbHk9Im1vbm9zcGFjZSIgZm9udC1zaXplPSIxNiIgZm9udC13ZWlnaHQ9ImJvbGQiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNmZmYiPmYoeCk8L3RleHQ+PC9zdmc+"
|
|
21
|
+
};
|
|
22
|
+
var block_definitions_default = {
|
|
23
|
+
extensionName: "Named Functions",
|
|
24
|
+
blocks: [
|
|
25
|
+
{
|
|
26
|
+
"opcode": "defineFunction",
|
|
27
|
+
"blockType": "HAT",
|
|
28
|
+
"text": "define function [NAME] description [DESCRIPTION] args schema [SCHEMA] export as [EXPORT]",
|
|
29
|
+
"description": "Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. export as tool marks it for consumers such as AI tool calling.",
|
|
30
|
+
"descriptionJa": "名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。export asをtoolにすると、AIのツール呼び出しなどの利用側に公開する印になります。",
|
|
31
|
+
"arguments": {
|
|
32
|
+
"NAME": {
|
|
33
|
+
"type": "STRING",
|
|
34
|
+
"defaultValue": "add"
|
|
35
|
+
},
|
|
36
|
+
"DESCRIPTION": {
|
|
37
|
+
"type": "STRING",
|
|
38
|
+
"defaultValue": "Adds two numbers."
|
|
39
|
+
},
|
|
40
|
+
"SCHEMA": {
|
|
41
|
+
"type": "STRING",
|
|
42
|
+
"defaultValue": "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"number\"},\"b\":{\"type\":\"number\"}},\"required\":[\"a\",\"b\"]}"
|
|
43
|
+
},
|
|
44
|
+
"EXPORT": {
|
|
45
|
+
"type": "STRING",
|
|
46
|
+
"defaultValue": "none",
|
|
47
|
+
"menu": "exportModes"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"opcode": "functionArgument",
|
|
53
|
+
"blockType": "REPORTER",
|
|
54
|
+
"text": "function argument [PATH]",
|
|
55
|
+
"description": "Inside a function, reports the argument at a dotted path such as a or items.0.name.",
|
|
56
|
+
"descriptionJa": "関数の中で、aやitems.0.nameのようなドット区切りのパスにある引数を返します。",
|
|
57
|
+
"arguments": { "PATH": {
|
|
58
|
+
"type": "STRING",
|
|
59
|
+
"defaultValue": "a"
|
|
60
|
+
} }
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
"opcode": "functionArgumentsJson",
|
|
64
|
+
"blockType": "REPORTER",
|
|
65
|
+
"text": "function arguments JSON",
|
|
66
|
+
"description": "Inside a function, reports all arguments as JSON text.",
|
|
67
|
+
"descriptionJa": "関数の中で、すべての引数をJSONテキストとして返します。",
|
|
68
|
+
"arguments": {}
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"opcode": "returnValue",
|
|
72
|
+
"blockType": "COMMAND",
|
|
73
|
+
"text": "return [VALUE]",
|
|
74
|
+
"description": "Inside a function, returns a value and ends the script. JSON text is returned as JSON; other text is returned as a string.",
|
|
75
|
+
"descriptionJa": "関数の中で値を返し、スクリプトを終了します。JSONテキストはJSONとして、それ以外のテキストは文字列として返します。",
|
|
76
|
+
"arguments": { "VALUE": {
|
|
77
|
+
"type": "STRING",
|
|
78
|
+
"defaultValue": "0"
|
|
79
|
+
} }
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"opcode": "callFunction",
|
|
83
|
+
"blockType": "REPORTER",
|
|
84
|
+
"text": "call function [NAME] with [ARGS]",
|
|
85
|
+
"description": "Calls a function and waits for its result. ARGS is JSON text and is checked against the args schema. Takes at least one frame.",
|
|
86
|
+
"descriptionJa": "関数を呼び出し、結果を待って返します。ARGSはJSONテキストで、args schemaで検査されます。少なくとも1フレームかかります。",
|
|
87
|
+
"arguments": {
|
|
88
|
+
"NAME": {
|
|
89
|
+
"type": "STRING",
|
|
90
|
+
"defaultValue": "add"
|
|
91
|
+
},
|
|
92
|
+
"ARGS": {
|
|
93
|
+
"type": "STRING",
|
|
94
|
+
"defaultValue": "{\"a\":1,\"b\":2}"
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
"opcode": "startFunction",
|
|
100
|
+
"blockType": "REPORTER",
|
|
101
|
+
"text": "start function [NAME] with [ARGS]",
|
|
102
|
+
"description": "Starts a function without waiting and reports a promise reference as JSON text.",
|
|
103
|
+
"descriptionJa": "関数を待たずに開始し、Promiseへの参照をJSONテキストで返します。",
|
|
104
|
+
"arguments": {
|
|
105
|
+
"NAME": {
|
|
106
|
+
"type": "STRING",
|
|
107
|
+
"defaultValue": "add"
|
|
108
|
+
},
|
|
109
|
+
"ARGS": {
|
|
110
|
+
"type": "STRING",
|
|
111
|
+
"defaultValue": "{\"a\":1,\"b\":2}"
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
"opcode": "awaitResult",
|
|
117
|
+
"blockType": "REPORTER",
|
|
118
|
+
"text": "await [PROMISE]",
|
|
119
|
+
"description": "Waits for a promise reference from start function and reports its result.",
|
|
120
|
+
"descriptionJa": "start functionが返したPromiseへの参照を待ち、その結果を返します。",
|
|
121
|
+
"arguments": { "PROMISE": {
|
|
122
|
+
"type": "STRING",
|
|
123
|
+
"defaultValue": "{\"$promise\":\"p_1\"}"
|
|
124
|
+
} }
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
"opcode": "awaitAll",
|
|
128
|
+
"blockType": "REPORTER",
|
|
129
|
+
"text": "await all [PROMISES]",
|
|
130
|
+
"description": "Waits for a JSON array of promise references and reports a JSON array of results. Failed calls become {\"$error\": message}.",
|
|
131
|
+
"descriptionJa": "Promiseへの参照のJSON配列をすべて待ち、結果のJSON配列を返します。失敗した呼び出しは{\"$error\": メッセージ}になります。",
|
|
132
|
+
"arguments": { "PROMISES": {
|
|
133
|
+
"type": "STRING",
|
|
134
|
+
"defaultValue": "[]"
|
|
135
|
+
} }
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"opcode": "isSettled",
|
|
139
|
+
"blockType": "BOOLEAN",
|
|
140
|
+
"text": "[PROMISE] settled?",
|
|
141
|
+
"description": "Reports whether a started function has finished, without waiting.",
|
|
142
|
+
"descriptionJa": "開始した関数が終わったかを、待たずに返します。",
|
|
143
|
+
"arguments": { "PROMISE": {
|
|
144
|
+
"type": "STRING",
|
|
145
|
+
"defaultValue": "{\"$promise\":\"p_1\"}"
|
|
146
|
+
} }
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
"opcode": "isDefined",
|
|
150
|
+
"blockType": "BOOLEAN",
|
|
151
|
+
"text": "function [NAME] defined?",
|
|
152
|
+
"description": "Reports whether a valid define function hat with this name exists.",
|
|
153
|
+
"descriptionJa": "この名前の正しいdefine functionハットがあるかを返します。",
|
|
154
|
+
"arguments": { "NAME": {
|
|
155
|
+
"type": "STRING",
|
|
156
|
+
"defaultValue": "add"
|
|
157
|
+
} }
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
"opcode": "lastError",
|
|
161
|
+
"blockType": "REPORTER",
|
|
162
|
+
"text": "last function error",
|
|
163
|
+
"description": "Reports the most recent function error, or an empty string.",
|
|
164
|
+
"descriptionJa": "直近の関数のエラーを返します。エラーがなければ空文字列を返します。",
|
|
165
|
+
"arguments": {}
|
|
166
|
+
}
|
|
167
|
+
],
|
|
168
|
+
menus: { "exportModes": {
|
|
169
|
+
"acceptReporters": false,
|
|
170
|
+
"items": ["none", "tool"]
|
|
171
|
+
} }
|
|
172
|
+
};
|
|
173
|
+
var FunctionDispatcher = class {
|
|
174
|
+
constructor(runtime, options) {
|
|
175
|
+
this.runtime = runtime;
|
|
176
|
+
this.options = options;
|
|
177
|
+
this.queue = [];
|
|
178
|
+
this.running = /* @__PURE__ */ new Map();
|
|
179
|
+
this.byThread = /* @__PURE__ */ new Map();
|
|
180
|
+
this.starting = null;
|
|
181
|
+
this.step = 0;
|
|
182
|
+
this.onAfterExecute = () => this.afterStep();
|
|
183
|
+
this.onStopAll = () => this.cancelAll("The project was stopped.");
|
|
184
|
+
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
185
|
+
this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
|
|
186
|
+
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
|
|
187
|
+
runtime.on("AFTER_EXECUTE", this.onAfterExecute);
|
|
188
|
+
runtime.on("PROJECT_STOP_ALL", this.onStopAll);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Starts a named function. `caller` is the thread of the block making the call, if any; it is used
|
|
192
|
+
* to detect reentrant calls.
|
|
193
|
+
*/
|
|
194
|
+
invoke(name, args, caller) {
|
|
195
|
+
if (!this.options.knownNames().has(name)) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${name}`));
|
|
196
|
+
const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
|
|
197
|
+
if (parentChain.includes(name)) return Promise.reject(/* @__PURE__ */ new Error(`Reentrant call: ${[...parentChain, name].join(" -> ")}. Use a custom block for recursion.`));
|
|
198
|
+
return new Promise((resolve, reject) => {
|
|
199
|
+
const invocation = {
|
|
200
|
+
name,
|
|
201
|
+
args,
|
|
202
|
+
chain: [...parentChain, name],
|
|
203
|
+
resolve,
|
|
204
|
+
reject,
|
|
205
|
+
thread: null,
|
|
206
|
+
startedAtStep: -1,
|
|
207
|
+
timer: null,
|
|
208
|
+
settled: false
|
|
209
|
+
};
|
|
210
|
+
invocation.timer = this.setTimer(() => this.settle(invocation, /* @__PURE__ */ new Error(`Function ${name} timed out.`)), this.timeoutMs);
|
|
211
|
+
this.queue.push(invocation);
|
|
212
|
+
this.pump();
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/** Hat predicate: true only for the script that should run the invocation being started. */
|
|
216
|
+
matchHat(name, thread) {
|
|
217
|
+
const invocation = this.starting;
|
|
218
|
+
if (!invocation || !thread || invocation.name !== name.trim()) return false;
|
|
219
|
+
invocation.thread = thread;
|
|
220
|
+
this.byThread.set(thread, invocation);
|
|
221
|
+
this.starting = null;
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
argumentsFor(thread) {
|
|
225
|
+
const invocation = thread ? this.byThread.get(thread) : void 0;
|
|
226
|
+
if (!invocation) throw new Error("This block can only be used inside a running function.");
|
|
227
|
+
return invocation.args;
|
|
228
|
+
}
|
|
229
|
+
returnFrom(thread, value) {
|
|
230
|
+
const invocation = thread ? this.byThread.get(thread) : void 0;
|
|
231
|
+
if (!invocation) throw new Error("return can only be used inside a running function.");
|
|
232
|
+
this.settle(invocation, null, value);
|
|
233
|
+
}
|
|
234
|
+
cancelAll(reason) {
|
|
235
|
+
for (const invocation of [...this.queue, ...this.running.values()]) this.settle(invocation, new Error(reason));
|
|
236
|
+
if (this.starting) this.settle(this.starting, new Error(reason));
|
|
237
|
+
}
|
|
238
|
+
get pendingCount() {
|
|
239
|
+
return this.queue.length + this.running.size;
|
|
240
|
+
}
|
|
241
|
+
release() {
|
|
242
|
+
this.cancelAll("Named functions were released.");
|
|
243
|
+
this.runtime.off?.("AFTER_EXECUTE", this.onAfterExecute);
|
|
244
|
+
this.runtime.off?.("PROJECT_STOP_ALL", this.onStopAll);
|
|
245
|
+
}
|
|
246
|
+
pump() {
|
|
247
|
+
if (this.starting) return;
|
|
248
|
+
const index = this.queue.findIndex((invocation) => !this.running.has(invocation.name));
|
|
249
|
+
if (index < 0) return;
|
|
250
|
+
const [invocation] = this.queue.splice(index, 1);
|
|
251
|
+
if (!invocation) return;
|
|
252
|
+
this.running.set(invocation.name, invocation);
|
|
253
|
+
this.starting = invocation;
|
|
254
|
+
invocation.startedAtStep = this.step;
|
|
255
|
+
this.runtime.startHats(this.options.hatOpcode);
|
|
256
|
+
}
|
|
257
|
+
afterStep() {
|
|
258
|
+
this.step += 1;
|
|
259
|
+
const starting = this.starting;
|
|
260
|
+
if (starting && this.step - starting.startedAtStep > 2) this.settle(starting, /* @__PURE__ */ new Error(`Function ${starting.name} did not start. Is its script already running?`));
|
|
261
|
+
for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settle(invocation, null, null);
|
|
262
|
+
this.pump();
|
|
263
|
+
}
|
|
264
|
+
settle(invocation, error, value) {
|
|
265
|
+
if (invocation.settled) return;
|
|
266
|
+
invocation.settled = true;
|
|
267
|
+
this.clearTimer(invocation.timer);
|
|
268
|
+
const queued = this.queue.indexOf(invocation);
|
|
269
|
+
if (queued >= 0) this.queue.splice(queued, 1);
|
|
270
|
+
if (this.running.get(invocation.name) === invocation) this.running.delete(invocation.name);
|
|
271
|
+
if (invocation.thread) this.byThread.delete(invocation.thread);
|
|
272
|
+
if (this.starting === invocation) this.starting = null;
|
|
273
|
+
if (error) invocation.reject(error);
|
|
274
|
+
else invocation.resolve(value);
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
/** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
|
|
278
|
+
function readArgumentPath(args, path) {
|
|
279
|
+
const trimmed = path.trim();
|
|
280
|
+
if (trimmed.length === 0) return args;
|
|
281
|
+
let current = args;
|
|
282
|
+
for (const segment of trimmed.split(".")) {
|
|
283
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
284
|
+
current = current[segment];
|
|
285
|
+
}
|
|
286
|
+
return current;
|
|
287
|
+
}
|
|
288
|
+
/** Converts a value for a Scratch reporter: objects and arrays become JSON text. */
|
|
289
|
+
function toScratchValue(value) {
|
|
290
|
+
if (value === void 0 || value === null) return "";
|
|
291
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
292
|
+
return JSON.stringify(value);
|
|
293
|
+
}
|
|
294
|
+
/** Parses block text: JSON text becomes JSON, anything else stays a string. */
|
|
295
|
+
function parseJsonOrText(text) {
|
|
296
|
+
const trimmed = text.trim();
|
|
297
|
+
if (trimmed.length === 0) return "";
|
|
298
|
+
try {
|
|
299
|
+
return JSON.parse(trimmed);
|
|
300
|
+
} catch {
|
|
301
|
+
return text;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
//#endregion
|
|
305
|
+
//#region src/function-registry.ts
|
|
306
|
+
var FUNCTION_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
307
|
+
var MAX_DESCRIPTION_LENGTH = 1024;
|
|
308
|
+
/**
|
|
309
|
+
* Reads every `define function` hat in the project. NAME, DESCRIPTION, and SCHEMA are part of the
|
|
310
|
+
* tool contract sent to the model before any script runs, so they must be literal text.
|
|
311
|
+
*/
|
|
312
|
+
function scanFunctionDefinitions(targets, hatOpcode) {
|
|
313
|
+
const functions = [];
|
|
314
|
+
const errors = [];
|
|
315
|
+
const seen = /* @__PURE__ */ new Map();
|
|
316
|
+
for (const target of targets) {
|
|
317
|
+
if (target.isOriginal === false) continue;
|
|
318
|
+
const targetName = target.getName?.() ?? (target.isStage ? "Stage" : "sprite");
|
|
319
|
+
const blocks = target.blocks._blocks;
|
|
320
|
+
for (const block of Object.values(blocks)) {
|
|
321
|
+
if (block.opcode !== hatOpcode || block.topLevel === false) continue;
|
|
322
|
+
const where = `${targetName} (block ${block.id})`;
|
|
323
|
+
try {
|
|
324
|
+
const definition = readDefinition(block, blocks, targetName);
|
|
325
|
+
const previous = seen.get(definition.name);
|
|
326
|
+
if (previous !== void 0) throw new Error(`function "${definition.name}" is already defined in ${previous}`);
|
|
327
|
+
seen.set(definition.name, where);
|
|
328
|
+
functions.push(definition);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
errors.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
functions.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
|
|
335
|
+
return {
|
|
336
|
+
functions,
|
|
337
|
+
errors
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
function toFunctionTools(functions) {
|
|
341
|
+
return functions.filter((definition) => definition.exportAs === "tool").map((definition) => ({
|
|
342
|
+
type: "function",
|
|
343
|
+
name: definition.name,
|
|
344
|
+
description: definition.description,
|
|
345
|
+
parameters: definition.parameters
|
|
346
|
+
}));
|
|
347
|
+
}
|
|
348
|
+
function readDefinition(block, blocks, targetName) {
|
|
349
|
+
const name = readLiteralInput(block, blocks, "NAME").trim();
|
|
350
|
+
if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
|
|
351
|
+
const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
|
|
352
|
+
if (description.length > 1024) throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
|
|
353
|
+
const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"));
|
|
354
|
+
const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
|
|
355
|
+
if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
|
|
356
|
+
return {
|
|
357
|
+
name,
|
|
358
|
+
description,
|
|
359
|
+
parameters,
|
|
360
|
+
exportAs,
|
|
361
|
+
targetName,
|
|
362
|
+
blockId: block.id
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function readLiteralInput(block, blocks, inputName) {
|
|
366
|
+
const input = block.inputs?.[inputName];
|
|
367
|
+
if (!input) throw new Error(`${inputName} is missing`);
|
|
368
|
+
if (input.block && input.block !== input.shadow) throw new Error(`${inputName} must be literal text, not a reporter block`);
|
|
369
|
+
const shadowId = input.shadow ?? input.block;
|
|
370
|
+
const shadow = shadowId ? blocks[shadowId] : void 0;
|
|
371
|
+
const field = shadow?.fields ? Object.values(shadow.fields)[0] : void 0;
|
|
372
|
+
if (!field) throw new Error(`${inputName} is missing`);
|
|
373
|
+
return String(field.value ?? "");
|
|
374
|
+
}
|
|
375
|
+
function parseSchema(text) {
|
|
376
|
+
let value;
|
|
377
|
+
try {
|
|
378
|
+
value = JSON.parse(text);
|
|
379
|
+
} catch {
|
|
380
|
+
throw new Error("args schema must be valid JSON");
|
|
381
|
+
}
|
|
382
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("args schema must be a JSON object");
|
|
383
|
+
const schema = value;
|
|
384
|
+
if (schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
|
|
385
|
+
return schema;
|
|
386
|
+
}
|
|
387
|
+
//#endregion
|
|
388
|
+
//#region src/schema-validator.ts
|
|
389
|
+
/**
|
|
390
|
+
* A small JSON Schema validator for function arguments. It interprets the schema at run time and
|
|
391
|
+
* never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
|
|
392
|
+
*
|
|
393
|
+
* Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
|
|
394
|
+
* const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
|
|
395
|
+
* description and title, are ignored.
|
|
396
|
+
*/
|
|
397
|
+
function validateAgainstSchema(value, schema, path = "$") {
|
|
398
|
+
const rule = asRecord(schema);
|
|
399
|
+
if (!rule) return [];
|
|
400
|
+
const errors = [];
|
|
401
|
+
if (rule.type !== void 0) {
|
|
402
|
+
const types = Array.isArray(rule.type) ? rule.type : [rule.type];
|
|
403
|
+
if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
|
|
404
|
+
}
|
|
405
|
+
if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => deepEqual(candidate, value))) errors.push(`${path} must be one of ${rule.enum.map((item) => JSON.stringify(item)).join(", ")}`);
|
|
406
|
+
if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
|
|
407
|
+
if (typeof value === "number") {
|
|
408
|
+
if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
|
|
409
|
+
if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
|
|
410
|
+
}
|
|
411
|
+
if (typeof value === "string") {
|
|
412
|
+
const length = [...value].length;
|
|
413
|
+
if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
|
|
414
|
+
if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
|
|
415
|
+
}
|
|
416
|
+
if (Array.isArray(value)) {
|
|
417
|
+
if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
|
|
418
|
+
if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
|
|
419
|
+
if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateAgainstSchema(item, rule.items, `${path}[${index}]`)));
|
|
420
|
+
}
|
|
421
|
+
const object = asRecord(value);
|
|
422
|
+
if (object) {
|
|
423
|
+
const properties = asRecord(rule.properties) ?? {};
|
|
424
|
+
if (Array.isArray(rule.required)) {
|
|
425
|
+
for (const name of rule.required) if (typeof name === "string" && !(name in object)) errors.push(`${path}.${name} is required`);
|
|
426
|
+
}
|
|
427
|
+
for (const [name, child] of Object.entries(object)) if (name in properties) errors.push(...validateAgainstSchema(child, properties[name], `${path}.${name}`));
|
|
428
|
+
else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
|
|
429
|
+
}
|
|
430
|
+
return errors;
|
|
431
|
+
}
|
|
432
|
+
function matchesType(value, type) {
|
|
433
|
+
switch (type) {
|
|
434
|
+
case "object": return asRecord(value) !== null;
|
|
435
|
+
case "array": return Array.isArray(value);
|
|
436
|
+
case "string": return typeof value === "string";
|
|
437
|
+
case "number": return typeof value === "number" && Number.isFinite(value);
|
|
438
|
+
case "integer": return typeof value === "number" && Number.isInteger(value);
|
|
439
|
+
case "boolean": return typeof value === "boolean";
|
|
440
|
+
case "null": return value === null;
|
|
441
|
+
default: return false;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
function deepEqual(left, right) {
|
|
445
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
446
|
+
}
|
|
447
|
+
function asRecord(value) {
|
|
448
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
449
|
+
}
|
|
450
|
+
//#endregion
|
|
451
|
+
//#region src/composition.ts
|
|
452
|
+
/**
|
|
453
|
+
* Composition API: named functions without TurboWarp block definitions.
|
|
454
|
+
*
|
|
455
|
+
* A consumer extension owns its `define function` hat (and its opcode) and forwards the hat
|
|
456
|
+
* predicate and the argument/return blocks here. Importing this module does not register a
|
|
457
|
+
* TurboWarp extension and does not touch the `Scratch` global.
|
|
458
|
+
*/
|
|
459
|
+
function createNamedFunctions(options) {
|
|
460
|
+
return new NamedFunctionsImpl(options);
|
|
461
|
+
}
|
|
462
|
+
var NamedFunctionsImpl = class {
|
|
463
|
+
constructor(options) {
|
|
464
|
+
this.options = options;
|
|
465
|
+
this.promises = /* @__PURE__ */ new Map();
|
|
466
|
+
this.waiting = [];
|
|
467
|
+
this.inFlight = 0;
|
|
468
|
+
this.nextPromiseId = 1;
|
|
469
|
+
this.maxInFlight = Math.max(1, options.maxInFlight ?? 8);
|
|
470
|
+
this.maxRetained = Math.max(1, options.maxRetainedPromises ?? 256);
|
|
471
|
+
const dispatcherOptions = {
|
|
472
|
+
hatOpcode: options.functionHatOpcode,
|
|
473
|
+
knownNames: () => new Set(this.scan().functions.map((definition) => definition.name)),
|
|
474
|
+
...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
|
|
475
|
+
...options.setTimer ? { setTimer: options.setTimer } : {},
|
|
476
|
+
...options.clearTimer ? { clearTimer: options.clearTimer } : {}
|
|
477
|
+
};
|
|
478
|
+
this.dispatcher = new FunctionDispatcher(options.runtime, dispatcherOptions);
|
|
479
|
+
options.runtime.on("PROJECT_STOP_ALL", () => this.promises.clear());
|
|
480
|
+
}
|
|
481
|
+
scan() {
|
|
482
|
+
return scanFunctionDefinitions(this.options.runtime.targets, this.options.functionHatOpcode);
|
|
483
|
+
}
|
|
484
|
+
tools() {
|
|
485
|
+
const scan = this.scan();
|
|
486
|
+
if (scan.errors.length > 0) throw new Error(`Invalid function definitions: ${scan.errors.join("; ")}`);
|
|
487
|
+
return toFunctionTools(scan.functions);
|
|
488
|
+
}
|
|
489
|
+
isDefined(name) {
|
|
490
|
+
return this.scan().functions.some((definition) => definition.name === name.trim());
|
|
491
|
+
}
|
|
492
|
+
call(name, args, options = {}) {
|
|
493
|
+
const trimmed = name.trim();
|
|
494
|
+
const definition = this.scan().functions.find((candidate) => candidate.name === trimmed);
|
|
495
|
+
if (!definition) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${trimmed}`));
|
|
496
|
+
if (options.exportedOnly && definition.exportAs !== "tool") return Promise.reject(/* @__PURE__ */ new Error(`Function ${trimmed} is not exported as a tool.`));
|
|
497
|
+
const errors = validateAgainstSchema(args, definition.parameters);
|
|
498
|
+
if (errors.length > 0) return Promise.reject(/* @__PURE__ */ new Error(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`));
|
|
499
|
+
return this.dispatcher.invoke(trimmed, args, options.caller);
|
|
500
|
+
}
|
|
501
|
+
start(name, args, options = {}) {
|
|
502
|
+
const id = `p_${this.nextPromiseId++}`;
|
|
503
|
+
const promise = this.acquireSlot().then(() => this.call(name, args, options).finally(() => this.releaseSlot()));
|
|
504
|
+
const entry = {
|
|
505
|
+
promise,
|
|
506
|
+
settled: false
|
|
507
|
+
};
|
|
508
|
+
promise.then(() => entry.settled = true, () => entry.settled = true);
|
|
509
|
+
this.promises.set(id, entry);
|
|
510
|
+
this.evictSettled();
|
|
511
|
+
return { $promise: id };
|
|
512
|
+
}
|
|
513
|
+
await(ref) {
|
|
514
|
+
const entry = this.lookup(ref);
|
|
515
|
+
return entry ? entry.promise : Promise.reject(/* @__PURE__ */ new Error("Unknown or expired promise reference."));
|
|
516
|
+
}
|
|
517
|
+
async awaitAll(refs) {
|
|
518
|
+
if (!Array.isArray(refs)) throw new Error("await all needs a JSON array of promise references.");
|
|
519
|
+
return (await Promise.allSettled(refs.map((ref) => this.await(ref)))).map((result) => result.status === "fulfilled" ? result.value : { $error: messageOf$1(result.reason) });
|
|
520
|
+
}
|
|
521
|
+
isSettled(ref) {
|
|
522
|
+
return this.lookup(ref)?.settled ?? false;
|
|
523
|
+
}
|
|
524
|
+
matchHat(name, thread) {
|
|
525
|
+
return this.dispatcher.matchHat(name, thread);
|
|
526
|
+
}
|
|
527
|
+
argumentsFor(thread) {
|
|
528
|
+
return this.dispatcher.argumentsFor(thread);
|
|
529
|
+
}
|
|
530
|
+
returnFrom(thread, value) {
|
|
531
|
+
this.dispatcher.returnFrom(thread, value);
|
|
532
|
+
}
|
|
533
|
+
cancelAll(reason) {
|
|
534
|
+
this.dispatcher.cancelAll(reason);
|
|
535
|
+
}
|
|
536
|
+
release() {
|
|
537
|
+
this.dispatcher.release();
|
|
538
|
+
this.promises.clear();
|
|
539
|
+
}
|
|
540
|
+
lookup(ref) {
|
|
541
|
+
const id = typeof ref === "object" && ref !== null && typeof ref.$promise === "string" ? ref.$promise : void 0;
|
|
542
|
+
return id ? this.promises.get(id) : void 0;
|
|
543
|
+
}
|
|
544
|
+
acquireSlot() {
|
|
545
|
+
if (this.inFlight < this.maxInFlight) {
|
|
546
|
+
this.inFlight += 1;
|
|
547
|
+
return Promise.resolve();
|
|
548
|
+
}
|
|
549
|
+
return new Promise((resolve) => this.waiting.push(() => {
|
|
550
|
+
this.inFlight += 1;
|
|
551
|
+
resolve();
|
|
552
|
+
}));
|
|
553
|
+
}
|
|
554
|
+
releaseSlot() {
|
|
555
|
+
this.inFlight -= 1;
|
|
556
|
+
this.waiting.shift()?.();
|
|
557
|
+
}
|
|
558
|
+
evictSettled() {
|
|
559
|
+
if (this.promises.size <= this.maxRetained) return;
|
|
560
|
+
for (const [id, entry] of this.promises) {
|
|
561
|
+
if (this.promises.size <= this.maxRetained) break;
|
|
562
|
+
if (entry.settled) this.promises.delete(id);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
function messageOf$1(error) {
|
|
567
|
+
return error instanceof Error ? error.message : String(error);
|
|
568
|
+
}
|
|
569
|
+
//#endregion
|
|
570
|
+
//#region src/extension.ts
|
|
571
|
+
var blockDefinitions = block_definitions_default.blocks;
|
|
572
|
+
var menuDefinitions = block_definitions_default.menus;
|
|
573
|
+
var DEFINE_FUNCTION_OPCODE = `${extensionConfig.id}_defineFunction`;
|
|
574
|
+
/** Block surface over the named-functions composition. */
|
|
575
|
+
var NamedFunctionsExtension = class {
|
|
576
|
+
constructor(deps) {
|
|
577
|
+
this.lastErrorMessage = "";
|
|
578
|
+
this.functions = createNamedFunctions({
|
|
579
|
+
...deps,
|
|
580
|
+
functionHatOpcode: DEFINE_FUNCTION_OPCODE
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
getInfo() {
|
|
584
|
+
return {
|
|
585
|
+
id: extensionConfig.id,
|
|
586
|
+
name: Scratch.translate(block_definitions_default.extensionName),
|
|
587
|
+
docsURI: extensionConfig.docsURI,
|
|
588
|
+
blockIconURI: extensionConfig.blockIconURI,
|
|
589
|
+
blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
|
|
590
|
+
menus: Object.fromEntries(Object.entries(menuDefinitions).map(([id, menu]) => [id, {
|
|
591
|
+
acceptReporters: menu.acceptReporters,
|
|
592
|
+
items: [...menu.items]
|
|
593
|
+
}]))
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
defineFunction(args, util) {
|
|
597
|
+
return this.functions.matchHat(Scratch.Cast.toString(args.NAME), util?.thread);
|
|
598
|
+
}
|
|
599
|
+
functionArgument(args, util) {
|
|
600
|
+
return this.guard("", () => toScratchValue(readArgumentPath(this.functions.argumentsFor(util?.thread), Scratch.Cast.toString(args.PATH))));
|
|
601
|
+
}
|
|
602
|
+
functionArgumentsJson(_args, util) {
|
|
603
|
+
return this.guard("", () => JSON.stringify(this.functions.argumentsFor(util?.thread) ?? null));
|
|
604
|
+
}
|
|
605
|
+
returnValue(args, util) {
|
|
606
|
+
this.guard(void 0, () => {
|
|
607
|
+
this.functions.returnFrom(util?.thread, parseJsonOrText(Scratch.Cast.toString(args.VALUE)));
|
|
608
|
+
util?.stopThisScript?.();
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
async callFunction(args, util) {
|
|
612
|
+
try {
|
|
613
|
+
const result = await this.functions.call(Scratch.Cast.toString(args.NAME), parseArguments(Scratch.Cast.toString(args.ARGS)), util?.thread ? { caller: util.thread } : {});
|
|
614
|
+
this.lastErrorMessage = "";
|
|
615
|
+
return toScratchValue(result);
|
|
616
|
+
} catch (error) {
|
|
617
|
+
this.lastErrorMessage = messageOf(error);
|
|
618
|
+
return "";
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
startFunction(args, util) {
|
|
622
|
+
return this.guard("", () => {
|
|
623
|
+
const ref = this.functions.start(Scratch.Cast.toString(args.NAME), parseArguments(Scratch.Cast.toString(args.ARGS)), util?.thread ? { caller: util.thread } : {});
|
|
624
|
+
return JSON.stringify(ref);
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
async awaitResult(args) {
|
|
628
|
+
try {
|
|
629
|
+
const result = await this.functions.await(parseJsonOrText(Scratch.Cast.toString(args.PROMISE)));
|
|
630
|
+
this.lastErrorMessage = "";
|
|
631
|
+
return toScratchValue(result);
|
|
632
|
+
} catch (error) {
|
|
633
|
+
this.lastErrorMessage = messageOf(error);
|
|
634
|
+
return "";
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
async awaitAll(args) {
|
|
638
|
+
try {
|
|
639
|
+
const results = await this.functions.awaitAll(parseJsonOrText(Scratch.Cast.toString(args.PROMISES)));
|
|
640
|
+
this.lastErrorMessage = "";
|
|
641
|
+
return JSON.stringify(results);
|
|
642
|
+
} catch (error) {
|
|
643
|
+
this.lastErrorMessage = messageOf(error);
|
|
644
|
+
return "";
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
isSettled(args) {
|
|
648
|
+
return this.functions.isSettled(parseJsonOrText(Scratch.Cast.toString(args.PROMISE)));
|
|
649
|
+
}
|
|
650
|
+
isDefined(args) {
|
|
651
|
+
return this.functions.isDefined(Scratch.Cast.toString(args.NAME));
|
|
652
|
+
}
|
|
653
|
+
lastError() {
|
|
654
|
+
return this.lastErrorMessage;
|
|
655
|
+
}
|
|
656
|
+
guard(fallback, action) {
|
|
657
|
+
try {
|
|
658
|
+
const result = action();
|
|
659
|
+
this.lastErrorMessage = "";
|
|
660
|
+
return result;
|
|
661
|
+
} catch (error) {
|
|
662
|
+
this.lastErrorMessage = messageOf(error);
|
|
663
|
+
return fallback;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
toScratchBlock(block) {
|
|
667
|
+
const scratchBlock = {
|
|
668
|
+
opcode: block.opcode,
|
|
669
|
+
blockType: Scratch.BlockType[block.blockType],
|
|
670
|
+
text: Scratch.translate(block.text),
|
|
671
|
+
arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
|
|
672
|
+
type: Scratch.ArgumentType[argument.type],
|
|
673
|
+
defaultValue: argument.defaultValue,
|
|
674
|
+
...argument.menu ? { menu: argument.menu } : {}
|
|
675
|
+
}]))
|
|
676
|
+
};
|
|
677
|
+
if (block.blockType === "HAT") scratchBlock.isEdgeActivated = false;
|
|
678
|
+
return scratchBlock;
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
/** ARGS text: empty means `{}`; otherwise it must be JSON. */
|
|
682
|
+
function parseArguments(text) {
|
|
683
|
+
if (text.trim().length === 0) return {};
|
|
684
|
+
try {
|
|
685
|
+
return JSON.parse(text);
|
|
686
|
+
} catch {
|
|
687
|
+
throw new Error("ARGS must be JSON text, for example {\"a\":1}.");
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function messageOf(error) {
|
|
691
|
+
return error instanceof Error ? error.message : String(error);
|
|
692
|
+
}
|
|
693
|
+
//#endregion
|
|
694
|
+
//#region src/index.ts
|
|
695
|
+
if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
|
|
696
|
+
var runtime = Scratch.vm?.runtime;
|
|
697
|
+
if (!runtime) throw new Error(`${extensionConfig.name} requires access to the TurboWarp VM runtime.`);
|
|
698
|
+
Scratch.extensions.register(new NamedFunctionsExtension({ runtime }));
|
|
699
|
+
//#endregion
|
|
700
|
+
|
|
701
|
+
})(Scratch);
|