Debian Codegraph @

resources/resource_transformers/js/js_integration_test.go

raw ◀ ▶
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 "runtime"
20 "strings"
21 "testing"
22
23 qt "github.com/frankban/quicktest"
24 "github.com/gohugoio/hugo/common/paths"
25 "github.com/gohugoio/hugo/htesting"
26 "github.com/gohugoio/hugo/hugolib"
27 "github.com/gohugoio/hugo/internal/js/esbuild"
28 )
29
30 func TestBuildVariants(t *testing.T) {
31 c := qt.New(t)
32
33 mainWithImport := `
34 -- hugo.toml --
35 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
36 disableLiveReload = true
37 -- assets/js/main.js --
38 import { hello1, hello2 } from './util1';
39 hello1();
40 hello2();
41 -- assets/js/util1.js --
42 import { hello3 } from './util2';
43 export function hello1() {
44 return 'abcd';
45 }
46 export function hello2() {
47 return hello3();
48 }
49 -- assets/js/util2.js --
50 export function hello3() {
51 return 'efgh';
52 }
53 -- layouts/home.html --
54 {{ $js := resources.Get "js/main.js" | js.Build }}
55 JS Content:{{ $js.Content }}:End:
56
57 `
58
59 c.Run("Basic", func(c *qt.C) {
60 b := hugolib.Test(c, mainWithImport, hugolib.TestOptOsFs())
61
62 b.AssertFileContent("public/index.html", `abcd`)
63 })
64
65 c.Run("Edit Import", func(c *qt.C) {
66 b := hugolib.Test(c, mainWithImport, hugolib.TestOptRunning(), hugolib.TestOptOsFs())
67
68 b.AssertFileContent("public/index.html", `abcd`)
69 b.EditFileReplaceFunc("assets/js/util1.js", func(s string) string { return strings.ReplaceAll(s, "abcd", "1234") }).Build()
70 b.AssertFileContent("public/index.html", `1234`)
71 })
72
73 c.Run("Edit Import Nested", func(c *qt.C) {
74 b := hugolib.Test(c, mainWithImport, hugolib.TestOptRunning(), hugolib.TestOptOsFs())
75
76 b.AssertFileContent("public/index.html", `efgh`)
77 b.EditFileReplaceFunc("assets/js/util2.js", func(s string) string { return strings.ReplaceAll(s, "efgh", "1234") }).Build()
78 b.AssertFileContent("public/index.html", `1234`)
79 })
80 }
81
82 // Issue #15173.
83 func TestBuildDataArtifacts(t *testing.T) {
84 t.Parallel()
85
86 files := `
87 -- hugo.toml --
88 baseURL = "https://example.org/"
89 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
90 -- assets/js/main.js --
91 import { hello } from './util';
92 hello();
93 -- assets/js/util.js --
94 export function hello() {
95 return 'abcd';
96 }
97 -- layouts/home.html --
98 {{ with resources.Get "js/main.js" | js.Build (dict "minify" true "sourcemap" "external") }}
99 COUNT: {{ len .Data.Artifacts }}
100 {{ range .Data.Artifacts }}
101 ARTIFACT: {{ .RelPermalink }}|{{ .Permalink }}|{{ .MediaType.Type }}
102 {{ end }}
103 {{ end }}
104 {{ with resources.Get "js/main.js" | js.Build }}
105 COUNT2: {{ len .Data.Artifacts }}
106 {{ end }}
107 `
108
109 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
110 b.AssertFileContent("public/index.html",
111 "COUNT: 1",
112 "ARTIFACT: /js/main.js.map|https://example.org/js/main.js.map|application/source-map",
113 "COUNT2: 0",
114 )
115 b.AssertFileExists("public/js/main.js.map", true)
116 }
117
118 func TestBuildWithModAndNpm(t *testing.T) {
•119 if os.Getenv("AUTOPKGTEST_TMP") == "" {
120 t.Skip("Skip test as network is inaccessible during Debian package build")
121 }
122 if !htesting.IsCI() {
123 t.Skip("skip (relative) long running modules test when running locally")
124 }
125
126 c := qt.New(t)
127
128 files := `
129 -- hugo.toml --
130 baseURL = "https://example.org"
131 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
132 [module]
133 [[module.imports]]
134 path="github.com/gohugoio/hugoTestProjectJSModImports"
135 -- go.mod --
136 module github.com/gohugoio/tests/testHugoModules
137
138 go 1.16
139
140 require github.com/gohugoio/hugoTestProjectJSModImports v0.10.0 // indirect
141 -- package.json --
142 {
143 "dependencies": {
144 "date-fns": "^2.16.1"
145 }
146 }
147
148 `
149 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
150 cfg.Verbose = true
151 }))
152
153 b.AssertFileContent("public/js/main.js", `
154 greeting: "greeting configured in mod2"
155 Hello1 from mod1: $
156 return "Hello2 from mod1";
157 var Hugo = "Rocks!";
158 Hello3 from mod2. Date from date-fns: ${today}
159 Hello from lib in the main project
160 Hello5 from mod2.
161 var myparam = "Hugo Rocks!";
162 shim cwd
163 `)
164
165 // React JSX, verify the shimming.
166 b.AssertFileContent("public/js/like.js", filepath.FromSlash(`@v0.10.0/assets/js/shims/react.js
167 module.exports = window.ReactDOM;
168 `))
169 }
170
171 func TestBuildWithNpm(t *testing.T) {
•172 if os.Getenv("AUTOPKGTEST_TMP") == "" {
173 t.Skip("Skip test as network is inaccessible during Debian package build")
174 }
175 if !htesting.IsCI() {
176 t.Skip("skip (relative) long running modules test when running locally")
177 }
178
179 c := qt.New(t)
180
181 files := `
182 -- assets/js/included.js --
183 console.log("included");
184 -- assets/js/main.js --
185 import "./included";
186 import { toCamelCase } from "to-camel-case";
187
188 console.log("main");
189 console.log("To camel:", toCamelCase("space case"));
190 -- assets/js/myjsx.jsx --
191 import * as React from 'react'
192 import * as ReactDOM from 'react-dom'
193
194 ReactDOM.render(
195 <h1>Hello, world!</h1>,
196 document.getElementById('root')
197 );
198 -- assets/js/myts.ts --
199 function greeter(person: string) {
200 return "Hello, " + person;
201 }
202 let user = [0, 1, 2];
203 document.body.textContent = greeter(user);
204 -- hugo.toml --
205 disablekinds = ['taxonomy', 'term', 'page']
206 -- content/p1.md --
207 Content.
208 -- data/hugo.toml --
209 slogan = "Hugo Rocks!"
210 -- i18n/en.yaml --
211 hello:
212 other: "Hello"
213 -- i18n/fr.yaml --
214 hello:
215 other: "Bonjour"
216 -- layouts/home.html --
217 {{ $options := dict "minify" false "externals" (slice "react" "react-dom") "sourcemap" "linked" }}
218 {{ $js := resources.Get "js/main.js" | js.Build $options }}
219 JS: {{ template "print" $js }}
220 {{ $jsx := resources.Get "js/myjsx.jsx" | js.Build $options }}
221 JSX: {{ template "print" $jsx }}
222 {{ $ts := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "inline")}}
223 TS: {{ template "print" $ts }}
224 {{ $ts2 := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "external" "TargetPath" "js/myts2.js")}}
225 TS2: {{ template "print" $ts2 }}
226 {{ define "print" }}RelPermalink: {{.RelPermalink}}|MIME: {{ .MediaType }}|Content: {{ .Content | safeJS }}{{ end }}
227 -- package.json --
228 {
229 "scripts": {},
230
231 "dependencies": {
232 "to-camel-case": "1.0.0"
233 }
234 }
235 `
236
237 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall())
238
239 b.AssertFileContent("public/js/main.js", `//# sourceMappingURL=main.js.map`)
240 b.AssertFileContent("public/js/main.js.map", `"version":3`, "! ns-hugo") // linked
241 b.AssertFileContent("public/js/myts.js", `//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJz`) // inline
242 b.AssertFileContent("public/index.html", `
243 console.log(&#34;included&#34;);
244 if (hasSpace.test(string))
245 var React = __toESM(__require(&#34;react&#34;));
246 function greeter(person) {
247 `)
248
249 checkMap := func(p string, expectLen int) {
250 s := b.FileContent(p)
251 sources := esbuild.SourcesFromSourceMap(s)
252 b.Assert(sources, qt.HasLen, expectLen)
253
254 // Check that all source files exist.
255 for _, src := range sources {
256 filename, ok := paths.UrlStringToFilename(src)
257 b.Assert(ok, qt.IsTrue)
258 _, err := os.Stat(filename)
259 b.Assert(err, qt.IsNil, qt.Commentf("src: %q", src))
260 }
261 }
262
263 checkMap("public/js/main.js.map", 5)
264 }
265
266 func TestBuildError(t *testing.T) {
267 c := qt.New(t)
268
269 filesTemplate := `
270 -- hugo.toml --
271 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
272 -- assets/js/main.js --
273 // A comment.
274 import { hello1, hello2 } from './util1';
275 hello1();
276 hello2();
277 -- assets/js/util1.js --
278 /* Some
279 comments.
280 */
281 import { hello3 } from './util2';
282 export function hello1() {
283 return 'abcd';
284 }
285 export function hello2() {
286 return hello3();
287 }
288 -- assets/js/util2.js --
289 export function hello3() {
290 return 'efgh';
291 }
292 -- layouts/home.html --
293 {{ $js := resources.Get "js/main.js" | js.Build }}
294 JS Content:{{ $js.Content }}:End:
295
296 `
297
298 c.Run("Import from main not found", func(c *qt.C) {
299 c.Parallel()
300 files := strings.Replace(filesTemplate, "import { hello1, hello2 }", "import { hello1, hello2, FOOBAR }", 1)
301 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs())
302 b.Assert(err, qt.IsNotNil)
303 b.Assert(err.Error(), qt.Contains, `main.js:2:25": No matching export`)
304 })
305
306 c.Run("Import from import not found", func(c *qt.C) {
307 c.Parallel()
308 files := strings.Replace(filesTemplate, "import { hello3 } from './util2';", "import { hello3, FOOBAR } from './util2';", 1)
309 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs())
310 b.Assert(err, qt.IsNotNil)
311 b.Assert(err.Error(), qt.Contains, `util1.js:4:17": No matching export in`)
312 })
313 }
314
315 // See issue 10527.
316 func TestImportHugoVsESBuild(t *testing.T) {
317 c := qt.New(t)
318
319 for _, importSrcDir := range []string{"node_modules", "assets"} {
320 c.Run(importSrcDir, func(c *qt.C) {
321 files := `
322 -- IMPORT_SRC_DIR/imp1/index.js --
323 console.log("IMPORT_SRC_DIR:imp1/index.js");
324 -- IMPORT_SRC_DIR/imp2/index.ts --
325 console.log("IMPORT_SRC_DIR:imp2/index.ts");
326 -- IMPORT_SRC_DIR/imp3/foo.ts --
327 console.log("IMPORT_SRC_DIR:imp3/foo.ts");
328 -- assets/js/main.js --
329 import 'imp1/index.js';
330 import 'imp2/index.js';
331 import 'imp3/foo.js';
332 -- layouts/home.html --
333 {{ $js := resources.Get "js/main.js" | js.Build }}
334 {{ $js.RelPermalink }}
335 `
336
337 files = strings.ReplaceAll(files, "IMPORT_SRC_DIR", importSrcDir)
338
339 b := hugolib.Test(c, files, hugolib.TestOptOsFs())
340
341 expected := `
342 IMPORT_SRC_DIR:imp1/index.js
343 IMPORT_SRC_DIR:imp2/index.ts
344 IMPORT_SRC_DIR:imp3/foo.ts
345 `
346 expected = strings.ReplaceAll(expected, "IMPORT_SRC_DIR", importSrcDir)
347
348 b.AssertFileContent("public/js/main.js", expected)
349 })
350 }
351 }
352
353 // See https://github.com/evanw/esbuild/issues/2745
354 func TestPreserveLegalComments(t *testing.T) {
355 t.Parallel()
356
357 files := `
358 -- assets/js/main.js --
359 /* @license
360 * Main license.
361 */
362 import * as foo from 'js/utils';
363 console.log("Hello Main");
364 -- assets/js/utils/index.js --
365 export * from './util1';
366 export * from './util2';
367 -- assets/js/utils/util1.js --
368 /*! License util1 */
369 console.log("Hello 1");
370 -- assets/js/utils/util2.js --
371 //! License util2 */
372 console.log("Hello 2");
373 -- layouts/home.html --
374 {{ $js := resources.Get "js/main.js" | js.Build (dict "minify" false) }}
375 {{ $js.RelPermalink }}
376 `
377
378 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
379
380 b.AssertFileContent("public/js/main.js", `
381 License util1
382 License util2
383 Main license
384
385 `)
386 }
387
388 // Issue #11232
389 func TestTypeScriptExperimentalDecorators(t *testing.T) {
390 t.Parallel()
391 files := `
392 -- hugo.toml --
393 disableKinds = ['RSS','sitemap','taxonomy','term']
394 -- tsconfig.json --
395 {
396 "compilerOptions": {
397 "experimentalDecorators": true,
398 }
399 }
400 -- assets/ts/main.ts --
401 function addFoo(target: any) {target.prototype.foo = 'bar'}
402 @addFoo
403 class A {}
404 -- layouts/home.html --
405 {{ $opts := dict "target" "es2020" "targetPath" "js/main.js" }}
406 {{ (resources.Get "ts/main.ts" | js.Build $opts).Publish }}
407 `
408 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
409 b.AssertFileContent("public/js/main.js", "__decorateClass")
410 }
411
412 // Issue 13183.
413 func TestExternalsInAssets(t *testing.T) {
414 files := `
415 -- assets/js/util1.js --
416 export function hello1() {
417 return 'abcd';
418 }
419 -- assets/js/util2.js --
420 export function hello2() {
421 return 'efgh';
422 }
423 -- assets/js/main.js --
424 import { hello1 } from './util1.js';
425 import { hello2 } from './util2.js';
426
427 hello1();
428 hello2();
429 -- layouts/home.html --
430 Home.
431 {{ $js := resources.Get "js/main.js" | js.Build (dict "externals" (slice "./util1.js")) }}
432 {{ $js.Publish }}
433 `
434
435 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
436
437 b.AssertFileContent("public/js/main.js", "efgh")
438 b.AssertFileContent("public/js/main.js", "! abcd")
439 }
440
441 func TestBuildErrorStack(t *testing.T) {
442 files := `
443 -- hugo.toml --
444 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
445 -- assets/js/main.js --
446 import { hello1, hello2 } from './util1';
447 hello1();
448 -- layouts/home.html --
449 {{ $js := resources.Get "js/main.js" | js.Build }}
450 JS Content:{{ $js.Content }}:End:
451 `
452
453 b, err := hugolib.TestE(t, files, hugolib.TestOptOsFs())
454 b.Assert(err, qt.IsNotNil)
455 b.Assert(err.Error(), qt.Contains, `execute of template failed: template: home.html:2:17`)
456 b.Assert(err.Error(), qt.Contains, `main.js:1:31": Could not resolve "./util1"`)
457 }
458
459 // ESBuild resolves imports not found in /assets on its own, following symlinks
460 // and with no notion of the project root.
461 func TestBuildImportOutsideProject(t *testing.T) {
462 c := qt.New(t)
463
464 base := t.TempDir()
465 secret := filepath.Join(base, "secret.txt")
466 c.Assert(os.WriteFile(secret, []byte("PWN-SECRET"), 0o644), qt.IsNil)
467
468 files := `
469 -- hugo.toml --
470 disableKinds = ["taxonomy", "term", "rss", "sitemap", "robotsTXT", "section", "page"]
471 theme = "mytheme"
472 SECURITY
473 -- themes/mytheme/hugo.toml --
474 -- themes/mytheme/assets/js/main.js --
475 import secret from "IMPORT";
476 import { helper } from "./helper.js";
477 console.log(secret, helper);
478 -- themes/mytheme/assets/js/helper.js --
479 export const helper = "LOCAL-HELPER-OK";
480 -- layouts/all.html --
481 {{ $js := resources.Get "js/main.js" | js.Build }}
482 RESULT:<pre>{{ $js.Content }}</pre>
483 `
484
485 build := func(c *qt.C, workingDir, imp, security string) (*hugolib.IntegrationTestBuilder, error) {
486 f := strings.ReplaceAll(files, "IMPORT", imp)
487 f = strings.ReplaceAll(f, "SECURITY", security)
488 return hugolib.NewIntegrationTestBuilder(
489 hugolib.IntegrationTestConfig{
490 T: c,
491 TxtarString: f,
492 NeedsOsFS: true,
493 WorkingDir: workingDir,
494 },
495 ).BuildE()
496 }
497
498 const outsideErr = `.*"[^"]*secret.txt" resolves to "[^"]*secret.txt" outside the project.*allowRead.*`
499
500 c.Run("Relative import", func(c *qt.C) {
501 _, err := build(c, filepath.Join(base, "relative"), "../secret.txt", "")
502 c.Assert(err, qt.ErrorMatches, outsideErr)
503 })
504
505 c.Run("Symlink in theme", func(c *qt.C) {
506 if runtime.GOOS == "windows" {
507 c.Skip("symlinks")
508 }
509 workingDir := filepath.Join(base, "symlink")
510 linkDir := filepath.Join(workingDir, "themes", "mytheme", "assets", "link")
511 c.Assert(os.MkdirAll(linkDir, 0o755), qt.IsNil)
512 c.Assert(os.Symlink(secret, filepath.Join(linkDir, "cred.txt")), qt.IsNil)
513 _, err := build(c, workingDir, "./themes/mytheme/assets/link/cred.txt", "")
514 c.Assert(err, qt.ErrorMatches, outsideErr)
515 })
516
517 c.Run("Relative import, target in allowRead", func(c *qt.C) {
518 b, err := build(c, filepath.Join(base, "allowed"), "../secret.txt", `
519 [security.node.permissions]
520 allowRead = [".", ".."]
521 `)
522 c.Assert(err, qt.IsNil)
523 b.AssertFileContent("public/index.html", "PWN-SECRET", "LOCAL-HELPER-OK")
524 })
525 }