target.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const memoize = require("../util/memoize");
  7. const getBrowserslistTargetHandler = memoize(() =>
  8. require("./browserslistTargetHandler")
  9. );
  10. /**
  11. * @param {string} context the context directory
  12. * @returns {string} default target
  13. */
  14. const getDefaultTarget = context => {
  15. const browsers = getBrowserslistTargetHandler().load(null, context);
  16. return browsers ? "browserslist" : "web";
  17. };
  18. /**
  19. * @typedef {object} PlatformTargetProperties
  20. * @property {boolean | null} web web platform, importing of http(s) and std: is available
  21. * @property {boolean | null} browser browser platform, running in a normal web browser
  22. * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker
  23. * @property {boolean | null} node node platform, require of node built-in modules is available
  24. * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available
  25. * @property {boolean | null} electron electron platform, require of some electron built-in modules is available
  26. */
  27. /**
  28. * @typedef {object} ElectronContextTargetProperties
  29. * @property {boolean | null} electronMain in main context
  30. * @property {boolean | null} electronPreload in preload context
  31. * @property {boolean | null} electronRenderer in renderer context with node integration
  32. */
  33. /**
  34. * @typedef {object} ApiTargetProperties
  35. * @property {boolean | null} require has require function available
  36. * @property {boolean | null} nodeBuiltins has node.js built-in modules available
  37. * @property {boolean | null} nodePrefixForCoreModules node.js allows to use `node:` prefix for core modules
  38. * @property {boolean | null} document has document available (allows script tags)
  39. * @property {boolean | null} importScripts has importScripts available
  40. * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker
  41. * @property {boolean | null} fetchWasm has fetch function available for WebAssembly
  42. * @property {boolean | null} global has global variable available
  43. */
  44. /**
  45. * @typedef {object} EcmaTargetProperties
  46. * @property {boolean | null} globalThis has globalThis variable available
  47. * @property {boolean | null} bigIntLiteral big int literal syntax is available
  48. * @property {boolean | null} const const and let variable declarations are available
  49. * @property {boolean | null} arrowFunction arrow functions are available
  50. * @property {boolean | null} forOf for of iteration is available
  51. * @property {boolean | null} destructuring destructuring is available
  52. * @property {boolean | null} dynamicImport async import() is available
  53. * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker
  54. * @property {boolean | null} module ESM syntax is available (when in module)
  55. * @property {boolean | null} optionalChaining optional chaining is available
  56. * @property {boolean | null} templateLiteral template literal is available
  57. * @property {boolean | null} asyncFunction async functions and await are available
  58. */
  59. ///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */
  60. /**
  61. * @template T
  62. * @typedef {{ [P in keyof T]?: never }} Never<T>
  63. */
  64. /**
  65. * @template A
  66. * @template B
  67. * @typedef {(A & Never<B>) | (Never<A> & B) | (A & B)} Mix<A, B>
  68. */
  69. /** @typedef {Mix<Mix<PlatformTargetProperties, ElectronContextTargetProperties>, Mix<ApiTargetProperties, EcmaTargetProperties>>} TargetProperties */
  70. /**
  71. * @param {string} major major version
  72. * @param {string | undefined} minor minor version
  73. * @returns {(vMajor: number, vMinor?: number) => boolean | undefined} check if version is greater or equal
  74. */
  75. const versionDependent = (major, minor) => {
  76. if (!major) {
  77. return () => /** @type {undefined} */ (undefined);
  78. }
  79. /** @type {number} */
  80. const nMajor = +major;
  81. /** @type {number} */
  82. const nMinor = minor ? +minor : 0;
  83. return (vMajor, vMinor = 0) => {
  84. return nMajor > vMajor || (nMajor === vMajor && nMinor >= vMinor);
  85. };
  86. };
  87. /** @type {[string, string, RegExp, (...args: string[]) => Partial<TargetProperties>][]} */
  88. const TARGETS = [
  89. [
  90. "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env",
  91. "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config",
  92. /^browserslist(?::(.+))?$/,
  93. (rest, context) => {
  94. const browserslistTargetHandler = getBrowserslistTargetHandler();
  95. const browsers = browserslistTargetHandler.load(
  96. rest ? rest.trim() : null,
  97. context
  98. );
  99. if (!browsers) {
  100. throw new Error(`No browserslist config found to handle the 'browserslist' target.
  101. See https://github.com/browserslist/browserslist#queries for possible ways to provide a config.
  102. The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions).
  103. You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`);
  104. }
  105. return browserslistTargetHandler.resolve(browsers);
  106. }
  107. ],
  108. [
  109. "web",
  110. "Web browser.",
  111. /^web$/,
  112. () => {
  113. return {
  114. web: true,
  115. browser: true,
  116. webworker: null,
  117. node: false,
  118. electron: false,
  119. nwjs: false,
  120. document: true,
  121. importScriptsInWorker: true,
  122. fetchWasm: true,
  123. nodeBuiltins: false,
  124. importScripts: false,
  125. require: false,
  126. global: false
  127. };
  128. }
  129. ],
  130. [
  131. "webworker",
  132. "Web Worker, SharedWorker or Service Worker.",
  133. /^webworker$/,
  134. () => {
  135. return {
  136. web: true,
  137. browser: true,
  138. webworker: true,
  139. node: false,
  140. electron: false,
  141. nwjs: false,
  142. importScripts: true,
  143. importScriptsInWorker: true,
  144. fetchWasm: true,
  145. nodeBuiltins: false,
  146. require: false,
  147. document: false,
  148. global: false
  149. };
  150. }
  151. ],
  152. [
  153. "[async-]node[X[.Y]]",
  154. "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.",
  155. /^(async-)?node((\d+)(?:\.(\d+))?)?$/,
  156. (asyncFlag, _, major, minor) => {
  157. const v = versionDependent(major, minor);
  158. // see https://node.green/
  159. return {
  160. node: true,
  161. electron: false,
  162. nwjs: false,
  163. web: false,
  164. webworker: false,
  165. browser: false,
  166. require: !asyncFlag,
  167. nodeBuiltins: true,
  168. // v16.0.0, v14.18.0
  169. nodePrefixForCoreModules: +major < 15 ? v(14, 18) : v(16),
  170. global: true,
  171. document: false,
  172. fetchWasm: false,
  173. importScripts: false,
  174. importScriptsInWorker: false,
  175. globalThis: v(12),
  176. const: v(6),
  177. templateLiteral: v(4),
  178. optionalChaining: v(14),
  179. arrowFunction: v(6),
  180. asyncFunction: v(7, 6),
  181. forOf: v(5),
  182. destructuring: v(6),
  183. bigIntLiteral: v(10, 4),
  184. dynamicImport: v(12, 17),
  185. dynamicImportInWorker: major ? false : undefined,
  186. module: v(12, 17)
  187. };
  188. }
  189. ],
  190. [
  191. "electron[X[.Y]]-main/preload/renderer",
  192. "Electron in version X.Y. Script is running in main, preload resp. renderer context.",
  193. /^electron((\d+)(?:\.(\d+))?)?-(main|preload|renderer)$/,
  194. (_, major, minor, context) => {
  195. const v = versionDependent(major, minor);
  196. // see https://node.green/ + https://github.com/electron/releases
  197. return {
  198. node: true,
  199. electron: true,
  200. web: context !== "main",
  201. webworker: false,
  202. browser: false,
  203. nwjs: false,
  204. electronMain: context === "main",
  205. electronPreload: context === "preload",
  206. electronRenderer: context === "renderer",
  207. global: true,
  208. nodeBuiltins: true,
  209. // 15.0.0 - Node.js v16.5
  210. // 14.0.0 - Mode.js v14.17, but prefixes only since v14.18
  211. nodePrefixForCoreModules: v(15),
  212. require: true,
  213. document: context === "renderer",
  214. fetchWasm: context === "renderer",
  215. importScripts: false,
  216. importScriptsInWorker: true,
  217. globalThis: v(5),
  218. const: v(1, 1),
  219. templateLiteral: v(1, 1),
  220. optionalChaining: v(8),
  221. arrowFunction: v(1, 1),
  222. asyncFunction: v(1, 7),
  223. forOf: v(0, 36),
  224. destructuring: v(1, 1),
  225. bigIntLiteral: v(4),
  226. dynamicImport: v(11),
  227. dynamicImportInWorker: major ? false : undefined,
  228. module: v(11)
  229. };
  230. }
  231. ],
  232. [
  233. "nwjs[X[.Y]] / node-webkit[X[.Y]]",
  234. "NW.js in version X.Y.",
  235. /^(?:nwjs|node-webkit)((\d+)(?:\.(\d+))?)?$/,
  236. (_, major, minor) => {
  237. const v = versionDependent(major, minor);
  238. // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md
  239. return {
  240. node: true,
  241. web: true,
  242. nwjs: true,
  243. webworker: null,
  244. browser: false,
  245. electron: false,
  246. global: true,
  247. nodeBuiltins: true,
  248. document: false,
  249. importScriptsInWorker: false,
  250. fetchWasm: false,
  251. importScripts: false,
  252. require: false,
  253. globalThis: v(0, 43),
  254. const: v(0, 15),
  255. templateLiteral: v(0, 13),
  256. optionalChaining: v(0, 44),
  257. arrowFunction: v(0, 15),
  258. asyncFunction: v(0, 21),
  259. forOf: v(0, 13),
  260. destructuring: v(0, 15),
  261. bigIntLiteral: v(0, 32),
  262. dynamicImport: v(0, 43),
  263. dynamicImportInWorker: major ? false : undefined,
  264. module: v(0, 43)
  265. };
  266. }
  267. ],
  268. [
  269. "esX",
  270. "EcmaScript in this version. Examples: es2020, es5.",
  271. /^es(\d+)$/,
  272. version => {
  273. let v = +version;
  274. if (v < 1000) v = v + 2009;
  275. return {
  276. const: v >= 2015,
  277. templateLiteral: v >= 2015,
  278. optionalChaining: v >= 2020,
  279. arrowFunction: v >= 2015,
  280. forOf: v >= 2015,
  281. destructuring: v >= 2015,
  282. module: v >= 2015,
  283. asyncFunction: v >= 2017,
  284. globalThis: v >= 2020,
  285. bigIntLiteral: v >= 2020,
  286. dynamicImport: v >= 2020,
  287. dynamicImportInWorker: v >= 2020
  288. };
  289. }
  290. ]
  291. ];
  292. /**
  293. * @param {string} target the target
  294. * @param {string} context the context directory
  295. * @returns {TargetProperties} target properties
  296. */
  297. const getTargetProperties = (target, context) => {
  298. for (const [, , regExp, handler] of TARGETS) {
  299. const match = regExp.exec(target);
  300. if (match) {
  301. const [, ...args] = match;
  302. const result = handler(...args, context);
  303. if (result) return /** @type {TargetProperties} */ (result);
  304. }
  305. }
  306. throw new Error(
  307. `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map(
  308. ([name, description]) => `* ${name}: ${description}`
  309. ).join("\n")}`
  310. );
  311. };
  312. /**
  313. * @param {TargetProperties[]} targetProperties array of target properties
  314. * @returns {TargetProperties} merged target properties
  315. */
  316. const mergeTargetProperties = targetProperties => {
  317. /** @type {Set<keyof TargetProperties>} */
  318. const keys = new Set();
  319. for (const tp of targetProperties) {
  320. for (const key of Object.keys(tp)) {
  321. keys.add(/** @type {keyof TargetProperties} */ (key));
  322. }
  323. }
  324. /** @type {object} */
  325. const result = {};
  326. for (const key of keys) {
  327. let hasTrue = false;
  328. let hasFalse = false;
  329. for (const tp of targetProperties) {
  330. const value = tp[key];
  331. switch (value) {
  332. case true:
  333. hasTrue = true;
  334. break;
  335. case false:
  336. hasFalse = true;
  337. break;
  338. }
  339. }
  340. if (hasTrue || hasFalse)
  341. /** @type {TargetProperties} */
  342. (result)[key] = hasFalse && hasTrue ? null : hasTrue ? true : false;
  343. }
  344. return /** @type {TargetProperties} */ (result);
  345. };
  346. /**
  347. * @param {string[]} targets the targets
  348. * @param {string} context the context directory
  349. * @returns {TargetProperties} target properties
  350. */
  351. const getTargetsProperties = (targets, context) => {
  352. return mergeTargetProperties(
  353. targets.map(t => getTargetProperties(t, context))
  354. );
  355. };
  356. exports.getDefaultTarget = getDefaultTarget;
  357. exports.getTargetProperties = getTargetProperties;
  358. exports.getTargetsProperties = getTargetsProperties;