@kubohiroya/turbowarp-plus-editor-project-model 0.0.0-stage → 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 ADDED
@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
package/README.ja.md ADDED
@@ -0,0 +1,21 @@
1
+ # TurboWarp Plus Editor Project Model
2
+
3
+ [English](README.md)
4
+
5
+ TurboWarp Plus Editor で、実行中の Scratch 作品を画面なしで読み取り、編集する。どの関数も VM と対象(スプライト・ステージ)を構造的な型で受け取るので、このパッケージは VM・GUI・React・Dockview を import しない。パネルと Editor の作品全体の検索が同じ関数を呼ぶため、作品の中身について両者の判断が食い違わない。
6
+
7
+ ## 入口
8
+
9
+ | import | 内容 |
10
+ | --- | --- |
11
+ | `@kubohiroya/turbowarp-plus-editor-project-model/project-messages` | どのブロックが各メッセージを送り、受け取るか(`scanProjectMessages`・`scanTargetMessages`・`projectMessageGraph`・`messageReference`)と、メッセージの名前を変えられるか(`checkMessageRename`) |
12
+ | `@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit` | 編集中のスプライトまたはステージの変数の作成・名前変更・削除(`editSpriteVariable`)。重複する名前を拒み、クラウド変数の接頭辞を保ち、ブロックが使っている変数は削除しない |
13
+ | `@kubohiroya/turbowarp-plus-editor-project-model` | 上の両方 |
14
+
15
+ ## 検証
16
+
17
+ `npm test` でビルドし、単体テストを実行する。
18
+
19
+ ## ライセンス
20
+
21
+ MPL-2.0。`@kubohiroya/turbowarp-plus-editor-layout` から切り出したコードで、その履歴をこのリポジトリに残している。
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # TurboWarp Plus Editor Project Model
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [日本語](README.ja.md)
4
+
5
+ Reads and edits a running Scratch project for TurboWarp Plus Editor, without any UI. Every function takes the VM and its targets through structural types, so this package never imports the VM, the GUI, React, or Dockview. Panels and the Editor's project search call the same functions, so they always agree on what a project contains.
6
+
7
+ ## Entry points
8
+
9
+ | Import | Contents |
10
+ | --- | --- |
11
+ | `@kubohiroya/turbowarp-plus-editor-project-model/project-messages` | Which blocks send or receive each broadcast message (`scanProjectMessages`, `scanTargetMessages`, `projectMessageGraph`, `messageReference`), and whether a message can be renamed (`checkMessageRename`) |
12
+ | `@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit` | Creating, renaming and deleting a variable of the editing sprite or the stage (`editSpriteVariable`). It refuses duplicate names, keeps the cloud prefix, and refuses to delete a variable that a block uses |
13
+ | `@kubohiroya/turbowarp-plus-editor-project-model` | Both of the above |
14
+
15
+ ## Verification
16
+
17
+ Run `npm test` to build the package and run the unit tests.
18
+
19
+ ## License
20
+
21
+ MPL-2.0. This code was split out of `@kubohiroya/turbowarp-plus-editor-layout`, and its history is kept in this repository.
@@ -0,0 +1,2 @@
1
+ export * from './project-messages.ts';
2
+ export * from './sprite-variable-edit.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./project-messages.js";
2
+ export * from "./sprite-variable-edit.js";
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Broadcast message scanning for the message section and for the host's project search.
3
+ *
4
+ * This module is the only place that decides which block sends or receives a message, so the
5
+ * section and the host's search can never disagree. It takes the runtime through structural
6
+ * types and never imports the VM or the GUI.
7
+ */
8
+ type Field = {
9
+ id?: string;
10
+ value?: unknown;
11
+ };
12
+ type Block = {
13
+ id: string;
14
+ opcode: string;
15
+ next?: string | null;
16
+ shadow?: boolean;
17
+ fields?: Record<string, Field>;
18
+ inputs?: Record<string, {
19
+ block?: string | null;
20
+ shadow?: string | null;
21
+ }>;
22
+ };
23
+ type Blocks = {
24
+ getScripts(): readonly string[];
25
+ getBlock(id: string): Block | undefined;
26
+ };
27
+ type MessageVariable = {
28
+ name: string;
29
+ type?: string;
30
+ };
31
+ export type MessageTarget = {
32
+ id: string;
33
+ isStage: boolean;
34
+ isOriginal: boolean;
35
+ getName(): string;
36
+ variables: Record<string, MessageVariable>;
37
+ blocks: Blocks;
38
+ };
39
+ export type MessageProject = {
40
+ targets: readonly MessageTarget[];
41
+ };
42
+ export declare const broadcastVariableType = "broadcast_msg";
43
+ export declare const sendOpcodes: readonly ["event_broadcast", "event_broadcastandwait"];
44
+ export declare const receiveOpcode = "event_whenbroadcastreceived";
45
+ export type MessageDirection = 'send' | 'receive';
46
+ export interface MessageReference {
47
+ direction: MessageDirection;
48
+ /** The broadcast_msg variable this block names, when it names one. */
49
+ id?: string;
50
+ /** The dropdown's own text, which is what the project file stores. */
51
+ fieldValue: string;
52
+ /** The owning variable's name when it resolves, otherwise the dropdown text. */
53
+ name: string;
54
+ /** `event_broadcastandwait` waits for every receiving script to finish. */
55
+ wait: boolean;
56
+ }
57
+ /**
58
+ * The judgement for a single block. Returns nothing for blocks that are not broadcast blocks and
59
+ * for a broadcast whose message is a reporter, because that message is only known while running.
60
+ */
61
+ export declare function messageReference(target: MessageTarget, block: Block, stage?: MessageTarget): MessageReference | undefined;
62
+ export interface MessageUse extends MessageReference {
63
+ key: string;
64
+ targetId: string;
65
+ targetName: string;
66
+ isStage: boolean;
67
+ blockId: string;
68
+ opcode: string;
69
+ /** The top block of the script holding this block, so the host can open the whole script. */
70
+ scriptId: string;
71
+ scriptOpcode: string;
72
+ /** When that script starts with a "when I receive" hat, the message it waits for. */
73
+ scriptMessageName?: string;
74
+ }
75
+ export type MessageStatus = 'both' | 'sendOnly' | 'receiveOnly' | 'unused';
76
+ export interface ProjectMessage {
77
+ /** Stable identity for a message: its variable id, or its name when no variable owns it. */
78
+ key: string;
79
+ id?: string;
80
+ name: string;
81
+ status: MessageStatus;
82
+ sends: readonly MessageUse[];
83
+ receives: readonly MessageUse[];
84
+ }
85
+ /** Every message in the project, with the places that send and receive it. */
86
+ export declare function scanProjectMessages(project: MessageProject): readonly ProjectMessage[];
87
+ export type MessageRenameError = 'emptyName' | 'duplicateName' | 'unavailable';
88
+ export type MessageRenameCheck = {
89
+ error: MessageRenameError;
90
+ } | {
91
+ name: string;
92
+ } | {
93
+ unchanged: true;
94
+ };
95
+ /**
96
+ * Whether a message may take this name. A message is owned by the stage, so its name has to be
97
+ * free across the whole project.
98
+ */
99
+ export declare function checkMessageRename(messages: readonly ProjectMessage[], message: ProjectMessage, name: string): MessageRenameCheck;
100
+ export interface MessageGraphNode {
101
+ id: string;
102
+ name: string;
103
+ isStage: boolean;
104
+ }
105
+ export interface MessageGraphEdge {
106
+ direction: MessageDirection;
107
+ targetId: string;
108
+ messageKey: string;
109
+ /** How many blocks in that target send or receive the message. */
110
+ count: number;
111
+ }
112
+ export interface MessageGraph {
113
+ targets: readonly MessageGraphNode[];
114
+ messages: readonly Pick<ProjectMessage, 'key' | 'id' | 'name' | 'status'>[];
115
+ edges: readonly MessageGraphEdge[];
116
+ }
117
+ /** The whole project as sprite or stage, message, sprite or stage. Isolated messages are kept. */
118
+ export declare function projectMessageGraph(project: MessageProject, messages?: readonly ProjectMessage[]): MessageGraph;
119
+ export interface TargetMessages {
120
+ targetId: string;
121
+ isStage: boolean;
122
+ /** Blocks in this target that send a message. */
123
+ sends: readonly MessageUse[];
124
+ /** Hats in this target that receive a message. */
125
+ receives: readonly MessageUse[];
126
+ /** Messages the project uses or declares that this target neither sends nor receives. */
127
+ elsewhere: readonly ProjectMessage[];
128
+ /** Every message in the project, so a rename can check the names already taken. */
129
+ messages: readonly ProjectMessage[];
130
+ /** The relationship diagram, which only the stage shows. */
131
+ graph?: MessageGraph;
132
+ }
133
+ /** What one sprite or the stage sends and receives. The stage also carries the project diagram. */
134
+ export declare function scanTargetMessages(project: MessageProject, targetId: string): TargetMessages;
135
+ export {};
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Broadcast message scanning for the message section and for the host's project search.
3
+ *
4
+ * This module is the only place that decides which block sends or receives a message, so the
5
+ * section and the host's search can never disagree. It takes the runtime through structural
6
+ * types and never imports the VM or the GUI.
7
+ */
8
+ export const broadcastVariableType = 'broadcast_msg';
9
+ export const sendOpcodes = ['event_broadcast', 'event_broadcastandwait'];
10
+ export const receiveOpcode = 'event_whenbroadcastreceived';
11
+ /**
12
+ * The judgement for a single block. Returns nothing for blocks that are not broadcast blocks and
13
+ * for a broadcast whose message is a reporter, because that message is only known while running.
14
+ */
15
+ export function messageReference(target, block, stage) {
16
+ const direction = block.opcode === receiveOpcode ? 'receive' :
17
+ sendOpcodes.includes(block.opcode) ? 'send' : undefined;
18
+ if (!direction)
19
+ return undefined;
20
+ const input = block.inputs?.BROADCAST_INPUT;
21
+ const menu = input?.block ? target.blocks.getBlock(input.block) : undefined;
22
+ const field = block.fields?.BROADCAST_OPTION ?? menu?.fields?.BROADCAST_OPTION;
23
+ if (!field)
24
+ return undefined;
25
+ const fieldValue = String(field.value ?? '');
26
+ const owner = field.id ? target.variables[field.id] ?? stage?.variables[field.id] : undefined;
27
+ return {
28
+ direction,
29
+ id: field.id,
30
+ fieldValue,
31
+ name: owner?.type === broadcastVariableType && owner.name ? owner.name : fieldValue,
32
+ wait: block.opcode === 'event_broadcastandwait'
33
+ };
34
+ }
35
+ const messageKey = (id, name) => id ?? 'name:' + name;
36
+ function* walkScripts(blocks) {
37
+ for (const rootId of blocks.getScripts()) {
38
+ const root = blocks.getBlock(rootId);
39
+ if (!root)
40
+ continue;
41
+ const pending = [rootId];
42
+ const seen = new Set();
43
+ while (pending.length) {
44
+ const id = pending.pop();
45
+ if (!id || seen.has(id))
46
+ continue;
47
+ seen.add(id);
48
+ const block = blocks.getBlock(id);
49
+ if (!block || block.shadow)
50
+ continue;
51
+ yield { root, block };
52
+ if (block.next)
53
+ pending.push(block.next);
54
+ for (const input of Object.values(block.inputs ?? {})) {
55
+ // A shadow holds a dropdown or a literal, which messageReference reads directly.
56
+ if (input.block && input.block !== input.shadow)
57
+ pending.push(input.block);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ const statusOf = (sends, receives) => sends.length && receives.length ? 'both' : sends.length ? 'sendOnly' : receives.length ? 'receiveOnly' : 'unused';
63
+ /** Every message in the project, with the places that send and receive it. */
64
+ export function scanProjectMessages(project) {
65
+ const stage = project.targets.find(target => target.isStage);
66
+ const found = new Map();
67
+ const ensure = (id, name) => {
68
+ const key = messageKey(id, name);
69
+ let entry = found.get(key);
70
+ if (!entry) {
71
+ entry = { key, id, name, sends: [], receives: [] };
72
+ found.set(key, entry);
73
+ }
74
+ // A message created but never used still carries its variable name.
75
+ if (name && entry.name !== name)
76
+ entry.name = name;
77
+ return entry;
78
+ };
79
+ for (const target of project.targets) {
80
+ if (!target.isOriginal)
81
+ continue;
82
+ for (const [id, variable] of Object.entries(target.variables)) {
83
+ if (variable.type === broadcastVariableType)
84
+ ensure(id, variable.name);
85
+ }
86
+ }
87
+ for (const target of project.targets) {
88
+ if (!target.isOriginal)
89
+ continue;
90
+ const targetName = target.getName();
91
+ for (const { root, block } of walkScripts(target.blocks)) {
92
+ const reference = messageReference(target, block, stage);
93
+ if (!reference)
94
+ continue;
95
+ const hat = root.opcode === receiveOpcode ? messageReference(target, root, stage) : undefined;
96
+ const entry = ensure(reference.id, reference.name);
97
+ const use = {
98
+ ...reference,
99
+ key: entry.key,
100
+ targetId: target.id,
101
+ targetName,
102
+ isStage: target.isStage,
103
+ blockId: block.id,
104
+ opcode: block.opcode,
105
+ scriptId: root.id,
106
+ scriptOpcode: root.opcode,
107
+ scriptMessageName: hat?.name
108
+ };
109
+ (reference.direction === 'send' ? entry.sends : entry.receives).push(use);
110
+ }
111
+ }
112
+ return [...found.values()]
113
+ .map(({ key, id, name, sends, receives }) => ({ key, id, name, sends, receives, status: statusOf(sends, receives) }))
114
+ .sort((left, right) => left.name.localeCompare(right.name) || left.key.localeCompare(right.key));
115
+ }
116
+ /**
117
+ * Whether a message may take this name. A message is owned by the stage, so its name has to be
118
+ * free across the whole project.
119
+ */
120
+ export function checkMessageRename(messages, message, name) {
121
+ const next = name.trim();
122
+ if (!next)
123
+ return { error: 'emptyName' };
124
+ if (next === message.name)
125
+ return { unchanged: true };
126
+ const taken = next.toLocaleLowerCase();
127
+ if (messages.some(other => other.key !== message.key && other.name.toLocaleLowerCase() === taken)) {
128
+ return { error: 'duplicateName' };
129
+ }
130
+ return { name: next };
131
+ }
132
+ /** The whole project as sprite or stage, message, sprite or stage. Isolated messages are kept. */
133
+ export function projectMessageGraph(project, messages = scanProjectMessages(project)) {
134
+ const edges = new Map();
135
+ for (const message of messages) {
136
+ for (const use of [...message.sends, ...message.receives]) {
137
+ const key = use.direction + '\u0000' + use.targetId + '\u0000' + message.key;
138
+ const edge = edges.get(key);
139
+ if (edge)
140
+ edge.count++;
141
+ else
142
+ edges.set(key, { direction: use.direction, targetId: use.targetId, messageKey: message.key, count: 1 });
143
+ }
144
+ }
145
+ return {
146
+ targets: project.targets.filter(target => target.isOriginal)
147
+ .map(target => ({ id: target.id, name: target.getName(), isStage: target.isStage })),
148
+ messages: messages.map(({ key, id, name, status }) => ({ key, id, name, status })),
149
+ edges: [...edges.values()]
150
+ };
151
+ }
152
+ /** What one sprite or the stage sends and receives. The stage also carries the project diagram. */
153
+ export function scanTargetMessages(project, targetId) {
154
+ const messages = scanProjectMessages(project);
155
+ const isStage = Boolean(project.targets.find(target => target.id === targetId)?.isStage);
156
+ const mine = (uses) => uses.filter(use => use.targetId === targetId);
157
+ const sends = messages.flatMap(message => mine(message.sends));
158
+ const receives = messages.flatMap(message => mine(message.receives));
159
+ return {
160
+ targetId,
161
+ isStage,
162
+ sends,
163
+ receives,
164
+ elsewhere: messages.filter(message => !message.sends.some(use => use.targetId === targetId) &&
165
+ !message.receives.some(use => use.targetId === targetId)),
166
+ messages,
167
+ graph: isStage ? projectMessageGraph(project, messages) : undefined
168
+ };
169
+ }
@@ -0,0 +1,66 @@
1
+ export type SpriteVariableEdit = {
2
+ type: 'create';
3
+ name: string;
4
+ } | {
5
+ type: 'rename';
6
+ id: string;
7
+ name: string;
8
+ } | {
9
+ type: 'delete';
10
+ id: string;
11
+ };
12
+ export type SpriteVariableEditError = 'emptyName' | 'duplicateName' | 'inUse' | 'unavailable';
13
+ type Variable = {
14
+ name: string;
15
+ type: string;
16
+ isCloud?: boolean;
17
+ };
18
+ type Block = {
19
+ opcode: string;
20
+ fields: Record<string, {
21
+ value: unknown;
22
+ }>;
23
+ inputs: Record<string, {
24
+ block: string | null;
25
+ shadow: string | null;
26
+ }>;
27
+ };
28
+ type VariableEvent = {
29
+ type: 'var_create';
30
+ varId: string;
31
+ varName: string;
32
+ varType: '';
33
+ isLocal: boolean;
34
+ isCloud: false;
35
+ } | {
36
+ type: 'var_rename';
37
+ varId: string;
38
+ newName: string;
39
+ } | {
40
+ type: 'var_delete';
41
+ varId: string;
42
+ };
43
+ type VariableTarget = {
44
+ id: string;
45
+ isStage: boolean;
46
+ isOriginal: boolean;
47
+ getName(): string;
48
+ variables: Record<string, Variable>;
49
+ blocks: {
50
+ _blocks: Record<string, Block>;
51
+ getAllVariableAndListReferences(): Record<string, unknown>;
52
+ blocklyListen(event: VariableEvent): void;
53
+ };
54
+ };
55
+ type VariableProject = {
56
+ editingTarget?: VariableTarget;
57
+ runtime: {
58
+ targets: readonly VariableTarget[];
59
+ getEditingTarget(): VariableTarget | null;
60
+ getTargetForStage(): VariableTarget | null;
61
+ };
62
+ refreshWorkspace(): void;
63
+ };
64
+ export declare const cloudVariablePrefix = "\u2601 ";
65
+ export declare function editSpriteVariable(vm: VariableProject, targetId: string, edit: SpriteVariableEdit): SpriteVariableEditError | void;
66
+ export {};
@@ -0,0 +1,53 @@
1
+ export const cloudVariablePrefix = '☁ ';
2
+ function isUsed(target, targets, id, name) {
3
+ const targetName = target.isStage ? '_stage_' : target.getName();
4
+ return targets.some(({ blocks }) => {
5
+ if (Object.hasOwn(blocks.getAllVariableAndListReferences(), id))
6
+ return true;
7
+ return Object.values(blocks._blocks).some(block => {
8
+ if (block.opcode !== 'sensing_of' || block.fields.PROPERTY?.value !== name)
9
+ return false;
10
+ const input = block.inputs.OBJECT;
11
+ if (!input?.block)
12
+ return false;
13
+ // A dynamic target can resolve to the variable's owner when the project runs.
14
+ return input.block !== input.shadow || blocks._blocks[input.block]?.fields.OBJECT?.value === targetName;
15
+ });
16
+ });
17
+ }
18
+ export function editSpriteVariable(vm, targetId, edit) {
19
+ const target = vm.editingTarget;
20
+ const { runtime } = vm;
21
+ if (!target || target.id !== targetId || runtime.getEditingTarget() !== target ||
22
+ !runtime.targets.includes(target) || (!target.isStage && !target.isOriginal))
23
+ return 'unavailable';
24
+ const variable = edit.type === 'create' ? undefined : target.variables[edit.id];
25
+ if (edit.type !== 'create' && variable?.type !== '')
26
+ return 'unavailable';
27
+ if (edit.type === 'delete') {
28
+ if (isUsed(target, runtime.targets, edit.id, variable.name))
29
+ return 'inUse';
30
+ target.blocks.blocklyListen({ type: 'var_delete', varId: edit.id });
31
+ }
32
+ else {
33
+ const name = edit.name.trim();
34
+ if (!name)
35
+ return 'emptyName';
36
+ const fullName = variable?.isCloud && !name.startsWith(cloudVariablePrefix) ? cloudVariablePrefix + name : name;
37
+ if (fullName === variable?.name)
38
+ return;
39
+ const scope = target.isStage ? runtime.targets.filter(item => item.isStage || item.isOriginal) :
40
+ [target, runtime.getTargetForStage()];
41
+ if (scope.some(owner => owner && Object.values(owner.variables).some(item => item.type === '' && item.name === fullName))) {
42
+ return 'duplicateName';
43
+ }
44
+ if (edit.type === 'create') {
45
+ const varId = Array.from(crypto.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('');
46
+ target.blocks.blocklyListen({ type: 'var_create', varId, varName: fullName, varType: '', isLocal: !target.isStage, isCloud: false });
47
+ }
48
+ else {
49
+ target.blocks.blocklyListen({ type: 'var_rename', varId: edit.id, newName: fullName });
50
+ }
51
+ }
52
+ vm.refreshWorkspace();
53
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-model",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "UI-free reads and edits of a running Scratch project for TurboWarp Plus Editor",
5
+ "type": "module",
6
+ "license": "MPL-2.0",
7
+ "author": "Hiroya Kubo",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kubohiroya/turbowarp-plus-editor-project-model.git"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./project-messages": {
18
+ "types": "./dist/project-messages.d.ts",
19
+ "default": "./dist/project-messages.js"
20
+ },
21
+ "./sprite-variable-edit": {
22
+ "types": "./dist/sprite-variable-edit.d.ts",
23
+ "default": "./dist/sprite-variable-edit.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "src",
29
+ "tsconfig.json",
30
+ "README.md",
31
+ "README.ja.md",
32
+ "LICENSE"
33
+ ],
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.json",
36
+ "prepare": "npm run build",
37
+ "test": "npm run build && node --test test/*.test.ts"
38
+ },
39
+ "devDependencies": {
40
+ "typescript": "6.0.3"
41
+ }
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './project-messages.ts';
2
+ export * from './sprite-variable-edit.ts';
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Broadcast message scanning for the message section and for the host's project search.
3
+ *
4
+ * This module is the only place that decides which block sends or receives a message, so the
5
+ * section and the host's search can never disagree. It takes the runtime through structural
6
+ * types and never imports the VM or the GUI.
7
+ */
8
+
9
+ type Field = {id?: string; value?: unknown};
10
+
11
+ type Block = {
12
+ id: string;
13
+ opcode: string;
14
+ next?: string | null;
15
+ shadow?: boolean;
16
+ fields?: Record<string, Field>;
17
+ inputs?: Record<string, {block?: string | null; shadow?: string | null}>;
18
+ };
19
+
20
+ type Blocks = {
21
+ getScripts(): readonly string[];
22
+ getBlock(id: string): Block | undefined;
23
+ };
24
+
25
+ type MessageVariable = {name: string; type?: string};
26
+
27
+ export type MessageTarget = {
28
+ id: string;
29
+ isStage: boolean;
30
+ isOriginal: boolean;
31
+ getName(): string;
32
+ variables: Record<string, MessageVariable>;
33
+ blocks: Blocks;
34
+ };
35
+
36
+ export type MessageProject = {targets: readonly MessageTarget[]};
37
+
38
+ export const broadcastVariableType = 'broadcast_msg';
39
+ export const sendOpcodes = ['event_broadcast', 'event_broadcastandwait'] as const;
40
+ export const receiveOpcode = 'event_whenbroadcastreceived';
41
+
42
+ export type MessageDirection = 'send' | 'receive';
43
+
44
+ export interface MessageReference {
45
+ direction: MessageDirection;
46
+ /** The broadcast_msg variable this block names, when it names one. */
47
+ id?: string;
48
+ /** The dropdown's own text, which is what the project file stores. */
49
+ fieldValue: string;
50
+ /** The owning variable's name when it resolves, otherwise the dropdown text. */
51
+ name: string;
52
+ /** `event_broadcastandwait` waits for every receiving script to finish. */
53
+ wait: boolean;
54
+ }
55
+
56
+ /**
57
+ * The judgement for a single block. Returns nothing for blocks that are not broadcast blocks and
58
+ * for a broadcast whose message is a reporter, because that message is only known while running.
59
+ */
60
+ export function messageReference(target: MessageTarget, block: Block,
61
+ stage?: MessageTarget): MessageReference | undefined {
62
+ const direction: MessageDirection | undefined = block.opcode === receiveOpcode ? 'receive' :
63
+ (sendOpcodes as readonly string[]).includes(block.opcode) ? 'send' : undefined;
64
+ if (!direction) return undefined;
65
+ const input = block.inputs?.BROADCAST_INPUT;
66
+ const menu = input?.block ? target.blocks.getBlock(input.block) : undefined;
67
+ const field = block.fields?.BROADCAST_OPTION ?? menu?.fields?.BROADCAST_OPTION;
68
+ if (!field) return undefined;
69
+ const fieldValue = String(field.value ?? '');
70
+ const owner = field.id ? target.variables[field.id] ?? stage?.variables[field.id] : undefined;
71
+ return {
72
+ direction,
73
+ id: field.id,
74
+ fieldValue,
75
+ name: owner?.type === broadcastVariableType && owner.name ? owner.name : fieldValue,
76
+ wait: block.opcode === 'event_broadcastandwait'
77
+ };
78
+ }
79
+
80
+ export interface MessageUse extends MessageReference {
81
+ key: string;
82
+ targetId: string;
83
+ targetName: string;
84
+ isStage: boolean;
85
+ blockId: string;
86
+ opcode: string;
87
+ /** The top block of the script holding this block, so the host can open the whole script. */
88
+ scriptId: string;
89
+ scriptOpcode: string;
90
+ /** When that script starts with a "when I receive" hat, the message it waits for. */
91
+ scriptMessageName?: string;
92
+ }
93
+
94
+ export type MessageStatus = 'both' | 'sendOnly' | 'receiveOnly' | 'unused';
95
+
96
+ export interface ProjectMessage {
97
+ /** Stable identity for a message: its variable id, or its name when no variable owns it. */
98
+ key: string;
99
+ id?: string;
100
+ name: string;
101
+ status: MessageStatus;
102
+ sends: readonly MessageUse[];
103
+ receives: readonly MessageUse[];
104
+ }
105
+
106
+ const messageKey = (id: string | undefined, name: string) => id ?? 'name:' + name;
107
+
108
+ function* walkScripts(blocks: Blocks) {
109
+ for (const rootId of blocks.getScripts()) {
110
+ const root = blocks.getBlock(rootId);
111
+ if (!root) continue;
112
+ const pending = [rootId];
113
+ const seen = new Set<string>();
114
+ while (pending.length) {
115
+ const id = pending.pop();
116
+ if (!id || seen.has(id)) continue;
117
+ seen.add(id);
118
+ const block = blocks.getBlock(id);
119
+ if (!block || block.shadow) continue;
120
+ yield {root, block};
121
+ if (block.next) pending.push(block.next);
122
+ for (const input of Object.values(block.inputs ?? {})) {
123
+ // A shadow holds a dropdown or a literal, which messageReference reads directly.
124
+ if (input.block && input.block !== input.shadow) pending.push(input.block);
125
+ }
126
+ }
127
+ }
128
+ }
129
+
130
+ const statusOf = (sends: readonly unknown[], receives: readonly unknown[]): MessageStatus =>
131
+ sends.length && receives.length ? 'both' : sends.length ? 'sendOnly' : receives.length ? 'receiveOnly' : 'unused';
132
+
133
+ /** Every message in the project, with the places that send and receive it. */
134
+ export function scanProjectMessages(project: MessageProject): readonly ProjectMessage[] {
135
+ const stage = project.targets.find(target => target.isStage);
136
+ const found = new Map<string, {key: string; id?: string; name: string; sends: MessageUse[]; receives: MessageUse[]}>();
137
+ const ensure = (id: string | undefined, name: string) => {
138
+ const key = messageKey(id, name);
139
+ let entry = found.get(key);
140
+ if (!entry) {
141
+ entry = {key, id, name, sends: [], receives: []};
142
+ found.set(key, entry);
143
+ }
144
+ // A message created but never used still carries its variable name.
145
+ if (name && entry.name !== name) entry.name = name;
146
+ return entry;
147
+ };
148
+
149
+ for (const target of project.targets) {
150
+ if (!target.isOriginal) continue;
151
+ for (const [id, variable] of Object.entries(target.variables)) {
152
+ if (variable.type === broadcastVariableType) ensure(id, variable.name);
153
+ }
154
+ }
155
+
156
+ for (const target of project.targets) {
157
+ if (!target.isOriginal) continue;
158
+ const targetName = target.getName();
159
+ for (const {root, block} of walkScripts(target.blocks)) {
160
+ const reference = messageReference(target, block, stage);
161
+ if (!reference) continue;
162
+ const hat = root.opcode === receiveOpcode ? messageReference(target, root, stage) : undefined;
163
+ const entry = ensure(reference.id, reference.name);
164
+ const use: MessageUse = {
165
+ ...reference,
166
+ key: entry.key,
167
+ targetId: target.id,
168
+ targetName,
169
+ isStage: target.isStage,
170
+ blockId: block.id,
171
+ opcode: block.opcode,
172
+ scriptId: root.id,
173
+ scriptOpcode: root.opcode,
174
+ scriptMessageName: hat?.name
175
+ };
176
+ (reference.direction === 'send' ? entry.sends : entry.receives).push(use);
177
+ }
178
+ }
179
+
180
+ return [...found.values()]
181
+ .map(({key, id, name, sends, receives}) => ({key, id, name, sends, receives, status: statusOf(sends, receives)}))
182
+ .sort((left, right) => left.name.localeCompare(right.name) || left.key.localeCompare(right.key));
183
+ }
184
+
185
+ export type MessageRenameError = 'emptyName' | 'duplicateName' | 'unavailable';
186
+
187
+ export type MessageRenameCheck = {error: MessageRenameError} | {name: string} | {unchanged: true};
188
+
189
+ /**
190
+ * Whether a message may take this name. A message is owned by the stage, so its name has to be
191
+ * free across the whole project.
192
+ */
193
+ export function checkMessageRename(messages: readonly ProjectMessage[], message: ProjectMessage,
194
+ name: string): MessageRenameCheck {
195
+ const next = name.trim();
196
+ if (!next) return {error: 'emptyName'};
197
+ if (next === message.name) return {unchanged: true};
198
+ const taken = next.toLocaleLowerCase();
199
+ if (messages.some(other => other.key !== message.key && other.name.toLocaleLowerCase() === taken)) {
200
+ return {error: 'duplicateName'};
201
+ }
202
+ return {name: next};
203
+ }
204
+
205
+ export interface MessageGraphNode {
206
+ id: string;
207
+ name: string;
208
+ isStage: boolean;
209
+ }
210
+
211
+ export interface MessageGraphEdge {
212
+ direction: MessageDirection;
213
+ targetId: string;
214
+ messageKey: string;
215
+ /** How many blocks in that target send or receive the message. */
216
+ count: number;
217
+ }
218
+
219
+ export interface MessageGraph {
220
+ targets: readonly MessageGraphNode[];
221
+ messages: readonly Pick<ProjectMessage, 'key' | 'id' | 'name' | 'status'>[];
222
+ edges: readonly MessageGraphEdge[];
223
+ }
224
+
225
+ /** The whole project as sprite or stage, message, sprite or stage. Isolated messages are kept. */
226
+ export function projectMessageGraph(project: MessageProject,
227
+ messages: readonly ProjectMessage[] = scanProjectMessages(project)): MessageGraph {
228
+ const edges = new Map<string, MessageGraphEdge>();
229
+ for (const message of messages) {
230
+ for (const use of [...message.sends, ...message.receives]) {
231
+ const key = use.direction + '\u0000' + use.targetId + '\u0000' + message.key;
232
+ const edge = edges.get(key);
233
+ if (edge) edge.count++;
234
+ else edges.set(key, {direction: use.direction, targetId: use.targetId, messageKey: message.key, count: 1});
235
+ }
236
+ }
237
+ return {
238
+ targets: project.targets.filter(target => target.isOriginal)
239
+ .map(target => ({id: target.id, name: target.getName(), isStage: target.isStage})),
240
+ messages: messages.map(({key, id, name, status}) => ({key, id, name, status})),
241
+ edges: [...edges.values()]
242
+ };
243
+ }
244
+
245
+ export interface TargetMessages {
246
+ targetId: string;
247
+ isStage: boolean;
248
+ /** Blocks in this target that send a message. */
249
+ sends: readonly MessageUse[];
250
+ /** Hats in this target that receive a message. */
251
+ receives: readonly MessageUse[];
252
+ /** Messages the project uses or declares that this target neither sends nor receives. */
253
+ elsewhere: readonly ProjectMessage[];
254
+ /** Every message in the project, so a rename can check the names already taken. */
255
+ messages: readonly ProjectMessage[];
256
+ /** The relationship diagram, which only the stage shows. */
257
+ graph?: MessageGraph;
258
+ }
259
+
260
+ /** What one sprite or the stage sends and receives. The stage also carries the project diagram. */
261
+ export function scanTargetMessages(project: MessageProject, targetId: string): TargetMessages {
262
+ const messages = scanProjectMessages(project);
263
+ const isStage = Boolean(project.targets.find(target => target.id === targetId)?.isStage);
264
+ const mine = (uses: readonly MessageUse[]) => uses.filter(use => use.targetId === targetId);
265
+ const sends = messages.flatMap(message => mine(message.sends));
266
+ const receives = messages.flatMap(message => mine(message.receives));
267
+ return {
268
+ targetId,
269
+ isStage,
270
+ sends,
271
+ receives,
272
+ elsewhere: messages.filter(message =>
273
+ !message.sends.some(use => use.targetId === targetId) &&
274
+ !message.receives.some(use => use.targetId === targetId)),
275
+ messages,
276
+ graph: isStage ? projectMessageGraph(project, messages) : undefined
277
+ };
278
+ }
@@ -0,0 +1,85 @@
1
+ export type SpriteVariableEdit =
2
+ {type: 'create'; name: string} |
3
+ {type: 'rename'; id: string; name: string} |
4
+ {type: 'delete'; id: string};
5
+
6
+ export type SpriteVariableEditError = 'emptyName' | 'duplicateName' | 'inUse' | 'unavailable';
7
+
8
+ type Variable = {name: string; type: string; isCloud?: boolean};
9
+ type Block = {
10
+ opcode: string;
11
+ fields: Record<string, {value: unknown}>;
12
+ inputs: Record<string, {block: string | null; shadow: string | null}>;
13
+ };
14
+ type VariableEvent =
15
+ {type: 'var_create'; varId: string; varName: string; varType: ''; isLocal: boolean; isCloud: false} |
16
+ {type: 'var_rename'; varId: string; newName: string} |
17
+ {type: 'var_delete'; varId: string};
18
+ type VariableTarget = {
19
+ id: string;
20
+ isStage: boolean;
21
+ isOriginal: boolean;
22
+ getName(): string;
23
+ variables: Record<string, Variable>;
24
+ blocks: {
25
+ _blocks: Record<string, Block>;
26
+ getAllVariableAndListReferences(): Record<string, unknown>;
27
+ blocklyListen(event: VariableEvent): void;
28
+ };
29
+ };
30
+ type VariableProject = {
31
+ editingTarget?: VariableTarget;
32
+ runtime: {
33
+ targets: readonly VariableTarget[];
34
+ getEditingTarget(): VariableTarget | null;
35
+ getTargetForStage(): VariableTarget | null;
36
+ };
37
+ refreshWorkspace(): void;
38
+ };
39
+
40
+ export const cloudVariablePrefix = '☁ ';
41
+
42
+ function isUsed(target: VariableTarget, targets: readonly VariableTarget[], id: string, name: string) {
43
+ const targetName = target.isStage ? '_stage_' : target.getName();
44
+ return targets.some(({blocks}) => {
45
+ if (Object.hasOwn(blocks.getAllVariableAndListReferences(), id)) return true;
46
+ return Object.values(blocks._blocks).some(block => {
47
+ if (block.opcode !== 'sensing_of' || block.fields.PROPERTY?.value !== name) return false;
48
+ const input = block.inputs.OBJECT;
49
+ if (!input?.block) return false;
50
+ // A dynamic target can resolve to the variable's owner when the project runs.
51
+ return input.block !== input.shadow || blocks._blocks[input.block]?.fields.OBJECT?.value === targetName;
52
+ });
53
+ });
54
+ }
55
+
56
+ export function editSpriteVariable(vm: VariableProject, targetId: string, edit: SpriteVariableEdit): SpriteVariableEditError | void {
57
+ const target = vm.editingTarget;
58
+ const {runtime} = vm;
59
+ if (!target || target.id !== targetId || runtime.getEditingTarget() !== target ||
60
+ !runtime.targets.includes(target) || (!target.isStage && !target.isOriginal)) return 'unavailable';
61
+
62
+ const variable = edit.type === 'create' ? undefined : target.variables[edit.id];
63
+ if (edit.type !== 'create' && variable?.type !== '') return 'unavailable';
64
+ if (edit.type === 'delete') {
65
+ if (isUsed(target, runtime.targets, edit.id, variable!.name)) return 'inUse';
66
+ target.blocks.blocklyListen({type: 'var_delete', varId: edit.id});
67
+ } else {
68
+ const name = edit.name.trim();
69
+ if (!name) return 'emptyName';
70
+ const fullName = variable?.isCloud && !name.startsWith(cloudVariablePrefix) ? cloudVariablePrefix + name : name;
71
+ if (fullName === variable?.name) return;
72
+ const scope = target.isStage ? runtime.targets.filter(item => item.isStage || item.isOriginal) :
73
+ [target, runtime.getTargetForStage()];
74
+ if (scope.some(owner => owner && Object.values(owner.variables).some(item => item.type === '' && item.name === fullName))) {
75
+ return 'duplicateName';
76
+ }
77
+ if (edit.type === 'create') {
78
+ const varId = Array.from(crypto.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('');
79
+ target.blocks.blocklyListen({type: 'var_create', varId, varName: fullName, varType: '', isLocal: !target.isStage, isCloud: false});
80
+ } else {
81
+ target.blocks.blocklyListen({type: 'var_rename', varId: edit.id, newName: fullName});
82
+ }
83
+ }
84
+ vm.refreshWorkspace();
85
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2023",
4
+ "module": "NodeNext",
5
+ "lib": [
6
+ "ES2023",
7
+ "DOM"
8
+ ],
9
+ "types": [],
10
+ "skipLibCheck": true,
11
+ "strict": true,
12
+ "declaration": true,
13
+ "rootDir": "src",
14
+ "outDir": "dist",
15
+ "rewriteRelativeImportExtensions": true
16
+ },
17
+ "include": [
18
+ "src/**/*.ts"
19
+ ]
20
+ }