npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

pawajs-vite-plugin

v0.0.15

Published

pawajs vite plugin hot module replacement and safe components naming minification

Readme

pawajs-vite-plugin

A comprehensive Vite plugin suite for PawaJS that provides Hot Module Replacement (HMR) and intelligent code transformations.


✨ Features

pawajsPlugin()

  • Minifier-safe returns for PawaJS component hooks
  • 🔄 Automatic component name injection for RegisterComponent()
  • ⚡ Works with both JavaScript and TypeScript
  • 🧠 Uses estree-walker and magic-string for efficient AST transforms

pawaHMR()

  • 🔥 Hot Module Replacement for Pawa components and utilities
  • 🎯 Intelligent file detection for components and global utilities
  • ⚡ Fast HMR with custom event system
  • 📦 Virtual module support for HMR client injection
  • 💾 Best-effort state preservation across edits, with source-change detection (see State Preservation & Trade-offs)

📦 Installation

npm install pawajs-vite-plugin --save-dev

⚠️ Requirements

__pawaDev.tool must be enabled

Live-instance HMR tracking in pawajs core is gated behind __pawaDev.tool. Component instances are only registered into the internal HmrComponentMap — the registry this plugin's client (src/reload.js) relies on to find and patch live DOM instances — when __pawaDev.tool is truthy at runtime.

If __pawaDev.tool is not set (misconfigured dev entry point, a build that imports pawajs in a way that skips dev-tool initialization, etc.), pawaHMR() will still send pawa-update events and the client will still receive them — but there will be no live instances to look up, and edits will silently fail to hot-patch anything, with no runtime error. If HMR appears to do nothing after a save, verify __pawaDev.tool is active before assuming the plugin or component is broken.


🚀 Usage

Basic Setup

import { defineConfig } from 'vite'
import { pawajsPlugin, pawaHMR } from 'pawajs-vite-plugin'

export default defineConfig({
  plugins: [
    pawaHMR(),
    pawajsPlugin()
  ]
})

pawajsPlugin() Configuration

Automatically transforms your PawaJS components:

// Input
RegisterComponent(MyButton)

// Output
RegisterComponent('MyButton', MyButton)

Ensures minifier-safe return statements:

// Input
export default function MyComponent() {
  runEffect()
  return html`<div>Content</div>`
}

// Output
export default function MyComponent() {
  runEffect()
  const _pawaTemplate = html`<div>Content</div>`
  return _pawaTemplate
}

pawaHMR() Configuration

Enables HMR with optional configuration:

import { defineConfig } from 'vite'
import { pawaHMR } from 'pawajs-vite-plugin'

export default defineConfig({
  plugins: [
    pawaHMR()
  ]
})

How It Works

The HMR plugin works in two parts:

Server-side (hmr):

  1. Detects PawaJS components - Files using PawaJS imports and APIs
  2. Tracks global utilities - Exported modules in utils/, helpers/, or lib/ folders
  3. Invalidates modules - Properly clears the module cache for utilities
  4. Sends custom events - Notifies the client with detailed change metadata via pawa-update event

Client-side (src/reload.js - auto-injected):

  1. Listens for updates - Receives pawa-update events from the dev server
  2. Re-imports modules - Dynamically re-imports updated component files with cache-busting timestamps
  3. Detects components - Checks which components are defined in the updated module by reference or name
  4. Updates component registry - Updates the PawaJS component map with new function implementations
  5. Re-renders instances - Automatically re-renders all active component instances in the DOM with the new code, attempting to preserve their state (see below)
  6. Handles utilities - For utility changes, re-imports dependent modules and re-renders affected components

Process flow:

File changes → Server detects → Sends pawa-update event → Client re-imports
         ↓
   Direct component change → Directly update & re-render
         ↓
   Utility change → Find importers → Re-import dependents → Update & re-render
         ↓
   Graceful fallback → Full page reload if needed

Event Handling

The HMR client is automatically injected into your page via a virtual module. No additional setup is required on the client side — it handles component updates automatically.

If you need custom handling in your application:

