Commit Graph

48 Commits

Author SHA1 Message Date
Ryan Hamamura
539a2ad504 feat: three-tier context lifecycle (grace → suspended → reaped)
All checks were successful
CI / Build and Test (push) Successful in 1m22s
Contexts that lose their SSE connection now pass through a suspended
state before being fully reaped. Suspended contexts keep their shell
(ID, route, CSRF token) but free page resources. On reconnect, the
page init function is re-run for a seamless resume. Contexts past
the TTL trigger a client-side reload instead of a silent dead page.

Configurable via ContextSuspendAfter (default 15m) and ContextTTL
(default 1h).
2026-02-13 15:22:08 -10:00
Ryan Hamamura
1384e49e14 fix: preserve context across SSE reconnects on tab visibility change
Datastar aborts SSE on visibilitychange (tab hidden) and reconnects
when visible. The previous cleanup-on-disconnect destroyed the context
before the client could reconnect. Now SSE disconnect does a soft
teardown (mark disconnected, keep context alive) and reconnect drains
stale patches before resuming. The reaper uses disconnect time instead
of creation time so recently-disconnected contexts aren't prematurely
reaped.
2026-02-13 10:52:46 -10:00
Ryan Hamamura
2f19874c17 feat: add PubSub() accessor to V struct 2026-02-12 14:32:05 -10:00
Ryan Hamamura
27b8540b71 feat: add SPA navigation with view transitions
Swap page content over the existing SSE connection without full page
loads. A persistent Context resets its page-specific state (signals,
actions, intervals, subscriptions) on navigate while preserving the
SSE stream, CSRF token, and session.

- c.Navigate(path) for programmatic SPA navigation from actions
- Injected JS intercepts same-origin <a> clicks (opt out with
  data-via-no-boost) and handles popstate for back/forward
- v.Layout() wraps pages in a shared shell for DRY nav/chrome
- View Transition API integration via WithViewTransitions() on
  PatchElements and h.DataViewTransition() helper
- POST /_navigate endpoint with CSRF validation and rate limiting
- pageStopChan cancels page-level OnInterval goroutines on navigate
- Includes SPA example with layout, counter, and live clock pages
2026-02-12 13:52:47 -10:00
Ryan Hamamura
2310e45d35 feat: auto-start embedded NATS server in New()
Pub/sub now works out of the box — New() starts a process-scoped
embedded NATS server with JetStream. The PubSub interface remains
for custom backends via Config(Options{PubSub: ...}).

- Move vianats functionality into nats.go (eliminates circular import)
- Add NATSConn(), JetStream(), EnsureStream(), ReplayHistory[T]() to via
- Delete vianats/ package
- Simplify nats-chatroom and pubsub-crud examples
- Rewrite pubsub tests to use real embedded NATS
2026-02-12 08:54:44 -10:00
ryanhamamura
e636970f7b feat: add middleware, route groups, and codebase cleanup
* feat: add middleware example demonstrating route groups

Self-contained example covering v.Use(), v.Group(), nested groups,
Group.Use(), and middleware chaining with role-based access control.

* feat: add per-action middleware via WithMiddleware ActionOption

Reuses the existing Middleware type so the same auth/logging functions
work at both page and action level. Middleware runs after CSRF and
rate-limit checks, with full access to session and signals.

* feat: add RedirectView helper and refactor session example to use middleware

RedirectView lets middleware abort and redirect in one step. The session
example now uses an authRequired middleware on a route group instead of
an inline check inside the view.

* fix: remove dead code, fix double Load and extractParams mismatch

- Remove componentRegistry (written, never read)
- Remove unused signal methods: Bytes, Int64, Float
- Remove unreachable nil check in registerCtx
- Simplify injectRouteParams (extractParams already returns fresh map)
- Fix double sync.Map.Load in injectSignals
- Merge Shutdown/shutdown into single method
- Inline currSessionNum
- Fix extractParams: mismatched literal segment now returns nil
- Minor: new(bytes.Buffer), go c.Sync(), genRandID reads 4 bytes
2026-02-11 13:50:02 -10:00
Ryan Hamamura
f5158b866c feat: add Static and StaticFS helpers for serving static files
One-liner static file serving: v.Static("/assets/", "./public") for
filesystem directories and v.StaticFS("/assets/", fsys) for embed.FS.
Both auto-normalize the URL prefix and disable directory listings.
2026-02-06 13:22:00 -10:00
Ryan Hamamura
0762ddbbc2 feat: add token-bucket rate limiting for action endpoints
Add per-context and per-action rate limiting using golang.org/x/time/rate.
Configure globally via Options.ActionRateLimit or per-action with
WithRateLimit(). Defaults to 10 req/s with burst of 20.
2026-02-06 11:52:07 -10:00
Ryan Hamamura
b7acfa6302 feat: add automatic CSRF protection for action calls
Generate a per-context CSRF token (128-bit, crypto/rand) and inject it
as a Datastar signal (via-csrf) alongside via-ctx. Validate with
constant-time comparison on /_action/{id} before executing, returning
403 on mismatch. Transparent to users since Datastar sends all signals
automatically.

