-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
client.go
227 lines (198 loc) · 8.89 KB
/
client.go
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
218
219
220
221
222
223
224
225
226
227
package build
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"rogchap.com/v8go"
)
// SSRctx is a v8go context for loaded with components needed to render HTML.
var SSRctx *v8go.Context
// Client builds the SPA.
func Client(buildPath string) {
defer Benchmark(time.Now(), "Compiling client SPA with Svelte")
Log("\nCompiling client SPA with svelte")
stylePath := buildPath + "/spa/bundle.css"
// Set up counter for logging output.
compiledComponentCounter := 0
// Get svelte compiler code from node_modules.
compiler, err := ioutil.ReadFile("node_modules/svelte/compiler.js")
if err != nil {
fmt.Printf("Can't read node_modules/svelte/compiler.js: %v", err)
}
// Remove reference to 'self' that breaks v8go on line 19 of node_modules/svelte/compiler.js.
compilerStr := strings.Replace(string(compiler), "self.performance.now();", "'';", 1)
ctx, _ := v8go.NewContext(nil)
_, addCompilerErr := ctx.RunScript(compilerStr, "compile_svelte")
if addCompilerErr != nil {
fmt.Printf("Could not add svelte compiler: %v\n", addCompilerErr)
}
// Use v8go and add create_ssr_component() function.
createSsrComponent, npmReadErr := ioutil.ReadFile("node_modules/svelte/internal/index.js")
if npmReadErr != nil {
fmt.Printf("Can't read node_modules/svelte/internal/index.js: %v", npmReadErr)
}
// Fix "Cannot access 'on_destroy' before initialization" errors on line 1320 & line 1337 of node_modules/svelte/internal/index.js.
createSsrStr := strings.ReplaceAll(string(createSsrComponent), "function create_ssr_component(fn) {", "function create_ssr_component(fn) {var on_destroy= {};")
SSRctx, _ = v8go.NewContext(nil)
_, createFuncErr := SSRctx.RunScript(createSsrStr, "create_ssr")
if err != nil {
fmt.Printf("Could not add create_ssr_component() func from svelte/internal: %v", createFuncErr)
}
// Fix "ReferenceError: exports is not defined" errors on line 1319 (exports.current_component;).
SSRctx.RunScript("var exports = {};", "create_ssr")
compileSvelte(ctx, SSRctx, "ejected/router.svelte", buildPath+"/spa/ejected/router.js", stylePath)
// Go through all file paths in the "/layout" folder.
layoutFilesErr := filepath.Walk("layout", func(layoutPath string, layoutFileInfo os.FileInfo, err error) error {
// Create destination path.
destFile := buildPath + strings.Replace(layoutPath, "layout", "/spa", 1)
// Make sure path is a directory
if layoutFileInfo.IsDir() {
// Create any sub directories need for filepath.
os.MkdirAll(destFile, os.ModePerm)
} else {
// If the file is in .svelte format, compile it to .js
if filepath.Ext(layoutPath) == ".svelte" {
// Replace .svelte file extension with .js.
destFile = strings.TrimSuffix(destFile, filepath.Ext(destFile)) + ".js"
compileSvelte(ctx, SSRctx, layoutPath, destFile, stylePath)
compiledComponentCounter++
}
}
return nil
})
if layoutFilesErr != nil {
fmt.Printf("Could not get layout file: %s", layoutFilesErr)
}
Log("Number of components compiled: " + strconv.Itoa(compiledComponentCounter))
}
func compileSvelte(ctx *v8go.Context, SSRctx *v8go.Context, layoutPath string, destFile string, stylePath string) {
component, err := ioutil.ReadFile(layoutPath)
if err != nil {
fmt.Printf("Can't read component: %v", err)
}
componentStr := string(component)
// Compile component with Svelte.
ctx.RunScript("var { js, css } = svelte.compile(`"+componentStr+"`, {css: false});", "compile_svelte")
// Get the JS code from the compiled result.
jsCode, err := ctx.RunScript("js.code;", "compile_svelte")
if err != nil {
fmt.Printf("V8go could not execute js.code: %v", err)
}
jsBytes := []byte(jsCode.String())
jsWriteErr := ioutil.WriteFile(destFile, jsBytes, 0755)
if jsWriteErr != nil {
fmt.Printf("Unable to write file: %v", jsWriteErr)
}
// Get the CSS code from the compiled result.
cssCode, err := ctx.RunScript("css.code;", "compile_svelte")
if err != nil {
fmt.Printf("V8go could not execute css.code: %v", err)
}
cssStr := strings.TrimSpace(cssCode.String())
// If there is CSS, write it into the bundle.css file.
if cssStr != "null" {
cssFile, WriteStyleErr := os.OpenFile(stylePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if WriteStyleErr != nil {
fmt.Printf("Could not open bundle.css for writing: %s", WriteStyleErr)
}
defer cssFile.Close()
if _, err := cssFile.WriteString(cssStr); err != nil {
log.Println(err)
}
}
// Get Server Side Rendered (SSR) JS.
ctx.RunScript("var { js: ssrJs, css: ssrCss } = svelte.compile(`"+componentStr+"`, {generate: 'ssr'});", "compile_svelte")
ssrJsCode, err := ctx.RunScript("ssrJs.code;", "compile_svelte")
if err != nil {
fmt.Printf("V8go could not execute ssrJs.code: %v", err)
}
// Regex match static import statements.
reStaticImport := regexp.MustCompile(`import\s((.*)\sfrom(.*);|(((.*)\n){0,})\}\sfrom(.*);)`)
// Regex match static export statements.
reStaticExport := regexp.MustCompile(`export\s(.*);`)
// Remove static import statements.
ssrStr := reStaticImport.ReplaceAllString(ssrJsCode.String(), `/*$0*/`)
// Remove static export statements.
ssrStr = reStaticExport.ReplaceAllString(ssrStr, `/*$0*/`)
// Use var instead of const so it can be redeclared multiple times.
reConst := regexp.MustCompile(`(?m)^const\s`)
ssrStr = reConst.ReplaceAllString(ssrStr, "var ")
// Create custom variable name for component based on the file path for the layout.
componentSignature := strings.ReplaceAll(strings.ReplaceAll(layoutPath, "/", "_"), ".", "_")
// Use signature instead of generic "Component". Add space to avoid also replacing part of "loadComponent".
ssrStr = strings.ReplaceAll(ssrStr, " Component ", " "+componentSignature+" ")
namedExports := reStaticExport.FindAllStringSubmatch(ssrStr, -1)
// Loop through all export statements.
for _, namedExport := range namedExports {
// Get exported functions that aren't default.
if !strings.HasPrefix(namedExport[1], "default ") {
exportName := strings.Trim(namedExport[1], "{ }")
if exportName != "" && componentSignature != "" {
if strings.Contains(ssrStr, "return ``;") {
ssrStr = strings.ReplaceAll(ssrStr, componentSignature, componentSignature+"_NOT_USED")
}
ssrStr = strings.ReplaceAll(ssrStr, exportName, componentSignature)
}
}
}
// Replace import references with variable signatures.
reStaticImportPath := regexp.MustCompile(`(?:'|").*(?:'|")`)
reStaticImportName := regexp.MustCompile(`import\s(.*)\sfrom`)
namedImports := reStaticImport.FindAllString(ssrStr, -1)
for _, namedImport := range namedImports {
// Get path only from static import statement.
importPath := reStaticImportPath.FindString(namedImport)
importNameSlice := reStaticImportName.FindStringSubmatch(namedImport)
importNameStr := ""
if len(importNameSlice) > 0 {
importNameStr = strings.Trim(importNameSlice[1], "{ }")
}
// Remove quotes around path.
importPath = strings.Trim(importPath, `'"`)
// Get individual path arguments.
layoutParts := strings.Split(layoutPath, "/")
layoutFileName := layoutParts[len(layoutParts)-1]
layoutRootPath := strings.TrimSuffix(layoutPath, layoutFileName)
importParts := strings.Split(importPath, "/")
// Initialize the import signature that will be used for unique variable names.
importSignature := ""
// Check if the path ends with a file extension, e.g. ".svelte".
if len(filepath.Ext(importParts[len(importParts)-1])) > 1 {
for _, importPart := range importParts {
// Check if path starts relative to current folder.
if importPart == "." {
// Remove the proceeding dot so the file can be combined with the root.
importPath = strings.TrimPrefix(importPath, "./")
}
// Check if path goes up a folder.
if importPart == ".." {
// Remove the proceeding double dots so it can be combined with root.
importPath = strings.TrimPrefix(importPath, importPart+"/")
// Split the layout root path so we can remove the last segment since the double dots indicates going back a folder.
layoutParts = strings.Split(layoutRootPath, "/")
layoutRootPath = strings.TrimSuffix(layoutRootPath, layoutParts[len(layoutParts)-2]+"/")
}
}
// Create the variable name from the full path.
importSignature = strings.ReplaceAll(strings.ReplaceAll((layoutRootPath+importPath), "/", "_"), ".", "_")
// TODO: Use regex ^ string replacement is dangerous, e.g. It will replace "Component" but also part of "loadComponent".
}
// TODO: Add an else ^ to account for NPM dependencies?
// Check that there is a valid import to replace.
if importNameStr != "" && importSignature != "" {
// Use the signature everywhere the imported name is referenced.
ssrStr = strings.ReplaceAll(ssrStr, importNameStr, importSignature)
}
}
// Add component to context so it can be used to render HTML in data_source.go.
_, addSSRCompErr := SSRctx.RunScript(ssrStr, "create_ssr")
if addSSRCompErr != nil {
fmt.Printf("Could not add SSR Component: %v\n", addSSRCompErr)
}
}