@objectstack/sveltekit 3.0.2
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/.turbo/turbo-build.log +22 -0
- package/LICENSE +202 -0
- package/README.md +25 -0
- package/dist/index.d.mts +50 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +167 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +141 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +29 -0
- package/src/__mocks__/runtime.ts +4 -0
- package/src/index.ts +213 -0
- package/src/sveltekit.test.ts +249 -0
- package/tsconfig.json +13 -0
- package/vitest.config.ts +16 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
> @objectstack/sveltekit@3.0.2 build /home/runner/work/spec/spec/packages/adapters/sveltekit
|
|
3
|
+
> tsup --config ../../../tsup.config.ts
|
|
4
|
+
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v8.5.1
|
|
8
|
+
[34mCLI[39m Using tsup config: /home/runner/work/spec/spec/tsup.config.ts
|
|
9
|
+
[34mCLI[39m Target: es2020
|
|
10
|
+
[34mCLI[39m Cleaning output folder
|
|
11
|
+
[34mESM[39m Build start
|
|
12
|
+
[34mCJS[39m Build start
|
|
13
|
+
[32mESM[39m [1mdist/index.mjs [22m[32m4.83 KB[39m
|
|
14
|
+
[32mESM[39m [1mdist/index.mjs.map [22m[32m10.44 KB[39m
|
|
15
|
+
[32mESM[39m ⚡️ Build success in 68ms
|
|
16
|
+
[32mCJS[39m [1mdist/index.js [22m[32m5.88 KB[39m
|
|
17
|
+
[32mCJS[39m [1mdist/index.js.map [22m[32m10.48 KB[39m
|
|
18
|
+
[32mCJS[39m ⚡️ Build success in 70ms
|
|
19
|
+
[34mDTS[39m Build start
|
|
20
|
+
[32mDTS[39m ⚡️ Build success in 10787ms
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.mts [22m[32m1.50 KB[39m
|
|
22
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m1.50 KB[39m
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute
|
|
108
|
+
must include a readable copy of the attribution notices
|
|
109
|
+
contained within such NOTICE file, excluding those notices
|
|
110
|
+
that do not pertain to any part of the Derivative Works,
|
|
111
|
+
in at least one of the following places: within a NOTICE
|
|
112
|
+
text file distributed as part of the Derivative Works; within
|
|
113
|
+
the Source form or documentation, if provided along with
|
|
114
|
+
the Derivative Works; or, within a display generated by the
|
|
115
|
+
Derivative Works, if and wherever such third-party notices
|
|
116
|
+
normally appear. The contents of the NOTICE file are for
|
|
117
|
+
informational purposes only and do not modify the License.
|
|
118
|
+
You may add Your own attribution notices within Derivative
|
|
119
|
+
Works that You distribute, alongside or as an addendum to
|
|
120
|
+
the NOTICE text from the Work, provided that such additional
|
|
121
|
+
attribution notices cannot be construed as modifying the
|
|
122
|
+
License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 ObjectStack
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# @objectstack/sveltekit
|
|
2
|
+
|
|
3
|
+
The official SvelteKit adapter for ObjectStack.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
- SvelteKit API route handler
|
|
7
|
+
- Full Auth/GraphQL/Metadata/Data/Storage routes
|
|
8
|
+
- AuthPlugin service support
|
|
9
|
+
- Handle hook for attaching kernel to event.locals
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
// src/routes/api/[...path]/+server.ts
|
|
15
|
+
import { createRequestHandler } from '@objectstack/sveltekit';
|
|
16
|
+
import { kernel } from '$lib/kernel';
|
|
17
|
+
|
|
18
|
+
const handler = createRequestHandler({ kernel });
|
|
19
|
+
|
|
20
|
+
export const GET = handler;
|
|
21
|
+
export const POST = handler;
|
|
22
|
+
export const PUT = handler;
|
|
23
|
+
export const PATCH = handler;
|
|
24
|
+
export const DELETE = handler;
|
|
25
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ObjectKernel } from '@objectstack/runtime';
|
|
2
|
+
|
|
3
|
+
interface SvelteKitAdapterOptions {
|
|
4
|
+
kernel: ObjectKernel;
|
|
5
|
+
prefix?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* SvelteKit request event type (minimal interface to avoid hard dependency on @sveltejs/kit types at runtime)
|
|
9
|
+
*/
|
|
10
|
+
interface RequestEvent {
|
|
11
|
+
request: Request;
|
|
12
|
+
url: URL;
|
|
13
|
+
params: Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates a SvelteKit request handler for ObjectStack API routes.
|
|
17
|
+
* Use in a catch-all `+server.ts` route like `src/routes/api/[...path]/+server.ts`.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* // src/routes/api/[...path]/+server.ts
|
|
22
|
+
* import { createRequestHandler } from '@objectstack/sveltekit';
|
|
23
|
+
* import { kernel } from '$lib/kernel';
|
|
24
|
+
*
|
|
25
|
+
* const handler = createRequestHandler({ kernel });
|
|
26
|
+
*
|
|
27
|
+
* export const GET = handler;
|
|
28
|
+
* export const POST = handler;
|
|
29
|
+
* export const PUT = handler;
|
|
30
|
+
* export const PATCH = handler;
|
|
31
|
+
* export const DELETE = handler;
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
declare function createRequestHandler(options: SvelteKitAdapterOptions): (event: RequestEvent) => Promise<Response>;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a SvelteKit handle hook that attaches the kernel to event.locals.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* // src/hooks.server.ts
|
|
41
|
+
* import { createHandle } from '@objectstack/sveltekit';
|
|
42
|
+
* export const handle = createHandle({ kernel });
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
declare function createHandle(options: SvelteKitAdapterOptions): ({ event, resolve }: {
|
|
46
|
+
event: any;
|
|
47
|
+
resolve: (event: any) => Promise<Response>;
|
|
48
|
+
}) => Promise<Response>;
|
|
49
|
+
|
|
50
|
+
export { type SvelteKitAdapterOptions, createHandle, createRequestHandler };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ObjectKernel } from '@objectstack/runtime';
|
|
2
|
+
|
|
3
|
+
interface SvelteKitAdapterOptions {
|
|
4
|
+
kernel: ObjectKernel;
|
|
5
|
+
prefix?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* SvelteKit request event type (minimal interface to avoid hard dependency on @sveltejs/kit types at runtime)
|
|
9
|
+
*/
|
|
10
|
+
interface RequestEvent {
|
|
11
|
+
request: Request;
|
|
12
|
+
url: URL;
|
|
13
|
+
params: Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates a SvelteKit request handler for ObjectStack API routes.
|
|
17
|
+
* Use in a catch-all `+server.ts` route like `src/routes/api/[...path]/+server.ts`.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* // src/routes/api/[...path]/+server.ts
|
|
22
|
+
* import { createRequestHandler } from '@objectstack/sveltekit';
|
|
23
|
+
* import { kernel } from '$lib/kernel';
|
|
24
|
+
*
|
|
25
|
+
* const handler = createRequestHandler({ kernel });
|
|
26
|
+
*
|
|
27
|
+
* export const GET = handler;
|
|
28
|
+
* export const POST = handler;
|
|
29
|
+
* export const PUT = handler;
|
|
30
|
+
* export const PATCH = handler;
|
|
31
|
+
* export const DELETE = handler;
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
declare function createRequestHandler(options: SvelteKitAdapterOptions): (event: RequestEvent) => Promise<Response>;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a SvelteKit handle hook that attaches the kernel to event.locals.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* // src/hooks.server.ts
|
|
41
|
+
* import { createHandle } from '@objectstack/sveltekit';
|
|
42
|
+
* export const handle = createHandle({ kernel });
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
declare function createHandle(options: SvelteKitAdapterOptions): ({ event, resolve }: {
|
|
46
|
+
event: any;
|
|
47
|
+
resolve: (event: any) => Promise<Response>;
|
|
48
|
+
}) => Promise<Response>;
|
|
49
|
+
|
|
50
|
+
export { type SvelteKitAdapterOptions, createHandle, createRequestHandler };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createHandle: () => createHandle,
|
|
24
|
+
createRequestHandler: () => createRequestHandler
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
var import_runtime = require("@objectstack/runtime");
|
|
28
|
+
function createRequestHandler(options) {
|
|
29
|
+
const dispatcher = new import_runtime.HttpDispatcher(options.kernel);
|
|
30
|
+
const prefix = options.prefix || "/api";
|
|
31
|
+
const errorJson = (message, code = 500) => {
|
|
32
|
+
return new Response(JSON.stringify({ success: false, error: { message, code } }), {
|
|
33
|
+
status: code,
|
|
34
|
+
headers: { "Content-Type": "application/json" }
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
const toResponse = (result) => {
|
|
38
|
+
if (result.handled) {
|
|
39
|
+
if (result.response) {
|
|
40
|
+
const headers = new Headers({ "Content-Type": "application/json" });
|
|
41
|
+
if (result.response.headers) {
|
|
42
|
+
Object.entries(result.response.headers).forEach(([k, v]) => headers.set(k, v));
|
|
43
|
+
}
|
|
44
|
+
return new Response(JSON.stringify(result.response.body), {
|
|
45
|
+
status: result.response.status,
|
|
46
|
+
headers
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (result.result) {
|
|
50
|
+
const res = result.result;
|
|
51
|
+
if (res.type === "redirect" && res.url) {
|
|
52
|
+
return new Response(null, {
|
|
53
|
+
status: 302,
|
|
54
|
+
headers: { Location: res.url }
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (res.type === "stream" && res.stream) {
|
|
58
|
+
const headers = new Headers();
|
|
59
|
+
if (res.headers) {
|
|
60
|
+
Object.entries(res.headers).forEach(([k, v]) => headers.set(k, v));
|
|
61
|
+
}
|
|
62
|
+
return new Response(res.stream, { status: 200, headers });
|
|
63
|
+
}
|
|
64
|
+
return new Response(JSON.stringify(res), {
|
|
65
|
+
status: 200,
|
|
66
|
+
headers: { "Content-Type": "application/json" }
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return errorJson("Not Found", 404);
|
|
71
|
+
};
|
|
72
|
+
return async function handler(event) {
|
|
73
|
+
const { request, url } = event;
|
|
74
|
+
const method = request.method;
|
|
75
|
+
const path = url.pathname.substring(prefix.length);
|
|
76
|
+
const segments = path.split("/").filter(Boolean);
|
|
77
|
+
if (segments.length === 0 && method === "GET") {
|
|
78
|
+
return new Response(JSON.stringify({ data: dispatcher.getDiscoveryInfo(prefix) }), {
|
|
79
|
+
status: 200,
|
|
80
|
+
headers: { "Content-Type": "application/json" }
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
if (segments[0] === "auth") {
|
|
85
|
+
const subPath = segments.slice(1).join("/");
|
|
86
|
+
const authService = typeof options.kernel.getService === "function" ? options.kernel.getService("auth") : null;
|
|
87
|
+
if (authService && typeof authService.handleRequest === "function") {
|
|
88
|
+
return await authService.handleRequest(request);
|
|
89
|
+
}
|
|
90
|
+
const body = method === "GET" || method === "HEAD" ? {} : await request.json().catch(() => ({}));
|
|
91
|
+
const result = await dispatcher.handleAuth(subPath, method, body, { request });
|
|
92
|
+
return toResponse(result);
|
|
93
|
+
}
|
|
94
|
+
if (segments[0] === "graphql" && method === "POST") {
|
|
95
|
+
const body = await request.json();
|
|
96
|
+
const result = await dispatcher.handleGraphQL(body, { request });
|
|
97
|
+
return new Response(JSON.stringify(result), {
|
|
98
|
+
status: 200,
|
|
99
|
+
headers: { "Content-Type": "application/json" }
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (segments[0] === "meta") {
|
|
103
|
+
const subPath = segments.slice(1).join("/");
|
|
104
|
+
let body = void 0;
|
|
105
|
+
if (method === "PUT" || method === "POST") {
|
|
106
|
+
body = await request.json().catch(() => ({}));
|
|
107
|
+
}
|
|
108
|
+
const result = await dispatcher.handleMetadata(
|
|
109
|
+
subPath ? `/${subPath}` : "",
|
|
110
|
+
{ request },
|
|
111
|
+
method,
|
|
112
|
+
body
|
|
113
|
+
);
|
|
114
|
+
return toResponse(result);
|
|
115
|
+
}
|
|
116
|
+
if (segments[0] === "data") {
|
|
117
|
+
const subPath = segments.slice(1).join("/");
|
|
118
|
+
let body = {};
|
|
119
|
+
if (method === "POST" || method === "PATCH") {
|
|
120
|
+
body = await request.json().catch(() => ({}));
|
|
121
|
+
}
|
|
122
|
+
const queryParams = {};
|
|
123
|
+
url.searchParams.forEach((val, key) => {
|
|
124
|
+
queryParams[key] = val;
|
|
125
|
+
});
|
|
126
|
+
const result = await dispatcher.handleData(
|
|
127
|
+
subPath ? `/${subPath}` : "",
|
|
128
|
+
method,
|
|
129
|
+
body,
|
|
130
|
+
queryParams,
|
|
131
|
+
{ request }
|
|
132
|
+
);
|
|
133
|
+
return toResponse(result);
|
|
134
|
+
}
|
|
135
|
+
if (segments[0] === "storage") {
|
|
136
|
+
const subPath = segments.slice(1).join("/");
|
|
137
|
+
let file = void 0;
|
|
138
|
+
if (method === "POST" && subPath === "upload") {
|
|
139
|
+
const formData = await request.formData();
|
|
140
|
+
file = formData.get("file");
|
|
141
|
+
}
|
|
142
|
+
const result = await dispatcher.handleStorage(
|
|
143
|
+
subPath ? `/${subPath}` : "",
|
|
144
|
+
method,
|
|
145
|
+
file,
|
|
146
|
+
{ request }
|
|
147
|
+
);
|
|
148
|
+
return toResponse(result);
|
|
149
|
+
}
|
|
150
|
+
return errorJson("Not Found", 404);
|
|
151
|
+
} catch (err) {
|
|
152
|
+
return errorJson(err.message || "Internal Server Error", err.statusCode || 500);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function createHandle(options) {
|
|
157
|
+
return async function handle({ event, resolve }) {
|
|
158
|
+
event.locals.objectStack = options.kernel;
|
|
159
|
+
return resolve(event);
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
163
|
+
0 && (module.exports = {
|
|
164
|
+
createHandle,
|
|
165
|
+
createRequestHandler
|
|
166
|
+
});
|
|
167
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';\n\nexport interface SvelteKitAdapterOptions {\n kernel: ObjectKernel;\n prefix?: string;\n}\n\n/**\n * Auth service interface with handleRequest method\n */\ninterface AuthService {\n handleRequest(request: Request): Promise<Response>;\n}\n\n/**\n * SvelteKit request event type (minimal interface to avoid hard dependency on @sveltejs/kit types at runtime)\n */\ninterface RequestEvent {\n request: Request;\n url: URL;\n params: Record<string, string>;\n}\n\n/**\n * Creates a SvelteKit request handler for ObjectStack API routes.\n * Use in a catch-all `+server.ts` route like `src/routes/api/[...path]/+server.ts`.\n *\n * @example\n * ```ts\n * // src/routes/api/[...path]/+server.ts\n * import { createRequestHandler } from '@objectstack/sveltekit';\n * import { kernel } from '$lib/kernel';\n *\n * const handler = createRequestHandler({ kernel });\n *\n * export const GET = handler;\n * export const POST = handler;\n * export const PUT = handler;\n * export const PATCH = handler;\n * export const DELETE = handler;\n * ```\n */\nexport function createRequestHandler(options: SvelteKitAdapterOptions) {\n const dispatcher = new HttpDispatcher(options.kernel);\n const prefix = options.prefix || '/api';\n\n const errorJson = (message: string, code: number = 500) => {\n return new Response(JSON.stringify({ success: false, error: { message, code } }), {\n status: code,\n headers: { 'Content-Type': 'application/json' },\n });\n };\n\n const toResponse = (result: HttpDispatcherResult): Response => {\n if (result.handled) {\n if (result.response) {\n const headers = new Headers({ 'Content-Type': 'application/json' });\n if (result.response.headers) {\n Object.entries(result.response.headers).forEach(([k, v]) => headers.set(k, v as string));\n }\n return new Response(JSON.stringify(result.response.body), {\n status: result.response.status,\n headers,\n });\n }\n if (result.result) {\n const res = result.result;\n if (res.type === 'redirect' && res.url) {\n return new Response(null, {\n status: 302,\n headers: { Location: res.url },\n });\n }\n if (res.type === 'stream' && res.stream) {\n const headers = new Headers();\n if (res.headers) {\n Object.entries(res.headers).forEach(([k, v]) => headers.set(k, v as string));\n }\n return new Response(res.stream, { status: 200, headers });\n }\n return new Response(JSON.stringify(res), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n return errorJson('Not Found', 404);\n };\n\n return async function handler(event: RequestEvent): Promise<Response> {\n const { request, url } = event;\n const method = request.method;\n const path = url.pathname.substring(prefix.length);\n const segments = path.split('/').filter(Boolean);\n\n // --- Discovery ---\n if (segments.length === 0 && method === 'GET') {\n return new Response(JSON.stringify({ data: dispatcher.getDiscoveryInfo(prefix) }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n try {\n // --- Auth ---\n if (segments[0] === 'auth') {\n const subPath = segments.slice(1).join('/');\n\n // Try AuthPlugin service first\n const authService = typeof options.kernel.getService === 'function'\n ? options.kernel.getService<AuthService>('auth')\n : null;\n\n if (authService && typeof authService.handleRequest === 'function') {\n return await authService.handleRequest(request);\n }\n\n // Fallback to dispatcher\n const body = method === 'GET' || method === 'HEAD'\n ? {}\n : await request.json().catch(() => ({}));\n const result = await dispatcher.handleAuth(subPath, method, body, { request });\n return toResponse(result);\n }\n\n // --- GraphQL ---\n if (segments[0] === 'graphql' && method === 'POST') {\n const body = await request.json() as { query: string; variables?: any };\n const result = await dispatcher.handleGraphQL(body, { request });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // --- Metadata ---\n if (segments[0] === 'meta') {\n const subPath = segments.slice(1).join('/');\n let body: any = undefined;\n if (method === 'PUT' || method === 'POST') {\n body = await request.json().catch(() => ({}));\n }\n const result = await dispatcher.handleMetadata(\n subPath ? `/${subPath}` : '',\n { request },\n method,\n body,\n );\n return toResponse(result);\n }\n\n // --- Data ---\n if (segments[0] === 'data') {\n const subPath = segments.slice(1).join('/');\n let body: any = {};\n if (method === 'POST' || method === 'PATCH') {\n body = await request.json().catch(() => ({}));\n }\n const queryParams: Record<string, any> = {};\n url.searchParams.forEach((val, key) => { queryParams[key] = val; });\n\n const result = await dispatcher.handleData(\n subPath ? `/${subPath}` : '',\n method,\n body,\n queryParams,\n { request },\n );\n return toResponse(result);\n }\n\n // --- Storage ---\n if (segments[0] === 'storage') {\n const subPath = segments.slice(1).join('/');\n let file: any = undefined;\n if (method === 'POST' && subPath === 'upload') {\n const formData = await request.formData();\n file = formData.get('file');\n }\n const result = await dispatcher.handleStorage(\n subPath ? `/${subPath}` : '',\n method,\n file,\n { request },\n );\n return toResponse(result);\n }\n\n return errorJson('Not Found', 404);\n } catch (err: any) {\n return errorJson(err.message || 'Internal Server Error', err.statusCode || 500);\n }\n };\n}\n\n/**\n * Creates a SvelteKit handle hook that attaches the kernel to event.locals.\n *\n * @example\n * ```ts\n * // src/hooks.server.ts\n * import { createHandle } from '@objectstack/sveltekit';\n * export const handle = createHandle({ kernel });\n * ```\n */\nexport function createHandle(options: SvelteKitAdapterOptions) {\n return async function handle({ event, resolve }: { event: any; resolve: (event: any) => Promise<Response> }) {\n event.locals.objectStack = options.kernel;\n return resolve(event);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAAwE;AA0CjE,SAAS,qBAAqB,SAAkC;AACrE,QAAM,aAAa,IAAI,8BAAe,QAAQ,MAAM;AACpD,QAAM,SAAS,QAAQ,UAAU;AAEjC,QAAM,YAAY,CAAC,SAAiB,OAAe,QAAQ;AACzD,WAAO,IAAI,SAAS,KAAK,UAAU,EAAE,SAAS,OAAO,OAAO,EAAE,SAAS,KAAK,EAAE,CAAC,GAAG;AAAA,MAChF,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC;AAAA,EACH;AAEA,QAAM,aAAa,CAAC,WAA2C;AAC7D,QAAI,OAAO,SAAS;AAClB,UAAI,OAAO,UAAU;AACnB,cAAM,UAAU,IAAI,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC;AAClE,YAAI,OAAO,SAAS,SAAS;AAC3B,iBAAO,QAAQ,OAAO,SAAS,OAAO,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,QAAQ,IAAI,GAAG,CAAW,CAAC;AAAA,QACzF;AACA,eAAO,IAAI,SAAS,KAAK,UAAU,OAAO,SAAS,IAAI,GAAG;AAAA,UACxD,QAAQ,OAAO,SAAS;AAAA,UACxB;AAAA,QACF,CAAC;AAA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AAM,QAAQ,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AAAA,QAC9C;AACA,cAAM,cAAmC,CAAC;AAC1C,YAAI,aAAa,QAAQ,CAAC,KAAK,QAAQ;AAAE,sBAAY,GAAG,IAAI;AAAA,QAAK,CAAC;AAElE,cAAM,SAAS,MAAM,WAAW;AAAA,UAC9B,UAAU,IAAI,OAAO,KAAK;AAAA,UAC1B;AAAA,UACA;AAAA,UACA;AAAA,UACA,EAAE,QAAQ;AAAA,QACZ;AACA,eAAO,WAAW,MAAM;AAAA,MAC1B;AAGA,UAAI,SAAS,CAAC,MAAM,WAAW;AAC7B,cAAM,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK,GAAG;AAC1C,YAAI,OAAY;AAChB,YAAI,WAAW,UAAU,YAAY,UAAU;AAC7C,gBAAM,WAAW,MAAM,QAAQ,SAAS;AACxC,iBAAO,SAAS,IAAI,MAAM;AAAA,QAC5B;AACA,cAAM,SAAS,MAAM,WAAW;AAAA,UAC9B,UAAU,IAAI,OAAO,KAAK;AAAA,UAC1B;AAAA,UACA;AAAA,UACA,EAAE,QAAQ;AAAA,QACZ;AACA,eAAO,WAAW,MAAM;AAAA,MAC1B;AAEA,aAAO,UAAU,aAAa,GAAG;AAAA,IACnC,SAAS,KAAU;AACjB,aAAO,UAAU,IAAI,WAAW,yBAAyB,IAAI,cAAc,GAAG;AAAA,IAChF;AAAA,EACF;AACF;AAYO,SAAS,aAAa,SAAkC;AAC7D,SAAO,eAAe,OAAO,EAAE,OAAO,QAAQ,GAA+D;AAC3G,UAAM,OAAO,cAAc,QAAQ;AACnC,WAAO,QAAQ,KAAK;AAAA,EACtB;AACF;","names":[]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { HttpDispatcher } from "@objectstack/runtime";
|
|
3
|
+
function createRequestHandler(options) {
|
|
4
|
+
const dispatcher = new HttpDispatcher(options.kernel);
|
|
5
|
+
const prefix = options.prefix || "/api";
|
|
6
|
+
const errorJson = (message, code = 500) => {
|
|
7
|
+
return new Response(JSON.stringify({ success: false, error: { message, code } }), {
|
|
8
|
+
status: code,
|
|
9
|
+
headers: { "Content-Type": "application/json" }
|
|
10
|
+
});
|
|
11
|
+
};
|
|
12
|
+
const toResponse = (result) => {
|
|
13
|
+
if (result.handled) {
|
|
14
|
+
if (result.response) {
|
|
15
|
+
const headers = new Headers({ "Content-Type": "application/json" });
|
|
16
|
+
if (result.response.headers) {
|
|
17
|
+
Object.entries(result.response.headers).forEach(([k, v]) => headers.set(k, v));
|
|
18
|
+
}
|
|
19
|
+
return new Response(JSON.stringify(result.response.body), {
|
|
20
|
+
status: result.response.status,
|
|
21
|
+
headers
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
if (result.result) {
|
|
25
|
+
const res = result.result;
|
|
26
|
+
if (res.type === "redirect" && res.url) {
|
|
27
|
+
return new Response(null, {
|
|
28
|
+
status: 302,
|
|
29
|
+
headers: { Location: res.url }
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
if (res.type === "stream" && res.stream) {
|
|
33
|
+
const headers = new Headers();
|
|
34
|
+
if (res.headers) {
|
|
35
|
+
Object.entries(res.headers).forEach(([k, v]) => headers.set(k, v));
|
|
36
|
+
}
|
|
37
|
+
return new Response(res.stream, { status: 200, headers });
|
|
38
|
+
}
|
|
39
|
+
return new Response(JSON.stringify(res), {
|
|
40
|
+
status: 200,
|
|
41
|
+
headers: { "Content-Type": "application/json" }
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return errorJson("Not Found", 404);
|
|
46
|
+
};
|
|
47
|
+
return async function handler(event) {
|
|
48
|
+
const { request, url } = event;
|
|
49
|
+
const method = request.method;
|
|
50
|
+
const path = url.pathname.substring(prefix.length);
|
|
51
|
+
const segments = path.split("/").filter(Boolean);
|
|
52
|
+
if (segments.length === 0 && method === "GET") {
|
|
53
|
+
return new Response(JSON.stringify({ data: dispatcher.getDiscoveryInfo(prefix) }), {
|
|
54
|
+
status: 200,
|
|
55
|
+
headers: { "Content-Type": "application/json" }
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
if (segments[0] === "auth") {
|
|
60
|
+
const subPath = segments.slice(1).join("/");
|
|
61
|
+
const authService = typeof options.kernel.getService === "function" ? options.kernel.getService("auth") : null;
|
|
62
|
+
if (authService && typeof authService.handleRequest === "function") {
|
|
63
|
+
return await authService.handleRequest(request);
|
|
64
|
+
}
|
|
65
|
+
const body = method === "GET" || method === "HEAD" ? {} : await request.json().catch(() => ({}));
|
|
66
|
+
const result = await dispatcher.handleAuth(subPath, method, body, { request });
|
|
67
|
+
return toResponse(result);
|
|
68
|
+
}
|
|
69
|
+
if (segments[0] === "graphql" && method === "POST") {
|
|
70
|
+
const body = await request.json();
|
|
71
|
+
const result = await dispatcher.handleGraphQL(body, { request });
|
|
72
|
+
return new Response(JSON.stringify(result), {
|
|
73
|
+
status: 200,
|
|
74
|
+
headers: { "Content-Type": "application/json" }
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (segments[0] === "meta") {
|
|
78
|
+
const subPath = segments.slice(1).join("/");
|
|
79
|
+
let body = void 0;
|
|
80
|
+
if (method === "PUT" || method === "POST") {
|
|
81
|
+
body = await request.json().catch(() => ({}));
|
|
82
|
+
}
|
|
83
|
+
const result = await dispatcher.handleMetadata(
|
|
84
|
+
subPath ? `/${subPath}` : "",
|
|
85
|
+
{ request },
|
|
86
|
+
method,
|
|
87
|
+
body
|
|
88
|
+
);
|
|
89
|
+
return toResponse(result);
|
|
90
|
+
}
|
|
91
|
+
if (segments[0] === "data") {
|
|
92
|
+
const subPath = segments.slice(1).join("/");
|
|
93
|
+
let body = {};
|
|
94
|
+
if (method === "POST" || method === "PATCH") {
|
|
95
|
+
body = await request.json().catch(() => ({}));
|
|
96
|
+
}
|
|
97
|
+
const queryParams = {};
|
|
98
|
+
url.searchParams.forEach((val, key) => {
|
|
99
|
+
queryParams[key] = val;
|
|
100
|
+
});
|
|
101
|
+
const result = await dispatcher.handleData(
|
|
102
|
+
subPath ? `/${subPath}` : "",
|
|
103
|
+
method,
|
|
104
|
+
body,
|
|
105
|
+
queryParams,
|
|
106
|
+
{ request }
|
|
107
|
+
);
|
|
108
|
+
return toResponse(result);
|
|
109
|
+
}
|
|
110
|
+
if (segments[0] === "storage") {
|
|
111
|
+
const subPath = segments.slice(1).join("/");
|
|
112
|
+
let file = void 0;
|
|
113
|
+
if (method === "POST" && subPath === "upload") {
|
|
114
|
+
const formData = await request.formData();
|
|
115
|
+
file = formData.get("file");
|
|
116
|
+
}
|
|
117
|
+
const result = await dispatcher.handleStorage(
|
|
118
|
+
subPath ? `/${subPath}` : "",
|
|
119
|
+
method,
|
|
120
|
+
file,
|
|
121
|
+
{ request }
|
|
122
|
+
);
|
|
123
|
+
return toResponse(result);
|
|
124
|
+
}
|
|
125
|
+
return errorJson("Not Found", 404);
|
|
126
|
+
} catch (err) {
|
|
127
|
+
return errorJson(err.message || "Internal Server Error", err.statusCode || 500);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function createHandle(options) {
|
|
132
|
+
return async function handle({ event, resolve }) {
|
|
133
|
+
event.locals.objectStack = options.kernel;
|
|
134
|
+
return resolve(event);
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export {
|
|
138
|
+
createHandle,
|
|
139
|
+
createRequestHandler
|
|
140
|
+
};
|
|
141
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';\n\nexport interface SvelteKitAdapterOptions {\n kernel: ObjectKernel;\n prefix?: string;\n}\n\n/**\n * Auth service interface with handleRequest method\n */\ninterface AuthService {\n handleRequest(request: Request): Promise<Response>;\n}\n\n/**\n * SvelteKit request event type (minimal interface to avoid hard dependency on @sveltejs/kit types at runtime)\n */\ninterface RequestEvent {\n request: Request;\n url: URL;\n params: Record<string, string>;\n}\n\n/**\n * Creates a SvelteKit request handler for ObjectStack API routes.\n * Use in a catch-all `+server.ts` route like `src/routes/api/[...path]/+server.ts`.\n *\n * @example\n * ```ts\n * // src/routes/api/[...path]/+server.ts\n * import { createRequestHandler } from '@objectstack/sveltekit';\n * import { kernel } from '$lib/kernel';\n *\n * const handler = createRequestHandler({ kernel });\n *\n * export const GET = handler;\n * export const POST = handler;\n * export const PUT = handler;\n * export const PATCH = handler;\n * export const DELETE = handler;\n * ```\n */\nexport function createRequestHandler(options: SvelteKitAdapterOptions) {\n const dispatcher = new HttpDispatcher(options.kernel);\n const prefix = options.prefix || '/api';\n\n const errorJson = (message: string, code: number = 500) => {\n return new Response(JSON.stringify({ success: false, error: { message, code } }), {\n status: code,\n headers: { 'Content-Type': 'application/json' },\n });\n };\n\n const toResponse = (result: HttpDispatcherResult): Response => {\n if (result.handled) {\n if (result.response) {\n const headers = new Headers({ 'Content-Type': 'application/json' });\n if (result.response.headers) {\n Object.entries(result.response.headers).forEach(([k, v]) => headers.set(k, v as string));\n }\n return new Response(JSON.stringify(result.response.body), {\n status: result.response.status,\n headers,\n });\n }\n if (result.result) {\n const res = result.result;\n if (res.type === 'redirect' && res.url) {\n return new Response(null, {\n status: 302,\n headers: { Location: res.url },\n });\n }\n if (res.type === 'stream' && res.stream) {\n const headers = new Headers();\n if (res.headers) {\n Object.entries(res.headers).forEach(([k, v]) => headers.set(k, v as string));\n }\n return new Response(res.stream, { status: 200, headers });\n }\n return new Response(JSON.stringify(res), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n return errorJson('Not Found', 404);\n };\n\n return async function handler(event: RequestEvent): Promise<Response> {\n const { request, url } = event;\n const method = request.method;\n const path = url.pathname.substring(prefix.length);\n const segments = path.split('/').filter(Boolean);\n\n // --- Discovery ---\n if (segments.length === 0 && method === 'GET') {\n return new Response(JSON.stringify({ data: dispatcher.getDiscoveryInfo(prefix) }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n try {\n // --- Auth ---\n if (segments[0] === 'auth') {\n const subPath = segments.slice(1).join('/');\n\n // Try AuthPlugin service first\n const authService = typeof options.kernel.getService === 'function'\n ? options.kernel.getService<AuthService>('auth')\n : null;\n\n if (authService && typeof authService.handleRequest === 'function') {\n return await authService.handleRequest(request);\n }\n\n // Fallback to dispatcher\n const body = method === 'GET' || method === 'HEAD'\n ? {}\n : await request.json().catch(() => ({}));\n const result = await dispatcher.handleAuth(subPath, method, body, { request });\n return toResponse(result);\n }\n\n // --- GraphQL ---\n if (segments[0] === 'graphql' && method === 'POST') {\n const body = await request.json() as { query: string; variables?: any };\n const result = await dispatcher.handleGraphQL(body, { request });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // --- Metadata ---\n if (segments[0] === 'meta') {\n const subPath = segments.slice(1).join('/');\n let body: any = undefined;\n if (method === 'PUT' || method === 'POST') {\n body = await request.json().catch(() => ({}));\n }\n const result = await dispatcher.handleMetadata(\n subPath ? `/${subPath}` : '',\n { request },\n method,\n body,\n );\n return toResponse(result);\n }\n\n // --- Data ---\n if (segments[0] === 'data') {\n const subPath = segments.slice(1).join('/');\n let body: any = {};\n if (method === 'POST' || method === 'PATCH') {\n body = await request.json().catch(() => ({}));\n }\n const queryParams: Record<string, any> = {};\n url.searchParams.forEach((val, key) => { queryParams[key] = val; });\n\n const result = await dispatcher.handleData(\n subPath ? `/${subPath}` : '',\n method,\n body,\n queryParams,\n { request },\n );\n return toResponse(result);\n }\n\n // --- Storage ---\n if (segments[0] === 'storage') {\n const subPath = segments.slice(1).join('/');\n let file: any = undefined;\n if (method === 'POST' && subPath === 'upload') {\n const formData = await request.formData();\n file = formData.get('file');\n }\n const result = await dispatcher.handleStorage(\n subPath ? `/${subPath}` : '',\n method,\n file,\n { request },\n );\n return toResponse(result);\n }\n\n return errorJson('Not Found', 404);\n } catch (err: any) {\n return errorJson(err.message || 'Internal Server Error', err.statusCode || 500);\n }\n };\n}\n\n/**\n * Creates a SvelteKit handle hook that attaches the kernel to event.locals.\n *\n * @example\n * ```ts\n * // src/hooks.server.ts\n * import { createHandle } from '@objectstack/sveltekit';\n * export const handle = createHandle({ kernel });\n * ```\n */\nexport function createHandle(options: SvelteKitAdapterOptions) {\n return async function handle({ event, resolve }: { event: any; resolve: (event: any) => Promise<Response> }) {\n event.locals.objectStack = options.kernel;\n return resolve(event);\n };\n}\n"],"mappings":";AAEA,SAA4B,sBAA4C;AA0CjE,SAAS,qBAAqB,SAAkC;AACrE,QAAM,aAAa,IAAI,eAAe,QAAQ,MAAM;AACpD,QAAM,SAAS,QAAQ,UAAU;AAEjC,QAAM,YAAY,CAAC,SAAiB,OAAe,QAAQ;AACzD,WAAO,IAAI,SAAS,KAAK,UAAU,EAAE,SAAS,OAAO,OAAO,EAAE,SAAS,KAAK,EAAE,CAAC,GAAG;AAAA,MAChF,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC;AAAA,EACH;AAEA,QAAM,aAAa,CAAC,WAA2C;AAC7D,QAAI,OAAO,SAAS;AAClB,UAAI,OAAO,UAAU;AACnB,cAAM,UAAU,IAAI,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC;AAClE,YAAI,OAAO,SAAS,SAAS;AAC3B,iBAAO,QAAQ,OAAO,SAAS,OAAO,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,QAAQ,IAAI,GAAG,CAAW,CAAC;AAAA,QACzF;AACA,eAAO,IAAI,SAAS,KAAK,UAAU,OAAO,SAAS,IAAI,GAAG;AAAA,UACxD,QAAQ,OAAO,SAAS;AAAA,UACxB;AAAA,QACF,CAAC;AAAA,MACH;AACA,UAAI,OAAO,QAAQ;AACj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,CAAC,EAAE;AAAA,QAC9C;AACA,cAAM,cAAmC,CAAC;AAC1C,YAAI,aAAa,QAAQ,CAAC,KAAK,QAAQ;AAAE,sBAAY,GAAG,IAAI;AAAA,QAAK,CAAC;AAElE,cAAM,SAAS,MAAM,WAAW;AAAA,UAC9B,UAAU,IAAI,OAAO,KAAK;AAAA,UAC1B;AAAA,UACA;AAAA,UACA;AAAA,UACA,EAAE,QAAQ;AAAA,QACZ;AACA,eAAO,WAAW,MAAM;AAAA,MAC1B;AAGA,UAAI,SAAS,CAAC,MAAM,WAAW;AAC7B,cAAM,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK,GAAG;AAC1C,YAAI,OAAY;AAChB,YAAI,WAAW,UAAU,YAAY,UAAU;AAC7C,gBAAM,WAAW,MAAM,QAAQ,SAAS;AACxC,iBAAO,SAAS,IAAI,MAAM;AAAA,QAC5B;AACA,cAAM,SAAS,MAAM,WAAW;AAAA,UAC9B,UAAU,IAAI,OAAO,KAAK;AAAA,UAC1B;AAAA,UACA;AAAA,UACA,EAAE,QAAQ;AAAA,QACZ;AACA,eAAO,WAAW,MAAM;AAAA,MAC1B;AAEA,aAAO,UAAU,aAAa,GAAG;AAAA,IACnC,SAAS,KAAU;AACjB,aAAO,UAAU,IAAI,WAAW,yBAAyB,IAAI,cAAc,GAAG;AAAA,IAChF;AAAA,EACF;AACF;AAYO,SAAS,aAAa,SAAkC;AAC7D,SAAO,eAAe,OAAO,EAAE,OAAO,QAAQ,GAA+D;AAC3G,UAAM,OAAO,cAAc,QAAQ;AACnC,WAAO,QAAQ,KAAK;AAAA,EACtB;AACF;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@objectstack/sveltekit",
|
|
3
|
+
"version": "3.0.2",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.mjs",
|
|
11
|
+
"require": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"peerDependencies": {
|
|
15
|
+
"@sveltejs/kit": "^2.21.5",
|
|
16
|
+
"@objectstack/runtime": "3.0.2"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@sveltejs/kit": "^2.21.5",
|
|
20
|
+
"typescript": "^5.0.0",
|
|
21
|
+
"vitest": "^4.0.18",
|
|
22
|
+
"@objectstack/runtime": "3.0.2"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup --config ../../../tsup.config.ts",
|
|
26
|
+
"test": "vitest run",
|
|
27
|
+
"test:watch": "vitest"
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';
|
|
4
|
+
|
|
5
|
+
export interface SvelteKitAdapterOptions {
|
|
6
|
+
kernel: ObjectKernel;
|
|
7
|
+
prefix?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Auth service interface with handleRequest method
|
|
12
|
+
*/
|
|
13
|
+
interface AuthService {
|
|
14
|
+
handleRequest(request: Request): Promise<Response>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* SvelteKit request event type (minimal interface to avoid hard dependency on @sveltejs/kit types at runtime)
|
|
19
|
+
*/
|
|
20
|
+
interface RequestEvent {
|
|
21
|
+
request: Request;
|
|
22
|
+
url: URL;
|
|
23
|
+
params: Record<string, string>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Creates a SvelteKit request handler for ObjectStack API routes.
|
|
28
|
+
* Use in a catch-all `+server.ts` route like `src/routes/api/[...path]/+server.ts`.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* // src/routes/api/[...path]/+server.ts
|
|
33
|
+
* import { createRequestHandler } from '@objectstack/sveltekit';
|
|
34
|
+
* import { kernel } from '$lib/kernel';
|
|
35
|
+
*
|
|
36
|
+
* const handler = createRequestHandler({ kernel });
|
|
37
|
+
*
|
|
38
|
+
* export const GET = handler;
|
|
39
|
+
* export const POST = handler;
|
|
40
|
+
* export const PUT = handler;
|
|
41
|
+
* export const PATCH = handler;
|
|
42
|
+
* export const DELETE = handler;
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export function createRequestHandler(options: SvelteKitAdapterOptions) {
|
|
46
|
+
const dispatcher = new HttpDispatcher(options.kernel);
|
|
47
|
+
const prefix = options.prefix || '/api';
|
|
48
|
+
|
|
49
|
+
const errorJson = (message: string, code: number = 500) => {
|
|
50
|
+
return new Response(JSON.stringify({ success: false, error: { message, code } }), {
|
|
51
|
+
status: code,
|
|
52
|
+
headers: { 'Content-Type': 'application/json' },
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const toResponse = (result: HttpDispatcherResult): Response => {
|
|
57
|
+
if (result.handled) {
|
|
58
|
+
if (result.response) {
|
|
59
|
+
const headers = new Headers({ 'Content-Type': 'application/json' });
|
|
60
|
+
if (result.response.headers) {
|
|
61
|
+
Object.entries(result.response.headers).forEach(([k, v]) => headers.set(k, v as string));
|
|
62
|
+
}
|
|
63
|
+
return new Response(JSON.stringify(result.response.body), {
|
|
64
|
+
status: result.response.status,
|
|
65
|
+
headers,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (result.result) {
|
|
69
|
+
const res = result.result;
|
|
70
|
+
if (res.type === 'redirect' && res.url) {
|
|
71
|
+
return new Response(null, {
|
|
72
|
+
status: 302,
|
|
73
|
+
headers: { Location: res.url },
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
if (res.type === 'stream' && res.stream) {
|
|
77
|
+
const headers = new Headers();
|
|
78
|
+
if (res.headers) {
|
|
79
|
+
Object.entries(res.headers).forEach(([k, v]) => headers.set(k, v as string));
|
|
80
|
+
}
|
|
81
|
+
return new Response(res.stream, { status: 200, headers });
|
|
82
|
+
}
|
|
83
|
+
return new Response(JSON.stringify(res), {
|
|
84
|
+
status: 200,
|
|
85
|
+
headers: { 'Content-Type': 'application/json' },
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return errorJson('Not Found', 404);
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return async function handler(event: RequestEvent): Promise<Response> {
|
|
93
|
+
const { request, url } = event;
|
|
94
|
+
const method = request.method;
|
|
95
|
+
const path = url.pathname.substring(prefix.length);
|
|
96
|
+
const segments = path.split('/').filter(Boolean);
|
|
97
|
+
|
|
98
|
+
// --- Discovery ---
|
|
99
|
+
if (segments.length === 0 && method === 'GET') {
|
|
100
|
+
return new Response(JSON.stringify({ data: dispatcher.getDiscoveryInfo(prefix) }), {
|
|
101
|
+
status: 200,
|
|
102
|
+
headers: { 'Content-Type': 'application/json' },
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
// --- Auth ---
|
|
108
|
+
if (segments[0] === 'auth') {
|
|
109
|
+
const subPath = segments.slice(1).join('/');
|
|
110
|
+
|
|
111
|
+
// Try AuthPlugin service first
|
|
112
|
+
const authService = typeof options.kernel.getService === 'function'
|
|
113
|
+
? options.kernel.getService<AuthService>('auth')
|
|
114
|
+
: null;
|
|
115
|
+
|
|
116
|
+
if (authService && typeof authService.handleRequest === 'function') {
|
|
117
|
+
return await authService.handleRequest(request);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Fallback to dispatcher
|
|
121
|
+
const body = method === 'GET' || method === 'HEAD'
|
|
122
|
+
? {}
|
|
123
|
+
: await request.json().catch(() => ({}));
|
|
124
|
+
const result = await dispatcher.handleAuth(subPath, method, body, { request });
|
|
125
|
+
return toResponse(result);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// --- GraphQL ---
|
|
129
|
+
if (segments[0] === 'graphql' && method === 'POST') {
|
|
130
|
+
const body = await request.json() as { query: string; variables?: any };
|
|
131
|
+
const result = await dispatcher.handleGraphQL(body, { request });
|
|
132
|
+
return new Response(JSON.stringify(result), {
|
|
133
|
+
status: 200,
|
|
134
|
+
headers: { 'Content-Type': 'application/json' },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// --- Metadata ---
|
|
139
|
+
if (segments[0] === 'meta') {
|
|
140
|
+
const subPath = segments.slice(1).join('/');
|
|
141
|
+
let body: any = undefined;
|
|
142
|
+
if (method === 'PUT' || method === 'POST') {
|
|
143
|
+
body = await request.json().catch(() => ({}));
|
|
144
|
+
}
|
|
145
|
+
const result = await dispatcher.handleMetadata(
|
|
146
|
+
subPath ? `/${subPath}` : '',
|
|
147
|
+
{ request },
|
|
148
|
+
method,
|
|
149
|
+
body,
|
|
150
|
+
);
|
|
151
|
+
return toResponse(result);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// --- Data ---
|
|
155
|
+
if (segments[0] === 'data') {
|
|
156
|
+
const subPath = segments.slice(1).join('/');
|
|
157
|
+
let body: any = {};
|
|
158
|
+
if (method === 'POST' || method === 'PATCH') {
|
|
159
|
+
body = await request.json().catch(() => ({}));
|
|
160
|
+
}
|
|
161
|
+
const queryParams: Record<string, any> = {};
|
|
162
|
+
url.searchParams.forEach((val, key) => { queryParams[key] = val; });
|
|
163
|
+
|
|
164
|
+
const result = await dispatcher.handleData(
|
|
165
|
+
subPath ? `/${subPath}` : '',
|
|
166
|
+
method,
|
|
167
|
+
body,
|
|
168
|
+
queryParams,
|
|
169
|
+
{ request },
|
|
170
|
+
);
|
|
171
|
+
return toResponse(result);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// --- Storage ---
|
|
175
|
+
if (segments[0] === 'storage') {
|
|
176
|
+
const subPath = segments.slice(1).join('/');
|
|
177
|
+
let file: any = undefined;
|
|
178
|
+
if (method === 'POST' && subPath === 'upload') {
|
|
179
|
+
const formData = await request.formData();
|
|
180
|
+
file = formData.get('file');
|
|
181
|
+
}
|
|
182
|
+
const result = await dispatcher.handleStorage(
|
|
183
|
+
subPath ? `/${subPath}` : '',
|
|
184
|
+
method,
|
|
185
|
+
file,
|
|
186
|
+
{ request },
|
|
187
|
+
);
|
|
188
|
+
return toResponse(result);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return errorJson('Not Found', 404);
|
|
192
|
+
} catch (err: any) {
|
|
193
|
+
return errorJson(err.message || 'Internal Server Error', err.statusCode || 500);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Creates a SvelteKit handle hook that attaches the kernel to event.locals.
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```ts
|
|
203
|
+
* // src/hooks.server.ts
|
|
204
|
+
* import { createHandle } from '@objectstack/sveltekit';
|
|
205
|
+
* export const handle = createHandle({ kernel });
|
|
206
|
+
* ```
|
|
207
|
+
*/
|
|
208
|
+
export function createHandle(options: SvelteKitAdapterOptions) {
|
|
209
|
+
return async function handle({ event, resolve }: { event: any; resolve: (event: any) => Promise<Response> }) {
|
|
210
|
+
event.locals.objectStack = options.kernel;
|
|
211
|
+
return resolve(event);
|
|
212
|
+
};
|
|
213
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
4
|
+
|
|
5
|
+
// Mock dispatcher instance
|
|
6
|
+
const mockDispatcher = {
|
|
7
|
+
getDiscoveryInfo: vi.fn().mockReturnValue({ version: '1.0', endpoints: [] }),
|
|
8
|
+
handleAuth: vi.fn().mockResolvedValue({ handled: true, response: { body: { ok: true }, status: 200 } }),
|
|
9
|
+
handleGraphQL: vi.fn().mockResolvedValue({ data: {} }),
|
|
10
|
+
handleMetadata: vi.fn().mockResolvedValue({ handled: true, response: { body: { objects: [] }, status: 200 } }),
|
|
11
|
+
handleData: vi.fn().mockResolvedValue({ handled: true, response: { body: { records: [] }, status: 200 } }),
|
|
12
|
+
handleStorage: vi.fn().mockResolvedValue({ handled: true, response: { body: {}, status: 200 } }),
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
vi.mock('@objectstack/runtime', () => {
|
|
16
|
+
return {
|
|
17
|
+
HttpDispatcher: function HttpDispatcher() {
|
|
18
|
+
return mockDispatcher;
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
import { createRequestHandler, createHandle } from './index';
|
|
24
|
+
|
|
25
|
+
const mockKernel = { name: 'test-kernel' } as any;
|
|
26
|
+
|
|
27
|
+
function makeEvent(url: string, method = 'GET', body?: any): any {
|
|
28
|
+
const parsedUrl = new URL(url, 'http://localhost');
|
|
29
|
+
const init: RequestInit = { method };
|
|
30
|
+
if (body) {
|
|
31
|
+
init.body = JSON.stringify(body);
|
|
32
|
+
init.headers = { 'Content-Type': 'application/json' };
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
request: new Request(parsedUrl, init),
|
|
36
|
+
url: parsedUrl,
|
|
37
|
+
params: {},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe('createRequestHandler', () => {
|
|
42
|
+
let handler: ReturnType<typeof createRequestHandler>;
|
|
43
|
+
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
vi.clearAllMocks();
|
|
46
|
+
handler = createRequestHandler({ kernel: mockKernel });
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('Discovery', () => {
|
|
50
|
+
it('GET /api returns discovery info', async () => {
|
|
51
|
+
const event = makeEvent('http://localhost/api');
|
|
52
|
+
const res = await handler(event);
|
|
53
|
+
expect(res.status).toBe(200);
|
|
54
|
+
const json = await res.json();
|
|
55
|
+
expect(json.data.version).toBe('1.0');
|
|
56
|
+
expect(mockDispatcher.getDiscoveryInfo).toHaveBeenCalledWith('/api');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('uses custom prefix', async () => {
|
|
60
|
+
const customHandler = createRequestHandler({ kernel: mockKernel, prefix: '/v2' });
|
|
61
|
+
const event = makeEvent('http://localhost/v2');
|
|
62
|
+
const res = await customHandler(event);
|
|
63
|
+
expect(res.status).toBe(200);
|
|
64
|
+
expect(mockDispatcher.getDiscoveryInfo).toHaveBeenCalledWith('/v2');
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('Auth', () => {
|
|
69
|
+
it('POST /api/auth/login calls handleAuth', async () => {
|
|
70
|
+
const event = makeEvent('http://localhost/api/auth/login', 'POST', { email: 'a@b.com' });
|
|
71
|
+
const res = await handler(event);
|
|
72
|
+
expect(res.status).toBe(200);
|
|
73
|
+
const json = await res.json();
|
|
74
|
+
expect(json.ok).toBe(true);
|
|
75
|
+
expect(mockDispatcher.handleAuth).toHaveBeenCalledWith(
|
|
76
|
+
'login', 'POST', { email: 'a@b.com' },
|
|
77
|
+
expect.objectContaining({ request: expect.anything() }),
|
|
78
|
+
);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('GET /api/auth/callback calls handleAuth with empty body', async () => {
|
|
82
|
+
const event = makeEvent('http://localhost/api/auth/callback');
|
|
83
|
+
const res = await handler(event);
|
|
84
|
+
expect(res.status).toBe(200);
|
|
85
|
+
expect(mockDispatcher.handleAuth).toHaveBeenCalledWith(
|
|
86
|
+
'callback', 'GET', {},
|
|
87
|
+
expect.objectContaining({ request: expect.anything() }),
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('returns error on exception', async () => {
|
|
92
|
+
mockDispatcher.handleAuth.mockRejectedValueOnce(
|
|
93
|
+
Object.assign(new Error('Unauthorized'), { statusCode: 401 }),
|
|
94
|
+
);
|
|
95
|
+
const event = makeEvent('http://localhost/api/auth/login', 'POST', {});
|
|
96
|
+
const res = await handler(event);
|
|
97
|
+
expect(res.status).toBe(401);
|
|
98
|
+
const json = await res.json();
|
|
99
|
+
expect(json.success).toBe(false);
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe('Auth via AuthPlugin service', () => {
|
|
104
|
+
it('uses kernel.getService("auth") when available', async () => {
|
|
105
|
+
const mockHandleRequest = vi.fn().mockResolvedValue(
|
|
106
|
+
new Response(JSON.stringify({ user: { id: '1' } }), {
|
|
107
|
+
status: 200,
|
|
108
|
+
headers: { 'Content-Type': 'application/json' },
|
|
109
|
+
}),
|
|
110
|
+
);
|
|
111
|
+
const kernelWithAuth = {
|
|
112
|
+
...mockKernel,
|
|
113
|
+
getService: vi.fn().mockReturnValue({ handleRequest: mockHandleRequest }),
|
|
114
|
+
};
|
|
115
|
+
const authHandler = createRequestHandler({ kernel: kernelWithAuth });
|
|
116
|
+
const event = makeEvent('http://localhost/api/auth/sign-in/email', 'POST', { email: 'a@b.com' });
|
|
117
|
+
const res = await authHandler(event);
|
|
118
|
+
expect(res.status).toBe(200);
|
|
119
|
+
expect(kernelWithAuth.getService).toHaveBeenCalledWith('auth');
|
|
120
|
+
expect(mockHandleRequest).toHaveBeenCalled();
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe('GraphQL', () => {
|
|
125
|
+
it('POST /api/graphql calls handleGraphQL', async () => {
|
|
126
|
+
const body = { query: '{ objects { name } }' };
|
|
127
|
+
const event = makeEvent('http://localhost/api/graphql', 'POST', body);
|
|
128
|
+
const res = await handler(event);
|
|
129
|
+
expect(res.status).toBe(200);
|
|
130
|
+
const json = await res.json();
|
|
131
|
+
expect(json.data).toBeDefined();
|
|
132
|
+
expect(mockDispatcher.handleGraphQL).toHaveBeenCalledWith(
|
|
133
|
+
body, expect.objectContaining({ request: expect.anything() }),
|
|
134
|
+
);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
describe('Metadata', () => {
|
|
139
|
+
it('GET /api/meta/objects calls handleMetadata', async () => {
|
|
140
|
+
const event = makeEvent('http://localhost/api/meta/objects');
|
|
141
|
+
const res = await handler(event);
|
|
142
|
+
expect(res.status).toBe(200);
|
|
143
|
+
expect(mockDispatcher.handleMetadata).toHaveBeenCalledWith(
|
|
144
|
+
'/objects',
|
|
145
|
+
expect.objectContaining({ request: expect.anything() }),
|
|
146
|
+
'GET', undefined,
|
|
147
|
+
);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe('Data', () => {
|
|
152
|
+
it('GET /api/data/account calls handleData', async () => {
|
|
153
|
+
const event = makeEvent('http://localhost/api/data/account');
|
|
154
|
+
const res = await handler(event);
|
|
155
|
+
expect(res.status).toBe(200);
|
|
156
|
+
const json = await res.json();
|
|
157
|
+
expect(json.records).toBeDefined();
|
|
158
|
+
expect(mockDispatcher.handleData).toHaveBeenCalledWith(
|
|
159
|
+
'/account', 'GET', {},
|
|
160
|
+
expect.any(Object),
|
|
161
|
+
expect.objectContaining({ request: expect.anything() }),
|
|
162
|
+
);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('POST /api/data/account parses body', async () => {
|
|
166
|
+
const body = { name: 'Acme' };
|
|
167
|
+
const event = makeEvent('http://localhost/api/data/account', 'POST', body);
|
|
168
|
+
const res = await handler(event);
|
|
169
|
+
expect(res.status).toBe(200);
|
|
170
|
+
expect(mockDispatcher.handleData).toHaveBeenCalledWith(
|
|
171
|
+
'/account', 'POST', body,
|
|
172
|
+
expect.any(Object),
|
|
173
|
+
expect.objectContaining({ request: expect.anything() }),
|
|
174
|
+
);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('returns 404 when not handled', async () => {
|
|
178
|
+
mockDispatcher.handleData.mockResolvedValueOnce({ handled: false });
|
|
179
|
+
const event = makeEvent('http://localhost/api/data/missing');
|
|
180
|
+
const res = await handler(event);
|
|
181
|
+
expect(res.status).toBe(404);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
describe('Storage', () => {
|
|
186
|
+
it('GET /api/storage/files calls handleStorage', async () => {
|
|
187
|
+
const event = makeEvent('http://localhost/api/storage/files');
|
|
188
|
+
const res = await handler(event);
|
|
189
|
+
expect(res.status).toBe(200);
|
|
190
|
+
expect(mockDispatcher.handleStorage).toHaveBeenCalledWith(
|
|
191
|
+
'/files', 'GET', undefined,
|
|
192
|
+
expect.objectContaining({ request: expect.anything() }),
|
|
193
|
+
);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
describe('Error handling', () => {
|
|
198
|
+
it('returns 404 for unknown routes', async () => {
|
|
199
|
+
const event = makeEvent('http://localhost/api/unknown');
|
|
200
|
+
const res = await handler(event);
|
|
201
|
+
expect(res.status).toBe(404);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('returns 500 on generic error', async () => {
|
|
205
|
+
mockDispatcher.handleData.mockRejectedValueOnce(new Error());
|
|
206
|
+
const event = makeEvent('http://localhost/api/data/account');
|
|
207
|
+
const res = await handler(event);
|
|
208
|
+
expect(res.status).toBe(500);
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
describe('toResponse', () => {
|
|
213
|
+
it('handles redirect result', async () => {
|
|
214
|
+
mockDispatcher.handleData.mockResolvedValueOnce({
|
|
215
|
+
handled: true,
|
|
216
|
+
result: { type: 'redirect', url: 'https://example.com' },
|
|
217
|
+
});
|
|
218
|
+
const event = makeEvent('http://localhost/api/data/redir');
|
|
219
|
+
const res = await handler(event);
|
|
220
|
+
expect(res.status).toBe(302);
|
|
221
|
+
expect(res.headers.get('location')).toBe('https://example.com');
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it('handles generic result objects', async () => {
|
|
225
|
+
mockDispatcher.handleData.mockResolvedValueOnce({
|
|
226
|
+
handled: true,
|
|
227
|
+
result: { foo: 'bar' },
|
|
228
|
+
});
|
|
229
|
+
const event = makeEvent('http://localhost/api/data/custom');
|
|
230
|
+
const res = await handler(event);
|
|
231
|
+
expect(res.status).toBe(200);
|
|
232
|
+
const json = await res.json();
|
|
233
|
+
expect(json.foo).toBe('bar');
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
describe('createHandle', () => {
|
|
239
|
+
it('attaches kernel to event.locals', async () => {
|
|
240
|
+
const handle = createHandle({ kernel: mockKernel });
|
|
241
|
+
const event: any = { locals: {} };
|
|
242
|
+
const resolve = vi.fn().mockResolvedValue(new Response('ok'));
|
|
243
|
+
|
|
244
|
+
await handle({ event, resolve });
|
|
245
|
+
|
|
246
|
+
expect(event.locals.objectStack).toBe(mockKernel);
|
|
247
|
+
expect(resolve).toHaveBeenCalledWith(event);
|
|
248
|
+
});
|
|
249
|
+
});
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"outDir": "./dist",
|
|
5
|
+
"rootDir": "./src",
|
|
6
|
+
"module": "NodeNext",
|
|
7
|
+
"moduleResolution": "NodeNext",
|
|
8
|
+
"esModuleInterop": true,
|
|
9
|
+
"skipLibCheck": true
|
|
10
|
+
},
|
|
11
|
+
"include": ["src/**/*"],
|
|
12
|
+
"exclude": ["node_modules", "dist"]
|
|
13
|
+
}
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { defineConfig } from 'vitest/config';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
export default defineConfig({
|
|
7
|
+
test: {
|
|
8
|
+
globals: true,
|
|
9
|
+
environment: 'node',
|
|
10
|
+
},
|
|
11
|
+
resolve: {
|
|
12
|
+
alias: {
|
|
13
|
+
'@objectstack/runtime': path.resolve(__dirname, 'src/__mocks__/runtime.ts'),
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
});
|