@jsenv/core 25.0.1 → 25.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jsenv/core",
3
- "version": "25.0.1",
3
+ "version": "25.1.0",
4
4
  "description": "Tool to develop, test and build js projects",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -11,8 +11,7 @@
11
11
  "node": ">=16.13.0"
12
12
  },
13
13
  "publishConfig": {
14
- "access": "public",
15
- "registry": "https://registry.npmjs.org"
14
+ "access": "public"
16
15
  },
17
16
  "type": "module",
18
17
  "exports": {
@@ -138,4 +137,4 @@
138
137
  "redux": "4.1.2",
139
138
  "rollup-plugin-import-assert": "1.1.1"
140
139
  }
141
- }
140
+ }
package/readme.md CHANGED
@@ -1,10 +1,20 @@
1
1
  # jsenv [![npm package](https://img.shields.io/npm/v/@jsenv/core.svg?logo=npm&label=package)](https://www.npmjs.com/package/@jsenv/core) [![github main worflow](https://github.com/jsenv/jsenv-core/workflows/main/badge.svg)](https://github.com/jsenv/jsenv-core/actions?workflow=main) [![codecov coverage](https://codecov.io/gh/jsenv/jsenv-core/branch/master/graph/badge.svg)](https://codecov.io/gh/jsenv/jsenv-core)
2
2
 
3
- _@jsenv/core_ is a quick start pack to launch a js project. It provides what you need from the beginning: a dev server, a build tool and a test "framework", all in one.
3
+ _@jsenv/core_ is a quick start pack to launch a js project. It provides what you need from the beginning: develoment, testing and building all in one.
4
4
 
5
- Jsenv integrates naturally with **standard** HTML, CSS and JS: you don't have to pick a JavaScript framework.
5
+ Jsenv **integrates naturally with standard** HTML, CSS and JS: you don't have to pick a JavaScript framework.
6
6
 
7
- # Test runner overview
7
+ # Overview
8
+
9
+ This section demos 3 things jsenv provides:
10
+
11
+ 1. A test runner
12
+ 2. A dev server
13
+ 3. A build script
14
+
15
+ Don't be fooled by the apparent simplicity of the following demos, jsenv can be used on more complex scenarios as well.
16
+
17
+ ## Test runner overview
8
18
 
9
19
  Let's assume you want to test `countDogs` exported by _animals.js_ file.
10
20
 
@@ -94,7 +104,7 @@ total duration: 1.2 seconds
94
104
 
