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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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/**
 * Copyright (C) 2021 Thomas Weber
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/* eslint-disable import/no-commonjs */
/* eslint-disable import/no-nodejs-modules */
/* eslint-disable no-console */
/* global __dirname */

const fs = require('fs');
const childProcess = require('child_process');
const rimraf = require('rimraf');
const pathUtil = require('path');
const {addons, newAddons} = require('./addons.js');

const walk = dir => {
    const children = fs.readdirSync(dir);
    const files = [];
    for (const child of children) {
        const path = pathUtil.join(dir, child);
        const stat = fs.statSync(path);
        if (stat.isDirectory()) {
            const childChildren = walk(path);
            for (const childChild of childChildren) {
                files.push(pathUtil.join(child, childChild));
            }
        } else {
            files.push(child);
        }
    }
    return files;
};

const clone = obj => JSON.parse(JSON.stringify(obj));

const repoPath = pathUtil.resolve(__dirname, 'ScratchAddons');
if (!process.argv.includes('-')) {
    rimraf.sync(repoPath);
    childProcess.execSync(`git clone --depth=1 --branch=tw https://github.com/TurboWarp/addons ${repoPath}`);
}

for (const folder of ['addons', 'addons-l10n', 'addons-l10n-settings', 'libraries']) {
    const path = pathUtil.resolve(__dirname, folder);
    rimraf.sync(path);
    fs.mkdirSync(path, {recursive: true});
}

const generatedPath = pathUtil.resolve(__dirname, 'generated');
rimraf.sync(generatedPath);
fs.mkdirSync(generatedPath, {recursive: true});

process.chdir(repoPath);
const commitHash = childProcess.execSync('git rev-parse --short HEAD')
    .toString()
    .trim();

class GeneratedImports {
    constructor () {
        this.source = '';
        this.namespaces = new Map();
    }

    add (src, namespace) {
        // On Windows, convert \ to / in paths.
        src = src.replace(/\\/g, '/');

        namespace = namespace.replace(/[^\w\d_]/g, '_');

        const count = this.namespaces.get(namespace) || 1;
        this.namespaces.set(namespace, count + 1);

        // All identifiers should start with _ so things like debugger and 2d-color-picker will be valid identifiers
        let importName = `_${namespace}`;
        if (count !== 1) {
            importName += `${count}`;
        }

        this.source += `import ${importName} from ${JSON.stringify(src)};\n`;
        return importName;
    }

    toString () {
        return this.source;
    }
}

const matchAll = (str, regex) => {
    const matches = [];
    let match;
    while ((match = regex.exec(str)) !== null) {
        matches.push(match);
    }
    return matches;
};

