starfederation / datastar

A real-time hypermedia framework.
https://data-star.dev/
MIT License
722 stars 41 forks source link

JS: Importing package results in side-effect of executing Datastar #168

Closed pdf closed 4 days ago

pdf commented 1 month ago

When attempting to manually run Datastar in order to modify plugins or similar, e.g.:

import { runDatastarWithAllPlugins } from "@sudodevnull/datastar";
runDatastarWithAllPlugins();

the code here: https://github.com/delaneyj/datastar/blob/00b8e6ba8f898091295ae8bc998f6b9b83dba0ee/packages/library/src/lib/index.ts#L78

results in Datastar being executed twice.

I suppose I could perform some shenanigans to work around it like:

const winAny = window as any;
winAny.ds = {};
import { runDatastarWithAllPlugins } from "@sudodevnull/datastar";
winAny.ds = runDatastarWithAllPlugins();

but that doesn't feel right.

delaneyj commented 1 month ago

I originally had the user do exact that cause i didn't want to pollute the window without user knowledge but most wanted it to "just work". I'm not a JS dev so if there is a better way to bootstrap please let me know!

pdf commented 1 month ago

I'm not a JS dev either sadly.

I think what should probably happen is that the browser bundle should be generated as a separate artifact to the library bundle, with the window init code only included for the browser build. I'm not certain how to rejigger the code/build to make that happen though.

There also seems to be a bunch of extra code in that if statement for supporting the inspector that's not reachable from anywhere else. I think that should probably all move into runDatastarWith(), or alternatively into another func that takes a callback arg (something like runForInspector(fn: () => Datastar)), so users can call it with e.g. runForInspector(() => runDatastarWithAllPlugins())

delaneyj commented 1 month ago

I'd gladly except the pr with the "right" way to do this. I'm stumbling around and it feels bad. I don't know enough about how mpm publishes multiple artifacts to do this correctly

pdf commented 1 month ago

I'm in the same boat when it comes to JS.

I've hacked something together here, but I don't love it: #171

delaneyj commented 4 days ago

done in v0.20.0