if (import.meta.hot) {
  import.meta.hot.on('pawa-update', async (data) => {
    console.log('Pawa components updated:', data.files)
    console.log('Kind:', data.kind) // 'component' or 'util'
    
    // Custom logic can be added here if needed
    // The automatic HMR client handles re-rendering
  })
}

💾 State Preservation & Trade-offs

When a component is hot-patched, pawajs core attempts to carry the previous run's state values into the new run rather than resetting everything on every save. This section documents how that works and where it intentionally falls short, so failures are predictable rather than mysterious.

Identity is by useInsert key name, not call order

PawaJS has no "rules of hooks" — $state() can be called conditionally, in any order, any number of times. Because of that, state identity across a hot reload is not determined by call position (the way React Fast Refresh does it). Instead, identity comes from the string keys a component explicitly exposes via useInsert({...}):

useInsert({ count, name })

Only state exposed this way participates in HMR state preservation. State that's created via $state() but never passed through useInsert has no identity across reloads and will always reset to its initial value on every hot edit — this is a known, accepted gap, not a bug to be chased down, since state that never reaches the template generally has no user-visible continuity to preserve anyway.

Initializer-change detection

A naive "always restore the old value for a matching key" approach has a real failure mode: if you edit $state(0) to $state(5) in source and save, a naive restore would silently overwrite your new 5 with the old runtime value, making the edit appear to do nothing.

To avoid this, each useInsert-exposed state's initial value is snapshotted on every reload and compared against the previous snapshot:

  • Snapshot unchanged → treated as a normal edit elsewhere in the file; the old runtime value (post-interaction, not the initial) is restored as usual.
  • Snapshot changed → treated as an intentional edit to that state's initializer; the freshly computed value is left standing instead of being overwritten.

Comparison is done via JSON.stringify on cloned, de-reactivated values — proxies and live bindings are stripped out before comparing, since comparing live references would always report "unchanged" (an object compared to itself).

Known trade-offs (accepted)

These are deliberate, understood limitations rather than defects:

  • Functions inside objects/arrays are detected and treated as "unknown." JSON.stringify silently drops function-valued properties. Any useInsert value containing a function anywhere in its structure (e.g. { increment: [{ increase: () => count.value++ }] }) is marked as un-comparable, and that key always falls back to old (always-restore) behavior rather than risking a false "unchanged" verdict.
  • undefined-valued object properties (not array entries) can still slip past detection. JSON.stringify omits undefined-valued object keys entirely before any replacer function is invoked for them, so this specific case can't be caught by the replacer-based detection used here. undefined values inside arrays (which JSON.stringify coerces to null rather than omitting) are caught. In practice this only matters if state is deliberately initialized to undefined inside an object literal rather than a concrete default like null or 0 — considered narrow enough to accept rather than build further defenses for.
  • Nominal identity, not semantic identity. Because matching is by useInsert key name, if a key is removed and a different, unrelated state happens to be reintroduced under the same name in the same edit, the old value will be restored into the new, unrelated meaning. This is the same class of ambiguity as React's list key prop — the developer's naming is treated as the source of truth, and this can't be resolved generically.
  • Type-mismatch restoration is silent. If a key survives an edit but its value's typeof changes (e.g. a number becomes an object), the old value is dropped without a console warning. State simply resets for that key with no explicit signal as to why.
  • Any unhandled exception during patch/reconcile falls back to a full page reload, per the process flow above — this is the ultimate safety net for cases the above heuristics don't cover.

📋 API Reference

pawajsPlugin(): Plugin

Vite plugin that transforms PawaJS component files.

No configuration options needed - works out of the box.

pawaHMR(): Plugin

Vite plugin that enables HMR for PawaJS components and utilities.

HMR Event Data

When a PawaJS file changes, a custom event is sent with the following structure:

interface PawaHMRCustomEventData {
  file: string | null          // URL of the first changed module
  files: string[]               // All changed module URLs
  kind: 'component' | 'util'   // Type of change
  isComponent: boolean
  isUtil: boolean
  modules: Array<{             // Module metadata
    url: string
    id: string
    importers: string[]
  }>
  timestamp: number            // Time of change
}

Note: The HMR client (src/reload.js) is automatically injected and handles most component updates for you. Component re-rendering and module re-importing are done automatically.

📄 License

This project is licensed under the MIT License.