blob: 9c0f41ca543c398760630c276df98a4103938404 [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
350 return nil
351 })
352 if err != nil {
353 return nil, fmt.Errorf("failed to compress .js/.js.map/.css files: %w", err)
354 }
355
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700356 return os.DirFS(tmpHashDir), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700357}
358
Sean McCullough86b56862025-04-18 13:04:03 -0700359func esbuildBundle(outDir, src, metafilePath string) error {
360 args := []string{
Earl Lee2e463fb2025-04-17 11:22:22 -0700361 src,
362 "--bundle",
363 "--sourcemap",
364 "--log-level=error",
philip.zeyligerc0a44592025-06-15 21:24:57 -0700365 "--minify",
Earl Lee2e463fb2025-04-17 11:22:22 -0700366 "--outdir=" + outDir,
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700367 "--loader:.ttf=file",
368 "--loader:.eot=file",
369 "--loader:.woff=file",
370 "--loader:.woff2=file",
371 // This changes where the sourcemap points to; we need relative dirs if we're proxied into a subdirectory.
372 "--public-path=.",
Sean McCullough86b56862025-04-18 13:04:03 -0700373 }
374
375 // Add metafile option if path is provided
376 if metafilePath != "" {
377 args = append(args, "--metafile="+metafilePath)
378 }
379
380 ret := esbuildcli.Run(args)
Earl Lee2e463fb2025-04-17 11:22:22 -0700381 if ret != 0 {
382 return fmt.Errorf("esbuild %s failed: %d", filepath.Base(src), ret)
383 }
384 return nil
385}
Sean McCullough86b56862025-04-18 13:04:03 -0700386
387// unpackTS unpacks all the typescript-relevant files from the embedded filesystem into tmpDir.
388func unpackTS(outDir string, embedded fs.FS) error {
389 return fs.WalkDir(embedded, ".", func(path string, d fs.DirEntry, err error) error {
390 if err != nil {
391 return err
392 }
393 tgt := filepath.Join(outDir, path)
394 if d.IsDir() {
395 if err := os.MkdirAll(tgt, 0o777); err != nil {
396 return err
397 }
398 return nil
399 }
400 if strings.HasSuffix(path, ".html") || strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".css") {
401 return nil
402 }
403 data, err := fs.ReadFile(embedded, path)
404 if err != nil {
405 return err
406 }
407 if err := os.WriteFile(tgt, data, 0o666); err != nil {
408 return err
409 }
410 return nil
411 })
412}
413
414// GenerateBundleMetafile creates metafiles for bundle analysis with esbuild.
415//
416// The metafiles contain information about bundle size and dependencies
417// that can be visualized at https://esbuild.github.io/analyze/
418//
419// It takes the output directory where the metafiles will be written.
420// Returns the file path of the generated metafiles.
421func GenerateBundleMetafile(outputDir string) (string, error) {
422 tmpDir, err := os.MkdirTemp("", "bundle-analysis-")
423 if err != nil {
424 return "", err
425 }
426 defer os.RemoveAll(tmpDir)
427
428 // Create output directory if it doesn't exist
Philip Zeyligerd1402952025-04-23 03:54:37 +0000429 if err := os.MkdirAll(outputDir, 0o755); err != nil {
Sean McCullough86b56862025-04-18 13:04:03 -0700430 return "", err
431 }
432
433 cacheDir, _, err := zipPath()
434 if err != nil {
435 return "", err
436 }
437 buildDir := filepath.Join(cacheDir, "build")
438 if err := os.MkdirAll(buildDir, 0o777); err != nil { // make sure .cache/sketch/build exists
439 return "", err
440 }
441
442 // Ensure we have a source to bundle
443 if err := unpackTS(tmpDir, embedded); err != nil {
444 return "", err
445 }
446
447 // All bundles to analyze
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700448 bundleTs := []string{
449 "src/web-components/sketch-app-shell.ts",
Philip Zeyligere08c7ff2025-06-06 13:22:12 -0700450 "src/web-components/mobile-app-shell.ts",
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700451 "src/web-components/sketch-monaco-view.ts",
Sean McCullough021231a2025-06-12 09:35:24 -0700452 "src/messages-viewer.ts",
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700453 }
Sean McCullough86b56862025-04-18 13:04:03 -0700454 metafiles := make([]string, len(bundleTs))
455
456 for i, tsName := range bundleTs {
457 // Create a metafile path for this bundle
458 baseFileName := filepath.Base(tsName)
459 metaFileName := strings.TrimSuffix(baseFileName, ".ts") + ".meta.json"
460 metafilePath := filepath.Join(outputDir, metaFileName)
461 metafiles[i] = metafilePath
462
463 // Bundle with metafile generation
464 outTmpDir, err := os.MkdirTemp("", "metafile-bundle-")
465 if err != nil {
466 return "", err
467 }
468 defer os.RemoveAll(outTmpDir)
469
470 if err := esbuildBundle(outTmpDir, filepath.Join(buildDir, tsName), metafilePath); err != nil {
471 return "", fmt.Errorf("failed to generate metafile for %s: %w", tsName, err)
472 }
473 }
474
475 return outputDir, nil
476}
philip.zeyligerc0a44592025-06-15 21:24:57 -0700477
478// createStandaloneMonacoBundle creates a separate Monaco editor bundle with content-based hash
479// This is useful for caching Monaco separately from the main application bundles
480func createStandaloneMonacoBundle(outDir, buildDir string) (string, error) {
481 // Create a temporary entry file that imports Monaco and exposes it globally
482 monacoEntryContent := `import * as monaco from 'monaco-editor';
483window.monaco = monaco;
484export default monaco;
485`
486 monacoEntryPath := filepath.Join(buildDir, "monaco-standalone-entry.js")
487 if err := os.WriteFile(monacoEntryPath, []byte(monacoEntryContent), 0o666); err != nil {
488 return "", fmt.Errorf("write monaco entry: %w", err)
489 }
490
491 // Calculate hash of monaco-editor package for content-based naming
492 monacoPackageJson := filepath.Join(buildDir, "node_modules", "monaco-editor", "package.json")
493 monacoContent, err := os.ReadFile(monacoPackageJson)
494 if err != nil {
495 return "", fmt.Errorf("read monaco package.json: %w", err)
496 }
497
498 h := sha256.New()
499 h.Write(monacoContent)
500 monacoHash := hex.EncodeToString(h.Sum(nil))[:16]
501
502 // Bundle Monaco with content-based filename
503 monacoOutputName := fmt.Sprintf("monaco-standalone-%s.js", monacoHash)
504 monacoOutputPath := filepath.Join(outDir, monacoOutputName)
505
506 args := []string{
507 monacoEntryPath,
508 "--bundle",
509 "--sourcemap",
510 "--minify",
511 "--log-level=error",
512 "--outfile=" + monacoOutputPath,
513 "--format=iife",
514 "--global-name=__MonacoLoader__",
515 "--loader:.ttf=file",
516 "--loader:.eot=file",
517 "--loader:.woff=file",
518 "--loader:.woff2=file",
519 "--public-path=.",
520 }
521
522 ret := esbuildcli.Run(args)
523 if ret != 0 {
524 return "", fmt.Errorf("esbuild monaco bundle failed: %d", ret)
525 }
526
527 return monacoHash, nil
528}
529
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000530// createStandaloneMermaidBundle creates a separate Mermaid bundle with content-based hash
531// This is useful for caching Mermaid separately from the main application bundles
532func createStandaloneMermaidBundle(outDir, buildDir string) (string, error) {
533 // Create a temporary entry file that imports Mermaid and exposes it globally
534 mermaidEntryContent := `import mermaid from 'mermaid';
535window.mermaid = mermaid;
536export default mermaid;
537`
538 mermaidEntryPath := filepath.Join(buildDir, "mermaid-standalone-entry.js")
539 if err := os.WriteFile(mermaidEntryPath, []byte(mermaidEntryContent), 0o666); err != nil {
540 return "", fmt.Errorf("write mermaid entry: %w", err)
541 }
542
543 // Calculate hash of mermaid package for content-based naming
544 mermaidPackageJson := filepath.Join(buildDir, "node_modules", "mermaid", "package.json")
545 mermaidContent, err := os.ReadFile(mermaidPackageJson)
546 if err != nil {
547 return "", fmt.Errorf("read mermaid package.json: %w", err)
548 }
549
550 h := sha256.New()
551 h.Write(mermaidContent)
552 mermaidHash := hex.EncodeToString(h.Sum(nil))[:16]
553
554 // Bundle Mermaid with content-based filename
555 mermaidOutputName := fmt.Sprintf("mermaid-standalone-%s.js", mermaidHash)
556 mermaidOutputPath := filepath.Join(outDir, mermaidOutputName)
557
558 args := []string{
559 mermaidEntryPath,
560 "--bundle",
561 "--sourcemap",
562 "--minify",
563 "--log-level=error",
564 "--outfile=" + mermaidOutputPath,
565 "--format=iife",
566 "--global-name=__MermaidLoader__",
567 "--loader:.ttf=file",
568 "--loader:.eot=file",
569 "--loader:.woff=file",
570 "--loader:.woff2=file",
571 "--public-path=.",
572 }
573
574 ret := esbuildcli.Run(args)
575 if ret != 0 {
576 return "", fmt.Errorf("esbuild mermaid bundle failed: %d", ret)
577 }
578
579 return mermaidHash, nil
580}
581
582// esbuildBundleWithExternals bundles a file with Monaco and Mermaid as external dependencies
583func esbuildBundleWithExternals(outDir, src, monacoHash, mermaidHash string) error {
philip.zeyligerc0a44592025-06-15 21:24:57 -0700584 args := []string{
585 src,
586 "--bundle",
587 "--sourcemap",
588 "--minify",
589 "--log-level=error",
590 "--outdir=" + outDir,
591 "--external:monaco-editor",
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000592 "--external:mermaid",
philip.zeyligerc0a44592025-06-15 21:24:57 -0700593 "--loader:.ttf=file",
594 "--loader:.eot=file",
595 "--loader:.woff=file",
596 "--loader:.woff2=file",
597 "--public-path=.",
598 "--define:__MONACO_HASH__=\"" + monacoHash + "\"",
philip.zeyliger7c1a6872025-06-16 03:54:37 +0000599 "--define:__MERMAID_HASH__=\"" + mermaidHash + "\"",
philip.zeyligerc0a44592025-06-15 21:24:57 -0700600 }
601
602 ret := esbuildcli.Run(args)
603 if ret != 0 {
604 return fmt.Errorf("esbuild %s failed: %d", filepath.Base(src), ret)
605 }
606 return nil
607}