@skein-js/nextjs 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +67 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +291 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the 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 [yyyy] [name of copyright owner]
|
|
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,67 @@
|
|
|
1
|
+
# @skein-js/nextjs
|
|
2
|
+
|
|
3
|
+
> Next.js adapter for skein-js — serve the [Agent Protocol](https://github.com/langchain-ai/agent-protocol) from Next.js API routes.
|
|
4
|
+
|
|
5
|
+
Part of **[skein-js](../../README.md)** — a TypeScript Agent Protocol server for [LangGraph.js](https://github.com/langchain-ai/langgraphjs), and a drop-in replacement for the LangGraph CLI.
|
|
6
|
+
|
|
7
|
+
A thin transport shim over the framework-agnostic [`@skein-js/agent-protocol`](../agent-protocol)
|
|
8
|
+
handler table — it adds no protocol logic. Mount the protocol **same-origin** inside an existing
|
|
9
|
+
Next.js app (no separate server, no CORS), ideal for small/medium graphs shipped alongside your
|
|
10
|
+
frontend. Supports both the **App Router** and the **Pages Router**.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm i @skein-js/nextjs @langchain/langgraph
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## App Router (recommended)
|
|
19
|
+
|
|
20
|
+
A catch-all route re-exports the per-method handlers:
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
// app/api/[...path]/route.ts
|
|
24
|
+
import { createSkeinRouteHandlers } from "@skein-js/nextjs";
|
|
25
|
+
|
|
26
|
+
export const runtime = "nodejs"; // the background run worker needs a long-lived Node process
|
|
27
|
+
export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } = createSkeinRouteHandlers({
|
|
28
|
+
config: "./langgraph.json",
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Point a browser client at the same origin — no CORS needed:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { useStream } from "@langchain/langgraph-sdk/react";
|
|
36
|
+
const thread = useStream({ apiUrl: "/api", assistantId: "agent" });
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Pages Router
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// pages/api/[...path].ts
|
|
43
|
+
import { createSkeinPagesHandler } from "@skein-js/nextjs";
|
|
44
|
+
|
|
45
|
+
// Let Next know this route settles the response itself (needed for SSE streaming).
|
|
46
|
+
export const config = { api: { bodyParser: true, externalResolver: true } };
|
|
47
|
+
export default createSkeinPagesHandler({ config: "./langgraph.json" });
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Both entry points accept the shared `{ config } | { deps }` seam, an optional `cors` (off by default),
|
|
51
|
+
and a `basePath` (defaults to `/api`, matching the mount above).
|
|
52
|
+
|
|
53
|
+
## Deployment caveat
|
|
54
|
+
|
|
55
|
+
The background run worker and the in-memory driver need a **long-lived Node process** — fine on
|
|
56
|
+
`next start` with `runtime = "nodejs"`. For serverless/edge deploys, back skein with the
|
|
57
|
+
[Redis queue](../runtime-redis) + [Postgres store](../storage-postgres) (pass `{ deps }` from
|
|
58
|
+
[`@skein-js/runtime`](../runtime)'s `buildRuntime`) so state and runs don't depend on one process.
|
|
59
|
+
|
|
60
|
+
## Learn more
|
|
61
|
+
|
|
62
|
+
- [`@skein-js/express`](../server-express) — the reference adapter
|
|
63
|
+
- [Building your own adapter](../../docs/building-an-adapter.md) · [skein-js overview](../../docs/index.md)
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
[Apache-2.0](../../LICENSE)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { SkeinRuntimeOptions, ResolvedProtocolRuntime } from '@skein-js/server-kit';
|
|
2
|
+
export { SkeinRuntimeOptions, sendNodeError, sendNodeResponse } from '@skein-js/server-kit';
|
|
3
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import { ProtocolResponse, Logger } from '@skein-js/agent-protocol';
|
|
5
|
+
|
|
6
|
+
/** Options for the App Router handlers: the shared runtime options plus where the catch-all is mounted. */
|
|
7
|
+
type SkeinRouteHandlerOptions = SkeinRuntimeOptions & {
|
|
8
|
+
/**
|
|
9
|
+
* The path the catch-all route is mounted at, stripped before matching the protocol route table.
|
|
10
|
+
* Defaults to `/api` (i.e. `app/api/[...path]/route.ts`). Set to `""` or `/` if you mount the
|
|
11
|
+
* catch-all at the app root.
|
|
12
|
+
*/
|
|
13
|
+
basePath?: string;
|
|
14
|
+
};
|
|
15
|
+
/** A single Route Handler: takes the Web `Request` and returns a Web `Response`. */
|
|
16
|
+
type SkeinRouteHandler = (request: Request) => Promise<Response>;
|
|
17
|
+
interface SkeinRouteHandlers {
|
|
18
|
+
GET: SkeinRouteHandler;
|
|
19
|
+
POST: SkeinRouteHandler;
|
|
20
|
+
PUT: SkeinRouteHandler;
|
|
21
|
+
PATCH: SkeinRouteHandler;
|
|
22
|
+
DELETE: SkeinRouteHandler;
|
|
23
|
+
OPTIONS: SkeinRouteHandler;
|
|
24
|
+
}
|
|
25
|
+
/** Build the App Router Route Handlers for the given options. */
|
|
26
|
+
declare function createSkeinRouteHandlers(options: SkeinRouteHandlerOptions): SkeinRouteHandlers;
|
|
27
|
+
|
|
28
|
+
/** Options for the Pages Router handler: shared runtime options plus the catch-all mount path. */
|
|
29
|
+
type SkeinPagesHandlerOptions = SkeinRuntimeOptions & {
|
|
30
|
+
/** The path the catch-all is mounted at (stripped before matching). Defaults to `/api`. */
|
|
31
|
+
basePath?: string;
|
|
32
|
+
};
|
|
33
|
+
/** The subset of a Next.js API request the adapter reads (structural, so no `next` type dependency). */
|
|
34
|
+
type SkeinPagesRequest = IncomingMessage & {
|
|
35
|
+
body?: unknown;
|
|
36
|
+
query?: Partial<Record<string, string | string[]>>;
|
|
37
|
+
};
|
|
38
|
+
/** A Next.js API route handler. Assignable to Next's `NextApiHandler`. */
|
|
39
|
+
type SkeinPagesHandler = (req: SkeinPagesRequest, res: ServerResponse) => Promise<void>;
|
|
40
|
+
/** Build the Pages Router API handler for the given options. */
|
|
41
|
+
declare function createSkeinPagesHandler(options: SkeinPagesHandlerOptions): SkeinPagesHandler;
|
|
42
|
+
|
|
43
|
+
type RuntimePromise = Promise<ResolvedProtocolRuntime>;
|
|
44
|
+
/** Resolve (once) the runtime for these options, reusing the cached promise across module reloads. */
|
|
45
|
+
declare function getSkeinRuntime(options: SkeinRuntimeOptions): RuntimePromise;
|
|
46
|
+
|
|
47
|
+
/** Serialize a `ProtocolResponse` into a Web `Response`, merging any `extraHeaders` (e.g. CORS). */
|
|
48
|
+
declare function toWebResponse(response: ProtocolResponse, extraHeaders?: Record<string, string>): Response;
|
|
49
|
+
/** Map a thrown error onto a Web `Response` — `SkeinHttpError` to its status, else a logged 500. */
|
|
50
|
+
declare function webErrorResponse(error: unknown, extraHeaders?: Record<string, string>, logger?: Logger): Response;
|
|
51
|
+
|
|
52
|
+
export { type SkeinPagesHandler, type SkeinPagesHandlerOptions, type SkeinPagesRequest, type SkeinRouteHandler, type SkeinRouteHandlerOptions, type SkeinRouteHandlers, createSkeinPagesHandler, createSkeinRouteHandlers, getSkeinRuntime, toWebResponse, webErrorResponse };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// src/create-route-handlers.ts
|
|
2
|
+
import { foldThreadId, matchSkeinRoute } from "@skein-js/agent-protocol";
|
|
3
|
+
import { SkeinHttpError } from "@skein-js/core";
|
|
4
|
+
|
|
5
|
+
// src/runtime-singleton.ts
|
|
6
|
+
import {
|
|
7
|
+
resolveProtocolRuntime
|
|
8
|
+
} from "@skein-js/server-kit";
|
|
9
|
+
var CONFIG_CACHE_KEY = /* @__PURE__ */ Symbol.for("skein.nextjs.configRuntimeCache");
|
|
10
|
+
var DEPS_CACHE_KEY = /* @__PURE__ */ Symbol.for("skein.nextjs.depsRuntimeCache");
|
|
11
|
+
function configCache() {
|
|
12
|
+
const store = globalThis;
|
|
13
|
+
store[CONFIG_CACHE_KEY] ??= /* @__PURE__ */ new Map();
|
|
14
|
+
return store[CONFIG_CACHE_KEY];
|
|
15
|
+
}
|
|
16
|
+
function depsCache() {
|
|
17
|
+
const store = globalThis;
|
|
18
|
+
store[DEPS_CACHE_KEY] ??= /* @__PURE__ */ new WeakMap();
|
|
19
|
+
return store[DEPS_CACHE_KEY];
|
|
20
|
+
}
|
|
21
|
+
function resolveOnce(cache, key, options) {
|
|
22
|
+
let resolved = cache.get(key);
|
|
23
|
+
if (!resolved) {
|
|
24
|
+
resolved = resolveProtocolRuntime(options).catch((error) => {
|
|
25
|
+
cache.delete(key);
|
|
26
|
+
throw error;
|
|
27
|
+
});
|
|
28
|
+
cache.set(key, resolved);
|
|
29
|
+
}
|
|
30
|
+
return resolved;
|
|
31
|
+
}
|
|
32
|
+
function getSkeinRuntime(options) {
|
|
33
|
+
if (typeof options.config === "string") {
|
|
34
|
+
return resolveOnce(configCache(), options.config, options);
|
|
35
|
+
}
|
|
36
|
+
return resolveOnce(depsCache(), options.deps, options);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/send-web-response.ts
|
|
40
|
+
import { SSE_HEADERS } from "@skein-js/agent-protocol";
|
|
41
|
+
import { isSkeinHttpError, serializeWireJson } from "@skein-js/core";
|
|
42
|
+
function sseStream(events) {
|
|
43
|
+
const iterator = events[Symbol.asyncIterator]();
|
|
44
|
+
const encoder = new TextEncoder();
|
|
45
|
+
return new ReadableStream({
|
|
46
|
+
async pull(controller) {
|
|
47
|
+
try {
|
|
48
|
+
const next = await iterator.next();
|
|
49
|
+
if (next.done) {
|
|
50
|
+
controller.close();
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
controller.enqueue(encoder.encode(next.value));
|
|
54
|
+
} catch (error) {
|
|
55
|
+
controller.error(error);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
async cancel() {
|
|
59
|
+
await iterator.return?.(void 0);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function toWebResponse(response, extraHeaders = {}) {
|
|
64
|
+
switch (response.kind) {
|
|
65
|
+
case "json":
|
|
66
|
+
return new Response(serializeWireJson(response.body), {
|
|
67
|
+
status: response.status,
|
|
68
|
+
headers: { "content-type": "application/json", ...extraHeaders }
|
|
69
|
+
});
|
|
70
|
+
case "empty":
|
|
71
|
+
return new Response(null, { status: response.status, headers: extraHeaders });
|
|
72
|
+
case "sse":
|
|
73
|
+
return new Response(sseStream(response.events), {
|
|
74
|
+
status: response.status,
|
|
75
|
+
headers: { ...SSE_HEADERS, ...extraHeaders }
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function webErrorResponse(error, extraHeaders = {}, logger) {
|
|
80
|
+
const headers = { "content-type": "application/json", ...extraHeaders };
|
|
81
|
+
if (isSkeinHttpError(error)) {
|
|
82
|
+
return new Response(
|
|
83
|
+
JSON.stringify({
|
|
84
|
+
status: error.status,
|
|
85
|
+
message: error.message,
|
|
86
|
+
...error.code !== void 0 ? { code: error.code } : {},
|
|
87
|
+
...error.details !== void 0 ? { details: error.details } : {}
|
|
88
|
+
}),
|
|
89
|
+
{ status: error.status, headers }
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
logger?.error("Unhandled error in the skein Next.js adapter.", error);
|
|
93
|
+
return new Response(JSON.stringify({ status: 500, message: "Internal Server Error" }), {
|
|
94
|
+
status: 500,
|
|
95
|
+
headers
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/web-cors.ts
|
|
100
|
+
import { corsPreflightHeaders, corsResponseHeaders } from "@skein-js/server-kit";
|
|
101
|
+
function corsHeaders(request, cors) {
|
|
102
|
+
return corsResponseHeaders(request.headers.get("origin") ?? void 0, cors);
|
|
103
|
+
}
|
|
104
|
+
function preflightResponse(request, cors) {
|
|
105
|
+
const headers = corsPreflightHeaders(
|
|
106
|
+
request.headers.get("origin") ?? void 0,
|
|
107
|
+
request.headers.get("access-control-request-headers") ?? void 0,
|
|
108
|
+
cors
|
|
109
|
+
);
|
|
110
|
+
return new Response(null, { status: 204, headers });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/create-route-handlers.ts
|
|
114
|
+
function stripBasePath(pathname, basePath) {
|
|
115
|
+
if (basePath === "" || basePath === "/") return pathname;
|
|
116
|
+
if (pathname === basePath) return "/";
|
|
117
|
+
if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
function toQuery(url) {
|
|
121
|
+
const query = {};
|
|
122
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
123
|
+
const all = url.searchParams.getAll(key);
|
|
124
|
+
query[key] = all.length > 1 ? all : all[0];
|
|
125
|
+
}
|
|
126
|
+
return query;
|
|
127
|
+
}
|
|
128
|
+
async function toProtocolRequest(request, url, skeinPathname, params) {
|
|
129
|
+
let body;
|
|
130
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
131
|
+
const text = await request.text();
|
|
132
|
+
try {
|
|
133
|
+
body = text ? JSON.parse(text) : {};
|
|
134
|
+
} catch {
|
|
135
|
+
throw SkeinHttpError.badRequest("Request body is not valid JSON.");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
method: request.method,
|
|
140
|
+
// Report the skein-relative absolute URL (mount prefix stripped) so auth handlers see the same
|
|
141
|
+
// path shape the other adapters produce.
|
|
142
|
+
url: `${url.origin}${skeinPathname}${url.search}`,
|
|
143
|
+
params,
|
|
144
|
+
query: toQuery(url),
|
|
145
|
+
body,
|
|
146
|
+
headers: Object.fromEntries(request.headers)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function createSkeinRouteHandlers(options) {
|
|
150
|
+
const basePath = options.basePath ?? "/api";
|
|
151
|
+
const logger = options.logger;
|
|
152
|
+
const dispatchRequest = async (request) => {
|
|
153
|
+
const url = new URL(request.url);
|
|
154
|
+
const skeinPathname = stripBasePath(url.pathname, basePath);
|
|
155
|
+
if (skeinPathname === null) return new Response(null, { status: 404 });
|
|
156
|
+
let resolved;
|
|
157
|
+
try {
|
|
158
|
+
resolved = await getSkeinRuntime(options);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
return webErrorResponse(error, {}, logger);
|
|
161
|
+
}
|
|
162
|
+
const cors = options.cors ?? resolved.cors;
|
|
163
|
+
if (request.method === "OPTIONS") {
|
|
164
|
+
return cors ? preflightResponse(request, cors) : new Response(null, { status: 404 });
|
|
165
|
+
}
|
|
166
|
+
const extraHeaders = cors ? corsHeaders(request, cors) : {};
|
|
167
|
+
const match = matchSkeinRoute(request.method, skeinPathname);
|
|
168
|
+
if (!match) {
|
|
169
|
+
return new Response(JSON.stringify({ status: 404, message: "Not Found" }), {
|
|
170
|
+
status: 404,
|
|
171
|
+
headers: { "content-type": "application/json", ...extraHeaders }
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
const request_ = await toProtocolRequest(request, url, skeinPathname, match.params);
|
|
176
|
+
const invoke = resolved.runtime.handlers[match.binding.handler];
|
|
177
|
+
const response = await invoke(
|
|
178
|
+
match.binding.foldThreadIdIntoBody ? foldThreadId(request_) : request_
|
|
179
|
+
);
|
|
180
|
+
return toWebResponse(response, extraHeaders);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
return webErrorResponse(error, extraHeaders, logger);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
return {
|
|
186
|
+
GET: dispatchRequest,
|
|
187
|
+
POST: dispatchRequest,
|
|
188
|
+
PUT: dispatchRequest,
|
|
189
|
+
PATCH: dispatchRequest,
|
|
190
|
+
DELETE: dispatchRequest,
|
|
191
|
+
OPTIONS: dispatchRequest
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/create-pages-handler.ts
|
|
196
|
+
import { foldThreadId as foldThreadId2, matchSkeinRoute as matchSkeinRoute2 } from "@skein-js/agent-protocol";
|
|
197
|
+
import {
|
|
198
|
+
applyNodeCors,
|
|
199
|
+
sendNodeError,
|
|
200
|
+
sendNodePreflight,
|
|
201
|
+
sendNodeResponse
|
|
202
|
+
} from "@skein-js/server-kit";
|
|
203
|
+
function stripBasePath2(pathname, basePath) {
|
|
204
|
+
if (basePath === "" || basePath === "/") return pathname;
|
|
205
|
+
if (pathname === basePath) return "/";
|
|
206
|
+
if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
function toQuery2(url) {
|
|
210
|
+
const query = {};
|
|
211
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
212
|
+
const all = url.searchParams.getAll(key);
|
|
213
|
+
query[key] = all.length > 1 ? all : all[0];
|
|
214
|
+
}
|
|
215
|
+
return query;
|
|
216
|
+
}
|
|
217
|
+
function toSingleValueHeaders(headers) {
|
|
218
|
+
const flattened = {};
|
|
219
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
220
|
+
flattened[name] = Array.isArray(value) ? value[0] : value;
|
|
221
|
+
}
|
|
222
|
+
return flattened;
|
|
223
|
+
}
|
|
224
|
+
function createSkeinPagesHandler(options) {
|
|
225
|
+
const basePath = options.basePath ?? "/api";
|
|
226
|
+
const logger = options.logger;
|
|
227
|
+
return async (req, res) => {
|
|
228
|
+
const host = req.headers.host ?? "localhost";
|
|
229
|
+
let url;
|
|
230
|
+
try {
|
|
231
|
+
url = new URL(req.url ?? "/", `http://${host}`);
|
|
232
|
+
} catch {
|
|
233
|
+
res.writeHead(400).end();
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const skeinPathname = stripBasePath2(url.pathname, basePath);
|
|
237
|
+
if (skeinPathname === null) {
|
|
238
|
+
res.writeHead(404).end();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
let resolved;
|
|
242
|
+
try {
|
|
243
|
+
resolved = await getSkeinRuntime(options);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
sendNodeError(error, res, logger, "skein Next.js");
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const cors = options.cors ?? resolved.cors;
|
|
249
|
+
if ((req.method ?? "GET").toUpperCase() === "OPTIONS") {
|
|
250
|
+
if (cors) sendNodePreflight(req.headers, res, cors);
|
|
251
|
+
else res.writeHead(404).end();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (cors) applyNodeCors(req.headers, res, cors);
|
|
255
|
+
const match = matchSkeinRoute2(req.method ?? "GET", skeinPathname);
|
|
256
|
+
if (!match) {
|
|
257
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
258
|
+
res.end(JSON.stringify({ status: 404, message: "Not Found" }));
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const request = {
|
|
263
|
+
method: req.method ?? "GET",
|
|
264
|
+
url: `${url.origin}${skeinPathname}${url.search}`,
|
|
265
|
+
params: match.params,
|
|
266
|
+
query: toQuery2(url),
|
|
267
|
+
body: req.body,
|
|
268
|
+
headers: toSingleValueHeaders(req.headers)
|
|
269
|
+
};
|
|
270
|
+
const invoke = resolved.runtime.handlers[match.binding.handler];
|
|
271
|
+
const response = await invoke(
|
|
272
|
+
match.binding.foldThreadIdIntoBody ? foldThreadId2(request) : request
|
|
273
|
+
);
|
|
274
|
+
await sendNodeResponse(response, res);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
sendNodeError(error, res, logger, "skein Next.js");
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// src/index.ts
|
|
282
|
+
import { sendNodeResponse as sendNodeResponse2, sendNodeError as sendNodeError2 } from "@skein-js/server-kit";
|
|
283
|
+
export {
|
|
284
|
+
createSkeinPagesHandler,
|
|
285
|
+
createSkeinRouteHandlers,
|
|
286
|
+
getSkeinRuntime,
|
|
287
|
+
sendNodeError2 as sendNodeError,
|
|
288
|
+
sendNodeResponse2 as sendNodeResponse,
|
|
289
|
+
toWebResponse,
|
|
290
|
+
webErrorResponse
|
|
291
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@skein-js/nextjs",
|
|
3
|
+
"version": "0.6.1",
|
|
4
|
+
"description": "Next.js adapter for skein-js — serve the Agent Protocol from App Router or Pages Router API routes.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Maina Wycliffe <wmmaina7@gmail.com>",
|
|
7
|
+
"homepage": "https://github.com/mainawycliffe/skein-js/tree/main/packages/server-nextjs#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/mainawycliffe/skein-js.git",
|
|
11
|
+
"directory": "packages/server-nextjs"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/mainawycliffe/skein-js/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"typescript",
|
|
18
|
+
"nextjs",
|
|
19
|
+
"langgraph",
|
|
20
|
+
"agent-protocol",
|
|
21
|
+
"sse"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"module": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"import": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"README.md"
|
|
37
|
+
],
|
|
38
|
+
"sideEffects": false,
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=20"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@skein-js/core": "0.6.1",
|
|
44
|
+
"@skein-js/server-kit": "0.6.1",
|
|
45
|
+
"@skein-js/agent-protocol": "0.6.1"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@langchain/langgraph": "^1.4.0",
|
|
49
|
+
"next": ">=14.0.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@langchain/core": "^1.2.0",
|
|
53
|
+
"@langchain/langgraph": "^1.4.0",
|
|
54
|
+
"@skein-js/storage-memory": "0.6.1"
|
|
55
|
+
},
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
}
|
|
59
|
+
}
|