Debian Codegraph @

livereload/livereload.go

raw
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 // Contains an embedded version of livereload.js
15 //
16 // Copyright (c) 2010-2015 Andrey Tarantsov
17 //
18 // Permission is hereby granted, free of charge, to any person obtaining
19 // a copy of this software and associated documentation files (the
20 // "Software"), to deal in the Software without restriction, including
21 // without limitation the rights to use, copy, modify, merge, publish,
22 // distribute, sublicense, and/or sell copies of the Software, and to
23 // permit persons to whom the Software is furnished to do so, subject to
24 // the following conditions:
25 //
26 // The above copyright notice and this permission notice shall be
27 // included in all copies or substantial portions of the Software.
28 //
29 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
33 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
34 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36
37 package livereload
38
39 import (
40 "fmt"
41 "net"
42 "net/http"
43 "net/url"
44 "path/filepath"
45
46 _ "embed"
47
48 "github.com/gohugoio/hugo/media"
49 "github.com/gorilla/websocket"
50 )
51
52 // Prefix to signal to LiveReload that we need to navigate to another path.
53 // Do not change this.
54 const hugoNavigatePrefix = "__hugo_navigate"
55
56 var upgrader = &websocket.Upgrader{
57 // Hugo may potentially spin up multiple HTTP servers, so we need to exclude the
58 // port when checking the origin.
59 CheckOrigin: func(r *http.Request) bool {
60 origin := r.Header["Origin"]
61 if len(origin) == 0 {
62 return true
63 }
64 u, err := url.Parse(origin[0])
65 if err != nil {
66 return false
67 }
68
69 rHost := r.Host
70 // For Github codespace in browser #9936
71 if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
72 rHost = forwardedHost
73 }
74
75 if u.Host == rHost {
76 return true
77 }
78
79 h1, _, err := net.SplitHostPort(u.Host)
80 if err != nil {
81 return false
82 }
83 h2, _, err := net.SplitHostPort(r.Host)
84 if err != nil {
85 return false
86 }
87
88 return h1 == h2
89 },
90 ReadBufferSize: 1024, WriteBufferSize: 1024,
91 }
92
93 // Handler is a HandlerFunc handling the livereload
94 // Websocket interaction.
95 func Handler(w http.ResponseWriter, r *http.Request) {
96 ws, err := upgrader.Upgrade(w, r, nil)
97 if err != nil {
98 return
99 }
100 c := &connection{send: make(chan []byte, 256), ws: ws}
101 wsHub.register <- c
102 defer func() { wsHub.unregister <- c }()
103 go c.writer()
104 c.reader()
105 }
106
107 // Initialize starts the Websocket Hub handling live reloads.
108 func Initialize() {
109 go wsHub.run()
110 }
111
112 // ForceRefresh tells livereload to force a hard refresh.
113 func ForceRefresh() {
114 RefreshPath("/x.js")
115 }
116
117 // NavigateToPathForPort is similar to NavigateToPath but will also
118 // set window.location.port to the given port value.
119 func NavigateToPathForPort(path string, port int) {
120 refreshPathForPort(hugoNavigatePrefix+path, port)
121 }
122
123 // RefreshPath tells livereload to refresh only the given path.
124 // If that path points to a CSS stylesheet or an image, only the changes
125 // will be updated in the browser, not the entire page.
126 func RefreshPath(s string) {
127 refreshPathForPort(s, -1)
128 }
129
130 func refreshPathForPort(s string, port int) {
131 // Tell livereload a file has changed - will force a hard refresh if not CSS or an image
132 urlPath := filepath.ToSlash(s)
133 portStr := ""
134 if port > 0 {
135 portStr = fmt.Sprintf(`, "overrideURL": %d`, port)
136 }
137 msg := fmt.Sprintf(`{"command":"reload","path":%q,"originalPath":"","liveCSS":true,"liveImg":true%s}`, urlPath, portStr)
138 wsHub.broadcast <- []byte(msg)
139 }
140
141 // ServeJS serves the livereload.js who's reference is injected into the page.
142 func ServeJS(w http.ResponseWriter, r *http.Request) {
143 w.Header().Set("Content-Type", media.Builtin.JavascriptType.Type)
144 w.Write(liveReloadJS())
145 }
146
147 func liveReloadJS() []byte {
148 return []byte(livereloadJS)
149 }
150
151 //go:embed livereload.min.js
152 var livereloadJS string