@ng-desktop/server 0.0.0-stage → 0.5.0

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) 2026 Gaspar1992 and NgDesktop Engine Contributors
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 CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # `@ng-desktop/server`
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
+ Embedded Analog/Nitro-style local server router and event handlers running in-process inside `ng-desktop-engine` (`server_worker`), with direct access to host SQLite, XDG filesystem, multithreaded compute, and OS HTTP/2 bridges.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @ng-desktop/server
9
+ ```
10
+
11
+ Peer dependencies: `@angular/core >= 22.0.0`, `@ng-desktop/platform`.
12
+
13
+ ## Quick Usage
14
+
15
+ Create file-based routes under `src/server/routes/` (for example `src/server/routes/api/notes/[id].put.ts`):
16
+
17
+ ```ts
18
+ import {
19
+ createError,
20
+ defineNativeEventHandler,
21
+ getRouterParam,
22
+ readBody,
23
+ } from '@ng-desktop/server';
24
+
25
+ export default defineNativeEventHandler((event) => {
26
+ const id = Number(getRouterParam(event, 'id'));
27
+ if (!Number.isInteger(id) || id < 1) {
28
+ throw createError({ statusCode: 400, message: 'Invalid note ID' });
29
+ }
30
+
31
+ const body = readBody<{ note?: string }>(event);
32
+ event.context.db.execute('INSERT OR REPLACE INTO notes (id, note) VALUES (?, ?);', [
33
+ id,
34
+ String(body.note ?? ''),
35
+ ]);
36
+ return { saved: true, id };
37
+ });
38
+ ```
39
+
40
+ ## Key Exports
41
+
42
+ - **Handlers & Request Helpers:** `defineNativeEventHandler`, `createError`, `readBody`, `getQuery`, `getRouterParam`, `setResponseStatus`, `setResponseHeader`, `NativeServerHttpError`
43
+ - **Router & Host Bridge:** `createNativeServerRouter`, `registerNativeServerApp`, `createHostServerContext`
44
+
45
+ ## Documentation
46
+
47
+ - [Getting Started with External Angular 22+ & Nx Apps](../../docs/GETTING_STARTED.md)
48
+ - [Ecosystem Compatibility Guide](../../docs/ECOSYSTEM_COMPATIBILITY.md)
49
+ - [Architectural Roadmap & OS Maturity Matrix](../../ROADMAP.md)
@@ -0,0 +1,98 @@
1
+ export type NativeServerMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | '*';
2
+ export type NativeServerXdgKind = 'config' | 'data' | 'cache';
3
+ export interface NativeServerComputeMatch {
4
+ index: number;
5
+ score: number;
6
+ value: string;
7
+ }
8
+ export interface NativeServerHttpRequestOptions {
9
+ headers?: Record<string, string>;
10
+ callKind?: string;
11
+ }
12
+ export interface NativeServerHttpResponse {
13
+ status: number;
14
+ statusText: string;
15
+ body: string;
16
+ headers: Record<string, string>;
17
+ cached?: boolean;
18
+ }
19
+ export type NativeServerSqlParam = string | number | boolean | null;
20
+ export interface NativeServerDbContext {
21
+ open(path: string): string;
22
+ execute(sql: string, params?: readonly NativeServerSqlParam[]): boolean;
23
+ query<T extends Record<string, unknown> = Record<string, unknown>>(sql: string, params?: readonly NativeServerSqlParam[]): T[];
24
+ }
25
+ export interface NativeServerFsContext {
26
+ resolvePath(kind: NativeServerXdgKind, relPath: string): string;
27
+ readText(path: string): string | null;
28
+ writeText(path: string, content: string): boolean;
29
+ watchFile(path: string): boolean;
30
+ pollChangedFiles(): string[];
31
+ }
32
+ export interface NativeServerComputeContext {
33
+ fuzzyFilter(items: readonly string[], query: string, limit?: number): NativeServerComputeMatch[];
34
+ hash(input: string): string;
35
+ }
36
+ export interface NativeServerHttpContext {
37
+ request(method: string, url: string, body?: unknown, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse>;
38
+ get(url: string, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse>;
39
+ post(url: string, body?: unknown, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse>;
40
+ }
41
+ export interface NativeServerContext {
42
+ params: Record<string, string>;
43
+ query: Record<string, string>;
44
+ db: NativeServerDbContext;
45
+ fs: NativeServerFsContext;
46
+ compute: NativeServerComputeContext;
47
+ http: NativeServerHttpContext;
48
+ }
49
+ export interface NativeServerRequest {
50
+ method: string;
51
+ url: string;
52
+ headers?: Record<string, string>;
53
+ body?: string | null;
54
+ }
55
+ export interface NativeServerResponse {
56
+ status: number;
57
+ statusText: string;
58
+ headers: Record<string, string>;
59
+ body: string;
60
+ }
61
+ export interface NativeServerEvent {
62
+ readonly method: string;
63
+ readonly url: string;
64
+ readonly path: string;
65
+ readonly headers: Record<string, string>;
66
+ readonly body: string | null;
67
+ readonly context: NativeServerContext;
68
+ readonly response: {
69
+ status: number;
70
+ statusText?: string;
71
+ headers: Record<string, string>;
72
+ };
73
+ }
74
+ export type NativeEventHandler<T = unknown> = (event: NativeServerEvent) => T | Promise<T>;
75
+ export declare class NativeServerHttpError extends Error {
76
+ readonly statusCode: number;
77
+ readonly statusMessage: string;
78
+ readonly data?: unknown;
79
+ constructor(options: {
80
+ statusCode: number;
81
+ statusMessage?: string;
82
+ message?: string;
83
+ data?: unknown;
84
+ });
85
+ }
86
+ export declare function defaultStatusText(status: number): string;
87
+ export declare function defineNativeEventHandler<T = unknown>(handler: NativeEventHandler<T>): NativeEventHandler<T>;
88
+ export declare function getRouterParam(event: NativeServerEvent, name: string): string | undefined;
89
+ export declare function getQuery(event: NativeServerEvent): Record<string, string>;
90
+ export declare function readBody<T = unknown>(event: NativeServerEvent): T;
91
+ export declare function setResponseStatus(event: NativeServerEvent, code: number, statusText?: string): void;
92
+ export declare function setResponseHeader(event: NativeServerEvent, name: string, value: string): void;
93
+ export declare function createError(input: {
94
+ statusCode?: number;
95
+ statusMessage?: string;
96
+ message?: string;
97
+ data?: unknown;
98
+ }): NativeServerHttpError;
@@ -0,0 +1,87 @@
1
+ export class NativeServerHttpError extends Error {
2
+ statusCode;
3
+ statusMessage;
4
+ data;
5
+ constructor(options) {
6
+ const statusMessage = options.statusMessage ?? defaultStatusText(options.statusCode);
7
+ super(options.message ?? statusMessage);
8
+ this.name = 'NativeServerHttpError';
9
+ this.statusCode = options.statusCode;
10
+ this.statusMessage = statusMessage;
11
+ this.data = options.data;
12
+ }
13
+ }
14
+ export function defaultStatusText(status) {
15
+ switch (status) {
16
+ case 200:
17
+ return 'OK';
18
+ case 201:
19
+ return 'Created';
20
+ case 204:
21
+ return 'No Content';
22
+ case 400:
23
+ return 'Bad Request';
24
+ case 401:
25
+ return 'Unauthorized';
26
+ case 403:
27
+ return 'Forbidden';
28
+ case 404:
29
+ return 'Not Found';
30
+ case 405:
31
+ return 'Method Not Allowed';
32
+ case 409:
33
+ return 'Conflict';
34
+ case 500:
35
+ return 'Internal Server Error';
36
+ default:
37
+ return status >= 400 ? 'Error' : 'OK';
38
+ }
39
+ }
40
+ export function defineNativeEventHandler(handler) {
41
+ return handler;
42
+ }
43
+ export function getRouterParam(event, name) {
44
+ return event.context.params[name];
45
+ }
46
+ export function getQuery(event) {
47
+ return { ...event.context.query };
48
+ }
49
+ export function readBody(event) {
50
+ const raw = event.body;
51
+ if (raw === null || raw === undefined || raw.length === 0) {
52
+ return undefined;
53
+ }
54
+ const trimmed = raw.trim();
55
+ if (trimmed.startsWith('{') ||
56
+ trimmed.startsWith('[') ||
57
+ trimmed.startsWith('"') ||
58
+ trimmed === 'true' ||
59
+ trimmed === 'false' ||
60
+ trimmed === 'null' ||
61
+ /^-?\d+(?:\.\d+)?$/.test(trimmed)) {
62
+ try {
63
+ return JSON.parse(raw);
64
+ }
65
+ catch {
66
+ return raw;
67
+ }
68
+ }
69
+ return raw;
70
+ }
71
+ export function setResponseStatus(event, code, statusText) {
72
+ event.response.status = code;
73
+ if (statusText !== undefined) {
74
+ event.response.statusText = statusText;
75
+ }
76
+ }
77
+ export function setResponseHeader(event, name, value) {
78
+ event.response.headers[name.toLowerCase()] = value;
79
+ }
80
+ export function createError(input) {
81
+ return new NativeServerHttpError({
82
+ statusCode: input.statusCode ?? 500,
83
+ statusMessage: input.statusMessage,
84
+ message: input.message,
85
+ data: input.data,
86
+ });
87
+ }
@@ -0,0 +1,2 @@
1
+ export { createError, defaultStatusText, defineNativeEventHandler, getQuery, getRouterParam, NativeServerHttpError, readBody, setResponseHeader, setResponseStatus, type NativeEventHandler, type NativeServerComputeContext, type NativeServerComputeMatch, type NativeServerContext, type NativeServerDbContext, type NativeServerEvent, type NativeServerFsContext, type NativeServerHttpContext, type NativeServerHttpRequestOptions, type NativeServerHttpResponse, type NativeServerMethod, type NativeServerRequest, type NativeServerResponse, type NativeServerSqlParam, type NativeServerXdgKind, } from './event';
2
+ export { createHostServerContext, createNativeServerRouter, registerNativeServerApp, type NativeServerHostBridge, type NativeServerRouteDefinition, type NativeServerRouter, } from './router';
@@ -0,0 +1,2 @@
1
+ export { createError, defaultStatusText, defineNativeEventHandler, getQuery, getRouterParam, NativeServerHttpError, readBody, setResponseHeader, setResponseStatus, } from './event.js';
2
+ export { createHostServerContext, createNativeServerRouter, registerNativeServerApp, } from './router.js';
@@ -0,0 +1,30 @@
1
+ import { NativeEventHandler, NativeServerComputeMatch, NativeServerContext, NativeServerHttpRequestOptions, NativeServerHttpResponse, NativeServerMethod, NativeServerRequest, NativeServerResponse, NativeServerSqlParam, NativeServerXdgKind } from './event';
2
+ export interface NativeServerRouteDefinition {
3
+ method: NativeServerMethod;
4
+ pattern: string;
5
+ handler: NativeEventHandler;
6
+ }
7
+ export interface NativeServerRouter {
8
+ handle(request: NativeServerRequest): Promise<NativeServerResponse>;
9
+ getRoutes(): readonly NativeServerRouteDefinition[];
10
+ }
11
+ export interface NativeServerHostBridge {
12
+ sqliteOpen?(path: string): string;
13
+ sqliteExecute(sql: string, params?: readonly NativeServerSqlParam[]): boolean;
14
+ sqliteQuery(sql: string, params?: readonly NativeServerSqlParam[]): Array<Record<string, unknown>>;
15
+ fsResolvePath(kind: NativeServerXdgKind, relPath: string): string;
16
+ fsReadText(path: string): string | null;
17
+ fsWriteText(path: string, content: string): boolean;
18
+ fsWatchFile(path: string): boolean;
19
+ fsPollChangedFiles(): string[];
20
+ computeFuzzyFilter(items: readonly string[], query: string, limit?: number): NativeServerComputeMatch[];
21
+ computeHash(input: string): string;
22
+ httpRequest(method: string, url: string, body?: string, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse> | NativeServerHttpResponse;
23
+ }
24
+ declare global {
25
+ var __NG_NATIVE_SERVER_HOST__: NativeServerHostBridge | undefined;
26
+ var __NG_NATIVE_SERVER_ROUTER__: NativeServerRouter | undefined;
27
+ }
28
+ export declare function createHostServerContext(): Omit<NativeServerContext, 'params' | 'query'>;
29
+ export declare function createNativeServerRouter(routes: readonly NativeServerRouteDefinition[], contextFactory?: () => Omit<NativeServerContext, 'params' | 'query'>): NativeServerRouter;
30
+ export declare function registerNativeServerApp(routes: readonly NativeServerRouteDefinition[]): NativeServerRouter;
@@ -0,0 +1,321 @@
1
+ import { defaultStatusText, NativeServerHttpError, } from './event.js';
2
+ function parseUrlParts(rawUrl) {
3
+ const withoutOrigin = rawUrl.trim().replace(/^(?:https?:\/\/localhost|local:\/?)/i, '');
4
+ const hashIdx = withoutOrigin.indexOf('#');
5
+ const cleanUrl = hashIdx === -1 ? withoutOrigin : withoutOrigin.slice(0, hashIdx);
6
+ const qIdx = cleanUrl.indexOf('?');
7
+ const rawPath = qIdx === -1 ? cleanUrl : cleanUrl.slice(0, qIdx);
8
+ const rawQuery = qIdx === -1 ? '' : cleanUrl.slice(qIdx + 1);
9
+ let normalizedPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
10
+ if (normalizedPath.length > 1) {
11
+ normalizedPath = normalizedPath.replace(/\/+$/, '');
12
+ }
13
+ const query = {};
14
+ if (rawQuery.length > 0) {
15
+ for (const pair of rawQuery.split('&')) {
16
+ if (!pair)
17
+ continue;
18
+ const eq = pair.indexOf('=');
19
+ const rawKey = eq === -1 ? pair : pair.slice(0, eq);
20
+ const rawVal = eq === -1 ? '' : pair.slice(eq + 1);
21
+ const key = decodeURIComponent(rawKey.replaceAll('+', ' '));
22
+ const val = decodeURIComponent(rawVal.replaceAll('+', ' '));
23
+ query[key] = val;
24
+ }
25
+ }
26
+ return { path: normalizedPath, query };
27
+ }
28
+ function splitSegments(path) {
29
+ return path.split('/').filter((seg) => seg.length > 0);
30
+ }
31
+ function matchPattern(pattern, path) {
32
+ const cleanPattern = pattern.startsWith('/') ? pattern : `/${pattern}`;
33
+ const patSegs = splitSegments(cleanPattern);
34
+ const pathSegs = splitSegments(path);
35
+ const params = {};
36
+ const weights = [];
37
+ for (let i = 0; i < patSegs.length; i++) {
38
+ const seg = patSegs[i];
39
+ if (seg.startsWith('*')) {
40
+ const paramName = seg.slice(1).trim() || 'slug';
41
+ params[paramName] = pathSegs.slice(i).map(decodeURIComponent).join('/');
42
+ weights.push(1);
43
+ return { params, weights };
44
+ }
45
+ if (i >= pathSegs.length) {
46
+ return null;
47
+ }
48
+ if (seg.startsWith(':')) {
49
+ const paramName = seg.slice(1).trim();
50
+ params[paramName] = decodeURIComponent(pathSegs[i]);
51
+ weights.push(2);
52
+ continue;
53
+ }
54
+ if (seg !== pathSegs[i]) {
55
+ return null;
56
+ }
57
+ weights.push(3);
58
+ }
59
+ if (patSegs.length !== pathSegs.length) {
60
+ return null;
61
+ }
62
+ return { params, weights };
63
+ }
64
+ function compareMatchPrecedence(a, b) {
65
+ const len = Math.max(a.weights.length, b.weights.length);
66
+ for (let i = 0; i < len; i++) {
67
+ const wa = a.weights[i] ?? 0;
68
+ const wb = b.weights[i] ?? 0;
69
+ if (wa !== wb) {
70
+ return wb - wa;
71
+ }
72
+ }
73
+ if (a.isExactMethod !== b.isExactMethod) {
74
+ return a.isExactMethod ? -1 : 1;
75
+ }
76
+ return 0;
77
+ }
78
+ function createFallbackHostBridge() {
79
+ const files = new Map();
80
+ const watched = new Set();
81
+ const changed = new Set();
82
+ const fallbackCompute = (items, query, limit = 50) => {
83
+ const needle = query.trim().toLowerCase();
84
+ const out = [];
85
+ for (let index = 0; index < items.length; index++) {
86
+ const value = items[index];
87
+ const lower = value.toLowerCase();
88
+ let score = null;
89
+ if (!needle)
90
+ score = 1;
91
+ else if (lower === needle)
92
+ score = 1000;
93
+ else if (lower.startsWith(needle))
94
+ score = 600 + Math.max(0, 80 - value.length);
95
+ else if (lower.includes(needle))
96
+ score = 350 + Math.max(0, 60 - lower.indexOf(needle) * 2);
97
+ if (score !== null)
98
+ out.push({ index, score, value });
99
+ }
100
+ out.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.index - b.index));
101
+ return out.slice(0, limit);
102
+ };
103
+ return {
104
+ sqliteOpen: (path) => path || ':memory:',
105
+ sqliteExecute: () => true,
106
+ sqliteQuery: () => [],
107
+ fsResolvePath: (kind, relPath) => `/tmp/ng-desktop-server/${kind}/${relPath.replace(/^[/\\]+/, '')}`,
108
+ fsReadText: (path) => files.get(path) ?? null,
109
+ fsWriteText: (path, content) => {
110
+ files.set(path, content);
111
+ if (watched.has(path))
112
+ changed.add(path);
113
+ return true;
114
+ },
115
+ fsWatchFile: (path) => {
116
+ watched.add(path);
117
+ return true;
118
+ },
119
+ fsPollChangedFiles: () => {
120
+ const out = [...changed];
121
+ changed.clear();
122
+ return out;
123
+ },
124
+ computeFuzzyFilter: fallbackCompute,
125
+ computeHash: (input) => {
126
+ let hash = 2166136261;
127
+ for (let i = 0; i < input.length; i++) {
128
+ hash = Math.imul(hash ^ input.charCodeAt(i), 16777619) >>> 0;
129
+ }
130
+ return hash.toString(16).padStart(8, '0');
131
+ },
132
+ httpRequest: () => ({
133
+ status: 501,
134
+ statusText: 'Not Implemented',
135
+ body: '{"error":"No native HTTP bridge configured"}',
136
+ headers: {},
137
+ }),
138
+ };
139
+ }
140
+ export function createHostServerContext() {
141
+ let fallbackBridge;
142
+ const getHost = () => {
143
+ if (globalThis.__NG_NATIVE_SERVER_HOST__) {
144
+ return globalThis.__NG_NATIVE_SERVER_HOST__;
145
+ }
146
+ fallbackBridge ??= createFallbackHostBridge();
147
+ return fallbackBridge;
148
+ };
149
+ const serializeHttpBody = (body) => {
150
+ if (body === undefined || body === null)
151
+ return undefined;
152
+ return typeof body === 'string' ? body : JSON.stringify(body);
153
+ };
154
+ return {
155
+ db: {
156
+ open: (path) => {
157
+ const host = getHost();
158
+ return host.sqliteOpen ? host.sqliteOpen(path) : path;
159
+ },
160
+ execute: (sql, params) => getHost().sqliteExecute(sql, params),
161
+ query: (sql, params) => getHost().sqliteQuery(sql, params),
162
+ },
163
+ fs: {
164
+ resolvePath: (kind, relPath) => getHost().fsResolvePath(kind, relPath),
165
+ readText: (path) => getHost().fsReadText(path),
166
+ writeText: (path, content) => getHost().fsWriteText(path, content),
167
+ watchFile: (path) => getHost().fsWatchFile(path),
168
+ pollChangedFiles: () => getHost().fsPollChangedFiles(),
169
+ },
170
+ compute: {
171
+ fuzzyFilter: (items, query, limit) => getHost().computeFuzzyFilter(items, query, limit),
172
+ hash: (input) => getHost().computeHash(input),
173
+ },
174
+ http: {
175
+ request: async (method, url, body, options) => {
176
+ const res = await getHost().httpRequest(method, url, serializeHttpBody(body), options);
177
+ return {
178
+ status: res.status,
179
+ statusText: res.statusText,
180
+ body: res.body,
181
+ headers: res.headers ?? {},
182
+ ...(res.cached !== undefined ? { cached: res.cached } : {}),
183
+ };
184
+ },
185
+ get: (url, options) => Promise.resolve(getHost().httpRequest('GET', url, undefined, options)).then((res) => ({
186
+ status: res.status,
187
+ statusText: res.statusText,
188
+ body: res.body,
189
+ headers: res.headers ?? {},
190
+ ...(res.cached !== undefined ? { cached: res.cached } : {}),
191
+ })),
192
+ post: (url, body, options) => Promise.resolve(getHost().httpRequest('POST', url, serializeHttpBody(body), options)).then((res) => ({
193
+ status: res.status,
194
+ statusText: res.statusText,
195
+ body: res.body,
196
+ headers: res.headers ?? {},
197
+ ...(res.cached !== undefined ? { cached: res.cached } : {}),
198
+ })),
199
+ },
200
+ };
201
+ }
202
+ function normalizeHeaders(headers) {
203
+ const normalized = {};
204
+ if (!headers)
205
+ return normalized;
206
+ for (const [k, v] of Object.entries(headers)) {
207
+ normalized[k.toLowerCase()] = String(v);
208
+ }
209
+ return normalized;
210
+ }
211
+ function serializeResult(result, event) {
212
+ const status = event.response.status;
213
+ const statusText = event.response.statusText ?? defaultStatusText(status);
214
+ const headers = { ...event.response.headers };
215
+ if (typeof result === 'string') {
216
+ headers['content-type'] ??= 'text/plain; charset=utf-8';
217
+ return { status, statusText, headers, body: result };
218
+ }
219
+ if (result === undefined) {
220
+ headers['content-type'] ??= 'application/json; charset=utf-8';
221
+ return { status, statusText, headers, body: '' };
222
+ }
223
+ headers['content-type'] ??= 'application/json; charset=utf-8';
224
+ return { status, statusText, headers, body: JSON.stringify(result) };
225
+ }
226
+ export function createNativeServerRouter(routes, contextFactory = createHostServerContext) {
227
+ const routeList = [...routes];
228
+ return {
229
+ getRoutes: () => routeList,
230
+ async handle(request) {
231
+ const method = String(request.method || 'GET')
232
+ .trim()
233
+ .toUpperCase();
234
+ const { path, query } = parseUrlParts(request.url);
235
+ const pathMatches = [];
236
+ for (const route of routeList) {
237
+ const matched = matchPattern(route.pattern, path);
238
+ if (!matched)
239
+ continue;
240
+ pathMatches.push({
241
+ route,
242
+ params: matched.params,
243
+ weights: matched.weights,
244
+ isExactMethod: route.method.toUpperCase() === method,
245
+ });
246
+ }
247
+ if (pathMatches.length === 0) {
248
+ return {
249
+ status: 404,
250
+ statusText: 'Not Found',
251
+ headers: { 'content-type': 'application/json; charset=utf-8' },
252
+ body: JSON.stringify({ error: `Route not found: ${path}`, statusCode: 404 }),
253
+ };
254
+ }
255
+ const methodMatches = pathMatches.filter((m) => m.isExactMethod || m.route.method === '*');
256
+ if (methodMatches.length === 0) {
257
+ return {
258
+ status: 405,
259
+ statusText: 'Method Not Allowed',
260
+ headers: { 'content-type': 'application/json; charset=utf-8' },
261
+ body: JSON.stringify({
262
+ error: `Method ${method} not allowed for ${path}`,
263
+ statusCode: 405,
264
+ }),
265
+ };
266
+ }
267
+ methodMatches.sort(compareMatchPrecedence);
268
+ const selected = methodMatches[0];
269
+ const baseCtx = contextFactory();
270
+ const event = {
271
+ method,
272
+ url: request.url,
273
+ path,
274
+ headers: normalizeHeaders(request.headers),
275
+ body: request.body ?? null,
276
+ context: {
277
+ ...baseCtx,
278
+ params: selected.params,
279
+ query,
280
+ },
281
+ response: {
282
+ status: 200,
283
+ headers: {},
284
+ },
285
+ };
286
+ try {
287
+ const result = await selected.route.handler(event);
288
+ return serializeResult(result, event);
289
+ }
290
+ catch (err) {
291
+ if (err instanceof NativeServerHttpError) {
292
+ return {
293
+ status: err.statusCode,
294
+ statusText: err.statusMessage,
295
+ headers: {
296
+ ...event.response.headers,
297
+ 'content-type': 'application/json; charset=utf-8',
298
+ },
299
+ body: JSON.stringify({
300
+ error: err.message,
301
+ statusCode: err.statusCode,
302
+ ...(err.data !== undefined ? { data: err.data } : {}),
303
+ }),
304
+ };
305
+ }
306
+ const message = err instanceof Error ? err.message : String(err);
307
+ return {
308
+ status: 500,
309
+ statusText: 'Internal Server Error',
310
+ headers: { 'content-type': 'application/json; charset=utf-8' },
311
+ body: JSON.stringify({ error: message, statusCode: 500 }),
312
+ };
313
+ }
314
+ },
315
+ };
316
+ }
317
+ export function registerNativeServerApp(routes) {
318
+ const router = createNativeServerRouter(routes, createHostServerContext);
319
+ globalThis.__NG_NATIVE_SERVER_ROUTER__ = router;
320
+ return router;
321
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@ng-desktop/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "Isolated local AnalogJS-style backend router and host context (SQLite, XDG FS, Compute, HTTP) for NgDesktop",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "angular",
8
+ "angular22",
9
+ "desktop",
10
+ "native",
11
+ "gtk4",
12
+ "winui3",
13
+ "appkit",
14
+ "rust"
15
+ ],
16
+ "homepage": "https://github.com/Gaspar1992/ng-desktop-engine",
17
+ "bugs": {
18
+ "url": "https://github.com/Gaspar1992/ng-desktop-engine/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/Gaspar1992/ng-desktop-engine.git",
23
+ "directory": "packages/server-native"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "type": "module",
29
+ "sideEffects": false,
30
+ "files": [
31
+ "fesm2022",
32
+ "README.md",
33
+ "LICENSE",
34
+ "!**/*.map"
35
+ ],
36
+ "main": "./fesm2022/index.js",
37
+ "module": "./fesm2022/index.js",
38
+ "types": "./fesm2022/index.d.ts",
39
+ "exports": {
40
+ ".": {
41
+ "types": "./fesm2022/index.d.ts",
42
+ "default": "./fesm2022/index.js"
43
+ },
44
+ "./package.json": {
45
+ "default": "./package.json"
46
+ }
47
+ }
48
+ }