@kubohiroya/turbowarp-named-functions 0.4.1-rc.2 → 0.4.2
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/README.ja.md +30 -11
- package/README.md +30 -11
- package/dist/composition.js +264 -42
- package/dist/extension-manifest.json +28 -0
- package/dist/turbowarp-named-functions.js +834 -411
- package/dist/types/composition.d.ts +32 -7
- package/dist/types/extension.d.ts +26 -3
- package/dist/types/fixed-input-editors.d.ts +12 -1
- package/dist/types/fixed-input-schema.d.ts +5 -2
- package/dist/types/function-dispatcher.d.ts +58 -9
- package/dist/types/function-registry.d.ts +43 -0
- package/dist/types/runtime-types.d.ts +21 -0
- package/package.json +2 -2
- package/schemas/block-editor-fixed-inputs.schema.json +11 -0
- package/src/block-definitions.json +47 -7
- package/src/composition.ts +91 -14
- package/src/extension.ts +113 -22
- package/src/fixed-input-editors.ts +74 -25
- package/src/fixed-input-schema.ts +19 -12
- package/src/function-dispatcher.ts +163 -40
- package/src/function-registry.ts +166 -10
- package/src/runtime-types.ts +20 -0
package/README.ja.md
CHANGED
|
@@ -19,10 +19,11 @@ JSONの引数を受け取りJSONの結果を返す「名前を持つ関数」を
|
|
|
19
19
|
|
|
20
20
|
## できること
|
|
21
21
|
|
|
22
|
-
- `define function
|
|
22
|
+
- `define function`ハットで関数を定義する(名前、範囲〔このスプライトのみ/すべてのスプライト〕、説明、引数のJSON Schema)
|
|
23
|
+
- 関数を名前で呼び出す、またはそのスプライトが呼べる関数の選択肢から選んで呼び出す
|
|
23
24
|
- 名前で呼び出して結果を待つ(`call function`)、または開始してあとで待つ(`start function`、`await`、`await all`)
|
|
24
25
|
- 関数を実行する前に、引数をスキーマで検査する(コード生成を使わない)
|
|
25
|
-
-
|
|
26
|
+
- TurboWarp Plusのランタイムでは、呼び出したブロックの中で関数を実行し、関数が自分自身を呼ぶ(再帰する)こともできる。素のTurboWarpでは、再帰を待ち続けずにエラーにする
|
|
26
27
|
- ほかの拡張が自分のブロックと組み合わせて同じ機能を使えるよう、Composition APIを提供する
|
|
27
28
|
|
|
28
29
|
## 動作条件と安全上の注意
|
|
@@ -46,7 +47,7 @@ JSONの引数を受け取りJSONの結果を返す「名前を持つ関数」を
|
|
|
46
47
|
npm packageとして使う場合は、検証済みのversionをexact pinします。
|
|
47
48
|
|
|
48
49
|
```bash
|
|
49
|
-
pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.4.
|
|
50
|
+
pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.4.2
|
|
50
51
|
```
|
|
51
52
|
|
|
52
53
|
## クイックスタート
|
|
@@ -65,15 +66,16 @@ say (call function [add] with [{"a":1,"b":2}])
|
|
|
65
66
|
|
|
66
67
|
<!-- BEGIN GENERATED BLOCKS -->
|
|
67
68
|
|
|
68
|
-
### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]`
|
|
69
|
+
### `define function [NAME] for [SCOPE] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]`
|
|
69
70
|
|
|
70
|
-
名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。SCHEMAとRETURNSには、JSON Schema文字列、または`define schema`ハットの名前(Name@1.0.0の形でバージョン固定も可)を書けます。RETURNSは任意で、空欄なら戻り値を検証しません。
|
|
71
|
+
名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。SCOPEを`this sprite only`(新しく置いたハットの既定値)にすると、定義したスプライトまたは背景と、そのクローンのスクリプトからだけ呼べます。`all sprites`にすると、ほかのスプライトや背景、ツールからも呼べます。SCOPEができる前に保存したハットは`all sprites`として扱います。SCHEMAとRETURNSには、JSON Schema文字列、または`define schema`ハットの名前(Name@1.0.0の形でバージョン固定も可)を書けます。RETURNSは任意で、空欄なら戻り値を検証しません。
|
|
71
72
|
|
|
72
73
|
| 項目 | 値 |
|
|
73
74
|
|---|---|
|
|
74
75
|
| 種類 | ハット |
|
|
75
76
|
| Opcode | `defineFunction` |
|
|
76
77
|
| `NAME` | 文字列, 既定値: `add` |
|
|
78
|
+
| `SCOPE` | 文字列, 既定値: `sprite`, 選択肢: `global` (all sprites), `sprite` (this sprite only) |
|
|
77
79
|
| `DESCRIPTION` | 文字列, 既定値: `Adds two numbers.` |
|
|
78
80
|
| `SCHEMA` | 文字列, 既定値: `{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}` |
|
|
79
81
|
| `RETURNS` | 文字列, 既定値: `` |
|
|
@@ -208,7 +210,7 @@ say (call function [add] with [{"a":1,"b":2}])
|
|
|
208
210
|
|
|
209
211
|
### `call function [NAME] with [ARGS]`
|
|
210
212
|
|
|
211
|
-
|
|
213
|
+
名前で関数を呼び出し、結果を待って返します。名前は、このスプライト自身の関数、すべてのスプライト用の関数の順に探します。ARGSはJSONテキストで、args schemaで検査されます。TurboWarp Plusのランタイムでは待ちのない関数は呼び出しの中で終わり、素のTurboWarpでは少なくとも1フレームかかります。
|
|
212
214
|
|
|
213
215
|
| 項目 | 値 |
|
|
214
216
|
|---|---|
|
|
@@ -217,6 +219,17 @@ say (call function [add] with [{"a":1,"b":2}])
|
|
|
217
219
|
| `NAME` | 文字列, 既定値: `add` |
|
|
218
220
|
| `ARGS` | 文字列, 既定値: `{"a":1,"b":2}` |
|
|
219
221
|
|
|
222
|
+
### `call [FUNCTION] with [ARGS]`
|
|
223
|
+
|
|
224
|
+
このスプライトが呼べる関数(このスプライト自身の関数と、すべてのスプライト用の関数)から選んで呼び出します。それ以外は`call function`と同じです。
|
|
225
|
+
|
|
226
|
+
| 項目 | 値 |
|
|
227
|
+
|---|---|
|
|
228
|
+
| 種類 | 値ブロック |
|
|
229
|
+
| Opcode | `callFunctionFromMenu` |
|
|
230
|
+
| `FUNCTION` | 文字列, 既定値: ``, 選択肢: このスプライトが呼べる関数 |
|
|
231
|
+
| `ARGS` | 文字列, 既定値: `{}` |
|
|
232
|
+
|
|
220
233
|
### `start function [NAME] with [ARGS]`
|
|
221
234
|
|
|
222
235
|
関数を待たずに開始し、Promiseへの参照をJSONテキストで返します。
|
|
@@ -260,7 +273,7 @@ Promiseへの参照のJSON配列をすべて待ち、結果のJSON配列を返
|
|
|
260
273
|
|
|
261
274
|
### `function [NAME] defined?`
|
|
262
275
|
|
|
263
|
-
|
|
276
|
+
このスプライトがこの名前の関数を呼べるか(このスプライト自身の関数、またはすべてのスプライト用の関数があるか)を返します。
|
|
264
277
|
|
|
265
278
|
| 項目 | 値 |
|
|
266
279
|
|---|---|
|
|
@@ -283,10 +296,16 @@ Promiseへの参照のJSON配列をすべて待ち、結果のJSON配列を返
|
|
|
283
296
|
|
|
284
297
|
| 状況 | 動作 |
|
|
285
298
|
|---|---|
|
|
286
|
-
|
|
|
287
|
-
|
|
|
288
|
-
|
|
|
289
|
-
|
|
|
299
|
+
| 範囲 | 新しく置いた`define function`ハットは「このスプライトのみ」で、定義したスプライト(または背景)とそのクローンのスクリプトから呼べる。「すべてのスプライト」にすると、どこからでも、ツールからも呼べる。範囲ができる前に保存したハットは「すべてのスプライト」として扱う |
|
|
300
|
+
| 関数の名前 | すべてのスプライト用の名前はプロジェクト内で重複できない。スプライト用の名前はそのスプライト内で重複できず、すべてのスプライト用の名前とも重複できない。別々のスプライトが同じ名前の関数をそれぞれ持つことはできる |
|
|
301
|
+
| どのスプライトとして動くか | スプライト自身の関数は呼び出したスプライトとして動く(クローンが呼べばそのクローンとして動く)。すべてのスプライト用の関数は、定義したスプライトまたは背景として動く |
|
|
302
|
+
| 別のスプライトの関数を呼んだ | `Function f belongs to Cat; make it for all sprites to call it from here.`というエラーで失敗する |
|
|
303
|
+
| 呼び出しの開始(TurboWarp Plusのランタイム) | 関数のスクリプトを直接起動し、呼び出したブロックの中で実行する |
|
|
304
|
+
| 呼び出しの開始(素のTurboWarp) | すべての`define function`ハットが起動され、NAMEが一致したものだけが実行を続ける |
|
|
305
|
+
| かかる時間(TurboWarp Plusのランタイム) | 待ちのない関数は、画面を再描画せずに実行する独自ブロックと同じく、呼び出しの中で終わる。待ちのある関数や、128段より深い入れ子の呼び出しは、後のフレームで結果が出る |
|
|
306
|
+
| かかる時間(素のTurboWarp) | 関数は独立したスクリプトとして動くため、1回の呼び出しに少なくとも1フレームかかる。細かいループには独自ブロックを使う |
|
|
307
|
+
| 同じ関数を続けて呼んだ | TurboWarp Plusのランタイムでは、呼び出しごとに独立して実行する。素のTurboWarpでは、1つずつ順番に実行し、異なる関数は並行して実行する |
|
|
308
|
+
| 関数が直接または別の関数を経由して自分自身を呼んだ | TurboWarp Plusのランタイムでは動く。素のTurboWarpでは`Reentrant call: a -> b -> a`というエラーで失敗するので、再帰には独自ブロックを使う |
|
|
290
309
|
| 引数がスキーマに合わない | スクリプトを起動する前に失敗する。どの項目が合わないかは`last function error`でわかる |
|
|
291
310
|
| スクリプトが`return`なしで終わった | 結果は空(`null`)になる |
|
|
292
311
|
| 戻り値がreturns schemaに合わない | 呼び出しが失敗し、`last function error`に期待型とJSON pathが表示される。`return`なしの終了も`null`として検証される |
|
package/README.md
CHANGED
|
@@ -20,11 +20,12 @@ Run `pnpm run samples:build` after source/bundle changes and `pnpm run samples:c
|
|
|
20
20
|
|
|
21
21
|
## What it does
|
|
22
22
|
|
|
23
|
-
- Defines functions with a `define function` hat: a name, a description, and a JSON Schema for the arguments.
|
|
23
|
+
- Defines functions with a `define function` hat: a name, a scope (this sprite only, or all sprites), a description, and a JSON Schema for the arguments.
|
|
24
|
+
- Calls a function by typing its name, or by choosing it from the functions the sprite can call.
|
|
24
25
|
- Calls a function by name and waits for its result (`call function`), or starts it and awaits it later (`start function`, `await`, `await all`).
|
|
25
26
|
- Checks arguments against the schema before the function runs, without generating code.
|
|
26
27
|
- Optionally checks returned values against the same JSON Schema subset.
|
|
27
|
-
-
|
|
28
|
+
- On the TurboWarp Plus runtime, runs a call inside the calling block and lets functions call themselves. On stock TurboWarp, reports such recursion as an error instead of waiting forever.
|
|
28
29
|
- Provides a Composition API so other extensions can bundle the same capability with their own blocks.
|
|
29
30
|
|
|
30
31
|
## Requirements and safety
|
|
@@ -50,7 +51,7 @@ Run `pnpm run samples:build` after source/bundle changes and `pnpm run samples:c
|
|
|
50
51
|
### npm package
|
|
51
52
|
|
|
52
53
|
```bash
|
|
53
|
-
pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.4.
|
|
54
|
+
pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.4.2
|
|
54
55
|
```
|
|
55
56
|
|
|
56
57
|
Standalone bundle:
|
|
@@ -77,15 +78,16 @@ generated section manually.
|
|
|
77
78
|
|
|
78
79
|
<!-- BEGIN GENERATED BLOCKS -->
|
|
79
80
|
|
|
80
|
-
### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]`
|
|
81
|
+
### `define function [NAME] for [SCOPE] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]`
|
|
81
82
|
|
|
82
|
-
Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. SCHEMA and RETURNS each take JSON Schema text or the name of a `define schema` hat, optionally pinned as Name@1.0.0. RETURNS is optional; leave it blank to disable return validation.
|
|
83
|
+
Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. SCOPE `this sprite only` (the default for new hats) makes the function callable only from scripts of this sprite or the stage that defines it, and its clones; `all sprites` makes it callable from everywhere, including tools. Hats saved before SCOPE existed are for all sprites. SCHEMA and RETURNS each take JSON Schema text or the name of a `define schema` hat, optionally pinned as Name@1.0.0. RETURNS is optional; leave it blank to disable return validation.
|
|
83
84
|
|
|
84
85
|
| Property | Value |
|
|
85
86
|
|---|---|
|
|
86
87
|
| Type | Hat |
|
|
87
88
|
| Opcode | `defineFunction` |
|
|
88
89
|
| `NAME` | String, default: `add` |
|
|
90
|
+
| `SCOPE` | String, default: `sprite`, choices: `global` (all sprites), `sprite` (this sprite only) |
|
|
89
91
|
| `DESCRIPTION` | String, default: `Adds two numbers.` |
|
|
90
92
|
| `SCHEMA` | String, default: `{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}` |
|
|
91
93
|
| `RETURNS` | String, default: `` |
|
|
@@ -220,7 +222,7 @@ Inside a function, returns a value and ends the script. JSON text is returned as
|
|
|
220
222
|
|
|
221
223
|
### `call function [NAME] with [ARGS]`
|
|
222
224
|
|
|
223
|
-
Calls a function and waits for its result. ARGS is JSON text and is checked against the args schema.
|
|
225
|
+
Calls a function by name and waits for its result. The name is looked up among this sprite's own functions, then the functions for all sprites. ARGS is JSON text and is checked against the args schema. On the TurboWarp Plus runtime a function that does not wait finishes within the call; on stock TurboWarp a call takes at least one frame.
|
|
224
226
|
|
|
225
227
|
| Property | Value |
|
|
226
228
|
|---|---|
|
|
@@ -229,6 +231,17 @@ Calls a function and waits for its result. ARGS is JSON text and is checked agai
|
|
|
229
231
|
| `NAME` | String, default: `add` |
|
|
230
232
|
| `ARGS` | String, default: `{"a":1,"b":2}` |
|
|
231
233
|
|
|
234
|
+
### `call [FUNCTION] with [ARGS]`
|
|
235
|
+
|
|
236
|
+
Calls a function chosen from the functions this sprite can call: its own functions and the functions for all sprites. Otherwise the same as `call function`.
|
|
237
|
+
|
|
238
|
+
| Property | Value |
|
|
239
|
+
|---|---|
|
|
240
|
+
| Type | Reporter |
|
|
241
|
+
| Opcode | `callFunctionFromMenu` |
|
|
242
|
+
| `FUNCTION` | String, default: ``, choices: the functions this sprite can call |
|
|
243
|
+
| `ARGS` | String, default: `{}` |
|
|
244
|
+
|
|
232
245
|
### `start function [NAME] with [ARGS]`
|
|
233
246
|
|
|
234
247
|
Starts a function without waiting and reports a promise reference as JSON text.
|
|
@@ -272,7 +285,7 @@ Reports whether a started function has finished, without waiting.
|
|
|
272
285
|
|
|
273
286
|
### `function [NAME] defined?`
|
|
274
287
|
|
|
275
|
-
Reports whether
|
|
288
|
+
Reports whether this sprite can call a function with this name: one of its own functions or a function for all sprites.
|
|
276
289
|
|
|
277
290
|
| Property | Value |
|
|
278
291
|
|---|---|
|
|
@@ -295,10 +308,16 @@ Reports the most recent function error, or an empty string.
|
|
|
295
308
|
|
|
296
309
|
| Situation | Behavior |
|
|
297
310
|
|---|---|
|
|
298
|
-
|
|
|
299
|
-
|
|
|
300
|
-
|
|
|
301
|
-
| A
|
|
311
|
+
| Scope | A new `define function` hat is for this sprite only: scripts of that sprite (or the stage), and its clones, can call it. Choose all sprites to call it from anywhere, including tools. Hats saved before scopes existed are for all sprites. |
|
|
312
|
+
| Function names | A name for all sprites is unique in the project. A name for one sprite is unique in that sprite and must differ from every name for all sprites. Different sprites may each have a function of the same name. |
|
|
313
|
+
| Which sprite runs the function | A sprite's own function runs as the caller (a clone runs it as itself). A function for all sprites runs as the sprite or stage that defines it. |
|
|
314
|
+
| A sprite calls another sprite's function | The call fails with `Function f belongs to Cat; make it for all sprites to call it from here.` |
|
|
315
|
+
| A call starts (TurboWarp Plus runtime) | The function's script starts directly and runs inside the calling block. |
|
|
316
|
+
| A call starts (stock TurboWarp) | Every `define function` hat is started; only the one whose NAME matches continues. |
|
|
317
|
+
| Timing (TurboWarp Plus runtime) | A function that does not wait finishes within the call, like a custom block that runs without screen refresh. A function that waits, or a call nested deeper than 128 levels, settles on a later frame. |
|
|
318
|
+
| Timing (stock TurboWarp) | Each call takes at least one frame, because the function runs as its own script. Use custom blocks for tight loops. |
|
|
319
|
+
| Several calls to the same function | On the TurboWarp Plus runtime, each call runs on its own. On stock TurboWarp, they run one at a time in order; different functions run concurrently. |
|
|
320
|
+
| A function calls itself, directly or through other functions | Works on the TurboWarp Plus runtime. On stock TurboWarp, the call fails with `Reentrant call: a -> b -> a`; use a custom block for recursion there. |
|
|
302
321
|
| Arguments do not match the schema | The call fails before the script starts; `last function error` explains which field. |
|
|
303
322
|
| A return value does not match RETURNS | The call fails; `last function error` reports the expected type and JSON path. Ending without `return` is checked as `null`. |
|
|
304
323
|
| The script ends without `return` | The result is empty (`null`). |
|
package/dist/composition.js
CHANGED
|
@@ -115,12 +115,23 @@ function deepEqual(left, right) {
|
|
|
115
115
|
function asRecord(value) {
|
|
116
116
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
117
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Calls nested deeper than this run on later frames instead of inside the calling block, so deep
|
|
120
|
+
* recursion cannot overflow the JavaScript stack.
|
|
121
|
+
*/
|
|
122
|
+
var MAX_SYNC_DEPTH = 128;
|
|
123
|
+
function outcomeToPromise(outcome) {
|
|
124
|
+
if (outcome.state === "fulfilled") return Promise.resolve(outcome.value);
|
|
125
|
+
if (outcome.state === "rejected") return Promise.reject(outcome.error);
|
|
126
|
+
return outcome.promise;
|
|
127
|
+
}
|
|
118
128
|
var FunctionDispatcher = class {
|
|
119
129
|
constructor(runtime, options) {
|
|
120
130
|
this.runtime = runtime;
|
|
121
131
|
this.options = options;
|
|
122
132
|
this.queue = [];
|
|
123
133
|
this.running = /* @__PURE__ */ new Map();
|
|
134
|
+
this.direct = /* @__PURE__ */ new Set();
|
|
124
135
|
this.byThread = /* @__PURE__ */ new Map();
|
|
125
136
|
this.starting = null;
|
|
126
137
|
this.step = 0;
|
|
@@ -129,39 +140,62 @@ var FunctionDispatcher = class {
|
|
|
129
140
|
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
130
141
|
this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
|
|
131
142
|
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
|
|
143
|
+
const port = runtime.getThreadExecutionPort?.();
|
|
144
|
+
this.port = port?.version === 1 ? port : null;
|
|
132
145
|
runtime.on("AFTER_EXECUTE", this.onAfterExecute);
|
|
133
146
|
runtime.on("PROJECT_STOP_ALL", this.onStopAll);
|
|
134
147
|
}
|
|
148
|
+
/** True when calls run inside the calling block and may recurse. */
|
|
149
|
+
get runsSynchronously() {
|
|
150
|
+
return this.port !== null;
|
|
151
|
+
}
|
|
135
152
|
/**
|
|
136
153
|
* Starts a named function. `caller` is the thread of the block making the call, if any; it is used
|
|
137
154
|
* to detect reentrant calls.
|
|
138
155
|
*/
|
|
139
156
|
invoke(name, args, caller, returnSchema) {
|
|
140
|
-
|
|
157
|
+
return outcomeToPromise(this.invokeNow({
|
|
158
|
+
name,
|
|
159
|
+
args,
|
|
160
|
+
caller,
|
|
161
|
+
returnSchema
|
|
162
|
+
}));
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Starts a named function and reports right away whether it already settled. With the port and a
|
|
166
|
+
* `script`, a function that does not wait settles before this returns.
|
|
167
|
+
*/
|
|
168
|
+
invokeNow(request) {
|
|
169
|
+
const { name, caller } = request;
|
|
170
|
+
if (!this.options.knownNames().has(name)) return {
|
|
171
|
+
state: "rejected",
|
|
172
|
+
error: /* @__PURE__ */ new Error(`Unknown function: ${name}`)
|
|
173
|
+
};
|
|
141
174
|
const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
|
|
142
|
-
|
|
143
|
-
return
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
invocation.timer = this.setTimer(() => this.settle(invocation, /* @__PURE__ */ new Error(`Function ${name} timed out.`)), this.timeoutMs);
|
|
157
|
-
this.queue.push(invocation);
|
|
158
|
-
this.pump();
|
|
159
|
-
});
|
|
175
|
+
const chain = [...parentChain, name];
|
|
176
|
+
if (this.port && request.script) return this.runDirect(this.port, request, chain);
|
|
177
|
+
if (parentChain.includes(name)) return {
|
|
178
|
+
state: "rejected",
|
|
179
|
+
error: /* @__PURE__ */ new Error(`Reentrant call: ${chain.join(" -> ")}. Recursion needs the TurboWarp Plus runtime; use a custom block for recursion here.`)
|
|
180
|
+
};
|
|
181
|
+
const invocation = this.createInvocation(request, chain);
|
|
182
|
+
this.armTimer(invocation);
|
|
183
|
+
this.queue.push(invocation);
|
|
184
|
+
this.pump();
|
|
185
|
+
return invocation.outcome ?? {
|
|
186
|
+
state: "pending",
|
|
187
|
+
promise: invocation.promise
|
|
188
|
+
};
|
|
160
189
|
}
|
|
161
190
|
/** Hat predicate: true only for the script that should run the invocation being started. */
|
|
162
191
|
matchHat(name, thread) {
|
|
192
|
+
if (!thread) return false;
|
|
193
|
+
const bound = this.byThread.get(thread);
|
|
194
|
+
if (bound) return bound.name === name.trim();
|
|
163
195
|
const invocation = this.starting;
|
|
164
|
-
if (!invocation ||
|
|
196
|
+
if (!invocation || invocation.name !== name.trim()) return false;
|
|
197
|
+
const script = invocation.script;
|
|
198
|
+
if (script && (thread.topBlock !== script.blockId || thread.target && thread.target !== script.target)) return false;
|
|
165
199
|
invocation.thread = thread;
|
|
166
200
|
this.byThread.set(thread, invocation);
|
|
167
201
|
this.starting = null;
|
|
@@ -178,17 +212,68 @@ var FunctionDispatcher = class {
|
|
|
178
212
|
this.settleWithValue(invocation, value);
|
|
179
213
|
}
|
|
180
214
|
cancelAll(reason) {
|
|
181
|
-
for (const invocation of [
|
|
215
|
+
for (const invocation of [
|
|
216
|
+
...this.queue,
|
|
217
|
+
...this.running.values(),
|
|
218
|
+
...this.direct
|
|
219
|
+
]) this.settle(invocation, new Error(reason));
|
|
182
220
|
if (this.starting) this.settle(this.starting, new Error(reason));
|
|
183
221
|
}
|
|
184
222
|
get pendingCount() {
|
|
185
|
-
return this.queue.length + this.running.size;
|
|
223
|
+
return this.queue.length + this.running.size + this.direct.size;
|
|
186
224
|
}
|
|
187
225
|
release() {
|
|
188
226
|
this.cancelAll("Named functions were released.");
|
|
189
227
|
this.runtime.off?.("AFTER_EXECUTE", this.onAfterExecute);
|
|
190
228
|
this.runtime.off?.("PROJECT_STOP_ALL", this.onStopAll);
|
|
191
229
|
}
|
|
230
|
+
runDirect(port, request, chain) {
|
|
231
|
+
const invocation = this.createInvocation(request, chain);
|
|
232
|
+
invocation.promise.catch(() => void 0);
|
|
233
|
+
const script = request.script;
|
|
234
|
+
try {
|
|
235
|
+
const thread = port.startScript(script.blockId, script.target);
|
|
236
|
+
invocation.thread = thread;
|
|
237
|
+
this.byThread.set(thread, invocation);
|
|
238
|
+
this.direct.add(invocation);
|
|
239
|
+
if (chain.length <= 128 && port.runNow(thread) === "done") this.settleWithValue(invocation, null);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
this.settle(invocation, error instanceof Error ? error : new Error(String(error)));
|
|
242
|
+
}
|
|
243
|
+
if (invocation.outcome) return invocation.outcome;
|
|
244
|
+
this.armTimer(invocation);
|
|
245
|
+
return {
|
|
246
|
+
state: "pending",
|
|
247
|
+
promise: invocation.promise
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
createInvocation(request, chain) {
|
|
251
|
+
let resolve = () => void 0;
|
|
252
|
+
let reject = () => void 0;
|
|
253
|
+
const promise = new Promise((resolvePromise, rejectPromise) => {
|
|
254
|
+
resolve = resolvePromise;
|
|
255
|
+
reject = rejectPromise;
|
|
256
|
+
});
|
|
257
|
+
return {
|
|
258
|
+
name: request.name,
|
|
259
|
+
args: request.args,
|
|
260
|
+
...request.returnSchema === void 0 ? {} : { returnSchema: request.returnSchema },
|
|
261
|
+
chain,
|
|
262
|
+
...request.script ? { script: request.script } : {},
|
|
263
|
+
promise,
|
|
264
|
+
resolve,
|
|
265
|
+
reject,
|
|
266
|
+
thread: null,
|
|
267
|
+
startedAtStep: -1,
|
|
268
|
+
timer: null,
|
|
269
|
+
settled: false,
|
|
270
|
+
outcome: null
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
armTimer(invocation) {
|
|
274
|
+
if (invocation.settled) return;
|
|
275
|
+
invocation.timer = this.setTimer(() => this.settle(invocation, /* @__PURE__ */ new Error(`Function ${invocation.name} timed out.`)), this.timeoutMs);
|
|
276
|
+
}
|
|
192
277
|
pump() {
|
|
193
278
|
if (this.starting) return;
|
|
194
279
|
const index = this.queue.findIndex((invocation) => !this.running.has(invocation.name));
|
|
@@ -204,20 +289,32 @@ var FunctionDispatcher = class {
|
|
|
204
289
|
this.step += 1;
|
|
205
290
|
const starting = this.starting;
|
|
206
291
|
if (starting && this.step - starting.startedAtStep > 2) this.settle(starting, /* @__PURE__ */ new Error(`Function ${starting.name} did not start. Is its script already running?`));
|
|
207
|
-
for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
|
|
292
|
+
for (const invocation of [...this.running.values(), ...this.direct]) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
|
|
208
293
|
this.pump();
|
|
209
294
|
}
|
|
210
295
|
settle(invocation, error, value) {
|
|
211
296
|
if (invocation.settled) return;
|
|
212
297
|
invocation.settled = true;
|
|
213
|
-
this.clearTimer(invocation.timer);
|
|
298
|
+
if (invocation.timer !== null) this.clearTimer(invocation.timer);
|
|
214
299
|
const queued = this.queue.indexOf(invocation);
|
|
215
300
|
if (queued >= 0) this.queue.splice(queued, 1);
|
|
216
301
|
if (this.running.get(invocation.name) === invocation) this.running.delete(invocation.name);
|
|
302
|
+
this.direct.delete(invocation);
|
|
217
303
|
if (invocation.thread) this.byThread.delete(invocation.thread);
|
|
218
304
|
if (this.starting === invocation) this.starting = null;
|
|
219
|
-
if (error)
|
|
220
|
-
|
|
305
|
+
if (error) {
|
|
306
|
+
invocation.outcome = {
|
|
307
|
+
state: "rejected",
|
|
308
|
+
error
|
|
309
|
+
};
|
|
310
|
+
invocation.reject(error);
|
|
311
|
+
} else {
|
|
312
|
+
invocation.outcome = {
|
|
313
|
+
state: "fulfilled",
|
|
314
|
+
value
|
|
315
|
+
};
|
|
316
|
+
invocation.resolve(value);
|
|
317
|
+
}
|
|
221
318
|
}
|
|
222
319
|
settleWithValue(invocation, value) {
|
|
223
320
|
if (invocation.returnSchema !== void 0) {
|
|
@@ -306,9 +403,8 @@ var MAX_DESCRIPTION_LENGTH = 1024;
|
|
|
306
403
|
* tool contract sent to the model before any script runs, so they must be literal text.
|
|
307
404
|
*/
|
|
308
405
|
function scanFunctionDefinitions(targets, hatOpcode, options = {}) {
|
|
309
|
-
const
|
|
406
|
+
const scanned = [];
|
|
310
407
|
const errors = [];
|
|
311
|
-
const seen = /* @__PURE__ */ new Map();
|
|
312
408
|
for (const target of targets) {
|
|
313
409
|
if (target.isOriginal === false) continue;
|
|
314
410
|
const targetName = target.getName?.() ?? (target.isStage ? "Stage" : "sprite");
|
|
@@ -317,22 +413,103 @@ function scanFunctionDefinitions(targets, hatOpcode, options = {}) {
|
|
|
317
413
|
if (block.opcode !== hatOpcode || block.topLevel === false) continue;
|
|
318
414
|
const where = `${targetName} (block ${block.id})`;
|
|
319
415
|
try {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
functions.push(definition);
|
|
416
|
+
scanned.push({
|
|
417
|
+
definition: readDefinition(block, blocks, targetName, target, options),
|
|
418
|
+
where
|
|
419
|
+
});
|
|
325
420
|
} catch (error) {
|
|
326
421
|
errors.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
|
|
327
422
|
}
|
|
328
423
|
}
|
|
329
424
|
}
|
|
425
|
+
const functions = [];
|
|
426
|
+
const globals = /* @__PURE__ */ new Map();
|
|
427
|
+
for (const { definition, where } of scanned) {
|
|
428
|
+
if (definition.scope !== "global") continue;
|
|
429
|
+
const previous = globals.get(definition.name);
|
|
430
|
+
if (previous !== void 0) {
|
|
431
|
+
errors.push(`${where}: function "${definition.name}" is already defined in ${previous}`);
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
globals.set(definition.name, where);
|
|
435
|
+
functions.push(definition);
|
|
436
|
+
}
|
|
437
|
+
const locals = /* @__PURE__ */ new Map();
|
|
438
|
+
for (const { definition, where } of scanned) {
|
|
439
|
+
if (definition.scope !== "sprite") continue;
|
|
440
|
+
const global = globals.get(definition.name);
|
|
441
|
+
if (global !== void 0) {
|
|
442
|
+
errors.push(`${where}: function "${definition.name}" is already defined for all sprites in ${global}`);
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
const own = locals.get(definition.target) ?? /* @__PURE__ */ new Map();
|
|
446
|
+
locals.set(definition.target, own);
|
|
447
|
+
const previous = own.get(definition.name);
|
|
448
|
+
if (previous !== void 0) {
|
|
449
|
+
errors.push(`${where}: function "${definition.name}" is already defined in ${previous}`);
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
own.set(definition.name, where);
|
|
453
|
+
functions.push(definition);
|
|
454
|
+
}
|
|
330
455
|
functions.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
|
|
331
456
|
return {
|
|
332
457
|
functions,
|
|
333
458
|
errors
|
|
334
459
|
};
|
|
335
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* Writes `SCOPE = global` into `define function` hats saved before SCOPE existed, so the stored
|
|
463
|
+
* value matches what the block shows (the menu's first choice) and a change made on the block is
|
|
464
|
+
* kept: the VM ignores a change to a field the block does not have. Each sprite is checked once;
|
|
465
|
+
* pass the same `checked` set every time.
|
|
466
|
+
*/
|
|
467
|
+
function upgradeLegacyScopes(targets, hatOpcode, checked) {
|
|
468
|
+
let upgraded = 0;
|
|
469
|
+
for (const target of targets) {
|
|
470
|
+
if (target.isOriginal === false || checked.has(target)) continue;
|
|
471
|
+
checked.add(target);
|
|
472
|
+
for (const block of Object.values(target.blocks._blocks)) {
|
|
473
|
+
if (block.opcode !== hatOpcode || block.topLevel === false || block.fields?.SCOPE) continue;
|
|
474
|
+
block.fields = {
|
|
475
|
+
...block.fields,
|
|
476
|
+
SCOPE: {
|
|
477
|
+
name: "SCOPE",
|
|
478
|
+
value: "global"
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
upgraded += 1;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return upgraded;
|
|
485
|
+
}
|
|
486
|
+
/** True when both are the same sprite: the original, one of its clones, or the stage itself. */
|
|
487
|
+
function sameSprite(left, right) {
|
|
488
|
+
return left === right || left.sprite !== void 0 && left.sprite === right.sprite;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Finds the function a call names. A caller's own sprite function runs as the caller (a clone runs it
|
|
492
|
+
* as itself, as with a custom block); a global function runs as the sprite or stage that defines it.
|
|
493
|
+
* Without a caller (a call from outside the project), only global functions are visible.
|
|
494
|
+
*/
|
|
495
|
+
function resolveFunction(functions, name, caller) {
|
|
496
|
+
if (caller) {
|
|
497
|
+
const own = functions.find((definition) => definition.scope === "sprite" && definition.name === name && sameSprite(definition.target, caller));
|
|
498
|
+
if (own) return {
|
|
499
|
+
definition: own,
|
|
500
|
+
runAs: caller
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
const global = functions.find((definition) => definition.scope === "global" && definition.name === name);
|
|
504
|
+
return global ? {
|
|
505
|
+
definition: global,
|
|
506
|
+
runAs: global.target
|
|
507
|
+
} : void 0;
|
|
508
|
+
}
|
|
509
|
+
/** Functions a script of `caller` can call: its sprite's own functions, then the global ones. */
|
|
510
|
+
function visibleFunctions(functions, caller) {
|
|
511
|
+
return functions.filter((definition) => definition.scope === "global" || caller !== void 0 && sameSprite(definition.target, caller));
|
|
512
|
+
}
|
|
336
513
|
function toFunctionTools(functions) {
|
|
337
514
|
return functions.filter((definition) => definition.exportAs === "tool").map((definition) => ({
|
|
338
515
|
type: "function",
|
|
@@ -341,7 +518,7 @@ function toFunctionTools(functions) {
|
|
|
341
518
|
parameters: definition.parameters
|
|
342
519
|
}));
|
|
343
520
|
}
|
|
344
|
-
function readDefinition(block, blocks, targetName, options) {
|
|
521
|
+
function readDefinition(block, blocks, targetName, target, options) {
|
|
345
522
|
const name = readLiteralInput(block, blocks, "NAME").trim();
|
|
346
523
|
if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
|
|
347
524
|
const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
|
|
@@ -351,16 +528,27 @@ function readDefinition(block, blocks, targetName, options) {
|
|
|
351
528
|
const returns = returnsText === void 0 || returnsText.trim() === "" ? void 0 : parseSchema(returnsText, "returns schema", false, options);
|
|
352
529
|
const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
|
|
353
530
|
if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
|
|
531
|
+
const scope = readScope(block);
|
|
532
|
+
if (exportAs === "tool" && scope !== "global") throw new Error("a function exported as a tool must be for all sprites");
|
|
354
533
|
return {
|
|
355
534
|
name,
|
|
535
|
+
scope,
|
|
356
536
|
description,
|
|
357
537
|
parameters,
|
|
358
538
|
...returns ? { returns } : {},
|
|
359
539
|
exportAs,
|
|
360
540
|
targetName,
|
|
541
|
+
target,
|
|
361
542
|
blockId: block.id
|
|
362
543
|
};
|
|
363
544
|
}
|
|
545
|
+
/** SCOPE is a menu field. Hats saved before it existed have none and keep their global meaning. */
|
|
546
|
+
function readScope(block) {
|
|
547
|
+
const value = block.fields?.SCOPE?.value;
|
|
548
|
+
if (value === void 0 || value === null || value === "global") return "global";
|
|
549
|
+
if (value === "sprite") return "sprite";
|
|
550
|
+
throw new Error(`unknown function scope "${String(value)}"`);
|
|
551
|
+
}
|
|
364
552
|
/**
|
|
365
553
|
* SCHEMA and RETURNS hold either JSON Schema text or, when the consumer supports it, the name of a
|
|
366
554
|
* `define schema` hat. Text that is not JSON is treated as a name, so existing JSON projects are
|
|
@@ -733,17 +921,39 @@ var NamedFunctionsImpl = class {
|
|
|
733
921
|
if (errors.length > 0) throw new Error(`Invalid function definitions: ${errors.join("; ")}`);
|
|
734
922
|
return toFunctionTools(this.scan().functions);
|
|
735
923
|
}
|
|
736
|
-
isDefined(name) {
|
|
737
|
-
return this.scan().functions.
|
|
924
|
+
isDefined(name, caller) {
|
|
925
|
+
return resolveFunction(this.scan().functions, name.trim(), caller) !== void 0;
|
|
926
|
+
}
|
|
927
|
+
visible(caller) {
|
|
928
|
+
const functions = visibleFunctions(this.scan().functions, caller);
|
|
929
|
+
return [...functions.filter((definition) => definition.scope === "sprite"), ...functions.filter((definition) => definition.scope === "global")];
|
|
930
|
+
}
|
|
931
|
+
get runsSynchronously() {
|
|
932
|
+
return this.dispatcher.runsSynchronously;
|
|
738
933
|
}
|
|
739
934
|
call(name, args, options = {}) {
|
|
935
|
+
return outcomeToPromise(this.callNow(name, args, options));
|
|
936
|
+
}
|
|
937
|
+
callNow(name, args, options = {}) {
|
|
740
938
|
const trimmed = name.trim();
|
|
741
|
-
const
|
|
742
|
-
|
|
743
|
-
|
|
939
|
+
const scan = this.scan();
|
|
940
|
+
const caller = options.caller?.target;
|
|
941
|
+
const resolved = resolveFunction(scan.functions, trimmed, caller);
|
|
942
|
+
if (!resolved) return rejected(unknownFunctionMessage(scan.functions, trimmed, caller));
|
|
943
|
+
const { definition, runAs } = resolved;
|
|
944
|
+
if (options.exportedOnly && definition.exportAs !== "tool") return rejected(`Function ${trimmed} is not exported as a tool.`);
|
|
744
945
|
const errors = validateAgainstSchema(args, definition.parameters);
|
|
745
|
-
if (errors.length > 0) return
|
|
746
|
-
return this.dispatcher.
|
|
946
|
+
if (errors.length > 0) return rejected(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`);
|
|
947
|
+
return this.dispatcher.invokeNow({
|
|
948
|
+
name: trimmed,
|
|
949
|
+
args,
|
|
950
|
+
caller: options.caller,
|
|
951
|
+
returnSchema: definition.returns,
|
|
952
|
+
script: {
|
|
953
|
+
target: runAs,
|
|
954
|
+
blockId: definition.blockId
|
|
955
|
+
}
|
|
956
|
+
});
|
|
747
957
|
}
|
|
748
958
|
start(name, args, options = {}) {
|
|
749
959
|
const id = `p_${this.nextPromiseId++}`;
|
|
@@ -810,8 +1020,20 @@ var NamedFunctionsImpl = class {
|
|
|
810
1020
|
}
|
|
811
1021
|
}
|
|
812
1022
|
};
|
|
1023
|
+
/** Names the sprite that owns a function the caller cannot see, so the fix is obvious. */
|
|
1024
|
+
function unknownFunctionMessage(functions, name, caller) {
|
|
1025
|
+
const elsewhere = functions.find((definition) => definition.name === name);
|
|
1026
|
+
if (!elsewhere) return `Unknown function: ${name}`;
|
|
1027
|
+
return caller ? `Function ${name} belongs to ${elsewhere.targetName}; make it for all sprites to call it from here.` : `Function ${name} belongs to ${elsewhere.targetName}; only functions for all sprites can be called from outside.`;
|
|
1028
|
+
}
|
|
1029
|
+
function rejected(message) {
|
|
1030
|
+
return {
|
|
1031
|
+
state: "rejected",
|
|
1032
|
+
error: new Error(message)
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
813
1035
|
function messageOf(error) {
|
|
814
1036
|
return error instanceof Error ? error.message : String(error);
|
|
815
1037
|
}
|
|
816
1038
|
//#endregion
|
|
817
|
-
export { FUNCTION_NAME_PATTERN, MAX_SCHEMA_REFERENCE_DEPTH, SCHEMA_NAME_PATTERN, SCHEMA_VERSION_PATTERN, createNamedFunctions, parseJsonOrText, parseSchemaReference, readArgumentPath, resolveSchemaReference, scanFunctionDefinitions, scanSchemaDefinitions, toFunctionTools, toScratchValue, validateAgainstSchema, validateSchemaDefinition };
|
|
1039
|
+
export { FUNCTION_NAME_PATTERN, MAX_SCHEMA_REFERENCE_DEPTH, MAX_SYNC_DEPTH, SCHEMA_NAME_PATTERN, SCHEMA_VERSION_PATTERN, createNamedFunctions, parseJsonOrText, parseSchemaReference, readArgumentPath, resolveFunction, resolveSchemaReference, sameSprite, scanFunctionDefinitions, scanSchemaDefinitions, toFunctionTools, toScratchValue, upgradeLegacyScopes, validateAgainstSchema, validateSchemaDefinition, visibleFunctions };
|