blob: 9f91c61b384b1f6e9a79c4a4cb2148f6e63d7d6f [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package webui provides the web interface for the sketch loop.
2// It bundles typescript files into JavaScript using esbuild.
Earl Lee2e463fb2025-04-17 11:22:22 -07003package webui
4
5import (
David Crawshaw8bff16a2025-04-18 01:16:49 -07006 "archive/zip"
7 "bytes"
Philip Zeyliger176de792025-04-21 12:25:18 -07008 "compress/gzip"
Earl Lee2e463fb2025-04-17 11:22:22 -07009 "crypto/sha256"
10 "embed"
11 "encoding/hex"
12 "fmt"
13 "io"
14 "io/fs"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "strings"
19
20 esbuildcli "github.com/evanw/esbuild/pkg/cli"
21)
22
Sean McCullough86b56862025-04-18 13:04:03 -070023//go:embed package.json package-lock.json src tsconfig.json
Earl Lee2e463fb2025-04-17 11:22:22 -070024var embedded embed.FS
25
Josh Bleecher Snydere634d262025-04-30 09:52:24 -070026//go:generate go run ../cmd/go2ts -o src/types.ts
27
Earl Lee2e463fb2025-04-17 11:22:22 -070028func embeddedHash() (string, error) {
29 h := sha256.New()
30 err := fs.WalkDir(embedded, ".", func(path string, d fs.DirEntry, err error) error {
31 if d.IsDir() {
32 return nil
33 }
34 f, err := embedded.Open(path)
35 if err != nil {
36 return err
37 }
38 defer f.Close()
39 if _, err := io.Copy(h, f); err != nil {
40 return fmt.Errorf("%s: %w", path, err)
41 }
42 return nil
43 })
44 if err != nil {
45 return "", fmt.Errorf("embedded hash: %w", err)
46 }
David Crawshaw8bff16a2025-04-18 01:16:49 -070047 return hex.EncodeToString(h.Sum(nil))[:32], nil
Earl Lee2e463fb2025-04-17 11:22:22 -070048}
49
50func cleanBuildDir(buildDir string) error {
51 err := fs.WalkDir(os.DirFS(buildDir), ".", func(path string, d fs.DirEntry, err error) error {
52 if d.Name() == "." {
53 return nil
54 }
55 if d.Name() == "node_modules" {
56 return fs.SkipDir
57 }
58 osPath := filepath.Join(buildDir, path)
Earl Lee2e463fb2025-04-17 11:22:22 -070059 os.RemoveAll(osPath)
60 if d.IsDir() {
61 return fs.SkipDir
62 }
63 return nil
64 })
65 if err != nil {
66 return fmt.Errorf("clean build dir: %w", err)
67 }
68 return nil
69}
70
71func unpackFS(out string, srcFS fs.FS) error {
72 err := fs.WalkDir(srcFS, ".", func(path string, d fs.DirEntry, err error) error {
73 if d.Name() == "." {
74 return nil
75 }
76 if d.IsDir() {
77 if err := os.Mkdir(filepath.Join(out, path), 0o777); err != nil {
78 return err
79 }
80 return nil
81 }
82 f, err := srcFS.Open(path)
83 if err != nil {
84 return err
85 }
86 defer f.Close()
87 dst, err := os.Create(filepath.Join(out, path))
88 if err != nil {
89 return err
90 }
91 defer dst.Close()
92 if _, err := io.Copy(dst, f); err != nil {
93 return err
94 }
95 if err := dst.Close(); err != nil {
96 return err
97 }
98 return nil
99 })
100 if err != nil {
101 return fmt.Errorf("unpack fs into out dir %s: %w", out, err)
102 }
103 return nil
104}
105
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700106// TODO: This path being /root/.cache/sketch/webui/skui-....zip means that the Dockerfile
107// in createdockerfile.go needs to create the parent directory. Ideally we bundle the built webui
108// into the binary and avoid this altogether.
David Crawshaw8bff16a2025-04-18 01:16:49 -0700109func zipPath() (cacheDir, hashZip string, err error) {
110 homeDir, err := os.UserHomeDir()
111 if err != nil {
112 return "", "", err
113 }
114 hash, err := embeddedHash()
115 if err != nil {
116 return "", "", err
117 }
118 cacheDir = filepath.Join(homeDir, ".cache", "sketch", "webui")
119 return cacheDir, filepath.Join(cacheDir, "skui-"+hash+".zip"), nil
120}
121
Sean McCullough39995932025-06-25 19:32:08 +0000122// generateTailwindCSS generates tailwind.css from global.css and outputs it to the specified directory
123func generateTailwindCSS(buildDir, outDir string) error {
124 // Run tailwindcss CLI to generate the CSS
125 cmd := exec.Command("npx", "tailwindcss", "-i", "./src/global.css", "-o", filepath.Join(outDir, "tailwind.css"))
126 cmd.Dir = buildDir
127 if out, err := cmd.CombinedOutput(); err != nil {
128 return fmt.Errorf("tailwindcss generation failed: %s: %v", out, err)
129 }
130 return nil
131}
132
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700133// copyMonacoAssets copies Monaco editor assets to the output directory
134func copyMonacoAssets(buildDir, outDir string) error {
135 // Create Monaco directories
136 monacoEditorDir := filepath.Join(outDir, "monaco", "min", "vs", "editor")
137 codiconDir := filepath.Join(outDir, "monaco", "min", "vs", "base", "browser", "ui", "codicons", "codicon")
138
139 if err := os.MkdirAll(monacoEditorDir, 0o777); err != nil {
140 return fmt.Errorf("failed to create monaco editor directory: %w", err)
141 }
142
143 if err := os.MkdirAll(codiconDir, 0o777); err != nil {
144 return fmt.Errorf("failed to create codicon directory: %w", err)
145 }
146
147 // Copy Monaco editor CSS
148 editorCssPath := "node_modules/monaco-editor/min/vs/editor/editor.main.css"
149 editorCss, err := os.ReadFile(filepath.Join(buildDir, editorCssPath))
150 if err != nil {
151 return fmt.Errorf("failed to read monaco editor CSS: %w", err)
152 }
153
154 if err := os.WriteFile(filepath.Join(monacoEditorDir, "editor.main.css"), editorCss, 0o666); err != nil {
155 return fmt.Errorf("failed to write monaco editor CSS: %w", err)
156 }
157
158 // Copy Codicon font
159 codiconFontPath := "node_modules/monaco-editor/min/vs/base/browser/ui/codicons/codicon/codicon.ttf"
160 codiconFont, err := os.ReadFile(filepath.Join(buildDir, codiconFontPath))
161 if err != nil {
162 return fmt.Errorf("failed to read codicon font: %w", err)
163 }
164
165 if err := os.WriteFile(filepath.Join(codiconDir, "codicon.ttf"), codiconFont, 0o666); err != nil {
166 return fmt.Errorf("failed to write codicon font: %w", err)
167 }
168
169 return nil
170}
171
Earl Lee2e463fb2025-04-17 11:22:22 -0700172// Build unpacks and esbuild's all bundleTs typescript files
173func Build() (fs.FS, error) {
David Crawshaw8bff16a2025-04-18 01:16:49 -0700174 cacheDir, hashZip, err := zipPath()
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 if err != nil {
176 return nil, err
177 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700178 buildDir := filepath.Join(cacheDir, "build")
179 if err := os.MkdirAll(buildDir, 0o777); err != nil { // make sure .cache/sketch/build exists
180 return nil, err
181 }
David Crawshaw8bff16a2025-04-18 01:16:49 -0700182 if b, err := os.ReadFile(hashZip); err == nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700183 // Build already done, serve it out.
David Crawshaw8bff16a2025-04-18 01:16:49 -0700184 return zip.NewReader(bytes.NewReader(b), int64(len(b)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700185 }
186
David Crawshaw8bff16a2025-04-18 01:16:49 -0700187 // TODO: try downloading "https://sketch.dev/webui/"+filepath.Base(hashZip)
188
Earl Lee2e463fb2025-04-17 11:22:22 -0700189 // We need to do a build.
190
191 // Clear everything out of the build directory except node_modules.
192 if err := cleanBuildDir(buildDir); err != nil {
193 return nil, err
194 }
195 tmpHashDir := filepath.Join(buildDir, "out")
196 if err := os.Mkdir(tmpHashDir, 0o777); err != nil {
197 return nil, err
198 }
199
200 // Unpack everything from embedded into build dir.
201 if err := unpackFS(buildDir, embedded); err != nil {
202 return nil, err
203 }
204
Sean McCullough86b56862025-04-18 13:04:03 -0700205 // Do the build. Don't install dev dependencies, because they can be large
206 // and slow enough to install that the /init requests from the host process
207 // will run out of retries and the whole thing exits. We do need better health
208 // checking in general, but that's a separate issue. Don't do slow stuff here:
209 cmd := exec.Command("npm", "ci", "--omit", "dev")
Earl Lee2e463fb2025-04-17 11:22:22 -0700210 cmd.Dir = buildDir
211 if out, err := cmd.CombinedOutput(); err != nil {
212 return nil, fmt.Errorf("npm ci: %s: %v", out, err)
213 }
Sean McCullough39995932025-06-25 19:32:08 +0000214
215 // Generate Tailwind CSS
216 if err := generateTailwindCSS(buildDir, tmpHashDir); err != nil {
217 return nil, fmt.Errorf("generate tailwind css: %w", err)
218 }
philip.zeyligerc0a44592025-06-15 21:24:57 -0700219 // Create all bundles
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700220 bundleTs := []string{
221 "src/web-components/sketch-app-shell.ts",
Philip Zeyligere08c7ff2025-06-06 13:22:12 -0700222 "src/web-components/mobile-app-shell.ts",
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700223 "src/web-components/sketch-monaco-view.ts",
Sean McCullough021231a2025-06-12 09:35:24 -0700224 "src/messages-viewer.ts",
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700225 "node_modules/monaco-editor/esm/vs/editor/editor.worker.js",
226 "node_modules/monaco-editor/esm/vs/language/typescript/ts.worker.js",
227 "node_modules/monaco-editor/esm/vs/language/html/html.worker.js",
228 "node_modules/monaco-editor/esm/vs/language/css/css.worker.js",
229 "node_modules/monaco-editor/esm/vs/language/json/json.worker.js",
230 }
231
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000232 // Additionally create standalone bundles for caching
philip.zeyligerc0a44592025-06-15 21:24:57 -0700233 monacoHash, err := createStandaloneMonacoBundle(tmpHashDir, buildDir)
234 if err != nil {
235 return nil, fmt.Errorf("create monaco bundle: %w", err)
236 }
philip.zeyligerc0a44592025-06-15 21:24:57 -0700237
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000238 mermaidHash, err := createStandaloneMermaidBundle(tmpHashDir, buildDir)
239 if err != nil {
240 return nil, fmt.Errorf("create mermaid bundle: %w", err)
241 }
242
243 // Bundle all files with Monaco and Mermaid as external (since they may transitively import them)
Earl Lee2e463fb2025-04-17 11:22:22 -0700244 for _, tsName := range bundleTs {
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000245 // Use external Monaco and Mermaid for all TypeScript files to ensure consistency
philip.zeyligerc0a44592025-06-15 21:24:57 -0700246 if strings.HasSuffix(tsName, ".ts") {
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000247 if err := esbuildBundleWithExternals(tmpHashDir, filepath.Join(buildDir, tsName), monacoHash, mermaidHash); err != nil {
philip.zeyligerc0a44592025-06-15 21:24:57 -0700248 return nil, fmt.Errorf("esbuild: %s: %w", tsName, err)
249 }
250 } else {
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000251 // Bundle worker files normally (they don't use Monaco or Mermaid)
philip.zeyligerc0a44592025-06-15 21:24:57 -0700252 if err := esbuildBundle(tmpHashDir, filepath.Join(buildDir, tsName), ""); err != nil {
253 return nil, fmt.Errorf("esbuild: %s: %w", tsName, err)
254 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700255 }
256 }
257
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700258 // Copy Monaco editor assets
259 if err := copyMonacoAssets(buildDir, tmpHashDir); err != nil {
260 return nil, fmt.Errorf("failed to copy Monaco assets: %w", err)
261 }
262
Earl Lee2e463fb2025-04-17 11:22:22 -0700263 // Copy src files used directly into the new hash output dir.
264 err = fs.WalkDir(embedded, "src", func(path string, d fs.DirEntry, err error) error {
265 if d.IsDir() {
Sean McCullough86b56862025-04-18 13:04:03 -0700266 if path == "src/web-components/demo" {
267 return fs.SkipDir
268 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 return nil
270 }
Pokey Rule8cac59a2025-04-24 12:21:19 +0100271 if strings.HasSuffix(path, "mockServiceWorker.js") {
272 return nil
273 }
Sean McCullough39995932025-06-25 19:32:08 +0000274 // Skip src/tailwind.css as it will be generated
275 if path == "src/tailwind.css" {
276 return nil
277 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700278 if strings.HasSuffix(path, ".html") || strings.HasSuffix(path, ".css") || strings.HasSuffix(path, ".js") {
279 b, err := embedded.ReadFile(path)
280 if err != nil {
281 return err
282 }
283 dstPath := filepath.Join(tmpHashDir, strings.TrimPrefix(path, "src/"))
284 if err := os.WriteFile(dstPath, b, 0o777); err != nil {
285 return err
286 }
287 return nil
288 }
289 return nil
290 })
291 if err != nil {
292 return nil, err
293 }
294
295 // Copy xterm.css from node_modules
296 const xtermCssPath = "node_modules/@xterm/xterm/css/xterm.css"
297 xtermCss, err := os.ReadFile(filepath.Join(buildDir, xtermCssPath))
298 if err != nil {
299 return nil, fmt.Errorf("failed to read xterm.css: %w", err)
300 }
301 if err := os.WriteFile(filepath.Join(tmpHashDir, "xterm.css"), xtermCss, 0o666); err != nil {
302 return nil, fmt.Errorf("failed to write xterm.css: %w", err)
303 }
304
Philip Zeyliger176de792025-04-21 12:25:18 -0700305 // Compress all .js, .js.map, and .css files with gzip, leaving the originals in place
306 err = filepath.Walk(tmpHashDir, func(path string, info os.FileInfo, err error) error {
307 if err != nil {
308 return err
309 }
310 if info.IsDir() {
311 return nil
312 }
313 // Check if file is a .js or .js.map file
314 if !strings.HasSuffix(path, ".js") && !strings.HasSuffix(path, ".js.map") && !strings.HasSuffix(path, ".css") {
315 return nil
316 }
317
318 // Read the original file
319 origData, err := os.ReadFile(path)
320 if err != nil {
321 return fmt.Errorf("failed to read file %s: %w", path, err)
322 }
323
324 // Create a gzipped file
325 gzipPath := path + ".gz"
326 gzipFile, err := os.Create(gzipPath)
327 if err != nil {
328 return fmt.Errorf("failed to create gzip file %s: %w", gzipPath, err)
329 }
330 defer gzipFile.Close()
331
332 // Create a gzip writer
333 gzWriter := gzip.NewWriter(gzipFile)
334 defer gzWriter.Close()
335
336 // Write the original file content to the gzip writer
337 _, err = gzWriter.Write(origData)
338 if err != nil {
339 return fmt.Errorf("failed to write to gzip file %s: %w", gzipPath, err)
340 }
341
342 // Ensure we flush and close properly
343 if err := gzWriter.Close(); err != nil {
344 return fmt.Errorf("failed to close gzip writer for %s: %w", gzipPath, err)
345 }
346 if err := gzipFile.Close(); err != nil {
347 return fmt.Errorf("failed to close gzip file %s: %w", gzipPath, err)
348 }
349
Josh Bleecher Snydera002a232025-07-09 19:38:03 +0000350 // The gzip handler will decompress on-the-fly for browsers that don't support gzip.
351 if err := os.Remove(path); err != nil {
352 return fmt.Errorf("failed to remove uncompressed file %s: %w", path, err)
353 }
354
Philip Zeyliger176de792025-04-21 12:25:18 -0700355 return nil
356 })
357 if err != nil {
358 return nil, fmt.Errorf("failed to compress .js/.js.map/.css files: %w", err)
359 }
360
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700361 return os.DirFS(tmpHashDir), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700362}
363
Sean McCullough86b56862025-04-18 13:04:03 -0700364func esbuildBundle(outDir, src, metafilePath string) error {
365 args := []string{
Earl Lee2e463fb2025-04-17 11:22:22 -0700366 src,
367 "--bundle",
368 "--sourcemap",
369 "--log-level=error",
philip.zeyligerc0a44592025-06-15 21:24:57 -0700370 "--minify",
Earl Lee2e463fb2025-04-17 11:22:22 -0700371 "--outdir=" + outDir,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700372 "--loader:.ttf=file",
373 "--loader:.eot=file",
374 "--loader:.woff=file",
375 "--loader:.woff2=file",
376 // This changes where the sourcemap points to; we need relative dirs if we're proxied into a subdirectory.
377 "--public-path=.",
Sean McCullough86b56862025-04-18 13:04:03 -0700378 }
379
380 // Add metafile option if path is provided
381 if metafilePath != "" {
382 args = append(args, "--metafile="+metafilePath)
383 }
384
385 ret := esbuildcli.Run(args)
Earl Lee2e463fb2025-04-17 11:22:22 -0700386 if ret != 0 {
387 return fmt.Errorf("esbuild %s failed: %d", filepath.Base(src), ret)
388 }
389 return nil
390}
Sean McCullough86b56862025-04-18 13:04:03 -0700391
392// unpackTS unpacks all the typescript-relevant files from the embedded filesystem into tmpDir.
393func unpackTS(outDir string, embedded fs.FS) error {
394 return fs.WalkDir(embedded, ".", func(path string, d fs.DirEntry, err error) error {
395 if err != nil {
396 return err
397 }
398 tgt := filepath.Join(outDir, path)
399 if d.IsDir() {
400 if err := os.MkdirAll(tgt, 0o777); err != nil {
401 return err
402 }
403 return nil
404 }
405 if strings.HasSuffix(path, ".html") || strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".css") {
406 return nil
407 }
408 data, err := fs.ReadFile(embedded, path)
409 if err != nil {
410 return err
411 }
412 if err := os.WriteFile(tgt, data, 0o666); err != nil {
413 return err
414 }
415 return nil
416 })
417}
418
419// GenerateBundleMetafile creates metafiles for bundle analysis with esbuild.
420//
421// The metafiles contain information about bundle size and dependencies
422// that can be visualized at https://esbuild.github.io/analyze/
423//
424// It takes the output directory where the metafiles will be written.
425// Returns the file path of the generated metafiles.
426func GenerateBundleMetafile(outputDir string) (string, error) {
427 tmpDir, err := os.MkdirTemp("", "bundle-analysis-")
428 if err != nil {
429 return "", err
430 }
431 defer os.RemoveAll(tmpDir)
432
433 // Create output directory if it doesn't exist
Philip Zeyligerd1402952025-04-23 03:54:37 +0000434 if err := os.MkdirAll(outputDir, 0o755); err != nil {
Sean McCullough86b56862025-04-18 13:04:03 -0700435 return "", err
436 }
437
438 cacheDir, _, err := zipPath()
439 if err != nil {
440 return "", err
441 }
442 buildDir := filepath.Join(cacheDir, "build")
443 if err := os.MkdirAll(buildDir, 0o777); err != nil { // make sure .cache/sketch/build exists
444 return "", err
445 }
446
447 // Ensure we have a source to bundle
448 if err := unpackTS(tmpDir, embedded); err != nil {
449 return "", err
450 }
451
452 // All bundles to analyze
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700453 bundleTs := []string{
454 "src/web-components/sketch-app-shell.ts",
Philip Zeyligere08c7ff2025-06-06 13:22:12 -0700455 "src/web-components/mobile-app-shell.ts",
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700456 "src/web-components/sketch-monaco-view.ts",
Sean McCullough021231a2025-06-12 09:35:24 -0700457 "src/messages-viewer.ts",
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700458 }
Sean McCullough86b56862025-04-18 13:04:03 -0700459 metafiles := make([]string, len(bundleTs))
460
461 for i, tsName := range bundleTs {
462 // Create a metafile path for this bundle
463 baseFileName := filepath.Base(tsName)
464 metaFileName := strings.TrimSuffix(baseFileName, ".ts") + ".meta.json"
465 metafilePath := filepath.Join(outputDir, metaFileName)
466 metafiles[i] = metafilePath
467
468 // Bundle with metafile generation
469 outTmpDir, err := os.MkdirTemp("", "metafile-bundle-")
470 if err != nil {
471 return "", err
472 }
473 defer os.RemoveAll(outTmpDir)
474
475 if err := esbuildBundle(outTmpDir, filepath.Join(buildDir, tsName), metafilePath); err != nil {
476 return "", fmt.Errorf("failed to generate metafile for %s: %w", tsName, err)
477 }
478 }
479
480 return outputDir, nil
481}
philip.zeyligerc0a44592025-06-15 21:24:57 -0700482
483// createStandaloneMonacoBundle creates a separate Monaco editor bundle with content-based hash
484// This is useful for caching Monaco separately from the main application bundles
485func createStandaloneMonacoBundle(outDir, buildDir string) (string, error) {
486 // Create a temporary entry file that imports Monaco and exposes it globally
487 monacoEntryContent := `import * as monaco from 'monaco-editor';
488window.monaco = monaco;
489export default monaco;
490`
491 monacoEntryPath := filepath.Join(buildDir, "monaco-standalone-entry.js")
492 if err := os.WriteFile(monacoEntryPath, []byte(monacoEntryContent), 0o666); err != nil {
493 return "", fmt.Errorf("write monaco entry: %w", err)
494 }
495
496 // Calculate hash of monaco-editor package for content-based naming
497 monacoPackageJson := filepath.Join(buildDir, "node_modules", "monaco-editor", "package.json")
498 monacoContent, err := os.ReadFile(monacoPackageJson)
499 if err != nil {
500 return "", fmt.Errorf("read monaco package.json: %w", err)
501 }
502
503 h := sha256.New()
504 h.Write(monacoContent)
505 monacoHash := hex.EncodeToString(h.Sum(nil))[:16]
506
507 // Bundle Monaco with content-based filename
508 monacoOutputName := fmt.Sprintf("monaco-standalone-%s.js", monacoHash)
509 monacoOutputPath := filepath.Join(outDir, monacoOutputName)
510
511 args := []string{
512 monacoEntryPath,
513 "--bundle",
514 "--sourcemap",
515 "--minify",
516 "--log-level=error",
517 "--outfile=" + monacoOutputPath,
518 "--format=iife",
519 "--global-name=__MonacoLoader__",
520 "--loader:.ttf=file",
521 "--loader:.eot=file",
522 "--loader:.woff=file",
523 "--loader:.woff2=file",
524 "--public-path=.",
525 }
526
527 ret := esbuildcli.Run(args)
528 if ret != 0 {
529 return "", fmt.Errorf("esbuild monaco bundle failed: %d", ret)
530 }
531
532 return monacoHash, nil
533}
534
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000535// createStandaloneMermaidBundle creates a separate Mermaid bundle with content-based hash
536// This is useful for caching Mermaid separately from the main application bundles
537func createStandaloneMermaidBundle(outDir, buildDir string) (string, error) {
538 // Create a temporary entry file that imports Mermaid and exposes it globally
539 mermaidEntryContent := `import mermaid from 'mermaid';
540window.mermaid = mermaid;
541export default mermaid;
542`
543 mermaidEntryPath := filepath.Join(buildDir, "mermaid-standalone-entry.js")
544 if err := os.WriteFile(mermaidEntryPath, []byte(mermaidEntryContent), 0o666); err != nil {
545 return "", fmt.Errorf("write mermaid entry: %w", err)
546 }
547
548 // Calculate hash of mermaid package for content-based naming
549 mermaidPackageJson := filepath.Join(buildDir, "node_modules", "mermaid", "package.json")
550 mermaidContent, err := os.ReadFile(mermaidPackageJson)
551 if err != nil {
552 return "", fmt.Errorf("read mermaid package.json: %w", err)
553 }
554
555 h := sha256.New()
556 h.Write(mermaidContent)
557 mermaidHash := hex.EncodeToString(h.Sum(nil))[:16]
558
559 // Bundle Mermaid with content-based filename
560 mermaidOutputName := fmt.Sprintf("mermaid-standalone-%s.js", mermaidHash)
561 mermaidOutputPath := filepath.Join(outDir, mermaidOutputName)
562
563 args := []string{
564 mermaidEntryPath,
565 "--bundle",
566 "--sourcemap",
567 "--minify",
568 "--log-level=error",
569 "--outfile=" + mermaidOutputPath,
570 "--format=iife",
571 "--global-name=__MermaidLoader__",
572 "--loader:.ttf=file",
573 "--loader:.eot=file",
574 "--loader:.woff=file",
575 "--loader:.woff2=file",
576 "--public-path=.",
577 }
578
579 ret := esbuildcli.Run(args)
580 if ret != 0 {
581 return "", fmt.Errorf("esbuild mermaid bundle failed: %d", ret)
582 }
583
584 return mermaidHash, nil
585}
586
587// esbuildBundleWithExternals bundles a file with Monaco and Mermaid as external dependencies
588func esbuildBundleWithExternals(outDir, src, monacoHash, mermaidHash string) error {
philip.zeyligerc0a44592025-06-15 21:24:57 -0700589 args := []string{
590 src,
591 "--bundle",
592 "--sourcemap",
593 "--minify",
594 "--log-level=error",
595 "--outdir=" + outDir,
596 "--external:monaco-editor",
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000597 "--external:mermaid",
philip.zeyligerc0a44592025-06-15 21:24:57 -0700598 "--loader:.ttf=file",
599 "--loader:.eot=file",
600 "--loader:.woff=file",
601 "--loader:.woff2=file",
602 "--public-path=.",
603 "--define:__MONACO_HASH__=\"" + monacoHash + "\"",
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000604 "--define:__MERMAID_HASH__=\"" + mermaidHash + "\"",
philip.zeyligerc0a44592025-06-15 21:24:57 -0700605 }
606
607 ret := esbuildcli.Run(args)
608 if ret != 0 {
609 return fmt.Errorf("esbuild %s failed: %d", filepath.Base(src), ret)
610 }
611 return nil
612}