Debian Codegraph @

resources/resource_transformers/js/js_integration_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package js_test
15
16 import (
17 "os"
18 "path/filepath"
19 "strings"
20 "testing"
21
22 qt "github.com/frankban/quicktest"
23 "github.com/gohugoio/hugo/common/paths"
24 "github.com/gohugoio/hugo/htesting"
25 "github.com/gohugoio/hugo/hugolib"
26 "github.com/gohugoio/hugo/internal/js/esbuild"
27 )
28
29 func TestBuildVariants(t *testing.T) {
30 c := qt.New(t)
31
32 mainWithImport := `
33 -- hugo.toml --
34 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
35 disableLiveReload = true
36 -- assets/js/main.js --
37 import { hello1, hello2 } from './util1';
38 hello1();
39 hello2();
40 -- assets/js/util1.js --
41 import { hello3 } from './util2';
42 export function hello1() {
43 return 'abcd';
44 }
45 export function hello2() {
46 return hello3();
47 }
48 -- assets/js/util2.js --
49 export function hello3() {
50 return 'efgh';
51 }
52 -- layouts/home.html --
53 {{ $js := resources.Get "js/main.js" | js.Build }}
54 JS Content:{{ $js.Content }}:End:
55
56 `
57
58 c.Run("Basic", func(c *qt.C) {
59 b := hugolib.Test(c, mainWithImport, hugolib.TestOptOsFs())
60
61 b.AssertFileContent("public/index.html", `abcd`)
62 })
63
64 c.Run("Edit Import", func(c *qt.C) {
65 b := hugolib.Test(c, mainWithImport, hugolib.TestOptRunning(), hugolib.TestOptOsFs())
66
67 b.AssertFileContent("public/index.html", `abcd`)
68 b.EditFileReplaceFunc("assets/js/util1.js", func(s string) string { return strings.ReplaceAll(s, "abcd", "1234") }).Build()
69 b.AssertFileContent("public/index.html", `1234`)
70 })
71
72 c.Run("Edit Import Nested", func(c *qt.C) {
73 b := hugolib.Test(c, mainWithImport, hugolib.TestOptRunning(), hugolib.TestOptOsFs())
74
75 b.AssertFileContent("public/index.html", `efgh`)
76 b.EditFileReplaceFunc("assets/js/util2.js", func(s string) string { return strings.ReplaceAll(s, "efgh", "1234") }).Build()
77 b.AssertFileContent("public/index.html", `1234`)
78 })
79 }
80
81 // Issue #15173.
82 func TestBuildDataArtifacts(t *testing.T) {
83 t.Parallel()
84
85 files := `
86 -- hugo.toml --
87 baseURL = "https://example.org/"
88 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
89 -- assets/js/main.js --
90 import { hello } from './util';
91 hello();
92 -- assets/js/util.js --
93 export function hello() {
94 return 'abcd';
95 }
96 -- layouts/home.html --
97 {{ with resources.Get "js/main.js" | js.Build (dict "minify" true "sourcemap" "external") }}
98 COUNT: {{ len .Data.Artifacts }}
99 {{ range .Data.Artifacts }}
100 ARTIFACT: {{ .RelPermalink }}|{{ .Permalink }}|{{ .MediaType.Type }}
101 {{ end }}
102 {{ end }}
103 {{ with resources.Get "js/main.js" | js.Build }}
104 COUNT2: {{ len .Data.Artifacts }}
105 {{ end }}
106 `
107
108 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
109 b.AssertFileContent("public/index.html",
110 "COUNT: 1",
111 "ARTIFACT: /js/main.js.map|https://example.org/js/main.js.map|application/source-map",
112 "COUNT2: 0",
113 )
114 b.AssertFileExists("public/js/main.js.map", true)
115 }
116
117 func TestBuildWithModAndNpm(t *testing.T) {
118 if !htesting.IsCI() {
119 t.Skip("skip (relative) long running modules test when running locally")
120 }
121
122 c := qt.New(t)
123
124 files := `
125 -- hugo.toml --
126 baseURL = "https://example.org"
127 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
128 [module]
129 [[module.imports]]
130 path="github.com/gohugoio/hugoTestProjectJSModImports"
131 -- go.mod --
132 module github.com/gohugoio/tests/testHugoModules
133
134 go 1.16
135
136 require github.com/gohugoio/hugoTestProjectJSModImports v0.10.0 // indirect
137 -- package.json --
138 {
139 "dependencies": {
140 "date-fns": "^2.16.1"
141 }
142 }
143
144 `
145 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
146 cfg.Verbose = true
147 }))
148
149 b.AssertFileContent("public/js/main.js", `
150 greeting: "greeting configured in mod2"
151 Hello1 from mod1: $
152 return "Hello2 from mod1";
153 var Hugo = "Rocks!";
154 Hello3 from mod2. Date from date-fns: ${today}
155 Hello from lib in the main project
156 Hello5 from mod2.
157 var myparam = "Hugo Rocks!";
158 shim cwd
159 `)
160
161 // React JSX, verify the shimming.
162 b.AssertFileContent("public/js/like.js", filepath.FromSlash(`@v0.10.0/assets/js/shims/react.js
163 module.exports = window.ReactDOM;
164 `))
165 }
166
167 func TestBuildWithNpm(t *testing.T) {
168 if !htesting.IsCI() {
169 t.Skip("skip (relative) long running modules test when running locally")
170 }
171
172 c := qt.New(t)
173
174 files := `
175 -- assets/js/included.js --
176 console.log("included");
177 -- assets/js/main.js --
178 import "./included";
179 import { toCamelCase } from "to-camel-case";
180
181 console.log("main");
182 console.log("To camel:", toCamelCase("space case"));
183 -- assets/js/myjsx.jsx --
184 import * as React from 'react'
185 import * as ReactDOM from 'react-dom'
186
187 ReactDOM.render(
188 <h1>Hello, world!</h1>,
189 document.getElementById('root')
190 );
191 -- assets/js/myts.ts --
192 function greeter(person: string) {
193 return "Hello, " + person;
194 }
195 let user = [0, 1, 2];
196 document.body.textContent = greeter(user);
197 -- hugo.toml --
198 disablekinds = ['taxonomy', 'term', 'page']
199 -- content/p1.md --
200 Content.
201 -- data/hugo.toml --
202 slogan = "Hugo Rocks!"
203 -- i18n/en.yaml --
204 hello:
205 other: "Hello"
206 -- i18n/fr.yaml --
207 hello:
208 other: "Bonjour"
209 -- layouts/home.html --
210 {{ $options := dict "minify" false "externals" (slice "react" "react-dom") "sourcemap" "linked" }}
211 {{ $js := resources.Get "js/main.js" | js.Build $options }}
212 JS: {{ template "print" $js }}
213 {{ $jsx := resources.Get "js/myjsx.jsx" | js.Build $options }}
214 JSX: {{ template "print" $jsx }}
215 {{ $ts := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "inline")}}
216 TS: {{ template "print" $ts }}
217 {{ $ts2 := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "external" "TargetPath" "js/myts2.js")}}
218 TS2: {{ template "print" $ts2 }}
219 {{ define "print" }}RelPermalink: {{.RelPermalink}}|MIME: {{ .MediaType }}|Content: {{ .Content | safeJS }}{{ end }}
220 -- package.json --
221 {
222 "scripts": {},
223
224 "dependencies": {
225 "to-camel-case": "1.0.0"
226 }
227 }
228 `
229
230 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall())
231
232 b.AssertFileContent("public/js/main.js", `//# sourceMappingURL=main.js.map`)
233 b.AssertFileContent("public/js/main.js.map", `"version":3`, "! ns-hugo") // linked
234 b.AssertFileContent("public/js/myts.js", `//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJz`) // inline
235 b.AssertFileContent("public/index.html", `
236 console.log(&#34;included&#34;);
237 if (hasSpace.test(string))
238 var React = __toESM(__require(&#34;react&#34;));
239 function greeter(person) {
240 `)
241
242 checkMap := func(p string, expectLen int) {
243 s := b.FileContent(p)
244 sources := esbuild.SourcesFromSourceMap(s)
245 b.Assert(sources, qt.HasLen, expectLen)
246
247 // Check that all source files exist.
248 for _, src := range sources {
249 filename, ok := paths.UrlStringToFilename(src)
250 b.Assert(ok, qt.IsTrue)
251 _, err := os.Stat(filename)
252 b.Assert(err, qt.IsNil, qt.Commentf("src: %q", src))
253 }
254 }
255
256 checkMap("public/js/main.js.map", 5)
257 }
258
259 func TestBuildError(t *testing.T) {
260 c := qt.New(t)
261
262 filesTemplate := `
263 -- hugo.toml --
264 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
265 -- assets/js/main.js --
266 // A comment.
267 import { hello1, hello2 } from './util1';
268 hello1();
269 hello2();
270 -- assets/js/util1.js --
271 /* Some
272 comments.
273 */
274 import { hello3 } from './util2';
275 export function hello1() {
276 return 'abcd';
277 }
278 export function hello2() {
279 return hello3();
280 }
281 -- assets/js/util2.js --
282 export function hello3() {
283 return 'efgh';
284 }
285 -- layouts/home.html --
286 {{ $js := resources.Get "js/main.js" | js.Build }}
287 JS Content:{{ $js.Content }}:End:
288
289 `
290
291 c.Run("Import from main not found", func(c *qt.C) {
292 c.Parallel()
293 files := strings.Replace(filesTemplate, "import { hello1, hello2 }", "import { hello1, hello2, FOOBAR }", 1)
294 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs())
295 b.Assert(err, qt.IsNotNil)
296 b.Assert(err.Error(), qt.Contains, `main.js:2:25": No matching export`)
297 })
298
299 c.Run("Import from import not found", func(c *qt.C) {
300 c.Parallel()
301 files := strings.Replace(filesTemplate, "import { hello3 } from './util2';", "import { hello3, FOOBAR } from './util2';", 1)
302 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs())
303 b.Assert(err, qt.IsNotNil)
304 b.Assert(err.Error(), qt.Contains, `util1.js:4:17": No matching export in`)
305 })
306 }
307
308 // See issue 10527.
309 func TestImportHugoVsESBuild(t *testing.T) {
310 c := qt.New(t)
311
312 for _, importSrcDir := range []string{"node_modules", "assets"} {
313 c.Run(importSrcDir, func(c *qt.C) {
314 files := `
315 -- IMPORT_SRC_DIR/imp1/index.js --
316 console.log("IMPORT_SRC_DIR:imp1/index.js");
317 -- IMPORT_SRC_DIR/imp2/index.ts --
318 console.log("IMPORT_SRC_DIR:imp2/index.ts");
319 -- IMPORT_SRC_DIR/imp3/foo.ts --
320 console.log("IMPORT_SRC_DIR:imp3/foo.ts");
321 -- assets/js/main.js --
322 import 'imp1/index.js';
323 import 'imp2/index.js';
324 import 'imp3/foo.js';
325 -- layouts/home.html --
326 {{ $js := resources.Get "js/main.js" | js.Build }}
327 {{ $js.RelPermalink }}
328 `
329
330 files = strings.ReplaceAll(files, "IMPORT_SRC_DIR", importSrcDir)
331
332 b := hugolib.Test(c, files, hugolib.TestOptOsFs())
333
334 expected := `
335 IMPORT_SRC_DIR:imp1/index.js
336 IMPORT_SRC_DIR:imp2/index.ts
337 IMPORT_SRC_DIR:imp3/foo.ts
338 `
339 expected = strings.ReplaceAll(expected, "IMPORT_SRC_DIR", importSrcDir)
340
341 b.AssertFileContent("public/js/main.js", expected)
342 })
343 }
344 }
345
346 // See https://github.com/evanw/esbuild/issues/2745
347 func TestPreserveLegalComments(t *testing.T) {
348 t.Parallel()
349
350 files := `
351 -- assets/js/main.js --
352 /* @license
353 * Main license.
354 */
355 import * as foo from 'js/utils';
356 console.log("Hello Main");
357 -- assets/js/utils/index.js --
358 export * from './util1';
359 export * from './util2';
360 -- assets/js/utils/util1.js --
361 /*! License util1 */
362 console.log("Hello 1");
363 -- assets/js/utils/util2.js --
364 //! License util2 */
365 console.log("Hello 2");
366 -- layouts/home.html --
367 {{ $js := resources.Get "js/main.js" | js.Build (dict "minify" false) }}
368 {{ $js.RelPermalink }}
369 `
370
371 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
372
373 b.AssertFileContent("public/js/main.js", `
374 License util1
375 License util2
376 Main license
377
378 `)
379 }
380
381 // Issue #11232
382 func TestTypeScriptExperimentalDecorators(t *testing.T) {
383 t.Parallel()
384 files := `
385 -- hugo.toml --
386 disableKinds = ['RSS','sitemap','taxonomy','term']
387 -- tsconfig.json --
388 {
389 "compilerOptions": {
390 "experimentalDecorators": true,
391 }
392 }
393 -- assets/ts/main.ts --
394 function addFoo(target: any) {target.prototype.foo = 'bar'}
395 @addFoo
396 class A {}
397 -- layouts/home.html --
398 {{ $opts := dict "target" "es2020" "targetPath" "js/main.js" }}
399 {{ (resources.Get "ts/main.ts" | js.Build $opts).Publish }}
400 `
401 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
402 b.AssertFileContent("public/js/main.js", "__decorateClass")
403 }
404
405 // Issue 13183.
406 func TestExternalsInAssets(t *testing.T) {
407 files := `
408 -- assets/js/util1.js --
409 export function hello1() {
410 return 'abcd';
411 }
412 -- assets/js/util2.js --
413 export function hello2() {
414 return 'efgh';
415 }
416 -- assets/js/main.js --
417 import { hello1 } from './util1.js';
418 import { hello2 } from './util2.js';
419
420 hello1();
421 hello2();
422 -- layouts/home.html --
423 Home.
424 {{ $js := resources.Get "js/main.js" | js.Build (dict "externals" (slice "./util1.js")) }}
425 {{ $js.Publish }}
426 `
427
428 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
429
430 b.AssertFileContent("public/js/main.js", "efgh")
431 b.AssertFileContent("public/js/main.js", "! abcd")
432 }
433
434 func TestBuildErrorStack(t *testing.T) {
435 files := `
436 -- hugo.toml --
437 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
438 -- assets/js/main.js --
439 import { hello1, hello2 } from './util1';
440 hello1();
441 -- layouts/home.html --
442 {{ $js := resources.Get "js/main.js" | js.Build }}
443 JS Content:{{ $js.Content }}:End:
444 `
445
446 b, err := hugolib.TestE(t, files, hugolib.TestOptOsFs())
447 b.Assert(err, qt.IsNotNil)
448 b.Assert(err.Error(), qt.Contains, `execute of template failed: template: home.html:2:17`)
449 b.Assert(err.Error(), qt.Contains, `main.js:1:31": Could not resolve "./util1"`)
450 }