@stencil/core 4.43.1 → 5.0.0-next.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 (368) hide show
  1. package/bin/stencil.mjs +2 -0
  2. package/dist/chunk-ClPoSABd.mjs +21 -0
  3. package/dist/client-DR9zhmKG.mjs +4449 -0
  4. package/dist/compiler/index.d.mts +187 -0
  5. package/dist/compiler/index.mjs +9 -0
  6. package/dist/compiler/utils/index.d.mts +3 -0
  7. package/dist/compiler/utils/index.mjs +5 -0
  8. package/dist/declarations/stencil-public-compiler.d.ts +4401 -0
  9. package/dist/declarations/stencil-public-compiler.js +53 -0
  10. package/dist/declarations/stencil-public-runtime.d.ts +1857 -0
  11. package/dist/index-Bxo2jCf6.d.mts +77 -0
  12. package/dist/index-szczUd2l.d.mts +6851 -0
  13. package/{internal/stencil-core/index.d.ts → dist/index.d.mts} +7 -3
  14. package/dist/index.mjs +4 -0
  15. package/dist/mock-doc.d.mts +1 -0
  16. package/dist/mock-doc.mjs +3 -0
  17. package/dist/node-sys-BGURUNOZ.mjs +1954 -0
  18. package/{internal → dist/runtime}/app-data/index.d.ts +11 -7
  19. package/dist/runtime/app-data/index.js +100 -0
  20. package/dist/runtime/app-globals/index.d.ts +5 -0
  21. package/dist/runtime/app-globals/index.js +6 -0
  22. package/dist/runtime/client/index.d.ts +2286 -0
  23. package/dist/runtime/client/index.js +4839 -0
  24. package/dist/runtime/index.d.ts +221 -0
  25. package/dist/runtime/index.js +4819 -0
  26. package/dist/runtime/server/index.d.mts +1277 -0
  27. package/dist/runtime/server/index.mjs +5376 -0
  28. package/dist/runtime/server/runner.d.mts +298 -0
  29. package/dist/runtime/server/runner.mjs +1976 -0
  30. package/dist/serialize-BJvhE9aQ.mjs +775 -0
  31. package/dist/stencil-private-Cgcr414u.d.ts +1893 -0
  32. package/dist/sys/node/index.d.mts +33 -0
  33. package/dist/sys/node/index.mjs +7 -0
  34. package/dist/sys/node/worker.d.mts +1 -0
  35. package/dist/sys/node/worker.mjs +60 -0
  36. package/dist/testing/index.d.mts +207 -0
  37. package/dist/testing/index.mjs +1188 -0
  38. package/dist/transpile-CJQcQEVa.mjs +21854 -0
  39. package/dist/validation-BdcPruW_.mjs +1451 -0
  40. package/package.json +88 -232
  41. package/bin/stencil +0 -57
  42. package/cli/config-flags.d.ts +0 -132
  43. package/cli/index.cjs +0 -5816
  44. package/cli/index.d.ts +0 -19
  45. package/cli/index.js +0 -5809
  46. package/cli/package.json +0 -14
  47. package/compiler/lib.d.ts +0 -22
  48. package/compiler/lib.decorators.d.ts +0 -384
  49. package/compiler/lib.decorators.legacy.d.ts +0 -22
  50. package/compiler/lib.dom.asynciterable.d.ts +0 -41
  51. package/compiler/lib.dom.d.ts +0 -29610
  52. package/compiler/lib.dom.iterable.d.ts +0 -493
  53. package/compiler/lib.es2015.collection.d.ts +0 -147
  54. package/compiler/lib.es2015.core.d.ts +0 -597
  55. package/compiler/lib.es2015.d.ts +0 -28
  56. package/compiler/lib.es2015.generator.d.ts +0 -77
  57. package/compiler/lib.es2015.iterable.d.ts +0 -605
  58. package/compiler/lib.es2015.promise.d.ts +0 -81
  59. package/compiler/lib.es2015.proxy.d.ts +0 -128
  60. package/compiler/lib.es2015.reflect.d.ts +0 -144
  61. package/compiler/lib.es2015.symbol.d.ts +0 -46
  62. package/compiler/lib.es2015.symbol.wellknown.d.ts +0 -326
  63. package/compiler/lib.es2016.array.include.d.ts +0 -116
  64. package/compiler/lib.es2016.d.ts +0 -21
  65. package/compiler/lib.es2016.full.d.ts +0 -23
  66. package/compiler/lib.es2016.intl.d.ts +0 -31
  67. package/compiler/lib.es2017.arraybuffer.d.ts +0 -21
  68. package/compiler/lib.es2017.d.ts +0 -26
  69. package/compiler/lib.es2017.date.d.ts +0 -31
  70. package/compiler/lib.es2017.full.d.ts +0 -23
  71. package/compiler/lib.es2017.intl.d.ts +0 -44
  72. package/compiler/lib.es2017.object.d.ts +0 -49
  73. package/compiler/lib.es2017.sharedmemory.d.ts +0 -135
  74. package/compiler/lib.es2017.string.d.ts +0 -45
  75. package/compiler/lib.es2017.typedarrays.d.ts +0 -53
  76. package/compiler/lib.es2018.asyncgenerator.d.ts +0 -77
  77. package/compiler/lib.es2018.asynciterable.d.ts +0 -53
  78. package/compiler/lib.es2018.d.ts +0 -24
  79. package/compiler/lib.es2018.full.d.ts +0 -24
  80. package/compiler/lib.es2018.intl.d.ts +0 -83
  81. package/compiler/lib.es2018.promise.d.ts +0 -30
  82. package/compiler/lib.es2018.regexp.d.ts +0 -37
  83. package/compiler/lib.es2019.array.d.ts +0 -79
  84. package/compiler/lib.es2019.d.ts +0 -24
  85. package/compiler/lib.es2019.full.d.ts +0 -24
  86. package/compiler/lib.es2019.intl.d.ts +0 -23
  87. package/compiler/lib.es2019.object.d.ts +0 -33
  88. package/compiler/lib.es2019.string.d.ts +0 -37
  89. package/compiler/lib.es2019.symbol.d.ts +0 -24
  90. package/compiler/lib.es2020.bigint.d.ts +0 -765
  91. package/compiler/lib.es2020.d.ts +0 -27
  92. package/compiler/lib.es2020.date.d.ts +0 -42
  93. package/compiler/lib.es2020.full.d.ts +0 -24
  94. package/compiler/lib.es2020.intl.d.ts +0 -474
  95. package/compiler/lib.es2020.number.d.ts +0 -28
  96. package/compiler/lib.es2020.promise.d.ts +0 -47
  97. package/compiler/lib.es2020.sharedmemory.d.ts +0 -99
  98. package/compiler/lib.es2020.string.d.ts +0 -44
  99. package/compiler/lib.es2020.symbol.wellknown.d.ts +0 -41
  100. package/compiler/lib.es2021.d.ts +0 -23
  101. package/compiler/lib.es2021.full.d.ts +0 -24
  102. package/compiler/lib.es2021.intl.d.ts +0 -166
  103. package/compiler/lib.es2021.promise.d.ts +0 -48
  104. package/compiler/lib.es2021.string.d.ts +0 -33
  105. package/compiler/lib.es2021.weakref.d.ts +0 -78
  106. package/compiler/lib.es2022.array.d.ts +0 -121
  107. package/compiler/lib.es2022.d.ts +0 -25
  108. package/compiler/lib.es2022.error.d.ts +0 -75
  109. package/compiler/lib.es2022.full.d.ts +0 -24
  110. package/compiler/lib.es2022.intl.d.ts +0 -121
  111. package/compiler/lib.es2022.object.d.ts +0 -26
  112. package/compiler/lib.es2022.regexp.d.ts +0 -39
  113. package/compiler/lib.es2022.string.d.ts +0 -25
  114. package/compiler/lib.es2023.array.d.ts +0 -924
  115. package/compiler/lib.es2023.collection.d.ts +0 -21
  116. package/compiler/lib.es2023.d.ts +0 -22
  117. package/compiler/lib.es2023.full.d.ts +0 -24
  118. package/compiler/lib.es2023.intl.d.ts +0 -56
  119. package/compiler/lib.es2024.arraybuffer.d.ts +0 -65
  120. package/compiler/lib.es2024.collection.d.ts +0 -29
  121. package/compiler/lib.es2024.d.ts +0 -26
  122. package/compiler/lib.es2024.full.d.ts +0 -24
  123. package/compiler/lib.es2024.object.d.ts +0 -29
  124. package/compiler/lib.es2024.promise.d.ts +0 -35
  125. package/compiler/lib.es2024.regexp.d.ts +0 -25
  126. package/compiler/lib.es2024.sharedmemory.d.ts +0 -68
  127. package/compiler/lib.es2024.string.d.ts +0 -29
  128. package/compiler/lib.es5.d.ts +0 -4594
  129. package/compiler/lib.es6.d.ts +0 -23
  130. package/compiler/lib.esnext.array.d.ts +0 -35
  131. package/compiler/lib.esnext.collection.d.ts +0 -96
  132. package/compiler/lib.esnext.d.ts +0 -27
  133. package/compiler/lib.esnext.decorators.d.ts +0 -28
  134. package/compiler/lib.esnext.disposable.d.ts +0 -193
  135. package/compiler/lib.esnext.float16.d.ts +0 -443
  136. package/compiler/lib.esnext.full.d.ts +0 -24
  137. package/compiler/lib.esnext.intl.d.ts +0 -21
  138. package/compiler/lib.esnext.iterator.d.ts +0 -148
  139. package/compiler/lib.esnext.promise.d.ts +0 -34
  140. package/compiler/lib.scripthost.d.ts +0 -322
  141. package/compiler/lib.webworker.asynciterable.d.ts +0 -41
  142. package/compiler/lib.webworker.d.ts +0 -9894
  143. package/compiler/lib.webworker.importscripts.d.ts +0 -23
  144. package/compiler/lib.webworker.iterable.d.ts +0 -287
  145. package/compiler/package.json +0 -8
  146. package/compiler/stencil.d.ts +0 -73
  147. package/compiler/stencil.js +0 -287696
  148. package/compiler/sys/in-memory-fs.d.ts +0 -227
  149. package/compiler/transpile.d.ts +0 -32
  150. package/dev-server/client/app-error.d.ts +0 -20
  151. package/dev-server/client/events.d.ts +0 -6
  152. package/dev-server/client/hmr-components.d.ts +0 -12
  153. package/dev-server/client/hmr-external-styles.d.ts +0 -1
  154. package/dev-server/client/hmr-images.d.ts +0 -1
  155. package/dev-server/client/hmr-inline-styles.d.ts +0 -1
  156. package/dev-server/client/hmr-util.d.ts +0 -39
  157. package/dev-server/client/hmr-window.d.ts +0 -10
  158. package/dev-server/client/index.d.ts +0 -6
  159. package/dev-server/client/index.js +0 -793
  160. package/dev-server/client/logger.d.ts +0 -6
  161. package/dev-server/client/package.json +0 -8
  162. package/dev-server/client/progress.d.ts +0 -3
  163. package/dev-server/client/status.d.ts +0 -4
  164. package/dev-server/client/test/hmr-util.spec.d.ts +0 -1
  165. package/dev-server/client/test/status.spec.d.ts +0 -1
  166. package/dev-server/connector.html +0 -6
  167. package/dev-server/index.d.ts +0 -3
  168. package/dev-server/index.js +0 -247
  169. package/dev-server/package.json +0 -8
  170. package/dev-server/server-process.js +0 -12095
  171. package/dev-server/server-worker-thread.js +0 -39
  172. package/dev-server/static/favicon.ico +0 -0
  173. package/dev-server/templates/directory-index.html +0 -176
  174. package/dev-server/templates/initial-load.html +0 -168
  175. package/dev-server/visualstudio.vbs +0 -82
  176. package/dev-server/xdg-open +0 -1066
  177. package/internal/app-data/index.cjs +0 -119
  178. package/internal/app-data/index.js +0 -92
  179. package/internal/app-data/package.json +0 -15
  180. package/internal/app-globals/index.d.ts +0 -2
  181. package/internal/app-globals/index.js +0 -14
  182. package/internal/app-globals/package.json +0 -14
  183. package/internal/child_process.d.ts +0 -7
  184. package/internal/client/index.js +0 -4727
  185. package/internal/client/package.json +0 -10
  186. package/internal/client/patch-browser.js +0 -45
  187. package/internal/client/polyfills/core-js.js +0 -11
  188. package/internal/client/polyfills/dom.js +0 -79
  189. package/internal/client/polyfills/es5-html-element.js +0 -1
  190. package/internal/client/polyfills/index.js +0 -34
  191. package/internal/client/polyfills/system.js +0 -6
  192. package/internal/client/shadow-css.js +0 -414
  193. package/internal/hydrate/index.js +0 -6664
  194. package/internal/hydrate/package.json +0 -7
  195. package/internal/hydrate/runner.d.ts +0 -287
  196. package/internal/hydrate/runner.js +0 -17947
  197. package/internal/index.d.ts +0 -4
  198. package/internal/index.js +0 -2
  199. package/internal/package.json +0 -9
  200. package/internal/stencil-core/index.cjs +0 -1
  201. package/internal/stencil-core/index.js +0 -18
  202. package/internal/stencil-core/jsx-dev-runtime.cjs +0 -7
  203. package/internal/stencil-core/jsx-dev-runtime.d.ts +0 -41
  204. package/internal/stencil-core/jsx-dev-runtime.js +0 -2
  205. package/internal/stencil-core/jsx-runtime.cjs +0 -8
  206. package/internal/stencil-core/jsx-runtime.d.ts +0 -40
  207. package/internal/stencil-core/jsx-runtime.js +0 -2
  208. package/internal/stencil-private.d.ts +0 -2538
  209. package/internal/stencil-public-compiler.d.ts +0 -2867
  210. package/internal/stencil-public-runtime.d.ts +0 -1860
  211. package/internal/testing/index.js +0 -6517
  212. package/internal/testing/jsx-dev-runtime.d.ts +0 -2
  213. package/internal/testing/jsx-dev-runtime.js +0 -8
  214. package/internal/testing/jsx-runtime.d.ts +0 -2
  215. package/internal/testing/jsx-runtime.js +0 -9
  216. package/internal/testing/package.json +0 -7
  217. package/internal/utils/index.d.ts +0 -1
  218. package/internal/utils/result.d.ts +0 -112
  219. package/mock-doc/index.cjs +0 -10162
  220. package/mock-doc/index.d.ts +0 -1171
  221. package/mock-doc/index.js +0 -10141
  222. package/mock-doc/package.json +0 -15
  223. package/readme.md +0 -94
  224. package/screenshot/compare/assets/favicon.ico +0 -0
  225. package/screenshot/compare/assets/logo.png +0 -0
  226. package/screenshot/compare/build/app.css +0 -1
  227. package/screenshot/compare/build/app.esm.js +0 -1
  228. package/screenshot/compare/build/app.js +0 -33
  229. package/screenshot/compare/build/p-081b0641.js +0 -1
  230. package/screenshot/compare/build/p-227a1e18.entry.js +0 -1
  231. package/screenshot/compare/build/p-2c298727.entry.js +0 -1
  232. package/screenshot/compare/build/p-5479268c.entry.js +0 -1
  233. package/screenshot/compare/build/p-573ec8a4.entry.js +0 -1
  234. package/screenshot/compare/build/p-6ba08604.entry.js +0 -1
  235. package/screenshot/compare/build/p-6bc63295.entry.js +0 -1
  236. package/screenshot/compare/build/p-7a3759fd.entry.js +0 -1
  237. package/screenshot/compare/build/p-7b4e3ba7.js +0 -1
  238. package/screenshot/compare/build/p-988eb362.css +0 -1
  239. package/screenshot/compare/build/p-9b6a9315.js +0 -1
  240. package/screenshot/compare/build/p-b4cc611c.entry.js +0 -1
  241. package/screenshot/compare/build/p-d1bf53f5.entry.js +0 -1
  242. package/screenshot/compare/build/p-e2efe0df.js +0 -1
  243. package/screenshot/compare/build/p-e8ca6d97.entry.js +0 -1
  244. package/screenshot/compare/build/p-ec2f13e0.entry.js +0 -1
  245. package/screenshot/compare/build/p-f0b99977.entry.js +0 -1
  246. package/screenshot/compare/build/p-f4745c2f.entry.js +0 -1
  247. package/screenshot/compare/build/p-fbbae598.js +0 -1
  248. package/screenshot/compare/host.config.json +0 -15
  249. package/screenshot/compare/index.html +0 -1
  250. package/screenshot/compare/manifest.json +0 -13
  251. package/screenshot/connector-base.d.ts +0 -42
  252. package/screenshot/connector-local.d.ts +0 -7
  253. package/screenshot/connector.js +0 -2
  254. package/screenshot/index.d.ts +0 -3
  255. package/screenshot/index.js +0 -2433
  256. package/screenshot/local-connector.js +0 -2
  257. package/screenshot/package.json +0 -15
  258. package/screenshot/pixel-match.d.ts +0 -1
  259. package/screenshot/pixel-match.js +0 -2315
  260. package/screenshot/screenshot-compare.d.ts +0 -20
  261. package/screenshot/screenshot-fs.d.ts +0 -14
  262. package/sys/node/460.node-fetch.js +0 -451
  263. package/sys/node/autoprefixer.js +0 -9
  264. package/sys/node/glob.js +0 -1
  265. package/sys/node/graceful-fs.js +0 -1
  266. package/sys/node/index.d.ts +0 -39
  267. package/sys/node/index.js +0 -64
  268. package/sys/node/node-fetch.js +0 -12
  269. package/sys/node/package.json +0 -8
  270. package/sys/node/prompts.js +0 -1
  271. package/sys/node/worker.js +0 -4
  272. package/testing/index.d.ts +0 -9
  273. package/testing/index.js +0 -13063
  274. package/testing/jest/jest-27-and-under/jest-config.d.ts +0 -16
  275. package/testing/jest/jest-27-and-under/jest-environment.d.ts +0 -2
  276. package/testing/jest/jest-27-and-under/jest-facade.d.ts +0 -155
  277. package/testing/jest/jest-27-and-under/jest-preprocessor.d.ts +0 -59
  278. package/testing/jest/jest-27-and-under/jest-preset.d.ts +0 -3
  279. package/testing/jest/jest-27-and-under/jest-runner.d.ts +0 -11
  280. package/testing/jest/jest-27-and-under/jest-screenshot.d.ts +0 -2
  281. package/testing/jest/jest-27-and-under/jest-serializer.d.ts +0 -4
  282. package/testing/jest/jest-27-and-under/jest-setup-test-framework.d.ts +0 -9
  283. package/testing/jest/jest-27-and-under/matchers/attributes.d.ts +0 -14
  284. package/testing/jest/jest-27-and-under/matchers/class-list.d.ts +0 -12
  285. package/testing/jest/jest-27-and-under/matchers/events.d.ts +0 -25
  286. package/testing/jest/jest-27-and-under/matchers/html.d.ts +0 -13
  287. package/testing/jest/jest-27-and-under/matchers/index.d.ts +0 -24
  288. package/testing/jest/jest-27-and-under/matchers/screenshot.d.ts +0 -5
  289. package/testing/jest/jest-27-and-under/matchers/text.d.ts +0 -4
  290. package/testing/jest/jest-27-and-under/test/jest-config.spec.d.ts +0 -1
  291. package/testing/jest/jest-27-and-under/test/jest-preprocessor.spec.d.ts +0 -1
  292. package/testing/jest/jest-27-and-under/test/jest-runner.spec.d.ts +0 -1
  293. package/testing/jest/jest-27-and-under/test/jest-serializer.spec.d.ts +0 -1
  294. package/testing/jest/jest-27-and-under/test/jest-setup-test-framework.spec.d.ts +0 -1
  295. package/testing/jest/jest-28/jest-config.d.ts +0 -16
  296. package/testing/jest/jest-28/jest-environment.d.ts +0 -2
  297. package/testing/jest/jest-28/jest-facade.d.ts +0 -134
  298. package/testing/jest/jest-28/jest-preprocessor.d.ts +0 -35
  299. package/testing/jest/jest-28/jest-preset.d.ts +0 -3
  300. package/testing/jest/jest-28/jest-runner.d.ts +0 -11
  301. package/testing/jest/jest-28/jest-screenshot.d.ts +0 -2
  302. package/testing/jest/jest-28/jest-serializer.d.ts +0 -4
  303. package/testing/jest/jest-28/jest-setup-test-framework.d.ts +0 -9
  304. package/testing/jest/jest-28/matchers/attributes.d.ts +0 -14
  305. package/testing/jest/jest-28/matchers/class-list.d.ts +0 -12
  306. package/testing/jest/jest-28/matchers/events.d.ts +0 -25
  307. package/testing/jest/jest-28/matchers/html.d.ts +0 -13
  308. package/testing/jest/jest-28/matchers/index.d.ts +0 -24
  309. package/testing/jest/jest-28/matchers/screenshot.d.ts +0 -5
  310. package/testing/jest/jest-28/matchers/text.d.ts +0 -4
  311. package/testing/jest/jest-28/test/jest-config.spec.d.ts +0 -1
  312. package/testing/jest/jest-28/test/jest-preprocessor.spec.d.ts +0 -1
  313. package/testing/jest/jest-28/test/jest-runner.spec.d.ts +0 -1
  314. package/testing/jest/jest-28/test/jest-serializer.spec.d.ts +0 -1
  315. package/testing/jest/jest-28/test/jest-setup-test-framework.spec.d.ts +0 -1
  316. package/testing/jest/jest-29/jest-config.d.ts +0 -16
  317. package/testing/jest/jest-29/jest-environment.d.ts +0 -2
  318. package/testing/jest/jest-29/jest-facade.d.ts +0 -136
  319. package/testing/jest/jest-29/jest-preprocessor.d.ts +0 -35
  320. package/testing/jest/jest-29/jest-preset.d.ts +0 -3
  321. package/testing/jest/jest-29/jest-runner.d.ts +0 -11
  322. package/testing/jest/jest-29/jest-screenshot.d.ts +0 -2
  323. package/testing/jest/jest-29/jest-serializer.d.ts +0 -4
  324. package/testing/jest/jest-29/jest-setup-test-framework.d.ts +0 -9
  325. package/testing/jest/jest-29/matchers/attributes.d.ts +0 -14
  326. package/testing/jest/jest-29/matchers/class-list.d.ts +0 -12
  327. package/testing/jest/jest-29/matchers/events.d.ts +0 -25
  328. package/testing/jest/jest-29/matchers/html.d.ts +0 -13
  329. package/testing/jest/jest-29/matchers/index.d.ts +0 -24
  330. package/testing/jest/jest-29/matchers/screenshot.d.ts +0 -5
  331. package/testing/jest/jest-29/matchers/text.d.ts +0 -4
  332. package/testing/jest/jest-29/test/jest-config.spec.d.ts +0 -1
  333. package/testing/jest/jest-29/test/jest-preprocessor.spec.d.ts +0 -1
  334. package/testing/jest/jest-29/test/jest-runner.spec.d.ts +0 -1
  335. package/testing/jest/jest-29/test/jest-serializer.spec.d.ts +0 -1
  336. package/testing/jest/jest-29/test/jest-setup-test-framework.spec.d.ts +0 -1
  337. package/testing/jest/jest-apis.d.ts +0 -86
  338. package/testing/jest/jest-facade.d.ts +0 -74
  339. package/testing/jest/jest-stencil-connector.d.ts +0 -65
  340. package/testing/jest/test/jest-stencil-connector.spec.d.ts +0 -1
  341. package/testing/jest-environment.js +0 -3
  342. package/testing/jest-preprocessor.js +0 -3
  343. package/testing/jest-preset.js +0 -2
  344. package/testing/jest-runner.js +0 -3
  345. package/testing/jest-setuptestframework.js +0 -3
  346. package/testing/mock-fetch.d.ts +0 -11
  347. package/testing/mocks.d.ts +0 -56
  348. package/testing/package.json +0 -8
  349. package/testing/puppeteer/index.d.ts +0 -2
  350. package/testing/puppeteer/puppeteer-browser.d.ts +0 -6
  351. package/testing/puppeteer/puppeteer-declarations.d.ts +0 -414
  352. package/testing/puppeteer/puppeteer-element.d.ts +0 -67
  353. package/testing/puppeteer/puppeteer-emulate.d.ts +0 -2
  354. package/testing/puppeteer/puppeteer-events.d.ts +0 -21
  355. package/testing/puppeteer/puppeteer-page.d.ts +0 -2
  356. package/testing/puppeteer/puppeteer-screenshot.d.ts +0 -27
  357. package/testing/puppeteer/test/puppeteer-screenshot.spec.d.ts +0 -1
  358. package/testing/reset-build-conditionals.d.ts +0 -12
  359. package/testing/spec-page.d.ts +0 -7
  360. package/testing/test/testing-utils.spec.d.ts +0 -1
  361. package/testing/test-transpile.d.ts +0 -2
  362. package/testing/testing-logger.d.ts +0 -26
  363. package/testing/testing-sys.d.ts +0 -6
  364. package/testing/testing-utils.d.ts +0 -80
  365. package/testing/testing.d.ts +0 -2
  366. /package/{internal → dist/declarations}/stencil-ext-modules.d.ts +0 -0
  367. /package/{internal → dist/declarations}/stencil-public-docs.d.ts +0 -0
  368. /package/{screenshot/compare/build/index.esm.js → dist/declarations/stencil-public-runtime.js} +0 -0
