vis-dev-utils 4.0.44 → 5.0.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.
Files changed (92) hide show
  1. package/babel-preset/index.cjs +102 -0
  2. package/babel-preset/index.cjs.map +1 -0
  3. package/babel-preset/{index.js → index.mjs} +58 -31
  4. package/babel-preset/index.mjs.map +1 -0
  5. package/bin/ci-utils.js +35 -41
  6. package/bin/ci-utils.js.map +1 -1
  7. package/bin/generate-examples-index.js +779 -1265
  8. package/bin/generate-examples-index.js.map +1 -1
  9. package/bin/test-e2e-interop.js +431 -3492
  10. package/bin/test-e2e-interop.js.map +1 -1
  11. package/declarations/babel-preset/index.d.ts +23 -0
  12. package/declarations/babel-preset/index.d.ts.map +1 -0
  13. package/declarations/ci-utils/index.d.ts +2 -0
  14. package/declarations/ci-utils/index.d.ts.map +1 -0
  15. package/declarations/generate-examples-index/cli.d.ts +44 -0
  16. package/declarations/generate-examples-index/cli.d.ts.map +1 -0
  17. package/declarations/generate-examples-index/content-builder/builder.d.ts +53 -0
  18. package/declarations/generate-examples-index/content-builder/builder.d.ts.map +1 -0
  19. package/declarations/generate-examples-index/content-builder/common.d.ts +47 -0
  20. package/declarations/generate-examples-index/content-builder/common.d.ts.map +1 -0
  21. package/declarations/generate-examples-index/content-builder/format.d.ts +5 -0
  22. package/declarations/generate-examples-index/content-builder/format.d.ts.map +1 -0
  23. package/declarations/generate-examples-index/content-builder/html/index.d.ts +3 -0
  24. package/declarations/generate-examples-index/content-builder/html/index.d.ts.map +1 -0
  25. package/declarations/generate-examples-index/content-builder/index.d.ts +6 -0
  26. package/declarations/generate-examples-index/content-builder/index.d.ts.map +1 -0
  27. package/declarations/generate-examples-index/content-builder/md/index.d.ts +3 -0
  28. package/declarations/generate-examples-index/content-builder/md/index.d.ts.map +1 -0
  29. package/declarations/generate-examples-index/content-builder/playground/codepen.d.ts +6 -0
  30. package/declarations/generate-examples-index/content-builder/playground/codepen.d.ts.map +1 -0
  31. package/declarations/generate-examples-index/content-builder/playground/data.d.ts +8 -0
  32. package/declarations/generate-examples-index/content-builder/playground/data.d.ts.map +1 -0
  33. package/declarations/generate-examples-index/content-builder/playground/index.d.ts +4 -0
  34. package/declarations/generate-examples-index/content-builder/playground/index.d.ts.map +1 -0
  35. package/declarations/generate-examples-index/content-builder/playground/jsfiddle.d.ts +6 -0
  36. package/declarations/generate-examples-index/content-builder/playground/jsfiddle.d.ts.map +1 -0
  37. package/declarations/generate-examples-index/content-builder/screenshots/index.d.ts +26 -0
  38. package/declarations/generate-examples-index/content-builder/screenshots/index.d.ts.map +1 -0
  39. package/declarations/generate-examples-index/index.d.ts +2 -0
  40. package/declarations/generate-examples-index/index.d.ts.map +1 -0
  41. package/declarations/generate-examples-index/paths.d.ts +16 -0
  42. package/declarations/generate-examples-index/paths.d.ts.map +1 -0
  43. package/declarations/generate-examples-index/types.d.ts +61 -0
  44. package/declarations/generate-examples-index/types.d.ts.map +1 -0
  45. package/declarations/module/constants.d.ts +2 -0
  46. package/declarations/module/constants.d.ts.map +1 -0
  47. package/declarations/{generate-rollup-configuration → module/generate-rollup-configuration}/index.d.ts +4 -3
  48. package/declarations/module/generate-rollup-configuration/index.d.ts.map +1 -0
  49. package/declarations/{header.d.ts → module/header.d.ts} +1 -3
  50. package/declarations/module/header.d.ts.map +1 -0
  51. package/declarations/module/index.d.ts.map +1 -0
  52. package/declarations/module/inspect-npm-pack.d.ts +8 -0
  53. package/declarations/module/inspect-npm-pack.d.ts.map +1 -0
  54. package/declarations/module/util.d.ts.map +1 -0
  55. package/declarations/test-e2e-interop/cli.d.ts +18 -0
  56. package/declarations/test-e2e-interop/cli.d.ts.map +1 -0
  57. package/declarations/test-e2e-interop/index.d.ts +2 -0
  58. package/declarations/test-e2e-interop/index.d.ts.map +1 -0
  59. package/declarations/test-e2e-interop/test.d.ts +23 -0
  60. package/declarations/test-e2e-interop/test.d.ts.map +1 -0
  61. package/declarations/test-e2e-interop/util.d.ts +49 -0
  62. package/declarations/test-e2e-interop/util.d.ts.map +1 -0
  63. package/dist/vis-dev-utils.cjs +871 -0
  64. package/dist/vis-dev-utils.cjs.map +1 -0
  65. package/dist/vis-dev-utils.mjs +864 -0
  66. package/dist/vis-dev-utils.mjs.map +1 -0
  67. package/package.json +81 -59
  68. package/babel-register/index.js +0 -110
  69. package/babel-register/index.js.map +0 -1
  70. package/declarations/constants.d.ts +0 -2
  71. package/declarations/constants.d.ts.map +0 -1
  72. package/declarations/generate-rollup-configuration/index.d.ts.map +0 -1
  73. package/declarations/header.d.ts.map +0 -1
  74. package/declarations/index.d.ts.map +0 -1
  75. package/declarations/inspect-npm-pack.d.ts +0 -8
  76. package/declarations/inspect-npm-pack.d.ts.map +0 -1
  77. package/declarations/util.d.ts.map +0 -1
  78. package/dist/vis-dev-utils.cjs.js +0 -777
  79. package/dist/vis-dev-utils.cjs.js.map +0 -1
  80. package/dist/vis-dev-utils.esm.js +0 -771
  81. package/dist/vis-dev-utils.esm.js.map +0 -1
  82. package/lib/header.d.ts +0 -38
  83. package/lib/header.d.ts.map +0 -1
  84. package/lib/header.js +0 -85
  85. package/lib/header.js.map +0 -1
  86. package/lib/inspect-npm-pack.d.ts +0 -8
  87. package/lib/inspect-npm-pack.d.ts.map +0 -1
  88. package/lib/inspect-npm-pack.js +0 -74
  89. package/lib/inspect-npm-pack.js.map +0 -1
  90. /package/declarations/{index.d.ts → module/index.d.ts} +0 -0
  91. /package/declarations/{util.d.ts → module/util.d.ts} +0 -0
  92. /package/eslint-shareable-config/{index.js → index.cjs} +0 -0
@@ -6,8 +6,8 @@
6
6
  *
7
7
  * Development utilities for the Vis family projects.
8
8
  *
9
- * @version 4.0.44
10
- * @date 2023-11-11T18:46:09.646Z
9
+ * @version 5.0.0
10
+ * @date 2025-07-12T17:03:14.214Z
11
11
  *
12
12
  * @copyright (c) 2011-2017 Almende B.V, http://almende.com
13
13
  * @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
@@ -26,893 +26,554 @@
26
26
  * vis.js may be distributed under either license.
27
27
  */
28
28
 
29
- 'use strict';
29
+ import * as cheerio from 'cheerio';
30
+ import fs from 'node:fs';
31
+ import util, { promisify } from 'node:util';
32
+ import yargs from 'yargs';
33
+ import { relative, resolve, dirname, basename, sep, posix, join } from 'node:path';
34
+ import puppeteer from 'puppeteer';
35
+ import prettier from 'prettier';
36
+ import { Jimp } from 'jimp';
37
+ import { hideBin } from 'yargs/helpers';
38
+ import { createHash } from 'node:crypto';
30
39
 
31
- var _toConsumableArray = require('@babel/runtime-corejs3/helpers/toConsumableArray');
32
- var _asyncToGenerator = require('@babel/runtime-corejs3/helpers/asyncToGenerator');
33
- var _regeneratorRuntime = require('@babel/runtime-corejs3/regenerator');
34
- var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
35
- var _Number$isNaN = require('@babel/runtime-corejs3/core-js-stable/number/is-nan');
36
- var _trimInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/trim');
37
- var _mapInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/map');
38
- var _Promise = require('@babel/runtime-corejs3/core-js-stable/promise');
39
- var _endsWithInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/ends-with');
40
- var _reduceInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/reduce');
41
- var _concatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/concat');
42
- var _sortInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/sort');
43
- var _forEachInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/for-each');
44
- var $ = require('cheerio');
45
- var fs = require('node:fs');
46
- var util = require('node:util');
47
- var yargs = require('yargs');
48
- var node_path = require('node:path');
49
- var _Object$getOwnPropertySymbols = require('@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols');
50
- var _filterInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/filter');
51
- var _Object$getOwnPropertyDescriptor = require('@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor');
52
- var _Object$getOwnPropertyDescriptors = require('@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors');
53
- var _Object$defineProperties = require('@babel/runtime-corejs3/core-js-stable/object/define-properties');
54
- var _Object$defineProperty = require('@babel/runtime-corejs3/core-js-stable/object/define-property');
55
- var _Array$from = require('@babel/runtime-corejs3/core-js-stable/array/from');
56
- var _Symbol = require('@babel/runtime-corejs3/core-js-stable/symbol');
57
- var _getIteratorMethod = require('@babel/runtime-corejs3/core-js/get-iterator-method');
58
- var _Array$isArray = require('@babel/runtime-corejs3/core-js-stable/array/is-array');
59
- var _defineProperty = require('@babel/runtime-corejs3/helpers/defineProperty');
60
- var _classCallCheck = require('@babel/runtime-corejs3/helpers/classCallCheck');
61
- var _createClass = require('@babel/runtime-corejs3/helpers/createClass');
62
- var _flatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/flat');
63
- var _everyInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/every');
64
- var _sliceInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/slice');
65
- var _fillInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/fill');
66
- var _padStartInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/pad-start');
67
- var _reverseInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/reverse');
68
- var _spliceInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/splice');
69
- var _flatMapInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/flat-map');
70
- var _Object$keys = require('@babel/runtime-corejs3/core-js-stable/object/keys');
71
- var puppeteer = require('puppeteer');
72
- var _typeof = require('@babel/runtime-corejs3/helpers/typeof');
73
- var _Date$now = require('@babel/runtime-corejs3/core-js-stable/date/now');
74
- var prettier = require('prettier');
75
- var _findInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/find');
76
- var _slicedToArray = require('@babel/runtime-corejs3/helpers/slicedToArray');
77
- var _Object$entries = require('@babel/runtime-corejs3/core-js-stable/object/entries');
78
- var Jimp = require('jimp');
79
- var _repeatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/repeat');
80
- var _startsWithInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/starts-with');
81
- var node_crypto = require('node:crypto');
82
-
83
- /**
84
- * @param value
85
- */
86
40
  function isExample(value) {
87
- return _typeof(value) === "object" && value !== null && typeof value.path === "string";
41
+ return typeof value === "object" && value !== null && typeof value.path === "string";
88
42
  }
