jamstacks 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, ServiceStack
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # Temporary Holding Version
1
+ # jamstacks
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared React components for Jamstacks templates. The initial library provides a light/dark/system theme toggle and a shared theme API. It works with React 18.2+ and React 19, including Next.js App Router and static exports, with no Next.js or Tailwind runtime dependency.
4
+
5
+ ## Install in a template
6
+
7
+ ```sh
8
+ npm install jamstacks
9
+ ```
10
+
11
+ For local development, build and install a release archive:
12
+
13
+ ```sh
14
+ # In this repository
15
+ npm ci
16
+ npm pack
17
+
18
+ # In the consuming React template (replace with the archive's actual path)
19
+ npm install /absolute/path/to/jamstacks-0.1.0.tgz
20
+ ```
21
+
22
+ Consumers can also install a pinned Git commit:
23
+
24
+ ```sh
25
+ npm install github:ServiceStack/jamstacks-react#COMMIT_SHA
26
+ ```
27
+
28
+ The Git installation's `prepare` step builds the library. Prefer a versioned npm release or a pinned Git commit for shared templates. A `file:` folder dependency is useful locally, but a packed archive tests the same files an npm release will ship and avoids linked duplicate React installations.
29
+
30
+ The package ships ESM JavaScript, TypeScript declarations, source maps with embedded sources, and component styles encapsulated inline. React and React DOM are peer dependencies supplied by the template.
31
+
32
+ ## Basic React usage
33
+
34
+ ```tsx
35
+ import { DarkModeToggle, ThemeProvider } from 'jamstacks';
36
+
37
+ export default function App() {
38
+ return (
39
+ <ThemeProvider>
40
+ <header><DarkModeToggle /></header>
41
+ <main>Your template content</main>
42
+ </ThemeProvider>
43
+ );
44
+ }
45
+ ```
46
+
47
+ Use one provider per document and place all toggles inside it. Multiple toggles share the same state. `DarkModeToggle` is a single native keyboard-accessible button that cycles between three preferences, showing a sun, moon or monitor icon for the current one. From System, a click switches to the opposite of the device's appearance, then to the device's appearance, then back to System, so the first click always changes what the visitor sees. Its accessible name and tooltip include the current preference ("Theme: System" by default; `aria-label` replaces the "Theme" prefix), and `data-theme-preference="light|dark|system"` exposes it to template selectors. It supports a forwarded button ref and ordinary button props, including `className`, `style`, `disabled`, `aria-label`, and `onClick`. Calling `event.preventDefault()` in `onClick` cancels the theme change. It stays disabled until hydration finishes so a click cannot overwrite a saved preference before it has loaded.
48
+
49
+ ## Next.js App Router
50
+
51
+ Import the early theme script from the separate **server-safe** entry point. Client entry points retain their `'use client'` directives, so a Server Component can import the provider or toggle directly.
52
+
53
+ ```tsx
54
+ // app/layout.tsx (a Server Component)
55
+ import type { ReactNode } from 'react';
56
+ import { ThemeProvider } from 'jamstacks';
57
+ import { ThemeScript } from 'jamstacks/server';
58
+ import './globals.css';
59
+
60
+ export default function RootLayout({ children }: { children: ReactNode }) {
61
+ return (
62
+ <html lang="en" suppressHydrationWarning>
63
+ <head><ThemeScript /></head>
64
+ <body><ThemeProvider>{children}</ThemeProvider></body>
65
+ </html>
66
+ );
67
+ }
68
+ ```
69
+
70
+ ```tsx
71
+ // A header or page, including a Server Component
72
+ import { DarkModeToggle } from 'jamstacks';
73
+
74
+ export default function Header() {
75
+ return <header><DarkModeToggle aria-label="Theme" /></header>;
76
+ }
77
+ ```
78
+
79
+ The early script applies the preference before the page paints; `suppressHydrationWarning` on `<html>` accounts for that intentional change to the root attributes. The provider itself renders consistently on the server and during hydration. Without `ThemeScript`, the provider still works, but the default page palette may appear briefly before hydration. No request-time rendering, cookies, or server routes are required.
80
+
81
+ For another SSR framework, inline `getThemeScript()` from `jamstacks/server` in the document head before page content. For a Content Security Policy, pass the permitted `nonce` to `ThemeScript` (or authorize the generated script with a CSP hash). Inline scripts blocked by a policy cannot prevent the initial theme flash.
82
+
83
+ ## Connect the template's palette
84
+
85
+ The provider sets `html.dark` or `html.light`, `data-theme="dark|light"`, and the root's `color-scheme` style. These attributes select the template's own palette; the library does not overwrite page design tokens.
86
+
87
+ An existing template that uses only `@media (prefers-color-scheme: dark)` needs explicit class overrides so a visitor can choose light mode on a dark device, or dark mode on a light device:
88
+
89
+ ```css
90
+ :root {
91
+ --page-background: #f5f5f0;
92
+ --page-ink: #202b26;
93
+ }
94
+
95
+ /* Device preference remains useful before hydration and without JavaScript. */
96
+ @media (prefers-color-scheme: dark) {
97
+ :root:not(.light) {
98
+ --page-background: #151c18;
99
+ --page-ink: #e5ede7;
100
+ }
101
+ }
102
+
103
+ :root.dark {
104
+ --page-background: #151c18;
105
+ --page-ink: #e5ede7;
106
+ }
107
+
108
+ body { background: var(--page-background); color: var(--page-ink); }
109
+ ```
110
+
111
+ Apply the same pattern to all of the template's dark palette variables, including inherited `--jamstacks-*` component fallbacks. With Tailwind, configure its dark variant to use the `.dark` class rather than a media query. The toggle carries its own inline styles and needs no stylesheet import or global CSS rules. Its colours can be customized through `--jamstacks-toggle-background`, `--jamstacks-toggle-dark-background`, `--jamstacks-toggle-border`, `--jamstacks-toggle-color`, and `--jamstacks-toggle-dark-color`. The `style` prop overrides the button's defaults; `className` remains available for template selectors. It preserves the browser's native keyboard-focus outline. Theme changes are instantaneous, with no animation that needs reduced-motion handling.
112
+
113
+ ## Theme API
114
+
115
+ ```tsx
116
+ 'use client';
117
+
118
+ import { useTheme } from 'jamstacks';
119
+
120
+ export function FollowDeviceButton() {
121
+ const { theme, resolvedTheme, mounted, setTheme } = useTheme();
122
+ return (
123
+ <button disabled={!mounted} onClick={() => setTheme('system')}>
124
+ Follow device (preference: {theme}, appearance: {resolvedTheme})
125
+ </button>
126
+ );
127
+ }
128
+ ```
129
+
130
+ | API | Default / behavior |
131
+ | --- | --- |
132
+ | `ThemeProvider.defaultTheme` | `'system'`; also accepts `'light'` or `'dark'` |
133
+ | `ThemeProvider.storageKey` | `'color-scheme'`, compatible with the original toggle's saved choices |
134
+ | `ThemeScript.defaultTheme`, `.storageKey` | Must match the provider when customized |
135
+ | `ThemeScript.nonce` | Optional CSP nonce |
136
+ | `useTheme().theme` | Preference: `'light'`, `'dark'`, or `'system'` |
137
+ | `useTheme().resolvedTheme` | Applied appearance: `'light'` or `'dark'` |
138
+ | `useTheme().mounted` | `false` on the server and initial hydration render; `true` after initialization |
139
+ | `useTheme().setTheme(value)` | Applies and saves the preference; `'system'` resumes following the device |
140
+
141
+ Valid saved preferences override the default. Invalid values fall back to the default. Device changes apply while using `'system'`; explicit light/dark choices remain fixed. Changes in another tab synchronize automatically; removing the key or clearing storage there returns other tabs to the default. If storage is blocked, switching still works for the current visit. Until mounted, the hook's resolved theme is the stable SSR fallback `'light'`; use `mounted` for any theme-dependent content you add yourself.
142
+
143
+ ## Local component playground
144
+
145
+ ```sh
146
+ npm ci
147
+ npm run dev
148
+ ```
149
+
150
+ Open [http://localhost:4173](http://localhost:4173). The page has light/dark/system controls, live theme and device state, shared toggle instances, colour and inline-style examples, and disabled/cancelled variants. Use the on-page checks to test persistence after reloading, synchronization between tabs, and keyboard operation. The playground uses the real component source without any library stylesheet.
151
+
152
+ Edit `demo/` or `src/` and refresh the browser to see changes. The early initialization script is rebuilt when the server starts; restart after changing that script. Stop with Ctrl+C, or select another port with `npm run dev -- --port 4300`. The server listens only on this computer and needs no external service. Demo page styles live in `demo/demo.css` and are not included in the published library.
153
+
154
+ ## Develop and validate
155
+
156
+ Use Node 24 (see `.nvmrc`).
157
+
158
+ ```sh
159
+ npm ci
160
+ npx playwright install chromium
161
+ npm run typecheck
162
+ npm test
163
+ npm pack --dry-run
164
+ ```
165
+
166
+ `npm test` builds the package, checks its public imports and server rendering, then exercises real-browser hydration, first-paint initialization, storage failures, persistence, cross-tab changes, keyboard operation and system overrides. On Linux, local tests use `/usr/bin/chromium` when available; override it with `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`. CI installs Playwright's Chromium and validates React 18.2 and React 19.3 compatibility on pushes and pull requests. Nothing is automatically published.
167
+
168
+ Add future reusable components under `src/components/` and export their public props from `src/index.ts`. Keep browser-interactive entry points marked `'use client'`, server utilities under `src/server.ts`, template content outside the package, and component styling encapsulated inline with `--jamstacks-` customization tokens.
169
+
170
+ ## Release
171
+
172
+ Publishing runs in `.github/workflows/npm-publish.yml` when a GitHub release is published, matching the ServiceStack React release flow. It checks both React versions, verifies the release tag matches the package version, builds the package and publishes to npm with provenance. Ordinary pushes and pull requests only validate; drafts and prereleases do not publish an npm version.
173
+
174
+ With a clean working tree on `main`:
175
+
176
+ ```sh
177
+ npm run bump # patch: update package + lockfile, commit, tag, and push
178
+ # Or: npm run bump:minor / npm run bump:major
179
+ npm run release # create the GitHub release; its Action publishes to npm
180
+ ```
181
+
182
+ `npm run release -- --dry-run` prints the release commands without creating or pushing tags or releases. The release command requires GitHub CLI authentication and refuses uncommitted, unpushed or mismatched-tag code. For the initial `0.1.0` release, it creates the missing version tag automatically; no bump is needed.
183
+
184
+ Configure npm trusted publishing for package `jamstacks`: GitHub organization `ServiceStack`, repository `jamstacks-react`, workflow filename `npm-publish.yml`, and permission to publish directly. No npm token is stored in the workflow. npm requires the package to exist before adding a trusted publisher; first-package registration must be completed once before running this Action. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
185
+
186
+ Commit the reproducible lockfile. `dist/`, browser reports, dependencies and package archives are generated files.
187
+
188
+ BSD-3-Clause. See [LICENSE](LICENSE).
@@ -0,0 +1,5 @@
1
+ import type { ButtonHTMLAttributes } from 'react';
2
+ export interface DarkModeToggleProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'role' | 'aria-checked' | 'aria-pressed'> {
3
+ }
4
+ /** A single tri-state light / dark / system button with encapsulated inline styles; no stylesheet import is needed. */
5
+ export declare const DarkModeToggle: import("react").ForwardRefExoticComponent<DarkModeToggleProps & import("react").RefAttributes<HTMLButtonElement>>;
@@ -0,0 +1,57 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { forwardRef } from 'react';
4
+ import { useTheme } from '../theme/ThemeProvider.js';
5
+ const names = { light: 'Light', dark: 'Dark', system: 'System' };
6
+ const buttonStyle = {
7
+ display: 'inline-grid',
8
+ placeItems: 'center',
9
+ flexShrink: 0,
10
+ boxSizing: 'border-box',
11
+ width: '2rem',
12
+ height: '2rem',
13
+ padding: 0,
14
+ border: '1px solid var(--jamstacks-toggle-border, #788579)',
15
+ borderRadius: 999,
16
+ outlineOffset: 3,
17
+ };
18
+ const iconStyle = { display: 'block', width: '1rem', height: '1rem' };
19
+ function deviceTheme() {
20
+ try {
21
+ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
22
+ }
23
+ catch {
24
+ return 'light';
25
+ }
26
+ }
27
+ /**
28
+ * Cycles through the three preferences so that the first click always changes the appearance:
29
+ * system → opposite of the device → same as the device → system.
30
+ */
31
+ function nextTheme(theme, device) {
32
+ const opposite = device === 'dark' ? 'light' : 'dark';
33
+ if (theme === 'system')
34
+ return opposite;
35
+ return theme === opposite ? device : 'system';
36
+ }
37
+ /** A single tri-state light / dark / system button with encapsulated inline styles; no stylesheet import is needed. */
38
+ export const DarkModeToggle = forwardRef(function DarkModeToggle({ className, style, onClick, disabled, title, 'aria-label': label = 'Theme', ...props }, ref) {
39
+ const { theme, resolvedTheme, setTheme, mounted } = useTheme();
40
+ const isDark = resolvedTheme === 'dark';
41
+ const isDisabled = disabled || !mounted;
42
+ const name = `${label}: ${names[theme]}`;
43
+ return (_jsx("button", { ...props, ref: ref, type: "button", className: ['jamstacks-dark-mode-toggle', className].filter(Boolean).join(' '), style: {
44
+ ...buttonStyle,
45
+ background: isDark ? 'var(--jamstacks-toggle-dark-background, #334a3c)' : 'var(--jamstacks-toggle-background, #e5e7eb)',
46
+ color: isDark ? 'var(--jamstacks-toggle-dark-color, #f3f4f6)' : 'var(--jamstacks-toggle-color, #243c2d)',
47
+ cursor: isDisabled ? 'default' : 'pointer',
48
+ opacity: isDisabled ? .55 : 1,
49
+ ...style,
50
+ }, "aria-label": name, title: title ?? name, "data-theme-preference": theme, disabled: isDisabled, onClick: event => {
51
+ onClick?.(event);
52
+ if (!event.defaultPrevented)
53
+ setTheme(nextTheme(theme, theme === 'system' ? resolvedTheme : deviceTheme()));
54
+ }, children: _jsx("svg", { className: "jamstacks-dark-mode-toggle__icon", style: iconStyle, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: theme === 'dark' ? _jsx("path", { d: "M20.5 13A8.5 8.5 0 0 1 11 3.5 8.5 8.5 0 1 0 20.5 13Z" })
55
+ : theme === 'light' ? _jsxs(_Fragment, { children: [_jsx("circle", { cx: "12", cy: "12", r: "4" }), _jsx("path", { d: "M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5" })] }) : _jsxs(_Fragment, { children: [_jsx("rect", { x: "3", y: "4", width: "18", height: "12", rx: "2" }), _jsx("path", { d: "M8 20h8m-4-4v4" })] }) }) }));
56
+ });
57
+ //# sourceMappingURL=DarkModeToggle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DarkModeToggle.js","sourceRoot":"","sources":["../../src/components/DarkModeToggle.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAEnC,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAKrD,MAAM,KAAK,GAA0B,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AAExF,MAAM,WAAW,GAAkB;IACjC,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,CAAC;IACb,SAAS,EAAE,YAAY;IACvB,KAAK,EAAE,MAAM;IACb,MAAM,EAAE,MAAM;IACd,OAAO,EAAE,CAAC;IACV,MAAM,EAAE,mDAAmD;IAC3D,YAAY,EAAE,GAAG;IACjB,aAAa,EAAE,CAAC;CACjB,CAAC;AAEF,MAAM,SAAS,GAAkB,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAErF,SAAS,WAAW;IAClB,IAAI,CAAC;QAAC,OAAO,M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AC,IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,GAAG,EAClD,eAAM,CAAC,EAAC,gBAAgB,GAAG,IAC1B,GACD,GACC,CACV,CAAC;AACJ,CAAC,CAAC,CAAC","sourcesContent":["'use client';\n\nimport { forwardRef } from 'react';\nimport type { ButtonHTMLAttributes, CSSProperties } from 'react';\nimport { useTheme } from '../theme/ThemeProvider.js';\nimport type { ResolvedTheme, Theme } from '../theme/types.js';\n\nexport interface DarkModeToggleProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'role' | 'aria-checked' | 'aria-pressed'> {}\n\nconst names: Record<Theme, string> = { light: 'Light', dark: 'Dark', system: 'System' };\n\nconst buttonStyle: CSSProperties = {\n display: 'inline-grid',\n placeItems: 'center',\n flexShrink: 0,\n boxSizing: 'border-box',\n width: '2rem',\n height: '2rem',\n padding: 0,\n border: '1px solid var(--jamstacks-toggle-border, #788579)',\n borderRadius: 999,\n outlineOffset: 3,\n};\n\nconst iconStyle: CSSProperties = { display: 'block', width: '1rem', height: '1rem' };\n\nfunction deviceTheme(): ResolvedTheme {\n try { return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } catch { return 'light'; }\n}\n\n/**\n * Cycles through the three preferences so that the first click always changes the appearance:\n * system → opposite of the device → same as the device → system.\n */\nfunction nextTheme(theme: Theme, device: ResolvedTheme): Theme {\n const opposite: ResolvedTheme = device === 'dark' ? 'light' : 'dark';\n if (theme === 'system') return opposite;\n return theme === opposite ? device : 'system';\n}\n\n/** A single tri-state light / dark / system button with encapsulated inline styles; no stylesheet import is needed. */\nexport const DarkModeToggle = forwardRef<HTMLButtonElement, DarkModeToggleProps>(function DarkModeToggle(\n { className, style, onClick, disabled, title, 'aria-label': label = 'Theme', ...props }, ref,\n) {\n const { theme, resolvedTheme, setTheme, mounted } = useTheme();\n const isDark = resolvedTheme === 'dark';\n const isDisabled = disabled || !mounted;\n const name = `${label}: ${names[theme]}`;\n return (\n <button\n {...props}\n ref={ref}\n type=\"button\"\n className={['jamstacks-dark-mode-toggle', className].filter(Boolean).join(' ')}\n style={{\n ...buttonStyle,\n background: isDark ? 'var(--jamstacks-toggle-dark-background, #334a3c)' : 'var(--jamstacks-toggle-background, #e5e7eb)',\n color: isDark ? 'var(--jamstacks-toggle-dark-color, #f3f4f6)' : 'var(--jamstacks-toggle-color, #243c2d)',\n cursor: isDisabled ? 'default' : 'pointer',\n opacity: isDisabled ? .55 : 1,\n ...style,\n }}\n aria-label={name}\n title={title ?? name}\n data-theme-preference={theme}\n disabled={isDisabled}\n onClick={event => {\n onClick?.(event);\n if (!event.defaultPrevented) setTheme(nextTheme(theme, theme === 'system' ? resolvedTheme : deviceTheme()));\n }}\n >\n <svg className=\"jamstacks-dark-mode-toggle__icon\" style={iconStyle} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n {theme === 'dark' ? <path d=\"M20.5 13A8.5 8.5 0 0 1 11 3.5 8.5 8.5 0 1 0 20.5 13Z\" />\n : theme === 'light' ? <>\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <path d=\"M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5\" />\n </> : <>\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"12\" rx=\"2\" />\n <path d=\"M8 20h8m-4-4v4\" />\n </>}\n </svg>\n </button>\n );\n});\n"]}
@@ -0,0 +1,5 @@
1
+ export { DarkModeToggle } from './components/DarkModeToggle.js';
2
+ export type { DarkModeToggleProps } from './components/DarkModeToggle.js';
3
+ export { ThemeProvider, useTheme } from './theme/ThemeProvider.js';
4
+ export type { ThemeProviderProps, ThemeContextValue } from './theme/ThemeProvider.js';
5
+ export type { Theme, ResolvedTheme } from './theme/types.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ 'use client';
2
+ export { DarkModeToggle } from './components/DarkModeToggle.js';
3
+ export { ThemeProvider, useTheme } from './theme/ThemeProvider.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["'use client';\n\nexport { DarkModeToggle } from './components/DarkModeToggle.js';\nexport type { DarkModeToggleProps } from './components/DarkModeToggle.js';\nexport { ThemeProvider, useTheme } from './theme/ThemeProvider.js';\nexport type { ThemeProviderProps, ThemeContextValue } from './theme/ThemeProvider.js';\nexport type { Theme, ResolvedTheme } from './theme/types.js';\n"]}
@@ -0,0 +1,3 @@
1
+ export { ThemeScript, getThemeScript } from './theme/ThemeScript.js';
2
+ export type { ThemeScriptProps } from './theme/ThemeScript.js';
3
+ export type { Theme, ResolvedTheme } from './theme/types.js';
package/dist/server.js ADDED
@@ -0,0 +1,2 @@
1
+ export { ThemeScript, getThemeScript } from './theme/ThemeScript.js';
2
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC","sourcesContent":["export { ThemeScript, getThemeScript } from './theme/ThemeScript.js';\nexport type { ThemeScriptProps } from './theme/ThemeScript.js';\nexport type { Theme, ResolvedTheme } from './theme/types.js';\n"]}
@@ -0,0 +1,18 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { ResolvedTheme, Theme } from './types.js';
3
+ export interface ThemeContextValue {
4
+ /** Saved preference; system follows the device until the user chooses a mode. */
5
+ theme: Theme;
6
+ resolvedTheme: ResolvedTheme;
7
+ /** False during server rendering and the first hydration render. */
8
+ mounted: boolean;
9
+ setTheme: (theme: Theme) => void;
10
+ }
11
+ export interface ThemeProviderProps {
12
+ children: ReactNode;
13
+ defaultTheme?: Theme;
14
+ storageKey?: string;
15
+ }
16
+ /** Use one provider per document. React rendering stays identical on the server and during hydration. */
17
+ export declare function ThemeProvider({ children, defaultTheme, storageKey }: ThemeProviderProps): import("react").JSX.Element;
18
+ export declare function useTheme(): ThemeContextValue;
@@ -0,0 +1,76 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { DEFAULT_STORAGE_KEY, isTheme } from './types.js';
5
+ const ThemeContext = createContext(null);
6
+ /** Use one provider per document. React rendering stays identical on the server and during hydration. */
7
+ export function ThemeProvider({ children, defaultTheme = 'system', storageKey = DEFAULT_STORAGE_KEY }) {
8
+ const [theme, setPreference] = useState(defaultTheme);
9
+ const [resolvedTheme, setResolvedTheme] = useState('light');
10
+ const [mounted, setMounted] = useState(false);
11
+ const preference = useRef(defaultTheme);
12
+ const apply = useCallback((next) => {
13
+ const resolved = next === 'system'
14
+ ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
15
+ : next;
16
+ preference.current = next;
17
+ const root = document.documentElement;
18
+ root.classList.toggle('dark', resolved === 'dark');
19
+ root.classList.toggle('light', resolved === 'light');
20
+ root.dataset.theme = resolved;
21
+ root.style.colorScheme = resolved;
22
+ setPreference(next);
23
+ setResolvedTheme(resolved);
24
+ }, []);
25
+ const setTheme = useCallback((next) => {
26
+ if (!isTheme(next))
27
+ return;
28
+ apply(next);
29
+ // Browsers may deny storage. The toggle must still work for this visit.
30
+ try {
31
+ window.localStorage.setItem(storageKey, next);
32
+ }
33
+ catch { /* Storage is optional. */ }
34
+ }, [apply, storageKey]);
35
+ useEffect(() => {
36
+ let initial = defaultTheme;
37
+ try {
38
+ const saved = window.localStorage.getItem(storageKey);
39
+ if (isTheme(saved))
40
+ initial = saved;
41
+ }
42
+ catch { /* Use the default when storage is unavailable. */ }
43
+ apply(initial);
44
+ setMounted(true);
45
+ const media = window.matchMedia('(prefers-color-scheme: dark)');
46
+ const onMediaChange = () => { if (preference.current === 'system')
47
+ apply('system'); };
48
+ const onStorage = (event) => {
49
+ if (event.key !== storageKey && event.key !== null)
50
+ return;
51
+ try {
52
+ if (event.storageArea !== window.localStorage)
53
+ return;
54
+ }
55
+ catch {
56
+ return;
57
+ }
58
+ apply(isTheme(event.newValue) ? event.newValue : defaultTheme);
59
+ };
60
+ media.addEventListener('change', onMediaChange);
61
+ window.addEventListener('storage', onStorage);
62
+ return () => {
63
+ media.removeEventListener('change', onMediaChange);
64
+ window.removeEventListener('storage', onStorage);
65
+ };
66
+ }, [apply, defaultTheme, storageKey]);
67
+ const value = useMemo(() => ({ theme, resolvedTheme, mounted, setTheme }), [theme, resolvedTheme, mounted, setTheme]);
68
+ return _jsx(ThemeContext.Provider, { value: value, children: children });
69
+ }
70
+ export function useTheme() {
71
+ const value = useContext(ThemeContext);
72
+ if (!value)
73
+ throw new Error('useTheme and DarkModeToggle must be used inside a ThemeProvider.');
74
+ return value;
75
+ }
76
+ //# sourceMappingURL=ThemeProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ThemeProvider.js","sourceRoot":"","sources":["../../src/theme/ThemeProvider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAErG,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAkB1D,MAAM,YAAY,GAAG,aAAa,CAA2B,IAAI,CAAC,CAAC;AAEnE,yGAAyG;AACzG,MAAM,UAAU,aAAa,CAAC,EAAE,QAAQ,EAAE,YAAY,GAAG,QAAQ,EAAE,UAAU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BAAgB,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;QAChD,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;QAC9C,OAAO,GAAG,EAAE;YACV,KAAK,CAAC,mBAAmB,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;YACnD,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;QACnD,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC,CAAC;IAEtC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;IACtH,OAAO,KAAC,YAAY,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAAyB,CAAC;AACjF,CAAC;AAED,MAAM,UAAU,QAAQ;IACtB,MAAM,KAAK,GAAG,UAAU,CAAC,YAAY,CAAC,CAAC;IACvC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IAChG,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { DEFAULT_STORAGE_KEY, isTheme } from './types.js';\nimport type { ResolvedTheme, Theme } from './types.js';\n\nexport interface ThemeContextValue {\n /** Saved preference; system follows the device until the user chooses a mode. */\n theme: Theme;\n resolvedTheme: ResolvedTheme;\n /** False during server rendering and the first hydration render. */\n mounted: boolean;\n setTheme: (theme: Theme) => void;\n}\n\nexport interface ThemeProviderProps {\n children: ReactNode;\n defaultTheme?: Theme;\n storageKey?: string;\n}\n\nconst ThemeContext = createContext<ThemeContextValue | null>(null);\n\n/** Use one provider per document. React rendering stays identical on the server and during hydration. */\nexport function ThemeProvider({ children, defaultTheme = 'system', storageKey = DEFAULT_STORAGE_KEY }: ThemeProviderProps) {\n const [theme, setPreference] = useState<Theme>(defaultTheme);\n const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>('light');\n const [mounted, setMounted] = useState(false);\n const preference = useRef<Theme>(defaultTheme);\n\n const apply = useCallback((next: Theme) => {\n const resolved = next === 'system'\n ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')\n : next;\n preference.current = next;\n const root = document.documentElement;\n root.classList.toggle('dark', resolved === 'dark');\n root.classList.toggle('light', resolved === 'light');\n root.dataset.theme = resolved;\n root.style.colorScheme = resolved;\n setPreference(next);\n setResolvedTheme(resolved);\n }, []);\n\n const setTheme = useCallback((next: Theme) => {\n if (!isTheme(next)) return;\n apply(next);\n // Browsers may deny storage. The toggle must still work for this visit.\n try { window.localStorage.setItem(storageKey, next); } catch { /* Storage is optional. */ }\n }, [apply, storageKey]);\n\n useEffect(() => {\n let initial = defaultTheme;\n try {\n const saved = window.localStorage.getItem(storageKey);\n if (isTheme(saved)) initial = saved;\n } catch { /* Use the default when storage is unavailable. */ }\n apply(initial);\n setMounted(true);\n\n const media = window.matchMedia('(prefers-color-scheme: dark)');\n const onMediaChange = () => { if (preference.current === 'system') apply('system'); };\n const onStorage = (event: StorageEvent) => {\n if (event.key !== storageKey && event.key !== null) return;\n try { if (event.storageArea !== window.localStorage) return; } catch { return; }\n apply(isTheme(event.newValue) ? event.newValue : defaultTheme);\n };\n media.addEventListener('change', onMediaChange);\n window.addEventListener('storage', onStorage);\n return () => {\n media.removeEventListener('change', onMediaChange);\n window.removeEventListener('storage', onStorage);\n };\n }, [apply, defaultTheme, storageKey]);\n\n const value = useMemo(() => ({ theme, resolvedTheme, mounted, setTheme }), [theme, resolvedTheme, mounted, setTheme]);\n return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;\n}\n\nexport function useTheme(): ThemeContextValue {\n const value = useContext(ThemeContext);\n if (!value) throw new Error('useTheme and DarkModeToggle must be used inside a ThemeProvider.');\n return value;\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import type { Theme } from './types.js';
2
+ export interface ThemeScriptProps {
3
+ defaultTheme?: Theme;
4
+ storageKey?: string;
5
+ /** Use the same nonce as your Content-Security-Policy. */
6
+ nonce?: string;
7
+ }
8
+ /** Inline in the document head to apply the preference before the first paint. */
9
+ export declare function getThemeScript({ storageKey, defaultTheme }?: Omit<ThemeScriptProps, 'nonce'>): string;
10
+ /** Server-safe entry point. Match its settings to ThemeProvider. */
11
+ export declare function ThemeScript({ nonce, ...options }: ThemeScriptProps): import("react").JSX.Element;
@@ -0,0 +1,28 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { DEFAULT_STORAGE_KEY } from './types.js';
3
+ // Self-contained so its compiled JavaScript can run before React hydrates.
4
+ function initializeTheme(storageKey, defaultTheme) {
5
+ let theme = defaultTheme;
6
+ try {
7
+ const saved = localStorage.getItem(storageKey);
8
+ if (saved === 'light' || saved === 'dark' || saved === 'system')
9
+ theme = saved;
10
+ }
11
+ catch { /* Storage is optional. */ }
12
+ const dark = theme === 'dark' || (theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
13
+ const root = document.documentElement;
14
+ root.classList.toggle('dark', dark);
15
+ root.classList.toggle('light', !dark);
16
+ root.dataset.theme = dark ? 'dark' : 'light';
17
+ root.style.colorScheme = dark ? 'dark' : 'light';
18
+ }
19
+ /** Inline in the document head to apply the preference before the first paint. */
20
+ export function getThemeScript({ storageKey = DEFAULT_STORAGE_KEY, defaultTheme = 'system' } = {}) {
21
+ const args = JSON.stringify([storageKey, defaultTheme]).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
22
+ return `(${initializeTheme.toString()})(...${args});`;
23
+ }
24
+ /** Server-safe entry point. Match its settings to ThemeProvider. */
25
+ export function ThemeScript({ nonce, ...options }) {
26
+ return _jsx("script", { nonce: nonce, dangerouslySetInnerHTML: { __html: getThemeScript(options) } });
27
+ }
28
+ //# sourceMappingURL=ThemeScript.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ThemeScript.js","sourceRoot":"","sources":["../../src/theme/ThemeScript.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAUjD,2EAA2E;AAC3E,SAAS,eAAe,CAAC,UAAkB,EAAE,YAAmB;IAC9D,IAAI,KAAK,GAAG,YAAY,CAAC;IACzB,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAC/C,IAAI,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,QAAQ;YAAE,KAAK,GAAG,KAAK,CAAC;IACjF,CAAC;IAAC,MAAM,CAAC,CAAC,0BAA0B,CAAC,CAAC;IACtC,MAAM,IAAI,GAAG,KAAK,KAAK,MAAM,IAAI,CAAC,KAAK,KAAK,QAAQ,IAAI,UAAU,CAAC,8BAA8B,CAAC,CAAC,OAAO,CAAC,CAAC;IAC5G,MAAM,IAAI,GAAG,QAAQ,CAAC,eAAe,CAAC;IACtC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACpC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,CAAC,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7C,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;AACnD,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,cAAc,CAAC,EAAE,UAAU,GAAG,mBAAmB,EAAE,YAAY,GAAG,QAAQ,EAAE,GAAoC,EAAE;IAChI,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IACtK,OAAO,IAAI,eAAe,CAAC,QAAQ,EAAE,QAAQ,IAAI,IAAI,CAAC;AACxD,CAAC;AAED,oEAAoE;AACpE,MAAM,UAAU,WAAW,CAAC,EAAE,KAAK,EAAE,GAAG,OAAO,EAAoB;IACjE,OAAO,iBAAQ,KAAK,EAAE,KAAK,EAAE,uBAAuB,EAAE,EAAE,MAAM,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,GAAI,CAAC;AAChG,CAAC","sourcesContent":["import { DEFAULT_STORAGE_KEY } from './types.js';\nimport type { Theme } from './types.js';\n\nexport interface ThemeScriptProps {\n defaultTheme?: Theme;\n storageKey?: string;\n /** Use the same nonce as your Content-Security-Policy. */\n nonce?: string;\n}\n\n// Self-contained so its compiled JavaScript can run before React hydrates.\nfunction initializeTheme(storageKey: string, defaultTheme: Theme) {\n let theme = defaultTheme;\n try {\n const saved = localStorage.getItem(storageKey);\n if (saved === 'light' || saved === 'dark' || saved === 'system') theme = saved;\n } catch { /* Storage is optional. */ }\n const dark = theme === 'dark' || (theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);\n const root = document.documentElement;\n root.classList.toggle('dark', dark);\n root.classList.toggle('light', !dark);\n root.dataset.theme = dark ? 'dark' : 'light';\n root.style.colorScheme = dark ? 'dark' : 'light';\n}\n\n/** Inline in the document head to apply the preference before the first paint. */\nexport function getThemeScript({ storageKey = DEFAULT_STORAGE_KEY, defaultTheme = 'system' }: Omit<ThemeScriptProps, 'nonce'> = {}): string {\n const args = JSON.stringify([storageKey, defaultTheme]).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');\n return `(${initializeTheme.toString()})(...${args});`;\n}\n\n/** Server-safe entry point. Match its settings to ThemeProvider. */\nexport function ThemeScript({ nonce, ...options }: ThemeScriptProps) {\n return <script nonce={nonce} dangerouslySetInnerHTML={{ __html: getThemeScript(options) }} />;\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export type Theme = 'light' | 'dark' | 'system';
2
+ export type ResolvedTheme = Exclude<Theme, 'system'>;
3
+ export declare const DEFAULT_STORAGE_KEY = "color-scheme";
4
+ export declare function isTheme(value: unknown): value is Theme;
@@ -0,0 +1,5 @@
1
+ export const DEFAULT_STORAGE_KEY = 'color-scheme';
2
+ export function isTheme(value) {
3
+ return value === 'light' || value === 'dark' || value === 'system';
4
+ }
5
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/theme/types.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,mBAAmB,GAAG,cAAc,CAAC;AAElD,MAAM,UAAU,OAAO,CAAC,KAAc;IACpC,OAAO,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,QAAQ,CAAC;AACrE,CAAC","sourcesContent":["export type Theme = 'light' | 'dark' | 'system';\nexport type ResolvedTheme = Exclude<Theme, 'system'>;\n\nexport const DEFAULT_STORAGE_KEY = 'color-scheme';\n\nexport function isTheme(value: unknown): value is Theme {\n return value === 'light' || value === 'dark' || value === 'system';\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "jamstacks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Shared React components and theme utilities for Jamstacks templates.",
5
+ "license": "BSD-3-Clause",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ServiceStack/jamstacks-react.git"
10
+ },
11
+ "homepage": "https://github.com/ServiceStack/jamstacks-react#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/ServiceStack/jamstacks-react/issues"
14
+ },
15
+ "keywords": [
16
+ "jamstacks",
17
+ "react",
18
+ "components",
19
+ "dark-mode",
20
+ "nextjs"
21
+ ],
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./server": {
35
+ "types": "./dist/server.d.ts",
36
+ "import": "./dist/server.js",
37
+ "default": "./dist/server.js"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "sideEffects": false,
42
+ "scripts": {
43
+ "dev": "npm run build && node scripts/dev.mjs",
44
+ "build": "node scripts/build.mjs",
45
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.demo.json",
46
+ "test": "npm run build && node --test tests/package.test.mjs && playwright test",
47
+ "test:browser": "playwright test",
48
+ "bump": "npm version patch && git push origin main --follow-tags",
49
+ "bump:minor": "npm version minor && git push origin main --follow-tags",
50
+ "bump:major": "npm version major && git push origin main --follow-tags",
51
+ "release": "node scripts/release.mjs",
52
+ "prepare": "npm run build",
53
+ "prepack": "npm run build"
54
+ },
55
+ "peerDependencies": {
56
+ "react": "^18.2.0 || ^19.0.0",
57
+ "react-dom": "^18.2.0 || ^19.0.0"
58
+ },
59
+ "devDependencies": {
60
+ "@playwright/test": "1.65.1",
61
+ "@types/node": "24.19.2",
62
+ "@types/react": "19.3.0",
63
+ "@types/react-dom": "19.3.0",
64
+ "esbuild": "0.28.2",
65
+ "react": "19.3.1",
66
+ "react-dom": "19.3.1",
67
+ "typescript": "7.0.2"
68
+ },
69
+ "engines": {
70
+ "node": ">=22"
71
+ },
72
+ "publishConfig": {
73
+ "access": "public"
74
+ }
75
+ }