@richie-router/server 0.0.1 → 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.
@@ -0,0 +1,237 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
36
+ });
37
+ };
38
+
39
+ // packages/server/src/index.ts
40
+ var exports_src = {};
41
+ __export(exports_src, {
42
+ handleRequest: () => handleRequest,
43
+ defineHeadTags: () => defineHeadTags
44
+ });
45
+ module.exports = __toCommonJS(exports_src);
46
+ var import_core = require("@richie-router/core");
47
+ function defineHeadTags(routeManifest, headTagSchema, definitions) {
48
+ return {
49
+ routeManifest,
50
+ headTagSchema,
51
+ definitions
52
+ };
53
+ }
54
+ var HEAD_PLACEHOLDER = "<!--richie-router-head-->";
55
+ var MANAGED_HEAD_ATTRIBUTE = "data-richie-router-head";
56
+ function routeHasRecord(value) {
57
+ return typeof value === "object" && value !== null;
58
+ }
59
+ function createHeadSnapshotScript(href, head) {
60
+ const payload = JSON.stringify({ href, head }).replaceAll("</script>", "<\\/script>");
61
+ return `<script ${MANAGED_HEAD_ATTRIBUTE}="true">window.__RICHIE_ROUTER_HEAD__=${payload}</script>`;
62
+ }
63
+ async function renderTemplate(html, ctx) {
64
+ const template = html.template;
65
+ if (typeof template === "function") {
66
+ return await template(ctx);
67
+ }
68
+ if (!template.includes(HEAD_PLACEHOLDER)) {
69
+ throw new Error(`HTML template is missing required Richie Router placeholder: ${HEAD_PLACEHOLDER}`);
70
+ }
71
+ return template.replace(HEAD_PLACEHOLDER, ctx.richieRouterHead);
72
+ }
73
+ function jsonResponse(data, init) {
74
+ return new Response(JSON.stringify(data), {
75
+ ...init,
76
+ headers: {
77
+ "content-type": "application/json; charset=utf-8",
78
+ ...init?.headers ?? {}
79
+ }
80
+ });
81
+ }
82
+ function resolveSearch(route, rawSearch) {
83
+ const fromSchema = route.searchSchema ? route.searchSchema.parse(rawSearch) : {};
84
+ if (routeHasRecord(fromSchema)) {
85
+ return fromSchema;
86
+ }
87
+ return rawSearch;
88
+ }
89
+ function buildMatches(routeManifest, location) {
90
+ const matched = import_core.matchRouteTree(routeManifest, location.pathname);
91
+ if (!matched) {
92
+ return [];
93
+ }
94
+ const rawSearch = location.search;
95
+ let accumulatedSearch = { ...rawSearch };
96
+ return matched.map(({ route, params }) => {
97
+ const nextSearch = resolveSearch(route, rawSearch);
98
+ if (routeHasRecord(nextSearch)) {
99
+ accumulatedSearch = {
100
+ ...accumulatedSearch,
101
+ ...nextSearch
102
+ };
103
+ }
104
+ return {
105
+ id: route.fullPath,
106
+ pathname: location.pathname,
107
+ params,
108
+ route,
109
+ search: accumulatedSearch,
110
+ to: route.to
111
+ };
112
+ });
113
+ }
114
+ async function executeHeadTag(request, headTags, headTagName, params, rawSearch) {
115
+ const definition = headTags.definitions[headTagName];
116
+ const schemaEntry = headTags.headTagSchema[headTagName];
117
+ if (!definition) {
118
+ throw new Error(`Unknown head tag "${headTagName}".`);
119
+ }
120
+ const search = schemaEntry?.searchSchema ? schemaEntry.searchSchema.parse(rawSearch) : rawSearch;
121
+ const head = await definition.head({
122
+ request,
123
+ params,
124
+ search
125
+ });
126
+ return {
127
+ head,
128
+ staleTime: definition.staleTime
129
+ };
130
+ }
131
+ async function resolveMatchedHead(request, headTags, matches) {
132
+ const resolvedHeadByRoute = new Map;
133
+ for (const match of matches) {
134
+ const headOption = match.route.options.head;
135
+ if (typeof headOption !== "string") {
136
+ continue;
137
+ }
138
+ const result = await executeHeadTag(request, headTags, headOption, match.params, match.search);
139
+ resolvedHeadByRoute.set(match.route.fullPath, result.head);
140
+ }
141
+ return import_core.resolveHeadConfig(matches, resolvedHeadByRoute);
142
+ }
143
+ async function handleRequest(request, options) {
144
+ const url = new URL(request.url);
145
+ const headBasePath = options.headBasePath ?? "/head-api";
146
+ const routeBasePath = options.routeBasePath ?? "/";
147
+ if (url.pathname.startsWith(`${headBasePath}/`)) {
148
+ const headTagName = decodeURIComponent(url.pathname.slice(headBasePath.length + 1));
149
+ const params = JSON.parse(url.searchParams.get("params") ?? "{}");
150
+ const search = JSON.parse(url.searchParams.get("search") ?? "{}");
151
+ try {
152
+ const result = await executeHeadTag(request, options.headTags, headTagName, params, search);
153
+ return {
154
+ matched: true,
155
+ response: jsonResponse(result)
156
+ };
157
+ } catch (error) {
158
+ if (error instanceof Response) {
159
+ return {
160
+ matched: true,
161
+ response: error
162
+ };
163
+ }
164
+ if (import_core.isNotFound(error)) {
165
+ return {
166
+ matched: true,
167
+ response: jsonResponse({ message: "Not Found" }, { status: 404 })
168
+ };
169
+ }
170
+ throw error;
171
+ }
172
+ }
173
+ if (!url.pathname.startsWith(routeBasePath)) {
174
+ return {
175
+ matched: false,
176
+ response: new Response("Not Found", { status: 404 })
177
+ };
178
+ }
179
+ const location = import_core.createParsedLocation(`${url.pathname}${url.search}${url.hash}`, null, import_core.defaultParseSearch);
180
+ const matches = buildMatches(options.routeManifest, location);
181
+ if (matches.length === 0) {
182
+ return {
183
+ matched: false,
184
+ response: new Response("Not Found", { status: 404 })
185
+ };
186
+ }
187
+ try {
188
+ const head = await resolveMatchedHead(request, options.headTags, matches);
189
+ const headHtml = import_core.serializeHeadConfig(head, {
190
+ managedAttribute: MANAGED_HEAD_ATTRIBUTE
191
+ });
192
+ const richieRouterHead = `${headHtml}${createHeadSnapshotScript(location.href, head)}`;
193
+ const html = await renderTemplate(options.html, {
194
+ request,
195
+ richieRouterHead,
196
+ head
197
+ });
198
+ return {
199
+ matched: true,
200
+ response: new Response(html, {
201
+ status: 200,
202
+ headers: {
203
+ "content-type": "text/html; charset=utf-8"
204
+ }
205
+ })
206
+ };
207
+ } catch (error) {
208
+ if (import_core.isRedirect(error)) {
209
+ const redirectPath = import_core.buildPath(error.options.to, error.options.params ?? {});
210
+ const redirectSearch = import_core.defaultStringifySearch(error.options.search === true ? {} : error.options.search ?? {});
211
+ const redirectHash = error.options.hash ? `#${error.options.hash.replace(/^#/, "")}` : "";
212
+ const redirectUrl = `${redirectPath}${redirectSearch}${redirectHash}`;
213
+ return {
214
+ matched: true,
215
+ response: new Response(null, {
216
+ status: error.options.replace ? 307 : 302,
217
+ headers: {
218
+ location: redirectUrl
219
+ }
220
+ })
221
+ };
222
+ }
223
+ if (error instanceof Response) {
224
+ return {
225
+ matched: true,
226
+ response: error
227
+ };
228
+ }
229
+ if (import_core.isNotFound(error)) {
230
+ return {
231
+ matched: true,
232
+ response: new Response("Not Found", { status: 404 })
233
+ };
234
+ }
235
+ throw error;
236
+ }
237
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,207 @@
1
+ // packages/server/src/index.ts
2
+ import {
3
+ buildPath,
4
+ createParsedLocation,
5
+ defaultParseSearch,
6
+ defaultStringifySearch,
7
+ isNotFound,
8
+ isRedirect,
9
+ matchRouteTree,
10
+ resolveHeadConfig,
11
+ serializeHeadConfig
12
+ } from "@richie-router/core";
13
+ function defineHeadTags(routeManifest, headTagSchema, definitions) {
14
+ return {
15
+ routeManifest,
16
+ headTagSchema,
17
+ definitions
18
+ };
19
+ }
20
+ var HEAD_PLACEHOLDER = "<!--richie-router-head-->";
21
+ var MANAGED_HEAD_ATTRIBUTE = "data-richie-router-head";
22
+ function routeHasRecord(value) {
23
+ return typeof value === "object" && value !== null;
24
+ }
25
+ function createHeadSnapshotScript(href, head) {
26
+ const payload = JSON.stringify({ href, head }).replaceAll("</script>", "<\\/script>");
27
+ return `<script ${MANAGED_HEAD_ATTRIBUTE}="true">window.__RICHIE_ROUTER_HEAD__=${payload}</script>`;
28
+ }
29
+ async function renderTemplate(html, ctx) {
30
+ const template = html.template;
31
+ if (typeof template === "function") {
32
+ return await template(ctx);
33
+ }
34
+ if (!template.includes(HEAD_PLACEHOLDER)) {
35
+ throw new Error(`HTML template is missing required Richie Router placeholder: ${HEAD_PLACEHOLDER}`);
36
+ }
37
+ return template.replace(HEAD_PLACEHOLDER, ctx.richieRouterHead);
38
+ }
39
+ function jsonResponse(data, init) {
40
+ return new Response(JSON.stringify(data), {
41
+ ...init,
42
+ headers: {
43
+ "content-type": "application/json; charset=utf-8",
44
+ ...init?.headers ?? {}
45
+ }
46
+ });
47
+ }
48
+ function resolveSearch(route, rawSearch) {
49
+ const fromSchema = route.searchSchema ? route.searchSchema.parse(rawSearch) : {};
50
+ if (routeHasRecord(fromSchema)) {
51
+ return fromSchema;
52
+ }
53
+ return rawSearch;
54
+ }
55
+ function buildMatches(routeManifest, location) {
56
+ const matched = matchRouteTree(routeManifest, location.pathname);
57
+ if (!matched) {
58
+ return [];
59
+ }
60
+ const rawSearch = location.search;
61
+ let accumulatedSearch = { ...rawSearch };
62
+ return matched.map(({ route, params }) => {
63
+ const nextSearch = resolveSearch(route, rawSearch);
64
+ if (routeHasRecord(nextSearch)) {
65
+ accumulatedSearch = {
66
+ ...accumulatedSearch,
67
+ ...nextSearch
68
+ };
69
+ }
70
+ return {
71
+ id: route.fullPath,
72
+ pathname: location.pathname,
73
+ params,
74
+ route,
75
+ search: accumulatedSearch,
76
+ to: route.to
77
+ };
78
+ });
79
+ }
80
+ async function executeHeadTag(request, headTags, headTagName, params, rawSearch) {
81
+ const definition = headTags.definitions[headTagName];
82
+ const schemaEntry = headTags.headTagSchema[headTagName];
83
+ if (!definition) {
84
+ throw new Error(`Unknown head tag "${headTagName}".`);
85
+ }
86
+ const search = schemaEntry?.searchSchema ? schemaEntry.searchSchema.parse(rawSearch) : rawSearch;
87
+ const head = await definition.head({
88
+ request,
89
+ params,
90
+ search
91
+ });
92
+ return {
93
+ head,
94
+ staleTime: definition.staleTime
95
+ };
96
+ }
97
+ async function resolveMatchedHead(request, headTags, matches) {
98
+ const resolvedHeadByRoute = new Map;
99
+ for (const match of matches) {
100
+ const headOption = match.route.options.head;
101
+ if (typeof headOption !== "string") {
102
+ continue;
103
+ }
104
+ const result = await executeHeadTag(request, headTags, headOption, match.params, match.search);
105
+ resolvedHeadByRoute.set(match.route.fullPath, result.head);
106
+ }
107
+ return resolveHeadConfig(matches, resolvedHeadByRoute);
108
+ }
109
+ async function handleRequest(request, options) {
110
+ const url = new URL(request.url);
111
+ const headBasePath = options.headBasePath ?? "/head-api";
112
+ const routeBasePath = options.routeBasePath ?? "/";
113
+ if (url.pathname.startsWith(`${headBasePath}/`)) {
114
+ const headTagName = decodeURIComponent(url.pathname.slice(headBasePath.length + 1));
115
+ const params = JSON.parse(url.searchParams.get("params") ?? "{}");
116
+ const search = JSON.parse(url.searchParams.get("search") ?? "{}");
117
+ try {
118
+ const result = await executeHeadTag(request, options.headTags, headTagName, params, search);
119
+ return {
120
+ matched: true,
121
+ response: jsonResponse(result)
122
+ };
123
+ } catch (error) {
124
+ if (error instanceof Response) {
125
+ return {
126
+ matched: true,
127
+ response: error
128
+ };
129
+ }
130
+ if (isNotFound(error)) {
131
+ return {
132
+ matched: true,
133
+ response: jsonResponse({ message: "Not Found" }, { status: 404 })
134
+ };
135
+ }
136
+ throw error;
137
+ }
138
+ }
139
+ if (!url.pathname.startsWith(routeBasePath)) {
140
+ return {
141
+ matched: false,
142
+ response: new Response("Not Found", { status: 404 })
143
+ };
144
+ }
145
+ const location = createParsedLocation(`${url.pathname}${url.search}${url.hash}`, null, defaultParseSearch);
146
+ const matches = buildMatches(options.routeManifest, location);
147
+ if (matches.length === 0) {
148
+ return {
149
+ matched: false,
150
+ response: new Response("Not Found", { status: 404 })
151
+ };
152
+ }
153
+ try {
154
+ const head = await resolveMatchedHead(request, options.headTags, matches);
155
+ const headHtml = serializeHeadConfig(head, {
156
+ managedAttribute: MANAGED_HEAD_ATTRIBUTE
157
+ });
158
+ const richieRouterHead = `${headHtml}${createHeadSnapshotScript(location.href, head)}`;
159
+ const html = await renderTemplate(options.html, {
160
+ request,
161
+ richieRouterHead,
162
+ head
163
+ });
164
+ return {
165
+ matched: true,
166
+ response: new Response(html, {
167
+ status: 200,
168
+ headers: {
169
+ "content-type": "text/html; charset=utf-8"
170
+ }
171
+ })
172
+ };
173
+ } catch (error) {
174
+ if (isRedirect(error)) {
175
+ const redirectPath = buildPath(error.options.to, error.options.params ?? {});
176
+ const redirectSearch = defaultStringifySearch(error.options.search === true ? {} : error.options.search ?? {});
177
+ const redirectHash = error.options.hash ? `#${error.options.hash.replace(/^#/, "")}` : "";
178
+ const redirectUrl = `${redirectPath}${redirectSearch}${redirectHash}`;
179
+ return {
180
+ matched: true,
181
+ response: new Response(null, {
182
+ status: error.options.replace ? 307 : 302,
183
+ headers: {
184
+ location: redirectUrl
185
+ }
186
+ })
187
+ };
188
+ }
189
+ if (error instanceof Response) {
190
+ return {
191
+ matched: true,
192
+ response: error
193
+ };
194
+ }
195
+ if (isNotFound(error)) {
196
+ return {
197
+ matched: true,
198
+ response: new Response("Not Found", { status: 404 })
199
+ };
200
+ }
201
+ throw error;
202
+ }
203
+ }
204
+ export {
205
+ handleRequest,
206
+ defineHeadTags
207
+ };
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,39 @@
1
+ import { type AnyRoute, type HeadConfig, type HeadTagSchemaShape, type InferHeadTagSearchSchema } from '@richie-router/core';
2
+ export interface HeadTagContext<TSearch> {
3
+ request: Request;
4
+ params: Record<string, string>;
5
+ search: TSearch;
6
+ }
7
+ export interface HeadTagDefinition<TSearch> {
8
+ staleTime?: number;
9
+ head: (ctx: HeadTagContext<TSearch>) => Promise<HeadConfig> | HeadConfig;
10
+ }
11
+ export interface DefinedHeadTags<TRouteManifest extends AnyRoute, THeadTagSchema extends HeadTagSchemaShape, TDefinitions extends Partial<{
12
+ [THeadTagName in keyof THeadTagSchema]: HeadTagDefinition<InferHeadTagSearchSchema<THeadTagSchema, THeadTagName>>;
13
+ }>> {
14
+ routeManifest: TRouteManifest;
15
+ headTagSchema: THeadTagSchema;
16
+ definitions: TDefinitions;
17
+ }
18
+ export declare function defineHeadTags<TRouteManifest extends AnyRoute, THeadTagSchema extends HeadTagSchemaShape, TDefinitions extends Partial<{
19
+ [THeadTagName in keyof THeadTagSchema]: HeadTagDefinition<InferHeadTagSearchSchema<THeadTagSchema, THeadTagName>>;
20
+ }>>(routeManifest: TRouteManifest, headTagSchema: THeadTagSchema, definitions: TDefinitions): DefinedHeadTags<TRouteManifest, THeadTagSchema, TDefinitions>;
21
+ export interface HtmlOptions {
22
+ template: string | ((ctx: {
23
+ request: Request;
24
+ richieRouterHead: string;
25
+ head: HeadConfig;
26
+ }) => string | Promise<string>);
27
+ }
28
+ export interface HandleRequestOptions<TRouteManifest extends AnyRoute, THeadTagSchema extends HeadTagSchemaShape, TDefinitions extends Partial<Record<keyof THeadTagSchema, HeadTagDefinition<any>>>> {
29
+ routeManifest: TRouteManifest;
30
+ headTags: DefinedHeadTags<TRouteManifest, THeadTagSchema, TDefinitions>;
31
+ html: HtmlOptions;
32
+ headBasePath?: string;
33
+ routeBasePath?: string;
34
+ }
35
+ export interface HandleRequestResult {
36
+ matched: boolean;
37
+ response: Response;
38
+ }
39
+ export declare function handleRequest<TRouteManifest extends AnyRoute, THeadTagSchema extends HeadTagSchemaShape, TDefinitions extends Partial<Record<keyof THeadTagSchema, HeadTagDefinition<any>>>>(request: Request, options: HandleRequestOptions<TRouteManifest, THeadTagSchema, TDefinitions>): Promise<HandleRequestResult>;
package/package.json CHANGED
@@ -1,10 +1,46 @@
1
1
  {
2
2
  "name": "@richie-router/server",
3
- "version": "0.0.1",
4
- "description": "OIDC trusted publishing setup package for @richie-router/server",
3
+ "version": "0.1.1",
4
+ "description": "Server helpers for Richie Router head tags and document handling",
5
+ "sideEffects": false,
6
+ "exports": {
7
+ "./package.json": "./package.json",
8
+ ".": {
9
+ "types": "./dist/types/index.d.ts",
10
+ "import": "./dist/esm/index.mjs",
11
+ "require": "./dist/cjs/index.cjs",
12
+ "default": "./dist/esm/index.mjs"
13
+ }
14
+ },
15
+ "dependencies": {
16
+ "@richie-router/core": "^0.1.1"
17
+ },
18
+ "author": "Richie <oss@ricsam.dev>",
19
+ "homepage": "https://docs.ricsam.dev/richie-router",
20
+ "bugs": {
21
+ "url": "https://github.com/ricsam/richie-router/issues"
22
+ },
5
23
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
24
+ "router",
25
+ "react",
26
+ "typescript",
27
+ "bun",
28
+ "file-based-routing",
29
+ "type-safe"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/ricsam/richie-router.git",
34
+ "directory": "packages/server"
35
+ },
36
+ "main": "./dist/cjs/index.cjs",
37
+ "module": "./dist/esm/index.mjs",
38
+ "types": "./dist/types/index.d.ts",
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "provenance": true
45
+ }
46
+ }
package/README.md DELETED
@@ -1,45 +0,0 @@
1
- # @richie-router/server
2
-
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
4
-
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
-
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@richie-router/server`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**