const includeImportedLibraries = contents => {
    // Parse things like:
    // import { normalizeHex, getHexRegex } from "../../libraries/normalize-color.js";
    // import RateLimiter from "../../libraries/rate-limiter.js";
    const matches = matchAll(
        contents,
        /import +(?:{.*}|.*) +from +["']\.\.\/\.\.\/libraries\/([\w\d_\/-]+(?:\.esm)?\.js)["'];/g
    );
    for (const match of matches) {
        const libraryFile = match[1];
        const oldLibraryPath = pathUtil.resolve(__dirname, 'ScratchAddons', 'libraries', libraryFile);
        const newLibraryPath = pathUtil.resolve(__dirname, 'libraries', libraryFile);
        const libraryContents = fs.readFileSync(oldLibraryPath, 'utf-8');
        const newLibraryDirName = pathUtil.dirname(newLibraryPath);
        fs.mkdirSync(newLibraryDirName, {
            recursive: true
        });
        fs.writeFileSync(newLibraryPath, libraryContents);
    }
};

const includePolyfills = contents => {
    if (contents.includes('EventTarget')) {
        contents = `import EventTarget from "../../event-target.js"; /* inserted by pull.js */\n\n${contents}`;
    }
    return contents;
};

const detectUnimplementedAPIs = (addonId, contents) => {
    if (contents.includes('data-addon-id')) {
        console.warn(`Warning: ${addonId} seems to use data-addon-id. It should use [data-addons*=...] instead.`);
    }

    if (contents.includes('addon.self.dir')) {
        // eslint-disable-next-line max-len
        console.warn(`Warning: ${addonId} contains unwritten addon.self.dir. It or this script should be modified so that it will be rewritten.`);
    }

    if (contents.includes('addon.self.lib')) {
        // eslint-disable-next-line max-len
        console.warn(`Warning: ${addonId} contains unwritten addon.self.lib. It should use modern ES6 import statements.`);
    }
};

const rewriteAssetImports = contents => {
    // Reroute addon.self.dir concatenation to call runtime function.
    // Parse things like:
    // el.src = addon.self.dir + "/" + name + ".svg";
    //          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  match
    //                           ^^^^^^^^^^^^^^^^^^^  capture group 1
    contents = contents.replace(
        /addon\.self\.(?:dir|lib) *\+ *([^;,\n]+)/g,
        (_fullText, name) => `addon.self.getResource(${name}) /* rewritten by pull.js */`
    );
    return contents;
};

const normalizeManifest = (id, manifest) => {
    const KEEP_TAGS = [
        'recommended',
        'theme',
        'beta',
        'danger'
    ];
    manifest.tags = manifest.tags.filter(i => KEEP_TAGS.includes(i));
    if (newAddons.includes(id)) {
        manifest.tags.push('new');
    }

    delete manifest.versionAdded;
    delete manifest.latestUpdate;
    delete manifest.libraries;
    delete manifest.injectAsStyleElt;
    delete manifest.updateUserstylesOnSettingsChange;

    // All addons have dynamic enable
    delete manifest.dynamicEnable;

    const filterUserscripts = scripts => scripts
        .filter(({matches}) => matches.includes('projects') || matches.includes('https://scratch.mit.edu/projects/*'))
        .map(obj => ({
            url: obj.url,
            if: obj.if
        }));

    if (manifest.userscripts) {
        manifest.userscripts = filterUserscripts(manifest.userscripts);
    }
    if (manifest.userstyles) {
        manifest.userstyles = filterUserscripts(manifest.userstyles);
    }

    if (manifest.credits) {
        for (const {link} of manifest.credits) {
            if (link && !link.startsWith('https://scratch.mit.edu/')) {
                console.warn(`Warning: ${id} contains unsafe credit link: ${link}`);
            }
        }
    }
};

const generateManifestEntry = (id, manifest) => {
    const trimmedManifest = clone(manifest);
    delete trimmedManifest.enabledByDefaultMobile;
    delete trimmedManifest.permissions;

    let result = '/* generated by pull.js */\n';
    result += `const manifest = ${JSON.stringify(trimmedManifest, null, 2)};\n`;
    if (typeof manifest.enabledByDefaultMobile === 'boolean') {
        result += 'import {isMobile} from "../../environment";\n';
        result += `if (isMobile) manifest.enabledByDefault = ${manifest.enabledByDefaultMobile};\n`;
    }
    if (manifest.permissions && manifest.permissions.includes('clipboardWrite')) {
        result += 'import {clipboardSupported} from "../../environment";\n';
        result += 'if (!clipboardSupported) manifest.unsupported = true;\n';
    }
    if (id === 'mediarecorder') {
        result += 'import {mediaRecorderSupported} from "../../environment";\n';
        result += 'if (!mediaRecorderSupported) manifest.unsupported = true;\n';
    }
    if (id === 'tw-disable-cloud-variables') {
        result += 'import {isScratchDesktop} from "../../../lib/isScratchDesktop";\n';
        result += 'if (isScratchDesktop()) manifest.unsupported = true;\n';
    }
    result += 'export default manifest;\n';
    return result;
};

const generateRuntimeEntry = (id, manifest, assets) => {
    const importSection = new GeneratedImports();
    let exportSection = 'export const resources = {\n';

    for (const userscript of manifest.userscripts || []) {
        const src = userscript.url;
        const importName = importSection.add(`./${src}`, 'js');
        exportSection += `  ${JSON.stringify(src)}: ${importName},\n`;
    }

    for (const userstyle of manifest.userstyles || []) {
        const src = userstyle.url;
        const importName = importSection.add(`!css-loader!./${src}`, 'css');
        exportSection += `  ${JSON.stringify(src)}: ${importName},\n`;
    }

    for (const assetName of assets) {
        const importName = importSection.add(`!url-loader!./${assetName}`, 'asset');
        exportSection += `  ${JSON.stringify(assetName)}: ${importName},\n`;
    }

    exportSection += '};\n';
    let result = '/* generated by pull.js */\n';
    result += importSection.toString();
    result += exportSection;
    return result;
};

const addonIdToManifest = {};
const processAddon = (id, oldDirectory, newDirectory) => {
    const files = walk(oldDirectory);

    const ASSET_EXTENSIONS = [
        '.svg',
        '.png'
    ];
    const assets = files.filter(file => ASSET_EXTENSIONS.some(extension => file.endsWith(extension)));

    for (const file of files) {
        const oldPath = pathUtil.join(oldDirectory, file);
        let contents = fs.readFileSync(oldPath);

        const newPath = pathUtil.join(newDirectory, file);
        fs.mkdirSync(pathUtil.dirname(newPath), {recursive: true});

        if (file === 'addon.json') {
            contents = contents.toString('utf-8');
            const parsedManifest = JSON.parse(contents);
            normalizeManifest(id, parsedManifest);
            addonIdToManifest[id] = parsedManifest;

            const settingsEntryPath = pathUtil.join(newDirectory, '_manifest_entry.js');
            fs.writeFileSync(settingsEntryPath, generateManifestEntry(id, parsedManifest));

            const runtimeEntryPath = pathUtil.join(newDirectory, '_runtime_entry.js');
            fs.writeFileSync(runtimeEntryPath, generateRuntimeEntry(id, parsedManifest, assets));
            continue;
        }

        if (file.endsWith('.js') || file.endsWith('.css')) {
            contents = contents.toString('utf-8');

            if (file.endsWith('.js')) {
                includeImportedLibraries(contents);
                contents = includePolyfills(contents);
                contents = rewriteAssetImports(contents);
            }

            detectUnimplementedAPIs(id, contents);
        }

        fs.writeFileSync(newPath, contents);
    }
};

const SKIP_MESSAGES = [
    'debugger/@description',
    'debugger/@settings-name-log_max_list_length',
    'debugger/log-msg-list-append-too-long',
    'debugger/log-msg-list-insert-too-long',
    'debugger/@settings-name-log_invalid_cloud_data',
    'debugger/log-cloud-data-nan',
    'debugger/log-cloud-data-too-long',
    'debugger/tab-performance',
    'debugger/performance-framerate-title',
    'debugger/performance-framerate-graph-tooltip',
    'debugger/performance-clonecount-title',
    'debugger/performance-clonecount-graph-tooltip',
    'editor-devtools/extension-description-not-for-addon',
    'mediarecorder/added-by',
    'editor-theme3/@settings-name-sa-color',
    'editor-theme3/@settings-name-forums',
    'block-switching/@settings-name-sa'
];

const parseMessageDirectory = localeRoot => {
    const settings = {};
    const runtime = {};
    const upstreamMessageIds = new Set();

    for (const addon of addons) {
        const path = pathUtil.join(localeRoot, `${addon}.json`);
        try {
            const contents = fs.readFileSync(path, 'utf-8');
            const parsed = JSON.parse(contents);
            for (const id of Object.keys(parsed).sort()) {
                upstreamMessageIds.add(id);
                if (SKIP_MESSAGES.includes(id)) {
                    continue;
                }

                const value = parsed[id];
                if (id.includes('/@')) {
                    settings[id] = value;
                } else {
                    runtime[id] = value;
                }
            }
        } catch (e) {
            // Ignore errors caused by file not existing.
            if (e.code !== 'ENOENT') {
                throw e;
            }
        }
    }

    return {
        settings,
        runtime,
        upstreamMessageIds
    };
};

const generateEntries = (items, callback) => {
    let exportSection = 'export default {\n';
    const importSection = new GeneratedImports();
    for (const i of items) {
        const {src, name, type} = callback(i);
        if (type === 'lazy-import') {
            // eslint-disable-next-line max-len
            exportSection += `  ${JSON.stringify(i)}: () => import(/* webpackChunkName: ${JSON.stringify(name)} */ ${JSON.stringify(src)}),\n`;
        } else if (type === 'lazy-require') {
            exportSection += `  ${JSON.stringify(i)}: () => require(${JSON.stringify(src)}),\n`;
        } else if (type === 'eager-import') {
            const importName = importSection.add(src, i);
            exportSection += `  ${JSON.stringify(i)}: ${importName},\n`;
        } else {
            throw new Error(`Unknown type: ${type}`);
        }
    }
    exportSection += '};\n';
    let result = '/* generated by pull.js */\n';
    result += importSection.toString();
    result += exportSection;
    return result;
};

const generateL10nEntries = locales => generateEntries(
    locales.filter(i => i !== 'en'),
    locale => ({
        name: `addon-l10n-${locale}`,
        src: `../addons-l10n/${locale}.json`,
        type: 'lazy-import'
    })
);

const generateL10nSettingsEntries = locales => generateEntries(
    locales.filter(i => i !== 'en'),
    locale => ({
        src: `../addons-l10n-settings/${locale}.json`,
        type: 'lazy-require'
    })
);

const generateRuntimeEntries = () => generateEntries(
    addons,
    id => {
        const manifest = addonIdToManifest[id];
        return {
            src: `../addons/${id}/_runtime_entry.js`,
            // Include default addons in a single bundle
            name: manifest.enabledByDefault ? 'addon-default-entry' : `addon-entry-${id}`,
            // Include default addons useful outside of the editor in the original bundle, no request required
            type: (manifest.enabledByDefault && !manifest.editorOnly) ? 'lazy-require' : 'lazy-import'
        };
    }
);

const generateManifestEntries = () => generateEntries(
    addons,
    id => ({
        src: `../addons/${id}/_manifest_entry.js`,
        type: 'eager-import'
    })
);

for (const addon of addons) {
    const oldDirectory = pathUtil.resolve(__dirname, 'ScratchAddons', 'addons', addon);
    const newDirectory = pathUtil.resolve(__dirname, 'addons', addon);
    processAddon(addon, oldDirectory, newDirectory);
}

const l10nFiles = fs.readdirSync(pathUtil.resolve(__dirname, 'ScratchAddons', 'addons-l10n'));
const languages = [];
const allUpstreamMessageIds = new Set();
for (const file of l10nFiles) {
    const oldDirectory = pathUtil.resolve(__dirname, 'ScratchAddons', 'addons-l10n', file);
    // Ignore README
    if (!fs.statSync(oldDirectory).isDirectory()) {
        continue;
    }
    // Convert pt-br to just pt
    const fixedName = file === 'pt-br' ? 'pt' : file;
    languages.push(fixedName);
    const runtimePath = pathUtil.resolve(__dirname, 'addons-l10n', `${fixedName}.json`);
    const settingsPath = pathUtil.resolve(__dirname, 'addons-l10n-settings', `${fixedName}.json`);
    const {settings, runtime, upstreamMessageIds} = parseMessageDirectory(oldDirectory);
    for (const id of upstreamMessageIds) {
        allUpstreamMessageIds.add(id);
    }
    fs.writeFileSync(runtimePath, JSON.stringify(runtime, null, 4));
    if (fixedName !== 'en') {
        fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 4));
    }
}

for (const id of SKIP_MESSAGES) {
    if (!allUpstreamMessageIds.has(id)) {
        console.warn(`Warning: Translation ${id} is in SKIP_MESSAGES but does not exist`);
    }
}

fs.writeFileSync(pathUtil.resolve(generatedPath, 'l10n-entries.js'), generateL10nEntries(languages));
fs.writeFileSync(pathUtil.resolve(generatedPath, 'l10n-settings-entries.js'), generateL10nSettingsEntries(languages));
fs.writeFileSync(pathUtil.resolve(generatedPath, 'addon-entries.js'), generateRuntimeEntries(languages));
fs.writeFileSync(pathUtil.resolve(generatedPath, 'addon-manifests.js'), generateManifestEntries(languages));

const upstreamMetaPath = pathUtil.resolve(generatedPath, 'upstream-meta.json');
fs.writeFileSync(upstreamMetaPath, JSON.stringify({
    commit: commitHash
}));