95
105
  To read more about testing in jsenv, check [jsenv test runner documentation](./docs/testing/readme.md#jsenv-test-runner).
96
106
 
97
- # Dev server overview
107
+ ## Dev server overview
98
108
 
99
109
  You want to execute the following _main.html_ file in a browser.
100
110
 
@@ -155,7 +165,7 @@ Browser navigates to _main.html_ and execute the file. Hello world is displayed
155
165
 
156
166
  To read more about jsenv dev server, check [jsenv dev server documentation](./docs/dev_server/readme.md#jsenv-dev-server).
157
167
 
158
- # Build overview
168
+ ## Build overview
159
169
 
160
170
  Following the steps below turns a `main.html` into an optimized `dist/main.prod.html`.
161
171
  Only the content of html files is shown below because the content of non-html files is trivial.
@@ -14,8 +14,8 @@ export const parseJsRessource = async (
14
14
  const jsUrl = jsRessource.url
15
15
  const jsString = String(jsRessource.bufferBeforeBuild)
16
16
  const jsSourcemapUrl = getJavaScriptSourceMappingUrl(jsString)
17
- let sourcemapReference
18
17
 
18
+ let sourcemapReference
19
19
  if (jsSourcemapUrl) {
20
20
  sourcemapReference = notifyReferenceFound({
21
21
  referenceLabel: "js sourcemapping comment",
@@ -76,13 +76,10 @@ export const parseJsRessource = async (
76
76
  code = result.code
77
77
  map = result.map
78
78
  }
79
-
80
79
  jsRessource.buildEnd(code)
81
-
82
80
  if (!map) {
83
81
  return
84
82
  }
85
-
86
83
  // In theory code should never be modified once buildEnd() is called
87
84
  // because buildRelativeUrl might be versioned based on file content
88
85
  // There is an exception for sourcemap because we want to update sourcemap.file
@@ -99,7 +96,6 @@ export const parseJsRessource = async (
99
96
  `${urlToFilename(jsBuildUrl)}.map`,
100
97
  jsBuildUrl,
101
98
  )
102
-
103
99
  map.file = urlToFilename(jsBuildUrl)
104
100
  if (map.sources) {
105
101
  map.sources = map.sources.map((source) => {
@@ -114,7 +110,6 @@ export const parseJsRessource = async (
114
110
  }
115
111
  const mapAsText = JSON.stringify(map, null, " ")
116
112
  sourcemapRessource.buildEnd(mapAsText)
117
-
118
113
  const sourcemapBuildUrl = resolveUrl(
119
114
  sourcemapRessource.buildRelativeUrl,
120
115
  buildDirectoryUrl,
@@ -948,8 +948,14 @@ export const createRessourceBuilder = (
948
948
  }
949
949
  return {
950
950
  ...htmlUrlSite,
951
- line: htmlUrlSite.line + urlSite.line,
952
- column: htmlUrlSite.column + urlSite.column,
951
+ line:
952
+ typeof urlSite.line === "number"
953
+ ? htmlUrlSite.line + urlSite.line
954
+ : htmlUrlSite.line,
955
+ column:
956
+ typeof urlSite.column === "number"
957
+ ? htmlUrlSite.column + urlSite.column
958
+ : htmlUrlSite.column,
953
959
  }
954
960
  }
955
961
 
@@ -690,6 +690,9 @@ export const createRollupPlugins = async ({
690
690
  // we compile for rollup, let top level await untouched
691
691
  // it will be converted, if needed, during "renderChunk" hook
692
692
  topLevelAwait: "ignore",
693
+ // if we put babel helpers, rollup might try to share them and a file
694
+ // might try to import from an inline script resulting in 404.
695
+ babelHelpersInjectionAsImport: false,
693
696
  })
694
697
  let code = transformResult.code
695
698
  let map = transformResult.map
@@ -1,7 +1,14 @@
1
- import { resolveUrl, urlToRelativeUrl } from "@jsenv/filesystem"
1
+ import {
2
+ resolveUrl,
3
+ urlToFilename,
4
+ urlToBasename,
5
+ urlToRelativeUrl,
6
+ urlIsInsideOf,
7
+ } from "@jsenv/filesystem"
2
8
  import { moveImportMap, composeTwoImportMaps } from "@jsenv/importmap"
3
9
  import { createDetailedMessage } from "@jsenv/logger"
4
10
 
11
+ import { jsenvDistDirectoryUrl } from "@jsenv/core/src/internal/jsenvCoreDirectoryUrl.js"
5
12
  import {
6
13
  BROWSER_RUNTIME_BUILD_URL,
7
14
  EVENT_SOURCE_CLIENT_BUILD_URL,
@@ -39,6 +46,7 @@ export const compileHtml = async ({
39
46
  url,
40
47
  compiledUrl,
41
48
  projectDirectoryUrl,
49
+ compileServerOrigin,
42
50
  outDirectoryRelativeUrl,
43
51
  compileId,
44
52
 
@@ -104,248 +112,478 @@ export const compileHtml = async ({
104
112
  ],
105
113
  })
106
114
 
107
- let sources = []
108
- let sourcesContent = []
115
+ const sources = []
116
+ const sourcesContent = []
117
+ const assets = []
118
+ const assetsContent = []
119
+
120
+ const addHtmlSourceFile = ({ url, content }) => {
121
+ sources.push(url)
122
+ sourcesContent.push(content)
123
+ }
124
+ addHtmlSourceFile({ url, content: code })
125
+
109
126
  const { scripts } = parseHtmlAstRessources(htmlAst)
110
- let importmapInfo = null
111
- scripts.forEach((script) => {
112
- const typeAttribute = getHtmlNodeAttributeByName(script, "type")
113
- if (typeAttribute && typeAttribute.value === "importmap") {
114
- if (importmapInfo) {
115
- console.error("HTML file must contain max 1 importmap")
116
- } else {
117
- const srcAttribute = getHtmlNodeAttributeByName(script, "src")
118
- const src = srcAttribute ? srcAttribute.value : ""
119
- if (src) {
120
- importmapInfo = {
121
- script,
122
- url: resolveUrl(src, url),
123
- load: async () => {
124
- const importMapResponse = await fetchUrl(importmapInfo.url)
125
- if (importMapResponse.status === 200) {
126
- const importmapAsText = await importMapResponse.text()
127
- let htmlImportmap = JSON.parse(importmapAsText)
128
- htmlImportmap = moveImportMap(
129
- htmlImportmap,
130
- importmapInfo.url,
131
- url,
132
- )
133
- sources.push(importmapInfo.url)
134
- sourcesContent.push(importmapAsText)
135
- return htmlImportmap
136
- }
137
- logger.warn(
138
- createDetailedMessage(
139
- importMapResponse.status === 404
140
- ? `importmap script file cannot be found.`
141
- : `importmap script file unexpected response status (${importMapResponse.status}).`,
142
- {
143
- "importmap url": importmapInfo.url,
144
- "html url": url,
145
- },
146
- ),
147
- )
148
- return {}
149
- },
150
- }
151
- } else {
152
- importmapInfo = {
153
- script,
154
- url: compiledUrl,
155
- load: () => {
156
- const jsenvImportmap = getDefaultImportmap(compiledUrl, {
157
- projectDirectoryUrl,
158
- compileDirectoryUrl: `${projectDirectoryUrl}${compileId}/${outDirectoryRelativeUrl}`,
159
- })
160
- const htmlImportmap = JSON.parse(
161
- getHtmlNodeTextNode(script).value,
162
- )
163
- const importmap = composeTwoImportMaps(
164
- jsenvImportmap,
165
- htmlImportmap,
166
- )
167
- return importmap
168
- },
169
- }
170
- }
171
- }
172
- }
173
- })
174
- if (importmapInfo) {
175
- const importmap = await importmapInfo.load()
176
- const importmapAsText = JSON.stringify(importmap, null, " ")
177
- replaceHtmlNode(
178
- importmapInfo.script,
179
- `<script type="${
180
- moduleOutFormat === "systemjs" ? "systemjs-importmap" : "importmap"
181
- }">${importmapAsText}</script>`,
182
- {
183
- attributesToIgnore: ["src"],
184
- },
185
- )
186
- importmapInfo.inlinedFrom = importmapInfo.url
187
- importmapInfo.text = importmapAsText
188
- } else {
189
- const defaultImportMap = getDefaultImportmap(compiledUrl, {
190
- projectDirectoryUrl,
191
- compileDirectoryUrl: `${projectDirectoryUrl}${outDirectoryRelativeUrl}${compileId}/`,
127
+ const htmlDependencies = collectHtmlDependenciesFromAst(htmlAst)
128
+
129
+ const htmlAssetGenerators = []
130
+ const htmlMutations = []
131
+ const addHtmlAssetGenerator = (htmlAssetGenerator) => {
132
+ htmlAssetGenerators.push(htmlAssetGenerator)
133
+ }
134
+ const addHtmlMutation = (htmlMutation) => {
135
+ htmlMutations.push(htmlMutation)
136
+ }
137
+ const addHtmlDependency = ({ htmlNode, specifier }) => {
138
+ htmlDependencies.push({
139
+ htmlNode,
140
+ specifier,
192
141
  })
193
- const importmapAsText = JSON.stringify(defaultImportMap, null, " ")
194
- manipulateHtmlAst(htmlAst, {
195
- scriptInjections: [
142
+ }
143
+
144
+ const importmapInfo = await visitImportmapScript({
145
+ logger,
146
+ url,
147
+ compiledUrl,
148
+ projectDirectoryUrl,
149
+ compileId,
150
+ outDirectoryRelativeUrl,
151
+ scripts,
152
+ addHtmlSourceFile,
153
+ })
154
+ const importmap = (await importmapInfo.load()) || {}
155
+ const importmapAsText = JSON.stringify(importmap, null, " ")
156
+ importmapInfo.inlinedFrom = importmapInfo.url
157
+ importmapInfo.text = importmapAsText
158
+ addHtmlMutation(() => {
159
+ if (importmapInfo.needsInjection) {
160
+ manipulateHtmlAst(htmlAst, {
161
+ scriptInjections: [
162
+ {
163
+ type:
164
+ moduleOutFormat === "systemjs"
165
+ ? "systemjs-importmap"
166
+ : "importmap",
167
+ // in case there is no importmap, force the presence
168
+ // so that '@jsenv/core/' are still remapped
169
+ text: importmapAsText,
170
+ },
171
+ ],
172
+ })
173
+ } else {
174
+ replaceHtmlNode(
175
+ importmapInfo.script,
176
+ `<script type="${
177
+ moduleOutFormat === "systemjs" ? "systemjs-importmap" : "importmap"
178
+ }">${importmapAsText}</script>`,
196
179
  {
197
- type:
198
- moduleOutFormat === "systemjs" ? "systemjs-importmap" : "importmap",
199
- // in case there is no importmap, force the presence
200
- // so that '@jsenv/core/' are still remapped
201
- text: importmapAsText,
180
+ attributesToIgnore: ["src"],
202
181
  },
203
- ],
204
- })
205
- importmapInfo = {
206
- url: compiledUrl,
207
- text: importmapAsText,
182
+ )
208
183
  }
209
- }
184
+ })
210
185
  onHtmlImportmapInfo({
211
186
  htmlUrl: url,
212
187
  importmapInfo,
213
188
  })
214
189
 
215
- const htmlDependencies = collectHtmlDependenciesFromAst(htmlAst)
216
- const inlineScriptsContentMap = {}
190
+ await visitScripts({
191
+ logger,
192
+ projectDirectoryUrl,
193
+ compileServerOrigin,
194
+ url,
195
+ compiledUrl,
196
+ scripts,
197
+ addHtmlSourceFile,
198
+ addHtmlAssetGenerator,
199
+ addHtmlMutation,
200
+ addHtmlDependency,
201
+
202
+ babelPluginMap,
203
+ moduleOutFormat,
204
+ importMetaFormat,
205
+ topLevelAwait,
206
+ sourcemapMethod,
207
+ })
208
+ await Promise.all(
209
+ htmlAssetGenerators.map(async (htmlAssetGenerator) => {
210
+ const assetInfos = await htmlAssetGenerator()
211
+ assetInfos.forEach((assetInfo) => {
212
+ assets.push(assetInfo.url)
213
+ assetsContent.push(assetInfo.content)
214
+ })
215
+ }),
216
+ )
217
+ htmlAssetGenerators.length = 0
218
+
219
+ htmlMutations.forEach((htmlMutation) => {
220
+ htmlMutation()
221
+ })
222
+ htmlMutations.length = 0
223
+ const htmlAfterTransformation = stringifyHtmlAst(htmlAst)
224
+
225
+ return {
226
+ contentType: "text/html",
227
+ compiledSource: htmlAfterTransformation,
228
+ sources,
229
+ sourcesContent,
230
+ assets,
231
+ assetsContent,
232
+ dependencies: htmlDependencies.map(({ specifier }) => {
233
+ return specifier
234
+ }),
235
+ }
236
+ }
237
+
238
+ const visitImportmapScript = async ({
239
+ logger,
240
+ url,
241
+ compiledUrl,
242
+ projectDirectoryUrl,
243
+ compileId,
244
+ outDirectoryRelativeUrl,
245
+ scripts,
246
+ addHtmlSourceFile,
247
+ }) => {
248
+ const importmapScripts = scripts.filter((script) => {
249
+ const typeAttribute = getHtmlNodeAttributeByName(script, "type")
250
+ const type = typeAttribute ? typeAttribute.value : "application/javascript"
251
+ return type === "importmap"
252
+ })
253
+ if (importmapScripts.length === 0) {
254
+ return {
255
+ needsInjection: true,
256
+ url: compiledUrl,
257
+ load: () => {
258
+ const defaultImportMap = getDefaultImportmap(compiledUrl, {
259
+ projectDirectoryUrl,
260
+ compileDirectoryUrl: `${projectDirectoryUrl}${outDirectoryRelativeUrl}${compileId}/`,
261
+ })
262
+ return defaultImportMap
263
+ },
264
+ }
265
+ }
266
+
267
+ if (importmapScripts.length > 1) {
268
+ logger.error("HTML file must contain max 1 importmap")
269
+ }
270
+ const firstImportmapScript = importmapScripts[0]
271
+ const srcAttribute = getHtmlNodeAttributeByName(firstImportmapScript, "src")
272
+ const src = srcAttribute ? srcAttribute.value : ""
273
+ if (src) {
274
+ const importmapUrl = resolveUrl(src, url)
275
+ const importmapInfo = {
276
+ script: firstImportmapScript,
277
+ url: importmapUrl,
278
+ load: async () => {
279
+ const importMapResponse = await fetchUrl(importmapUrl)
280
+ if (importMapResponse.status === 200) {
281
+ const importmapAsText = await importMapResponse.text()
282
+ addHtmlSourceFile({
283
+ url: importmapUrl,
284
+ content: importmapAsText,
285
+ })
286
+ let htmlImportmap = JSON.parse(importmapAsText)
287
+ htmlImportmap = moveImportMap(htmlImportmap, importmapUrl, url)
288
+ return htmlImportmap
289
+ }
290
+ logger.warn(
291
+ createDetailedMessage(
292
+ importMapResponse.status === 404
293
+ ? `importmap script file cannot be found.`
294
+ : `importmap script file unexpected response status (${importMapResponse.status}).`,
295
+ {
296
+ "importmap url": importmapInfo.url,
297
+ "html url": url,
298
+ },
299
+ ),
300
+ )
301
+ return null
302
+ },
303
+ }
304
+ return importmapInfo
305
+ }
306
+ const importmapInfo = {
307
+ script: firstImportmapScript,
308
+ url: compiledUrl,
309
+ load: () => {
310
+ const jsenvImportmap = getDefaultImportmap(compiledUrl, {
311
+ projectDirectoryUrl,
312
+ compileDirectoryUrl: `${projectDirectoryUrl}${compileId}/${outDirectoryRelativeUrl}`,
313
+ })
314
+ const htmlImportmap = JSON.parse(
315
+ getHtmlNodeTextNode(firstImportmapScript).value,
316
+ )
317
+ const importmap = composeTwoImportMaps(jsenvImportmap, htmlImportmap)
318
+ return importmap
319
+ },
320
+ }
321
+ return importmapInfo
322
+ }
323
+
324
+ const visitScripts = async ({
325
+ logger,
326
+ projectDirectoryUrl,
327
+ compileServerOrigin,
328
+ url,
329
+ compiledUrl,
330
+ scripts,
331
+ addHtmlSourceFile,
332
+ addHtmlAssetGenerator,
333
+ addHtmlMutation,
334
+ addHtmlDependency,
335
+
336
+ babelPluginMap,
337
+ moduleOutFormat,
338
+ importMetaFormat,
339
+ topLevelAwait,
340
+ sourcemapMethod,
341
+ }) => {
217
342
  scripts.forEach((script) => {
218
343
  const typeAttribute = getHtmlNodeAttributeByName(script, "type")
344
+ const type = typeAttribute ? typeAttribute.value : "application/javascript"
219
345
  const srcAttribute = getHtmlNodeAttributeByName(script, "src")
220
346
  const src = srcAttribute ? srcAttribute.value : ""
221
- // remote module script
222
- if (typeAttribute && typeAttribute.value === "module" && src) {
223
- if (moduleOutFormat === "systemjs") {
224
- removeHtmlNodeAttribute(script, typeAttribute)
347
+ const textNode = getHtmlNodeTextNode(script)
348
+
349
+ if (type === "module") {
350
+ if (src) {
351
+ addHtmlMutation(() => {
352
+ if (moduleOutFormat === "systemjs") {
353
+ removeHtmlNodeAttribute(script, typeAttribute)
354
+ }
355
+ removeHtmlNodeAttribute(script, srcAttribute)
356
+ const jsenvMethod =
357
+ moduleOutFormat === "systemjs"
358
+ ? "executeFileUsingSystemJs"
359
+ : "executeFileUsingDynamicImport"
360
+ setHtmlNodeText(
361
+ script,
362
+ `window.__jsenv__.${jsenvMethod}(${JSON.stringify(src)})`,
363
+ )
364
+ })
365
+ return
225
366
  }
226
- removeHtmlNodeAttribute(script, srcAttribute)
227
- const jsenvMethod =
228
- moduleOutFormat === "systemjs"
229
- ? "executeFileUsingSystemJs"
230
- : "executeFileUsingDynamicImport"
231
- setHtmlNodeText(
367
+
368
+ const inlineScriptName = getUniqueNameForInlineHtmlNode(
232
369
  script,
233
- `window.__jsenv__.${jsenvMethod}(${JSON.stringify(src)})`,
370
+ scripts,
371
+ `[id].js`,
234
372
  )
235
- return
236
- }
237
-
238
- // inline module script
239
- const textNode = getHtmlNodeTextNode(script)
240
- if (typeAttribute && typeAttribute.value === "module" && textNode) {
241
- if (moduleOutFormat === "systemjs") {
242
- removeHtmlNodeAttribute(script, typeAttribute)
243
- }
244
- removeHtmlNodeAttribute(script, srcAttribute)
245
- const scriptAssetUrl = generateCompiledFileAssetUrl(
373
+ const scriptOriginalUrl = resolveUrl(inlineScriptName, url)
374
+ const scriptCompiledUrl = generateCompiledFileAssetUrl(
246
375
  compiledUrl,
247
- getUniqueNameForInlineHtmlNode(script, scripts, `[id].js`),
376
+ inlineScriptName,
248
377
  )
249
- const specifier = `./${urlToRelativeUrl(scriptAssetUrl, compiledUrl)}`
250
- inlineScriptsContentMap[specifier] = textNode.value
251
- const jsenvMethod =
252
- moduleOutFormat === "systemjs"
253
- ? "executeFileUsingSystemJs"
254
- : "executeFileUsingDynamicImport"
255
- setHtmlNodeText(
256
- script,
257
- `window.__jsenv__.${jsenvMethod}(${JSON.stringify(specifier)})`,
258
- )
259
- htmlDependencies.push({
378
+ addHtmlAssetGenerator(async () => {
379
+ return transformHtmlScript({
380
+ projectDirectoryUrl,
381
+ url: scriptOriginalUrl,
382
+ compiledUrl: scriptCompiledUrl,
383
+ code: textNode.value,
384
+
385
+ type: "module",
386
+ babelPluginMap,
387
+ moduleOutFormat,
388
+ importMetaFormat,
389
+ topLevelAwait,
390
+ sourcemapMethod,
391
+ })
392
+ })
393
+ const specifier = `./${urlToRelativeUrl(scriptCompiledUrl, compiledUrl)}`
394
+ addHtmlMutation(() => {
395
+ if (moduleOutFormat === "systemjs") {
396
+ removeHtmlNodeAttribute(script, typeAttribute)
397
+ }
398
+ removeHtmlNodeAttribute(script, srcAttribute)
399
+ const jsenvMethod =
400
+ moduleOutFormat === "systemjs"
401
+ ? "executeFileUsingSystemJs"
402
+ : "executeFileUsingDynamicImport"
403
+ setHtmlNodeText(
404
+ script,
405
+ `window.__jsenv__.${jsenvMethod}(${JSON.stringify(specifier)})`,
406
+ )
407
+ })
408
+ addHtmlDependency({
260
409
  htmlNode: script,
261
410
  specifier,
262
411
  })
263
412
  return
264
413
  }
265
- })
266
- const htmlAfterTransformation = stringifyHtmlAst(htmlAst)
267
414
 
268
- let assets = []
269
- let assetsContent = []
270
- await Promise.all(
271
- Object.keys(inlineScriptsContentMap).map(async (scriptSrc) => {
272
- const scriptAssetUrl = resolveUrl(scriptSrc, compiledUrl)
273
- const scriptBasename = urlToRelativeUrl(scriptAssetUrl, compiledUrl)
274
- const scriptOriginalFileUrl = resolveUrl(scriptBasename, url)
275
- const scriptCompiledFileUrl = resolveUrl(scriptBasename, compiledUrl)
276
-
277
- const scriptBeforeCompilation = inlineScriptsContentMap[scriptSrc]
278
- let scriptTransformResult
279
- try {
280
- scriptTransformResult = await transformJs({
281
- code: scriptBeforeCompilation,
282
- url: scriptOriginalFileUrl,
283
- compiledUrl: scriptCompiledFileUrl,
415
+ if (type === "application/javascript" || type === "text/javascript") {
416
+ if (src) {
417
+ const htmlServerUrl = url.replace(
418
+ projectDirectoryUrl,
419
+ `${compileServerOrigin}/`,
420
+ )
421
+ const scriptOriginalServerUrl = resolveUrl(src, htmlServerUrl)
422
+ const scriptOriginalUrl = scriptOriginalServerUrl.replace(
423
+ `${compileServerOrigin}/`,
284
424
  projectDirectoryUrl,
425
+ )
426
+ const fileIsInsideJsenvDistDirectory = urlIsInsideOf(
427
+ scriptOriginalUrl,
428
+ jsenvDistDirectoryUrl,
429
+ )
430
+ if (fileIsInsideJsenvDistDirectory) {
431
+ return
432
+ }
433
+
434
+ const scriptCompiledUrl = generateCompiledFileAssetUrl(
435
+ compiledUrl,
436
+ urlToFilename(scriptOriginalUrl),
437
+ )
438
+ addHtmlAssetGenerator(async () => {
439
+ // we fetch scriptOriginalUrl on purpose because we do
440
+ // the transformation here and not in compile server
441
+ // (because compile server would think it's a module script
442
+ // and add things like systemjs)
443
+ const scriptResponse = await fetchUrl(scriptOriginalUrl)
444
+ if (scriptResponse.status !== 200) {
445
+ logger.warn(
446
+ createDetailedMessage(
447
+ scriptResponse.status === 404
448
+ ? `script file cannot be found.`
449
+ : `script file unexpected response status (${scriptResponse.status}).`,
450
+ {
451
+ "script url": script.url,
452
+ "html url": url,
453
+ },
454
+ ),
455
+ )
456
+ return []
457
+ }
458
+ const scriptAsText = await scriptResponse.text()
459
+ addHtmlSourceFile({
460
+ url: scriptOriginalUrl,
461
+ content: scriptAsText,
462
+ })
463
+ return transformHtmlScript({
464
+ projectDirectoryUrl,
465
+ url: scriptOriginalUrl,
466
+ compiledUrl: scriptCompiledUrl,
467
+ code: scriptAsText,
285
468
 
469
+ type: "classic",
470
+ babelPluginMap,
471
+ moduleOutFormat,
472
+ importMetaFormat,
473
+ topLevelAwait,
474
+ sourcemapMethod,
475
+ })
476
+ })
477
+ addHtmlMutation(() => {
478
+ srcAttribute.value = `./${urlToRelativeUrl(
479
+ scriptCompiledUrl,
480
+ compiledUrl,
481
+ )}`
482
+ })
483
+ return
484
+ }
485
+ const inlineScriptName = getUniqueNameForInlineHtmlNode(
486
+ script,
487
+ scripts,
488
+ `[id].js`,
489
+ )
490
+ const scriptOriginalUrl = resolveUrl(inlineScriptName, url)
491
+ const scriptCompiledUrl = generateCompiledFileAssetUrl(
492
+ compiledUrl,
493
+ inlineScriptName,
494
+ )
495
+ addHtmlAssetGenerator(async () => {
496
+ const htmlAssets = await transformHtmlScript({
497
+ projectDirectoryUrl,
498
+ url: scriptOriginalUrl,
499
+ compiledUrl: scriptCompiledUrl,
500
+ code: textNode.value,
501
+
502
+ type: "classic",
286
503
  babelPluginMap,
287
504
  moduleOutFormat,
288
505
  importMetaFormat,
289
506
  topLevelAwait,
507
+ sourcemapMethod,
290
508
  })
291
- } catch (e) {
292
- // If there is a syntax error in inline script
293
- // we put the raw script without transformation.
294
- // when systemjs will try to instantiate to script it
295
- // will re-throw this syntax error.
296
- // Thanks to this we see the syntax error in the
297
- // document and livereloading still works
298
- // because we gracefully handle this error
299
- if (e.code === "PARSE_ERROR") {
300
- const code = scriptBeforeCompilation
301
- assets = [...assets, scriptAssetUrl]
302
- assetsContent = [...assetsContent, code]
303
- return
304
- }
305
- throw e
306
- }
307
- const sourcemapFileUrl = resolveUrl(
308
- `${scriptBasename}.map`,
309
- scriptCompiledFileUrl,
310
- )
509
+ addHtmlMutation(() => {
510
+ setHtmlNodeText(script, htmlAssets[0].content)
511
+ })
512
+ return htmlAssets
513
+ })
514
+ return
515
+ }
516
+ })
517
+ }
311
518
 
312
- let { code, map } = scriptTransformResult
313
- const sourcemapFileRelativePathForModule = urlToRelativeUrl(
314
- sourcemapFileUrl,
315
- compiledUrl,
316
- )
519
+ const transformHtmlScript = async ({
520
+ projectDirectoryUrl,
521
+ url,
522
+ compiledUrl,
523
+ code,
524
+ type,
317
525
 
318
- if (sourcemapMethod === "inline") {
319
- code = setJavaScriptSourceMappingUrl(code, sourcemapToBase64Url(map))
320
- } else {
321
- // TODO: respect "sourcemapMethod" parameter
322
- code = setJavaScriptSourceMappingUrl(
323
- code,
324
- sourcemapFileRelativePathForModule,
325
- )
326
- assets = [...assets, scriptAssetUrl, sourcemapFileUrl]
327
- assetsContent = [
328
- ...assetsContent,
329
- code,
330
- JSON.stringify(map, null, " "),
331
- ]
332
- }
333
- }),
334
- )
335
- sources.push(url)
336
- sourcesContent.push(code)
526
+ babelPluginMap,
527
+ moduleOutFormat,
528
+ importMetaFormat,
529
+ topLevelAwait,
530
+ sourcemapMethod,
531
+ }) => {
532
+ let transformResult
533
+ try {
534
+ transformResult = await transformJs({
535
+ code,
536
+ url,
537
+ compiledUrl,
538
+ projectDirectoryUrl,
337
539
 
338
- return {
339
- contentType: "text/html",
340
- compiledSource: htmlAfterTransformation,
341
- sources,
342
- sourcesContent,
343
- assets,
344
- assetsContent,
345
- dependencies: htmlDependencies.map(({ specifier }) => {
346
- return specifier
347
- }),
540
+ babelPluginMap,
541
+ moduleOutFormat: type === "module" ? moduleOutFormat : "global",
542
+ importMetaFormat,
543
+ topLevelAwait: type === "module" ? topLevelAwait : false,
544
+ babelHelpersInjectionAsImport: type === "module" ? undefined : false,
545
+ })
546
+ } catch (e) {
547
+ // If there is a syntax error in inline script
548
+ // we put the raw script without transformation.
549
+ // when systemjs will try to instantiate to script it
550
+ // will re-throw this syntax error.
551
+ // Thanks to this we see the syntax error in the
552
+ // document and livereloading still works
553
+ // because we gracefully handle this error
554
+ if (e.code === "PARSE_ERROR") {
555
+ return [{ url, content: code }]
556
+ }
557
+ throw e
348
558
  }
559
+
560
+ code = transformResult.code
561
+ let map = transformResult.map
562
+ const sourcemapUrl = resolveUrl(
563
+ `${urlToBasename(compiledUrl)}.map`,
564
+ compiledUrl,
565
+ )
566
+ if (sourcemapMethod === "inline") {
567
+ code = setJavaScriptSourceMappingUrl(code, sourcemapToBase64Url(map))
568
+ return [
569
+ {
570
+ url: compiledUrl,
571
+ content: code,
572
+ },
573
+ ]
574
+ }
575
+ const sourcemapSpecifier = urlToRelativeUrl(sourcemapUrl, compiledUrl)
576
+ code = setJavaScriptSourceMappingUrl(code, sourcemapSpecifier)
577
+ return [
578
+ {
579
+ url: compiledUrl,
580
+ content: code,
581
+ },
582
+ {
583
+ url: sourcemapUrl,
584
+ content: JSON.stringify(map, null, " "),
585
+ },
586
+ ]
349
587
  }
350
588
 
351
589
  // transform <link type="modulepreload"> into <link type="preload">
@@ -42,7 +42,10 @@ import {
42
42
  sourcemapMainFileInfo,
43
43
  sourcemapMappingFileInfo,
44
44
  } from "../jsenvInternalFiles.js"
45
- import { jsenvCoreDirectoryUrl } from "../jsenvCoreDirectoryUrl.js"
45
+ import {
46
+ jsenvCoreDirectoryUrl,
47
+ jsenvDistDirectoryUrl,
48
+ } from "../jsenvCoreDirectoryUrl.js"
46
49
  import { babelPluginReplaceExpressions } from "../babel_plugin_replace_expressions.js"
47
50
  import { babelPluginGlobalThisAsJsenvImport } from "./babel_plugin_global_this_as_jsenv_import.js"
48
51
  import { babelPluginNewStylesheetAsJsenvImport } from "./babel_plugin_new_stylesheet_as_jsenv_import.js"
@@ -945,7 +948,7 @@ const createSourceFileService = ({
945
948
  .href
946
949
  const fileIsInsideJsenvDistDirectory = urlIsInsideOf(
947
950
  fileUrl,
948
- new URL("./dist/", jsenvCoreDirectoryUrl),
951
+ jsenvDistDirectoryUrl,
949
952
  )
950
953
 
951
954
  const responsePromise = fetchFileSystem(fileUrl, {
@@ -17,4 +17,6 @@ if (typeof __filename === "string") {
17
17
  )
18
18
  }
19
19
 
20
+ export const jsenvDistDirectoryUrl = new URL("./dist/", jsenvCoreDirectoryUrl)
21
+
20
22
  export { jsenvCoreDirectoryUrl }