@@ -0,0 +1,1954 @@
1
+ import { n as __require } from "./chunk-ClPoSABd.mjs";
2
+ import { _ as isString, c as flatOne, p as isFunction, y as noop } from "./serialize-BJvhE9aQ.mjs";
3
+ import { bt as isGlob, dt as TASK_CANCELED_MSG, ft as buildError, ht as catchError, rt as normalizePath, vt as shouldIgnoreError } from "./validation-BdcPruW_.mjs";
4
+ import path from "node:path";
5
+ import path$1 from "path";
6
+ import fs from "graceful-fs";
7
+ import chalk from "chalk";
8
+ import { createHash } from "node:crypto";
9
+ import * as os from "node:os";
10
+ import { cpus, freemem, platform, release, tmpdir, totalmem } from "node:os";
11
+ import * as parcelWatcher from "@parcel/watcher";
12
+ import { glob } from "glob";
13
+ import { promisify } from "util";
14
+ import semverLte from "semver/functions/lte.js";
15
+ import major from "semver/functions/major.js";
16
+ import satisfies from "semver/functions/satisfies.js";
17
+ import { cpus as cpus$1, tmpdir as tmpdir$1 } from "os";
18
+ import semverLt from "semver/functions/lt.js";
19
+ import { EventEmitter } from "events";
20
+ import * as cp from "child_process";
21
+
22
+ //#region src/compiler/events.ts
23
+ const buildEvents = () => {
24
+ const evCallbacks = [];
25
+ const off = (callback) => {
26
+ const index = evCallbacks.findIndex((ev) => ev.callback === callback);
27
+ if (index > -1) {
28
+ evCallbacks.splice(index, 1);
29
+ return true;
30
+ }
31
+ return false;
32
+ };
33
+ const on = (arg0, arg1) => {
34
+ if (typeof arg0 === "function") {
35
+ const eventName = null;
36
+ const callback = arg0;
37
+ evCallbacks.push({
38
+ eventName,
39
+ callback
40
+ });
41
+ return () => off(callback);
42
+ } else if (typeof arg0 === "string" && typeof arg1 === "function") {
43
+ const eventName = arg0.toLowerCase().trim();
44
+ const callback = arg1;
45
+ evCallbacks.push({
46
+ eventName,
47
+ callback
48
+ });
49
+ return () => off(callback);
50
+ }
51
+ return () => false;
52
+ };
53
+ const emit = (eventName, data) => {
54
+ const normalizedEventName = eventName.toLowerCase().trim();
55
+ const callbacks = evCallbacks.slice();
56
+ for (const ev of callbacks) if (ev.eventName == null) try {
57
+ ev.callback(eventName, data);
58
+ } catch (e) {
59
+ console.error(e);
60
+ }
61
+ else if (ev.eventName === normalizedEventName) try {
62
+ ev.callback(data);
63
+ } catch (e) {
64
+ console.error(e);
65
+ }
66
+ };
67
+ const unsubscribeAll = () => {
68
+ evCallbacks.length = 0;
69
+ };
70
+ return {
71
+ emit,
72
+ on,
73
+ unsubscribeAll
74
+ };
75
+ };
76
+
77
+ //#endregion
78
+ //#region src/declarations/stencil-public-compiler.ts
79
+ /**
80
+ * This sets the log level hierarchy for our terminal logger, ranging from
81
+ * most to least verbose.
82
+ *
83
+ * Ordering the levels like this lets us easily check whether we should log a
84
+ * message at a given time. For instance, if the log level is set to `'warn'`,
85
+ * then anything passed to the logger with level `'warn'` or `'error'` should
86
+ * be logged, but we should _not_ log anything with level `'info'` or `'debug'`.
87
+ *
88
+ * If we have a current log level `currentLevel` and a message with level
89
+ * `msgLevel` is passed to the logger, we can determine whether or not we should
90
+ * log it by checking if the log level on the message is further up or at the
91
+ * same level in the hierarchy than `currentLevel`, like so:
92
+ *
93
+ * ```ts
94
+ * LOG_LEVELS.indexOf(msgLevel) >= LOG_LEVELS.indexOf(currentLevel)
95
+ * ```
96
+ *
97
+ * NOTE: for the reasons described above, do not change the order of the entries
98
+ * in this array without good reason!
99
+ */
100
+ const LOG_LEVELS = [
101
+ "debug",
102
+ "info",
103
+ "warn",
104
+ "error"
105
+ ];
106
+ /**
107
+ * The collection of valid export behaviors.
108
+ * Used to generate a type for typed configs as well as output target validation
109
+ * for the `dist-custom-elements` output target.
110
+ *
111
+ * Adding a value to this const array will automatically add it as a valid option on the
112
+ * output target configuration for `customElementsExportBehavior`.
113
+ *
114
+ * - `default`: No additional export or definition behavior will happen.
115
+ * - `auto-define-custom-elements`: Enables the auto-definition of a component and its children (recursively) in the custom elements registry. This
116
+ * functionality allows consumers to bypass the explicit call to define a component, its children, its children's
117
+ * children, etc. Users of this flag should be aware that enabling this functionality may increase bundle size.
118
+ * - `bundle`: A `defineCustomElements` function will be exported from the distribution directory. This behavior was added to allow easy migration
119
+ * from `dist-custom-elements-bundle` to `dist-custom-elements`.
120
+ * - `single-export-module`: All components will be re-exported from the specified directory's root `index.js` file.
121
+ */
122
+ const CustomElementsExportBehaviorOptions = [
123
+ "default",
124
+ "auto-define-custom-elements",
125
+ "bundle",
126
+ "single-export-module"
127
+ ];
128
+
129
+ //#endregion
130
+ //#region src/sys/node/logger/terminal-logger.ts
131
+ const { bgRed, blue, bold, cyan, dim, gray, green, magenta, red, yellow } = chalk;
132
+ /**
133
+ * Map of color names to chalk functions for dynamic access
134
+ */
135
+ const chalkColors = {
136
+ yellow: chalk.yellow,
137
+ red: chalk.red,
138
+ magenta: chalk.magenta,
139
+ green: chalk.green,
140
+ gray: chalk.gray,
141
+ cyan: chalk.cyan,
142
+ blue: chalk.blue,
143
+ bold: chalk.bold,
144
+ dim: chalk.dim
145
+ };
146
+ /**
147
+ * Create a logger for outputting information to a terminal environment
148
+ * @param loggerSys an underlying logger system entity used to create the terminal logger
149
+ * @returns the created logger
150
+ */
151
+ const createTerminalLogger = (loggerSys) => {
152
+ let currentLogLevel = "info";
153
+ let logFilePath = null;
154
+ const writeLogQueue = [];
155
+ const setLevel = (l) => currentLogLevel = l;
156
+ const getLevel = () => currentLogLevel;
157
+ const setLogFilePath = (p) => logFilePath = p;
158
+ const info = (...msg) => {
159
+ if (shouldLog(currentLogLevel, "info")) {
160
+ const lines = wordWrap(msg, loggerSys.getColumns());
161
+ infoPrefix(lines);
162
+ console.log(lines.join("\n"));
163
+ }
164
+ queueWriteLog("I", msg);
165
+ };
166
+ const infoPrefix = (lines) => {
167
+ if (lines.length > 0) {
168
+ const prefix = formatPrefixTimestamp();
169
+ lines[0] = dim(prefix) + lines[0].slice(prefix.length);
170
+ }
171
+ };
172
+ const warn = (...msg) => {
173
+ if (shouldLog(currentLogLevel, "warn")) {
174
+ const lines = wordWrap(msg, loggerSys.getColumns());
175
+ warnPrefix(lines);
176
+ console.warn("\n" + lines.join("\n") + "\n");
177
+ }
178
+ queueWriteLog("W", msg);
179
+ };
180
+ const warnPrefix = (lines) => {
181
+ if (lines.length) lines[0] = bold(yellow("[ WARN ]")) + lines[0].slice(9);
182
+ };
183
+ const error = (...msg) => {
184
+ for (let i = 0; i < msg.length; i++) if (msg[i] instanceof Error) {
185
+ const err = msg[i];
186
+ msg[i] = err.message;
187
+ if (err.stack) msg[i] += "\n" + err.stack;
188
+ }
189
+ if (shouldLog(currentLogLevel, "error")) {
190
+ const lines = wordWrap(msg, loggerSys.getColumns());
191
+ errorPrefix(lines);
192
+ console.error("\n" + lines.join("\n") + "\n");
193
+ }
194
+ queueWriteLog("E", msg);
195
+ };
196
+ const errorPrefix = (lines) => {
197
+ if (lines.length) lines[0] = bold(red("[ ERROR ]")) + lines[0].slice(9);
198
+ };
199
+ const debug = (...msg) => {
200
+ if (shouldLog(currentLogLevel, "debug")) {
201
+ formatMemoryUsage(msg);
202
+ const lines = wordWrap(msg, loggerSys.getColumns());
203
+ debugPrefix(lines);
204
+ console.log(lines.join("\n"));
205
+ }
206
+ queueWriteLog("D", msg);
207
+ };
208
+ const debugPrefix = (lines) => {
209
+ if (lines.length) {
210
+ const prefix = formatPrefixTimestamp();
211
+ lines[0] = cyan(prefix) + lines[0].slice(prefix.length);
212
+ }
213
+ };
214
+ const timespanStart = (startMsg, debug, appendTo) => {
215
+ const msg = [`${startMsg} ${dim("...")}`];
216
+ if (debug) {
217
+ if (shouldLog(currentLogLevel, "debug")) {
218
+ formatMemoryUsage(msg);
219
+ const lines = wordWrap(msg, loggerSys.getColumns());
220
+ debugPrefix(lines);
221
+ console.log(lines.join("\n"));
222
+ queueWriteLog("D", [`${startMsg} ...`]);
223
+ }
224
+ } else {
225
+ const lines = wordWrap(msg, loggerSys.getColumns());
226
+ infoPrefix(lines);
227
+ console.log(lines.join("\n"));
228
+ queueWriteLog("I", [`${startMsg} ...`]);
229
+ if (appendTo) appendTo.push(`${startMsg} ...`);
230
+ }
231
+ };
232
+ /**
233
+ * A little helper to (conditionally) format and add the current memory usage
234
+ *
235
+ * @param message an array to which the memory usage will be added
236
+ */
237
+ const formatMemoryUsage = (message) => {
238
+ const mem = loggerSys.memoryUsage();
239
+ if (mem > 0) message.push(dim(` MEM: ${(mem / 1e6).toFixed(1)}MB`));
240
+ };
241
+ const timespanFinish = (finishMsg, timeSuffix, colorName, textBold, newLineSuffix, debug, appendTo) => {
242
+ let msg = finishMsg;
243
+ if (colorName && chalkColors[colorName]) msg = chalkColors[colorName](finishMsg);
244
+ if (textBold) msg = bold(msg);
245
+ msg += " " + dim(timeSuffix);
246
+ if (debug) {
247
+ if (shouldLog(currentLogLevel, "debug")) {
248
+ const m = [msg];
249
+ formatMemoryUsage(m);
250
+ const lines = wordWrap(m, loggerSys.getColumns());
251
+ debugPrefix(lines);
252
+ console.log(lines.join("\n"));
253
+ }
254
+ queueWriteLog("D", [`${finishMsg} ${timeSuffix}`]);
255
+ } else {
256
+ const lines = wordWrap([msg], loggerSys.getColumns());
257
+ infoPrefix(lines);
258
+ console.log(lines.join("\n"));
259
+ queueWriteLog("I", [`${finishMsg} ${timeSuffix}`]);
260
+ if (appendTo) appendTo.push(`${finishMsg} ${timeSuffix}`);
261
+ }
262
+ if (newLineSuffix) console.log("");
263
+ };
264
+ const createTimeSpan = (startMsg, debug = false, appendTo) => {
265
+ const start = Date.now();
266
+ const duration = () => Date.now() - start;
267
+ const timeSpan = {
268
+ duration,
269
+ finish: (finishMsg, colorName, textBold, newLineSuffix) => {
270
+ const dur = duration();
271
+ let time;
272
+ if (dur > 1e3) time = "in " + (dur / 1e3).toFixed(2) + " s";
273
+ else if (parseFloat(dur.toFixed(3)) > 0) time = "in " + dur + " ms";
274
+ else time = "in less than 1 ms";
275
+ timespanFinish(finishMsg, time, colorName, !!textBold, !!newLineSuffix, debug, appendTo);
276
+ return dur;
277
+ }
278
+ };
279
+ timespanStart(startMsg, debug, appendTo);
280
+ return timeSpan;
281
+ };
282
+ const queueWriteLog = (prefix, msg) => {
283
+ if (logFilePath) {
284
+ const d = /* @__PURE__ */ new Date();
285
+ const log = "" + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2) + ":" + ("0" + d.getSeconds()).slice(-2) + "." + ("0" + Math.floor(d.getMilliseconds() / 1e3 * 10)) + " " + ("000" + (loggerSys.memoryUsage() / 1e6).toFixed(1)).slice(-6) + "MB " + prefix + " " + msg.join(", ");
286
+ writeLogQueue.push(log);
287
+ }
288
+ };
289
+ const writeLogs = (append) => {
290
+ if (logFilePath) try {
291
+ queueWriteLog("F", ["--------------------------------------"]);
292
+ loggerSys.writeLogs(logFilePath, writeLogQueue.join("\n"), append);
293
+ } catch (e) {}
294
+ writeLogQueue.length = 0;
295
+ };
296
+ /**
297
+ * Callback to enable / disable colored output in logs
298
+ * @param useColors whether to enable colors (chalk.level = 3) or disable (chalk.level = 0)
299
+ */
300
+ const enableColors = (useColors) => {
301
+ chalk.level = useColors ? 3 : 0;
302
+ };
303
+ /**
304
+ * Print all diagnostics to the console
305
+ * @param diagnostics the diagnostics to print
306
+ * @param cwd the current working directory
307
+ */
308
+ const printDiagnostics = (diagnostics, cwd) => {
309
+ if (!diagnostics || diagnostics.length === 0) return;
310
+ let outputLines = [""];
311
+ diagnostics.forEach((d) => {
312
+ outputLines = outputLines.concat(printDiagnostic(d, cwd));
313
+ });
314
+ console.log(outputLines.join("\n"));
315
+ };
316
+ /**
317
+ * Formats a single diagnostic to be printed
318
+ * @param diagnostic the diagnostic to prepare for printing
319
+ * @param cwd the current working directory
320
+ * @returns the message from the diagnostic, formatted and split into multiple lines
321
+ */
322
+ const printDiagnostic = (diagnostic, cwd) => {
323
+ const outputLines = wordWrap([diagnostic.messageText], loggerSys.getColumns());
324
+ let header = "";
325
+ if (diagnostic.header && diagnostic.header !== "Build Error") header += diagnostic.header;
326
+ if (typeof diagnostic.absFilePath === "string" && typeof diagnostic.relFilePath !== "string") {
327
+ if (typeof cwd !== "string") cwd = loggerSys.cwd();
328
+ diagnostic.relFilePath = loggerSys.relativePath(cwd, diagnostic.absFilePath);
329
+ if (!diagnostic.relFilePath.includes("/")) diagnostic.relFilePath = "./" + diagnostic.relFilePath;
330
+ }
331
+ let filePath = diagnostic.relFilePath;
332
+ if (typeof filePath !== "string") filePath = diagnostic.absFilePath;
333
+ if (typeof filePath === "string") {
334
+ if (header.length > 0) header += ": ";
335
+ header += cyan(filePath);
336
+ if (typeof diagnostic.lineNumber === "number" && diagnostic.lineNumber > -1) {
337
+ header += dim(`:`);
338
+ header += yellow(`${diagnostic.lineNumber}`);
339
+ if (typeof diagnostic.columnNumber === "number" && diagnostic.columnNumber > -1) {
340
+ header += dim(`:`);
341
+ header += yellow(`${diagnostic.columnNumber}`);
342
+ }
343
+ }
344
+ }
345
+ if (header.length > 0) outputLines.unshift(INDENT$1 + header);
346
+ outputLines.push("");
347
+ if (diagnostic.lines && diagnostic.lines.length) {
348
+ removeLeadingWhitespace(diagnostic.lines).forEach((l) => {
349
+ if (!isMeaningfulLine(l.text)) return;
350
+ let msg = ``;
351
+ if (l.lineNumber > -1) msg = `L${l.lineNumber}: `;
352
+ while (msg.length < INDENT$1.length) msg = " " + msg;
353
+ let text = l.text;
354
+ if (l.errorCharStart > -1) text = highlightError(text, l.errorCharStart, l.errorLength);
355
+ msg = dim(msg);
356
+ if (diagnostic.language === "typescript" || diagnostic.language === "javascript") msg += javaScriptSyntaxHighlight(text);
357
+ else if (diagnostic.language === "scss" || diagnostic.language === "css") msg += cssSyntaxHighlight(text);
358
+ else msg += text;
359
+ outputLines.push(msg);
360
+ });
361
+ outputLines.push("");
362
+ }
363
+ if (diagnostic.level === "error") errorPrefix(outputLines);
364
+ else if (diagnostic.level === "warn") warnPrefix(outputLines);
365
+ else if (diagnostic.level === "debug") debugPrefix(outputLines);
366
+ else infoPrefix(outputLines);
367
+ if (diagnostic.debugText != null && currentLogLevel === "debug") {
368
+ outputLines.push(diagnostic.debugText);
369
+ debugPrefix(wordWrap([diagnostic.debugText], loggerSys.getColumns()));
370
+ }
371
+ return outputLines;
372
+ };
373
+ /**
374
+ * Highlights an error
375
+ * @param errorLine the line containing the error
376
+ * @param errorCharStart the character at which the error starts
377
+ * @param errorLength the length of the error, how many characters should be highlighted
378
+ * @returns the highlighted error
379
+ */
380
+ const highlightError = (errorLine, errorCharStart, errorLength = 0) => {
381
+ let rightSideChars = errorLine.length - errorCharStart + errorLength - 1;
382
+ while (errorLine.length + INDENT$1.length > loggerSys.getColumns()) if (errorCharStart > errorLine.length - errorCharStart + errorLength && errorCharStart > 5) {
383
+ errorLine = errorLine.slice(1);
384
+ errorCharStart--;
385
+ } else if (rightSideChars > 1) {
386
+ errorLine = errorLine.slice(0, -1);
387
+ rightSideChars--;
388
+ } else break;
389
+ const lineChars = [];
390
+ const lineLength = Math.max(errorLine.length, errorCharStart + errorLength);
391
+ for (let i = 0; i < lineLength; i++) {
392
+ let chr = errorLine.charAt(i);
393
+ if (i >= errorCharStart && i < errorCharStart + errorLength) chr = bgRed(chr === "" ? " " : chr);
394
+ lineChars.push(chr);
395
+ }
396
+ return lineChars.join("");
397
+ };
398
+ /**
399
+ * Highlights JavaScript/TypeScript syntax, taking in text and selectively highlighting keywords from the language
400
+ * @param text the text to highlight
401
+ * @returns the text with highlighted JS/TS
402
+ */
403
+ const javaScriptSyntaxHighlight = (text) => {
404
+ if (text.trim().startsWith("//")) return dim(text);
405
+ return text.split(" ").map((word) => {
406
+ if (JS_KEYWORDS.indexOf(word) > -1) return cyan(word);
407
+ return word;
408
+ }).join(" ");
409
+ };
410
+ /**
411
+ * Highlights CSS syntax, taking in text and selectively highlighting keywords from the language
412
+ * @param text the text to highlight
413
+ * @returns the text with highlighted CSS
414
+ */
415
+ const cssSyntaxHighlight = (text) => {
416
+ let cssProp = true;
417
+ const safeChars = "abcdefghijklmnopqrstuvwxyz-_";
418
+ const notProp = ".#,:}@$[]/*";
419
+ const chars = [];
420
+ for (let i = 0; i < text.length; i++) {
421
+ const c = text.charAt(i);
422
+ if (c === ";" || c === "{") cssProp = true;
423
+ else if (notProp.indexOf(c) > -1) cssProp = false;
424
+ if (cssProp && safeChars.indexOf(c.toLowerCase()) > -1) {
425
+ chars.push(cyan(c));
426
+ continue;
427
+ }
428
+ chars.push(c);
429
+ }
430
+ return chars.join("");
431
+ };
432
+ return {
433
+ createLineUpdater: loggerSys.createLineUpdater,
434
+ createTimeSpan,
435
+ debug,
436
+ emoji: loggerSys.emoji,
437
+ enableColors,
438
+ error,
439
+ getLevel,
440
+ info,
441
+ printDiagnostics,
442
+ setLevel,
443
+ setLogFilePath,
444
+ warn,
445
+ writeLogs,
446
+ bgRed,
447
+ blue,
448
+ bold,
449
+ cyan,
450
+ dim,
451
+ gray,
452
+ green,
453
+ magenta,
454
+ red,
455
+ yellow
456
+ };
457
+ };
458
+ /**
459
+ * Helper function to determine, based on the current log level setting, whether
460
+ * a message at a given log level should be logged or not.
461
+ *
462
+ * @param currentSetting the current log level setting
463
+ * @param messageLevel the log level to check
464
+ * @returns whether we should log or not!
465
+ */
466
+ const shouldLog = (currentSetting, messageLevel) => LOG_LEVELS.indexOf(messageLevel) >= LOG_LEVELS.indexOf(currentSetting);
467
+ /**
468
+ * Format a simple timestamp string for log prefixes
469
+ *
470
+ * @returns a formatted timestamp
471
+ */
472
+ const formatPrefixTimestamp = () => {
473
+ const currentTime = /* @__PURE__ */ new Date();
474
+ return `[${clampTwoDigits(currentTime.getMinutes())}:${clampTwoDigits(currentTime.getSeconds())}.${Math.floor(currentTime.getMilliseconds() / 1e3 * 10)}]`;
475
+ };
476
+ /**
477
+ * Format a number as a string and clamp it to exactly
478
+ * two digits, e.g.
479
+ *
480
+ * ```ts
481
+ * clampTwoDigits(3) // '03'
482
+ * clampTwoDigits(14) // '14'
483
+ * clampTwoDigits(104) // '04'
484
+ * ```
485
+ *
486
+ * @param n the number to clamp
487
+ * @returns a formatted string
488
+ */
489
+ const clampTwoDigits = (n) => ("0" + n.toString()).slice(-2);
490
+ /**
491
+ * Helper function for word wrapping
492
+ * @param msg the message to wrap
493
+ * @param columns the maximum number of columns to occupy per line
494
+ * @returns the wrapped message
495
+ */
496
+ const wordWrap = (msg, columns) => {
497
+ const lines = [];
498
+ const words = [];
499
+ msg.forEach((m) => {
500
+ if (m === null) words.push("null");
501
+ else if (typeof m === "undefined") words.push("undefined");
502
+ else if (typeof m === "string") m.replace(/\s/gm, " ").split(" ").forEach((strWord) => {
503
+ if (strWord.trim().length) words.push(strWord.trim());
504
+ });
505
+ else if (typeof m === "number" || typeof m === "boolean" || typeof m === "function") words.push(m.toString());
506
+ else if (Array.isArray(m)) words.push(() => {
507
+ return m.toString();
508
+ });
509
+ else if (Object(m) === m) words.push(() => {
510
+ return m.toString();
511
+ });
512
+ else words.push(m.toString());
513
+ });
514
+ let line = INDENT$1;
515
+ words.forEach((word) => {
516
+ if (lines.length > 25) return;
517
+ if (typeof word === "function") {
518
+ if (line.trim().length) lines.push(line);
519
+ lines.push(word());
520
+ line = INDENT$1;
521
+ } else if (INDENT$1.length + word.length > columns - 1) {
522
+ if (line.trim().length) lines.push(line);
523
+ lines.push(INDENT$1 + word);
524
+ line = INDENT$1;
525
+ } else if (word.length + line.length > columns - 1) {
526
+ lines.push(line);
527
+ line = INDENT$1 + word + " ";
528
+ } else line += word + " ";
529
+ });
530
+ if (line.trim().length) lines.push(line);
531
+ return lines.map((line) => {
532
+ return line.trimRight();
533
+ });
534
+ };
535
+ /**
536
+ * Prepare the code associated with the error/warning to be logged by stripping variable length, leading whitespace
537
+ * @param orgLines the lines of code to log
538
+ * @returns the code, with leading whitespace stripped
539
+ */
540
+ const removeLeadingWhitespace = (orgLines) => {
541
+ const numberOfTries = 100;
542
+ const lines = JSON.parse(JSON.stringify(orgLines));
543
+ for (let i = 0; i < numberOfTries; i++) {
544
+ if (!eachLineHasLeadingWhitespace(lines)) return lines;
545
+ for (let i = 0; i < lines.length; i++) {
546
+ lines[i].text = lines[i].text.slice(1);
547
+ lines[i].errorCharStart--;
548
+ if (!lines[i].text.length) return lines;
549
+ }
550
+ }
551
+ return lines;
552
+ };
553
+ /**
554
+ * Determine if any of the provided lines begin with whitespace or not
555
+ * @param lines the lines to check for whitespace
556
+ * @returns true if each of the provided `lines` has some leading whitespace, false otherwise
557
+ */
558
+ const eachLineHasLeadingWhitespace = (lines) => {
559
+ if (!lines.length) return false;
560
+ for (let i = 0; i < lines.length; i++) {
561
+ if (!lines[i].text || lines[i].text.length < 1) return false;
562
+ const firstChar = lines[i].text.charAt(0);
563
+ if (firstChar !== " " && firstChar !== " ") return false;
564
+ }
565
+ return true;
566
+ };
567
+ /**
568
+ * Verify that a given line has more than just whitespace
569
+ * @param line the line to check
570
+ * @returns true if a line has characters other than whitespace in it, false otherwise
571
+ */
572
+ const isMeaningfulLine = (line) => {
573
+ if (line) {
574
+ line = line.trim();
575
+ return line.length > 0;
576
+ }
577
+ return false;
578
+ };
579
+ const JS_KEYWORDS = [
580
+ "abstract",
581
+ "any",
582
+ "as",
583
+ "break",
584
+ "boolean",
585
+ "case",
586
+ "catch",
587
+ "class",
588
+ "console",
589
+ "const",
590
+ "continue",
591
+ "debugger",
592
+ "declare",
593
+ "default",
594
+ "delete",
595
+ "do",
596
+ "else",
597
+ "enum",
598
+ "export",
599
+ "extends",
600
+ "false",
601
+ "finally",
602
+ "for",
603
+ "from",
604
+ "function",
605
+ "get",
606
+ "if",
607
+ "import",
608
+ "in",
609
+ "implements",
610
+ "Infinity",
611
+ "instanceof",
612
+ "let",
613
+ "module",
614
+ "namespace",
615
+ "NaN",
616
+ "new",
617
+ "number",
618
+ "null",
619
+ "public",
620
+ "private",
621
+ "protected",
622
+ "require",
623
+ "return",
624
+ "static",
625
+ "set",
626
+ "string",
627
+ "super",
628
+ "switch",
629
+ "this",
630
+ "throw",
631
+ "try",
632
+ "true",
633
+ "type",
634
+ "typeof",
635
+ "undefined",
636
+ "var",
637
+ "void",
638
+ "with",
639
+ "while",
640
+ "yield"
641
+ ];
642
+ /**
643
+ * This is used to prefix lines with whitespace which is then
644
+ * replaced by various prefixes like [ WARN ] and so on
645
+ */
646
+ const INDENT$1 = " ";
647
+
648
+ //#endregion
649
+ //#region src/sys/node/logger/index.ts
650
+ /**
651
+ * Create a logger to run in a Node environment
652
+ *
653
+ * @returns the created logger
654
+ */
655
+ const createNodeLogger = () => {
656
+ return createTerminalLogger(createNodeLoggerSys());
657
+ };
658
+ /**
659
+ * Create a logger sys object for use in a Node.js environment
660
+ *
661
+ * The `TerminalLoggerSys` interface basically abstracts away some
662
+ * environment-specific details so that the terminal logger can deal with
663
+ * things in a (potentially) platform-agnostic way.
664
+ *
665
+ * @returns a configured logger sys object
666
+ */
667
+ function createNodeLoggerSys() {
668
+ const cwd = () => process.cwd();
669
+ const emoji = (emoji) => process.platform !== "win32" ? emoji : "";
670
+ /**
671
+ * Get the number of columns for the terminal to use when printing
672
+ * @returns the number of columns to use
673
+ */
674
+ const getColumns = () => {
675
+ const min_columns = 60;
676
+ const max_columns = 120;
677
+ const terminalWidth = process?.stdout?.columns ?? 80;
678
+ return Math.max(Math.min(terminalWidth, max_columns), min_columns);
679
+ };
680
+ const memoryUsage = () => process.memoryUsage().rss;
681
+ const relativePath = (from, to) => path$1.relative(from, to);
682
+ const writeLogs = (logFilePath, log, append) => {
683
+ if (append) try {
684
+ fs.accessSync(logFilePath);
685
+ } catch (e) {
686
+ append = false;
687
+ }
688
+ if (append) fs.appendFileSync(logFilePath, log);
689
+ else fs.writeFileSync(logFilePath, log);
690
+ };
691
+ const createLineUpdater = async () => {
692
+ const readline = await import("readline");
693
+ let promise = Promise.resolve();
694
+ const update = (text) => {
695
+ text = text.substring(0, process.stdout.columns - 5) + "\x1B[0m";
696
+ return promise = promise.then(() => {
697
+ return new Promise((resolve) => {
698
+ readline.clearLine(process.stdout, 0);
699
+ readline.cursorTo(process.stdout, 0, void 0);
700
+ process.stdout.write(text, resolve);
701
+ });
702
+ });
703
+ };
704
+ const stop = () => {
705
+ return update("\x1B[?25h");
706
+ };
707
+ process.stdout.write("\x1B[?25l");
708
+ return {
709
+ update,
710
+ stop
711
+ };
712
+ };
713
+ return {
714
+ cwd,
715
+ emoji,
716
+ getColumns,
717
+ memoryUsage,
718
+ relativePath,
719
+ writeLogs,
720
+ createLineUpdater
721
+ };
722
+ }
723
+
724
+ //#endregion
725
+ //#region src/sys/node/node-setup-process.ts
726
+ function setupNodeProcess(c) {
727
+ c.process.on(`unhandledRejection`, (e) => {
728
+ if (!shouldIgnoreError(e)) {
729
+ let msg = "unhandledRejection";
730
+ if (e != null) {
731
+ if (typeof e === "string") msg += ": " + e;
732
+ else if (e.stack) msg += ": " + e.stack;
733
+ else if (e.message) msg += ": " + e.message;
734
+ }
735
+ c.logger.error(msg);
736
+ }
737
+ });
738
+ }
739
+
740
+ //#endregion
741
+ //#region src/sys/node/node-fs-promisify.ts
742
+ const copyFile = promisify(fs.copyFile);
743
+ const mkdir = promisify(fs.mkdir);
744
+ const readdir = promisify(fs.readdir);
745
+ const readFile = promisify(fs.readFile);
746
+ const stat = promisify(fs.stat);
747
+
748
+ //#endregion
749
+ //#region src/sys/node/node-copy-tasks.ts
750
+ async function nodeCopyTasks(copyTasks, srcDir) {
751
+ const results = {
752
+ diagnostics: [],
753
+ dirPaths: [],
754
+ filePaths: []
755
+ };
756
+ try {
757
+ copyTasks = flatOne(await Promise.all(copyTasks.map((task) => processGlobs(task, srcDir))));
758
+ const allCopyTasks = [];
759
+ while (copyTasks.length > 0) {
760
+ const tasks = copyTasks.splice(0, 100);
761
+ await Promise.all(tasks.map((copyTask) => processCopyTask(results, allCopyTasks, copyTask)));
762
+ }
763
+ const mkDirs = ensureDirs(allCopyTasks);
764
+ try {
765
+ await Promise.all(mkDirs.map((dir) => mkdir(dir, { recursive: true })));
766
+ } catch (mkDirErr) {}
767
+ while (allCopyTasks.length > 0) {
768
+ const tasks = allCopyTasks.splice(0, 100);
769
+ await Promise.all(tasks.map((copyTask) => copyFile(copyTask.src, copyTask.dest)));
770
+ }
771
+ } catch (e) {
772
+ catchError(results.diagnostics, e);
773
+ }
774
+ return results;
775
+ }
776
+ async function processGlobs(copyTask, srcDir) {
777
+ return isGlob(copyTask.src) ? await processGlobTask(copyTask, srcDir) : [{
778
+ src: getSrcAbsPath(srcDir, copyTask.src),
779
+ dest: copyTask.keepDirStructure ? path$1.join(copyTask.dest, copyTask.src) : copyTask.dest,
780
+ warn: copyTask.warn,
781
+ ignore: copyTask.ignore,
782
+ keepDirStructure: copyTask.keepDirStructure
783
+ }];
784
+ }
785
+ function getSrcAbsPath(srcDir, src) {
786
+ if (path$1.isAbsolute(src)) return src;
787
+ return path$1.join(srcDir, src);
788
+ }
789
+ async function processGlobTask(copyTask, srcDir) {
790
+ return (await asyncGlob(copyTask.src, {
791
+ cwd: srcDir,
792
+ nodir: true,
793
+ ignore: copyTask.ignore
794
+ })).map((globRelPath) => createGlobCopyTask(copyTask, srcDir, globRelPath));
795
+ }
796
+ function createGlobCopyTask(copyTask, srcDir, globRelPath) {
797
+ const dest = path$1.join(copyTask.dest, copyTask.keepDirStructure ? globRelPath : path$1.basename(globRelPath));
798
+ return {
799
+ src: path$1.join(srcDir, globRelPath),
800
+ dest,
801
+ ignore: copyTask.ignore,
802
+ warn: copyTask.warn,
803
+ keepDirStructure: copyTask.keepDirStructure
804
+ };
805
+ }
806
+ async function processCopyTask(results, allCopyTasks, copyTask) {
807
+ try {
808
+ copyTask.src = normalizePath(copyTask.src);
809
+ copyTask.dest = normalizePath(copyTask.dest);
810
+ if ((await stat(copyTask.src)).isDirectory()) {
811
+ if (!results.dirPaths.includes(copyTask.dest)) results.dirPaths.push(copyTask.dest);
812
+ await processCopyTaskDirectory(results, allCopyTasks, copyTask);
813
+ } else if (!shouldIgnore(copyTask)) {
814
+ if (!results.filePaths.includes(copyTask.dest)) results.filePaths.push(copyTask.dest);
815
+ allCopyTasks.push(copyTask);
816
+ }
817
+ } catch (e) {
818
+ if (copyTask.warn !== false) {
819
+ const err = buildError(results.diagnostics);
820
+ if (e instanceof Error) err.messageText = e.message;
821
+ }
822
+ }
823
+ }
824
+ async function processCopyTaskDirectory(results, allCopyTasks, copyTask) {
825
+ try {
826
+ const dirItems = await readdir(copyTask.src);
827
+ await Promise.all(dirItems.map(async (dirItem) => {
828
+ await processCopyTask(results, allCopyTasks, {
829
+ src: path$1.join(copyTask.src, dirItem),
830
+ dest: path$1.join(copyTask.dest, dirItem),
831
+ warn: copyTask.warn
832
+ });
833
+ }));
834
+ } catch (e) {
835
+ catchError(results.diagnostics, e);
836
+ }
837
+ }
838
+ function ensureDirs(copyTasks) {
839
+ const mkDirs = [];
840
+ copyTasks.forEach((copyTask) => {
841
+ addMkDir(mkDirs, path$1.dirname(copyTask.dest));
842
+ });
843
+ mkDirs.sort((a, b) => {
844
+ const partsA = a.split("/").length;
845
+ const partsB = b.split("/").length;
846
+ if (partsA < partsB) return -1;
847
+ if (partsA > partsB) return 1;
848
+ if (a < b) return -1;
849
+ if (a > b) return 1;
850
+ return 0;
851
+ });
852
+ return mkDirs;
853
+ }
854
+ function addMkDir(mkDirs, destDir) {
855
+ destDir = normalizePath(destDir);
856
+ if (destDir === ROOT_DIR || destDir + "/" === ROOT_DIR || destDir === "") return;
857
+ if (!mkDirs.includes(destDir)) mkDirs.push(destDir);
858
+ }
859
+ const ROOT_DIR = normalizePath(path$1.resolve("/"));
860
+ function shouldIgnore({ src, ignore = [] }) {
861
+ const filePath = src.trim().toLowerCase();
862
+ return ignore.some((ignoreFile) => filePath.endsWith(ignoreFile));
863
+ }
864
+ function asyncGlob(pattern, opts) {
865
+ return glob(pattern, opts);
866
+ }
867
+
868
+ //#endregion
869
+ //#region src/sys/node/node-lazy-require.ts
870
+ /**
871
+ * Lazy requirer for Node, with functionality for specifying version ranges and
872
+ * returning diagnostic errors if requirements aren't met.
873
+ */
874
+ var NodeLazyRequire = class {
875
+ ensured = /* @__PURE__ */ new Set();
876
+ /**
877
+ * Create a NodeLazyRequire instance
878
+ *
879
+ * @param nodeResolveModule an object which wraps up module resolution functionality
880
+ * @param lazyDependencies the dependency requirements we want to enforce here
881
+ */
882
+ constructor(nodeResolveModule, lazyDependencies) {
883
+ this.nodeResolveModule = nodeResolveModule;
884
+ this.lazyDependencies = lazyDependencies;
885
+ }
886
+ /**
887
+ * Ensure that a dependency within our supported range is installed in the
888
+ * current environment. This function will check all the dependency
889
+ * requirements passed in when the class is instantiated and return
890
+ * diagnostics if there are any issues.
891
+ *
892
+ * @param fromDir the directory from which we'll attempt to resolve the
893
+ * dependencies, typically this will be project's root directory.
894
+ * @param ensureModuleIds an array of module names whose versions we're going
895
+ * to check
896
+ * @returns a Promise holding diagnostics if any of the dependencies either
897
+ * were not resolved _or_ did not meet our version requirements.
898
+ */
899
+ async ensure(fromDir, ensureModuleIds) {
900
+ const diagnostics = [];
901
+ const problemDeps = [];
902
+ ensureModuleIds.forEach((ensureModuleId) => {
903
+ if (!this.ensured.has(ensureModuleId)) {
904
+ const { minVersion, recommendedVersion, maxVersion } = this.lazyDependencies[ensureModuleId];
905
+ try {
906
+ const pkgJsonPath = this.nodeResolveModule.resolveModule(fromDir, ensureModuleId);
907
+ const installedPkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8"));
908
+ if (maxVersion ? satisfies(installedPkgJson.version, `${minVersion} - ${major(maxVersion)}.x`) : semverLte(minVersion, installedPkgJson.version)) {
909
+ this.ensured.add(ensureModuleId);
910
+ return;
911
+ }
912
+ } catch (e) {}
913
+ problemDeps.push(`${ensureModuleId}@${recommendedVersion}`);
914
+ }
915
+ });
916
+ if (problemDeps.length > 0) {
917
+ const err = buildError(diagnostics);
918
+ err.header = `Please install supported versions of dev dependencies with either npm or yarn.`;
919
+ err.messageText = `npm install --save-dev ${problemDeps.join(" ")}`;
920
+ }
921
+ return diagnostics;
922
+ }
923
+ require(fromDir, moduleId) {
924
+ const modulePath = this.getModulePath(fromDir, moduleId);
925
+ return __require(modulePath);
926
+ }
927
+ getModulePath(fromDir, moduleId) {
928
+ const modulePath = this.nodeResolveModule.resolveModule(fromDir, moduleId);
929
+ return path$1.dirname(modulePath);
930
+ }
931
+ };
932
+
933
+ //#endregion
934
+ //#region src/sys/node/node-resolve-module.ts
935
+ var NodeResolveModule = class {
936
+ resolveModuleCache = /* @__PURE__ */ new Map();
937
+ resolveModule(fromDir, moduleId, opts) {
938
+ const cacheKey = `${fromDir}:${moduleId}`;
939
+ const cachedPath = this.resolveModuleCache.get(cacheKey);
940
+ if (cachedPath) return cachedPath;
941
+ if (opts && opts.manuallyResolve) return this.resolveModuleManually(fromDir, moduleId, cacheKey);
942
+ if (moduleId.startsWith("@types/")) return this.resolveTypesModule(fromDir, moduleId, cacheKey);
943
+ const Module = __require("module");
944
+ fromDir = path$1.resolve(fromDir);
945
+ const fromFile = path$1.join(fromDir, "noop.js");
946
+ let dir = normalizePath(Module._resolveFilename(moduleId, {
947
+ id: fromFile,
948
+ filename: fromFile,
949
+ paths: Module._nodeModulePaths(fromDir)
950
+ }));
951
+ const root = normalizePath(path$1.parse(fromDir).root);
952
+ let packageJsonFilePath;
953
+ while (dir !== root) {
954
+ dir = normalizePath(path$1.dirname(dir));
955
+ packageJsonFilePath = path$1.join(dir, "package.json");
956
+ if (!fs.existsSync(packageJsonFilePath)) continue;
957
+ this.resolveModuleCache.set(cacheKey, packageJsonFilePath);
958
+ return packageJsonFilePath;
959
+ }
960
+ throw new Error(`error loading "${moduleId}" from "${fromDir}"`);
961
+ }
962
+ resolveTypesModule(fromDir, moduleId, cacheKey) {
963
+ const moduleSplt = moduleId.split("/");
964
+ const root = normalizePath(path$1.parse(fromDir).root);
965
+ let dir = normalizePath(path$1.join(fromDir, "noop.js"));
966
+ let typesPackageJsonFilePath;
967
+ while (dir !== root) {
968
+ dir = normalizePath(path$1.dirname(dir));
969
+ typesPackageJsonFilePath = path$1.join(dir, "node_modules", moduleSplt[0], moduleSplt[1], "package.json");
970
+ if (!fs.existsSync(typesPackageJsonFilePath)) continue;
971
+ this.resolveModuleCache.set(cacheKey, typesPackageJsonFilePath);
972
+ return typesPackageJsonFilePath;
973
+ }
974
+ throw new Error(`error loading "${moduleId}" from "${fromDir}"`);
975
+ }
976
+ resolveModuleManually(fromDir, moduleId, cacheKey) {
977
+ const root = normalizePath(path$1.parse(fromDir).root);
978
+ let dir = normalizePath(path$1.join(fromDir, "noop.js"));
979
+ let packageJsonFilePath;
980
+ while (dir !== root) {
981
+ dir = normalizePath(path$1.dirname(dir));
982
+ packageJsonFilePath = path$1.join(dir, "node_modules", moduleId, "package.json");
983
+ if (!fs.existsSync(packageJsonFilePath)) continue;
984
+ this.resolveModuleCache.set(cacheKey, packageJsonFilePath);
985
+ return packageJsonFilePath;
986
+ }
987
+ throw new Error(`error loading "${moduleId}" from "${fromDir}"`);
988
+ }
989
+ };
990
+
991
+ //#endregion
992
+ //#region src/sys/node/node-stencil-version-checker.ts
993
+ const REGISTRY_URL = `https://registry.npmjs.org/@stencil/core`;
994
+ const CHECK_INTERVAL = 1e3 * 60 * 60 * 24 * 7;
995
+ const CHANGELOG = `https://github.com/stenciljs/core/blob/main/CHANGELOG.md`;
996
+ async function checkVersion(logger, currentVersion) {
997
+ try {
998
+ const latestVersion = await getLatestCompilerVersion(logger);
999
+ if (latestVersion != null) return () => {
1000
+ if (semverLt(currentVersion, latestVersion)) printUpdateMessage(logger, currentVersion, latestVersion);
1001
+ else console.debug(`${logger.cyan("@stencil/core")} version ${logger.green(currentVersion)} is the latest version`);
1002
+ };
1003
+ } catch (e) {
1004
+ logger.debug(`unable to load latest compiler version: ${e}`);
1005
+ }
1006
+ return noop;
1007
+ }
1008
+ async function getLatestCompilerVersion(logger) {
1009
+ try {
1010
+ const lastCheck = await getLastCheck();
1011
+ if (lastCheck == null) {
1012
+ setLastCheck();
1013
+ return null;
1014
+ }
1015
+ if (!requiresCheck(Date.now(), lastCheck, CHECK_INTERVAL)) return null;
1016
+ const setPromise = setLastCheck();
1017
+ const body = await requestUrl(REGISTRY_URL);
1018
+ const data = JSON.parse(body);
1019
+ await setPromise;
1020
+ return data["dist-tags"].latest;
1021
+ } catch (e) {
1022
+ logger.debug(`getLatestCompilerVersion error: ${e}`);
1023
+ }
1024
+ return null;
1025
+ }
1026
+ async function requestUrl(url) {
1027
+ const https = await import("https");
1028
+ return new Promise((resolve, reject) => {
1029
+ const req = https.request(url, (res) => {
1030
+ if (res.statusCode > 299) {
1031
+ reject(`url: ${url}, staus: ${res.statusCode}`);
1032
+ return;
1033
+ }
1034
+ res.once("error", reject);
1035
+ const ret = [];
1036
+ res.once("end", () => {
1037
+ resolve(ret.join(""));
1038
+ });
1039
+ res.on("data", (data) => {
1040
+ ret.push(data);
1041
+ });
1042
+ });
1043
+ req.once("error", reject);
1044
+ req.end();
1045
+ });
1046
+ }
1047
+ function requiresCheck(now, lastCheck, checkInterval) {
1048
+ return lastCheck + checkInterval < now;
1049
+ }
1050
+ function getLastCheck() {
1051
+ return new Promise((resolve) => {
1052
+ fs.readFile(getLastCheckStoragePath(), "utf8", (err, data) => {
1053
+ if (!err && isString(data)) try {
1054
+ resolve(JSON.parse(data));
1055
+ } catch (e) {}
1056
+ resolve(null);
1057
+ });
1058
+ });
1059
+ }
1060
+ function setLastCheck() {
1061
+ return new Promise((resolve) => {
1062
+ const now = JSON.stringify(Date.now());
1063
+ fs.writeFile(getLastCheckStoragePath(), now, () => {
1064
+ resolve();
1065
+ });
1066
+ });
1067
+ }
1068
+ function getLastCheckStoragePath() {
1069
+ return path$1.join(tmpdir$1(), "stencil_last_version_node.json");
1070
+ }
1071
+ function printUpdateMessage(logger, currentVersion, latestVersion) {
1072
+ const installMessage = `npm install @stencil/core`;
1073
+ const msg = [
1074
+ `Update available: ${currentVersion} ${ARROW} ${latestVersion}`,
1075
+ `To get the latest, please run:`,
1076
+ installMessage,
1077
+ CHANGELOG
1078
+ ];
1079
+ const lineLength = msg.reduce((longest, line) => line.length > longest ? line.length : longest, 0);
1080
+ const o = [];
1081
+ let top = BOX_TOP_LEFT;
1082
+ while (top.length <= lineLength + PADDING * 2) top += BOX_HORIZONTAL;
1083
+ top += BOX_TOP_RIGHT;
1084
+ o.push(top);
1085
+ msg.forEach((m) => {
1086
+ let line = BOX_VERTICAL;
1087
+ for (let i = 0; i < PADDING; i++) line += ` `;
1088
+ line += m;
1089
+ while (line.length <= lineLength + PADDING * 2) line += ` `;
1090
+ line += BOX_VERTICAL;
1091
+ o.push(line);
1092
+ });
1093
+ let bottom = BOX_BOTTOM_LEFT;
1094
+ while (bottom.length <= lineLength + PADDING * 2) bottom += BOX_HORIZONTAL;
1095
+ bottom += BOX_BOTTOM_RIGHT;
1096
+ o.push(bottom);
1097
+ let output = `${INDENT}${o.join(`\n${INDENT}`)}\n`;
1098
+ output = output.replace(currentVersion, logger.red(currentVersion));
1099
+ output = output.replace(latestVersion, logger.green(latestVersion));
1100
+ output = output.replace(installMessage, logger.cyan(installMessage));
1101
+ output = output.replace(CHANGELOG, logger.dim(CHANGELOG));
1102
+ console.log(output);
1103
+ }
1104
+ const ARROW = `→`;
1105
+ const BOX_TOP_LEFT = `╭`;
1106
+ const BOX_TOP_RIGHT = `╮`;
1107
+ const BOX_BOTTOM_LEFT = `╰`;
1108
+ const BOX_BOTTOM_RIGHT = `╯`;
1109
+ const BOX_VERTICAL = `│`;
1110
+ const BOX_HORIZONTAL = `─`;
1111
+ const PADDING = 2;
1112
+ const INDENT = ` `;
1113
+
1114
+ //#endregion
1115
+ //#region src/sys/node/node-worker-main.ts
1116
+ /**
1117
+ * A class that holds a reference to a node worker sub-process within the main
1118
+ * thread so that messages may be passed to it.
1119
+ */
1120
+ var NodeWorkerMain = class extends EventEmitter {
1121
+ /**
1122
+ * A handle for the OS process that is running our worker code
1123
+ */
1124
+ childProcess;
1125
+ tasks = /* @__PURE__ */ new Map();
1126
+ exitCode = null;
1127
+ processQueue = true;
1128
+ sendQueue = [];
1129
+ stopped = false;
1130
+ successfulMessage = false;
1131
+ totalTasksAssigned = 0;
1132
+ /**
1133
+ * Create an object for holding and interacting with a reference to a worker
1134
+ * child-process.
1135
+ *
1136
+ * @param id a unique ID
1137
+ * @param forkModulePath the path to the module which should be run by the
1138
+ * child process
1139
+ */
1140
+ constructor(id, forkModulePath) {
1141
+ super();
1142
+ this.id = id;
1143
+ this.fork(forkModulePath);
1144
+ }
1145
+ fork(forkModulePath) {
1146
+ const options = {
1147
+ execArgv: process.execArgv.filter((v) => !/^--(debug|inspect)/.test(v)),
1148
+ env: process.env,
1149
+ cwd: process.cwd(),
1150
+ silent: true
1151
+ };
1152
+ this.childProcess = cp.fork(forkModulePath, [], options);
1153
+ this.childProcess.stdout.setEncoding("utf8");
1154
+ this.childProcess.stdout.on("data", (data) => {
1155
+ console.log(data);
1156
+ });
1157
+ this.childProcess.stderr.setEncoding("utf8");
1158
+ this.childProcess.stderr.on("data", (data) => {
1159
+ console.log(data);
1160
+ });
1161
+ this.childProcess.on("message", this.receiveFromWorker.bind(this));
1162
+ this.childProcess.on("error", (err) => {
1163
+ this.emit("error", err);
1164
+ });
1165
+ this.childProcess.once("exit", (code) => {
1166
+ this.exitCode = code;
1167
+ this.emit("exit", code);
1168
+ });
1169
+ }
1170
+ run(task) {
1171
+ this.totalTasksAssigned++;
1172
+ this.tasks.set(task.stencilId, task);
1173
+ const [method, ...args] = task.inputArgs;
1174
+ this.sendToWorker({
1175
+ stencilId: task.stencilId,
1176
+ method,
1177
+ args
1178
+ });
1179
+ }
1180
+ sendToWorker(msg) {
1181
+ if (!this.processQueue) {
1182
+ this.sendQueue.push(msg);
1183
+ return;
1184
+ }
1185
+ if (!this.childProcess.send(msg, (error) => {
1186
+ if (error && error instanceof Error) return;
1187
+ this.processQueue = true;
1188
+ if (this.sendQueue.length > 0) {
1189
+ const queueCopy = this.sendQueue.slice();
1190
+ this.sendQueue = [];
1191
+ queueCopy.forEach((d) => this.sendToWorker(d));
1192
+ }
1193
+ }) || /^win/.test(process.platform)) this.processQueue = false;
1194
+ }
1195
+ receiveFromWorker(msgFromWorker) {
1196
+ this.successfulMessage = true;
1197
+ if (this.stopped) return;
1198
+ const task = this.tasks.get(msgFromWorker.stencilId);
1199
+ if (!task) {
1200
+ if (msgFromWorker.stencilRtnError != null) this.emit("error", msgFromWorker.stencilRtnError);
1201
+ return;
1202
+ }
1203
+ if (msgFromWorker.stencilRtnError != null) task.reject(msgFromWorker.stencilRtnError);
1204
+ else task.resolve(msgFromWorker.stencilRtnValue);
1205
+ this.tasks.delete(msgFromWorker.stencilId);
1206
+ this.emit("response", msgFromWorker);
1207
+ }
1208
+ stop() {
1209
+ this.stopped = true;
1210
+ this.tasks.forEach((t) => t.reject(TASK_CANCELED_MSG));
1211
+ this.tasks.clear();
1212
+ if (this.successfulMessage) {
1213
+ this.childProcess.send({ exit: true });
1214
+ setTimeout(() => {
1215
+ if (this.exitCode === null) this.childProcess.kill("SIGKILL");
1216
+ }, 100);
1217
+ } else this.childProcess.kill("SIGKILL");
1218
+ }
1219
+ };
1220
+
1221
+ //#endregion
1222
+ //#region src/sys/node/node-worker-controller.ts
1223
+ /**
1224
+ * A custom EventEmitter which provides centralizes dispatching and control for
1225
+ * node.js workers ({@link NodeWorkerMain} instances)
1226
+ */
1227
+ var NodeWorkerController = class extends EventEmitter {
1228
+ workerIds = 0;
1229
+ stencilId = 0;
1230
+ isEnding = false;
1231
+ taskQueue = [];
1232
+ workers = [];
1233
+ maxWorkers;
1234
+ useForkedWorkers;
1235
+ mainThreadRunner;
1236
+ /**
1237
+ * Create a node.js-specific worker controller, which controls and
1238
+ * coordinates distributing tasks to a series of child processes (tracked by
1239
+ * {@link NodeWorkerMain} instances). These child processes are node
1240
+ * processes executing a special worker script (`src/sys/node/worker.ts`)
1241
+ * which listens for {@link d.MsgToWorker} messages and runs certain tasks in
1242
+ * response.
1243
+ *
1244
+ * @param forkModulePath the path to the module which k
1245
+ * @param maxConcurrentWorkers the max number of worker threads to spin up
1246
+ */
1247
+ constructor(forkModulePath, maxConcurrentWorkers) {
1248
+ super();
1249
+ this.forkModulePath = forkModulePath;
1250
+ const osCpus = cpus$1().length;
1251
+ this.useForkedWorkers = maxConcurrentWorkers > 0;
1252
+ this.maxWorkers = Math.max(Math.min(maxConcurrentWorkers, osCpus), 2) - 1;
1253
+ if (this.useForkedWorkers) this.startWorkers();
1254
+ else this.mainThreadRunner = __require(forkModulePath);
1255
+ }
1256
+ onError(err, workerId) {
1257
+ if (err.code === "ERR_IPC_CHANNEL_CLOSED") return this.stopWorker(workerId);
1258
+ if (err.code !== "EPIPE") console.error(err);
1259
+ }
1260
+ onExit(workerId) {
1261
+ setTimeout(() => {
1262
+ let doQueue = false;
1263
+ const worker = this.workers.find((w) => w.id === workerId);
1264
+ if (worker) {
1265
+ worker.tasks.forEach((t) => {
1266
+ t.retries++;
1267
+ this.taskQueue.unshift(t);
1268
+ doQueue = true;
1269
+ });
1270
+ worker.tasks.clear();
1271
+ }
1272
+ this.stopWorker(workerId);
1273
+ if (doQueue) this.processTaskQueue();
1274
+ }, 10);
1275
+ }
1276
+ startWorkers() {
1277
+ while (this.workers.length < this.maxWorkers) this.startWorker();
1278
+ }
1279
+ startWorker() {
1280
+ const workerId = this.workerIds++;
1281
+ const worker = new NodeWorkerMain(workerId, this.forkModulePath);
1282
+ worker.on("response", this.processTaskQueue.bind(this));
1283
+ worker.once("exit", () => {
1284
+ this.onExit(workerId);
1285
+ });
1286
+ worker.on("error", (err) => {
1287
+ this.onError(err, workerId);
1288
+ });
1289
+ this.workers.push(worker);
1290
+ }
1291
+ stopWorker(workerId) {
1292
+ const worker = this.workers.find((w) => w.id === workerId);
1293
+ if (worker) {
1294
+ worker.stop();
1295
+ const index = this.workers.indexOf(worker);
1296
+ if (index > -1) this.workers.splice(index, 1);
1297
+ }
1298
+ }
1299
+ processTaskQueue() {
1300
+ if (this.isEnding) return;
1301
+ if (this.useForkedWorkers) this.startWorkers();
1302
+ while (this.taskQueue.length > 0) {
1303
+ const worker = getNextWorker(this.workers);
1304
+ if (!worker) break;
1305
+ worker.run(this.taskQueue.shift());
1306
+ }
1307
+ }
1308
+ send(...args) {
1309
+ if (this.isEnding) return Promise.reject(TASK_CANCELED_MSG);
1310
+ if (this.useForkedWorkers) return new Promise((resolve, reject) => {
1311
+ const task = {
1312
+ stencilId: this.stencilId++,
1313
+ inputArgs: args,
1314
+ retries: 0,
1315
+ resolve,
1316
+ reject
1317
+ };
1318
+ this.taskQueue.push(task);
1319
+ this.processTaskQueue();
1320
+ });
1321
+ return this.mainThreadRunner[args[0]].apply(null, args.slice(1));
1322
+ }
1323
+ handler(name) {
1324
+ return (...args) => {
1325
+ return this.send(name, ...args);
1326
+ };
1327
+ }
1328
+ cancelTasks() {
1329
+ for (const worker of this.workers) {
1330
+ worker.tasks.forEach((t) => t.reject(TASK_CANCELED_MSG));
1331
+ worker.tasks.clear();
1332
+ }
1333
+ this.taskQueue.length = 0;
1334
+ }
1335
+ destroy() {
1336
+ if (!this.isEnding) {
1337
+ this.isEnding = true;
1338
+ for (const task of this.taskQueue) task.reject(TASK_CANCELED_MSG);
1339
+ this.taskQueue.length = 0;
1340
+ const workerIds = this.workers.map((w) => w.id);
1341
+ for (const workerId of workerIds) this.stopWorker(workerId);
1342
+ }
1343
+ }
1344
+ };
1345
+ function getNextWorker(workers) {
1346
+ const availableWorkers = workers.filter((w) => {
1347
+ if (w.stopped) return false;
1348
+ return true;
1349
+ });
1350
+ if (availableWorkers.length === 0) return null;
1351
+ return availableWorkers.sort((a, b) => {
1352
+ if (a.tasks.size < b.tasks.size) return -1;
1353
+ if (a.tasks.size > b.tasks.size) return 1;
1354
+ if (a.totalTasksAssigned < b.totalTasksAssigned) return -1;
1355
+ if (a.totalTasksAssigned > b.totalTasksAssigned) return 1;
1356
+ return 0;
1357
+ })[0];
1358
+ }
1359
+
1360
+ //#endregion
1361
+ //#region src/sys/node/node-sys.ts
1362
+ const __dirname = import.meta.dirname;
1363
+ /**
1364
+ * Create a node.js-specific {@link CompilerSystem} to be used when Stencil is
1365
+ * run from the CLI or via the public API in a node context.
1366
+ *
1367
+ * This takes an optional param supplying a `process` object to be used.
1368
+ *
1369
+ * @param c an optional object wrapping `process` and `logger` objects
1370
+ * @returns a node.js `CompilerSystem` object
1371
+ */
1372
+ function createNodeSys(c = {}) {
1373
+ const prcs = c?.process ?? global.process;
1374
+ const logger = c?.logger;
1375
+ const destroys = /* @__PURE__ */ new Set();
1376
+ const onInterruptsCallbacks = [];
1377
+ const sysCpus = cpus();
1378
+ const hardwareConcurrency = sysCpus.length;
1379
+ const osPlatform = platform();
1380
+ const compilerExecutingPath = path.join(__dirname, "compiler", "index.mjs");
1381
+ const runInterruptsCallbacks = () => {
1382
+ const returnValues = [];
1383
+ let cb;
1384
+ while (isFunction(cb = onInterruptsCallbacks.pop())) try {
1385
+ const rtn = cb();
1386
+ returnValues.push(rtn);
1387
+ } catch (e) {}
1388
+ return Promise.all(returnValues).then(() => {});
1389
+ };
1390
+ const sys = {
1391
+ name: "node",
1392
+ version: prcs.versions.node,
1393
+ access(p) {
1394
+ return new Promise((resolve) => {
1395
+ fs.access(p, (err) => resolve(!err));
1396
+ });
1397
+ },
1398
+ accessSync(p) {
1399
+ let hasAccess = false;
1400
+ try {
1401
+ fs.accessSync(p);
1402
+ hasAccess = true;
1403
+ } catch (e) {}
1404
+ return hasAccess;
1405
+ },
1406
+ addDestroy(cb) {
1407
+ destroys.add(cb);
1408
+ },
1409
+ removeDestroy(cb) {
1410
+ destroys.delete(cb);
1411
+ },
1412
+ applyPrerenderGlobalPatch(opts) {
1413
+ if (typeof global.fetch !== "function") {
1414
+ const nodeFetch = __require(path.join(__dirname, "node-fetch.js"));
1415
+ global.fetch = (input, init) => {
1416
+ if (typeof input === "string") {
1417
+ const urlStr = new URL(input, opts.devServerHostUrl).href;
1418
+ return nodeFetch.fetch(urlStr, init);
1419
+ } else {
1420
+ input.url = new URL(input.url, opts.devServerHostUrl).href;
1421
+ return nodeFetch.fetch(input, init);
1422
+ }
1423
+ };
1424
+ global.Headers = nodeFetch.Headers;
1425
+ global.Request = nodeFetch.Request;
1426
+ global.Response = nodeFetch.Response;
1427
+ global.FetchError = nodeFetch.FetchError;
1428
+ }
1429
+ opts.window.fetch = global.fetch;
1430
+ opts.window.Headers = global.Headers;
1431
+ opts.window.Request = global.Request;
1432
+ opts.window.Response = global.Response;
1433
+ opts.window.FetchError = global.FetchError;
1434
+ },
1435
+ fetch: (input, init) => {
1436
+ const nodeFetch = __require(path.join(__dirname, "node-fetch.js"));
1437
+ if (typeof input === "string") {
1438
+ const urlStr = new URL(input).href;
1439
+ return nodeFetch.fetch(urlStr, init);
1440
+ } else {
1441
+ input.url = new URL(input.url).href;
1442
+ return nodeFetch.fetch(input, init);
1443
+ }
1444
+ },
1445
+ checkVersion,
1446
+ copyFile(src, dst) {
1447
+ return new Promise((resolve) => {
1448
+ fs.copyFile(src, dst, (err) => {
1449
+ resolve(!err);
1450
+ });
1451
+ });
1452
+ },
1453
+ createDir(p, opts) {
1454
+ return new Promise((resolve) => {
1455
+ if (opts) fs.mkdir(p, opts, (err) => {
1456
+ resolve({
1457
+ basename: path.basename(p),
1458
+ dirname: path.dirname(p),
1459
+ path: p,
1460
+ newDirs: [],
1461
+ error: err
1462
+ });
1463
+ });
1464
+ else fs.mkdir(p, (err) => {
1465
+ resolve({
1466
+ basename: path.basename(p),
1467
+ dirname: path.dirname(p),
1468
+ path: p,
1469
+ newDirs: [],
1470
+ error: err
1471
+ });
1472
+ });
1473
+ });
1474
+ },
1475
+ createDirSync(p, opts) {
1476
+ const results = {
1477
+ basename: path.basename(p),
1478
+ dirname: path.dirname(p),
1479
+ path: p,
1480
+ newDirs: [],
1481
+ error: null
1482
+ };
1483
+ try {
1484
+ fs.mkdirSync(p, opts);
1485
+ } catch (e) {
1486
+ results.error = e;
1487
+ }
1488
+ return results;
1489
+ },
1490
+ createWorkerController(maxConcurrentWorkers) {
1491
+ return new NodeWorkerController(path.join(__dirname, "sys", "node", "worker.mjs"), maxConcurrentWorkers);
1492
+ },
1493
+ async destroy() {
1494
+ const waits = [];
1495
+ destroys.forEach((cb) => {
1496
+ try {
1497
+ const rtn = cb();
1498
+ if (rtn && typeof rtn.then === "function") waits.push(rtn);
1499
+ } catch (e) {
1500
+ console.error(`node sys destroy: ${e}`);
1501
+ }
1502
+ });
1503
+ if (waits.length > 0) await Promise.all(waits);
1504
+ destroys.clear();
1505
+ },
1506
+ dynamicImport(p) {
1507
+ return Promise.resolve(__require(p));
1508
+ },
1509
+ encodeToBase64(str) {
1510
+ return Buffer.from(str).toString("base64");
1511
+ },
1512
+ async ensureDependencies() {
1513
+ console.warn(`ensureDependencies will be removed in a future version of Stencil.`);
1514
+ console.warn(`To get the stencilPath, please use getCompilerExecutingPath().`);
1515
+ return {
1516
+ stencilPath: sys.getCompilerExecutingPath(),
1517
+ diagnostics: []
1518
+ };
1519
+ },
1520
+ async ensureResources() {
1521
+ console.warn(`ensureResources is a no-op, and will be removed in a future version of Stencil`);
1522
+ },
1523
+ exit: async (exitCode) => {
1524
+ await runInterruptsCallbacks();
1525
+ process.exitCode = exitCode;
1526
+ },
1527
+ getCurrentDirectory() {
1528
+ return normalizePath(prcs.cwd());
1529
+ },
1530
+ getCompilerExecutingPath() {
1531
+ return compilerExecutingPath;
1532
+ },
1533
+ getEnvironmentVar(key) {
1534
+ return process.env[key];
1535
+ },
1536
+ getLocalModulePath() {
1537
+ return null;
1538
+ },
1539
+ getRemoteModuleUrl() {
1540
+ return null;
1541
+ },
1542
+ glob: asyncGlob,
1543
+ hardwareConcurrency,
1544
+ isSymbolicLink(p) {
1545
+ return new Promise((resolve) => {
1546
+ try {
1547
+ fs.lstat(p, (err, stats) => {
1548
+ if (err) resolve(false);
1549
+ else resolve(stats.isSymbolicLink());
1550
+ });
1551
+ } catch (e) {
1552
+ resolve(false);
1553
+ }
1554
+ });
1555
+ },
1556
+ nextTick: prcs.nextTick,
1557
+ normalizePath,
1558
+ onProcessInterrupt: (cb) => {
1559
+ if (!onInterruptsCallbacks.includes(cb)) onInterruptsCallbacks.push(cb);
1560
+ },
1561
+ platformPath: path,
1562
+ readDir(p) {
1563
+ return new Promise((resolve) => {
1564
+ fs.readdir(p, (err, files) => {
1565
+ if (err) resolve([]);
1566
+ else resolve(files.map((f) => {
1567
+ return normalizePath(path.join(p, f));
1568
+ }));
1569
+ });
1570
+ });
1571
+ },
1572
+ isTTY() {
1573
+ return !!process?.stdout?.isTTY;
1574
+ },
1575
+ readDirSync(p) {
1576
+ try {
1577
+ return fs.readdirSync(p).map((f) => {
1578
+ return normalizePath(path.join(p, f));
1579
+ });
1580
+ } catch (e) {}
1581
+ return [];
1582
+ },
1583
+ readFile(p, encoding) {
1584
+ if (encoding === "binary") return new Promise((resolve) => {
1585
+ fs.readFile(p, (_, data) => {
1586
+ resolve(data);
1587
+ });
1588
+ });
1589
+ return new Promise((resolve) => {
1590
+ fs.readFile(p, "utf8", (_, data) => {
1591
+ resolve(data);
1592
+ });
1593
+ });
1594
+ },
1595
+ readFileSync(p) {
1596
+ try {
1597
+ return fs.readFileSync(p, "utf8");
1598
+ } catch (e) {}
1599
+ },
1600
+ homeDir() {
1601
+ try {
1602
+ return os.homedir();
1603
+ } catch (e) {}
1604
+ },
1605
+ realpath(p) {
1606
+ return new Promise((resolve) => {
1607
+ fs.realpath(p, "utf8", (e, data) => {
1608
+ resolve({
1609
+ path: data,
1610
+ error: e
1611
+ });
1612
+ });
1613
+ });
1614
+ },
1615
+ realpathSync(p) {
1616
+ const results = {
1617
+ path: void 0,
1618
+ error: null
1619
+ };
1620
+ try {
1621
+ results.path = fs.realpathSync(p, "utf8");
1622
+ } catch (e) {
1623
+ results.error = e;
1624
+ }
1625
+ return results;
1626
+ },
1627
+ rename(oldPath, newPath) {
1628
+ return new Promise((resolve) => {
1629
+ fs.rename(oldPath, newPath, (error) => {
1630
+ resolve({
1631
+ oldPath,
1632
+ newPath,
1633
+ error,
1634
+ oldDirs: [],
1635
+ oldFiles: [],
1636
+ newDirs: [],
1637
+ newFiles: [],
1638
+ renamed: [],
1639
+ isFile: false,
1640
+ isDirectory: false
1641
+ });
1642
+ });
1643
+ });
1644
+ },
1645
+ resolvePath(p) {
1646
+ return normalizePath(p);
1647
+ },
1648
+ removeDir(p, opts) {
1649
+ return new Promise((resolve) => {
1650
+ if (!!(opts && opts.recursive)) fs.rm(p, {
1651
+ recursive: true,
1652
+ force: true
1653
+ }, (err) => {
1654
+ resolve({
1655
+ basename: path.basename(p),
1656
+ dirname: path.dirname(p),
1657
+ path: p,
1658
+ removedDirs: [],
1659
+ removedFiles: [],
1660
+ error: err
1661
+ });
1662
+ });
1663
+ else fs.rmdir(p, (err) => {
1664
+ resolve({
1665
+ basename: path.basename(p),
1666
+ dirname: path.dirname(p),
1667
+ path: p,
1668
+ removedDirs: [],
1669
+ removedFiles: [],
1670
+ error: err
1671
+ });
1672
+ });
1673
+ });
1674
+ },
1675
+ removeDirSync(p, opts) {
1676
+ try {
1677
+ if (!!(opts && opts.recursive)) fs.rmSync(p, {
1678
+ recursive: true,
1679
+ force: true
1680
+ });
1681
+ else fs.rmdirSync(p);
1682
+ return {
1683
+ basename: path.basename(p),
1684
+ dirname: path.dirname(p),
1685
+ path: p,
1686
+ removedDirs: [],
1687
+ removedFiles: [],
1688
+ error: null
1689
+ };
1690
+ } catch (e) {
1691
+ return {
1692
+ basename: path.basename(p),
1693
+ dirname: path.dirname(p),
1694
+ path: p,
1695
+ removedDirs: [],
1696
+ removedFiles: [],
1697
+ error: e
1698
+ };
1699
+ }
1700
+ },
1701
+ removeFile(p) {
1702
+ return new Promise((resolve) => {
1703
+ fs.unlink(p, (err) => {
1704
+ resolve({
1705
+ basename: path.basename(p),
1706
+ dirname: path.dirname(p),
1707
+ path: p,
1708
+ error: err
1709
+ });
1710
+ });
1711
+ });
1712
+ },
1713
+ removeFileSync(p) {
1714
+ const results = {
1715
+ basename: path.basename(p),
1716
+ dirname: path.dirname(p),
1717
+ path: p,
1718
+ error: null
1719
+ };
1720
+ try {
1721
+ fs.unlinkSync(p);
1722
+ } catch (e) {
1723
+ results.error = e;
1724
+ }
1725
+ return results;
1726
+ },
1727
+ setupCompiler(_c) {
1728
+ sys.watchTimeout = 80;
1729
+ sys.events = buildEvents();
1730
+ const activeSubscriptions = /* @__PURE__ */ new Map();
1731
+ /**
1732
+ * Watch a directory for changes using @parcel/watcher.
1733
+ * Uses native file system events (FSEvents on macOS, inotify on Linux, ReadDirectoryChangesW on Windows)
1734
+ * for efficient, low-latency change detection.
1735
+ */
1736
+ sys.watchDirectory = (p, callback, _recursive) => {
1737
+ logger?.debug(`NODE_SYS_DEBUG::watchDir ${p}`);
1738
+ const subscriptionPromise = parcelWatcher.subscribe(p, (err, events) => {
1739
+ if (err) {
1740
+ logger?.error(`Watch error for ${p}: ${err.message}`);
1741
+ return;
1742
+ }
1743
+ for (const event of events) {
1744
+ const fileName = normalizePath(event.path);
1745
+ logger?.debug(`NODE_SYS_DEBUG::watchDir:callback dir=${p} changedPath=${fileName} type=${event.type}`);
1746
+ if (event.type === "create") callback(fileName, "fileAdd");
1747
+ else if (event.type === "update") callback(fileName, "fileUpdate");
1748
+ else if (event.type === "delete") callback(fileName, "fileDelete");
1749
+ }
1750
+ }, { ignore: [
1751
+ ".git",
1752
+ "node_modules",
1753
+ ".stencil",
1754
+ "dist",
1755
+ "www",
1756
+ ".cache"
1757
+ ] }).catch((err) => {
1758
+ logger?.debug(`Watch subscribe failed for ${p}: ${err.message}`);
1759
+ return null;
1760
+ });
1761
+ activeSubscriptions.set(p, subscriptionPromise);
1762
+ const close = () => {
1763
+ const sub = activeSubscriptions.get(p);
1764
+ if (sub) {
1765
+ activeSubscriptions.delete(p);
1766
+ sub.then((s) => s?.unsubscribe()).catch(() => {});
1767
+ }
1768
+ };
1769
+ sys.addDestroy(close);
1770
+ return { close() {
1771
+ sys.removeDestroy(close);
1772
+ close();
1773
+ } };
1774
+ };
1775
+ /**
1776
+ * Watch an individual file for changes using @parcel/watcher.
1777
+ * Watches the parent directory and filters events for the specific file.
1778
+ */
1779
+ sys.watchFile = (filePath, callback) => {
1780
+ logger?.debug(`NODE_SYS_DEBUG::watchFile ${filePath}`);
1781
+ const normalizedPath = normalizePath(filePath);
1782
+ const dirPath = path.dirname(filePath);
1783
+ const subscriptionPromise = parcelWatcher.subscribe(dirPath, (err, events) => {
1784
+ if (err) {
1785
+ logger?.error(`Watch error for ${filePath}: ${err.message}`);
1786
+ return;
1787
+ }
1788
+ for (const event of events) {
1789
+ const eventPath = normalizePath(event.path);
1790
+ if (eventPath === normalizedPath) {
1791
+ logger?.debug(`NODE_SYS_DEBUG::watchFile:callback file=${filePath} type=${event.type}`);
1792
+ if (event.type === "create") {
1793
+ callback(eventPath, "fileAdd");
1794
+ sys.events.emit("fileAdd", eventPath);
1795
+ } else if (event.type === "update") {
1796
+ callback(eventPath, "fileUpdate");
1797
+ sys.events.emit("fileUpdate", eventPath);
1798
+ } else if (event.type === "delete") {
1799
+ callback(eventPath, "fileDelete");
1800
+ sys.events.emit("fileDelete", eventPath);
1801
+ }
1802
+ }
1803
+ }
1804
+ }, { ignore: [".git", "node_modules"] }).catch((err) => {
1805
+ logger?.debug(`Watch subscribe failed for ${filePath}: ${err.message}`);
1806
+ return null;
1807
+ });
1808
+ const subscriptionKey = `file:${filePath}`;
1809
+ activeSubscriptions.set(subscriptionKey, subscriptionPromise);
1810
+ const close = () => {
1811
+ const sub = activeSubscriptions.get(subscriptionKey);
1812
+ if (sub) {
1813
+ activeSubscriptions.delete(subscriptionKey);
1814
+ sub.then((s) => s?.unsubscribe()).catch(() => {});
1815
+ }
1816
+ };
1817
+ sys.addDestroy(close);
1818
+ return { close() {
1819
+ sys.removeDestroy(close);
1820
+ close();
1821
+ } };
1822
+ };
1823
+ },
1824
+ stat(p) {
1825
+ return new Promise((resolve) => {
1826
+ fs.stat(p, (err, fsStat) => {
1827
+ if (err) resolve({
1828
+ isDirectory: false,
1829
+ isFile: false,
1830
+ isSymbolicLink: false,
1831
+ size: 0,
1832
+ mtimeMs: 0,
1833
+ error: err
1834
+ });
1835
+ else resolve({
1836
+ isDirectory: fsStat.isDirectory(),
1837
+ isFile: fsStat.isFile(),
1838
+ isSymbolicLink: fsStat.isSymbolicLink(),
1839
+ size: fsStat.size,
1840
+ mtimeMs: fsStat.mtimeMs,
1841
+ error: null
1842
+ });
1843
+ });
1844
+ });
1845
+ },
1846
+ statSync(p) {
1847
+ try {
1848
+ const fsStat = fs.statSync(p);
1849
+ return {
1850
+ isDirectory: fsStat.isDirectory(),
1851
+ isFile: fsStat.isFile(),
1852
+ isSymbolicLink: fsStat.isSymbolicLink(),
1853
+ size: fsStat.size,
1854
+ mtimeMs: fsStat.mtimeMs,
1855
+ error: null
1856
+ };
1857
+ } catch (e) {
1858
+ return {
1859
+ isDirectory: false,
1860
+ isFile: false,
1861
+ isSymbolicLink: false,
1862
+ size: 0,
1863
+ mtimeMs: 0,
1864
+ error: e
1865
+ };
1866
+ }
1867
+ },
1868
+ tmpDirSync() {
1869
+ return tmpdir();
1870
+ },
1871
+ writeFile(p, content) {
1872
+ return new Promise((resolve) => {
1873
+ fs.writeFile(p, content, (err) => {
1874
+ resolve({
1875
+ path: p,
1876
+ error: err
1877
+ });
1878
+ });
1879
+ });
1880
+ },
1881
+ writeFileSync(p, content) {
1882
+ const results = {
1883
+ path: p,
1884
+ error: null
1885
+ };
1886
+ try {
1887
+ fs.writeFileSync(p, content);
1888
+ } catch (e) {
1889
+ results.error = e;
1890
+ }
1891
+ return results;
1892
+ },
1893
+ generateContentHash(content, length) {
1894
+ let hash = createHash("sha1").update(content).digest("hex").toLowerCase();
1895
+ if (typeof length === "number") hash = hash.slice(0, length);
1896
+ return Promise.resolve(hash);
1897
+ },
1898
+ generateFileHash(filePath, length) {
1899
+ return new Promise((resolve, reject) => {
1900
+ const h = createHash("sha1");
1901
+ fs.createReadStream(filePath).on("error", (err) => reject(err)).on("data", (data) => h.update(data)).on("end", () => {
1902
+ let hash = h.digest("hex").toLowerCase();
1903
+ if (typeof length === "number") hash = hash.slice(0, length);
1904
+ resolve(hash);
1905
+ });
1906
+ });
1907
+ },
1908
+ copy: nodeCopyTasks,
1909
+ details: {
1910
+ cpuModel: (Array.isArray(sysCpus) && sysCpus.length > 0 ? sysCpus[0] && sysCpus[0].model : "") || "",
1911
+ freemem() {
1912
+ return freemem();
1913
+ },
1914
+ platform: osPlatform === "darwin" || osPlatform === "linux" ? osPlatform : osPlatform === "win32" ? "windows" : "",
1915
+ release: release(),
1916
+ totalmem: totalmem()
1917
+ }
1918
+ };
1919
+ sys.lazyRequire = new NodeLazyRequire(new NodeResolveModule(), {
1920
+ "@types/jest": {
1921
+ minVersion: "24.9.1",
1922
+ recommendedVersion: "29",
1923
+ maxVersion: "29.0.0"
1924
+ },
1925
+ jest: {
1926
+ minVersion: "24.9.0",
1927
+ recommendedVersion: "29",
1928
+ maxVersion: "29.0.0"
1929
+ },
1930
+ "jest-cli": {
1931
+ minVersion: "24.9.0",
1932
+ recommendedVersion: "29",
1933
+ maxVersion: "29.0.0"
1934
+ },
1935
+ puppeteer: {
1936
+ minVersion: "10.0.0",
1937
+ recommendedVersion: "20"
1938
+ },
1939
+ "puppeteer-core": {
1940
+ minVersion: "10.0.0",
1941
+ recommendedVersion: "20"
1942
+ },
1943
+ "workbox-build": {
1944
+ minVersion: "4.3.1",
1945
+ recommendedVersion: "4.3.1"
1946
+ }
1947
+ });
1948
+ prcs.on("SIGINT", runInterruptsCallbacks);
1949
+ prcs.on("exit", runInterruptsCallbacks);
1950
+ return sys;
1951
+ }
1952
+
1953
+ //#endregion
1954
+ export { LOG_LEVELS as a, CustomElementsExportBehaviorOptions as i, setupNodeProcess as n, buildEvents as o, createNodeLogger as r, createNodeSys as t };