89
- /**
90
- *
91
- */
92
43
  function measureStartStopMs() {
93
- var start = _Date$now();
94
- return function () {
95
- var stop = _Date$now();
96
- return {
97
- start: start,
98
- stop: stop
99
- };
44
+ const start = Date.now();
45
+ return () => {
46
+ const stop = Date.now();
47
+ return { start, stop };
100
48
  };
101
49
  }
102
- /**
103
- * @param reports
104
- * @param fallback
105
- */
106
- function reduceReports(reports) {
107
- var _reports$reduce;
108
- var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
109
- count: 0,
110
- result: "fulfilled",
111
- start: -1,
112
- stop: -1
113
- };
114
- return (_reports$reduce = _reduceInstanceProperty(reports).call(reports, function (acc, val) {
115
- var _acc$count, _val$count, _context, _acc$result, _acc$start, _acc$stop;
50
+ function reduceReports(reports, fallback = {
51
+ count: 0,
52
+ result: "fulfilled",
53
+ start: -1,
54
+ stop: -1
55
+ }) {
56
+ return reports.reduce((acc, val) => {
116
57
  return {
117
- count: ((_acc$count = acc === null || acc === void 0 ? void 0 : acc.count) !== null && _acc$count !== void 0 ? _acc$count : 0) + ((_val$count = val === null || val === void 0 ? void 0 : val.count) !== null && _val$count !== void 0 ? _val$count : 0),
118
- result: _everyInstanceProperty(_context = [(_acc$result = acc === null || acc === void 0 ? void 0 : acc.result) !== null && _acc$result !== void 0 ? _acc$result : "fulfilled", val.result]).call(_context, function (result) {
119
- return result === "fulfilled";
120
- }) ? "fulfilled" : "rejected",
121
- start: Math.min((_acc$start = acc === null || acc === void 0 ? void 0 : acc.start) !== null && _acc$start !== void 0 ? _acc$start : Number.POSITIVE_INFINITY, val.start),
122
- stop: Math.max((_acc$stop = acc === null || acc === void 0 ? void 0 : acc.stop) !== null && _acc$stop !== void 0 ? _acc$stop : Number.NEGATIVE_INFINITY, val.stop)
58
+ count: (acc?.count ?? 0) + (val?.count ?? 0),
59
+ result: [acc?.result ?? "fulfilled", val.result].every(
60
+ (result) => result === "fulfilled"
61
+ ) ? "fulfilled" : "rejected",
62
+ start: Math.min(acc?.start ?? Number.POSITIVE_INFINITY, val.start),
63
+ stop: Math.max(acc?.stop ?? Number.NEGATIVE_INFINITY, val.stop)
123
64
  };
124
- }, null)) !== null && _reports$reduce !== void 0 ? _reports$reduce : fallback;
65
+ }, null) ?? fallback;
125
66
  }
126
- /**
127
- * @param root0
128
- * @param root0.start
129
- * @param root0.stop
130
- */
131
- function formatStartStopMs(_ref) {
132
- var start = _ref.start,
133
- stop = _ref.stop;
134
- return "".concat((Math.round((stop - start) / 100) / 10).toFixed(1), "s");
67
+ function formatStartStopMs({ start, stop }) {
68
+ return `${(Math.round((stop - start) / 100) / 10).toFixed(1)}s`;
135
69
  }
136
70
 
137
- var formatCSS = function formatCSS(css) {
138
- return prettier.format(css || "", {
139
- filepath: "style.css"
140
- });
141
- };
142
- var formatHTML = function formatHTML(html) {
143
- return prettier.format(html || "", {
144
- filepath: "index.html"
145
- });
146
- };
147
- var formatJS = function formatJS(js) {
148
- return prettier.format(js || "", {
149
- filepath: "script.js"
150
- });
151
- };
152
- var formatMD = function formatMD(md) {
153
- return prettier.format(md || "", {
154
- filepath: "README.md"
155
- });
156
- };
71
+ const formatCSS = (css) => prettier.format(css || "", { filepath: "style.css" });
72
+ const formatHTML = (html) => prettier.format(html || "", { filepath: "index.html" });
73
+ const formatJS = (js) => prettier.format(js || "", { filepath: "script.js" });
74
+ const formatMD = (md) => prettier.format(md || "", { filepath: "README.md" });
157
75
 
158
- var template$1 = "<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>CodePen</title>\n </head>\n <body>\n <form\n id=\"form\"\n action=\"https://codepen.io/pen/define\"\n method=\"post\"\n target=\"_self\"\n >\n <input type=\"hidden\" name=\"data\" />\n <button id=\"open\" alt=\"JSFiddle\" title=\"JSFiddle\">Open CodePen</button>\n </form>\n\n <script type=\"text/javascript\">\n document.getElementById(\"open\").click();\n </script>\n </body>\n</html>\n";
76
+ var codepen_template_default = '<html>\n <head>\n <meta charset="utf-8" />\n <title>CodePen</title>\n </head>\n <body>\n <form\n id="form"\n action="https://codepen.io/pen/define"\n method="post"\n target="_self"\n >\n <input type="hidden" name="data" />\n <button id="open" alt="JSFiddle" title="JSFiddle">Open CodePen</button>\n </form>\n\n <script type="text/javascript">\n document.getElementById("open").click();\n <\/script>\n </body>\n</html>\n';
159
77
 
160
- /**
161
- * @param example
162
- */
163
78
  function generateCodePenPage(example) {
164
- var data = example.playground;
165
- var title = example.titles.join(" | ");
166
- var page = $.load(template$1);
79
+ const data = example.playground;
80
+ const title = example.titles.join(" | ");
81
+ const page = cheerio.load(codepen_template_default);
167
82
  page("title").text(title);
168
- var form = page("#form");
169
- _findInstanceProperty(form).call(form, 'input[name="data"]').attr("value", _JSON$stringify({
170
- css: data.code.css,
171
- css_external: data.resources.css.join(";"),
172
- html: data.code.html,
173
- js: data.code.js,
174
- js_external: data.resources.js.join(";"),
175
- title: example.titles.join(" | ")
176
- }));
83
+ const form = page("#form");
84
+ form.find('input[name="data"]').attr(
85
+ "value",
86
+ JSON.stringify({
87
+ css: data.code.css,
88
+ css_external: data.resources.css.join(";"),
89
+ html: data.code.html,
90
+ js: data.code.js,
91
+ js_external: data.resources.js.join(";"),
92
+ title: example.titles.join(" | ")
93
+ })
94
+ );
177
95
  return page.html();
178
96
  }
179
97
 
180
- /**
181
- * @param baseURL
182
- * @param example$
183
- * @param examplePath
184
- */
185
- function generatePlaygroundData(baseURL, example$, examplePath) {
186
- var _context, _context2, _context3, _context5, _context6, _context7, _context8, _context9, _context10, _context11, _context12, _context13, _context14;
187
- // JavaScript
188
- var eventListeners = _mapInstanceProperty(_context = _mapInstanceProperty(_context2 = _filterInstanceProperty(_context3 = _Object$entries(example$("body").get(0).attribs)).call(_context3, function (_ref) {
189
- var _ref2 = _slicedToArray(_ref, 1),
190
- name = _ref2[0];
191
- return /^on/.test(name);
192
- })).call(_context2, function (_ref3) {
193
- var _ref4 = _slicedToArray(_ref3, 2),
194
- name = _ref4[0],
195
- value = _ref4[1];
196
- return [_sliceInstanceProperty(name).call(name, 2), "".concat(value)];
197
- })).call(_context, function (_ref5) {
198
- var _context4;
199
- var _ref6 = _slicedToArray(_ref5, 2),
200
- name = _ref6[0],
201
- value = _ref6[1];
202
- return _concatInstanceProperty(_context4 = "window.addEventListener(\"".concat(name, "\", () => { ")).call(_context4, value, " });");
203
- }).join("\n");
204
- var js = formatJS(_mapInstanceProperty(_context5 = _mapInstanceProperty(_context6 = example$("script")).call(_context6, function (_i, elem) {
205
- return elem.children[0];
206
- }).get()).call(_context5, function (elem) {
207
- return elem.data;
208
- }).join("") + "\n\n;" + eventListeners);
209
- // Cascading Style Sheets
210
- var css = formatCSS(_mapInstanceProperty(_context7 = _mapInstanceProperty(_context8 = example$("style")).call(_context8, function (_i, elem) {
211
- return elem.children[0];
212
- }).get()).call(_context7, function (elem) {
213
- return elem.data;
214
- }).join(""));
215
- // Hypertext Markup Language
216
- var $html = $.load(example$("body").html() || "");
98
+ async function generatePlaygroundData(baseURL, example$, examplePath) {
99
+ const firstBodyChild = example$("body").get(0);
100
+ if (firstBodyChild == null) {
101
+ throw new Error("Example body has no children.");
102
+ }
103
+ const eventListeners = Object.entries(firstBodyChild.attribs).filter(([name]) => /^on/.test(name)).map(([name, value]) => [name.slice(2), `${value}`]).map(
104
+ ([name, value]) => `window.addEventListener("${name}", () => { ${value} });`
105
+ ).join("\n");
106
+ const js = formatJS(
107
+ example$("script").map((_i, elem) => elem.children[0]).get().map((elem) => elem.data).join("") + "\n\n;" + eventListeners
108
+ );
109
+ const css = formatCSS(
110
+ example$("style").map((_i, elem) => elem.children[0]).get().map((elem) => elem.data).join("")
111
+ );
112
+ const $html = cheerio.load(example$("body").html() || "");
217
113
  $html("script").remove();
218
- var html = formatHTML($html("body").html());
219
- // Resources
220
- var fixPath = function fixPath(rawPath) {
221
- return /^https?:\/\//.test(rawPath) ?
114
+ const html = formatHTML($html("body").html());
115
+ const fixPath = (rawPath) => /^https?:\/\//.test(rawPath) ? (
222
116
  // World wide web absolute.
223
- rawPath : /^\//.test(rawPath) ?
117
+ rawPath
118
+ ) : /^\//.test(rawPath) ? (
224
119
  // Domain absolute.
225
- baseURL + _sliceInstanceProperty(rawPath).call(rawPath, 1) :
120
+ baseURL + rawPath.slice(1)
121
+ ) : (
226
122
  //Relative.
227
- baseURL + node_path.relative(process.cwd(), node_path.resolve(node_path.dirname(examplePath), rawPath));
228
- };
229
- var resources = {
230
- js: _mapInstanceProperty(_context9 = _filterInstanceProperty(_context10 = _mapInstanceProperty(_context11 = example$("script")).call(_context11, function (_i, elem) {
231
- return $.load(elem)("script").attr("src");
232
- }).get()).call(_context10, function (src) {
233
- return typeof src === "string";
234
- })).call(_context9, fixPath),
235
- css: _mapInstanceProperty(_context12 = _filterInstanceProperty(_context13 = _mapInstanceProperty(_context14 = example$("link[rel='stylesheet']")).call(_context14, function (_i, elem) {
236
- return $.load(elem)("script").attr("href");
237
- }).get()).call(_context13, function (href) {
238
- return typeof href === "string";
239
- })).call(_context12, fixPath)
123
+ baseURL + relative(process.cwd(), resolve(dirname(examplePath), rawPath))
124
+ );
125
+ const resources = {
126
+ js: example$("script").map(
127
+ (_i, elem) => cheerio.load(elem)("script").attr("src")
128
+ ).get().filter((src) => typeof src === "string").map(fixPath),
129
+ css: example$("link[rel='stylesheet']").map(
130
+ (_i, elem) => cheerio.load(elem)("script").attr("href")
131
+ ).get().filter((href) => typeof href === "string").map(fixPath)
240
132
  };
241
133
  return {
242
134
  code: {
243
- css: css,
244
- html: html,
245
- js: js
135
+ css: await css,
136
+ html: await html,
137
+ js: await js
246
138
  },
247
- resources: resources
139
+ resources
248
140
  };
249
141
  }
250
142
 
251
- var template = "<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>JSFiddle</title>\n </head>\n <body>\n <form\n id=\"form\"\n action=\"https://jsfiddle.net/api/post/library/pure/\"\n method=\"post\"\n target=\"_self\"\n >\n <input type=\"hidden\" name=\"css\" />\n <input type=\"hidden\" name=\"html\" />\n <input type=\"hidden\" name=\"js\" />\n <input type=\"hidden\" name=\"resources\" />\n <input type=\"hidden\" name=\"title\" />\n <input type=\"hidden\" name=\"wrap\" />\n <button id=\"open\" alt=\"JSFiddle\" title=\"JSFiddle\">Open JSFiddle</button>\n </form>\n\n <script type=\"text/javascript\">\n document.getElementById(\"open\").click();\n </script>\n </body>\n</html>\n";
143
+ var jsfiddle_template_default = '<html>\n <head>\n <meta charset="utf-8" />\n <title>JSFiddle</title>\n </head>\n <body>\n <form\n id="form"\n action="https://jsfiddle.net/api/post/library/pure/"\n method="post"\n target="_self"\n >\n <input type="hidden" name="css" />\n <input type="hidden" name="html" />\n <input type="hidden" name="js" />\n <input type="hidden" name="resources" />\n <input type="hidden" name="title" />\n <input type="hidden" name="wrap" />\n <button id="open" alt="JSFiddle" title="JSFiddle">Open JSFiddle</button>\n </form>\n\n <script type="text/javascript">\n document.getElementById("open").click();\n <\/script>\n </body>\n</html>\n';
252
144
 
253
- /**
254
- * @param example
255
- */
256
145
  function generateJSFiddlePage(example) {
257
- var _context;
258
- var data = example.playground;
259
- var title = example.titles.join(" | ");
260
- var resources = _concatInstanceProperty(_context = []).call(_context, _toConsumableArray(data.resources.css), _toConsumableArray(data.resources.js)).join(",");
261
- var page = $.load(template);
146
+ const data = example.playground;
147
+ const title = example.titles.join(" | ");
148
+ const resources = [...data.resources.css, ...data.resources.js].join(",");
149
+ const page = cheerio.load(jsfiddle_template_default);
262
150
  page("title").text(title);
263
- var form = page("#form");
264
- // Playground data.
265
- _findInstanceProperty(form).call(form, 'input[name="css"]').attr("value", data.code.css);
266
- _findInstanceProperty(form).call(form, 'input[name="html"]').attr("value", data.code.html);
267
- _findInstanceProperty(form).call(form, 'input[name="js"]').attr("value", data.code.js);
268
- _findInstanceProperty(form).call(form, 'input[name="resources"]').attr("value", resources);
269
- _findInstanceProperty(form).call(form, 'input[name="title"]').attr("value", title);
270
- // Don't run JS before the DOM is ready.
271
- _findInstanceProperty(form).call(form, 'input[name="wrap"]').attr("value", "b");
151
+ const form = page("#form");
152
+ form.find('input[name="css"]').attr("value", data.code.css);
153
+ form.find('input[name="html"]').attr("value", data.code.html);
154
+ form.find('input[name="js"]').attr("value", data.code.js);
155
+ form.find('input[name="resources"]').attr("value", resources);
156
+ form.find('input[name="title"]').attr("value", title);
157
+ form.find('input[name="wrap"]').attr("value", "b");
272
158
  return page.html();
273
159
  }
274
160
 
275
- var commonScreenshotScript = "/* global window: false */\n\n/**\n * Simulates confirmation usind window.confirm and window.alert otherwise the\n * screenshot generator would just hang forever.\n */\nwindow.realAlert = window.alert;\nwindow.alert = function () {};\nwindow.confirm = function () {\n return true;\n};\n\n/**\n * Wait for the page to report it's ready to take a screenshot.\n */\nwindow.readyToTakeAScreenshot = new Promise(function (resolve) {\n window.takeScreenshot = resolve;\n});\n";
161
+ var screenshot_script_js_default = "/* global window: false */\n\n/**\n * Simulates confirmation usind window.confirm and window.alert otherwise the\n * screenshot generator would just hang forever.\n */\nwindow.realAlert = window.alert;\nwindow.alert = function () {};\nwindow.confirm = function () {\n return true;\n};\n\n/**\n * Wait for the page to report it's ready to take a screenshot.\n */\nwindow.readyToTakeAScreenshot = new Promise(function (resolve) {\n window.takeScreenshot = resolve;\n});\n";
276
162
 
277
- function _createForOfIteratorHelper$3(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (_Array$isArray(o) || (it = _unsupportedIterableToArray$3(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
278
- function _unsupportedIterableToArray$3(o, minLen) { var _context5; if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(o, minLen); var n = _sliceInstanceProperty(_context5 = Object.prototype.toString.call(o)).call(_context5, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen); }
279
- function _arrayLikeToArray$3(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
280
- var unlink = util.promisify(fs.unlink);
281
- var writeFile$1 = util.promisify(fs.writeFile);
282
- /**
283
- * Check if the screenshot is valid. At the moment this simply considers
284
- * everything except for solid color images as valid. This works pretty well
285
- * though may yield some false positives.
286
- *
287
- * @param screenshot - The binary data of the screenshot.
288
- * @returns True for valid and false for invalid.
289
- */
290
- function isScreenshotValid(_x) {
291
- return _isScreenshotValid.apply(this, arguments);
292
- }
293
- /**
294
- * Capture an element on the example's page and save the screenshot to the
295
- * disk as a PNG file.
296
- *
297
- * @param browser - Puppeteer's browser instance.
298
- * @param config - See the type's docs for detail.
299
- * @returns Whether or not the screenshot passed validation check.
300
- */
301
- function _isScreenshotValid() {
302
- _isScreenshotValid = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(screenshot) {
303
- var image, firstPixel, x, y;
304
- return _regeneratorRuntime.wrap(function _callee$(_context) {
305
- while (1) switch (_context.prev = _context.next) {
306
- case 0:
307
- _context.next = 2;
308
- return Jimp.read(screenshot);
309
- case 2:
310
- image = _context.sent;
311
- firstPixel = image.getPixelColor(0, 0);
312
- x = 0;
313
- case 5:
314
- if (!(x < image.getWidth())) {
315
- _context.next = 16;
316
- break;
317
- }
318
- y = 0;
319
- case 7:
320
- if (!(y < image.getHeight())) {
321
- _context.next = 13;
322
- break;
323
- }
324
- if (!(firstPixel !== image.getPixelColor(x, y))) {
325
- _context.next = 10;
326
- break;
327
- }
328
- return _context.abrupt("return", true);
329
- case 10:
330
- ++y;
331
- _context.next = 7;
332
- break;
333
- case 13:
334
- ++x;
335
- _context.next = 5;
336
- break;
337
- case 16:
338
- return _context.abrupt("return", false);
339
- case 17:
340
- case "end":
341
- return _context.stop();
163
+ const unlink = promisify(fs.unlink);
164
+ const writeFile$1 = promisify(fs.writeFile);
165
+ async function isScreenshotValid(screenshot) {
166
+ const image = await Jimp.read(screenshot);
167
+ const firstPixel = image.getPixelColor(0, 0);
168
+ for (let x = 0; x < image.width; ++x) {
169
+ for (let y = 0; y < image.height; ++y) {
170
+ if (firstPixel !== image.getPixelColor(x, y)) {
171
+ return true;
342
172
  }
343
- }, _callee);
344
- }));
345
- return _isScreenshotValid.apply(this, arguments);
346
- }
347
- function generateScreenshot(_x2, _x3) {
348
- return _generateScreenshot.apply(this, arguments);
173
+ }
174
+ }
175
+ return false;
349
176
  }
350
- function _generateScreenshot() {
351
- _generateScreenshot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(browser, config) {
352
- var debug, example, height, screenshotScript, width, cleanup, tmpPath, screenshotPage, context, page, $element, _context2, screenshot, _context3, _iterator, _step, callback;
353
- return _regeneratorRuntime.wrap(function _callee2$(_context4) {
354
- while (1) switch (_context4.prev = _context4.next) {
355
- case 0:
356
- debug = config.debug, example = config.example, height = config.height, screenshotScript = config.screenshotScript, width = config.width;
357
- cleanup = [];
358
- _context4.prev = 2;
359
- // Prepare the page. It has to be written to the disk so that files with
360
- // relative URLs can be loaded.
361
- tmpPath = node_path.resolve(node_path.dirname(example.paths.page.local), ".tmp.example.screenshot." + node_path.basename(example.paths.page.local));
362
- screenshotPage = $.load(example.html);
363
- screenshotPage("head").prepend($.load([])("<script>").attr("type", "text/javascript").text("window.DEBUG = ".concat(true, ";")), $.load([])("<script>").attr("type", "text/javascript").text(commonScreenshotScript), $.load([])("<script>").attr("type", "text/javascript").text(screenshotScript), $.load([])("<style>").attr("type", "text/css").text(["".concat(example.selector, " {"), " border: none !important;", "", " min-width: ".concat(width, "px !important;"), " min-height: ".concat(height, "px !important;"), " width: ".concat(width, "px !important;"), " height: ".concat(height, "px !important;"), " max-width: ".concat(width, "px !important;"), " max-height: ".concat(height, "px !important;"), "}"].join("\n")));
364
- _context4.next = 8;
365
- return writeFile$1(tmpPath, formatHTML(screenshotPage.html()));
366
- case 8:
367
- if (!debug) {
368
- cleanup.push(function () {
369
- return unlink(tmpPath);
370
- });
371
- }
372
- _context4.next = 11;
373
- return browser.createIncognitoBrowserContext();
374
- case 11:
375
- context = _context4.sent;
376
- if (!debug) {
377
- cleanup.push(function () {
378
- return context.close();
379
- });
380
- }
381
- _context4.next = 15;
382
- return context.newPage();
383
- case 15:
384
- page = _context4.sent;
385
- if (!debug) {
386
- cleanup.push(function () {
387
- return page.close();
388
- });
389
- }
390
- _context4.next = 19;
391
- return page.setViewport({
392
- width: width + 50,
393
- height: height + 50
394
- });
395
- case 19:
396
- _context4.next = 21;
397
- return page.goto("file://" + tmpPath.split(node_path.sep).join(node_path.posix.sep));
398
- case 21:
399
- _context4.next = 23;
400
- return page.waitForSelector(example.selector, {
401
- visible: true,
402
- timeout: example.timeout * 1000
403
- });
404
- case 23:
405
- if (!(example.delay === "call")) {
406
- _context4.next = 28;
407
- break;
408
- }
409
- _context4.next = 26;
410
- return page.evaluate("function fn() { return window.readyToTakeAScreenshot; }");
411
- case 26:
412
- _context4.next = 30;
413
- break;
414
- case 28:
415
- _context4.next = 30;
416
- return page.waitForTimeout(example.delay * 1000);
417
- case 30:
418
- _context4.next = 32;
419
- return page.$(example.selector);
420
- case 32:
421
- $element = _context4.sent;
422
- if (!($element == null)) {
423
- _context4.next = 35;
424
- break;
425
- }
426
- throw new Error(_concatInstanceProperty(_context2 = "Element \"".concat(example.selector, "\" not found in ")).call(_context2, example.path, "."));
427
- case 35:
428
- _context4.next = 37;
429
- return $element.evaluate(function (element) {
430
- element.scrollIntoView();
431
- });
432
- case 37:
433
- _context4.next = 39;
434
- return $element.screenshot({
435
- encoding: "binary"
436
- });
437
- case 39:
438
- screenshot = _context4.sent;
439
- if (!(screenshot == null)) {
440
- _context4.next = 44;
441
- break;
442
- }
443
- throw new Error("Failed to take screenshot of \u201C".concat(example.paths.page, "\u201D"));
444
- case 44:
445
- if (!(typeof screenshot === "string")) {
446
- _context4.next = 46;
447
- break;
448
- }
449
- throw new Error("Failed to get the binary data of the screenshot of \u201C".concat(example.paths.page, "\u201D"));
450
- case 46:
451
- _context4.next = 48;
452
- return writeFile$1(example.paths.screenshot.local, screenshot);
453
- case 48:
454
- return _context4.abrupt("return", isScreenshotValid(screenshot));
455
- case 51:
456
- _context4.prev = 51;
457
- _context4.t0 = _context4["catch"](2);
458
- console.error(_context4.t0);
459
- return _context4.abrupt("return", false);
460
- case 55:
461
- _context4.prev = 55;
462
- _iterator = _createForOfIteratorHelper$3(_reverseInstanceProperty(_context3 = _spliceInstanceProperty(cleanup).call(cleanup, 0)).call(_context3));
463
- _context4.prev = 57;
464
- _iterator.s();
465
- case 59:
466
- if ((_step = _iterator.n()).done) {
467
- _context4.next = 71;
468
- break;
469
- }
470
- callback = _step.value;
471
- _context4.prev = 61;
472
- _context4.next = 64;
473
- return callback();
474
- case 64:
475
- _context4.next = 69;
476
- break;
477
- case 66:
478
- _context4.prev = 66;
479
- _context4.t1 = _context4["catch"](61);
480
- console.error(_context4.t1);
481
- case 69:
482
- _context4.next = 59;
483
- break;
484
- case 71:
485
- _context4.next = 76;
486
- break;
487
- case 73:
488
- _context4.prev = 73;
489
- _context4.t2 = _context4["catch"](57);
490
- _iterator.e(_context4.t2);
491
- case 76:
492
- _context4.prev = 76;
493
- _iterator.f();
494
- return _context4.finish(76);
495
- case 79:
496
- return _context4.finish(55);
497
- case 80:
498
- case "end":
499
- return _context4.stop();
177
+ async function generateScreenshot(browser, config) {
178
+ const { debug, example, height, screenshotScript, width } = config;
179
+ const cleanup = [];
180
+ try {
181
+ const tmpPath = resolve(
182
+ dirname(example.paths.page.local),
183
+ ".tmp.example.screenshot." + basename(example.paths.page.local)
184
+ );
185
+ const screenshotPage = cheerio.load(example.html);
186
+ screenshotPage("head").prepend(
187
+ cheerio.load([])("<script>").attr("type", "text/javascript").text(`window.DEBUG = ${true};`),
188
+ cheerio.load([])("<script>").attr("type", "text/javascript").text(screenshot_script_js_default),
189
+ cheerio.load([])("<script>").attr("type", "text/javascript").text(screenshotScript),
190
+ cheerio.load([])("<style>").attr("type", "text/css").text(
191
+ [
192
+ `${example.selector} {`,
193
+ " border: none !important;",
194
+ "",
195
+ ` min-width: ${width}px !important;`,
196
+ ` min-height: ${height}px !important;`,
197
+ ` width: ${width}px !important;`,
198
+ ` height: ${height}px !important;`,
199
+ ` max-width: ${width}px !important;`,
200
+ ` max-height: ${height}px !important;`,
201
+ "}"
202
+ ].join("\n")
203
+ )
204
+ );
205
+ await writeFile$1(tmpPath, await formatHTML(screenshotPage.html()));
206
+ if (!debug) {
207
+ cleanup.push(() => unlink(tmpPath));
208
+ }
209
+ const context = await browser.createBrowserContext();
210
+ if (!debug) {
211
+ cleanup.push(() => context.close());
212
+ }
213
+ const page = await context.newPage();
214
+ if (!debug) {
215
+ cleanup.push(() => page.close());
216
+ }
217
+ await page.setViewport({ width: width + 50, height: height + 50 });
218
+ await page.goto("file://" + tmpPath.split(sep).join(posix.sep));
219
+ await page.waitForSelector(example.selector, {
220
+ visible: true,
221
+ timeout: example.timeout * 1e3
222
+ });
223
+ const { delay } = example;
224
+ if (delay === "call") {
225
+ await page.evaluate(
226
+ "function fn() { return window.readyToTakeAScreenshot; }"
227
+ );
228
+ } else {
229
+ await new Promise(
230
+ (resolve2) => void setTimeout(resolve2, delay * 1e3)
231
+ );
232
+ }
233
+ const $element = await page.$(example.selector);
234
+ if ($element == null) {
235
+ throw new Error(
236
+ `Element "${example.selector}" not found in ${example.path}.`
237
+ );
238
+ }
239
+ await $element.evaluate((element) => {
240
+ element.scrollIntoView();
241
+ });
242
+ const screenshot = await $element.screenshot({
243
+ encoding: "binary"
244
+ });
245
+ if (screenshot == null) {
246
+ throw new Error(`Failed to take screenshot of \u201C${example.paths.page}\u201D`);
247
+ } else if (typeof screenshot === "string") {
248
+ throw new Error(
249
+ `Failed to get the binary data of the screenshot of \u201C${example.paths.page}\u201D`
250
+ );
251
+ }
252
+ await writeFile$1(example.paths.screenshot.local, screenshot);
253
+ return isScreenshotValid(Buffer.from(screenshot));
254
+ } catch (error) {
255
+ console.error(error);
256
+ return false;
257
+ } finally {
258
+ for (const callback of cleanup.splice(0).reverse()) {
259
+ try {
260
+ await callback();
261
+ } catch (error) {
262
+ console.error(error);
500
263
  }
501
- }, _callee2, null, [[2, 51, 55, 80], [57, 73, 76, 79], [61, 66]]);
502
- }));
503
- return _generateScreenshot.apply(this, arguments);
264
+ }
265
+ }
504
266
  }
505
267
 
506
- function _createForOfIteratorHelper$2(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (_Array$isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
507
- function _unsupportedIterableToArray$2(o, minLen) { var _context24; if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = _sliceInstanceProperty(_context24 = Object.prototype.toString.call(o)).call(_context24, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); }
508
- function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
509
- function ownKeys$1(e, r) { var t = _Object$keys(e); if (_Object$getOwnPropertySymbols) { var o = _Object$getOwnPropertySymbols(e); r && (o = _filterInstanceProperty(o).call(o, function (r) { return _Object$getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
510
- function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var _context22, _context23; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty(_context22 = ownKeys$1(Object(t), !0)).call(_context22, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(e, _Object$getOwnPropertyDescriptors(t)) : _forEachInstanceProperty(_context23 = ownKeys$1(Object(t))).call(_context23, function (r) { _Object$defineProperty(e, r, _Object$getOwnPropertyDescriptor(t, r)); }); } return e; }
511
- var collator = new Intl.Collator("US");
512
- var writeFile = util.promisify(fs.writeFile);
513
- var ContentBuilder = /*#__PURE__*/function () {
514
- function ContentBuilder(_config) {
515
- _classCallCheck(this, ContentBuilder);
268
+ const collator = new Intl.Collator("US");
269
+ const writeFile = promisify(fs.writeFile);
270
+ class ContentBuilder {
271
+ constructor(_config) {
516
272
  this._config = _config;
517
273
  }
518
- /**
519
- * Build the files and write them to the disk.
520
- *
521
- * @param emit - Which types of files to emit.
522
- * @param emit.index
523
- * @param emit.playgrounds
524
- * @param emit.screenshots
525
- * @returns A report with check results and the number of written files.
274
+ /**
275
+ * Build the files and write them to the disk.
276
+ * @param emit - Which types of files to emit.
277
+ * @param emit.index
278
+ * @param emit.playgrounds
279
+ * @param emit.screenshots
280
+ * @returns A report with check results and the number of written files.
526
281
  */
527
- _createClass(ContentBuilder, [{
528
- key: "build",
529
- value: function build() {
530
- var _context,
531
- _context2,
532
- _this = this;
533
- var emit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
534
- var allExamples = this._processGroup(this._config.examples);
535
- var okay = [];
536
- var fail = [];
537
- console.info(_concatInstanceProperty(_context = "Going to generate ".concat(_flatInstanceProperty(_context2 = [emit.index ? ["index files"] : [], emit.playgrounds ? ["playground openers"] : [], emit.screenshots ? ["screenshots"] : []]).call(_context2).join(", "), " for ")).call(_context, allExamples.length, " examples."));
538
- process.stdout.write("\n");
539
- var index = emit.index ?
282
+ build(emit = {}) {
283
+ const allExamples = this._processGroup(this._config.examples);
284
+ const okay = [];
285
+ const fail = [];
286
+ console.info(
287
+ `Going to generate ${[
288
+ emit.index ? ["index files"] : [],
289
+ emit.playgrounds ? ["playground openers"] : [],
290
+ emit.screenshots ? ["screenshots"] : []
291
+ ].flat().join(", ")} for ${allExamples.length} examples.`
292
+ );
293
+ process.stdout.write("\n");
294
+ const index = emit.index ? (
540
295
  // Generate indexes.
541
- _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
542
- var _context3;
543
- var getStartStopMs, results;
544
- return _regeneratorRuntime.wrap(function _callee2$(_context5) {
545
- while (1) switch (_context5.prev = _context5.next) {
546
- case 0:
547
- getStartStopMs = measureStartStopMs();
548
- _context5.next = 3;
549
- return _Promise.allSettled(_mapInstanceProperty(_context3 = _this._config.renderer.render(_this._config.examples, _this._config.output, _this._config.title, collator)).call(_context3, /*#__PURE__*/function () {
550
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) {
551
- var content, filename;
552
- return _regeneratorRuntime.wrap(function _callee$(_context4) {
553
- while (1) switch (_context4.prev = _context4.next) {
554
- case 0:
555
- content = _ref2.content, filename = _ref2.filename;
556
- return _context4.abrupt("return", writeFile(node_path.join(_this._config.output, filename), content));
557
- case 2:
558
- case "end":
559
- return _context4.stop();
560
- }
561
- }, _callee);
562
- }));
563
- return function (_x) {
564
- return _ref3.apply(this, arguments);
565
- };
566
- }()));
567
- case 3:
568
- results = _context5.sent;
569
- return _context5.abrupt("return", [_objectSpread$1(_objectSpread$1({}, getStartStopMs()), {}, {
570
- count: results.length,
571
- result: _everyInstanceProperty(results).call(results, function (_ref4) {
572
- var status = _ref4.status;
573
- return status === "fulfilled";
574
- }) ? "fulfilled" : "rejected"
575
- })]);
576
- case 5:
577
- case "end":
578
- return _context5.stop();
296
+ (async () => {
297
+ const getStartStopMs = measureStartStopMs();
298
+ const contentParts = await this._config.renderer.render(
299
+ this._config.examples,
300
+ this._config.output,
301
+ this._config.title,
302
+ collator
303
+ );
304
+ const results = await Promise.allSettled(
305
+ contentParts.map(
306
+ async ({ content, filename }) => writeFile(join(this._config.output, filename), content)
307
+ )
308
+ );
309
+ return [
310
+ {
311
+ ...getStartStopMs(),
312
+ count: results.length,
313
+ result: results.every(
314
+ ({ status }) => status === "fulfilled"
315
+ ) ? "fulfilled" : "rejected"
579
316
  }
580
- }, _callee2);
581
- }))() :
317
+ ];
318
+ })()
319
+ ) : (
582
320
  // Skip indexes.
583
- _Promise.resolve([]);
584
- var playgrounds = emit.playgrounds ?
321
+ Promise.resolve([])
322
+ );
323
+ const playgrounds = emit.playgrounds ? (
585
324
  // Generate playground pages.
586
- _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
587
- return _regeneratorRuntime.wrap(function _callee4$(_context8) {
588
- while (1) switch (_context8.prev = _context8.next) {
589
- case 0:
590
- _context8.next = 2;
591
- return _Promise.all(_mapInstanceProperty(allExamples).call(allExamples, /*#__PURE__*/function () {
592
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(example) {
593
- var _context6;
594
- var getStartStopMs, results;
595
- return _regeneratorRuntime.wrap(function _callee3$(_context7) {
596
- while (1) switch (_context7.prev = _context7.next) {
597
- case 0:
598
- getStartStopMs = measureStartStopMs();
599
- _context7.next = 3;
600
- return _Promise.allSettled(_mapInstanceProperty(_context6 = [{
601
- html: generateJSFiddlePage(example),
602
- path: example.paths.jsfiddle.local
603
- }, {
604
- html: generateCodePenPage(example),
605
- path: example.paths.codepen.local
606
- }]).call(_context6, function (_ref7) {
607
- var html = _ref7.html,
608
- path = _ref7.path;
609
- return writeFile(path, formatHTML(html));
610
- }));
611
- case 3:
612
- results = _context7.sent;
613
- return _context7.abrupt("return", _objectSpread$1(_objectSpread$1({}, getStartStopMs()), {}, {
614
- count: results.length,
615
- example: example,
616
- result: _everyInstanceProperty(results).call(results, function (_ref8) {
617
- var status = _ref8.status;
618
- return status === "fulfilled";
619
- }) ? "fulfilled" : "rejected"
620
- }));
621
- case 5:
622
- case "end":
623
- return _context7.stop();
624
- }
625
- }, _callee3);
626
- }));
627
- return function (_x2) {
628
- return _ref6.apply(this, arguments);
629
- };
630
- }()));
631
- case 2:
632
- return _context8.abrupt("return", _context8.sent);
633
- case 3:
634
- case "end":
635
- return _context8.stop();
636
- }
637
- }, _callee4);
638
- }))() :
325
+ (async () => await Promise.all(
326
+ allExamples.map(async (example) => {
327
+ const getStartStopMs = measureStartStopMs();
328
+ const results = await Promise.allSettled(
329
+ [
330
+ {
331
+ html: generateJSFiddlePage(example),
332
+ path: example.paths.jsfiddle.local
333
+ },
334
+ {
335
+ html: generateCodePenPage(example),
336
+ path: example.paths.codepen.local
337
+ }
338
+ ].map(
339
+ async ({ html, path }) => writeFile(path, await formatHTML(html))
340
+ )
341
+ );
342
+ return {
343
+ ...getStartStopMs(),
344
+ count: results.length,
345
+ example,
346
+ result: results.every(
347
+ ({ status }) => status === "fulfilled"
348
+ ) ? "fulfilled" : "rejected"
349
+ };
350
+ })
351
+ ))()
352
+ ) : (
639
353
  // Skip playground pages.
640
- _Promise.resolve([]);
641
- var screenshots = emit.screenshots ?
354
+ Promise.resolve([])
355
+ );
356
+ const screenshots = emit.screenshots ? (
642
357
  // Generate screenshots.
643
- _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() {
644
- var cleanup, _process$env$DEBUG, _context10, _context11, debug, browser, todo, total, reports, _context17, _iterator, _step, callback;
645
- return _regeneratorRuntime.wrap(function _callee7$(_context18) {
646
- while (1) switch (_context18.prev = _context18.next) {
647
- case 0:
648
- cleanup = [];
649
- _context18.prev = 1;
650
- debug = /^1|y|yes|true$/i.test((_process$env$DEBUG = process.env.DEBUG) !== null && _process$env$DEBUG !== void 0 ? _process$env$DEBUG : "");
651
- _context18.next = 5;
652
- return puppeteer.launch({
653
- headless: !debug,
654
- slowMo: debug ? 100 : undefined
655
- });
656
- case 5:
657
- browser = _context18.sent;
658
- if (debug) {
659
- cleanup.push( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
660
- return _regeneratorRuntime.wrap(function _callee5$(_context9) {
661
- while (1) switch (_context9.prev = _context9.next) {
662
- case 0:
663
- return _context9.abrupt("return", browser.disconnect());
664
- case 1:
665
- case "end":
666
- return _context9.stop();
667
- }
668
- }, _callee5);
669
- })));
670
- } else {
671
- cleanup.push(function () {
672
- return browser.close();
358
+ (async () => {
359
+ const cleanup = [];
360
+ try {
361
+ const debug = /^1|y|yes|true$/i.test(process.env.DEBUG ?? "");
362
+ const browser = await puppeteer.launch({
363
+ headless: !debug,
364
+ slowMo: debug ? 100 : void 0
365
+ });
366
+ if (debug) {
367
+ cleanup.push(async () => browser.disconnect());
368
+ } else {
369
+ cleanup.push(() => browser.close());
370
+ }
371
+ const todo = allExamples.slice();
372
+ const total = todo.length;
373
+ const reports = [];
374
+ await Promise.allSettled(
375
+ new Array(this._config.parallel).fill(null).map(async () => {
376
+ let example;
377
+ while (example = todo.pop()) {
378
+ const getStartStopMs = measureStartStopMs();
379
+ const valid = await generateScreenshot(browser, {
380
+ debug,
381
+ example,
382
+ height: this._config.renderer.screenshot.height,
383
+ screenshotScript: this._config.screenshotScript,
384
+ width: this._config.renderer.screenshot.width
673
385
  });
386
+ const report = {
387
+ ...getStartStopMs(),
388
+ count: 1,
389
+ example,
390
+ result: valid ? "fulfilled" : "rejected"
391
+ };
392
+ reports.push(report);
393
+ if (valid) {
394
+ okay.push(example.path);
395
+ } else {
396
+ fail.push(example.path);
397
+ }
398
+ const percentage = (Math.floor(reports.length / total * 100) + "%").padStart(4, " ");
399
+ const validText = valid ? "okay" : "fail";
400
+ const msText = formatStartStopMs(report);
401
+ console.info(
402
+ `${percentage} ${validText} ${msText} - ${example.path}`
403
+ );
674
404
  }
675
- // Generate screenshots.
676
- // There is quite long delay to ensure the chart is rendered properly
677
- // so it's much faster to run a lot of them at the same time.
678
- todo = _sliceInstanceProperty(allExamples).call(allExamples);
679
- total = todo.length;
680
- reports = [];
681
- _context18.next = 12;
682
- return _Promise.allSettled(_mapInstanceProperty(_context10 = _fillInstanceProperty(_context11 = new Array(_this._config.parallel)).call(_context11, null)).call(_context10, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
683
- var example, _context12, _context13, _context14, _context15, getStartStopMs, valid, report, percentage, validText, msText;
684
- return _regeneratorRuntime.wrap(function _callee6$(_context16) {
685
- while (1) switch (_context16.prev = _context16.next) {
686
- case 0:
687
- if (!(example = todo.pop())) {
688
- _context16.next = 14;
689
- break;
690
- }
691
- getStartStopMs = measureStartStopMs();
692
- _context16.next = 4;
693
- return generateScreenshot(browser, {
694
- debug: debug,
695
- example: example,
696
- height: _this._config.renderer.screenshot.height,
697
- screenshotScript: _this._config.screenshotScript,
698
- width: _this._config.renderer.screenshot.width
699
- });
700
- case 4:
701
- valid = _context16.sent;
702
- report = _objectSpread$1(_objectSpread$1({}, getStartStopMs()), {}, {
703
- count: 1,
704
- example: example,
705
- result: valid ? "fulfilled" : "rejected"
706
- });
707
- reports.push(report);
708
- if (valid) {
709
- okay.push(example.path);
710
- } else {
711
- fail.push(example.path);
712
- }
713
- percentage = _padStartInstanceProperty(_context12 = Math.floor(reports.length / total * 100) + "%").call(_context12, 4, " ");
714
- validText = valid ? "okay" : "fail";
715
- msText = formatStartStopMs(report);
716
- console.info(_concatInstanceProperty(_context13 = _concatInstanceProperty(_context14 = _concatInstanceProperty(_context15 = "".concat(percentage, " ")).call(_context15, validText, " ")).call(_context14, msText, " - ")).call(_context13, example.path));
717
- _context16.next = 0;
718
- break;
719
- case 14:
720
- case "end":
721
- return _context16.stop();
722
- }
723
- }, _callee6);
724
- }))));
725
- case 12:
726
- return _context18.abrupt("return", reports);
727
- case 13:
728
- _context18.prev = 13;
729
- _iterator = _createForOfIteratorHelper$2(_reverseInstanceProperty(_context17 = _spliceInstanceProperty(cleanup).call(cleanup, 0)).call(_context17));
730
- _context18.prev = 15;
731
- _iterator.s();
732
- case 17:
733
- if ((_step = _iterator.n()).done) {
734
- _context18.next = 29;
735
- break;
736
- }
737
- callback = _step.value;
738
- _context18.prev = 19;
739
- _context18.next = 22;
740
- return callback();
741
- case 22:
742
- _context18.next = 27;
743
- break;
744
- case 24:
745
- _context18.prev = 24;
746
- _context18.t0 = _context18["catch"](19);
747
- console.error(_context18.t0);
748
- case 27:
749
- _context18.next = 17;
750
- break;
751
- case 29:
752
- _context18.next = 34;
753
- break;
754
- case 31:
755
- _context18.prev = 31;
756
- _context18.t1 = _context18["catch"](15);
757
- _iterator.e(_context18.t1);
758
- case 34:
759
- _context18.prev = 34;
760
- _iterator.f();
761
- return _context18.finish(34);
762
- case 37:
763
- return _context18.finish(13);
764
- case 38:
765
- case "end":
766
- return _context18.stop();
405
+ })
406
+ );
407
+ return reports;
408
+ } finally {
409
+ for (const callback of cleanup.splice(0).reverse()) {
410
+ try {
411
+ await callback();
412
+ } catch (error) {
413
+ console.error(error);
414
+ }
767
415
  }
768
- }, _callee7, null, [[1,, 13, 38], [15, 31, 34, 37], [19, 24]]);
769
- }))() :
416
+ }
417
+ })()
418
+ ) : (
770
419
  // Skip screenshots.
771
- _Promise.resolve([]);
772
- var checks = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
773
- var total;
774
- return _regeneratorRuntime.wrap(function _callee8$(_context19) {
775
- while (1) switch (_context19.prev = _context19.next) {
776
- case 0:
777
- _context19.next = 2;
778
- return index;
779
- case 2:
780
- _context19.next = 4;
781
- return playgrounds;
782
- case 4:
783
- _context19.next = 6;
784
- return screenshots;
785
- case 6:
786
- total = okay.length + fail.length;
787
- return _context19.abrupt("return", {
788
- fail: fail.length,
789
- failPaths: fail,
790
- okay: okay.length,
791
- okayPaths: okay,
792
- percentage: total === 0 ? 100 : 100 * okay.length / total,
793
- total: total
794
- });
795
- case 8:
796
- case "end":
797
- return _context19.stop();
798
- }
799
- }, _callee8);
800
- }))();
420
+ Promise.resolve([])
421
+ );
422
+ const checks = (async () => {
423
+ await index;
424
+ await playgrounds;
425
+ await screenshots;
426
+ const total = okay.length + fail.length;
801
427
  return {
802
- checks: checks,
803
- index: index,
804
- playgrounds: playgrounds,
805
- screenshots: screenshots
428
+ fail: fail.length,
429
+ failPaths: fail,
430
+ okay: okay.length,
431
+ okayPaths: okay,
432
+ percentage: total === 0 ? 100 : 100 * okay.length / total,
433
+ total
806
434
  };
807
- }
808
- }, {
809
- key: "_processGroup",
810
- value: function _processGroup(examples) {
811
- var _context20,
812
- _context21,
813
- _this2 = this;
814
- return _flatMapInstanceProperty(_context20 = _sortInstanceProperty(_context21 = _Object$keys(examples)).call(_context21, collator.compare)).call(_context20, function (key) {
815
- var example = examples[key];
816
- if (isExample(example)) {
817
- return [example];
818
- } else {
819
- return _this2._processGroup(example);
820
- }
821
- });
822
- }
823
- }]);
824
- return ContentBuilder;
825
- }();
435
+ })();
436
+ return { checks, index, playgrounds, screenshots };
437
+ }
438
+ _processGroup(examples) {
439
+ return Object.keys(examples).sort(collator.compare).flatMap((key) => {
440
+ const example = examples[key];
441
+ if (isExample(example)) {
442
+ return [example];
443
+ } else {
444
+ return this._processGroup(example);
445
+ }
446
+ });
447
+ }
448
+ }
826
449
 
