@valuya/bot-channel-server-core 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Valuya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # @valuya/bot-channel-server-core
2
+
3
+ Shared server/bootstrap helpers for gated bot-channel packages.
4
+
5
+ This package is intentionally small and transport-neutral. It provides:
6
+
7
+ - env helpers
8
+ - request body / path helpers
9
+ - internal JSON message endpoint handling
10
+ - OpenAI Responses API runner for schema-driven souls
11
+
12
+ Channel packages keep only their transport-specific webhook/polling glue on top.
@@ -0,0 +1,31 @@
1
+ export declare function requiredEnv(name: string): string;
2
+ export declare function getRequestPath(rawUrl?: string | null): string;
3
+ export declare function readRequestBody(req: AsyncIterable<unknown>): Promise<string>;
4
+ export declare function parseJsonBody(req: AsyncIterable<unknown>): Promise<Record<string, unknown>>;
5
+ export declare function resolveRequestUrl(args: {
6
+ headers: Record<string, string | string[] | undefined>;
7
+ url?: string | null;
8
+ }): string;
9
+ export declare function handleInternalJsonMessage(args: {
10
+ req: AsyncIterable<unknown>;
11
+ internalApiToken?: string;
12
+ providedToken?: string | null;
13
+ onMessage: (body: Record<string, unknown>) => Promise<{
14
+ reply: string;
15
+ metadata?: Record<string, unknown>;
16
+ }>;
17
+ }): Promise<{
18
+ status: number;
19
+ headers: Record<string, string>;
20
+ body: string;
21
+ }>;
22
+ export declare function createOpenAIResponsesRunner(args: {
23
+ apiKey: string;
24
+ model: string;
25
+ }): (input: {
26
+ system: string;
27
+ user: string;
28
+ }) => Promise<Record<string, unknown> | string>;
29
+ export declare function tryParseJson(value: string): Record<string, unknown> | null;
30
+ export declare function safeParseJson(response: Response): Promise<unknown>;
31
+ export declare function extractResponseObject(body: unknown): Record<string, unknown> | string;
package/dist/index.js ADDED
@@ -0,0 +1,125 @@
1
+ export function requiredEnv(name) {
2
+ const value = process.env[name]?.trim();
3
+ if (!value)
4
+ throw new Error(`${name}_required`);
5
+ return value;
6
+ }
7
+ export function getRequestPath(rawUrl) {
8
+ if (!rawUrl)
9
+ return "/";
10
+ try {
11
+ return new URL(rawUrl, "http://localhost").pathname;
12
+ }
13
+ catch {
14
+ return "/";
15
+ }
16
+ }
17
+ export async function readRequestBody(req) {
18
+ const chunks = [];
19
+ for await (const chunk of req) {
20
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
21
+ }
22
+ return Buffer.concat(chunks).toString("utf8");
23
+ }
24
+ export async function parseJsonBody(req) {
25
+ const raw = await readRequestBody(req);
26
+ if (!raw.trim())
27
+ return {};
28
+ const parsed = JSON.parse(raw);
29
+ return parsed && typeof parsed === "object" ? parsed : {};
30
+ }
31
+ export function resolveRequestUrl(args) {
32
+ const forwardedProto = normalizeHeaderValue(args.headers["x-forwarded-proto"]);
33
+ const forwardedHost = normalizeHeaderValue(args.headers["x-forwarded-host"]);
34
+ const host = normalizeHeaderValue(args.headers.host);
35
+ const proto = forwardedProto || "http";
36
+ const resolvedHost = forwardedHost || host || "localhost";
37
+ return `${proto}://${resolvedHost}${args.url || "/"}`;
38
+ }
39
+ export async function handleInternalJsonMessage(args) {
40
+ if (args.internalApiToken) {
41
+ const provided = String(args.providedToken || "").trim();
42
+ if (provided !== args.internalApiToken) {
43
+ return {
44
+ status: 401,
45
+ headers: { "Content-Type": "application/json" },
46
+ body: JSON.stringify({ ok: false, error: "unauthorized" }),
47
+ };
48
+ }
49
+ }
50
+ const body = await parseJsonBody(args.req);
51
+ const result = await args.onMessage(body);
52
+ return {
53
+ status: 200,
54
+ headers: { "Content-Type": "application/json" },
55
+ body: JSON.stringify({ ok: true, reply: result.reply, metadata: result.metadata || {} }),
56
+ };
57
+ }
58
+ export function createOpenAIResponsesRunner(args) {
59
+ return async (input) => {
60
+ const response = await fetch("https://api.openai.com/v1/responses", {
61
+ method: "POST",
62
+ headers: {
63
+ Authorization: `Bearer ${args.apiKey}`,
64
+ "Content-Type": "application/json",
65
+ },
66
+ body: JSON.stringify({
67
+ model: args.model,
68
+ input: [
69
+ { role: "system", content: input.system },
70
+ { role: "user", content: input.user },
71
+ ],
72
+ }),
73
+ });
74
+ const body = await safeParseJson(response);
75
+ if (!response.ok) {
76
+ throw new Error(`bot_channel_openai_failed:${response.status}:${JSON.stringify(body).slice(0, 300)}`);
77
+ }
78
+ return extractResponseObject(body);
79
+ };
80
+ }
81
+ export function tryParseJson(value) {
82
+ try {
83
+ const parsed = JSON.parse(value);
84
+ return parsed && typeof parsed === "object" ? parsed : null;
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ export async function safeParseJson(response) {
91
+ const text = await response.text();
92
+ if (!text.trim())
93
+ return {};
94
+ try {
95
+ return JSON.parse(text);
96
+ }
97
+ catch {
98
+ return { raw: text };
99
+ }
100
+ }
101
+ export function extractResponseObject(body) {
102
+ const record = body && typeof body === "object" ? body : {};
103
+ if (typeof record.output_text === "string" && record.output_text.trim()) {
104
+ const parsed = tryParseJson(record.output_text);
105
+ return parsed || record.output_text.trim();
106
+ }
107
+ const output = Array.isArray(record.output) ? record.output : [];
108
+ const chunks = [];
109
+ for (const item of output) {
110
+ const content = Array.isArray(item?.content)
111
+ ? item.content
112
+ : [];
113
+ for (const part of content) {
114
+ if (typeof part.text === "string" && part.text.trim())
115
+ chunks.push(part.text.trim());
116
+ }
117
+ }
118
+ const text = chunks.join("\n").trim();
119
+ return tryParseJson(text) || text;
120
+ }
121
+ function normalizeHeaderValue(value) {
122
+ if (Array.isArray(value))
123
+ return String(value[0] || "").split(",")[0]?.trim() || "";
124
+ return String(value || "").split(",")[0]?.trim() || "";
125
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@valuya/bot-channel-server-core",
3
+ "version": "0.2.0-beta.1",
4
+ "description": "Shared server/bootstrap helpers for gated bot-channel packages",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "devDependencies": {
19
+ "@types/node": "^25.0.10"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "tag": "next"
24
+ },
25
+ "license": "MIT",
26
+ "scripts": {
27
+ "build": "rm -rf dist && tsc -p tsconfig.json",
28
+ "test": "pnpm run build && node --test dist/*.test.js"
29
+ }
30
+ }