@rindo/core 2.16.0-beta.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 (229) hide show
  1. package/LICENSE.md +27 -0
  2. package/bin/rindo +57 -0
  3. package/cli/index.cjs +1784 -0
  4. package/cli/index.d.ts +15 -0
  5. package/cli/index.js +1758 -0
  6. package/cli/package.json +14 -0
  7. package/compiler/lib.d.ts +24 -0
  8. package/compiler/lib.dom.d.ts +17791 -0
  9. package/compiler/lib.dom.iterable.d.ts +323 -0
  10. package/compiler/lib.es2015.collection.d.ts +89 -0
  11. package/compiler/lib.es2015.core.d.ts +559 -0
  12. package/compiler/lib.es2015.d.ts +30 -0
  13. package/compiler/lib.es2015.generator.d.ts +79 -0
  14. package/compiler/lib.es2015.iterable.d.ts +497 -0
  15. package/compiler/lib.es2015.promise.d.ts +78 -0
  16. package/compiler/lib.es2015.proxy.d.ts +41 -0
  17. package/compiler/lib.es2015.reflect.d.ts +123 -0
  18. package/compiler/lib.es2015.symbol.d.ts +48 -0
  19. package/compiler/lib.es2015.symbol.wellknown.d.ts +324 -0
  20. package/compiler/lib.es2016.array.include.d.ts +118 -0
  21. package/compiler/lib.es2016.d.ts +22 -0
  22. package/compiler/lib.es2016.full.d.ts +25 -0
  23. package/compiler/lib.es2017.d.ts +26 -0
  24. package/compiler/lib.es2017.full.d.ts +25 -0
  25. package/compiler/lib.es2017.intl.d.ts +32 -0
  26. package/compiler/lib.es2017.object.d.ts +51 -0
  27. package/compiler/lib.es2017.sharedmemory.d.ts +137 -0
  28. package/compiler/lib.es2017.string.d.ts +47 -0
  29. package/compiler/lib.es2017.typedarrays.d.ts +55 -0
  30. package/compiler/lib.es2018.asyncgenerator.d.ts +79 -0
  31. package/compiler/lib.es2018.asynciterable.d.ts +45 -0
  32. package/compiler/lib.es2018.d.ts +26 -0
  33. package/compiler/lib.es2018.full.d.ts +25 -0
  34. package/compiler/lib.es2018.intl.d.ts +73 -0
  35. package/compiler/lib.es2018.promise.d.ts +32 -0
  36. package/compiler/lib.es2018.regexp.d.ts +39 -0
  37. package/compiler/lib.es2019.array.d.ts +85 -0
  38. package/compiler/lib.es2019.d.ts +25 -0
  39. package/compiler/lib.es2019.full.d.ts +25 -0
  40. package/compiler/lib.es2019.object.d.ts +35 -0
  41. package/compiler/lib.es2019.string.d.ts +39 -0
  42. package/compiler/lib.es2019.symbol.d.ts +26 -0
  43. package/compiler/lib.es2020.bigint.d.ts +728 -0
  44. package/compiler/lib.es2020.d.ts +27 -0
  45. package/compiler/lib.es2020.full.d.ts +25 -0
  46. package/compiler/lib.es2020.intl.d.ts +368 -0
  47. package/compiler/lib.es2020.promise.d.ts +49 -0
  48. package/compiler/lib.es2020.sharedmemory.d.ts +99 -0
  49. package/compiler/lib.es2020.string.d.ts +30 -0
  50. package/compiler/lib.es2020.symbol.wellknown.d.ts +39 -0
  51. package/compiler/lib.es2021.d.ts +25 -0
  52. package/compiler/lib.es2021.full.d.ts +25 -0
  53. package/compiler/lib.es2021.intl.d.ts +44 -0
  54. package/compiler/lib.es2021.promise.d.ts +50 -0
  55. package/compiler/lib.es2021.string.d.ts +35 -0
  56. package/compiler/lib.es2021.weakref.d.ts +75 -0
  57. package/compiler/lib.es5.d.ts +4495 -0
  58. package/compiler/lib.es6.d.ts +25 -0
  59. package/compiler/lib.esnext.d.ts +22 -0
  60. package/compiler/lib.esnext.full.d.ts +25 -0
  61. package/compiler/lib.esnext.intl.d.ts +23 -0
  62. package/compiler/lib.esnext.promise.d.ts +43 -0
  63. package/compiler/lib.esnext.string.d.ts +35 -0
  64. package/compiler/lib.esnext.weakref.d.ts +75 -0
  65. package/compiler/lib.scripthost.d.ts +327 -0
  66. package/compiler/lib.webworker.d.ts +5733 -0
  67. package/compiler/lib.webworker.importscripts.d.ts +26 -0
  68. package/compiler/lib.webworker.iterable.d.ts +160 -0
  69. package/compiler/package.json +8 -0
  70. package/compiler/rindo.d.ts +95 -0
  71. package/compiler/rindo.js +67222 -0
  72. package/compiler/rindo.min.js +4 -0
  73. package/dependencies.json +109 -0
  74. package/dev-server/client/app-error.d.ts +18 -0
  75. package/dev-server/client/events.d.ts +6 -0
  76. package/dev-server/client/hmr-components.d.ts +1 -0
  77. package/dev-server/client/hmr-external-styles.d.ts +1 -0
  78. package/dev-server/client/hmr-images.d.ts +1 -0
  79. package/dev-server/client/hmr-inline-styles.d.ts +1 -0
  80. package/dev-server/client/hmr-util.d.ts +9 -0
  81. package/dev-server/client/hmr-window.d.ts +10 -0
  82. package/dev-server/client/index.d.ts +6 -0
  83. package/dev-server/client/index.js +808 -0
  84. package/dev-server/client/logger.d.ts +5 -0
  85. package/dev-server/client/package.json +8 -0
  86. package/dev-server/client/progress.d.ts +3 -0
  87. package/dev-server/client/status.d.ts +4 -0
  88. package/dev-server/connector.html +6 -0
  89. package/dev-server/index.d.ts +3 -0
  90. package/dev-server/index.js +264 -0
  91. package/dev-server/open-in-editor-api.js +1 -0
  92. package/dev-server/package.json +8 -0
  93. package/dev-server/server-process.js +1763 -0
  94. package/dev-server/server-worker-thread.js +39 -0
  95. package/dev-server/static/favicon.ico +0 -0
  96. package/dev-server/templates/directory-index.html +132 -0
  97. package/dev-server/templates/initial-load.html +160 -0
  98. package/dev-server/visualstudio.vbs +82 -0
  99. package/dev-server/ws.js +1 -0
  100. package/dev-server/xdg-open +1066 -0
  101. package/internal/app-data/index.cjs +92 -0
  102. package/internal/app-data/index.d.ts +4 -0
  103. package/internal/app-data/index.js +88 -0
  104. package/internal/app-data/package.json +15 -0
  105. package/internal/client/css-shim.js +4 -0
  106. package/internal/client/dom.js +73 -0
  107. package/internal/client/index.js +3059 -0
  108. package/internal/client/package.json +8 -0
  109. package/internal/client/patch-browser.js +124 -0
  110. package/internal/client/patch-esm.js +23 -0
  111. package/internal/client/polyfills/core-js.js +11 -0
  112. package/internal/client/polyfills/css-shim.js +1 -0
  113. package/internal/client/polyfills/dom.js +79 -0
  114. package/internal/client/polyfills/es5-html-element.js +1 -0
  115. package/internal/client/polyfills/index.js +34 -0
  116. package/internal/client/polyfills/system.js +6 -0
  117. package/internal/client/shadow-css.js +387 -0
  118. package/internal/hydrate/index.js +1132 -0
  119. package/internal/hydrate/package.json +7 -0
  120. package/internal/hydrate/runner.d.ts +217 -0
  121. package/internal/hydrate/runner.js +777 -0
  122. package/internal/hydrate/shadow-css.js +143 -0
  123. package/internal/index.d.ts +4 -0
  124. package/internal/index.js +2 -0
  125. package/internal/package.json +9 -0
  126. package/internal/rindo-core/index.cjs +1 -0
  127. package/internal/rindo-core/index.d.ts +52 -0
  128. package/internal/rindo-core/index.js +16 -0
  129. package/internal/rindo-ext-modules.d.ts +41 -0
  130. package/internal/rindo-private.d.ts +2289 -0
  131. package/internal/rindo-public-compiler.d.ts +2273 -0
  132. package/internal/rindo-public-docs.d.ts +116 -0
  133. package/internal/rindo-public-runtime.d.ts +1565 -0
  134. package/internal/testing/index.js +1093 -0
  135. package/internal/testing/package.json +7 -0
  136. package/internal/testing/shadow-css.js +143 -0
  137. package/mock-doc/index.cjs +4658 -0
  138. package/mock-doc/index.d.ts +928 -0
  139. package/mock-doc/index.js +4622 -0
  140. package/mock-doc/package.json +15 -0
  141. package/package.json +151 -0
  142. package/readme.md +74 -0
  143. package/screenshot/compare/assets/favicon.ico +0 -0
  144. package/screenshot/compare/assets/logo.png +0 -0
  145. package/screenshot/compare/build/app.css +1 -0
  146. package/screenshot/compare/build/app.esm.js +1 -0
  147. package/screenshot/compare/build/app.js +33 -0
  148. package/screenshot/compare/build/index.esm.js +0 -0
  149. package/screenshot/compare/build/p-081b0641.js +1 -0
  150. package/screenshot/compare/build/p-227a1e18.entry.js +1 -0
  151. package/screenshot/compare/build/p-2c298727.entry.js +1 -0
  152. package/screenshot/compare/build/p-5479268c.entry.js +1 -0
  153. package/screenshot/compare/build/p-573ec8a4.entry.js +1 -0
  154. package/screenshot/compare/build/p-6ba08604.entry.js +1 -0
  155. package/screenshot/compare/build/p-6bc63295.entry.js +1 -0
  156. package/screenshot/compare/build/p-7a3759fd.entry.js +1 -0
  157. package/screenshot/compare/build/p-7b4e3ba7.js +1 -0
  158. package/screenshot/compare/build/p-988eb362.css +1 -0
  159. package/screenshot/compare/build/p-9b6a9315.js +1 -0
  160. package/screenshot/compare/build/p-b4cc611c.entry.js +1 -0
  161. package/screenshot/compare/build/p-d1bf53f5.entry.js +1 -0
  162. package/screenshot/compare/build/p-e2efe0df.js +1 -0
  163. package/screenshot/compare/build/p-e8ca6d97.entry.js +1 -0
  164. package/screenshot/compare/build/p-ec2f13e0.entry.js +1 -0
  165. package/screenshot/compare/build/p-f0b99977.entry.js +1 -0
  166. package/screenshot/compare/build/p-f4745c2f.entry.js +1 -0
  167. package/screenshot/compare/build/p-fbbae598.js +1 -0
  168. package/screenshot/compare/host.config.json +15 -0
  169. package/screenshot/compare/index.html +1 -0
  170. package/screenshot/compare/manifest.json +13 -0
  171. package/screenshot/connector-base.d.ts +42 -0
  172. package/screenshot/connector-local.d.ts +7 -0
  173. package/screenshot/connector.js +2 -0
  174. package/screenshot/index.d.ts +3 -0
  175. package/screenshot/index.js +659 -0
  176. package/screenshot/local-connector.js +2 -0
  177. package/screenshot/package.json +15 -0
  178. package/screenshot/pixel-match.d.ts +1 -0
  179. package/screenshot/pixel-match.js +2673 -0
  180. package/screenshot/screenshot-compare.d.ts +3 -0
  181. package/screenshot/screenshot-fs.d.ts +15 -0
  182. package/sys/node/autoprefixer.js +8 -0
  183. package/sys/node/glob.js +1 -0
  184. package/sys/node/graceful-fs.js +1 -0
  185. package/sys/node/index.d.ts +18 -0
  186. package/sys/node/index.js +6124 -0
  187. package/sys/node/node-fetch.js +1 -0
  188. package/sys/node/package.json +8 -0
  189. package/sys/node/prompts.js +1 -0
  190. package/sys/node/worker.js +52 -0
  191. package/testing/index.d.ts +12 -0
  192. package/testing/index.js +4232 -0
  193. package/testing/jest/jest-config.d.ts +16 -0
  194. package/testing/jest/jest-environment.d.ts +15 -0
  195. package/testing/jest/jest-preprocessor.d.ts +59 -0
  196. package/testing/jest/jest-runner.d.ts +9 -0
  197. package/testing/jest/jest-screenshot.d.ts +2 -0
  198. package/testing/jest/jest-serializer.d.ts +5 -0
  199. package/testing/jest/jest-setup-test-framework.d.ts +1 -0
  200. package/testing/jest-environment.js +3 -0
  201. package/testing/jest-preprocessor.js +3 -0
  202. package/testing/jest-preset.js +37 -0
  203. package/testing/jest-runner.js +3 -0
  204. package/testing/jest-setuptestframework.js +3 -0
  205. package/testing/matchers/attributes.d.ts +14 -0
  206. package/testing/matchers/class-list.d.ts +12 -0
  207. package/testing/matchers/events.d.ts +21 -0
  208. package/testing/matchers/html.d.ts +12 -0
  209. package/testing/matchers/index.d.ts +23 -0
  210. package/testing/matchers/screenshot.d.ts +5 -0
  211. package/testing/matchers/text.d.ts +4 -0
  212. package/testing/mock-fetch.d.ts +11 -0
  213. package/testing/mocks.d.ts +10 -0
  214. package/testing/package.json +8 -0
  215. package/testing/puppeteer/index.d.ts +2 -0
  216. package/testing/puppeteer/puppeteer-browser.d.ts +6 -0
  217. package/testing/puppeteer/puppeteer-declarations.d.ts +429 -0
  218. package/testing/puppeteer/puppeteer-element.d.ts +67 -0
  219. package/testing/puppeteer/puppeteer-emulate.d.ts +2 -0
  220. package/testing/puppeteer/puppeteer-events.d.ts +21 -0
  221. package/testing/puppeteer/puppeteer-page.d.ts +2 -0
  222. package/testing/puppeteer/puppeteer-screenshot.d.ts +4 -0
  223. package/testing/reset-build-conditionals.d.ts +2 -0
  224. package/testing/spec-page.d.ts +2 -0
  225. package/testing/test-transpile.d.ts +2 -0
  226. package/testing/testing-logger.d.ts +25 -0
  227. package/testing/testing-sys.d.ts +6 -0
  228. package/testing/testing-utils.d.ts +6 -0
  229. package/testing/testing.d.ts +2 -0
