Debian Codegraph @

internal/js/esbuild/batch.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 // Package esbuild provides functions for building JavaScript resources.
15 package esbuild
16
17 import (
18 "bytes"
19 "context"
20 _ "embed"
21 "encoding/json"
22 "fmt"
23 "io"
24 "path"
25 "path/filepath"
26 "reflect"
27 "sort"
28 "strings"
29 "sync"
30 "sync/atomic"
31
32 "github.com/evanw/esbuild/pkg/api"
33 "github.com/gohugoio/hugo/cache/dynacache"
34 "github.com/gohugoio/hugo/common/hmaps"
35 "github.com/gohugoio/hugo/common/hsync"
36 "github.com/gohugoio/hugo/common/hugio"
37 "github.com/gohugoio/hugo/common/paths"
38 "github.com/gohugoio/hugo/deps"
39 "github.com/gohugoio/hugo/helpers"
40 "github.com/gohugoio/hugo/identity"
41 "github.com/gohugoio/hugo/internal/js"
42 "github.com/gohugoio/hugo/media"
43 "github.com/gohugoio/hugo/resources"
44 "github.com/gohugoio/hugo/resources/resource"
45 "github.com/gohugoio/hugo/resources/resource_factories/create"
46 "github.com/gohugoio/hugo/tpl/tplimpl"
47 "github.com/mitchellh/mapstructure"
48 )
49
50 var _ js.Batcher = (*batcher)(nil)
51
52 const (
53 NsBatch = "_hugo-js-batch"
54
55 propsKeyImportContext = "importContext"
56 )
57
58 //go:embed batch-esm-runner.gotmpl
59 var runnerTemplateStr string
60
61 var _ js.BatchPackage = (*Package)(nil)
62
63 var _ buildToucher = (*optsHolder[scriptOptions])(nil)
64
65 var (
66 _ buildToucher = (*scriptGroup)(nil)
67 _ isBuiltOrTouchedProvider = (*scriptGroup)(nil)
68 )
69
70 func NewBatcherClient(deps *deps.Deps) (js.BatcherClient, error) {
71 c := &BatcherClient{
72 d: deps,
73 buildClient: NewBuildClient(deps.BaseFs.Assets, deps.ResourceSpec, false),
74 createClient: create.New(deps.ResourceSpec),
75 batcherStore: hmaps.NewCache[string, js.Batcher](),
76 bundlesStore: hmaps.NewCache[string, js.BatchPackage](),
77 }
78
79 deps.BuildEndListeners.Add(func(...any) bool {
80 c.bundlesStore.Reset()
81 return false
82 })
83
84 return c, nil
85 }
86
87 func (o optionsMap[K, C]) ByKey() optionsGetSetters[K, C] {
88 var values []optionsGetSetter[K, C]
89 for _, v := range o {
90 values = append(values, v)
91 }
92
93 sort.Slice(values, func(i, j int) bool {
94 return values[i].Key().String() < values[j].Key().String()
95 })
96
97 return values
98 }
99
100 func (o *opts[K, C]) Compiled() C {
101 o.h.checkCompileErr()
102 return o.h.compiled
103 }
104
105 func (os optionsGetSetters[K, C]) Filter(predicate func(K) bool) optionsGetSetters[K, C] {
106 var a optionsGetSetters[K, C]
107 for _, v := range os {
108 if predicate(v.Key()) {
109 a = append(a, v)
110 }
111 }
112 return a
113 }
114
115 func (o *optsHolder[C]) IdentifierBase() string {
116 return o.optionsID
117 }
118
119 func (o *opts[K, C]) Key() K {
120 return o.key
121 }
122
123 func (o *opts[K, C]) Reset() {
124 o.once.Reset()
125 o.h.resetCounter++
126 }
127
128 func (o *opts[K, C]) Get(id uint32) js.OptionsSetter {
129 var b *optsHolder[C]
130 o.once.Do(func() {
131 b = o.h
132 b.setBuilt(id)
133 })
134 return b
135 }
136
137 func (o *opts[K, C]) GetIdentity() identity.Identity {
138 return o.h
139 }
140
141 func (o *optsHolder[C]) SetOptions(m map[string]any) string {
142 o.optsSetCounter++
143 o.optsPrev = o.optsCurr
144 o.optsCurr = m
145 o.compiledPrev = o.compiled
146 o.compiled, o.compileErr = o.compiled.compileOptions(m, o.defaults)
147 o.checkCompileErr()
148 return ""
149 }
150
151 // ValidateBatchID validates the given ID according to some very
152 func ValidateBatchID(id string, isTopLevel bool) error {
153 if id == "" {
154 return fmt.Errorf("id must be set")
155 }
156 // No Windows slashes.
157 if strings.Contains(id, "\\") {
158 return fmt.Errorf("id must not contain backslashes")
159 }
160
161 // Allow forward slashes in top level IDs only.
162 if !isTopLevel && strings.Contains(id, "/") {
163 return fmt.Errorf("id must not contain forward slashes")
164 }
165
166 return nil
167 }
168
169 func newIsBuiltOrTouched() isBuiltOrTouched {
170 return isBuiltOrTouched{
171 built: make(buildIDs),
172 touched: make(buildIDs),
173 }
174 }
175
176 func newOpts[K any, C optionsCompiler[C]](key K, optionsID string, defaults defaultOptionValues) *opts[K, C] {
177 return &opts[K, C]{
178 key: key,
179 h: &optsHolder[C]{
180 optionsID: optionsID,
181 defaults: defaults,
182 isBuiltOrTouched: newIsBuiltOrTouched(),
183 },
184 }
185 }
186
187 // BatcherClient is a client for building JavaScript packages.
188 type BatcherClient struct {
189 d *deps.Deps
190
191 once sync.Once
192 runnerTemplate *tplimpl.TemplInfo
193
194 createClient *create.Client
195 buildClient *BuildClient
196
197 batcherStore *hmaps.Cache[string, js.Batcher]
198 bundlesStore *hmaps.Cache[string, js.BatchPackage]
199 }
200
201 // New creates a new Batcher with the given ID.
202 // This will be typically created once and reused across rebuilds.
203 func (c *BatcherClient) New(id string) (js.Batcher, error) {
204 var initErr error
205 c.once.Do(func() {
206 // We should fix the initialization order here (or use the Go template package directly), but we need to wait
207 // for the Hugo templates to be ready.
208 tmpl, err := c.d.TemplateStore.TextParse("batch-esm-runner", runnerTemplateStr)
209 if err != nil {
210 initErr = err
211 return
212 }
213 c.runnerTemplate = tmpl
214 })
215
216 if initErr != nil {
217 return nil, initErr
218 }
219
220 dependencyManager := c.d.Conf.NewIdentityManager()
221 configID := "config_" + id
222
223 b := &batcher{
224 id: id,
225 scriptGroups: make(map[string]*scriptGroup),
226 dependencyManager: dependencyManager,
227 client: c,
228 configOptions: newOpts[scriptID, configOptions](
229 scriptID(configID),
230 configID,
231 defaultOptionValues{},
232 ),
233 }
234
235 c.d.BuildEndListeners.Add(func(...any) bool {
236 b.reset()
237 return false
238 })
239
240 idFinder := identity.NewFinder(identity.FinderConfig{})
241
242 c.d.OnChangeListeners.Add(func(ids ...identity.Identity) bool {
243 for _, id := range ids {
244 if r := idFinder.Contains(id, b.dependencyManager, 50); r > 0 {
245 b.staleVersion.Add(1)
246 return false
247 }
248
249 sp, ok := id.(identity.DependencyManagerScopedProvider)
250 if !ok {
251 continue
252 }
253 idms := sp.GetDependencyManagerForScopesAll()
254
255 for _, g := range b.scriptGroups {
256 g.forEachIdentity(func(id2 identity.Identity) bool {
257 bt, ok := id2.(buildToucher)
258 if !ok {
259 return false
260 }
261 for _, id3 := range idms {
262 // This handles the removal of the only source for a script group (e.g. all shortcodes in a contnt page).
263 // Note the very shallow search.
264 if r := idFinder.Contains(id2, id3, 0); r > 0 {
265 bt.setTouched(b.buildCount)
266 return false
267 }
268 }
269 return false
270 })
271 }
272 }
273
274 return false
275 })
276
277 return b, nil
278 }
279
280 func (c *BatcherClient) Store() *hmaps.Cache[string, js.Batcher] {
281 return c.batcherStore
282 }
283
284 func (c *BatcherClient) buildBatchGroup(ctx context.Context, t *batchGroupTemplateContext) (resource.Resource, string, error) {
285 var buf bytes.Buffer
286
287 if err := c.d.GetTemplateStore().ExecuteWithContext(ctx, c.runnerTemplate, &buf, t); err != nil {
288 return nil, "", err
289 }
290
291 s := paths.AddLeadingSlash(t.keyPath + ".js")
292 r, err := c.createClient.FromString(s, buf.String())
293 if err != nil {
294 return nil, "", err
295 }
296
297 return r, s, nil
298 }
299
300 // Package holds a group of JavaScript resources.
301 type Package struct {
302 id string
303 b *batcher
304
305 groups map[string]resource.Resources
306 }
307
308 func (p *Package) Groups() map[string]resource.Resources {
309 return p.groups
310 }
311
312 type batchGroupTemplateContext struct {
313 keyPath string
314 ID string
315 Runners []scriptRunnerTemplateContext
316 Scripts []scriptBatchTemplateContext
317 }
318
319 type batcher struct {
320 mu sync.Mutex
321 id string
322 buildCount uint32
323 staleVersion atomic.Uint32
324 scriptGroups scriptGroups
325
326 client *BatcherClient
327 dependencyManager identity.Manager
328
329 configOptions optionsGetSetter[scriptID, configOptions]
330
331 // The last successfully built package.
332 // If this is non-nil and not stale, we can reuse it (e.g. on server rebuilds)
333 prevBuild *Package
334 }
335
336 // Build builds the batch if not already built or if it's stale.
337 func (b *batcher) Build(ctx context.Context) (js.BatchPackage, error) {
338 key := dynacache.CleanKey(b.id + ".js")
339 p, err := b.client.bundlesStore.GetOrCreate(key, func() (js.BatchPackage, error) {
340 return b.build(ctx)
341 })
342 if err != nil {
343 return nil, fmt.Errorf("failed to build JS batch %q: %w", b.id, err)
344 }
345 return p, nil
346 }
347
348 func (b *batcher) Config(ctx context.Context) js.OptionsSetter {
349 return b.configOptions.Get(b.buildCount)
350 }
351
352 func (b *batcher) Group(ctx context.Context, id string) js.BatcherGroup {
353 if err := ValidateBatchID(id, false); err != nil {
354 panic(err)
355 }
356
357 b.mu.Lock()
358 defer b.mu.Unlock()
359
360 group, found := b.scriptGroups[id]
361 if !found {
362 idm := b.client.d.Conf.NewIdentityManager()
363 b.dependencyManager.AddIdentity(idm)
364
365 group = &scriptGroup{
366 id: id, b: b,
367 isBuiltOrTouched: newIsBuiltOrTouched(),
368 dependencyManager: idm,
369 scriptsOptions: make(optionsMap[scriptID, scriptOptions]),
370 instancesOptions: make(optionsMap[instanceID, paramsOptions]),
371 runnersOptions: make(optionsMap[scriptID, scriptOptions]),
372 }
373 b.scriptGroups[id] = group
374 }
375
376 group.setBuilt(b.buildCount)
377
378 return group
379 }
380
381 func (b *batcher) isStale() bool {
382 if b.staleVersion.Load() > 0 {
383 return true
384 }
385
386 if b.removeNotSet() {
387 return true
388 }
389
390 if b.configOptions.isStale() {
391 return true
392 }
393
394 for _, v := range b.scriptGroups {
395 if v.isStale() {
396 return true
397 }
398 }
399
400 return false
401 }
402
403 func (b *batcher) build(ctx context.Context) (js.BatchPackage, error) {
404 b.mu.Lock()
405 defer b.mu.Unlock()
406 defer func() {
407 b.staleVersion.Store(0)
408 b.buildCount++
409 }()
410
411 if b.prevBuild != nil {
412 if !b.isStale() {
413 return b.prevBuild, nil
414 }
415 }
416
417 p, err := b.doBuild(ctx)
418 if err != nil {
419 return nil, err
420 }
421
422 b.prevBuild = p
423
424 return p, nil
425 }
426
427 func (b *batcher) doBuild(ctx context.Context) (*Package, error) {
428 type importContext struct {
429 name string
430 resourceGetter resource.ResourceGetter
431 scriptOptions scriptOptions
432 dm identity.Manager
433 }
434
435 state := struct {
436 importResource *hmaps.Cache[string, resource.Resource]
437 resultResource *hmaps.Cache[string, resource.Resource]
438 importerImportContext *hmaps.Cache[string, importContext]
439 pathGroup *hmaps.Cache[string, string]
440 }{
441 importResource: hmaps.NewCache[string, resource.Resource](),
442 resultResource: hmaps.NewCache[string, resource.Resource](),
443 importerImportContext: hmaps.NewCache[string, importContext](),
444 pathGroup: hmaps.NewCache[string, string](),
445 }
446
447 multihostBasePaths := b.client.d.ResourceSpec.MultihostTargetBasePaths
448
449 // Entry points passed to ESBuid.
450 var entryPoints []string
451 addResource := func(group, pth string, r resource.Resource, isResult bool) {
452 state.pathGroup.Set(paths.TrimExt(pth), group)
453 state.importResource.Set(pth, r)
454 if isResult {
455 state.resultResource.Set(pth, r)
456 }
457 entryPoints = append(entryPoints, pth)
458 }
459
460 for _, g := range b.scriptGroups.Sorted() {
461 keyPath := g.id
462
463 t := &batchGroupTemplateContext{
464 keyPath: keyPath,
465 ID: g.id,
466 }
467
468 instances := g.instancesOptions.ByKey()
469
470 for _, vv := range g.scriptsOptions.ByKey() {
471 keyPath := keyPath + "_" + vv.Key().String()
472 opts := vv.Compiled()
473 impPath := path.Join(PrefixHugoVirtual, opts.Dir(), keyPath+opts.Resource.MediaType().FirstSuffix.FullSuffix)
474 impCtx := opts.ImportContext
475
476 state.importerImportContext.Set(impPath, importContext{
477 name: keyPath,
478 resourceGetter: impCtx,
479 scriptOptions: opts,
480 dm: g.dependencyManager,
481 })
482
483 bt := scriptBatchTemplateContext{
484 opts: vv,
485 Import: impPath,
486 Instances: []scriptInstanceBatchTemplateContext{},
487 }
488 state.importResource.Set(bt.Import, vv.Compiled().Resource)
489 predicate := func(k instanceID) bool {
490 return k.scriptID == vv.Key()
491 }
492 for _, vvv := range instances.Filter(predicate) {
493 bt.Instances = append(bt.Instances, scriptInstanceBatchTemplateContext{opts: vvv})
494 }
495
496 t.Scripts = append(t.Scripts, bt)
497 }
498
499 for _, vv := range g.runnersOptions.ByKey() {
500 runnerKeyPath := keyPath + "_" + vv.Key().String()
501 runnerImpPath := paths.AddLeadingSlash(runnerKeyPath + "_runner" + vv.Compiled().Resource.MediaType().FirstSuffix.FullSuffix)
502 t.Runners = append(t.Runners, scriptRunnerTemplateContext{opts: vv, Import: runnerImpPath})
503 addResource(g.id, runnerImpPath, vv.Compiled().Resource, false)
504 }
505
506 r, s, err := b.client.buildBatchGroup(ctx, t)
507 if err != nil {
508 return nil, fmt.Errorf("failed to build JS batch: %w", err)
509 }
510
511 state.importerImportContext.Set(s, importContext{
512 name: s,
513 resourceGetter: nil,
514 dm: g.dependencyManager,
515 })
516
517 addResource(g.id, s, r, true)
518 }
519
520 mediaTypes := b.client.d.ResourceSpec.MediaTypes()
521
522 externalOptions := b.configOptions.Compiled().Options
523 if externalOptions.Format == "" {
524 externalOptions.Format = "esm"
525 }
526 if externalOptions.Format != "esm" {
527 return nil, fmt.Errorf("only esm format is currently supported")
528 }
529
530 jsOpts := Options{
531 ExternalOptions: externalOptions,
532 DependencyManager: b.dependencyManager,
533 Splitting: true,
534 ImportOnResolveFunc: func(imp string, args api.OnResolveArgs) string {
535 var importContextPath string
536 if args.Kind == api.ResolveEntryPoint {
537 importContextPath = args.Path
538 } else {
539 importContextPath = args.Importer
540 }
541 importContext, importContextFound := state.importerImportContext.Get(importContextPath)
542
543 // We want to track the dependencies closest to where they're used.
544 dm := b.dependencyManager
545 if importContextFound {
546 dm = importContext.dm
547 }
548
549 if r, found := state.importResource.Get(imp); found {
550 dm.AddIdentity(identity.FirstIdentity(r))
551 return imp
552 }
553
554 if importContext.resourceGetter != nil {
555 resolved := ResolveResource(imp, importContext.resourceGetter)
556 if resolved != nil {
557 resolvePath := resources.InternalResourceTargetPath(resolved)
558 dm.AddIdentity(identity.FirstIdentity(resolved))
559 imp := PrefixHugoVirtual + resolvePath
560 state.importResource.Set(imp, resolved)
561 state.importerImportContext.Set(imp, importContext)
562 return imp
563
564 }
565 }
566 return ""
567 },
568 ImportOnLoadFunc: func(args api.OnLoadArgs) (string, error) {
569 imp := args.Path
570
571 if r, found := state.importResource.Get(imp); found {
572 content, err := resources.InternalResourceSourceContent(ctx, r)
573 if err != nil {
574 return "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)
575 }
576 return content, nil
577 }
578 return "", nil
579 },
580 ImportParamsOnLoadFunc: func(args api.OnLoadArgs) json.RawMessage {
581 if importContext, found := state.importerImportContext.Get(args.Path); found {
582 if !importContext.scriptOptions.IsZero() {
583 return importContext.scriptOptions.Params
584 }
585 }
586 return nil
587 },
588 ErrorMessageResolveFunc: func(args api.Message) *ErrorMessageResolved {
589 if loc := args.Location; loc != nil {
590 path := strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":")
591 if r, found := state.importResource.Get(path); found {
592 sourcePath := resources.InternalResourceSourcePathBestEffort(r)
593
594 var contentr hugio.ReadSeekCloser
595 if cp, ok := r.(hugio.ReadSeekCloserProvider); ok {
596 contentr, _ = cp.ReadSeekCloser()
597 }
598 return &ErrorMessageResolved{
599 Content: contentr,
600 Path: sourcePath,
601 Message: args.Text,
602 }
603
604 }
605
606 }
607 return nil
608 },
609 ResolveSourceMapSource: func(s string) string {
610 if r, found := state.importResource.Get(s); found {
611 if ss := resources.InternalResourceSourcePath(r); ss != "" {
612 return ss
613 }
614 return PrefixHugoMemory + s
615 }
616 return ""
617 },
618 EntryPoints: entryPoints,
619 }
620
621 result, err := b.client.buildClient.Build(jsOpts)
622 if err != nil {
623 return nil, fmt.Errorf("failed to build JS bundle: %w", err)
624 }
625
626 groups := make(map[string]resource.Resources)
627
628 createAndAddResource := func(targetPath, group string, o api.OutputFile, mt media.Type) error {
629 var sourceFilename string
630 if r, found := state.importResource.Get(targetPath); found {
631 sourceFilename = resources.InternalResourceSourcePathBestEffort(r)
632 }
633 targetPath = path.Join(b.id, targetPath)
634
635 rd := resources.ResourceSourceDescriptor{
636 LazyPublish: true,
637 OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
638 return hugio.NewReadSeekerNoOpCloserFromBytes(o.Contents), nil
639 },
640 MediaType: mt,
641 TargetPath: targetPath,
642 SourceFilenameOrPath: sourceFilename,
643 }
644 r, err := b.client.d.ResourceSpec.NewResource(rd)
645 if err != nil {
646 return err
647 }
648
649 groups[group] = append(groups[group], r)
650
651 return nil
652 }
653
654 outDir := b.client.d.AbsPublishDir
655
656 createAndAddResources := func(o api.OutputFile) (bool, error) {
657 p := paths.ToSlashPreserveLeading(strings.TrimPrefix(o.Path, outDir))
658 ext := path.Ext(p)
659 mt, _, found := mediaTypes.GetBySuffix(ext)
660 if !found {
661 return false, nil
662 }
663
664 group, found := state.pathGroup.Get(paths.TrimExt(p))
665
666 if !found {
667 return false, nil
668 }
669
670 if err := createAndAddResource(p, group, o, mt); err != nil {
671 return false, err
672 }
673
674 return true, nil
675 }
676
677 for _, o := range result.OutputFiles {
678 handled, err := createAndAddResources(o)
679 if err != nil {
680 return nil, err
681 }
682
683 if !handled {
684 // Copy to destination.
685 // In a multihost setup, we will have multiple targets.
686 var targetFilenames []string
687 if len(multihostBasePaths) > 0 {
688 for _, base := range multihostBasePaths {
689 p := strings.TrimPrefix(o.Path, outDir)
690 targetFilename := filepath.Join(base, b.id, p)
691 targetFilenames = append(targetFilenames, targetFilename)
692 }
693 } else {
694 p := strings.TrimPrefix(o.Path, outDir)
695 targetFilename := filepath.Join(b.id, p)
696 targetFilenames = append(targetFilenames, targetFilename)
697 }
698
699 fs := b.client.d.BaseFs.PublishFs
700
701 if err := func() error {
702 fw, err := helpers.OpenFilesForWriting(fs, targetFilenames...)
703 if err != nil {
704 return err
705 }
706 defer fw.Close()
707
708 fr := bytes.NewReader(o.Contents)
709
710 _, err = io.Copy(fw, fr)
711
712 return err
713 }(); err != nil {
714 return nil, fmt.Errorf("failed to copy to %q: %w", targetFilenames, err)
715 }
716 }
717 }
718
719 p := &Package{
720 id: path.Join(NsBatch, b.id),
721 b: b,
722 groups: groups,
723 }
724
725 return p, nil
726 }
727
728 func (b *batcher) removeNotSet() bool {
729 // We already have the lock.
730 var removed bool
731 currentBuildID := b.buildCount
732 for k, v := range b.scriptGroups {
733 if !v.isBuilt(currentBuildID) && v.isTouched(currentBuildID) {
734 // Remove entire group.
735 removed = true
736 delete(b.scriptGroups, k)
737 continue
738 }
739 if v.removeTouchedButNotSet() {
740 removed = true
741 }
742 if v.removeNotSet() {
743 removed = true
744 }
745 }
746
747 return removed
748 }
749
750 func (b *batcher) reset() {
751 b.mu.Lock()
752 defer b.mu.Unlock()
753 b.configOptions.Reset()
754 for _, v := range b.scriptGroups {
755 v.Reset()
756 }
757 }
758
759 type buildIDs map[uint32]bool
760
761 func (b buildIDs) Has(buildID uint32) bool {
762 return b[buildID]
763 }
764
765 func (b buildIDs) Set(buildID uint32) {
766 b[buildID] = true
767 }
768
769 type buildToucher interface {
770 setTouched(buildID uint32)
771 }
772
773 type configOptions struct {
774 Options ExternalOptions
775 }
776
777 func (s configOptions) isStaleCompiled(prev configOptions) bool {
778 return false
779 }
780
781 func (s configOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (configOptions, error) {
782 config, err := DecodeExternalOptions(m)
783 if err != nil {
784 return configOptions{}, err
785 }
786
787 return configOptions{
788 Options: config,
789 }, nil
790 }
791
792 type defaultOptionValues struct {
793 defaultExport string
794 }
795
796 type instanceID struct {
797 scriptID scriptID
798 instanceID string
799 }
800
801 func (i instanceID) String() string {
802 return i.scriptID.String() + "_" + i.instanceID
803 }
804
805 type isBuiltOrTouched struct {
806 built buildIDs
807 touched buildIDs
808 }
809
810 func (i isBuiltOrTouched) setBuilt(id uint32) {
811 i.built.Set(id)
812 }
813
814 func (i isBuiltOrTouched) isBuilt(id uint32) bool {
815 return i.built.Has(id)
816 }
817
818 func (i isBuiltOrTouched) setTouched(id uint32) {
819 i.touched.Set(id)
820 }
821
822 func (i isBuiltOrTouched) isTouched(id uint32) bool {
823 return i.touched.Has(id)
824 }
825
826 type isBuiltOrTouchedProvider interface {
827 isBuilt(uint32) bool
828 isTouched(uint32) bool
829 }
830
831 type key interface {
832 comparable
833 fmt.Stringer
834 }
835
836 type optionsCompiler[C any] interface {
837 isStaleCompiled(C) bool
838 compileOptions(map[string]any, defaultOptionValues) (C, error)
839 }
840
841 type optionsGetSetter[K, C any] interface {
842 isBuiltOrTouchedProvider
843 identity.IdentityProvider
844 // resource.StaleInfo
845
846 Compiled() C
847 Key() K
848 Reset()
849
850 Get(uint32) js.OptionsSetter
851 isStale() bool
852 currPrev() (map[string]any, map[string]any)
853 }
854
855 type optionsGetSetters[K key, C any] []optionsGetSetter[K, C]
856
857 type optionsMap[K key, C any] map[K]optionsGetSetter[K, C]
858
859 type opts[K any, C optionsCompiler[C]] struct {
860 key K
861 h *optsHolder[C]
862 once hsync.OnceMore
863 }
864
865 type optsHolder[C optionsCompiler[C]] struct {
866 optionsID string
867
868 defaults defaultOptionValues
869
870 // Keep track of one generation so we can detect changes.
871 // Note that most of this tracking is performed on the options/map level.
872 compiled C
873 compiledPrev C
874 compileErr error
875
876 resetCounter uint32
877 optsSetCounter uint32
878 optsCurr map[string]any
879 optsPrev map[string]any
880
881 isBuiltOrTouched
882 }
883
884 type paramsOptions struct {
885 Params json.RawMessage
886 }
887
888 func (s paramsOptions) isStaleCompiled(prev paramsOptions) bool {
889 return false
890 }
891
892 func (s paramsOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (paramsOptions, error) {
893 v := struct {
894 Params map[string]any
895 }{}
896
897 if err := mapstructure.WeakDecode(m, &v); err != nil {
898 return paramsOptions{}, err
899 }
900
901 paramsJSON, err := json.Marshal(v.Params)
902 if err != nil {
903 return paramsOptions{}, err
904 }
905
906 return paramsOptions{
907 Params: paramsJSON,
908 }, nil
909 }
910
911 type scriptBatchTemplateContext struct {
912 opts optionsGetSetter[scriptID, scriptOptions]
913 Import string
914 Instances []scriptInstanceBatchTemplateContext
915 }
916
917 func (s *scriptBatchTemplateContext) Export() string {
918 return s.opts.Compiled().Export
919 }
920
921 func (c scriptBatchTemplateContext) MarshalJSON() (b []byte, err error) {
922 return json.Marshal(&struct {
923 ID string `json:"id"`
924 Instances []scriptInstanceBatchTemplateContext `json:"instances"`
925 }{
926 ID: c.opts.Key().String(),
927 Instances: c.Instances,
928 })
929 }
930
931 func (b scriptBatchTemplateContext) RunnerJSON(i int) string {
932 script := fmt.Sprintf("Script%d", i)
933
934 v := struct {
935 ID string `json:"id"`
936
937 // Read-only live JavaScript binding.
938 Binding string `json:"binding"`
939 Instances []scriptInstanceBatchTemplateContext `json:"instances"`
940 }{
941 b.opts.Key().String(),
942 script,
943 b.Instances,
944 }
945
946 bb, err := json.Marshal(v)
947 if err != nil {
948 panic(err)
949 }
950 s := string(bb)
951
952 // Remove the quotes to make it a valid JS object.
953 s = strings.ReplaceAll(s, fmt.Sprintf("%q", script), script)
954
955 return s
956 }
957
958 type scriptGroup struct {
959 mu sync.Mutex
960 id string
961 b *batcher
962 isBuiltOrTouched
963 dependencyManager identity.Manager
964
965 scriptsOptions optionsMap[scriptID, scriptOptions]
966 instancesOptions optionsMap[instanceID, paramsOptions]
967 runnersOptions optionsMap[scriptID, scriptOptions]
968 }
969
970 // For internal use only.
971 func (b *scriptGroup) GetDependencyManager() identity.Manager {
972 return b.dependencyManager
973 }
974
975 // For internal use only.
976 func (b *scriptGroup) IdentifierBase() string {
977 return b.id
978 }
979
980 func (s *scriptGroup) Instance(sid, id string) js.OptionsSetter {
981 if err := ValidateBatchID(sid, false); err != nil {
982 panic(err)
983 }
984 if err := ValidateBatchID(id, false); err != nil {
985 panic(err)
986 }
987
988 s.mu.Lock()
989 defer s.mu.Unlock()
990
991 iid := instanceID{scriptID: scriptID(sid), instanceID: id}
992 if v, found := s.instancesOptions[iid]; found {
993 return v.Get(s.b.buildCount)
994 }
995
996 fullID := "instance_" + s.key() + "_" + iid.String()
997
998 s.instancesOptions[iid] = newOpts[instanceID, paramsOptions](
999 iid,
1000 fullID,
1001 defaultOptionValues{},
1002 )
1003
1004 return s.instancesOptions[iid].Get(s.b.buildCount)
1005 }
1006
1007 func (g *scriptGroup) Reset() {
1008 for _, v := range g.scriptsOptions {
1009 v.Reset()
1010 }
1011 for _, v := range g.instancesOptions {
1012 v.Reset()
1013 }
1014 for _, v := range g.runnersOptions {
1015 v.Reset()
1016 }
1017 }
1018
1019 func (s *scriptGroup) Runner(id string) js.OptionsSetter {
1020 if err := ValidateBatchID(id, false); err != nil {
1021 panic(err)
1022 }
1023
1024 s.mu.Lock()
1025 defer s.mu.Unlock()
1026 sid := scriptID(id)
1027 if v, found := s.runnersOptions[sid]; found {
1028 return v.Get(s.b.buildCount)
1029 }
1030
1031 runnerIdentity := "runner_" + s.key() + "_" + id
1032
1033 // A typical signature for a runner would be:
1034 // export default function Run(scripts) {}
1035 // The user can override the default export in the templates.
1036
1037 s.runnersOptions[sid] = newOpts[scriptID, scriptOptions](
1038 sid,
1039 runnerIdentity,
1040 defaultOptionValues{
1041 defaultExport: "default",
1042 },
1043 )
1044
1045 return s.runnersOptions[sid].Get(s.b.buildCount)
1046 }
1047
1048 func (s *scriptGroup) Script(id string) js.OptionsSetter {
1049 if err := ValidateBatchID(id, false); err != nil {
1050 panic(err)
1051 }
1052
1053 s.mu.Lock()
1054 defer s.mu.Unlock()
1055 sid := scriptID(id)
1056 if v, found := s.scriptsOptions[sid]; found {
1057 return v.Get(s.b.buildCount)
1058 }
1059
1060 scriptIdentity := "script_" + s.key() + "_" + id
1061
1062 s.scriptsOptions[sid] = newOpts[scriptID, scriptOptions](
1063 sid,
1064 scriptIdentity,
1065 defaultOptionValues{
1066 defaultExport: "*",
1067 },
1068 )
1069
1070 return s.scriptsOptions[sid].Get(s.b.buildCount)
1071 }
1072
1073 func (s *scriptGroup) isStale() bool {
1074 for _, v := range s.scriptsOptions {
1075 if v.isStale() {
1076 return true
1077 }
1078 }
1079
1080 for _, v := range s.instancesOptions {
1081 if v.isStale() {
1082 return true
1083 }
1084 }
1085
1086 for _, v := range s.runnersOptions {
1087 if v.isStale() {
1088 return true
1089 }
1090 }
1091
1092 return false
1093 }
1094
1095 func (v *scriptGroup) forEachIdentity(
1096 f func(id identity.Identity) bool,
1097 ) bool {
1098 if f(v) {
1099 return true
1100 }
1101 for _, vv := range v.instancesOptions {
1102 if f(vv.GetIdentity()) {
1103 return true
1104 }
1105 }
1106
1107 for _, vv := range v.scriptsOptions {
1108 if f(vv.GetIdentity()) {
1109 return true
1110 }
1111 }
1112
1113 for _, vv := range v.runnersOptions {
1114 if f(vv.GetIdentity()) {
1115 return true
1116 }
1117 }
1118
1119 return false
1120 }
1121
1122 func (s *scriptGroup) key() string {
1123 return s.b.id + "_" + s.id
1124 }
1125
1126 func (g *scriptGroup) removeNotSet() bool {
1127 currentBuildID := g.b.buildCount
1128 if !g.isBuilt(currentBuildID) {
1129 // This group was never accessed in this build.
1130 return false
1131 }
1132 var removed bool
1133
1134 if g.instancesOptions.isBuilt(currentBuildID) {
1135 // A new instance has been set in this group for this build.
1136 // Remove any instance that has not been set in this build.
1137 for k, v := range g.instancesOptions {
1138 if v.isBuilt(currentBuildID) {
1139 continue
1140 }
1141 delete(g.instancesOptions, k)
1142 removed = true
1143 }
1144 }
1145
1146 if g.runnersOptions.isBuilt(currentBuildID) {
1147 // A new runner has been set in this group for this build.
1148 // Remove any runner that has not been set in this build.
1149 for k, v := range g.runnersOptions {
1150 if v.isBuilt(currentBuildID) {
1151 continue
1152 }
1153 delete(g.runnersOptions, k)
1154 removed = true
1155 }
1156 }
1157
1158 if g.scriptsOptions.isBuilt(currentBuildID) {
1159 // A new script has been set in this group for this build.
1160 // Remove any script that has not been set in this build.
1161 for k, v := range g.scriptsOptions {
1162 if v.isBuilt(currentBuildID) {
1163 continue
1164 }
1165 delete(g.scriptsOptions, k)
1166
1167 // Also remove any instance with this ID.
1168 for kk := range g.instancesOptions {
1169 if kk.scriptID == k {
1170 delete(g.instancesOptions, kk)
1171 }
1172 }
1173 removed = true
1174 }
1175 }
1176
1177 return removed
1178 }
1179
1180 func (g *scriptGroup) removeTouchedButNotSet() bool {
1181 currentBuildID := g.b.buildCount
1182 var removed bool
1183 for k, v := range g.instancesOptions {
1184 if v.isBuilt(currentBuildID) {
1185 continue
1186 }
1187 if v.isTouched(currentBuildID) {
1188 delete(g.instancesOptions, k)
1189 removed = true
1190 }
1191 }
1192 for k, v := range g.runnersOptions {
1193 if v.isBuilt(currentBuildID) {
1194 continue
1195 }
1196 if v.isTouched(currentBuildID) {
1197 delete(g.runnersOptions, k)
1198 removed = true
1199 }
1200 }
1201 for k, v := range g.scriptsOptions {
1202 if v.isBuilt(currentBuildID) {
1203 continue
1204 }
1205 if v.isTouched(currentBuildID) {
1206 delete(g.scriptsOptions, k)
1207 removed = true
1208
1209 // Also remove any instance with this ID.
1210 for kk := range g.instancesOptions {
1211 if kk.scriptID == k {
1212 delete(g.instancesOptions, kk)
1213 }
1214 }
1215 }
1216
1217 }
1218 return removed
1219 }
1220
1221 type scriptGroups map[string]*scriptGroup
1222
1223 func (s scriptGroups) Sorted() []*scriptGroup {
1224 var a []*scriptGroup
1225 for _, v := range s {
1226 a = append(a, v)
1227 }
1228 sort.Slice(a, func(i, j int) bool {
1229 return a[i].id < a[j].id
1230 })
1231 return a
1232 }
1233
1234 type scriptID string
1235
1236 func (s scriptID) String() string {
1237 return string(s)
1238 }
1239
1240 type scriptInstanceBatchTemplateContext struct {
1241 opts optionsGetSetter[instanceID, paramsOptions]
1242 }
1243
1244 func (c scriptInstanceBatchTemplateContext) ID() string {
1245 return c.opts.Key().instanceID
1246 }
1247
1248 func (c scriptInstanceBatchTemplateContext) MarshalJSON() (b []byte, err error) {
1249 return json.Marshal(&struct {
1250 ID string `json:"id"`
1251 Params json.RawMessage `json:"params"`
1252 }{
1253 ID: c.opts.Key().instanceID,
1254 Params: c.opts.Compiled().Params,
1255 })
1256 }
1257
1258 type scriptOptions struct {
1259 // The script to build.
1260 Resource resource.Resource
1261
1262 // The import context to use.
1263 // Note that we will always fall back to the resource's own import context.
1264 ImportContext resource.ResourceGetter
1265
1266 // The export name to use for this script's group's runners (if any).
1267 // If not set, the default export will be used.
1268 Export string
1269
1270 // Params marshaled to JSON.
1271 Params json.RawMessage
1272 }
1273
1274 func (o *scriptOptions) Dir() string {
1275 return path.Dir(resources.InternalResourceTargetPath(o.Resource))
1276 }
1277
1278 func (s scriptOptions) IsZero() bool {
1279 return s.Resource == nil
1280 }
1281
1282 func (s scriptOptions) isStaleCompiled(prev scriptOptions) bool {
1283 if prev.IsZero() {
1284 return false
1285 }
1286
1287 // All but the ImportContext are checked at the options/map level.
1288 i1nil, i2nil := prev.ImportContext == nil, s.ImportContext == nil
1289 if i1nil && i2nil {
1290 return false
1291 }
1292 if i1nil || i2nil {
1293 return true
1294 }
1295 // On its own this check would have too many false positives, but combined with the other checks it should be fine.
1296 // We cannot do equality checking here.
1297 if !prev.ImportContext.(resource.IsProbablySameResourceGetter).IsProbablySameResourceGetter(s.ImportContext) {
1298 return true
1299 }
1300
1301 return false
1302 }
1303
1304 func (s scriptOptions) compileOptions(m map[string]any, defaults defaultOptionValues) (scriptOptions, error) {
1305 v := struct {
1306 Resource resource.Resource
1307 ImportContext any
1308 Export string
1309 Params map[string]any
1310 }{}
1311
1312 if err := mapstructure.WeakDecode(m, &v); err != nil {
1313 panic(err)
1314 }
1315
1316 var paramsJSON []byte
1317 if v.Params != nil {
1318 var err error
1319 paramsJSON, err = json.Marshal(v.Params)
1320 if err != nil {
1321 panic(err)
1322 }
1323 }
1324
1325 if v.Export == "" {
1326 v.Export = defaults.defaultExport
1327 }
1328
1329 compiled := scriptOptions{
1330 Resource: v.Resource,
1331 Export: v.Export,
1332 ImportContext: resource.NewCachedResourceGetter(v.ImportContext),
1333 Params: paramsJSON,
1334 }
1335
1336 if compiled.Resource == nil {
1337 return scriptOptions{}, fmt.Errorf("resource not set")
1338 }
1339
1340 return compiled, nil
1341 }
1342
1343 type scriptRunnerTemplateContext struct {
1344 opts optionsGetSetter[scriptID, scriptOptions]
1345 Import string
1346 }
1347
1348 func (s *scriptRunnerTemplateContext) Export() string {
1349 return s.opts.Compiled().Export
1350 }
1351
1352 func (c scriptRunnerTemplateContext) MarshalJSON() (b []byte, err error) {
1353 return json.Marshal(&struct {
1354 ID string `json:"id"`
1355 }{
1356 ID: c.opts.Key().String(),
1357 })
1358 }
1359
1360 func (o optionsMap[K, C]) isBuilt(id uint32) bool {
1361 for _, v := range o {
1362 if v.isBuilt(id) {
1363 return true
1364 }
1365 }
1366
1367 return false
1368 }
1369
1370 func (o *opts[K, C]) isBuilt(id uint32) bool {
1371 return o.h.isBuilt(id)
1372 }
1373
1374 func (o *opts[K, C]) isStale() bool {
1375 if o.h.isStaleOpts() {
1376 return true
1377 }
1378 if o.h.compiled.isStaleCompiled(o.h.compiledPrev) {
1379 return true
1380 }
1381 return false
1382 }
1383
1384 func (o *optsHolder[C]) isStaleOpts() bool {
1385 if o.optsSetCounter == 1 && o.resetCounter > 0 {
1386 return false
1387 }
1388 isStale := func() bool {
1389 if len(o.optsCurr) != len(o.optsPrev) {
1390 return true
1391 }
1392 for k, v := range o.optsPrev {
1393 vv, found := o.optsCurr[k]
1394 if !found {
1395 return true
1396 }
1397 if strings.EqualFold(k, propsKeyImportContext) {
1398 // This is checked later.
1399 } else if si, ok := vv.(resource.StaleInfo); ok {
1400 if si.StaleVersion() > 0 {
1401 return true
1402 }
1403 } else {
1404 if !reflect.DeepEqual(v, vv) {
1405 return true
1406 }
1407 }
1408 }
1409 return false
1410 }()
1411
1412 return isStale
1413 }
1414
1415 func (o *opts[K, C]) isTouched(id uint32) bool {
1416 return o.h.isTouched(id)
1417 }
1418
1419 func (o *optsHolder[C]) checkCompileErr() {
1420 if o.compileErr != nil {
1421 panic(o.compileErr)
1422 }
1423 }
1424
1425 func (o *opts[K, C]) currPrev() (map[string]any, map[string]any) {
1426 return o.h.optsCurr, o.h.optsPrev
1427 }
1428
1429 func init() {
1430 // We don't want any dependencies/change tracking on the top level Package,
1431 // we want finer grained control via Package.Group.
1432 var p any = &Package{}
1433 if _, ok := p.(identity.Identity); ok {
1434 panic("esbuid.Package should not implement identity.Identity")
1435 }
1436 if _, ok := p.(identity.DependencyManagerProvider); ok {
1437 panic("esbuid.Package should not implement identity.DependencyManagerProvider")
1438 }
1439 }