827
- var indexTemplate = "<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>Examples</title>\n\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"examples.css\" />\n </head>\n <body></body>\n</html>\n";
450
+ var index_template_default$1 = '<html>\n <head>\n <meta charset="utf-8" />\n <title>Examples</title>\n\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n\n <link rel="stylesheet" type="text/css" href="examples.css" />\n </head>\n <body></body>\n</html>\n';
828
451
 
829
- var styleTemplate = ".examples-root {\n margin: 50px auto 200px;\n min-width: calc(200px + 2em);\n width: calc(100vw - 200px);\n}\n\n.examples-root a {\n color: #2b7ce9;\n}\n.examples-root a:visited {\n color: #46417a;\n}\n\n.examples-root .example-link {\n margin: 1em;\n position: relative;\n width: 200px;\n\n display: inline-block;\n}\n\n.examples-root .example-link .example-image {\n display: block;\n height: 200px;\n margin-top: 1ex;\n position: relative;\n width: 200px;\n}\n.examples-root .example-link .example-image > img {\n position: absolute;\n top: 0px;\n left: 0px;\n width: 200px;\n height: 200px;\n\n background: #2b7ce9;\n border: 1px solid #2b7ce9;\n color: #ffffff;\n\n transition: transform 0.5s ease 0s, z-index 0.5s linear 0s;\n z-index: 1;\n}\n.examples-root .example-link:hover .example-image > img {\n transform: translate(0px, 95px) scale(2, 2);\n z-index: 100;\n}\n\n.examples-root .example-header > *:last-child {\n margin-left: 0.5em;\n}\n.examples-root .icon {\n height: 1.5em;\n margin-bottom: -0.25em;\n width: 1.5em;\n\n background: none;\n border: none;\n cursor: pointer;\n display: inline-block;\n}\n.examples-root .icon.jsfiddle {\n background-size: contain;\n background-image: url(\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%232b7ce9' d='M16.45,17.5C17.45,17.5 18.3,17.15 19,16.5C19.67,15.8 20,15 20,14C20,13.05 19.66,12.22 18.96,11.53C18.26,10.84 17.41,10.5 16.41,10.5C15.47,10.5 14.64,10.83 13.92,11.5L9.14,15.56C8.7,16 8.17,16.22 7.55,16.22C6.92,16.22 6.39,16 5.95,15.56C5.5,15.13 5.3,14.61 5.3,14C5.3,13.42 5.5,12.91 5.95,12.47C6.39,12.03 6.92,11.81 7.55,11.81C8.14,11.81 8.69,12.03 9.19,12.47L9.94,13.13L10.92,12.23L10.08,11.53C9.39,10.84 8.55,10.5 7.55,10.5C6.58,10.5 5.74,10.84 5.04,11.53C4.34,12.22 4,13.05 4,14C4,15 4.34,15.8 5.04,16.5C5.74,17.15 6.59,17.5 7.59,17.5C8.53,17.5 9.36,17.16 10.08,16.5L14.86,12.42C15.27,12 15.8,11.81 16.45,11.81C17.08,11.81 17.61,12.03 18.05,12.47C18.5,12.91 18.7,13.42 18.7,14C18.7,14.61 18.5,15.13 18.05,15.56C17.61,16 17.08,16.22 16.45,16.22C15.89,16.22 15.34,16 14.81,15.5L14.06,14.86L13.08,15.75L13.92,16.45C14.61,17.14 15.45,17.5 16.45,17.5M19.36,10.03C20.64,10.13 21.73,10.65 22.64,11.6C23.55,12.55 24,13.69 24,15C24,16.38 23.5,17.55 22.5,18.54C21.54,19.5 20.36,20 19,20H6C4.34,20 2.93,19.43 1.76,18.26C0.59,17.09 0,15.67 0,14C0,12.55 0.5,11.23 1.57,10.05C2.62,8.88 3.88,8.22 5.34,8.06C6,6.84 6.92,5.86 8.11,5.11C9.3,4.36 10.59,4 12,4C13.69,4 15.26,4.58 16.71,5.77C18.16,6.95 19.05,8.38 19.36,10.03Z' /%3E%3C/svg%3E\");\n}\n.examples-root .icon.codepen {\n background-size: contain;\n background-image: url(\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%232b7ce9' d='M15.09,12L12,14.08V14.09L8.91,12L12,9.92V9.92L15.09,12M12,2C11.84,2 11.68,2.06 11.53,2.15L2.5,8.11C2.27,8.22 2.09,8.43 2,8.67V14.92C2,15.33 2,15.33 2.15,15.53L11.53,21.86C11.67,21.96 11.84,22 12,22C12.16,22 12.33,21.95 12.47,21.85L21.85,15.5C22,15.33 22,15.33 22,14.92V8.67C21.91,8.42 21.73,8.22 21.5,8.1L12.47,2.15C12.32,2.05 12.16,2 12,2M16.58,13L19.59,15.04L12.83,19.6V15.53L16.58,13M19.69,8.9L16.58,11L12.83,8.47V4.38L19.69,8.9M20.33,10.47V13.53L18.07,12L20.33,10.47M7.42,13L11.17,15.54V19.6L4.41,15.04L7.42,13M4.31,8.9L11.17,4.39V8.5L7.42,11L4.31,8.9M3.67,10.5L5.93,12L3.67,13.54V10.5Z' /%3E%3C/svg%3E\");\n}\n";
452
+ var index_template_default = `.examples-root {
453
+ margin: 50px auto 200px;
454
+ min-width: calc(200px + 2em);
455
+ width: calc(100vw - 200px);
456
+ }
457
+
458
+ .examples-root a {
459
+ color: #2b7ce9;
460
+ }
461
+ .examples-root a:visited {
462
+ color: #46417a;
463
+ }
464
+
465
+ .examples-root .example-link {
466
+ margin: 1em;
467
+ position: relative;
468
+ width: 200px;
469
+
470
+ display: inline-block;
471
+ }
472
+
473
+ .examples-root .example-link .example-image {
474
+ display: block;
475
+ height: 200px;
476
+ margin-top: 1ex;
477
+ position: relative;
478
+ width: 200px;
479
+ }
480
+ .examples-root .example-link .example-image > img {
481
+ position: absolute;
482
+ top: 0px;
483
+ left: 0px;
484
+ width: 200px;
485
+ height: 200px;
486
+
487
+ background: #2b7ce9;
488
+ border: 1px solid #2b7ce9;
489
+ color: #ffffff;
490
+
491
+ transition:
492
+ transform 0.5s ease 0s,
493
+ z-index 0.5s linear 0s;
494
+ z-index: 1;
495
+ }
496
+ .examples-root .example-link:hover .example-image > img {
497
+ transform: translate(0px, 95px) scale(2, 2);
498
+ z-index: 100;
499
+ }
500
+
501
+ .examples-root .example-header > *:last-child {
502
+ margin-left: 0.5em;
503
+ }
504
+ .examples-root .icon {
505
+ height: 1.5em;
506
+ margin-bottom: -0.25em;
507
+ width: 1.5em;
508
+
509
+ background: none;
510
+ border: none;
511
+ cursor: pointer;
512
+ display: inline-block;
513
+ }
514
+ .examples-root .icon.jsfiddle {
515
+ background-size: contain;
516
+ background-image: url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%232b7ce9' d='M16.45,17.5C17.45,17.5 18.3,17.15 19,16.5C19.67,15.8 20,15 20,14C20,13.05 19.66,12.22 18.96,11.53C18.26,10.84 17.41,10.5 16.41,10.5C15.47,10.5 14.64,10.83 13.92,11.5L9.14,15.56C8.7,16 8.17,16.22 7.55,16.22C6.92,16.22 6.39,16 5.95,15.56C5.5,15.13 5.3,14.61 5.3,14C5.3,13.42 5.5,12.91 5.95,12.47C6.39,12.03 6.92,11.81 7.55,11.81C8.14,11.81 8.69,12.03 9.19,12.47L9.94,13.13L10.92,12.23L10.08,11.53C9.39,10.84 8.55,10.5 7.55,10.5C6.58,10.5 5.74,10.84 5.04,11.53C4.34,12.22 4,13.05 4,14C4,15 4.34,15.8 5.04,16.5C5.74,17.15 6.59,17.5 7.59,17.5C8.53,17.5 9.36,17.16 10.08,16.5L14.86,12.42C15.27,12 15.8,11.81 16.45,11.81C17.08,11.81 17.61,12.03 18.05,12.47C18.5,12.91 18.7,13.42 18.7,14C18.7,14.61 18.5,15.13 18.05,15.56C17.61,16 17.08,16.22 16.45,16.22C15.89,16.22 15.34,16 14.81,15.5L14.06,14.86L13.08,15.75L13.92,16.45C14.61,17.14 15.45,17.5 16.45,17.5M19.36,10.03C20.64,10.13 21.73,10.65 22.64,11.6C23.55,12.55 24,13.69 24,15C24,16.38 23.5,17.55 22.5,18.54C21.54,19.5 20.36,20 19,20H6C4.34,20 2.93,19.43 1.76,18.26C0.59,17.09 0,15.67 0,14C0,12.55 0.5,11.23 1.57,10.05C2.62,8.88 3.88,8.22 5.34,8.06C6,6.84 6.92,5.86 8.11,5.11C9.3,4.36 10.59,4 12,4C13.69,4 15.26,4.58 16.71,5.77C18.16,6.95 19.05,8.38 19.36,10.03Z' /%3E%3C/svg%3E");
517
+ }
518
+ .examples-root .icon.codepen {
519
+ background-size: contain;
520
+ background-image: url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%232b7ce9' d='M15.09,12L12,14.08V14.09L8.91,12L12,9.92V9.92L15.09,12M12,2C11.84,2 11.68,2.06 11.53,2.15L2.5,8.11C2.27,8.22 2.09,8.43 2,8.67V14.92C2,15.33 2,15.33 2.15,15.53L11.53,21.86C11.67,21.96 11.84,22 12,22C12.16,22 12.33,21.95 12.47,21.85L21.85,15.5C22,15.33 22,15.33 22,14.92V8.67C21.91,8.42 21.73,8.22 21.5,8.1L12.47,2.15C12.32,2.05 12.16,2 12,2M16.58,13L19.59,15.04L12.83,19.6V15.53L16.58,13M19.69,8.9L16.58,11L12.83,8.47V4.38L19.69,8.9M20.33,10.47V13.53L18.07,12L20.33,10.47M7.42,13L11.17,15.54V19.6L4.41,15.04L7.42,13M4.31,8.9L11.17,4.39V8.5L7.42,11L4.31,8.9M3.67,10.5L5.93,12L3.67,13.54V10.5Z' /%3E%3C/svg%3E");
521
+ }
522
+ `;
830
523
 