Closes #9
2026-02-06 11:17:41 -10:00
Ryan Hamamura
6dcd54c88b fix: clean up leaked contexts on SSE disconnect and add orphan reaper
When clients disconnect without beforeunload firing (network drops,
mobile kills, crashes), contexts leaked in the registry permanently.

- Extract cleanupCtx helper for dispose/unregister sequence
- Call cleanupCtx on SSE disconnect (sse.Context().Done())
- Add background reaper for contexts where SSE never connected
- Add ContextTTL config option (default 30s, negative disables)
- Fix inverted condition in devModeRemovePersisted
2026-02-06 10:34:28 -10:00
Ryan Hamamura
4a7acbb630 feat: add graceful shutdown with OS signal handling
Handle SIGINT/SIGTERM in Start() to cleanly drain all contexts,
stop goroutines, close SSE connections, and tear down PubSub.

Fix stopAllRoutines() to close() the channel instead of sending a
single value, so all listening goroutines are notified.
2026-01-31 09:22:43 -10:00
Ryan Hamamura
a7ace9099f feat: replace log with rs/zerolog for structured logging
Switch from the standard library log package to rs/zerolog with
ConsoleWriter for colorful terminal output in dev mode and JSON
output in production. Users can now provide their own logger via
Options.Logger or set the level via Options.LogLevel.
2026-01-31 08:18:24 -10:00
Ryan Hamamura
30cc6d88e6 feat: add embedded NATS pub/sub support on Context
Define PubSub and Subscription interfaces in the core via package with
a vianats sub-package providing the embedded NATS + JetStream
implementation. Expose c.Publish() and c.Subscribe() on Context with
automatic subscription cleanup on session close. Refactor the NATS
chatroom example to use the built-in methods instead of manual
subscription tracking.
2026-01-26 08:06:50 -10:00
Ryan Hamamura
73f4e4009b Always sync full state when SSE connects
Previously only called Sync() on SSE reconnect (detected via last-event-id
header). This caused issues when application code registered contexts for
updates before the SSE connection was established - patches sent to
patchChan could be dropped.

Now always call Sync() when SSE connects, ensuring clients receive the
full current state regardless of what happened before the connection
was established.

Fixes #2
2026-01-14 19:02:44 -10:00
Ryan Hamamura
c77ccc0796 chore: rename module to github.com/ryanhamamura/via
Update module path and all internal imports to use the new repository location.
2026-01-14 10:47:11 -10:00
Ryan Hamamura
d4b831492e refactor: simplify Datastar configuration API
Flatten DatastarConfig struct into Options (DatastarContent, DatastarPath)
and replace datastarHandlerRegistered bool with sync.Once for thread safety.
2026-01-14 02:01:18 -10:00
Ryan Hamamura
ea7b9ad4a1 feat: add custom Datastar.js configuration support
Allow users to provide their own Datastar.js script (e.g., Datastar Pro
or custom builds) via Via's Options configuration. Adds DatastarConfig
struct with Content ([]byte) and Path (string) fields.
2026-01-14 01:47:39 -10:00
Ryan Hamamura
03b6d7453a feat: add Redirect and ReplaceURL methods for browser navigation
Add SSE-based navigation methods to Context:
- Redirect(url) / Redirectf() - navigate to new page
- ReplaceURL(url) / ReplaceURLf() - update URL without navigation