package/cli/index.cjs ADDED
@@ -0,0 +1,1784 @@
1
+ /*!
2
+ Rindo CLI (CommonJS) v0.0.0-dev.20220810110141 | MIT Licensed | https://rindojs.web.app
3
+ */
4
+ 'use strict';
5
+
6
+ Object.defineProperty(exports, '__esModule', { value: true });
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () {
18
+ return e[k];
19
+ }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n['default'] = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ const toLowerCase = (str) => str.toLowerCase();
29
+ const dashToPascalCase = (str) => toLowerCase(str)
30
+ .split('-')
31
+ .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
32
+ .join('');
33
+ const isFunction = (v) => typeof v === 'function';
34
+ const isString = (v) => typeof v === 'string';
35
+
36
+ /**
37
+ * Builds a template `Diagnostic` entity for a build error. The created `Diagnostic` is returned, and have little
38
+ * detail attached to it regarding the specifics of the error - it is the responsibility of the caller of this method
39
+ * to attach the specifics of the error message.
40
+ *
41
+ * The created `Diagnostic` is pushed to the `diagnostics` argument as a side effect of calling this method.
42
+ *
43
+ * @param diagnostics the existing diagnostics that the created template `Diagnostic` should be added to
44
+ * @returns the created `Diagnostic`
45
+ */
46
+ const buildError = (diagnostics) => {
47
+ const diagnostic = {
48
+ level: 'error',
49
+ type: 'build',
50
+ header: 'Build Error',
51
+ messageText: 'build error',
52
+ relFilePath: null,
53
+ absFilePath: null,
54
+ lines: [],
55
+ };
56
+ if (diagnostics) {
57
+ diagnostics.push(diagnostic);
58
+ }
59
+ return diagnostic;
60
+ };
61
+ /**
62
+ * Builds a diagnostic from an `Error`, appends it to the `diagnostics` parameter, and returns the created diagnostic
63
+ * @param diagnostics the series of diagnostics the newly created diagnostics should be added to
64
+ * @param err the error to derive information from in generating the diagnostic
65
+ * @param msg an optional message to use in place of `err` to generate the diagnostic
66
+ * @returns the generated diagnostic
67
+ */
68
+ const catchError = (diagnostics, err, msg) => {
69
+ const diagnostic = {
70
+ level: 'error',
71
+ type: 'build',
72
+ header: 'Build Error',
73
+ messageText: 'build error',
74
+ relFilePath: null,
75
+ absFilePath: null,
76
+ lines: [],
77
+ };
78
+ if (isString(msg)) {
79
+ diagnostic.messageText = msg.length ? msg : 'UNKNOWN ERROR';
80
+ }
81
+ else if (err != null) {
82
+ if (err.stack != null) {
83
+ diagnostic.messageText = err.stack.toString();
84
+ }
85
+ else {
86
+ if (err.message != null) {
87
+ diagnostic.messageText = err.message.length ? err.message : 'UNKNOWN ERROR';
88
+ }
89
+ else {
90
+ diagnostic.messageText = err.toString();
91
+ }
92
+ }
93
+ }
94
+ if (diagnostics != null && !shouldIgnoreError(diagnostic.messageText)) {
95
+ diagnostics.push(diagnostic);
96
+ }
97
+ return diagnostic;
98
+ };
99
+ /**
100
+ * Determine if the provided diagnostics have any build errors
101
+ * @param diagnostics the diagnostics to inspect
102
+ * @returns true if any of the diagnostics in the list provided are errors that did not occur at runtime. false
103
+ * otherwise.
104
+ */
105
+ const hasError = (diagnostics) => {
106
+ if (diagnostics == null || diagnostics.length === 0) {
107
+ return false;
108
+ }
109
+ return diagnostics.some((d) => d.level === 'error' && d.type !== 'runtime');
110
+ };
111
+ const shouldIgnoreError = (msg) => {
112
+ return msg === TASK_CANCELED_MSG;
113
+ };
114
+ const TASK_CANCELED_MSG = `task canceled`;
115
+
116
+ /**
117
+ * Convert Windows backslash paths to slash paths: foo\\bar ➔ foo/bar
118
+ * Forward-slash paths can be used in Windows as long as they're not
119
+ * extended-length paths and don't contain any non-ascii characters.
120
+ * This was created since the path methods in Node.js outputs \\ paths on Windows.
121
+ */
122
+ const normalizePath = (path) => {
123
+ if (typeof path !== 'string') {
124
+ throw new Error(`invalid path to normalize`);
125
+ }
126
+ path = normalizeSlashes(path.trim());
127
+ const components = pathComponents(path, getRootLength(path));
128
+ const reducedComponents = reducePathComponents(components);
129
+ const rootPart = reducedComponents[0];
130
+ const secondPart = reducedComponents[1];
131
+ const normalized = rootPart + reducedComponents.slice(1).join('/');
132
+ if (normalized === '') {
133
+ return '.';
134
+ }
135
+ if (rootPart === '' &&
136
+ secondPart &&
137
+ path.includes('/') &&
138
+ !secondPart.startsWith('.') &&
139
+ !secondPart.startsWith('@')) {
140
+ return './' + normalized;
141
+ }
142
+ return normalized;
143
+ };
144
+ const normalizeSlashes = (path) => path.replace(backslashRegExp, '/');
145
+ const altDirectorySeparator = '\\';
146
+ const urlSchemeSeparator = '://';
147
+ const backslashRegExp = /\\/g;
148
+ const reducePathComponents = (components) => {
149
+ if (!Array.isArray(components) || components.length === 0) {
150
+ return [];
151
+ }
152
+ const reduced = [components[0]];
153
+ for (let i = 1; i < components.length; i++) {
154
+ const component = components[i];
155
+ if (!component)
156
+ continue;
157
+ if (component === '.')
158
+ continue;
159
+ if (component === '..') {
160
+ if (reduced.length > 1) {
161
+ if (reduced[reduced.length - 1] !== '..') {
162
+ reduced.pop();
163
+ continue;
164
+ }
165
+ }
166
+ else if (reduced[0])
167
+ continue;
168
+ }
169
+ reduced.push(component);
170
+ }
171
+ return reduced;
172
+ };
173
+ const getRootLength = (path) => {
174
+ const rootLength = getEncodedRootLength(path);
175
+ return rootLength < 0 ? ~rootLength : rootLength;
176
+ };
177
+ const getEncodedRootLength = (path) => {
178
+ if (!path)
179
+ return 0;
180
+ const ch0 = path.charCodeAt(0);
181
+ // POSIX or UNC
182
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
183
+ if (path.charCodeAt(1) !== ch0)
184
+ return 1; // POSIX: "/" (or non-normalized "\")
185
+ const p1 = path.indexOf(ch0 === 47 /* slash */ ? '/' : altDirectorySeparator, 2);
186
+ if (p1 < 0)
187
+ return path.length; // UNC: "//server" or "\\server"
188
+ return p1 + 1; // UNC: "//server/" or "\\server\"
189
+ }
190
+ // DOS
191
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
192
+ const ch2 = path.charCodeAt(2);
193
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
194
+ return 3; // DOS: "c:/" or "c:\"
195
+ if (path.length === 2)
196
+ return 2; // DOS: "c:" (but not "c:d")
197
+ }
198
+ // URL
199
+ const schemeEnd = path.indexOf(urlSchemeSeparator);
200
+ if (schemeEnd !== -1) {
201
+ const authorityStart = schemeEnd + urlSchemeSeparator.length;
202
+ const authorityEnd = path.indexOf('/', authorityStart);
203
+ if (authorityEnd !== -1) {
204
+ // URL: "file:///", "file://server/", "file://server/path"
205
+ // For local "file" URLs, include the leading DOS volume (if present).
206
+ // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
207
+ // special case interpreted as "the machine from which the URL is being interpreted".
208
+ const scheme = path.slice(0, schemeEnd);
209
+ const authority = path.slice(authorityStart, authorityEnd);
210
+ if (scheme === 'file' &&
211
+ (authority === '' || authority === 'localhost') &&
212
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
213
+ const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
214
+ if (volumeSeparatorEnd !== -1) {
215
+ if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
216
+ // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
217
+ return ~(volumeSeparatorEnd + 1);
218
+ }
219
+ if (volumeSeparatorEnd === path.length) {
220
+ // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
221
+ // but not "file:///c:d" or "file:///c%3ad"
222
+ return ~volumeSeparatorEnd;
223
+ }
224
+ }
225
+ }
226
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
227
+ }
228
+ return ~path.length; // URL: "file://server", "http://server"
229
+ }
230
+ // relative
231
+ return 0;
232
+ };
233
+ const isVolumeCharacter = (charCode) => (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
234
+ (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
235
+ const getFileUrlVolumeSeparatorEnd = (url, start) => {
236
+ const ch0 = url.charCodeAt(start);
237
+ if (ch0 === 58 /* colon */)
238
+ return start + 1;
239
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
240
+ const ch2 = url.charCodeAt(start + 2);
241
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
242
+ return start + 3;
243
+ }
244
+ return -1;
245
+ };
246
+ const pathComponents = (path, rootLength) => {
247
+ const root = path.substring(0, rootLength);
248
+ const rest = path.substring(rootLength).split('/');
249
+ const restLen = rest.length;
250
+ if (restLen > 0 && !rest[restLen - 1]) {
251
+ rest.pop();
252
+ }
253
+ return [root, ...rest];
254
+ };
255
+
256
+ /**
257
+ * Validates that a component tag meets required naming conventions to be used for a web component
258
+ * @param tag the tag to validate
259
+ * @returns an error message if the tag has an invalid name, undefined if the tag name passes all checks
260
+ */
261
+ const validateComponentTag = (tag) => {
262
+ // we want to check this first since we call some String.prototype methods below
263
+ if (typeof tag !== 'string') {
264
+ return `Tag "${tag}" must be a string type`;
265
+ }
266
+ if (tag !== tag.trim()) {
267
+ return `Tag can not contain white spaces`;
268
+ }
269
+ if (tag !== tag.toLowerCase()) {
270
+ return `Tag can not contain upper case characters`;
271
+ }
272
+ if (tag.length === 0) {
273
+ return `Received empty tag value`;
274
+ }
275
+ if (tag.indexOf(' ') > -1) {
276
+ return `"${tag}" tag cannot contain a space`;
277
+ }
278
+ if (tag.indexOf(',') > -1) {
279
+ return `"${tag}" tag cannot be used for multiple tags`;
280
+ }
281
+ const invalidChars = tag.replace(/\w|-/g, '');
282
+ if (invalidChars !== '') {
283
+ return `"${tag}" tag contains invalid characters: ${invalidChars}`;
284
+ }
285
+ if (tag.indexOf('-') === -1) {
286
+ return `"${tag}" tag must contain a dash (-) to work as a valid web component`;
287
+ }
288
+ if (tag.indexOf('--') > -1) {
289
+ return `"${tag}" tag cannot contain multiple dashes (--) next to each other`;
290
+ }
291
+ if (tag.indexOf('-') === 0) {
292
+ return `"${tag}" tag cannot start with a dash (-)`;
293
+ }
294
+ if (tag.lastIndexOf('-') === tag.length - 1) {
295
+ return `"${tag}" tag cannot end with a dash (-)`;
296
+ }
297
+ return undefined;
298
+ };
299
+
300
+ const parseFlags = (args, sys) => {
301
+ const flags = {
302
+ task: null,
303
+ args: [],
304
+ knownArgs: [],
305
+ unknownArgs: null,
306
+ };
307
+ // cmd line has more priority over npm scripts cmd
308
+ flags.args = args.slice();
309
+ if (flags.args.length > 0 && flags.args[0] && !flags.args[0].startsWith('-')) {
310
+ flags.task = flags.args[0];
311
+ }
312
+ parseArgs(flags, flags.args, flags.knownArgs);
313
+ if (sys && sys.name === 'node') {
314
+ const envArgs = getNpmConfigEnvArgs(sys);
315
+ parseArgs(flags, envArgs, flags.knownArgs);
316
+ envArgs.forEach((envArg) => {
317
+ if (!flags.args.includes(envArg)) {
318
+ flags.args.push(envArg);
319
+ }
320
+ });
321
+ }
322
+ if (flags.task != null) {
323
+ const i = flags.args.indexOf(flags.task);
324
+ if (i > -1) {
325
+ flags.args.splice(i, 1);
326
+ }
327
+ }
328
+ flags.unknownArgs = flags.args.filter((arg) => {
329
+ return !flags.knownArgs.includes(arg);
330
+ });
331
+ return flags;
332
+ };
333
+ /**
334
+ * Parse command line arguments that are whitelisted via the BOOLEAN_ARG_OPTS,
335
+ * STRING_ARG_OPTS, and NUMBER_ARG_OPTS arrays in this file. Handles leading
336
+ * dashes on arguments, aliases that are defined for a small number of argument
337
+ * types, and parsing values for non-boolean arguments (e.g. port number).
338
+ *
339
+ * @param flags a ConfigFlags object
340
+ * @param args an array of command-line arguments to parse
341
+ * @param knownArgs an array to which all recognized, legal arguments are added
342
+ */
343
+ const parseArgs = (flags, args, knownArgs) => {
344
+ BOOLEAN_ARG_OPTS.forEach((booleanName) => {
345
+ const alias = ARG_OPTS_ALIASES[booleanName];
346
+ const flagKey = configCase(booleanName);
347
+ if (typeof flags[flagKey] !== 'boolean') {
348
+ flags[flagKey] = null;
349
+ }
350
+ args.forEach((cmdArg) => {
351
+ if (cmdArg === `--${booleanName}`) {
352
+ flags[flagKey] = true;
353
+ knownArgs.push(cmdArg);
354
+ }
355
+ else if (cmdArg === `--${flagKey}`) {
356
+ flags[flagKey] = true;
357
+ knownArgs.push(cmdArg);
358
+ }
359
+ else if (cmdArg === `--no-${booleanName}`) {
360
+ flags[flagKey] = false;
361
+ knownArgs.push(cmdArg);
362
+ }
363
+ else if (cmdArg === `--no${dashToPascalCase(booleanName)}`) {
364
+ flags[flagKey] = false;
365
+ knownArgs.push(cmdArg);
366
+ }
367
+ else if (alias && cmdArg === `-${alias}`) {
368
+ flags[flagKey] = true;
369
+ knownArgs.push(cmdArg);
370
+ }
371
+ });
372
+ });
373
+ STRING_ARG_OPTS.forEach((stringName) => {
374
+ const alias = ARG_OPTS_ALIASES[stringName];
375
+ const flagKey = configCase(stringName);
376
+ if (typeof flags[flagKey] !== 'string') {
377
+ flags[flagKey] = null;
378
+ }
379
+ for (let i = 0; i < args.length; i++) {
380
+ const cmdArg = args[i];
381
+ if (cmdArg.startsWith(`--${stringName}=`)) {
382
+ const values = cmdArg.split('=');
383
+ values.shift();
384
+ flags[flagKey] = values.join('=');
385
+ knownArgs.push(cmdArg);
386
+ }
387
+ else if (cmdArg === `--${stringName}`) {
388
+ flags[flagKey] = args[i + 1];
389
+ knownArgs.push(cmdArg);
390
+ knownArgs.push(args[i + 1]);
391
+ }
392
+ else if (cmdArg === `--${flagKey}`) {
393
+ flags[flagKey] = args[i + 1];
394
+ knownArgs.push(cmdArg);
395
+ knownArgs.push(args[i + 1]);
396
+ }
397
+ else if (cmdArg.startsWith(`--${flagKey}=`)) {
398
+ const values = cmdArg.split('=');
399
+ values.shift();
400
+ flags[flagKey] = values.join('=');
401
+ knownArgs.push(cmdArg);
402
+ }
403
+ else if (alias) {
404
+ if (cmdArg.startsWith(`-${alias}=`)) {
405
+ const values = cmdArg.split('=');
406
+ values.shift();
407
+ flags[flagKey] = values.join('=');
408
+ knownArgs.push(cmdArg);
409
+ }
410
+ else if (cmdArg === `-${alias}`) {
411
+ flags[flagKey] = args[i + 1];
412
+ knownArgs.push(args[i + 1]);
413
+ }
414
+ }
415
+ }
416
+ });
417
+ NUMBER_ARG_OPTS.forEach((numberName) => {
418
+ const alias = ARG_OPTS_ALIASES[numberName];
419
+ const flagKey = configCase(numberName);
420
+ if (typeof flags[flagKey] !== 'number') {
421
+ flags[flagKey] = null;
422
+ }
423
+ for (let i = 0; i < args.length; i++) {
424
+ const cmdArg = args[i];
425
+ if (cmdArg.startsWith(`--${numberName}=`)) {
426
+ const values = cmdArg.split('=');
427
+ values.shift();
428
+ flags[flagKey] = parseInt(values.join(''), 10);
429
+ knownArgs.push(cmdArg);
430
+ }
431
+ else if (cmdArg === `--${numberName}`) {
432
+ flags[flagKey] = parseInt(args[i + 1], 10);
433
+ knownArgs.push(args[i + 1]);
434
+ }
435
+ else if (cmdArg.startsWith(`--${flagKey}=`)) {
436
+ const values = cmdArg.split('=');
437
+ values.shift();
438
+ flags[flagKey] = parseInt(values.join(''), 10);
439
+ knownArgs.push(cmdArg);
440
+ }
441
+ else if (cmdArg === `--${flagKey}`) {
442
+ flags[flagKey] = parseInt(args[i + 1], 10);
443
+ knownArgs.push(args[i + 1]);
444
+ }
445
+ else if (alias) {
446
+ if (cmdArg.startsWith(`-${alias}=`)) {
447
+ const values = cmdArg.split('=');
448
+ values.shift();
449
+ flags[flagKey] = parseInt(values.join(''), 10);
450
+ knownArgs.push(cmdArg);
451
+ }
452
+ else if (cmdArg === `-${alias}`) {
453
+ flags[flagKey] = parseInt(args[i + 1], 10);
454
+ knownArgs.push(args[i + 1]);
455
+ }
456
+ }
457
+ }
458
+ });
459
+ };
460
+ const configCase = (prop) => {
461
+ prop = dashToPascalCase(prop);
462
+ return prop.charAt(0).toLowerCase() + prop.slice(1);
463
+ };
464
+ const BOOLEAN_ARG_OPTS = [
465
+ 'build',
466
+ 'cache',
467
+ 'check-version',
468
+ 'ci',
469
+ 'compare',
470
+ 'debug',
471
+ 'dev',
472
+ 'devtools',
473
+ 'docs',
474
+ 'e2e',
475
+ 'es5',
476
+ 'esm',
477
+ 'headless',
478
+ 'help',
479
+ 'log',
480
+ 'open',
481
+ 'prerender',
482
+ 'prerender-external',
483
+ 'prod',
484
+ 'profile',
485
+ 'service-worker',
486
+ 'screenshot',
487
+ 'serve',
488
+ 'skip-node-check',
489
+ 'spec',
490
+ 'ssr',
491
+ 'stats',
492
+ 'update-screenshot',
493
+ 'verbose',
494
+ 'version',
495
+ 'watch',
496
+ ];
497
+ const NUMBER_ARG_OPTS = ['max-workers', 'port'];
498
+ const STRING_ARG_OPTS = [
499
+ 'address',
500
+ 'config',
501
+ 'docs-json',
502
+ 'emulate',
503
+ 'log-level',
504
+ 'root',
505
+ 'screenshot-connector',
506
+ ];
507
+ const ARG_OPTS_ALIASES = {
508
+ config: 'c',
509
+ help: 'h',
510
+ port: 'p',
511
+ version: 'v',
512
+ };
513
+ const getNpmConfigEnvArgs = (sys) => {
514
+ // process.env.npm_config_argv
515
+ // {"remain":["4444"],"cooked":["run","serve","--port","4444"],"original":["run","serve","--port","4444"]}
516
+ let args = [];
517
+ try {
518
+ const npmConfigArgs = sys.getEnvironmentVar('npm_config_argv');
519
+ if (npmConfigArgs) {
520
+ args = JSON.parse(npmConfigArgs).original;
521
+ if (args[0] === 'run') {
522
+ args = args.slice(2);
523
+ }
524
+ }
525
+ }
526
+ catch (e) { }
527
+ return args;
528
+ };
529
+
530
+ const dependencies = [
531
+ {
532
+ name: "@rindo/core",
533
+ version: "0.0.0-dev.20220810110141",
534
+ main: "compiler/rindo.js",
535
+ resources: [
536
+ "package.json",
537
+ "compiler/lib.d.ts",
538
+ "compiler/lib.dom.d.ts",
539
+ "compiler/lib.dom.iterable.d.ts",
540
+ "compiler/lib.es2015.collection.d.ts",
541
+ "compiler/lib.es2015.core.d.ts",
542
+ "compiler/lib.es2015.d.ts",
543
+ "compiler/lib.es2015.generator.d.ts",
544
+ "compiler/lib.es2015.iterable.d.ts",
545
+ "compiler/lib.es2015.promise.d.ts",
546
+ "compiler/lib.es2015.proxy.d.ts",
547
+ "compiler/lib.es2015.reflect.d.ts",
548
+ "compiler/lib.es2015.symbol.d.ts",
549
+ "compiler/lib.es2015.symbol.wellknown.d.ts",
550
+ "compiler/lib.es2016.array.include.d.ts",
551
+ "compiler/lib.es2016.d.ts",
552
+ "compiler/lib.es2016.full.d.ts",
553
+ "compiler/lib.es2017.d.ts",
554
+ "compiler/lib.es2017.full.d.ts",
555
+ "compiler/lib.es2017.intl.d.ts",
556
+ "compiler/lib.es2017.object.d.ts",
557
+ "compiler/lib.es2017.sharedmemory.d.ts",
558
+ "compiler/lib.es2017.string.d.ts",
559
+ "compiler/lib.es2017.typedarrays.d.ts",
560
+ "compiler/lib.es2018.asyncgenerator.d.ts",
561
+ "compiler/lib.es2018.asynciterable.d.ts",
562
+ "compiler/lib.es2018.d.ts",
563
+ "compiler/lib.es2018.full.d.ts",
564
+ "compiler/lib.es2018.intl.d.ts",
565
+ "compiler/lib.es2018.promise.d.ts",
566
+ "compiler/lib.es2018.regexp.d.ts",
567
+ "compiler/lib.es2019.array.d.ts",
568
+ "compiler/lib.es2019.d.ts",
569
+ "compiler/lib.es2019.full.d.ts",
570
+ "compiler/lib.es2019.object.d.ts",
571
+ "compiler/lib.es2019.string.d.ts",
572
+ "compiler/lib.es2019.symbol.d.ts",
573
+ "compiler/lib.es2020.bigint.d.ts",
574
+ "compiler/lib.es2020.d.ts",
575
+ "compiler/lib.es2020.full.d.ts",
576
+ "compiler/lib.es2020.intl.d.ts",
577
+ "compiler/lib.es2020.promise.d.ts",
578
+ "compiler/lib.es2020.sharedmemory.d.ts",
579
+ "compiler/lib.es2020.string.d.ts",
580
+ "compiler/lib.es2020.symbol.wellknown.d.ts",
581
+ "compiler/lib.es2021.d.ts",
582
+ "compiler/lib.es2021.full.d.ts",
583
+ "compiler/lib.es2021.intl.d.ts",
584
+ "compiler/lib.es2021.promise.d.ts",
585
+ "compiler/lib.es2021.string.d.ts",
586
+ "compiler/lib.es2021.weakref.d.ts",
587
+ "compiler/lib.es5.d.ts",
588
+ "compiler/lib.es6.d.ts",
589
+ "compiler/lib.esnext.d.ts",
590
+ "compiler/lib.esnext.full.d.ts",
591
+ "compiler/lib.esnext.intl.d.ts",
592
+ "compiler/lib.esnext.promise.d.ts",
593
+ "compiler/lib.esnext.string.d.ts",
594
+ "compiler/lib.esnext.weakref.d.ts",
595
+ "compiler/lib.scripthost.d.ts",
596
+ "compiler/lib.webworker.d.ts",
597
+ "compiler/lib.webworker.importscripts.d.ts",
598
+ "compiler/lib.webworker.iterable.d.ts",
599
+ "internal/index.d.ts",
600
+ "internal/index.js",
601
+ "internal/package.json",
602
+ "internal/rindo-ext-modules.d.ts",
603
+ "internal/rindo-private.d.ts",
604
+ "internal/rindo-public-compiler.d.ts",
605
+ "internal/rindo-public-docs.d.ts",
606
+ "internal/rindo-public-runtime.d.ts",
607
+ "mock-doc/index.js",
608
+ "mock-doc/package.json",
609
+ "internal/client/css-shim.js",
610
+ "internal/client/dom.js",
611
+ "internal/client/index.js",
612
+ "internal/client/package.json",
613
+ "internal/client/patch-browser.js",
614
+ "internal/client/patch-esm.js",
615
+ "internal/client/shadow-css.js",
616
+ "internal/hydrate/index.js",
617
+ "internal/hydrate/package.json",
618
+ "internal/hydrate/runner.js",
619
+ "internal/hydrate/shadow-css.js",
620
+ "internal/rindo-core/index.d.ts",
621
+ "internal/rindo-core/index.js"
622
+ ]
623
+ },
624
+ {
625
+ name: "rollup",
626
+ version: "2.42.3",
627
+ main: "dist/es/rollup.browser.js"
628
+ },
629
+ {
630
+ name: "terser",
631
+ version: "5.6.1",
632
+ main: "dist/bundle.min.js"
633
+ },
634
+ {
635
+ name: "typescript",
636
+ version: "4.5.4",
637
+ main: "lib/typescript.js"
638
+ }
639
+ ];
640
+
641
+ const findConfig = async (opts) => {
642
+ const sys = opts.sys;
643
+ const cwd = sys.getCurrentDirectory();
644
+ const results = {
645
+ configPath: null,
646
+ rootDir: normalizePath(cwd),
647
+ diagnostics: [],
648
+ };
649
+ let configPath = opts.configPath;
650
+ if (isString(configPath)) {
651
+ if (!sys.platformPath.isAbsolute(configPath)) {
652
+ // passed in a custom rindo config location
653
+ // but it's relative, so prefix the cwd
654
+ configPath = normalizePath(sys.platformPath.join(cwd, configPath));
655
+ }
656
+ else {
657
+ // config path already an absolute path, we're good here
658
+ configPath = normalizePath(opts.configPath);
659
+ }
660
+ }
661
+ else {
662
+ // nothing was passed in, use the current working directory
663
+ configPath = results.rootDir;
664
+ }
665
+ const stat = await sys.stat(configPath);
666
+ if (stat.error) {
667
+ const diagnostic = buildError(results.diagnostics);
668
+ diagnostic.absFilePath = configPath;
669
+ diagnostic.header = `Invalid config path`;
670
+ diagnostic.messageText = `Config path "${configPath}" not found`;
671
+ return results;
672
+ }
673
+ if (stat.isFile) {
674
+ results.configPath = configPath;
675
+ results.rootDir = sys.platformPath.dirname(configPath);
676
+ }
677
+ else if (stat.isDirectory) {
678
+ // this is only a directory, so let's make some assumptions
679
+ for (const configName of ['rindo.config.ts', 'rindo.config.js']) {
680
+ const testConfigFilePath = sys.platformPath.join(configPath, configName);
681
+ const stat = await sys.stat(testConfigFilePath);
682
+ if (stat.isFile) {
683
+ results.configPath = testConfigFilePath;
684
+ results.rootDir = sys.platformPath.dirname(testConfigFilePath);
685
+ break;
686
+ }
687
+ }
688
+ }
689
+ return results;
690
+ };
691
+
692
+ const loadCoreCompiler = async (sys) => {
693
+ await sys.dynamicImport(sys.getCompilerExecutingPath());
694
+ return globalThis.rindo;
695
+ };
696
+
697
+ const startupLog = (logger, task) => {
698
+ if (task === 'info' || task === 'serve' || task === 'version') {
699
+ return;
700
+ }
701
+ logger.info(logger.cyan(`@rindo/core`));
702
+ };
703
+ const startupLogVersion = (logger, task, coreCompiler) => {
704
+ if (task === 'info' || task === 'serve' || task === 'version') {
705
+ return;
706
+ }
707
+ const isDevBuild = coreCompiler.version.includes('-dev.');
708
+ let startupMsg;
709
+ if (isDevBuild) {
710
+ startupMsg = logger.yellow('[LOCAL DEV]');
711
+ }
712
+ else {
713
+ startupMsg = logger.cyan(`v${coreCompiler.version}`);
714
+ }
715
+ startupMsg += logger.emoji(' ' + coreCompiler.vermoji);
716
+ logger.info(startupMsg);
717
+ };
718
+ const loadedCompilerLog = (sys, logger, flags, coreCompiler) => {
719
+ const sysDetails = sys.details;
720
+ const runtimeInfo = `${sys.name} ${sys.version}`;
721
+ const platformInfo = `${sysDetails.platform}, ${sysDetails.cpuModel}`;
722
+ const statsInfo = `cpus: ${sys.hardwareConcurrency}, freemem: ${Math.round(sysDetails.freemem() / 1000000)}MB, totalmem: ${Math.round(sysDetails.totalmem / 1000000)}MB`;
723
+ if (logger.getLevel() === 'debug') {
724
+ logger.debug(runtimeInfo);
725
+ logger.debug(platformInfo);
726
+ logger.debug(statsInfo);
727
+ logger.debug(`compiler: ${sys.getCompilerExecutingPath()}`);
728
+ logger.debug(`build: ${coreCompiler.buildId}`);
729
+ }
730
+ else if (flags.ci) {
731
+ logger.info(runtimeInfo);
732
+ logger.info(platformInfo);
733
+ logger.info(statsInfo);
734
+ }
735
+ };
736
+ const startupCompilerLog = (coreCompiler, config) => {
737
+ if (config.suppressLogs === true) {
738
+ return;
739
+ }
740
+ const { logger } = config;
741
+ const isDebug = logger.getLevel() === 'debug';
742
+ const isPrerelease = coreCompiler.version.includes('-');
743
+ const isDevBuild = coreCompiler.version.includes('-dev.');
744
+ if (isPrerelease && !isDevBuild) {
745
+ logger.warn(logger.yellow(`This is a prerelease build, undocumented changes might happen at any time. Technical support is not available for prereleases, but any assistance testing is appreciated.`));
746
+ }
747
+ if (config.devMode && !isDebug) {
748
+ if (config.buildEs5) {
749
+ logger.warn(`Generating ES5 during development is a very task expensive, initial and incremental builds will be much slower. Drop the '--es5' flag and use a modern browser for development.`);
750
+ }
751
+ if (!config.enableCache) {
752
+ logger.warn(`Disabling cache during development will slow down incremental builds.`);
753
+ }
754
+ }
755
+ };
756
+
757
+ const taskPrerender = async (coreCompiler, config) => {
758
+ startupCompilerLog(coreCompiler, config);
759
+ const hydrateAppFilePath = config.flags.unknownArgs[0];
760
+ if (typeof hydrateAppFilePath !== 'string') {
761
+ config.logger.error(`Missing hydrate app script path`);
762
+ return config.sys.exit(1);
763
+ }
764
+ const srcIndexHtmlPath = config.srcIndexHtml;
765
+ const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, null, srcIndexHtmlPath);
766
+ config.logger.printDiagnostics(diagnostics);
767
+ if (diagnostics.some((d) => d.level === 'error')) {
768
+ return config.sys.exit(1);
769
+ }
770
+ };
771
+ const runPrerenderTask = async (coreCompiler, config, hydrateAppFilePath, componentGraph, srcIndexHtmlPath) => {
772
+ const diagnostics = [];
773
+ try {
774
+ const prerenderer = await coreCompiler.createPrerenderer(config);
775
+ const results = await prerenderer.start({
776
+ hydrateAppFilePath,
777
+ componentGraph,
778
+ srcIndexHtmlPath,
779
+ });
780
+ diagnostics.push(...results.diagnostics);
781
+ }
782
+ catch (e) {
783
+ catchError(diagnostics, e);
784
+ }
785
+ return diagnostics;
786
+ };
787
+
788
+ const startCheckVersion = async (config, currentVersion) => {
789
+ if (config.devMode && !config.flags.ci && !currentVersion.includes('-dev.') && isFunction(config.sys.checkVersion)) {
790
+ return config.sys.checkVersion(config.logger, currentVersion);
791
+ }
792
+ return null;
793
+ };
794
+ const printCheckVersionResults = async (versionChecker) => {
795
+ if (versionChecker) {
796
+ const checkVersionResults = await versionChecker;
797
+ if (isFunction(checkVersionResults)) {
798
+ checkVersionResults();
799
+ }
800
+ }
801
+ };
802
+
803
+ const taskWatch = async (coreCompiler, config) => {
804
+ let devServer = null;
805
+ let exitCode = 0;
806
+ try {
807
+ startupCompilerLog(coreCompiler, config);
808
+ const versionChecker = startCheckVersion(config, coreCompiler.version);
809
+ const compiler = await coreCompiler.createCompiler(config);
810
+ const watcher = await compiler.createWatcher();
811
+ if (config.flags.serve) {
812
+ const devServerPath = config.sys.getDevServerExecutingPath();
813
+ const { start } = await config.sys.dynamicImport(devServerPath);
814
+ devServer = await start(config.devServer, config.logger, watcher);
815
+ }
816
+ config.sys.onProcessInterrupt(() => {
817
+ config.logger.debug(`close watch`);
818
+ compiler && compiler.destroy();
819
+ });
820
+ const rmVersionCheckerLog = watcher.on('buildFinish', async () => {
821
+ // log the version check one time
822
+ rmVersionCheckerLog();
823
+ printCheckVersionResults(versionChecker);
824
+ });
825
+ if (devServer) {
826
+ const rmDevServerLog = watcher.on('buildFinish', () => {
827
+ // log the dev server url one time
828
+ rmDevServerLog();
829
+ config.logger.info(`${config.logger.cyan(devServer.browserUrl)}\n`);
830
+ });
831
+ }
832
+ const closeResults = await watcher.start();
833
+ if (closeResults.exitCode > 0) {
834
+ exitCode = closeResults.exitCode;
835
+ }
836
+ }
837
+ catch (e) {
838
+ exitCode = 1;
839
+ config.logger.error(e);
840
+ }
841
+ if (devServer) {
842
+ await devServer.close();
843
+ }
844
+ if (exitCode > 0) {
845
+ return config.sys.exit(exitCode);
846
+ }
847
+ };
848
+
849
+ const tryFn = async (fn, ...args) => {
850
+ try {
851
+ return await fn(...args);
852
+ }
853
+ catch (_a) {
854
+ // ignore
855
+ }
856
+ return null;
857
+ };
858
+ const isInteractive = (sys, config, object) => {
859
+ var _a;
860
+ const terminalInfo = object ||
861
+ Object.freeze({
862
+ tty: sys.isTTY() ? true : false,
863
+ ci: ['CI', 'BUILD_ID', 'BUILD_NUMBER', 'BITBUCKET_COMMIT', 'CODEBUILD_BUILD_ARN'].filter((v) => !!sys.getEnvironmentVar(v)).length > 0 || !!((_a = config.flags) === null || _a === void 0 ? void 0 : _a.ci),
864
+ });
865
+ return terminalInfo.tty && !terminalInfo.ci;
866
+ };
867
+ const UUID_REGEX = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
868
+ function uuidv4() {
869
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
870
+ const r = (Math.random() * 16) | 0;
871
+ const v = c == 'x' ? r : (r & 0x3) | 0x8;
872
+ return v.toString(16);
873
+ });
874
+ }
875
+ /**
876
+ * Reads and parses a JSON file from the given `path`
877
+ * @param sys The system where the command is invoked
878
+ * @param path the path on the file system to read and parse
879
+ * @returns the parsed JSON
880
+ */
881
+ async function readJson(sys, path) {
882
+ const file = await sys.readFile(path);
883
+ return !!file && JSON.parse(file);
884
+ }
885
+ /**
886
+ * Does the command have the debug flag?
887
+ * @param config The config passed into the Rindo command
888
+ * @returns true if --debug has been passed, otherwise false
889
+ */
890
+ function hasDebug(config) {
891
+ return config.flags.debug;
892
+ }
893
+ /**
894
+ * Does the command have the verbose and debug flags?
895
+ * @param config The config passed into the Rindo command
896
+ * @returns true if both --debug and --verbose have been passed, otherwise false
897
+ */
898
+ function hasVerbose(config) {
899
+ return config.flags.verbose && hasDebug(config);
900
+ }
901
+
902
+ /**
903
+ * Used to determine if tracking should occur.
904
+ * @param config The config passed into the Rindo command
905
+ * @param sys The system where the command is invoked
906
+ * @param ci whether or not the process is running in a Continuous Integration (CI) environment
907
+ * @returns true if telemetry should be sent, false otherwise
908
+ */
909
+ async function shouldTrack(config, sys, ci) {
910
+ return !ci && isInteractive(sys, config) && (await checkTelemetry(sys));
911
+ }
912
+
913
+ const isTest$1 = () => process.env.JEST_WORKER_ID !== undefined;
914
+ const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.navify/${isTest$1() ? 'tmp-config.json' : 'config.json'}`);
915
+ const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.navify`);
916
+ /**
917
+ * Reads an Navify configuration file from disk, parses it, and performs any necessary corrections to it if certain
918
+ * values are deemed to be malformed
919
+ * @param sys The system where the command is invoked
920
+ * @returns the config read from disk that has been potentially been updated
921
+ */
922
+ async function readConfig(sys) {
923
+ let config = await readJson(sys, defaultConfig(sys));
924
+ if (!config) {
925
+ config = {
926
+ 'tokens.telemetry': uuidv4(),
927
+ 'telemetry.rindo': true,
928
+ };
929
+ await writeConfig(sys, config);
930
+ }
931
+ else if (!UUID_REGEX.test(config['tokens.telemetry'])) {
932
+ const newUuid = uuidv4();
933
+ await writeConfig(sys, { ...config, 'tokens.telemetry': newUuid });
934
+ config['tokens.telemetry'] = newUuid;
935
+ }
936
+ return config;
937
+ }
938
+ /**
939
+ * Writes an Navify configuration file to disk.
940
+ * @param sys The system where the command is invoked
941
+ * @param config The config passed into the Rindo command
942
+ * @returns boolean If the command was successful
943
+ */
944
+ async function writeConfig(sys, config) {
945
+ let result = false;
946
+ try {
947
+ await sys.createDir(defaultConfigDirectory(sys), { recursive: true });
948
+ await sys.writeFile(defaultConfig(sys), JSON.stringify(config, null, 2));
949
+ result = true;
950
+ }
951
+ catch (error) {
952
+ console.error(`Rindo Telemetry: couldn't write configuration file to ${defaultConfig(sys)} - ${error}.`);
953
+ }
954
+ return result;
955
+ }
956
+ /**
957
+ * Update a subset of the Navify config.
958
+ * @param sys The system where the command is invoked
959
+ * @param newOptions The new options to save
960
+ * @returns boolean If the command was successful
961
+ */
962
+ async function updateConfig(sys, newOptions) {
963
+ const config = await readConfig(sys);
964
+ return await writeConfig(sys, Object.assign(config, newOptions));
965
+ }
966
+
967
+ const isOutputTargetDocs = (o) => o.type === DOCS_README || o.type === DOCS_JSON || o.type === DOCS_CUSTOM || o.type === DOCS_VSCODE;
968
+ const DOCS_CUSTOM = 'docs-custom';
969
+ const DOCS_JSON = 'docs-json';
970
+ const DOCS_README = 'docs-readme';
971
+ const DOCS_VSCODE = 'docs-vscode';
972
+ const WWW = 'www';
973
+
974
+ /**
975
+ * Used to within taskBuild to provide the component_count property.
976
+ *
977
+ * @param sys The system where the command is invoked
978
+ * @param config The config passed into the Rindo command
979
+ * @param logger The tool used to do logging
980
+ * @param coreCompiler The compiler used to do builds
981
+ * @param result The results of a compiler build.
982
+ */
983
+ async function telemetryBuildFinishedAction(sys, config, logger, coreCompiler, result) {
984
+ const tracking = await shouldTrack(config, sys, config.flags.ci);
985
+ if (!tracking) {
986
+ return;
987
+ }
988
+ const component_count = Object.keys(result.componentGraph).length;
989
+ const data = await prepareData(coreCompiler, config, sys, result.duration, component_count);
990
+ await sendMetric(sys, config, 'rindo_cli_command', data);
991
+ logger.debug(`${logger.blue('Telemetry')}: ${logger.gray(JSON.stringify(data))}`);
992
+ }
993
+ /**
994
+ * A function to wrap a compiler task function around. Will send telemetry if, and only if, the machine allows.
995
+ * @param sys The system where the command is invoked
996
+ * @param config The config passed into the Rindo command
997
+ * @param logger The tool used to do logging
998
+ * @param coreCompiler The compiler used to do builds
999
+ * @param action A Promise-based function to call in order to get the duration of any given command.
1000
+ * @returns void
1001
+ */
1002
+ async function telemetryAction(sys, config, logger, coreCompiler, action) {
1003
+ var _a;
1004
+ const tracking = await shouldTrack(config, sys, !!((_a = config === null || config === void 0 ? void 0 : config.flags) === null || _a === void 0 ? void 0 : _a.ci));
1005
+ let duration = undefined;
1006
+ let error;
1007
+ if (action) {
1008
+ const start = new Date();
1009
+ try {
1010
+ await action();
1011
+ }
1012
+ catch (e) {
1013
+ error = e;
1014
+ }
1015
+ const end = new Date();
1016
+ duration = end.getTime() - start.getTime();
1017
+ }
1018
+ // We'll get componentCount details inside the taskBuild, so let's not send two messages.
1019
+ if (!tracking || (config.flags.task == 'build' && !config.flags.args.includes('--watch'))) {
1020
+ return;
1021
+ }
1022
+ const data = await prepareData(coreCompiler, config, sys, duration);
1023
+ await sendMetric(sys, config, 'rindo_cli_command', data);
1024
+ logger.debug(`${logger.blue('Telemetry')}: ${logger.gray(JSON.stringify(data))}`);
1025
+ if (error) {
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ function hasAppTarget(config) {
1030
+ return config.outputTargets.some((target) => target.type === WWW && (!!target.serviceWorker || (!!target.baseUrl && target.baseUrl !== '/')));
1031
+ }
1032
+ function isUsingYarn(sys) {
1033
+ var _a;
1034
+ return ((_a = sys.getEnvironmentVar('npm_execpath')) === null || _a === void 0 ? void 0 : _a.includes('yarn')) || false;
1035
+ }
1036
+ async function getActiveTargets(config) {
1037
+ const result = config.outputTargets.map((t) => t.type);
1038
+ return Array.from(new Set(result));
1039
+ }
1040
+ const prepareData = async (coreCompiler, config, sys, duration_ms, component_count = undefined) => {
1041
+ const { typescript, rollup } = coreCompiler.versions || { typescript: 'unknown', rollup: 'unknown' };
1042
+ const { packages, packagesNoVersions } = await getInstalledPackages(sys, config);
1043
+ const targets = await getActiveTargets(config);
1044
+ const yarn = isUsingYarn(sys);
1045
+ const rindo = coreCompiler.version || 'unknown';
1046
+ const system = `${sys.name} ${sys.version}`;
1047
+ const os_name = sys.details.platform;
1048
+ const os_version = sys.details.release;
1049
+ const cpu_model = sys.details.cpuModel;
1050
+ const build = coreCompiler.buildId || 'unknown';
1051
+ const has_app_pwa_config = hasAppTarget(config);
1052
+ return {
1053
+ yarn,
1054
+ duration_ms,
1055
+ component_count,
1056
+ targets,
1057
+ packages,
1058
+ packages_no_versions: packagesNoVersions,
1059
+ arguments: config.flags.args,
1060
+ task: config.flags.task,
1061
+ rindo,
1062
+ system,
1063
+ system_major: getMajorVersion(system),
1064
+ os_name,
1065
+ os_version,
1066
+ cpu_model,
1067
+ build,
1068
+ typescript,
1069
+ rollup,
1070
+ has_app_pwa_config,
1071
+ };
1072
+ };
1073
+ /**
1074
+ * Reads package-lock.json, yarn.lock, and package.json files in order to cross reference
1075
+ * the dependencies and devDependencies properties. Pulls up the current installed version
1076
+ * of each package under the @rindo, @navify, and @jigra scopes.
1077
+ * @returns string[]
1078
+ */
1079
+ async function getInstalledPackages(sys, config) {
1080
+ let packages = [];
1081
+ let packagesNoVersions = [];
1082
+ const yarn = isUsingYarn(sys);
1083
+ try {
1084
+ // Read package.json and package-lock.json
1085
+ const appRootDir = sys.getCurrentDirectory();
1086
+ const packageJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + '/package.json'));
1087
+ // They don't have a package.json for some reason? Eject button.
1088
+ if (!packageJson) {
1089
+ return { packages, packagesNoVersions };
1090
+ }
1091
+ const rawPackages = Object.entries({
1092
+ ...packageJson.devDependencies,
1093
+ ...packageJson.dependencies,
1094
+ });
1095
+ // Collect packages only in the rindo, navify, or jigra org's:
1096
+ // https://www.npmjs.com/org/rindo
1097
+ const navifyPackages = rawPackages.filter(([k]) => k.startsWith('@rindo/') || k.startsWith('@navify/') || k.startsWith('@jigra/'));
1098
+ try {
1099
+ packages = yarn ? await yarnPackages(sys, navifyPackages) : await npmPackages(sys, navifyPackages);
1100
+ }
1101
+ catch (e) {
1102
+ packages = navifyPackages.map(([k, v]) => `${k}@${v.replace('^', '')}`);
1103
+ }
1104
+ packagesNoVersions = navifyPackages.map(([k]) => `${k}`);
1105
+ return { packages, packagesNoVersions };
1106
+ }
1107
+ catch (err) {
1108
+ hasDebug(config) && console.error(err);
1109
+ return { packages, packagesNoVersions };
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Visits the npm lock file to find the exact versions that are installed
1114
+ * @param sys The system where the command is invoked
1115
+ * @param navifyPackages a list of the found packages matching `@rindo`, `@jigra`, or `@navify` from the package.json file.
1116
+ * @returns an array of strings of all the packages and their versions.
1117
+ */
1118
+ async function npmPackages(sys, navifyPackages) {
1119
+ const appRootDir = sys.getCurrentDirectory();
1120
+ const packageLockJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + '/package-lock.json'));
1121
+ return navifyPackages.map(([k, v]) => {
1122
+ var _a, _b, _c, _d;
1123
+ let version = (_d = (_b = (_a = packageLockJson === null || packageLockJson === void 0 ? void 0 : packageLockJson.dependencies[k]) === null || _a === void 0 ? void 0 : _a.version) !== null && _b !== void 0 ? _b : (_c = packageLockJson === null || packageLockJson === void 0 ? void 0 : packageLockJson.devDependencies[k]) === null || _c === void 0 ? void 0 : _c.version) !== null && _d !== void 0 ? _d : v;
1124
+ version = version.includes('file:') ? sanitizeDeclaredVersion(v) : version;
1125
+ return `${k}@${version}`;
1126
+ });
1127
+ }
1128
+ /**
1129
+ * Visits the yarn lock file to find the exact versions that are installed
1130
+ * @param sys The system where the command is invoked
1131
+ * @param navifyPackages a list of the found packages matching `@rindo`, `@jigra`, or `@navify` from the package.json file.
1132
+ * @returns an array of strings of all the packages and their versions.
1133
+ */
1134
+ async function yarnPackages(sys, navifyPackages) {
1135
+ const appRootDir = sys.getCurrentDirectory();
1136
+ const yarnLock = sys.readFileSync(sys.resolvePath(appRootDir + '/yarn.lock'));
1137
+ const yarnLockYml = sys.parseYarnLockFile(yarnLock);
1138
+ return navifyPackages.map(([k, v]) => {
1139
+ var _a;
1140
+ const identifiedVersion = `${k}@${v}`;
1141
+ let version = (_a = yarnLockYml.object[identifiedVersion]) === null || _a === void 0 ? void 0 : _a.version;
1142
+ version = version.includes('undefined') ? sanitizeDeclaredVersion(identifiedVersion) : version;
1143
+ return `${k}@${version}`;
1144
+ });
1145
+ }
1146
+ /**
1147
+ * This function is used for fallback purposes, where an npm or yarn lock file doesn't exist in the consumers directory.
1148
+ * This will strip away '*', '^' and '~' from the declared package versions in a package.json.
1149
+ * @param version the raw semver pattern identifier version string
1150
+ * @returns a cleaned up representation without any qualifiers
1151
+ */
1152
+ function sanitizeDeclaredVersion(version) {
1153
+ return version.replace(/[*^~]/g, '');
1154
+ }
1155
+ /**
1156
+ * If telemetry is enabled, send a metric via IPC to a forked process for uploading.
1157
+ */
1158
+ async function sendMetric(sys, config, name, value) {
1159
+ const session_id = await getTelemetryToken(sys);
1160
+ const message = {
1161
+ name,
1162
+ timestamp: new Date().toISOString(),
1163
+ source: 'rindo_cli',
1164
+ value,
1165
+ session_id,
1166
+ };
1167
+ await sendTelemetry(sys, config, { type: 'telemetry', message });
1168
+ }
1169
+ /**
1170
+ * Used to read the config file's tokens.telemetry property.
1171
+ * @param sys The system where the command is invoked
1172
+ * @returns string
1173
+ */
1174
+ async function getTelemetryToken(sys) {
1175
+ const config = await readConfig(sys);
1176
+ if (config['tokens.telemetry'] === undefined) {
1177
+ config['tokens.telemetry'] = uuidv4();
1178
+ await writeConfig(sys, config);
1179
+ }
1180
+ return config['tokens.telemetry'];
1181
+ }
1182
+ /**
1183
+ * Issues a request to the telemetry server.
1184
+ * @param sys The system where the command is invoked
1185
+ * @param config The config passed into the Rindo command
1186
+ * @param data Data to be tracked
1187
+ */
1188
+ async function sendTelemetry(sys, config, data) {
1189
+ try {
1190
+ const now = new Date().toISOString();
1191
+ const body = {
1192
+ metrics: [data.message],
1193
+ sent_at: now,
1194
+ };
1195
+ // This request is only made if telemetry is on.
1196
+ const response = await sys.fetch('https://api-navifyjs.web.app/events/metrics', {
1197
+ method: 'POST',
1198
+ headers: {
1199
+ 'Content-Type': 'application/json',
1200
+ },
1201
+ body: JSON.stringify(body),
1202
+ });
1203
+ hasVerbose(config) &&
1204
+ console.debug('\nSent %O metric to events service (status: %O)', data.message.name, response.status, '\n');
1205
+ if (response.status !== 204) {
1206
+ hasVerbose(config) &&
1207
+ console.debug('\nBad response from events service. Request body: %O', response.body.toString(), '\n');
1208
+ }
1209
+ }
1210
+ catch (e) {
1211
+ hasVerbose(config) && console.debug('Telemetry request failed:', e);
1212
+ }
1213
+ }
1214
+ /**
1215
+ * Checks if telemetry is enabled on this machine
1216
+ * @param sys The system where the command is invoked
1217
+ * @returns true if telemetry is enabled, false otherwise
1218
+ */
1219
+ async function checkTelemetry(sys) {
1220
+ const config = await readConfig(sys);
1221
+ if (config['telemetry.rindo'] === undefined) {
1222
+ config['telemetry.rindo'] = true;
1223
+ await writeConfig(sys, config);
1224
+ }
1225
+ return config['telemetry.rindo'];
1226
+ }
1227
+ /**
1228
+ * Writes to the config file, enabling telemetry for this machine.
1229
+ * @param sys The system where the command is invoked
1230
+ * @returns true if writing the file was successful, false otherwise
1231
+ */
1232
+ async function enableTelemetry(sys) {
1233
+ return await updateConfig(sys, { 'telemetry.rindo': true });
1234
+ }
1235
+ /**
1236
+ * Writes to the config file, disabling telemetry for this machine.
1237
+ * @param sys The system where the command is invoked
1238
+ * @returns true if writing the file was successful, false otherwise
1239
+ */
1240
+ async function disableTelemetry(sys) {
1241
+ return await updateConfig(sys, { 'telemetry.rindo': false });
1242
+ }
1243
+ /**
1244
+ * Takes in a semver string in order to return the major version.
1245
+ * @param version The fully qualified semver version
1246
+ * @returns a string of the major version
1247
+ */
1248
+ function getMajorVersion(version) {
1249
+ const parts = version.split('.');
1250
+ return parts[0];
1251
+ }
1252
+
1253
+ const taskBuild = async (coreCompiler, config, sys) => {
1254
+ if (config.flags.watch) {
1255
+ // watch build
1256
+ await taskWatch(coreCompiler, config);
1257
+ return;
1258
+ }
1259
+ // one-time build
1260
+ let exitCode = 0;
1261
+ try {
1262
+ startupCompilerLog(coreCompiler, config);
1263
+ const versionChecker = startCheckVersion(config, coreCompiler.version);
1264
+ const compiler = await coreCompiler.createCompiler(config);
1265
+ const results = await compiler.build();
1266
+ // TODO: make this parameter no longer optional, remove the surrounding if statement
1267
+ if (sys) {
1268
+ await telemetryBuildFinishedAction(sys, config, config.logger, coreCompiler, results);
1269
+ }
1270
+ await compiler.destroy();
1271
+ if (results.hasError) {
1272
+ exitCode = 1;
1273
+ }
1274
+ else if (config.flags.prerender) {
1275
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.hydrateAppFilePath, results.componentGraph, null);
1276
+ config.logger.printDiagnostics(prerenderDiagnostics);
1277
+ if (prerenderDiagnostics.some((d) => d.level === 'error')) {
1278
+ exitCode = 1;
1279
+ }
1280
+ }
1281
+ await printCheckVersionResults(versionChecker);
1282
+ }
1283
+ catch (e) {
1284
+ exitCode = 1;
1285
+ config.logger.error(e);
1286
+ }
1287
+ if (exitCode > 0) {
1288
+ return config.sys.exit(exitCode);
1289
+ }
1290
+ };
1291
+
1292
+ const taskDocs = async (coreCompiler, config) => {
1293
+ config.devServer = null;
1294
+ config.outputTargets = config.outputTargets.filter(isOutputTargetDocs);
1295
+ config.devMode = true;
1296
+ startupCompilerLog(coreCompiler, config);
1297
+ const compiler = await coreCompiler.createCompiler(config);
1298
+ await compiler.build();
1299
+ await compiler.destroy();
1300
+ };
1301
+
1302
+ const IS_NODE_ENV = typeof global !== 'undefined' &&
1303
+ typeof require === 'function' &&
1304
+ !!global.process &&
1305
+ typeof __filename === 'string' &&
1306
+ (!global.origin || typeof global.origin !== 'string');
1307
+
1308
+ /**
1309
+ * Task to generate component boilerplate and write it to disk. This task can
1310
+ * cause the program to exit with an error under various circumstances, such as
1311
+ * being called in an inappropriate place, being asked to overwrite files that
1312
+ * already exist, etc.
1313
+ *
1314
+ * @param coreCompiler the CoreCompiler we're using currently, here we're
1315
+ * mainly accessing the `path` module
1316
+ * @param config the user-supplied config, which we need here to access `.sys`.
1317
+ */
1318
+ const taskGenerate = async (coreCompiler, config) => {
1319
+ if (!IS_NODE_ENV) {
1320
+ config.logger.error(`"generate" command is currently only implemented for a NodeJS environment`);
1321
+ return config.sys.exit(1);
1322
+ }
1323
+ const path = coreCompiler.path;
1324
+ if (!config.configPath) {
1325
+ config.logger.error('Please run this command in your root directory (i. e. the one containing rindo.config.ts).');
1326
+ return config.sys.exit(1);
1327
+ }
1328
+ const absoluteSrcDir = config.srcDir;
1329
+ if (!absoluteSrcDir) {
1330
+ config.logger.error(`Rindo's srcDir was not specified.`);
1331
+ return config.sys.exit(1);
1332
+ }
1333
+ const { prompt } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('../sys/node/prompts.js')); });
1334
+ const input = config.flags.unknownArgs.find((arg) => !arg.startsWith('-')) ||
1335
+ (await prompt({ name: 'tagName', type: 'text', message: 'Component tag name (dash-case):' })).tagName;
1336
+ const { dir, base: componentName } = path.parse(input);
1337
+ const tagError = validateComponentTag(componentName);
1338
+ if (tagError) {
1339
+ config.logger.error(tagError);
1340
+ return config.sys.exit(1);
1341
+ }
1342
+ const extensionsToGenerate = ['tsx', ...(await chooseFilesToGenerate())];
1343
+ const testFolder = extensionsToGenerate.some(isTest) ? 'test' : '';
1344
+ const outDir = path.join(absoluteSrcDir, 'components', dir, componentName);
1345
+ await config.sys.createDir(path.join(outDir, testFolder), { recursive: true });
1346
+ const filesToGenerate = extensionsToGenerate.map((extension) => ({
1347
+ extension,
1348
+ path: getFilepathForFile(coreCompiler, outDir, componentName, extension),
1349
+ }));
1350
+ await checkForOverwrite(filesToGenerate, config);
1351
+ const writtenFiles = await Promise.all(filesToGenerate.map((file) => getBoilerplateAndWriteFile(config, componentName, extensionsToGenerate.includes('css'), file))).catch((error) => config.logger.error(error));
1352
+ if (!writtenFiles) {
1353
+ return config.sys.exit(1);
1354
+ }
1355
+ // TODO: Investigate moving these console.log calls to config.logger.info
1356
+ console.log();
1357
+ console.log(`${config.logger.gray('$')} rindo generate ${input}`);
1358
+ console.log();
1359
+ console.log(config.logger.bold('The following files have been generated:'));
1360
+ const absoluteRootDir = config.rootDir;
1361
+ writtenFiles.map((file) => console.log(` - ${path.relative(absoluteRootDir, file)}`));
1362
+ };
1363
+ /**
1364
+ * Show a checkbox prompt to select the files to be generated.
1365
+ *
1366
+ * @returns a read-only array of `GenerableExtension`, the extensions that the user has decided
1367
+ * to generate
1368
+ */
1369
+ const chooseFilesToGenerate = async () => {
1370
+ const { prompt } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('../sys/node/prompts.js')); });
1371
+ return (await prompt({
1372
+ name: 'filesToGenerate',
1373
+ type: 'multiselect',
1374
+ message: 'Which additional files do you want to generate?',
1375
+ choices: [
1376
+ { value: 'css', title: 'Stylesheet (.css)', selected: true },
1377
+ { value: 'spec.tsx', title: 'Spec Test (.spec.tsx)', selected: true },
1378
+ { value: 'e2e.ts', title: 'E2E Test (.e2e.ts)', selected: true },
1379
+ ],
1380
+ })).filesToGenerate;
1381
+ };
1382
+ /**
1383
+ * Get a filepath for a file we want to generate!
1384
+ *
1385
+ * The filepath for a given file depends on the path, the user-supplied
1386
+ * component name, the extension, and whether we're inside of a test directory.
1387
+ *
1388
+ * @param coreCompiler the compiler we're using, here to acces the `.path` module
1389
+ * @param path path to where we're going to generate the component
1390
+ * @param componentName the user-supplied name for the generated component
1391
+ * @param extension the file extension
1392
+ * @returns the full filepath to the component (with a possible `test` directory
1393
+ * added)
1394
+ */
1395
+ const getFilepathForFile = (coreCompiler, path, componentName, extension) => isTest(extension)
1396
+ ? coreCompiler.path.join(path, 'test', `${componentName}.${extension}`)
1397
+ : coreCompiler.path.join(path, `${componentName}.${extension}`);
1398
+ /**
1399
+ * Get the boilerplate for a file and write it to disk
1400
+ *
1401
+ * @param config the current config, needed for file operations
1402
+ * @param componentName the component name (user-supplied)
1403
+ * @param withCss are we generating CSS?
1404
+ * @param file the file we want to write
1405
+ * @returns a `Promise<string>` which holds the full filepath we've written to,
1406
+ * used to print out a little summary of our activity to the user.
1407
+ */
1408
+ const getBoilerplateAndWriteFile = async (config, componentName, withCss, file) => {
1409
+ const boilerplate = getBoilerplateByExtension(componentName, file.extension, withCss);
1410
+ await config.sys.writeFile(file.path, boilerplate);
1411
+ return file.path;
1412
+ };
1413
+ /**
1414
+ * Check to see if any of the files we plan to write already exist and would
1415
+ * therefore be overwritten if we proceed, because we'd like to not overwrite
1416
+ * people's code!
1417
+ *
1418
+ * This function will check all the filepaths and if it finds any files log an
1419
+ * error and exit with an error code. If it doesn't find anything it will just
1420
+ * peacefully return `Promise<void>`.
1421
+ *
1422
+ * @param files the files we want to check
1423
+ * @param config the Config object, used here to get access to `sys.readFile`
1424
+ */
1425
+ const checkForOverwrite = async (files, config) => {
1426
+ const alreadyPresent = [];
1427
+ await Promise.all(files.map(async ({ path }) => {
1428
+ if ((await config.sys.readFile(path)) !== undefined) {
1429
+ alreadyPresent.push(path);
1430
+ }
1431
+ }));
1432
+ if (alreadyPresent.length > 0) {
1433
+ config.logger.error('Generating code would overwrite the following files:', ...alreadyPresent.map((path) => '\t' + path));
1434
+ await config.sys.exit(1);
1435
+ }
1436
+ };
1437
+ /**
1438
+ * Check if an extension is for a test
1439
+ *
1440
+ * @param extension the extension we want to check
1441
+ * @returns a boolean indicating whether or not its a test
1442
+ */
1443
+ const isTest = (extension) => {
1444
+ return extension === 'e2e.ts' || extension === 'spec.tsx';
1445
+ };
1446
+ /**
1447
+ * Get the boilerplate for a file by its extension.
1448
+ *
1449
+ * @param tagName the name of the component we're generating
1450
+ * @param extension the file extension we want boilerplate for (.css, tsx, etc)
1451
+ * @param withCss a boolean indicating whether we're generating a CSS file
1452
+ * @returns a string container the file boilerplate for the supplied extension
1453
+ */
1454
+ const getBoilerplateByExtension = (tagName, extension, withCss) => {
1455
+ switch (extension) {
1456
+ case 'tsx':
1457
+ return getComponentBoilerplate(tagName, withCss);
1458
+ case 'css':
1459
+ return getStyleUrlBoilerplate();
1460
+ case 'spec.tsx':
1461
+ return getSpecTestBoilerplate(tagName);
1462
+ case 'e2e.ts':
1463
+ return getE2eTestBoilerplate(tagName);
1464
+ default:
1465
+ throw new Error(`Unkown extension "${extension}".`);
1466
+ }
1467
+ };
1468
+ /**
1469
+ * Get the boilerplate for a component.
1470
+ */
1471
+ const getComponentBoilerplate = (tagName, hasStyle) => {
1472
+ const decorator = [`{`];
1473
+ decorator.push(` tag: '${tagName}',`);
1474
+ if (hasStyle) {
1475
+ decorator.push(` styleUrl: '${tagName}.css',`);
1476
+ }
1477
+ decorator.push(` shadow: true,`);
1478
+ decorator.push(`}`);
1479
+ return `import { Component, Host, h } from '@rindo/core';
1480
+
1481
+ @Component(${decorator.join('\n')})
1482
+ export class ${toPascalCase(tagName)} {
1483
+
1484
+ render() {
1485
+ return (
1486
+ <Host>
1487
+ <slot></slot>
1488
+ </Host>
1489
+ );
1490
+ }
1491
+
1492
+ }
1493
+ `;
1494
+ };
1495
+ /**
1496
+ * Get the boilerplate for style.
1497
+ */
1498
+ const getStyleUrlBoilerplate = () => `:host {
1499
+ display: block;
1500
+ }
1501
+ `;
1502
+ /**
1503
+ * Get the boilerplate for a spec test.
1504
+ */
1505
+ const getSpecTestBoilerplate = (tagName) => `import { newSpecPage } from '@rindo/core/testing';
1506
+ import { ${toPascalCase(tagName)} } from '../${tagName}';
1507
+
1508
+ describe('${tagName}', () => {
1509
+ it('renders', async () => {
1510
+ const page = await newSpecPage({
1511
+ components: [${toPascalCase(tagName)}],
1512
+ html: \`<${tagName}></${tagName}>\`,
1513
+ });
1514
+ expect(page.root).toEqualHtml(\`
1515
+ <${tagName}>
1516
+ <mock:shadow-root>
1517
+ <slot></slot>
1518
+ </mock:shadow-root>
1519
+ </${tagName}>
1520
+ \`);
1521
+ });
1522
+ });
1523
+ `;
1524
+ /**
1525
+ * Get the boilerplate for an E2E test.
1526
+ */
1527
+ const getE2eTestBoilerplate = (name) => `import { newE2EPage } from '@rindo/core/testing';
1528
+
1529
+ describe('${name}', () => {
1530
+ it('renders', async () => {
1531
+ const page = await newE2EPage();
1532
+ await page.setContent('<${name}></${name}>');
1533
+
1534
+ const element = await page.find('${name}');
1535
+ expect(element).toHaveClass('hydrated');
1536
+ });
1537
+ });
1538
+ `;
1539
+ /**
1540
+ * Convert a dash case string to pascal case.
1541
+ */
1542
+ const toPascalCase = (str) => str.split('-').reduce((res, part) => res + part[0].toUpperCase() + part.slice(1), '');
1543
+
1544
+ const taskTelemetry = async (config, sys, logger) => {
1545
+ const prompt = logger.dim(sys.details.platform === 'windows' ? '>' : '$');
1546
+ const isEnabling = config.flags.args.includes('on');
1547
+ const isDisabling = config.flags.args.includes('off');
1548
+ const INFORMATION = `Opt in or our of telemetry. Information about the data we collect is available on our website: ${logger.bold('https://rindojs.web.app/telemetry')}`;
1549
+ const THANK_YOU = `Thank you for helping to make Rindo better! 💖`;
1550
+ const ENABLED_MESSAGE = `${logger.green('Enabled')}. ${THANK_YOU}\n\n`;
1551
+ const DISABLED_MESSAGE = `${logger.red('Disabled')}\n\n`;
1552
+ const hasTelemetry = await checkTelemetry(sys);
1553
+ if (isEnabling) {
1554
+ const result = await enableTelemetry(sys);
1555
+ result
1556
+ ? console.log(`\n ${logger.bold('Telemetry is now ') + ENABLED_MESSAGE}`)
1557
+ : console.log(`Something went wrong when enabling Telemetry.`);
1558
+ return;
1559
+ }
1560
+ if (isDisabling) {
1561
+ const result = await disableTelemetry(sys);
1562
+ result
1563
+ ? console.log(`\n ${logger.bold('Telemetry is now ') + DISABLED_MESSAGE}`)
1564
+ : console.log(`Something went wrong when disabling Telemetry.`);
1565
+ return;
1566
+ }
1567
+ console.log(` ${logger.bold('Telemetry:')} ${logger.dim(INFORMATION)}`);
1568
+ console.log(`\n ${logger.bold('Status')}: ${hasTelemetry ? ENABLED_MESSAGE : DISABLED_MESSAGE}`);
1569
+ console.log(` ${prompt} ${logger.green('rindo telemetry [off|on]')}
1570
+
1571
+ ${logger.cyan('off')} ${logger.dim('.............')} Disable sharing anonymous usage data
1572
+ ${logger.cyan('on')} ${logger.dim('..............')} Enable sharing anonymous usage data
1573
+ `);
1574
+ };
1575
+
1576
+ const taskHelp = async (config, logger, sys) => {
1577
+ const prompt = logger.dim(sys.details.platform === 'windows' ? '>' : '$');
1578
+ console.log(`
1579
+ ${logger.bold('Build:')} ${logger.dim('Build components for development or production.')}
1580
+
1581
+ ${prompt} ${logger.green('rindo build [--dev] [--watch] [--prerender] [--debug]')}
1582
+
1583
+ ${logger.cyan('--dev')} ${logger.dim('.............')} Development build
1584
+ ${logger.cyan('--watch')} ${logger.dim('...........')} Rebuild when files update
1585
+ ${logger.cyan('--serve')} ${logger.dim('...........')} Start the dev-server
1586
+ ${logger.cyan('--prerender')} ${logger.dim('.......')} Prerender the application
1587
+ ${logger.cyan('--docs')} ${logger.dim('............')} Generate component readme.md docs
1588
+ ${logger.cyan('--config')} ${logger.dim('..........')} Set rindo config file
1589
+ ${logger.cyan('--stats')} ${logger.dim('...........')} Write rindo-stats.json file
1590
+ ${logger.cyan('--log')} ${logger.dim('.............')} Write rindo-build.log file
1591
+ ${logger.cyan('--debug')} ${logger.dim('...........')} Set the log level to debug
1592
+
1593
+
1594
+ ${logger.bold('Test:')} ${logger.dim('Run unit and end-to-end tests.')}
1595
+
1596
+ ${prompt} ${logger.green('rindo test [--spec] [--e2e]')}
1597
+
1598
+ ${logger.cyan('--spec')} ${logger.dim('............')} Run unit tests with Jest
1599
+ ${logger.cyan('--e2e')} ${logger.dim('.............')} Run e2e tests with Puppeteer
1600
+
1601
+
1602
+ ${logger.bold('Generate:')} ${logger.dim('Bootstrap components.')}
1603
+
1604
+ ${prompt} ${logger.green('rindo generate')} or ${logger.green('rindo g')}
1605
+
1606
+ `);
1607
+ // TODO: make this parameter no longer optional, remove the surrounding if statement
1608
+ if (sys) {
1609
+ await taskTelemetry(config, sys, logger);
1610
+ }
1611
+ console.log(`
1612
+ ${logger.bold('Examples:')}
1613
+
1614
+ ${prompt} ${logger.green('rindo build --dev --watch --serve')}
1615
+ ${prompt} ${logger.green('rindo build --prerender')}
1616
+ ${prompt} ${logger.green('rindo test --spec --e2e')}
1617
+ ${prompt} ${logger.green('rindo telemetry on')}
1618
+ ${prompt} ${logger.green('rindo generate')}
1619
+ ${prompt} ${logger.green('rindo g my-component')}
1620
+ `);
1621
+ };
1622
+
1623
+ const taskInfo = (coreCompiler, sys, logger) => {
1624
+ const details = sys.details;
1625
+ const versions = coreCompiler.versions;
1626
+ console.log(``);
1627
+ console.log(`${logger.cyan(' System:')} ${sys.name} ${sys.version}`);
1628
+ console.log(`${logger.cyan(' Plaform:')} ${details.platform} (${details.release})`);
1629
+ console.log(`${logger.cyan(' CPU Model:')} ${details.cpuModel} (${sys.hardwareConcurrency} cpu${sys.hardwareConcurrency !== 1 ? 's' : ''})`);
1630
+ console.log(`${logger.cyan(' Compiler:')} ${sys.getCompilerExecutingPath()}`);
1631
+ console.log(`${logger.cyan(' Build:')} ${coreCompiler.buildId}`);
1632
+ console.log(`${logger.cyan(' Rindo:')} ${coreCompiler.version}${logger.emoji(' ' + coreCompiler.vermoji)}`);
1633
+ console.log(`${logger.cyan(' TypeScript:')} ${versions.typescript}`);
1634
+ console.log(`${logger.cyan(' Rollup:')} ${versions.rollup}`);
1635
+ console.log(`${logger.cyan(' Parse5:')} ${versions.parse5}`);
1636
+ console.log(`${logger.cyan(' Sizzle:')} ${versions.sizzle}`);
1637
+ console.log(`${logger.cyan(' Terser:')} ${versions.terser}`);
1638
+ console.log(``);
1639
+ };
1640
+
1641
+ const taskServe = async (config) => {
1642
+ config.suppressLogs = true;
1643
+ config.flags.serve = true;
1644
+ config.devServer.openBrowser = config.flags.open;
1645
+ config.devServer.reloadStrategy = null;
1646
+ config.devServer.initialLoadUrl = '/';
1647
+ config.devServer.websocket = false;
1648
+ config.maxConcurrentWorkers = 1;
1649
+ config.devServer.root = isString(config.flags.root) ? config.flags.root : config.sys.getCurrentDirectory();
1650
+ const devServerPath = config.sys.getDevServerExecutingPath();
1651
+ const { start } = await config.sys.dynamicImport(devServerPath);
1652
+ const devServer = await start(config.devServer, config.logger);
1653
+ console.log(`${config.logger.cyan(' Root:')} ${devServer.root}`);
1654
+ console.log(`${config.logger.cyan(' Address:')} ${devServer.address}`);
1655
+ console.log(`${config.logger.cyan(' Port:')} ${devServer.port}`);
1656
+ console.log(`${config.logger.cyan(' Server:')} ${devServer.browserUrl}`);
1657
+ console.log(``);
1658
+ config.sys.onProcessInterrupt(() => {
1659
+ if (devServer) {
1660
+ config.logger.debug(`dev server close: ${devServer.browserUrl}`);
1661
+ devServer.close();
1662
+ }
1663
+ });
1664
+ };
1665
+
1666
+ const run = async (init) => {
1667
+ const { args, logger, sys } = init;
1668
+ try {
1669
+ const flags = parseFlags(args, sys);
1670
+ const task = flags.task;
1671
+ if (flags.debug || flags.verbose) {
1672
+ logger.setLevel('debug');
1673
+ }
1674
+ if (flags.ci) {
1675
+ logger.enableColors(false);
1676
+ }
1677
+ if (isFunction(sys.applyGlobalPatch)) {
1678
+ sys.applyGlobalPatch(sys.getCurrentDirectory());
1679
+ }
1680
+ if (task === 'help' || flags.help) {
1681
+ await taskHelp({ flags: { task: 'help', args }, outputTargets: [] }, logger, sys);
1682
+ return;
1683
+ }
1684
+ startupLog(logger, task);
1685
+ const findConfigResults = await findConfig({ sys, configPath: flags.config });
1686
+ if (hasError(findConfigResults.diagnostics)) {
1687
+ logger.printDiagnostics(findConfigResults.diagnostics);
1688
+ return sys.exit(1);
1689
+ }
1690
+ const ensureDepsResults = await sys.ensureDependencies({
1691
+ rootDir: findConfigResults.rootDir,
1692
+ logger,
1693
+ dependencies: dependencies,
1694
+ });
1695
+ if (hasError(ensureDepsResults.diagnostics)) {
1696
+ logger.printDiagnostics(ensureDepsResults.diagnostics);
1697
+ return sys.exit(1);
1698
+ }
1699
+ const coreCompiler = await loadCoreCompiler(sys);
1700
+ if (task === 'version' || flags.version) {
1701
+ console.log(coreCompiler.version);
1702
+ return;
1703
+ }
1704
+ startupLogVersion(logger, task, coreCompiler);
1705
+ loadedCompilerLog(sys, logger, flags, coreCompiler);
1706
+ if (task === 'info') {
1707
+ await telemetryAction(sys, { flags: { task: 'info' }, outputTargets: [] }, logger, coreCompiler, async () => {
1708
+ await taskInfo(coreCompiler, sys, logger);
1709
+ });
1710
+ return;
1711
+ }
1712
+ const validated = await coreCompiler.loadConfig({
1713
+ config: {
1714
+ flags,
1715
+ },
1716
+ configPath: findConfigResults.configPath,
1717
+ logger,
1718
+ sys,
1719
+ });
1720
+ if (validated.diagnostics.length > 0) {
1721
+ logger.printDiagnostics(validated.diagnostics);
1722
+ if (hasError(validated.diagnostics)) {
1723
+ return sys.exit(1);
1724
+ }
1725
+ }
1726
+ if (isFunction(sys.applyGlobalPatch)) {
1727
+ sys.applyGlobalPatch(validated.config.rootDir);
1728
+ }
1729
+ await sys.ensureResources({ rootDir: validated.config.rootDir, logger, dependencies: dependencies });
1730
+ await telemetryAction(sys, validated.config, logger, coreCompiler, async () => {
1731
+ await runTask(coreCompiler, validated.config, task, sys);
1732
+ });
1733
+ }
1734
+ catch (e) {
1735
+ if (!shouldIgnoreError(e)) {
1736
+ const details = `${logger.getLevel() === 'debug' && e instanceof Error ? e.stack : ''}`;
1737
+ logger.error(`uncaught cli error: ${e}${details}`);
1738
+ return sys.exit(1);
1739
+ }
1740
+ }
1741
+ };
1742
+ const runTask = async (coreCompiler, config, task, sys) => {
1743
+ config.flags = config.flags || { task };
1744
+ config.outputTargets = config.outputTargets || [];
1745
+ switch (task) {
1746
+ case 'build':
1747
+ await taskBuild(coreCompiler, config, sys);
1748
+ break;
1749
+ case 'docs':
1750
+ await taskDocs(coreCompiler, config);
1751
+ break;
1752
+ case 'generate':
1753
+ case 'g':
1754
+ await taskGenerate(coreCompiler, config);
1755
+ break;
1756
+ case 'help':
1757
+ await taskHelp(config, config.logger, sys);
1758
+ break;
1759
+ case 'prerender':
1760
+ await taskPrerender(coreCompiler, config);
1761
+ break;
1762
+ case 'serve':
1763
+ await taskServe(config);
1764
+ break;
1765
+ case 'telemetry':
1766
+ // TODO: make this parameter no longer optional, remove the surrounding if statement
1767
+ if (sys) {
1768
+ await taskTelemetry(config, sys, config.logger);
1769
+ }
1770
+ break;
1771
+ case 'version':
1772
+ console.log(coreCompiler.version);
1773
+ break;
1774
+ default:
1775
+ config.logger.error(`${config.logger.emoji('❌ ')}Invalid rindo command, please see the options below:`);
1776
+ await taskHelp(config, config.logger, sys);
1777
+ return config.sys.exit(1);
1778
+ }
1779
+ };
1780
+
1781
+ exports.parseFlags = parseFlags;
1782
+ exports.run = run;
1783
+ exports.runTask = runTask;
1784
+ //# sourceMappingURL=index.cjs.map