831
- function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (_Array$isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
832
- function _unsupportedIterableToArray$1(o, minLen) { var _context3; if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = _sliceInstanceProperty(_context3 = Object.prototype.toString.call(o)).call(_context3, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
833
- function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
834
- /**
835
- * @param example
836
- */
837
524
  function generateJSFiddle(example) {
838
- return $.load([])("<a>").addClass("icon jsfiddle").attr("href", example.paths.jsfiddle.web).attr("title", "JSFiddle");
525
+ return cheerio.load([])("<a>").addClass("icon jsfiddle").attr("href", example.paths.jsfiddle.web).attr("title", "JSFiddle");
839
526
  }
840
- /**
841
- * @param example
842
- */
843
527
  function generateCodePen(example) {
844
- return $.load([])("<a>").addClass("icon codepen").attr("href", example.paths.codepen.web).attr("title", "CodePen");
528
+ return cheerio.load([])("<a>").addClass("icon codepen").attr("href", example.paths.codepen.web).attr("title", "CodePen");
845
529
  }
846
- /**
847
- * @param examples
848
- * @param title
849
- * @param level
850
- * @param collator
851
- */
852
530
  function processGroup$1(examples, title, level, collator) {
853
- var _context;
854
- var heading = $.load([])("<h".concat(Math.max(1, Math.min(6, level)), ">"));
531
+ const heading = cheerio.load([])(`<h${Math.max(1, Math.min(6, level))}>`);
855
532
  heading.text(title);
856
- var list = $.load([])("<div>");
857
- var section = $.load([])("<div>");
533
+ const list = cheerio.load([])("<div>");
534
+ const section = cheerio.load([])("<div>");
858
535
  section.append(heading, list);
859
- var _iterator = _createForOfIteratorHelper$1(_sortInstanceProperty(_context = _Object$keys(examples)).call(_context, collator.compare)),
860
- _step;
861
- try {
862
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
863
- var key = _step.value;
864
- var example = examples[key];
865
- if (isExample(example)) {
866
- var header = $.load([])("<div>").addClass("example-header").append(
536
+ for (const key of Object.keys(examples).sort(collator.compare)) {
537
+ const example = examples[key];
538
+ if (isExample(example)) {
539
+ const header = cheerio.load([])("<div>").addClass("example-header").append(
867
540
  // Playgrounds
868
- generateJSFiddle(example), generateCodePen(example),
541
+ generateJSFiddle(example),
542
+ generateCodePen(example),
869
543
  // Title
870
- $.load([])("<a>").attr("href", example.paths.page.web).text(key));
871
- var image = $.load([])("<a>").addClass("example-image").attr("href", example.paths.page.web).append($.load([])("<img>").attr("src", example.paths.screenshot.web).attr("alt", key));
872
- var item = $.load([])("<span>").addClass("example-link").append(header, image);
873
- list.append(item);
874
- } else {
875
- section.append(processGroup$1(example, key, level + 1, collator));
876
- }
544
+ cheerio.load([])("<a>").attr("href", example.paths.page.web).text(key)
545
+ );
546
+ const image = cheerio.load([])("<a>").addClass("example-image").attr("href", example.paths.page.web).append(
547
+ cheerio.load([])("<img>").attr("src", example.paths.screenshot.web).attr("alt", key)
548
+ );
549
+ const item = cheerio.load([])("<span>").addClass("example-link").append(header, image);
550
+ list.append(item);
551
+ } else {
552
+ section.append(processGroup$1(example, key, level + 1, collator));
877
553
  }
878
- } catch (err) {
879
- _iterator.e(err);
880
- } finally {
881
- _iterator.f();
882
554
  }
883
555
  return section;
884
556
  }
885
- var htmlRenderer = {
886
- render: function render(examples, _output, title, collator) {
887
- var _context2;
888
- var filename = "index.html";
889
- var root = $.load([])("<div>");
557
+ const htmlRenderer = {
558
+ async render(examples, _output, title, collator) {
559
+ const filename = "index.html";
560
+ const root = cheerio.load([])("<div>");
890
561
  root.addClass("examples-root");
891
- var _iterator2 = _createForOfIteratorHelper$1(_sortInstanceProperty(_context2 = _Object$keys(examples)).call(_context2, collator.compare)),
892
- _step2;
893
- try {
894
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
895
- var key = _step2.value;
896
- root.append(processGroup$1(examples[key], key, 1, collator));
897
- }
898
- } catch (err) {
899
- _iterator2.e(err);
900
- } finally {
901
- _iterator2.f();
562
+ for (const key of Object.keys(examples).sort(collator.compare)) {
563
+ root.append(processGroup$1(examples[key], key, 1, collator));
902
564
  }
903
- var page = $.load(indexTemplate);
565
+ const page = cheerio.load(index_template_default$1);
904
566
  page("title").text(title);
905
567
  page("body").append(root);
906
- var content = formatHTML(page.html());
907
- return [{
908
- content: content,
909
- filename: filename,
910
- title: title
911
- }, {
912
- content: styleTemplate,
913
- filename: "examples.css",
914
- title: "examples.css"
915
- }];
568
+ const content = await formatHTML(page.html());
569
+ return [
570
+ { content, filename, title },
571
+ {
572
+ content: index_template_default,
573
+ filename: "examples.css",
574
+ title: "examples.css"
575
+ }
576
+ ];
916
577
  },
917
578
  screenshot: {
918
579
  width: 400,
@@ -920,109 +581,83 @@ var htmlRenderer = {
920
581
  }
921
582
  };
922
583
 
923
- function ownKeys(e, r) { var t = _Object$keys(e); if (_Object$getOwnPropertySymbols) { var o = _Object$getOwnPropertySymbols(e); r && (o = _filterInstanceProperty(o).call(o, function (r) { return _Object$getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
924
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var _context14, _context15; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty(_context14 = ownKeys(Object(t), !0)).call(_context14, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(e, _Object$getOwnPropertyDescriptors(t)) : _forEachInstanceProperty(_context15 = ownKeys(Object(t))).call(_context15, function (r) { _Object$defineProperty(e, r, _Object$getOwnPropertyDescriptor(t, r)); }); } return e; }
925
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (_Array$isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
926
- function _unsupportedIterableToArray(o, minLen) { var _context13; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context13 = Object.prototype.toString.call(o)).call(_context13, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
927
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
928
- /**
929
- * @param lines
930
- */
931
584
  function linesToContent(lines) {
932
585
  return formatMD(lines.join("\n"));
933
586
  }
934
- /**
935
- * @param title
936
- * @param src
937
- * @param href
938
- */
939
587
  function image(title, src, href) {
940
- var _context, _context2;
941
- return href == null ? _concatInstanceProperty(_context = "![".concat(title, "](")).call(_context, src, ")") : link(href, _concatInstanceProperty(_context2 = "![".concat(title, "](")).call(_context2, src, ")"));
588
+ return href == null ? `![${title}](${src})` : link(href, `![${title}](${src})`);
942
589
  }
943
- /**
944
- * @param href
945
- * @param text
946
- */
947
- function link(href) {
948
- var _context3;
949
- var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : href;
950
- return _concatInstanceProperty(_context3 = "[".concat(text, "](")).call(_context3, href, ")");
590
+ function link(href, text = href) {
591
+ return `[${text}](${href})`;
951
592
  }
952
- /**
953
- * @param level
954
- * @param text
955
- */
956
593
  function header(level, text) {
957
- var _context4, _context5;
958
- return _concatInstanceProperty(_context4 = "".concat(_repeatInstanceProperty(_context5 = "#").call(_context5, level), " ")).call(_context4, text);
594
+ return `${"#".repeat(level)} ${text}`;
959
595
  }
960
- /**
961
- * @param examples
962
- * @param output
963
- * @param title
964
- * @param collator
965
- */
966
- function processGroup(examples, output, title, collator) {
967
- var _context6, _context7, _context8;
968
- var items = [];
969
- var sections = [];
970
- var filenamePart = title.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase();
971
- var _iterator = _createForOfIteratorHelper(_sortInstanceProperty(_context8 = _Object$keys(examples)).call(_context8, collator.compare)),
972
- _step;
973
- try {
974
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
975
- var key = _step.value;
976
- var example = examples[key];
977
- if (isExample(example)) {
978
- // An example in this group.
979
- items.push(header(2, key), "", image(key, "./" + node_path.relative(output, example.paths.screenshot.local), example.paths.page.web), "", [link(example.paths.page.web, "Open"), link(example.paths.jsfiddle.web, "JSFiddle"), link(example.paths.codepen.web, "CodePen")].join(" | "), "");
980
- } else {
981
- var _context9;
982
- // A subgroup of examples.
983
- sections.push.apply(sections, _toConsumableArray(_mapInstanceProperty(_context9 = processGroup(example, output, key, collator)).call(_context9, function (contentPart) {
984
- return _objectSpread(_objectSpread({}, contentPart), {}, {
596
+ async function processGroup(examples, output, title, collator) {
597
+ const items = [];
598
+ const sections = [];
599
+ const filenamePart = title.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase();
600
+ for (const key of Object.keys(examples).sort(collator.compare)) {
601
+ const example = examples[key];
602
+ if (isExample(example)) {
603
+ items.push(
604
+ header(2, key),
605
+ "",
606
+ image(
607
+ key,
608
+ "./" + relative(output, example.paths.screenshot.local),
609
+ example.paths.page.web
610
+ ),
611
+ "",
612
+ [
613
+ link(example.paths.page.web, "Open"),
614
+ link(example.paths.jsfiddle.web, "JSFiddle"),
615
+ link(example.paths.codepen.web, "CodePen")
616
+ ].join(" | "),
617
+ ""
618
+ );
619
+ } else {
620
+ sections.push(
621
+ ...(await processGroup(example, output, key, collator)).map(
622
+ (contentPart) => ({
623
+ ...contentPart,
985
624
  filename: filenamePart + "." + contentPart.filename
986
- });
987
- })));
988
- }
625
+ })
626
+ )
627
+ );
989
628
  }
990
- } catch (err) {
991
- _iterator.e(err);
992
- } finally {
993
- _iterator.f();
994
629
  }
995
- return _concatInstanceProperty(_context6 = [{
996
- content: linesToContent(_concatInstanceProperty(_context7 = [header(1, title), ""]).call(_context7, items)),
997
- filename: filenamePart + ".md",
998
- title: title
999
- }]).call(_context6, sections);
630
+ return [
631
+ {
632
+ content: await linesToContent([header(1, title), "", ...items]),
633
+ filename: filenamePart + ".md",
634
+ title
635
+ },
636
+ ...sections
637
+ ];
1000
638
  }
1001
- var mdRenderer = {
1002
- render: function render(examples, output, _title, collator) {
1003
- var _context10, _context11, _context12;
1004
- var sections = [];
1005
- var _iterator2 = _createForOfIteratorHelper(_sortInstanceProperty(_context12 = _Object$keys(examples)).call(_context12, collator.compare)),
1006
- _step2;
1007
- try {
1008
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1009
- var key = _step2.value;
1010
- sections.push.apply(sections, _toConsumableArray(processGroup(examples[key], output, key, collator)));
1011
- }
1012
- } catch (err) {
1013
- _iterator2.e(err);
1014
- } finally {
1015
- _iterator2.f();
639
+ const mdRenderer = {
640
+ async render(examples, output, _title, collator) {
641
+ const sections = [];
642
+ for (const key of Object.keys(examples).sort(collator.compare)) {
643
+ sections.push(
644
+ ...await processGroup(examples[key], output, key, collator)
645
+ );
1016
646
  }
1017
- return _concatInstanceProperty(_context10 = [{
1018
- content: linesToContent(_concatInstanceProperty(_context11 = [header(1, "Examples"), ""]).call(_context11, _toConsumableArray(_mapInstanceProperty(sections).call(sections, function (_ref) {
1019
- var filename = _ref.filename,
1020
- title = _ref.title;
1021
- return "- " + link("./" + filename, title);
1022
- })))),
1023
- filename: "README.md",
1024
- title: "Examples"
1025
- }]).call(_context10, sections);
647
+ return [
648
+ {
649
+ content: await linesToContent([
650
+ header(1, "Examples"),
651
+ "",
652
+ ...sections.map(
653
+ ({ filename, title }) => "- " + link("./" + filename, title)
654
+ )
655
+ ]),
656
+ filename: "README.md",
657
+ title: "Examples"
658
+ },
659
+ ...sections
660
+ ];
1026
661
  },
1027
662
  screenshot: {
1028
663
  width: 740,
@@ -1030,7 +665,7 @@ var mdRenderer = {
1030
665
  }
1031
666
  };
1032
667
 
1033
- var y = yargs.strict(true).usage("generate-example-index [options]").hide("version").config().help().option("assets-local-directory", {
668
+ const y = yargs(hideBin(process.argv)).strict(true).usage("generate-example-index [options]").hide("version").config().help().option("assets-local-directory", {
1034
669
  default: "./examples/thumbnails",
1035
670
  describe: "The directory where assets will be written to.",
1036
671
  type: "string"
@@ -1102,137 +737,106 @@ var y = yargs.strict(true).usage("generate-example-index [options]").hide("versi
1102
737
  describe: "Attempt to verify that the examples were generated correctly. The value is a percentage of checks that have to pass for the run to be considered success.",
1103
738
  type: "number"
1104
739
  });
1105
- /**
1106
- *
1107
- */
1108
740
  function parseArguments() {
1109
- return y.parserConfiguration({
1110
- "camel-case-expansion": false
1111
- }).parseSync();
741
+ return y.parserConfiguration({ "camel-case-expansion": false }).parseSync();
1112
742
  }
1113
743
 
1114
- /**
1115
- * @param urls
1116
- */
1117
- function joinURLs() {
1118
- for (var _len = arguments.length, urls = new Array(_len), _key = 0; _key < _len; _key++) {
1119
- urls[_key] = arguments[_key];
1120
- }
1121
- return _mapInstanceProperty(urls).call(urls, function (url) {
1122
- return (
744
+ function joinURLs(...urls) {
745
+ return urls.map(
746
+ (url) => (
1123
747
  // Strip the parts of leading and trailing slashes if they have them.
1124
748
  url.replace(/^\/?(.*?)\/?$/, "$1")
1125
- );
1126
- }).join("/");
749
+ )
750
+ ).join("/");
1127
751
  }
1128
- /**
1129
- * @param baseURL
1130
- * @param url
1131
- */
1132
752
  function fixAbsoluteInputURL(baseURL, url) {
1133
- return _startsWithInstanceProperty(url).call(url, "/") ?
1134
- // Relative to the base URL. Base URL starts and URL ends with a slash.
1135
- baseURL + _sliceInstanceProperty(url).call(url, 1) :
1136
- // Relative to some other point or absolute already.
1137
- url;
753
+ return url.startsWith("/") ? (
754
+ // Relative to the base URL. Base URL starts and URL ends with a slash.
755
+ baseURL + url.slice(1)
756
+ ) : (
757
+ // Relative to some other point or absolute already.
758
+ url
759
+ );
1138
760
  }
1139
- /**
1140
- * @param config
1141
- * @param exampleAbsolutePath
1142
- */
1143
761
  function generatePaths(config, exampleAbsolutePath) {
1144
- var exampleRelativePath = node_path.relative(config.page.local, exampleAbsolutePath);
1145
- // It's important that the hash is created from the relative path so that it
1146
- // is the same on all computers.
1147
- var hash = node_crypto.createHash("sha256").update(exampleRelativePath).digest("hex");
762
+ const exampleRelativePath = relative(config.page.local, exampleAbsolutePath);
763
+ const hash = createHash("sha256").update(exampleRelativePath).digest("hex");
1148
764
  return {
1149
- codepen: generateLocalWebPair(config.codepen.local, config.codepen.web, hash, "codepen", "html"),
1150
- jsfiddle: generateLocalWebPair(config.jsfiddle.local, config.jsfiddle.web, hash, "jsfiddle", "html"),
765
+ codepen: generateLocalWebPair(
766
+ config.codepen.local,
767
+ config.codepen.web,
768
+ hash,
769
+ "codepen",
770
+ "html"
771
+ ),
772
+ jsfiddle: generateLocalWebPair(
773
+ config.jsfiddle.local,
774
+ config.jsfiddle.web,
775
+ hash,
776
+ "jsfiddle",
777
+ "html"
778
+ ),
1151
779
  page: {
1152
780
  local: exampleAbsolutePath,
1153
781
  web: joinURLs(config.page.web, exampleRelativePath)
1154
782
  },
1155
- screenshot: generateLocalWebPair(config.screenshot.local, config.screenshot.web, hash, "screenshot", "png")
783
+ screenshot: generateLocalWebPair(
784
+ config.screenshot.local,
785
+ config.screenshot.web,
786
+ hash,
787
+ "screenshot",
788
+ "png"
789
+ )
1156
790
  };
1157
791
  }
1158
- /**
1159
- * @param localRoot
1160
- * @param webRoot
1161
- * @param hash
1162
- * @param prefix
1163
- * @param extension
1164
- */
1165
792
  function generateLocalWebPair(localRoot, webRoot, hash, prefix, extension) {
1166
- var _context, _context2;
1167
- var filename = _concatInstanceProperty(_context = _concatInstanceProperty(_context2 = "".concat(prefix, ".")).call(_context2, hash, ".")).call(_context, extension);
793
+ const filename = `${prefix}.${hash}.${extension}`;
1168
794
  return {
1169
- local: node_path.resolve(localRoot, filename),
795
+ local: resolve(localRoot, filename),
1170
796
  web: joinURLs(webRoot, filename)
1171
797
  };
1172
798
  }
1173
799
 
1174
- var globby = import('globby');
1175
- var argv = parseArguments();
1176
- // Log the parsed configuration for debugging purposes.
1177
- console.info("Configuration: ", _JSON$stringify(argv, null, 2));
800
+ const argv = parseArguments();
801
+ console.info("Configuration: ", JSON.stringify(argv, null, 2));
1178
802
  process.stdout.write("\n");
1179
- // Pageres uses quite a lot of listeners when invoked multiple times in
1180
- // parallel. This ensures there are no warnings about it.
1181
803
  process.setMaxListeners(40);
1182
- // Resolve paths relative to PWD.
1183
- var screenshotScriptPath = typeof argv["screenshot-script"] === "string" ? node_path.resolve(argv["screenshot-script"]) : undefined;
1184
- var mkdir = util.promisify(fs.mkdir);
1185
- var readFile = util.promisify(fs.readFile);
1186
- /**
1187
- * Extract and coerce a value from meta tag.
1188
- *
1189
- * @param page - The page to be queried.
1190
- * @param name - The name of the meta tag.
1191
- * @param fallback - The value to be used if the meta tag is not present.
1192
- * @returns The value “smartly” coerced or the fallback if conversion isn't
1193
- * possible or the value is not present in the page.
1194
- */
804
+ const screenshotScriptPath = typeof argv["screenshot-script"] === "string" ? resolve(argv["screenshot-script"]) : void 0;
805
+ const mkdir = util.promisify(fs.mkdir);
806
+ const readFile = util.promisify(fs.readFile);
1195
807
  function getMeta(page, name, fallback) {
1196
- var content = page("meta[name=\"".concat(name, "\"]")).attr("content");
808
+ const content = page(`meta[name="${name}"]`).attr("content");
1197
809
  if (content == null) {
1198
- // No meta of this name exists in the page, use the fallback.
1199
810
  return fallback;
1200
- } else if (!_Number$isNaN(+content)) {
1201
- // Number.
811
+ } else if (!Number.isNaN(+content)) {
1202
812
  return +content;
1203
813
  } else if (typeof content === "string") {
1204
- // String.
1205
814
  return content;
1206
815
  } else {
1207
- // Something doesn't match, use the fallback.
1208
816
  return fallback;
1209
817
  }
1210
818
  }
1211
- /**
1212
- * Test if the example conforms to the conventions.
1213
- *
1214
- * @param path - The path to the example (used for identification in logs).
1215
- * @param page - The HTML to be linted.
1216
- * @returns True if everything's okay, false otherwise.
1217
- */
1218
819
  function lintExample(path, page) {
1219
- var _context, _context2, _context3;
1220
- var valid = true;
1221
- var msgs = ["".concat(path, ":")];
820
+ let valid = true;
821
+ const msgs = [`${path}:`];
1222
822
  if (page("#title").length !== 1) {
1223
823
  msgs.push("Missing #title element in the body.");
1224
824
  valid = false;
1225
825
  }
1226
826
  if (page("#title > *").length < 2) {
1227
- msgs.push("There have to be at least two headings (group and example name).");
827
+ msgs.push(
828
+ "There have to be at least two headings (group and example name)."
829
+ );
1228
830
  valid = false;
1229
831
  }
1230
- var headTitle = _trimInstanceProperty(_context = page("head > title").text()).call(_context);
1231
- var bodyTitle = _trimInstanceProperty(_context2 = _mapInstanceProperty(_context3 = page("#title > *")).call(_context3, function (_i, elem) {
1232
- return $.load([])(elem).text();
1233
- }).get().join(" | ")).call(_context2);
832
+ const headTitle = page("head > title").text().trim();
833
+ const bodyTitle = page("#title > *").map((_i, elem) => cheerio.load([])(elem).text()).get().join(" | ").trim();
1234
834
  if (headTitle !== bodyTitle) {
1235
- msgs.push("The title in the head doesn't match the title in the body.", " head: ".concat(headTitle), " body: ".concat(bodyTitle));
835
+ msgs.push(
836
+ "The title in the head doesn't match the title in the body.",
837
+ ` head: ${headTitle}`,
838
+ ` body: ${bodyTitle}`
839
+ );
1236
840
  valid = false;
1237
841
  }
1238
842
  if (msgs.length > 1) {
@@ -1240,284 +844,194 @@ function lintExample(path, page) {
1240
844
  }
1241
845
  return valid;
1242
846
  }
1243
- _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
1244
- var _context4, _context6;
1245
- var code, baseURL, pathsConfig, examples, selector, stats, skipped, _context11, screenshotScript, builtData, _context12, _context13, cummulativeReport, _context14, _context15, _cummulativeReport, _context16, _context17, _cummulativeReport2, checks, _context18, _context23, _context19, _context20, _context21, _context22;
1246
- return _regeneratorRuntime.wrap(function _callee3$(_context24) {
1247
- while (1) switch (_context24.prev = _context24.next) {
1248
- case 0:
1249
- code = 0;
1250
- if (!(!argv.index && !argv.screenshots && !argv.lint)) {
1251
- _context24.next = 4;
1252
- break;
1253
- }
1254
- yargs.parse("--help");
1255
- return _context24.abrupt("return");
1256
- case 4:
1257
- _context24.next = 6;
1258
- return _Promise.all(_mapInstanceProperty(_context4 = [argv["assets-local-directory"], argv["examples-local-directory"], argv["output-directory"], argv["pages-local-directory"]]).call(_context4, /*#__PURE__*/function () {
1259
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(path) {
1260
- return _regeneratorRuntime.wrap(function _callee$(_context5) {
1261
- while (1) switch (_context5.prev = _context5.next) {
1262
- case 0:
1263
- _context5.next = 2;
1264
- return mkdir(path, {
1265
- recursive: true
1266
- });
1267
- case 2:
1268
- case "end":
1269
- return _context5.stop();
1270
- }
1271
- }, _callee);
1272
- }));
1273
- return function (_x) {
1274
- return _ref2.apply(this, arguments);
1275
- };
1276
- }()));
1277
- case 6:
1278
- baseURL = argv["base-url"];
1279
- if (_endsWithInstanceProperty(baseURL).call(baseURL, "/")) {
1280
- _context24.next = 9;
1281
- break;
1282
- }
1283
- throw new Error("Base URL (`base-url`) has to end with a slash (`/`).");
1284
- case 9:
1285
- // Paths.
1286
- pathsConfig = {
1287
- codepen: {
1288
- local: argv["pages-local-directory"],
1289
- web: fixAbsoluteInputURL(baseURL, argv["pages-web-directory"])
1290
- },
1291
- jsfiddle: {
1292
- local: argv["pages-local-directory"],
1293
- web: fixAbsoluteInputURL(baseURL, argv["pages-web-directory"])
1294
- },
1295
- page: {
1296
- local: argv["examples-local-directory"],
1297
- web: fixAbsoluteInputURL(baseURL, argv["examples-web-directory"])
1298
- },
1299
- screenshot: {
1300
- local: argv["assets-local-directory"],
1301
- web: fixAbsoluteInputURL(baseURL, argv["assets-web-directory"])
1302
- }
1303
- };
1304
- examples = {};
1305
- selector = "#" + argv["container-id"];
1306
- stats = {
1307
- examples: 0
1308
- };
1309
- skipped = [];
1310
- _context24.t0 = _Promise;
1311
- _context24.t1 = _mapInstanceProperty;
1312
- _context24.next = 18;
1313
- return globby;
1314
- case 18:
1315
- _context24.next = 20;
1316
- return _context24.sent.default(node_path.join(pathsConfig.page.local, "**/*.html"));
1317
- case 20:
1318
- _context24.t2 = _context6 = _context24.sent;
1319
- _context24.t3 = (0, _context24.t1)(_context24.t2).call(_context6, /*#__PURE__*/function () {
1320
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(pagePath) {
1321
- var _context7;
1322
- var html, $page, pageDelay, pageTimeout, pageSelector, titles, _context9;
1323
- return _regeneratorRuntime.wrap(function _callee2$(_context10) {
1324
- while (1) switch (_context10.prev = _context10.next) {
1325
- case 0:
1326
- _context10.next = 2;
1327
- return readFile(pagePath, "utf-8");
1328
- case 2:
1329
- html = _context10.sent;
1330
- $page = $.load(html);
1331
- pageDelay = getMeta($page, "example-screenshot-delay", 6);
1332
- pageTimeout = getMeta($page, "example-screenshot-timeout", 60);
1333
- pageSelector = getMeta($page, "example-screenshot-selector", selector); // Is this an examples?
1334
- if (!($page(pageSelector).length === 0)) {
1335
- _context10.next = 10;
1336
- break;
1337
- }
1338
- skipped.push(pagePath);
1339
- return _context10.abrupt("return");
1340
- case 10:
1341
- // Lint if requested.
1342
- if (argv.lint) {
1343
- lintExample(pagePath, $page);
1344
- }
1345
- // Body titles.
1346
- titles = _mapInstanceProperty(_context7 = $page("#title > *").get()).call(_context7, function (elem) {
1347
- var _context8;
1348
- return _trimInstanceProperty(_context8 = $page(elem).text()).call(_context8);
1349
- }); // Head title fallback.
1350
- if (titles.length < 2) {
1351
- titles = _mapInstanceProperty(_context9 = $page("head > title").text().split("|")).call(_context9, function (title) {
1352
- return _trimInstanceProperty(title).call(title);
1353
- });
1354
- }
1355
- // File path fallback.
1356
- if (titles.length < 2) {
1357
- titles = pagePath.split("/");
1358
- }
1359
- // Just ignore it.
1360
- if (!(titles.length < 2)) {
1361
- _context10.next = 17;
1362
- break;
1363
- }
1364
- console.error("Title resolution failed. Skipping.");
1365
- return _context10.abrupt("return");
1366
- case 17:
1367
- // Put this example into the structure while creating any missing groups in the process.
1368
- _reduceInstanceProperty(titles).call(titles, function (acc, title, i, arr) {
1369
- while (acc[title] != null && acc[title].path != null) {
1370
- console.error("The following group already exists: ", titles);
1371
- title += "!";
1372
- }
1373
- if (i === arr.length - 1) {
1374
- if (acc[title] != null) {
1375
- console.error("The following example has the same name as an already existing group: ", titles);
1376
- return null;
1377
- } else {
1378
- var example = {
1379
- $: $page,
1380
- delay: pageDelay,
1381
- html: html,
1382
- path: pagePath,
1383
- paths: generatePaths(pathsConfig, pagePath),
1384
- playground: generatePlaygroundData(baseURL, $page, pagePath),
1385
- selector: pageSelector,
1386
- timeout: pageTimeout,
1387
- titles: titles
1388
- };
1389
- acc[title] = example;
1390
- ++stats.examples;
1391
- }
1392
- } else {
1393
- return acc[title] = acc[title] || {};
1394
- }
1395
- }, examples);
1396
- case 18:
1397
- case "end":
1398
- return _context10.stop();
1399
- }
1400
- }, _callee2);
1401
- }));
1402
- return function (_x2) {
1403
- return _ref3.apply(this, arguments);
1404
- };
1405
- }());
1406
- _context24.next = 24;
1407
- return _context24.t0.all.call(_context24.t0, _context24.t3);
1408
- case 24:
1409
- if (skipped.length) {
1410
- process.stdout.write("\n");
1411
- console.info(_concatInstanceProperty(_context11 = ["The following files don't look like examples (there is nothing to take a screenshot of):"]).call(_context11, _toConsumableArray(_sortInstanceProperty(skipped).call(skipped))).join("\n "));
1412
- }
1413
- if (!(stats.examples === 0)) {
1414
- _context24.next = 29;
1415
- break;
1416
- }
1417
- console.info("No usable example files were found.");
1418
- _context24.next = 69;
1419
- break;
1420
- case 29:
1421
- if (!(argv.index || argv.playgrounds || argv.screenshots)) {
1422
- _context24.next = 69;
1423
- break;
1424
- }
1425
- process.stdout.write("\n");
1426
- if (!(screenshotScriptPath != null)) {
1427
- _context24.next = 40;
1428
- break;
1429
- }
1430
- _context24.next = 34;
1431
- return readFile(screenshotScriptPath, "utf-8");
1432
- case 34:
1433
- _context24.t5 = _context24.sent;
1434
- if (_context24.t5) {
1435
- _context24.next = 37;
1436
- break;
1437
- }
1438
- _context24.t5 = "";
1439
- case 37:
1440
- _context24.t4 = _context24.t5;
1441
- _context24.next = 41;
1442
- break;
1443
- case 40:
1444
- _context24.t4 = "";
1445
- case 41:
1446
- screenshotScript = _context24.t4;
1447
- builtData = new ContentBuilder({
1448
- examples: examples,
1449
- output: node_path.resolve(argv["output-directory"]),
1450
- parallel: argv.parallel,
1451
- renderer: argv.format === "md" ? mdRenderer : htmlRenderer,
1452
- screenshotScript: screenshotScript,
1453
- title: argv.title
1454
- }).build({
1455
- index: argv.index,
1456
- playgrounds: argv.playgrounds,
1457
- screenshots: argv.screenshots
1458
- }); // Create and write the page.
1459
- if (!argv.index) {
1460
- _context24.next = 50;
1461
- break;
1462
- }
1463
- _context24.t6 = reduceReports;
1464
- _context24.next = 47;
1465
- return builtData.index;
1466
- case 47:
1467
- _context24.t7 = _context24.sent;
1468
- cummulativeReport = (0, _context24.t6)(_context24.t7);
1469
- console.info(_concatInstanceProperty(_context12 = _concatInstanceProperty(_context13 = "Index with ".concat(stats.examples, " examples written (")).call(_context13, cummulativeReport.count, " files in ")).call(_context12, formatStartStopMs(cummulativeReport), ")."));
1470
- case 50:
1471
- if (!argv.index) {
1472
- _context24.next = 57;
1473
- break;
1474
- }
1475
- _context24.t8 = reduceReports;
1476
- _context24.next = 54;
1477
- return builtData.playgrounds;
1478
- case 54:
1479
- _context24.t9 = _context24.sent;
1480
- _cummulativeReport = (0, _context24.t8)(_context24.t9);
1481
- console.info(_concatInstanceProperty(_context14 = _concatInstanceProperty(_context15 = "Playground opener files for ".concat(stats.examples, " examples written (")).call(_context15, _cummulativeReport.count, " files in ")).call(_context14, formatStartStopMs(_cummulativeReport), ")."));
1482
- case 57:
1483
- if (!argv.screenshots) {
1484
- _context24.next = 64;
1485
- break;
847
+ (async () => {
848
+ let code = 0;
849
+ if (!argv.index && !argv.screenshots && !argv.lint) {
850
+ yargs.parse("--help");
851
+ return;
852
+ }
853
+ await Promise.all(
854
+ [
855
+ argv["assets-local-directory"],
856
+ argv["examples-local-directory"],
857
+ argv["output-directory"],
858
+ argv["pages-local-directory"]
859
+ ].map(async (path) => {
860
+ await mkdir(path, { recursive: true });
861
+ })
862
+ );
863
+ const baseURL = argv["base-url"];
864
+ if (!baseURL.endsWith("/")) {
865
+ throw new Error("Base URL (`base-url`) has to end with a slash (`/`).");
866
+ }
867
+ const pathsConfig = {
868
+ codepen: {
869
+ local: argv["pages-local-directory"],
870
+ web: fixAbsoluteInputURL(baseURL, argv["pages-web-directory"])
871
+ },
872
+ jsfiddle: {
873
+ local: argv["pages-local-directory"],
874
+ web: fixAbsoluteInputURL(baseURL, argv["pages-web-directory"])
875
+ },
876
+ page: {
877
+ local: argv["examples-local-directory"],
878
+ web: fixAbsoluteInputURL(baseURL, argv["examples-web-directory"])
879
+ },
880
+ screenshot: {
881
+ local: argv["assets-local-directory"],
882
+ web: fixAbsoluteInputURL(baseURL, argv["assets-web-directory"])
883
+ }
884
+ };
885
+ const examples = {};
886
+ const selector = "#" + argv["container-id"];
887
+ const stats = { examples: 0 };
888
+ const skipped = [];
889
+ await Promise.all(
890
+ (await (await import('globby')).globby(join(pathsConfig.page.local, "**/*.html"))).map(async (pagePath) => {
891
+ const html = await readFile(pagePath, "utf-8");
892
+ const $page = cheerio.load(html);
893
+ const pageDelay = getMeta(
894
+ $page,
895
+ "example-screenshot-delay",
896
+ 6
897
+ );
898
+ const pageTimeout = getMeta(
899
+ $page,
900
+ "example-screenshot-timeout",
901
+ 60
902
+ );
903
+ const pageSelector = getMeta(
904
+ $page,
905
+ "example-screenshot-selector",
906
+ selector
907
+ );
908
+ if ($page(pageSelector).length === 0) {
909
+ skipped.push(pagePath);
910
+ return;
911
+ }
912
+ if (argv.lint) {
913
+ lintExample(pagePath, $page);
914
+ }
915
+ let titles = $page("#title > *").get().map((elem) => $page(elem).text().trim());
916
+ if (titles.length < 2) {
917
+ titles = $page("head > title").text().split("|").map((title) => title.trim());
918
+ }
919
+ if (titles.length < 2) {
920
+ titles = pagePath.split("/");
921
+ }
922
+ if (titles.length < 2) {
923
+ console.error("Title resolution failed. Skipping.");
924
+ return;
925
+ }
926
+ const example = {
927
+ $: $page,
928
+ delay: pageDelay,
929
+ html,
930
+ path: pagePath,
931
+ paths: generatePaths(pathsConfig, pagePath),
932
+ playground: await generatePlaygroundData(baseURL, $page, pagePath),
933
+ selector: pageSelector,
934
+ timeout: pageTimeout,
935
+ titles
936
+ };
937
+ titles.reduce((acc, title, i, arr) => {
938
+ while (acc[title] != null && acc[title].path != null) {
939
+ console.error("The following group already exists: ", titles);
940
+ title += "!";
1486
941
  }
1487
- _context24.t10 = reduceReports;
1488
- _context24.next = 61;
1489
- return builtData.screenshots;
1490
- case 61:
1491
- _context24.t11 = _context24.sent;
1492
- _cummulativeReport2 = (0, _context24.t10)(_context24.t11);
1493
- console.info(_concatInstanceProperty(_context16 = _concatInstanceProperty(_context17 = "Screenshot files for ".concat(stats.examples, " written (")).call(_context17, _cummulativeReport2.count, " files in ")).call(_context16, formatStartStopMs(_cummulativeReport2), ")."));
1494
- case 64:
1495
- _context24.next = 66;
1496
- return builtData.checks;
1497
- case 66:
1498
- checks = _context24.sent;
1499
- process.stdout.write("\n");
1500
- if (checks.fail === 0) {
1501
- console.info(_concatInstanceProperty(_context18 = "Verification: ".concat(checks.okay, " passed (")).call(_context18, Math.round(checks.percentage), " %) passed."));
1502
- } else {
1503
- if (checks.percentage >= argv.verify) {
1504
- console.info(_concatInstanceProperty(_context19 = _concatInstanceProperty(_context20 = "Verification: ".concat(checks.okay, " passed (")).call(_context20, Math.round(checks.percentage), " %), ")).call(_context19, checks.fail, " failed.\n") + "This is within the threshold set by --verify.");
942
+ if (i === arr.length - 1) {
943
+ if (acc[title] != null) {
944
+ console.error(
945
+ "The following example has the same name as an already existing group: ",
946
+ titles
947
+ );
948
+ return null;
1505
949
  } else {
1506
- console.error(_concatInstanceProperty(_context21 = _concatInstanceProperty(_context22 = "Verification: Only ".concat(checks.okay, " passed (")).call(_context22, Math.round(checks.percentage), " %), ")).call(_context21, checks.fail, " failed.\n") + "This is not within the threshold set by --verify. Exiting with an error.");
1507
- code = 3;
950
+ acc[title] = example;
951
+ ++stats.examples;
1508
952
  }
1509
- _forEachInstanceProperty(_context23 = checks.failPaths).call(_context23, function (path) {
1510
- console.error(path);
1511
- });
953
+ } else {
954
+ return acc[title] = acc[title] || {};
1512
955
  }
1513
- case 69:
1514
- process.exitCode = code;
1515
- case 70:
1516
- case "end":
1517
- return _context24.stop();
956
+ }, examples);
957
+ })
958
+ );
959
+ if (skipped.length) {
960
+ process.stdout.write("\n");
961
+ console.info(
962
+ [
963
+ "The following files don't look like examples (there is nothing to take a screenshot of):",
964
+ ...skipped.sort()
965
+ ].join("\n ")
966
+ );
967
+ }
968
+ if (stats.examples === 0) {
969
+ console.info("No usable example files were found.");
970
+ } else if (argv.index || argv.playgrounds || argv.screenshots) {
971
+ process.stdout.write("\n");
972
+ const screenshotScript = screenshotScriptPath != null ? await readFile(screenshotScriptPath, "utf-8") || "" : "";
973
+ const builtData = new ContentBuilder({
974
+ examples,
975
+ output: resolve(argv["output-directory"]),
976
+ parallel: argv.parallel,
977
+ renderer: argv.format === "md" ? mdRenderer : htmlRenderer,
978
+ screenshotScript,
979
+ title: argv.title
980
+ }).build({
981
+ index: argv.index,
982
+ playgrounds: argv.playgrounds,
983
+ screenshots: argv.screenshots
984
+ });
985
+ if (argv.index) {
986
+ const cummulativeReport = reduceReports(await builtData.index);
987
+ console.info(
988
+ `Index with ${stats.examples} examples written (${cummulativeReport.count} files in ${formatStartStopMs(cummulativeReport)}).`
989
+ );
990
+ }
991
+ if (argv.index) {
992
+ const cummulativeReport = reduceReports(await builtData.playgrounds);
993
+ console.info(
994
+ `Playground opener files for ${stats.examples} examples written (${cummulativeReport.count} files in ${formatStartStopMs(cummulativeReport)}).`
995
+ );
996
+ }
997
+ if (argv.screenshots) {
998
+ const cummulativeReport = reduceReports(await builtData.screenshots);
999
+ console.info(
1000
+ `Screenshot files for ${stats.examples} written (${cummulativeReport.count} files in ${formatStartStopMs(cummulativeReport)}).`
1001
+ );
1518
1002
  }
1519
- }, _callee3);
1520
- }))().catch(function (error) {
1003
+ const checks = await builtData.checks;
1004
+ process.stdout.write("\n");
1005
+ if (checks.fail === 0) {
1006
+ console.info(
1007
+ `Verification: ${checks.okay} passed (${Math.round(
1008
+ checks.percentage
1009
+ )} %) passed.`
1010
+ );
1011
+ } else {
1012
+ if (checks.percentage >= argv.verify) {
1013
+ console.info(
1014
+ `Verification: ${checks.okay} passed (${Math.round(
1015
+ checks.percentage
1016
+ )} %), ${checks.fail} failed.
1017
+ This is within the threshold set by --verify.`
1018
+ );
1019
+ } else {
1020
+ console.error(
1021
+ `Verification: Only ${checks.okay} passed (${Math.round(
1022
+ checks.percentage
1023
+ )} %), ${checks.fail} failed.
1024
+ This is not within the threshold set by --verify. Exiting with an error.`
1025
+ );
1026
+ code = 3;
1027
+ }
1028
+ checks.failPaths.forEach((path) => {
1029
+ console.error(path);
1030
+ });
1031
+ }
1032
+ }
1033
+ process.exitCode = code;
1034
+ })().catch((error) => {
1521
1035
  process.exitCode = 1;
1522
1036
  console.error(error);
1523
1037
  });