File size: 6,670 Bytes
30c32c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// ScratchX API Documentation: https://github.com/LLK/scratchx/wiki/

const ArgumentType = require('./argument-type');
const BlockType = require('./block-type');

const {
    argumentIndexToId,
    generateExtensionId
} = require('./tw-scratchx-utilities');

/**
 * @typedef ScratchXDescriptor
 * @property {unknown[][]} blocks
 * @property {Record<string, unknown[]>} [menus]
 * @property {string} [url]
 * @property {string} [displayName]
 */

/**
 * @typedef ScratchXStatus
 * @property {0|1|2} status 0 is red/error, 1 is yellow/not ready, 2 is green/ready
 * @property {string} msg
 */

const parseScratchXBlockType = type => {
    if (type === '' || type === ' ' || type === 'w') {
        return {
            type: BlockType.COMMAND,
            async: type === 'w'
        };
    }
    if (type === 'r' || type === 'R') {
        return {
            type: BlockType.REPORTER,
            async: type === 'R'
        };
    }
    if (type === 'b') {
        return {
            type: BlockType.BOOLEAN,
            // ScratchX docs don't seem to mention boolean reporters that wait
            async: false
        };
    }
    if (type === 'h') {
        return {
            type: BlockType.HAT,
            async: false
        };
    }
    throw new Error(`Unknown ScratchX block type: ${type}`);
};

const isScratchCompatibleValue = v => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';

/**
 * @param {string} argument ScratchX argument with leading % removed.
 * @param {unknown} defaultValue Default value, if any
 */
const parseScratchXArgument = (argument, defaultValue) => {
    const result = {};
    const hasDefaultValue = isScratchCompatibleValue(defaultValue);
    if (hasDefaultValue) {
        result.defaultValue = defaultValue;
    }
    // TODO: ScratchX docs don't mention support for boolean arguments?
    if (argument === 's') {
        result.type = ArgumentType.STRING;
        if (!hasDefaultValue) {
            result.defaultValue = '';
        }
    } else if (argument === 'n') {
        result.type = ArgumentType.NUMBER;
        if (!hasDefaultValue) {
            result.defaultValue = 0;
        }
    } else if (argument[0] === 'm') {
        result.type = ArgumentType.STRING;
        const split = argument.split(/\.|:/);
        const menuName = split[1];
        result.menu = menuName;
    } else {
        throw new Error(`Unknown ScratchX argument type: ${argument}`);
    }
    return result;
};

const wrapScratchXFunction = (originalFunction, argumentCount, async) => args => {
    // Convert Scratch 3's argument object to an argument list expected by ScratchX
    const argumentList = [];
    for (let i = 0; i < argumentCount; i++) {
        argumentList.push(args[argumentIndexToId(i)]);
    }
    if (async) {
        return new Promise(resolve => {
            originalFunction(...argumentList, resolve);
        });
    }
    return originalFunction(...argumentList);
};

/**
 * @param {string} name
 * @param {ScratchXDescriptor} descriptor
 * @param {Record<string, () => unknown>} functions
 */
const convert = (name, descriptor, functions) => {
    const extensionId = generateExtensionId(name);
    const info = {
        id: extensionId,
        name: descriptor.displayName || name,
        blocks: [],
        color1: '#4a4a5e',
        color2: '#31323f',
        color3: '#191a21'
    };
    const scratch3Extension = {
        getInfo: () => info,
        _getStatus: functions._getStatus
    };

    if (descriptor.url) {
        info.docsURI = descriptor.url;
    }

    for (const blockDescriptor of descriptor.blocks) {
        if (blockDescriptor.length === 1) {
            // Separator
            info.blocks.push('---');
            continue;
        }
        const scratchXBlockType = blockDescriptor[0];
        const blockText = blockDescriptor[1];
        const functionName = blockDescriptor[2];
        const defaultArgumentValues = blockDescriptor.slice(3);

        let scratchText = '';
        const argumentInfo = [];
        const blockTextParts = blockText.split(/%([\w.:]+)/g);
        for (let i = 0; i < blockTextParts.length; i++) {
            const part = blockTextParts[i];
            const isArgument = i % 2 === 1;
            if (isArgument) {
                parseScratchXArgument(part);
                const argumentIndex = Math.floor(i / 2).toString();
                const argumentDefaultValue = defaultArgumentValues[argumentIndex];
                const argumentId = argumentIndexToId(argumentIndex);
                argumentInfo[argumentId] = parseScratchXArgument(part, argumentDefaultValue);
                scratchText += `[${argumentId}]`;
            } else {
                scratchText += part;
            }
        }

        const scratch3BlockType = parseScratchXBlockType(scratchXBlockType);
        const blockInfo = {
            opcode: functionName,
            blockType: scratch3BlockType.type,
            text: scratchText,
            arguments: argumentInfo
        };
        info.blocks.push(blockInfo);

        const originalFunction = functions[functionName];
        const argumentCount = argumentInfo.length;
        scratch3Extension[functionName] = wrapScratchXFunction(
            originalFunction,
            argumentCount,
            scratch3BlockType.async
        );
    }

    const menus = descriptor.menus;
    if (menus) {
        const scratch3Menus = {};
        for (const menuName of Object.keys(menus) || {}) {
            const menuItems = menus[menuName];
            const menuInfo = {
                items: menuItems
            };
            scratch3Menus[menuName] = menuInfo;
        }
        info.menus = scratch3Menus;
    }

    return scratch3Extension;
};

const extensionNameToExtension = new Map();

/**
 * @param {*} Scratch Scratch 3.0 extension API object
 * @returns {*} ScratchX-compatible API object
 */
const createScratchX = Scratch => {
    const register = (name, descriptor, functions) => {
        const scratch3Extension = convert(name, descriptor, functions);
        extensionNameToExtension.set(name, scratch3Extension);
        Scratch.extensions.register(scratch3Extension);
    };

    /**
     * @param {string} extensionName
     * @returns {ScratchXStatus}
     */
    const getStatus = extensionName => {
        const extension = extensionNameToExtension.get(extensionName);
        if (extension) {
            return extension._getStatus();
        }
        return {
            status: 0,
            msg: 'does not exist'
        };
    };

    return {
        register,
        getStatus
    };
};

module.exports = createScratchX;