@taujs/react 0.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Aoede Ltd 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # @taujs/server
2
+
3
+ `npm install @taujs/server`
4
+
5
+ `yarn add @taujs/server`
6
+
7
+ `pnpm add @taujs/server`
8
+
9
+ ## CSR; SSR; Streaming SSR; Hydration; Fastify + React 19
10
+
11
+ Supports rendering modes:
12
+
13
+ - Client-side rendering (CSR)
14
+ - Server-side rendering (SSR)
15
+ - Streaming SSR
16
+
17
+ Supported application structure and composition:
18
+
19
+ - Single-page Application (SPA)
20
+ - Multi-page Application (MPA)
21
+ - Build-time Micro-Frontends (MFE), with server orchestration and delivery
22
+
23
+ Assemble independent frontends at build time incorporating flexible per-route SPA-MPA hybrid with CSR, SSR, and Streaming SSR, rendering options.
24
+
25
+ Fastify Plugin for integration with taujs [ τjs ] template https://github.com/aoede3/taujs
26
+
27
+ - Production: Fastify, React
28
+ - Development: Fastify, React, tsx, Vite
29
+
30
+ - TypeScript-first
31
+ - ESM-only focus
32
+
33
+ ## τjs - DX Developer Experience
34
+
35
+ Integrated Vite HMR run alongside tsx (TS eXecute) providing fast responsive dev reload times for universal backend / frontend changes
36
+
37
+ - Fastify https://fastify.dev/
38
+ - React https://reactjs.org/
39
+ - tsx https://tsx.is/
40
+ - Vite https://vitejs.dev/guide/ssr#building-for-production
41
+
42
+ - ESBuild https://esbuild.github.io/
43
+ - Rollup https://rollupjs.org/
44
+ - ESM https://nodejs.org/api/esm.html
45
+
46
+ ## Development / CI
47
+
48
+ `npm install --legacy-peer-deps`
49
+
50
+ ## Usage
51
+
52
+ ### Fastify
53
+
54
+ https://github.com/aoede3/taujs/blob/main/src/server/index.ts
55
+
56
+ Not utilising taujs [ τjs ] template? Add in your own ts `alias` object for your own particular directory setup e.g. `alias: { object }`
57
+
58
+ ### React 'entry-client.tsx'
59
+
60
+ https://github.com/aoede3/taujs/blob/main/src/client/entry-client.tsx
61
+
62
+ ### React 'entry-server.tsx'
63
+
64
+ Extended pipe object with callbacks to @taujs/server enabling additional manipulation of HEAD content from client code
65
+
66
+ https://github.com/aoede3/taujs/blob/main/src/client/entry-server.tsx
67
+
68
+ ### index.html
69
+
70
+ https://github.com/aoede3/taujs/blob/main/src/client/index.html
71
+
72
+ ### client.d.ts
73
+
74
+ https://github.com/aoede3/taujs/blob/main/src/client/client.d.ts
75
+
76
+ ### Routes
77
+
78
+ Integral to τjs is its internal routing:
79
+
80
+ 1. Fastify serving index.html to client browser for client routing
81
+ 2. Internal service calls to API to provide data for streaming/hydration
82
+ 3. Fastify serving API calls via HTTP in the more traditional sense of client/server
83
+
84
+ In ensuring a particular 'route' receives data for hydration there are two options:
85
+
86
+ 1. An HTTP call syntactically not unlike 'fetch' providing params to a 'fetch' call
87
+ 2. Internal service call returning data as per your architecture
88
+
89
+ In supporting Option 2. there is a registry of services. More detail in 'Service Registry'.
90
+
91
+ Each routes 'path' is a simple URL regex as per below examples.
92
+
93
+ https://github.com/aoede3/taujs/blob/main/src/shared/routes/Routes.ts
94
+
95
+ ### Service Registry
96
+
97
+ In supporting internal calls via τjs a registry of available services and methods can provide linkage to your own architectural setup and developmental patterns
98
+
99
+ https://github.com/aoede3/taujs/blob/main/src/server/services/ServiceRegistry.ts
100
+
101
+ https://github.com/aoede3/taujs/blob/main/src/server/services/ServiceExample.ts
@@ -0,0 +1,49 @@
1
+ import React from 'react';
2
+ import { ServerResponse } from 'node:http';
3
+
4
+ type SSRStore<T> = {
5
+ getSnapshot: () => T;
6
+ getServerSnapshot: () => T;
7
+ setData: (newData: T) => void;
8
+ subscribe: (callback: () => void) => () => void;
9
+ };
10
+ declare const createSSRStore: <T>(initialDataOrPromise: T | Promise<T>) => SSRStore<T>;
11
+ declare const SSRStoreProvider: React.FC<React.PropsWithChildren<{
12
+ store: SSRStore<Record<string, unknown>>;
13
+ }>>;
14
+ declare const useSSRStore: <T>() => T;
15
+
16
+ type HydrateAppOptions = {
17
+ appComponent: React.ReactElement;
18
+ initialDataKey?: keyof Window;
19
+ rootElementId?: string;
20
+ debug?: boolean;
21
+ };
22
+ declare const hydrateApp: ({ appComponent, initialDataKey, rootElementId, debug }: HydrateAppOptions) => void;
23
+
24
+ type RendererOptions = {
25
+ appComponent: (props: {
26
+ location: string;
27
+ }) => React.ReactElement;
28
+ headContent: string | ((data: Record<string, unknown>) => string);
29
+ };
30
+ type RenderCallbacks = {
31
+ onHead: (headContent: string) => void;
32
+ onFinish: (initialDataResolved: unknown) => void;
33
+ onError: (error: unknown) => void;
34
+ };
35
+ declare const resolveHeadContent: (headContent: string | ((meta: Record<string, unknown>) => string), meta?: Record<string, unknown>) => string;
36
+ declare const createRenderer: ({ appComponent, headContent }: RendererOptions) => {
37
+ renderSSR: (initialDataResolved: Record<string, unknown>, location: string, meta?: Record<string, unknown>) => Promise<{
38
+ headContent: string;
39
+ appHtml: string;
40
+ }>;
41
+ renderStream: (serverResponse: ServerResponse, callbacks: RenderCallbacks, initialDataResolved: Record<string, unknown>, location: string, bootstrapModules?: string, meta?: Record<string, unknown>) => void;
42
+ };
43
+ declare const createRenderStream: (serverResponse: ServerResponse, { onHead, onFinish, onError }: RenderCallbacks, { appComponent, headContent, initialDataResolved, location, bootstrapModules, }: RendererOptions & {
44
+ initialDataResolved: Record<string, unknown>;
45
+ location: string;
46
+ bootstrapModules?: string;
47
+ }) => void;
48
+
49
+ export { type SSRStore, SSRStoreProvider, createRenderStream, createRenderer, createSSRStore, hydrateApp, resolveHeadContent, useSSRStore };
package/dist/index.js ADDED
@@ -0,0 +1,182 @@
1
+ // src/SSRDataStore.tsx
2
+ import { createContext, useContext, useSyncExternalStore } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ var createSSRStore = (initialDataOrPromise) => {
5
+ let currentData;
6
+ let status;
7
+ const subscribers = /* @__PURE__ */ new Set();
8
+ let serverDataPromise;
9
+ if (initialDataOrPromise instanceof Promise) {
10
+ status = "pending";
11
+ serverDataPromise = initialDataOrPromise.then((data) => {
12
+ currentData = data;
13
+ status = "success";
14
+ subscribers.forEach((callback) => callback());
15
+ }).catch((error) => {
16
+ console.error("Failed to load initial data:", error);
17
+ status = "error";
18
+ }).then(() => {
19
+ });
20
+ } else {
21
+ currentData = initialDataOrPromise;
22
+ status = "success";
23
+ serverDataPromise = Promise.resolve();
24
+ }
25
+ const setData = (newData) => {
26
+ currentData = newData;
27
+ status = "success";
28
+ subscribers.forEach((callback) => callback());
29
+ };
30
+ const subscribe = (callback) => {
31
+ subscribers.add(callback);
32
+ return () => subscribers.delete(callback);
33
+ };
34
+ const getSnapshot = () => {
35
+ if (status === "pending") {
36
+ throw serverDataPromise;
37
+ } else if (status === "error") {
38
+ throw new Error("An error occurred while fetching the data.");
39
+ }
40
+ return currentData;
41
+ };
42
+ const getServerSnapshot = () => {
43
+ if (status === "pending") {
44
+ throw serverDataPromise;
45
+ } else if (status === "error") {
46
+ throw new Error("Data is not available on the server.");
47
+ }
48
+ return currentData;
49
+ };
50
+ return { getSnapshot, getServerSnapshot, setData, subscribe };
51
+ };
52
+ var SSRStoreContext = createContext(null);
53
+ var SSRStoreProvider = ({ store, children }) => /* @__PURE__ */ jsx(SSRStoreContext.Provider, { value: store, children });
54
+ var useSSRStore = () => {
55
+ const store = useContext(SSRStoreContext);
56
+ if (!store) throw new Error("useSSRStore must be used within a SSRStoreProvider");
57
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
58
+ };
59
+
60
+ // src/SSRHydration.tsx
61
+ import React2 from "react";
62
+ import { createRoot, hydrateRoot } from "react-dom/client";
63
+
64
+ // src/utils/Logger.ts
65
+ var createLogger = (debug) => ({
66
+ log: (...args) => {
67
+ if (debug) console.log(...args);
68
+ },
69
+ warn: (...args) => {
70
+ if (debug) console.warn(...args);
71
+ },
72
+ error: (...args) => {
73
+ if (debug) console.error(...args);
74
+ }
75
+ });
76
+
77
+ // src/SSRHydration.tsx
78
+ import { jsx as jsx2 } from "react/jsx-runtime";
79
+ var hydrateApp = ({ appComponent, initialDataKey = "__INITIAL_DATA__", rootElementId = "root", debug = false }) => {
80
+ const { log, warn, error } = createLogger(debug);
81
+ const bootstrap = () => {
82
+ log("Hydration started");
83
+ const rootElement = document.getElementById(rootElementId);
84
+ if (!rootElement) {
85
+ error(`Root element with id "${rootElementId}" not found.`);
86
+ return;
87
+ }
88
+ const initialData = window[initialDataKey];
89
+ if (!initialData) {
90
+ warn(`Initial data key "${initialDataKey}" is undefined on window. Defaulting to SPA createRoot`);
91
+ const root = createRoot(rootElement);
92
+ root.render(/* @__PURE__ */ jsx2(React2.StrictMode, { children: appComponent }));
93
+ } else {
94
+ log("Initial data loaded:", initialData);
95
+ const initialDataPromise = Promise.resolve(initialData);
96
+ const store = createSSRStore(initialDataPromise);
97
+ log("Store created:", store);
98
+ hydrateRoot(
99
+ rootElement,
100
+ /* @__PURE__ */ jsx2(React2.StrictMode, { children: /* @__PURE__ */ jsx2(SSRStoreProvider, { store, children: appComponent }) })
101
+ );
102
+ log("Hydration completed");
103
+ }
104
+ };
105
+ if (document.readyState !== "loading") {
106
+ bootstrap();
107
+ } else {
108
+ document.addEventListener("DOMContentLoaded", bootstrap);
109
+ }
110
+ };
111
+
112
+ // src/SSRRender.tsx
113
+ import "http";
114
+ import { Writable } from "stream";
115
+ import "react";
116
+ import { renderToPipeableStream, renderToString } from "react-dom/server";
117
+ import { jsx as jsx3 } from "react/jsx-runtime";
118
+ var resolveHeadContent = (headContent, meta = {}) => typeof headContent === "function" ? headContent(meta) : headContent;
119
+ var createRenderer = ({ appComponent, headContent }) => {
120
+ const renderSSR = async (initialDataResolved, location, meta = {}) => {
121
+ const dataForHeadContent = Object.keys(initialDataResolved).length > 0 ? initialDataResolved : meta;
122
+ const dynamicHeadContent = resolveHeadContent(headContent, dataForHeadContent);
123
+ const appHtml = renderToString(/* @__PURE__ */ jsx3(SSRStoreProvider, { store: createSSRStore(initialDataResolved), children: appComponent({ location }) }));
124
+ return {
125
+ headContent: dynamicHeadContent,
126
+ appHtml
127
+ };
128
+ };
129
+ const renderStream = (serverResponse, callbacks, initialDataResolved, location, bootstrapModules, meta = {}) => {
130
+ const dynamicHeadContent = resolveHeadContent(headContent, meta);
131
+ createRenderStream(serverResponse, callbacks, {
132
+ appComponent: (props) => appComponent({ ...props, location }),
133
+ headContent: dynamicHeadContent,
134
+ initialDataResolved,
135
+ location,
136
+ bootstrapModules
137
+ });
138
+ };
139
+ return { renderSSR, renderStream };
140
+ };
141
+ var createRenderStream = (serverResponse, { onHead, onFinish, onError }, {
142
+ appComponent,
143
+ headContent,
144
+ initialDataResolved,
145
+ location,
146
+ bootstrapModules
147
+ }) => {
148
+ const store = createSSRStore(initialDataResolved);
149
+ const appElement = /* @__PURE__ */ jsx3(SSRStoreProvider, { store, children: appComponent({ location }) });
150
+ const { pipe } = renderToPipeableStream(appElement, {
151
+ bootstrapModules: bootstrapModules ? [bootstrapModules] : void 0,
152
+ onShellReady() {
153
+ const dynamicHeadContent = resolveHeadContent(headContent, initialDataResolved);
154
+ onHead(dynamicHeadContent);
155
+ pipe(
156
+ new Writable({
157
+ write(chunk, _encoding, callback) {
158
+ serverResponse.write(chunk, callback);
159
+ },
160
+ final(callback) {
161
+ onFinish(store.getSnapshot());
162
+ callback();
163
+ }
164
+ })
165
+ );
166
+ },
167
+ onAllReady() {
168
+ },
169
+ onError(error) {
170
+ onError(error);
171
+ }
172
+ });
173
+ };
174
+ export {
175
+ SSRStoreProvider,
176
+ createRenderStream,
177
+ createRenderer,
178
+ createSSRStore,
179
+ hydrateApp,
180
+ resolveHeadContent,
181
+ useSSRStore
182
+ };
package/package.json ADDED
@@ -0,0 +1,84 @@
1
+ {
2
+ "name": "@taujs/react",
3
+ "version": "0.0.1",
4
+ "description": "taujs | τjs",
5
+ "author": "Aoede <taujs@aoede.uk.net> (https://www.aoede.uk.net)",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/aoede3/taujs-react",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/aoede3/taujs-react.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/aoede3/taujs-react/issues"
14
+ },
15
+ "keywords": [
16
+ "fastify",
17
+ "typescript",
18
+ "esm",
19
+ "vite",
20
+ "streaming",
21
+ "react",
22
+ "ssr"
23
+ ],
24
+ "type": "module",
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": "./dist/index.js",
30
+ "types": "./dist/index.d.ts"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "devDependencies": {
38
+ "@arethetypeswrong/cli": "^0.15.4",
39
+ "@babel/preset-typescript": "^7.24.7",
40
+ "@changesets/cli": "^2.27.7",
41
+ "@testing-library/dom": "^10.4.0",
42
+ "@testing-library/react": "^16.1.0",
43
+ "@types/react": "^19.0.2",
44
+ "@types/react-dom": "^19.0.2",
45
+ "@vitest/coverage-v8": "^2.1.0",
46
+ "jsdom": "^25.0.0",
47
+ "prettier": "^3.3.3",
48
+ "react": "^19.0.0",
49
+ "react-dom": "^19.0.0",
50
+ "tsup": "^8.2.4",
51
+ "typescript": "^5.5.4",
52
+ "vite": "^6.3.5",
53
+ "vitest": "^2.0.5"
54
+ },
55
+ "peerDependencies": {
56
+ "@taujs/server": "^0.2.0",
57
+ "react": "^19.0.0",
58
+ "react-dom": "^19.0.0",
59
+ "typescript": "^5.5.4",
60
+ "vite": "^6.3.5"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "react": {
64
+ "optional": true
65
+ },
66
+ "react-dom": {
67
+ "optional": true
68
+ }
69
+ },
70
+ "scripts": {
71
+ "build": "tsup",
72
+ "build-local": "tsup && ./move.sh",
73
+ "ci": "npm run build && npm run check-format && npm run lint",
74
+ "lint": "tsc",
75
+ "test": "vitest run",
76
+ "test:ui": "vitest --ui --coverage.enabled=true",
77
+ "coverage": "vitest run --coverage",
78
+ "format": "prettier --write .",
79
+ "check-format": "prettier --check .",
80
+ "check-exports": "attw --pack . --ignore-rules=cjs-resolves-to-esm",
81
+ "prepublishOnly": "npm run ci",
82
+ "local-release": "npm run ci && changeset version && changeset publish"
83
+ }
84
+ }