Skip to content
← Public packages

@kentcdodds/package-app-kit

Design tokens, PWA install/update, About/version, cache helpers, and optional realtime notes sync for Kody package apps.

FollowFork

starter-tanstack/app/assets/entry.ts

39 lines · 1.5 KB · TypeScript
import { hydrateRoot } from 'react-dom/client'
import { createElement } from 'react'
import { createBrowserHistory, RouterProvider } from '@tanstack/react-router'
import { createAppRouter, type RouterContext } from '../routeTree.tsx'

function readContext(): RouterContext {
	const root = document.documentElement
	return {
		appBasePath: root.getAttribute('data-app-base') || '',
		assetBasePath: root.getAttribute('data-asset-base') || '',
		clientModuleUrl: root.getAttribute('data-client-module'),
		runningSha: root.getAttribute('data-running-sha') || '',
	}
}

function registerServiceWorker() {
	if (!('serviceWorker' in navigator)) return
	const root = document.documentElement
	const appBase = (root.getAttribute('data-app-base') || '').replace(/\/$/, '')
	const assetBase = (root.getAttribute('data-asset-base') || '').replace(/\/$/, '')
	const swUrl =
		root.getAttribute('data-sw-url') ||
		(assetBase ? `${assetBase}/sw.js` : `${appBase}/sw.js`)
	if (!appBase || !swUrl) return
	void navigator.serviceWorker
		.register(swUrl, { scope: `${appBase}/`, updateViaCache: 'none' })
		.catch((error) => console.warn('SW register failed', error))
}

const context = readContext()
const basepath = context.appBasePath.replace(/\/+$/, '') || undefined
const history = createBrowserHistory()
const router = createAppRouter({ history, context, basepath })

void router.load().then(() => {
	hydrateRoot(document, createElement(RouterProvider, { router }))
	document.documentElement.dataset.hydrated = 'true'
	registerServiceWorker()
})