Repository navigation
Expand file tree
/
Copy pathrelease.go
More file actions
217 lines (202 loc) · 5.86 KB
/
Copy pathrelease.go
File metadata and controls
217 lines (202 loc) · 5.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package sitec
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"path"
"strings"
"webtyp.com/fmt"
"webtyp.com/image/favicon"
"webtyp.com/pwa"
)
// contentHash is the hex SHA-256 of content, 16 characters: the revision of a shell asset.
func contentHash(content []byte) string {
h := sha256.Sum256(content)
return hex.EncodeToString(h[:])[:16]
}
// releaseInput is what the final pass needs from the compiler.
type releaseInput struct {
CSSURL, JSURL string // GetURLPath() of the main stylesheet and script ("" = absent)
PWA *pwa.Config // nil = the project is not a PWA
Favicons []favicon.File // c.getFaviconFiles()
Log func(...any)
}
// finalizeRelease returns the artifacts of a release build: PWA tags and register script
// inserted (when PWA != nil), the main CSS and JS renamed by content hash with every
// HTML reference rewritten, and manifest.webmanifest + sw.js added (when PWA != nil).
func finalizeRelease(arts []Artifact, in releaseInput) ([]Artifact, error) {
out := make([]Artifact, len(arts))
copy(out, arts)
// 1. PWA head and script (only when in.PWA != nil)
var app pwa.App
var hasPWA bool
if in.PWA != nil {
hasPWA = true
if len(in.Favicons) == 0 {
return nil, fmt.Err(msgPWAWithoutIcon())
}
var icons []pwa.Icon
for _, f := range in.Favicons {
if f.Sizes == "192x192" || f.Sizes == "512x512" {
icons = append(icons, pwa.Icon{
URL: path.Join("/", f.Name),
Sizes: f.Sizes,
Type: f.Mediatype,
})
}
}
var err error
app, err = pwa.New(*in.PWA, icons)
if err != nil {
return nil, err
}
// Every artifact with mediatype text/html: insert app.HeadTags immediately before </head>
headEnd := "</head>"
for i, art := range out {
if art.Mediatype == "text/html" {
htmlStr := string(art.Content)
idx := strings.Index(htmlStr, headEnd)
if idx == -1 {
return nil, fmt.Err(fmt.Sprintf("sitec: %s has no </head> to insert the PWA tags into", art.Path))
}
newHTML := htmlStr[:idx] + app.HeadTags + htmlStr[idx:]
out[i].Content = []byte(newHTML)
}
}
// The artifact whose Path == in.JSURL: append "\n" + app.RegisterScript
if in.JSURL != "" {
for i, art := range out {
if art.Path == in.JSURL {
out[i].Content = append(out[i].Content, []byte("\n"+app.RegisterScript)...)
break
}
}
}
// Append manifest artifact
out = append(out, Artifact{
Path: pwa.ManifestPath,
Mediatype: "application/manifest+json",
Content: []byte(app.Manifest),
})
}
// 1.5 Recompute SRI and csp.json after PWA RegisterScript injection (or any final JS/CSS adjustment)
var jsSRI, cssSRI string
for _, art := range out {
if in.JSURL != "" && art.Path == in.JSURL {
jsSRI = sriSHA384(art.Content)
}
if in.CSSURL != "" && art.Path == in.CSSURL {
cssSRI = sriSHA384(art.Content)
}
}
if jsSRI != "" || cssSRI != "" {
for i, art := range out {
if art.Mediatype == "text/html" {
s := string(art.Content)
s = updateReleaseIntegrityInHTML(s, "script", "src", in.JSURL, jsSRI)
s = updateReleaseIntegrityInHTML(s, "link", "href", in.CSSURL, cssSRI)
out[i].Content = []byte(s)
}
}
if jsSRI != "" {
manifest := CSPManifest{ScriptHashes: []string{jsSRI}}
for _, art := range out {
if path.Base(art.Path) == CSPManifestFile {
var prev CSPManifest
if err := json.Unmarshal(art.Content, &prev); err == nil {
manifest.BlobWorkers = prev.BlobWorkers
manifest.BlobMedia = prev.BlobMedia
manifest.CrossOriginIsolated = prev.CrossOriginIsolated
}
break
}
}
if payload, err := json.Marshal(manifest); err == nil {
updated := false
for i, art := range out {
if path.Base(art.Path) == CSPManifestFile {
out[i].Content = payload
updated = true
break
}
}
if !updated {
out = append(out, Artifact{
Path: path.Join("/", CSPManifestFile),
Mediatype: "application/json",
Content: payload,
})
}
}
}
}
// 2. Hashed names (always in release)
targetURLs := []string{in.CSSURL, in.JSURL}
renames := make(map[string]string) // oldURL -> newURL
for _, old := range targetURLs {
if old == "" {
continue
}
for i, art := range out {
if art.Path == old {
dir := path.Dir(old)
base := path.Base(old)
newName := pwa.HashedName(base, art.Content)
newURL := path.Join(dir, newName)
if !strings.HasPrefix(old, "/") {
newURL = strings.TrimPrefix(newURL, "./")
newURL = strings.TrimPrefix(newURL, "/")
}
renames[old] = newURL
out[i].Path = newURL
break
}
}
}
// In every text/html artifact replace "old" with "newURL"
if len(renames) > 0 {
for i, art := range out {
if art.Mediatype == "text/html" {
contentStr := string(art.Content)
for old, newURL := range renames {
contentStr = strings.ReplaceAll(contentStr, `"`+old+`"`, `"`+newURL+`"`)
}
out[i].Content = []byte(contentStr)
}
}
}
// 3. Service worker (only when in.PWA != nil)
if hasPWA {
var shell []pwa.Asset
for _, art := range out {
if art.Path == pwa.ServiceWorkerPath || path.Base(art.Path) == CSPManifestFile {
continue
}
// Large artifacts are kept in OPFS by webtyp/artifacts, never precached.
if strings.HasPrefix(path.Join("/", art.Path)+"/", pwa.ArtifactsDir) {
continue
}
urlPath := art.Path
if !strings.HasPrefix(urlPath, "/") {
urlPath = path.Join("/", urlPath)
}
shell = append(shell, pwa.Asset{
URL: urlPath,
Revision: contentHash(art.Content),
})
}
worker, err := app.ServiceWorker(shell)
if err != nil {
return nil, err
}
out = append(out, Artifact{
Path: pwa.ServiceWorkerPath,
Mediatype: "text/javascript",
Content: []byte(worker.Script),
})
if in.Log != nil {
in.Log(fmt.Sprintf("PWA version %s, %d files precached", worker.Version, len(shell)))
}
}
return out, nil
}