Update session example to demonstrate full login flow with redirects.
2026-01-12 00:47:52 -10:00
ryanhamamura
9a23188973 feat: add cookie-based session support using alexedwards/scs (#1)
- Add Session wrapper with typed getters (GetString, GetInt, GetBool, etc.)
- Add flash message support via Pop methods (PopString, PopInt, etc.)
- Add session utilities: Exists, Keys, ID, Clear, Destroy, RenewToken
- Create default session manager in New() for zero-config usage
- Allow custom session manager via Options.SessionManager
- Wrap mux with scs LoadAndSave middleware in Start()
- Add session example demonstrating login/logout with flash messages
2026-01-09 06:59:26 -10:00
Joao Goncalves
43495ccada feat: do full sync after sse reconnect 2025-12-17 23:11:19 -01:00
Joao Goncalves
20dad802a1 feat: replace Handler() method for HTTPServeMux() for better plugin and testing integration; remove via-plugin-picocss dependency from examples; add datastar h.H nodes for data-init, data-effect, and data-ignore-morph; update realtimechart example; other small improvements 2025-12-17 17:11:59 -01:00
Gerard Webb
6da518d990 feat: Add Handler() method and fix SSE closed pipe errors (#24)
* feat: add Handler() method for testing and custom server integration

Exposes the underlying http.Handler to enable:
- Integration testing with gost-dom/browser for SSE/Datastar testing
- Custom server setups (e.g., embedding Via in existing applications)
- Standard Go httptest patterns

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: Suppress closed pipe errors when SSE connection closes

Don't log error when SSE fails to send patches if the connection was
already closed. This reduces noise in logs during shutdown and testing,
where browsers/clients close connections before server handlers finish.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: joeblew999 <joeblew999@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-11 08:51:16 -01:00
Joao Goncalves
81d44954a4 feat: add path params; add pathparams example 2025-12-04 17:53:06 -01:00
Joao Goncalves
26268f698a refactor: simplify oninterval routine; fix(runtime): session end handler; update realtime chart example 2025-12-04 12:40:36 -01:00
Joao Goncalves
51218e7a2a fix(runtime): sync on sse reconnect 2025-11-26 00:33:38 -01:00
Joao Goncalves
36c0fb9050 fix(runtime): solve chan blocks; other small improvements 2025-11-25 23:19:50 -01:00
Joao Goncalves
a71d6f0960 feat: introduce via routine; update realtime chart example 2025-11-25 22:56:21 -01:00
Joao Goncalves
6edace647e fix(via_test): remove signal sync test that was bocking test execution 2025-11-25 22:54:00 -01:00
Joao Goncalves
9776fe0a49 fix: shakespere example not compiling; remove sleep statements from patchChan loop 2025-11-18 13:03:21 -01:00
Joao Goncalves
0064150cbc fix: patchChan loop ending after switching browser tab; feat: improve realtime chart example 2025-11-18 11:17:06 -01:00
Joao Goncalves
f5a786730a fix: check for panics on page registration. Fix header append bug: was appending multiple ctx_id to the header; feat: handle complex signal init values as json; add tests; other small improvemnts 2025-11-17 16:46:33 -01:00
Joao Goncalves
472351d9a5 refactor: simplify signals; small optimizations 2025-11-16 19:53:51 -01:00
Jeff Winkler
2bb5d80502 Use beacon (#19)
Perfect. Tried with send beacon before. Dodn work for me. Because was using get instead o post.
2025-11-16 12:44:03 -01:00
Jeff Winkler
f7b5b24dd5 Script, GH action to check that all go files compile, and any tests pass. (#16) 2025-11-15 17:47:49 -01:00
Joao Goncalves
80879216b2 fix: components not using parent page patchShan; fix: chat example nil pointer error when sync outside action 2025-11-15 02:34:27 -01:00
Joao Goncalves
808d4dd0d1 fix: try solution for race conditions; use brotli included in datastar sdk; small improvements 2025-11-14 17:16:09 -01:00
Jeff Winkler
7670926733 Brotli Compression. (#12)
Co-authored-by: João Gonçalves <joao.goncalves01@gmail.com>
2025-11-13 14:03:45 -01:00
Joao Goncalves
f6c9990f38 feat: devmode removes the persist file after successful restore 2025-11-13 12:30:45 -01:00
Joao Goncalves
b9df99889e feat: introduce ctx close mechanism using beforeunload event; small fixes and improvements; improve live reload example 2025-11-13 12:11:26 -01:00
Joao Goncalves
d282773379 fix: auto reload on multiple browser windows/tabs closes #6; fix: chatroom example not compiling 2025-11-12 02:33:22 -01:00
Joao Goncalves
03ce9808e6 feat: add devmode flag; introduce live reload support; update examples 2025-11-11 00:15:44 -01:00
Joao Goncalves
9f9e4eb568 refactor: move document head includes out of via configuration into their own append funcs; update examples 2025-11-09 03:17:03 -01:00
Jeff Winkler
3b658ed7d0 LiveReload 2025-11-08 13:05:23 -05:00
Joao Goncalves
a46c06b467 feat: introduce support for plugins 2025-11-07 02:45:58 -01:00
Joao Goncalves
798f024743 feat: improve real-time chart example; add small refinements to via core files 2025-11-07 00:44:48 -01:00
Joao Goncalves
c167f0c74f feat: add real-time chart example 2025-11-05 17:29:29 -01:00
Joao Goncalves
23aebf73f2 feat: improve component support 2025-11-03 00:41:05 -01:00
Joao Goncalves
eb20a2a0a9 feat: add working prototype for via 2025-10-31 00:58:53 -01:00