Files
blockly/tests/bootstrap.js
Christopher Allen 46df7d132d refactor(tests): Revise tests/playgrounds/prepare.js as tests/bootstrap.js to improve support for ES modules and post-bootstrap scripts (#6214)
* refactor(tests): Move and rename prepare.js, blockly.mjs

  Since prepare.js and blockly.mjs are going to be needed for running
  all tests in uncompiled mode (not just the playgrounds), move them
  tests/.  Further, rename prepare.js to bootstrap.js to better reflect
  its purpose.

* feat(tests): Introduce BLOCKLY_BOOTSTRAP_OPTIONS

  Provide a mechanism for web pages that use bootstrap.js to control
  what is loaded and how.

* fix(tests): Use the blockly repository path for all script src= URLs

  Previously the (non-advanced) playground was only correctly loadging
  on localhost because you can put an arbitrary number of "../"s in front
  of a relative URL and it just takes you to the root directory.

* fix(tests): Don't use template literals in bootstrap.js

  This is necessary (but not necessarily sufficient) to be able to
  load the file in IE 11.

* fix(tests): Throw error if attempting to bootstrap in node.js

* feat(tests): Make bootstrap.js more configurable.

* Terminology change: use "compressed" and "uncompressed" to describe
  what Closure Compiler calls "compiled" and "uncompiled", to reduce
  confusion with the compilation that will be done by tsc.

* Get the list of modules to bootstrap (in compressed mode), or
  scripts to load (in compressed mode) from BLOCKLY_BOOTSTRAP_OPTIONS,
  to allow calling scripts to to specify exactly what to load.

* feat(tests): Use a proper quote function

  We need to generate string literals.  Best to use a quote function
  instead of concatenating on quote marks withou escaping.  Copy a
  well-tested one from Code City.

* feat(tests): Support an additionalScripts option

  This is a list of scripts to load (in order) once the required modules
  have been bootstrapped.

  We do this using goog.addDependency to make the first script depend
  on the required modules, then each subsequent script depend on the
  previous one, and then finally goog.bootstrapping the last such script.

* refactor(tests): Remove special handling of msg/messages.js

* refactor(tests): Use additionalScripts for all script loading

  Use additionalScripts option for all script loading in
  playground.html and advanced_playground.html.

* refactor(tests): Use bootstrap instead of uncompressed in Mocha tests

  Use tests/bootstrap.js instead of blockly_uncompressed.js to load
  blockly in uncompressed mode in the Mocha tests.

  This entails adding a new item, despFiles, to BLOCKLY_BOOTSTRAP_OPTIONS,
  to allow tests/deps.mocha.js to be loaded at the appropriate point.

  Mention of blockly_uncompressed.js is removed from
  tests/mocah/.mocharc.js; it's not clear to me what effect the "file:"
  directive in this file might have previously had and I was not able to
  find documentation for it on mochajs.org, but in any case removing it
  appears to have had no ill effect.

* refactor(tests): Use bootstrap instead of uncompressed in generator tests

  This entails adding an additional check in bootstrap so as to load
  uncompressed when loading from a file: URL, since these are not
  localhost URLs - though in fact the generator tests run equally well
  in compressed mode, albeit against (for now) the previously-check-in
  build products rather than the live code.

* refactor(test): Use bootstrap.js in multi_playground.html

  This removes the last use of load_all.js, so remove it.

* chore(tests): Delete blockly_uncompressed.js

  Its function has now been entirely subsumed by tests/bootstrap.js,
  so remove it and update any remaining mentions of it.

  Also fix formatting and positions of some comments in playground.html.

* fix(tests): Rewrite bootstrap sequencing code

  An earlier commit modified the generated <script> to use
  goog.addDependency to trick the debug module loader into loading
  .additionalScripts (via goog.bootstrap), but it turns out there is
  a small problem: scripts like msg/messages.js have undeclared
  dependencies on the Blockly module, and without a call to
  goog.require('Blockly') in them they can end up being run before
  the Blockly module is fully loaded.

  (This problem only occurs when there are ES Modules, rather than
  merely goog.modules, in the mix.)

  Fix this by adding a script, bootstrap_helper.js, to be loaded
  options.requires and any options.additionalScripts that makes an
  explicit call to goog.require for each of option.requires.

  Also refactor the code so that instead of generating a loop which
  calls goog.addDependency, we generate the addDependency calls
  directly.  This makes debugging a bit easer as we can use the browser's
  dev tools to inspect the generated calls in the DOM tree.

* fix(tests): Prevent spurious transpilation warnings

  For some reason when the debug module loader encounters ES modules
  it starts to complain about being unable to transpile some ES202x
  features in other (non-ESM) modules, even though it doesn't normally
  try to transpile those.

  Since uncompressed-mode testing is almost exclusively on modern
  browsers we don't care about transpiling these features, so suppress
  the warnings instead.

* refactor(tests): Rename blockly.mjs to bootstrap_done.mjs; simplify

  Since blockly.mjs is no longer returning just the exports object
  from core/blockly.js (see PR #5995), it might be better named after
  its actual purpose: to wait for bootstrapping to be done.

  Remove all the code that was used to pass the blockly.js exports
  object along from the bootstrap callback to the blockly.mjs export,
  since there's no reason to go to a lot of trouble to set a local
  variable named Blockly to the same value as a global variable named
  Blockly.

  (Something like this may be needed again in future, but certainly in
  a different form.)

* chore(tests): Use freshly-build files in compressed mode.

  Use the freshly-built build/*_compresssed.js files when bootstrapping
  in compressed mode, rather than using the checked-in files in the
  repository root.

  This helps ensure that compressed and uncompressed mode will be
  testing (as closely as possible) the same code.

* chore(tests): Rename BlocklyLoader to blocklyLoader; record compressed

  - Rename the BlocklyLoader global to blocklyLoader (since it is not
    a class constructor).
  - Create it regardless of whether we are bootstrapping in
    uncompressed or loading compressed via <script> tags.
  - Record which we are doing as .compressed, and use this property
    to choose playground background colour.

* chore(tests): Resolve comments for PR #6214

  Mostly documentation changes, but notably renaming blocklyLoader to
  bootstrapInfo.

* Revert "chore(tests): Use freshly-build files in compressed mode."

  This reverts commit de8d356838.
2022-06-15 19:35:01 +01:00

247 lines
9.4 KiB
JavaScript

/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Bootstrap code to load Blockly, typically in
* uncompressed mode.
*
* Load this file in a <script> tag in a web page to use the
* Closure Library debug module loader to load Blockly in
* uncompressed mode.
*
* You must use a <script src=> tag to load this script first
* (after setting BLOCKLY_BOOTSTRAP_OPTIONS in a preceeding
* <script> tag, if desired - see below), then import
* bootstrap_done.mjs in a <script type=module> to wait for
* bootstrapping to finish.
*
* See tests/playground.html for example usage.
*
* Exception: for speed and compatibility reasons, if this is
* script is loaded in Internet Explorer or from a host other than
* localhost, blockly_compressed.js (et al.) will be loaded
* instead. IE 11 doesn't understand modern JavaScript, and
* because of the sequential, non-parallel module loading carried
* out by thedeubg module loader can be painfully tedious over a
* slow network connection. (This can be overridden by the page
* if desired.)
*
* (Note also that this file eschews certain modern JS constructs,
* like template literals, for compatibility with IE 11.)
*
* The bootstrap code will consult a BLOCKLY_BOOTSTRAP_OPTIONS
* global variable to determine what to load. This must be set
* before loading this script. See documentation inline below.
*
*/
'use strict';
(function() {
// Values used to compute default bootstrap options.
const isIe = navigator.userAgent.indexOf('MSIE') !== -1 ||
navigator.appVersion.indexOf('Trident/') > -1;
const localhosts = ['localhost', '127.0.0.1', '[::1]'];
const isLocalhost = localhosts.includes(location.hostname);
const isFileUrl = location.origin === 'file://';
// Default bootstrap options. These can be overridden by setting
// the same property on BLOCKLY_BOOTSTRAP_OPTIONS.
const options = {
// Decide whether to use compressed mode or not. Please see issue
// #5557 for more information.
loadCompressed: isIe || !(isLocalhost || isFileUrl),
// URL of the blockly repository. This is needed for a few reasons:
//
// - We need an absolute path instead of relative path because the
// advanced_playground and the regular playground are in
// different folders.
// - We need to get the root directory for blockly because it is
// different for github.io, appspot and local.
//
// Default value will work so long as top-level page is loaded
// from somewhere in tests/.
root: window.location.href.replace(/\/tests\/.*$/, '/'),
// List of deps files to load. Paths relative to root.
depsFiles: [
'build/deps.js',
],
// List of goog.modules to goog.require.
requires: [
'Blockly',
'Blockly.libraryBlocks',
'Blockly.Dart.all',
'Blockly.JavaScript.all',
'Blockly.Lua.all',
'Blockly.PHP.all',
'Blockly.Python.all',
],
// List of scripts to load in compressed mode, instead of
// requires. Paths relative to root.
compressedScripts: [
'blockly_compressed.js',
'blocks_compressed.js',
'dart_compressed.js',
'javascript_compressed.js',
'lua_compressed.js',
'php_compressed.js',
'python_compressed.js',
],
// Additional scripts to be loaded after Blockly is loaded,
// whether Blockly is loaded from compressed or uncompressed.
// Paths relative to root.
additionalScripts: [
'msg/messages.js',
],
};
if (typeof window.BLOCKLY_BOOTSTRAP_OPTIONS === 'object') {
Object.assign(options, window.BLOCKLY_BOOTSTRAP_OPTIONS);
}
/* eslint-disable-next-line no-undef */
if (typeof module === 'object' && typeof module.exports === 'object') {
// Running in node.js. Maybe we wish to support this.
// blockly_uncompressed formerly did, though it appears that the
// code had not been working for some time (at least since PR
// #5718 back in December 2021. For now just throw an error.
throw new Error('Bootstrapping in node.js not implemented.');
}
// Create a global variable to remember some state that will be
// needed by later scripts.
window.bootstrapInfo = {
/** boolean */ compressed: options.loadCompressed,
/** ?Array<string> */ requires: null,
/** ?Promise */ done: null,
};
if (!options.loadCompressed) {
// We can load Blockly in uncompressed mode. Note that this section
// needs to parse in IE11 (mostly ES5.1, but allowing e.g. const),
// but it does not need to be _executable_ in IE11 - it is safe to
// use ES6 builtins.
// Disable loading of closure/goog/deps.js (which doesn't exist).
window.CLOSURE_NO_DEPS = true;
// Load the Closure Library's base.js (the only part of the
// libary we use, mainly for goog.require / goog.provide /
// goog.module).
document.write(
'<script src="' + options.root + '/closure/goog/base.js"></script>');
// Prevent spurious transpilation warnings.
document.write('<script>goog.TRANSPILE = "never";</script>');
// Load dependency graph info from the specified deps files -
// typically just build/deps.js. To update deps after changing
// any module's goog.requires / imports, run `npm run build:deps`.
for (let i = 0; i < options.depsFiles.length; i++) {
document.write(
'<script src="' + options.root + options.depsFiles[i] + '">' +
'</script>');
}
// Record require targets for bootstrap_helper.js.
window.bootstrapInfo.requires = options.requires;
// Assemble a list of module targets to bootstrap.
//
// The first group of targets are those listed in
// options.requires.
//
// The next target is a fake one that will load
// bootstrap_helper.js. We generate a call to goog.addDependency
// to tell the debug module loader that it can be loaded via a
// fake module name, and that it depends on all the targets in the
// first group (and indeed bootstrap_helper.js will make a call to
// goog.require for each one).
//
// We then create another target for each of
// options.additionalScripts, again generating calls to
// goog.addDependency for each one making it dependent on the
// previous one.
let requires = options.requires.slice();
const scripts =
['tests/bootstrap_helper.js'].concat(options.additionalScripts);
const scriptDeps = [];
for (let script, i = 0; script = scripts[i]; i++) {
const fakeModuleName = 'script.' + script.replace(/[./]/g, "-");
scriptDeps.push(' goog.addDependency(' +
quote('../../' + script) + ', [' + quote(fakeModuleName) +
'], [' + requires.map(quote).join() + "], {'lang': 'es6'});\n");
requires = [fakeModuleName];
}
// Finally, write out a script containing the generated
// goog.addDependency calls and a call to goog.bootstrap
// requesting the loading of the final target, which will cause
// all the previous ones to be loaded recursively. Wrap this in a
// promise and save it so it can be awaited in bootstrap_done.mjs.
document.write(
'<script>\n' + scriptDeps.join('') +
' window.bootstrapInfo.done = new Promise((resolve, reject) => {\n' +
' goog.bootstrap([' + requires.map(quote).join() + '], resolve);\n' +
' });\n' +
'</script>\n');
} else {
// We need to load Blockly in compressed mode. Load
// blockly_compressed.js et al. using <script> tags.
const scripts =
options.compressedScripts.concat(options.additionalScripts);
for (let i = 0; i < scripts.length; i++) {
document.write(
'<script src="' + options.root + scripts[i] + '"></script>');
}
}
return; // All done. Only helper functions after this point.
/**
* Convert a string into a string literal. Strictly speaking we
* only need to escape backslash, \r, \n, \u2028 (line separator),
* \u2029 (paragraph separator) and whichever quote character we're
* using, but for simplicity we escape all the control characters.
*
* Based on https://github.com/google/CodeCity/blob/master/server/code.js
*
* @param {string} str The string to convert.
* @return {string} The value s as a eval-able string literal.
*/
function quote(str) {
/* eslint-disable no-control-regex, no-multi-spaces */
/** Regexp for characters to be escaped in a single-quoted string. */
const singleRE = /[\x00-\x1f\\\u2028\u2029']/g;
/** Map of control character replacements. */
const replacements = {
'\x00': '\\0', '\x01': '\\x01', '\x02': '\\x02', '\x03': '\\x03',
'\x04': '\\x04', '\x05': '\\x05', '\x06': '\\x06', '\x07': '\\x07',
'\x08': '\\b', '\x09': '\\t', '\x0a': '\\n', '\x0b': '\\v',
'\x0c': '\\f', '\x0d': '\\r', '\x0e': '\\x0e', '\x0f': '\\x0f',
'"': '\\"', "'": "\\'", '\\': '\\\\',
'\u2028': '\\u2028', '\u2029': '\\u2029',
};
/* eslint-enable no-control-regex, no-multi-spaces */
/**
* Replacer function.
* @param {string} c Single UTF-16 code unit ("character") string to
* be replaced.
* @return {string} Multi-character string containing escaped
* representation of c.
*/
function replace(c) {
return replacements[c];
}
return "'" + str.replace(singleRE, replace) + "'";
}
})();