@omem-ai/plugin-sdk 0.0.0-stage → 0.0.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/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @omem-ai/plugin-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The SDK for [omem](https://github.com/lejunyang/omem) plugins. A plugin's page runs in a sandboxed
4
+ iframe inside omem; this is how it talks to omem.
5
+
6
+ ```ts
7
+ import { connect } from "@omem-ai/plugin-sdk";
8
+
9
+ const omem = await connect(); // waits for the shell: theme, route params
10
+ const sessions = await omem.get("sessions");
11
+ omem.on((event) => { /* this plugin's server events */ });
12
+ const live = omem.stream("live"); // a WebSocket to the plugin's service, through omem
13
+ // In a click handler, with `voice: true` in plugin.yaml: a conversation with omem's voice model.
14
+ const call = await omem.voice({ instructions: "Play a waiter…", onTurns: (turns) => draw(turns) });
15
+ const { transcript } = await call.stop();
16
+ ```
17
+
18
+ - `@omem-ai/plugin-sdk`: `connect()` → `get` / `post` (only `/api/plugins/<this plugin>/…`), `on`,
19
+ `navigate`, `openSettings`, `stream`, `voice` / `voiceStatus` (omem holds the microphone and the
20
+ connection; the page gets the transcript only), and `renderBlock` / `renderView` for the agent's questions (forms) and views (tables, charts, comparisons) in a session.
21
+ - `@omem-ai/plugin-sdk/blocks`: `renderBlock` and `renderView` alone, without a framework.
22
+ - `@omem-ai/plugin-sdk/service`: for a plugin's service (Node): `serve({ http, socket })` on
23
+ `127.0.0.1:OMEM_SERVICE_PORT`, refusing requests without omem's token.
24
+
25
+ omem's styles (buttons, inputs, cards, theme tokens) are at `/plugins/_sdk/omem.css` on the omem
26
+ server. Plugins in omem's data directory need not install this package: omem serves the same SDK at
27
+ `/plugins/_sdk/omem.js` and passes the service helper's path in `OMEM_SERVICE_SDK`.
28
+
29
+ The plugin format: [docs/v2/plugins.md](https://github.com/lejunyang/omem/blob/main/docs/v2/plugins.md).
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Component blocks (docs/v2/interactive-ui.md), rendered without a framework so omem's web pages,
3
+ * the shell's default plugin page and any plugin page draw them the same way:
4
+ *
5
+ * - `renderView`: display components (Markdown, heading, table, chart, metric, compare, timeline).
6
+ * - `renderBlock`: a block of a plugin session — kind "view" (what an agent showed) or "ask" (its
7
+ * question, with a form when it has fields). omem's own pages draw a question's fields with their
8
+ * own controls (web/src/components/UiFields.vue); plugin pages use the plain ones here.
9
+ *
10
+ * Text goes in through textContent only, unless the caller passes a Markdown renderer that
11
+ * sanitizes. Colors come from omem's tokens; series colors are the validated categorical slots for
12
+ * light and dark surfaces.
13
+ */
14
+ export type BlockView = {
15
+ id: string;
16
+ kind: string;
17
+ status: "open" | "submitted" | "shown";
18
+ data: any;
19
+ answers: Record<string, unknown> | null;
20
+ result: any;
21
+ };
22
+ /** Block kinds the host draws (the rest are a plugin's own, e.g. the English plugin's quiz). */
23
+ export declare const GENERIC_KINDS: string[];
24
+ export type Card = {
25
+ id: string;
26
+ title: string;
27
+ summary?: string;
28
+ pros?: string[];
29
+ cons?: string[];
30
+ };
31
+ export type ViewComponent = {
32
+ type: "markdown";
33
+ text: string;
34
+ } | {
35
+ type: "heading";
36
+ text: string;
37
+ } | {
38
+ type: "table";
39
+ title?: string;
40
+ columns: string[];
41
+ rows: (string | number | boolean | null)[][];
42
+ note?: string;
43
+ } | {
44
+ type: "chart";
45
+ title: string;
46
+ kind: "bar" | "line" | "pie";
47
+ labels: string[];
48
+ series: {
49
+ name: string;
50
+ values: number[];
51
+ }[];
52
+ unit?: string;
53
+ note?: string;
54
+ } | {
55
+ type: "metric";
56
+ items: {
57
+ label: string;
58
+ value: string | number;
59
+ unit?: string;
60
+ change?: string;
61
+ }[];
62
+ } | {
63
+ type: "compare";
64
+ title?: string;
65
+ items: Card[];
66
+ } | {
67
+ type: "timeline";
68
+ items: {
69
+ time: string;
70
+ title: string;
71
+ text?: string;
72
+ }[];
73
+ }
74
+ /** An interactive page (`ui_page`): drawn by omem's own pages only; elsewhere a line that says where to open it. */
75
+ | {
76
+ type: "page";
77
+ id: string;
78
+ version?: number;
79
+ height?: number;
80
+ title?: string;
81
+ };
82
+ type ShowIf = {
83
+ field: string;
84
+ equals?: string | number | boolean;
85
+ in?: string[];
86
+ };
87
+ export type UiField = {
88
+ id: string;
89
+ label: string;
90
+ help?: string;
91
+ required?: boolean;
92
+ show_if?: ShowIf;
93
+ } & ({
94
+ type: "text" | "textarea";
95
+ placeholder?: string;
96
+ default?: string;
97
+ } | {
98
+ type: "number";
99
+ min?: number;
100
+ max?: number;
101
+ default?: number;
102
+ } | {
103
+ type: "choice";
104
+ options: string[];
105
+ default?: string;
106
+ } | {
107
+ type: "multi";
108
+ options: string[];
109
+ default?: string[];
110
+ } | {
111
+ type: "scale" | "date" | "datetime";
112
+ } | {
113
+ type: "toggle";
114
+ default?: boolean;
115
+ } | {
116
+ type: "pick";
117
+ items: Card[];
118
+ } | {
119
+ type: "checklist";
120
+ items: {
121
+ id: string;
122
+ title: string;
123
+ detail?: string;
124
+ }[];
125
+ choices: string[];
126
+ note: boolean;
127
+ } | {
128
+ type: "rank";
129
+ items: {
130
+ id: string;
131
+ title: string;
132
+ detail?: string;
133
+ }[];
134
+ } | {
135
+ type: "table";
136
+ columns: {
137
+ id: string;
138
+ label: string;
139
+ type: "text" | "number" | "choice";
140
+ options?: string[];
141
+ }[];
142
+ rows: Record<string, string | number | null>[];
143
+ max_rows: number;
144
+ });
145
+ export type RenderOptions = {
146
+ /** Draw Markdown into an element (sanitized by the caller); plain text with line breaks otherwise. */
147
+ markdown?: (el: HTMLElement, source: string) => void;
148
+ };
149
+ /** Draw `block` into `el` (replacing what is there). False when the kind is not a host block. */
150
+ export declare function renderBlock(el: HTMLElement, block: BlockView, opts: {
151
+ submit: (answers: Record<string, unknown>) => Promise<void>;
152
+ } & RenderOptions): boolean;
153
+ /** Draw display components into `el` (replacing what is there). */
154
+ export declare function renderView(el: HTMLElement, components: ViewComponent[], opts?: RenderOptions, owner?: HTMLElement): void;
155
+ /** Whether a field shows, given the values so far (docs/v2/interactive-ui.md, show_if). */
156
+ export declare function fieldVisible(f: UiField, values: Record<string, unknown>): boolean;
157
+ /** A field's starting value: its default, if it has one. */
158
+ export declare function initialValues(fields: UiField[]): Record<string, unknown>;
159
+ export {};
package/dist/blocks.js ADDED
@@ -0,0 +1,345 @@
1
+ const P = ["ask", "view"], Z = `
2
+ .ob { display: grid; gap: 12px; min-width: 0; color: var(--ink); }
3
+ .ob h3 { margin: 0; font: 600 16px/1.35 var(--serif); }
4
+ .ob h4 { margin: 4px 0 0; font: 600 14.5px/1.4 var(--serif); }
5
+ .ob p { margin: 0; }
6
+ .ob .ob-text { white-space: pre-wrap; overflow-wrap: anywhere; }
7
+ .ob .ob-muted { color: var(--muted); font-size: 12.5px; }
8
+ .ob .ob-field { display: grid; gap: 6px; min-width: 0; }
9
+ .ob .ob-label { font-weight: 550; overflow-wrap: anywhere; }
10
+ .ob .ob-req { color: var(--danger); margin-left: 2px; }
11
+ .ob .ob-options { display: flex; flex-wrap: wrap; gap: 6px; }
12
+ .ob .ob-opt { border-radius: 999px; font-weight: 400; }
13
+ .ob .ob-opt[aria-pressed="true"], .ob .ob-opt[aria-checked="true"], .ob .ob-opt[aria-pressed="true"]:hover, .ob .ob-opt[aria-checked="true"]:hover { border-color: var(--ink); background: var(--ink); color: var(--bg); }
14
+ .ob .ob-field > button, .ob .ob-field > input[type="number"], .ob .ob-field > input[type="date"], .ob .ob-field > input[type="datetime-local"] { justify-self: start; }
15
+ .ob .ob-field > input[type="number"] { width: 200px; max-width: 100%; }
16
+ .ob .ob-field > input[type="date"], .ob .ob-field > input[type="datetime-local"] { width: auto; max-width: 100%; }
17
+ .ob .ob-foot { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
18
+ .ob .ob-spacer { flex: 1; }
19
+ .ob .ob-err { color: var(--danger); font-size: 12.5px; }
20
+ .ob .ob-value { color: var(--ink-2); overflow-wrap: anywhere; white-space: pre-wrap; }
21
+ .ob svg { width: 100%; height: auto; display: block; overflow: visible; }
22
+ .ob .ob-axis { stroke: var(--line-strong); stroke-width: 1; }
23
+ .ob .ob-grid { stroke: var(--line); stroke-width: 1; }
24
+ .ob .ob-tick { fill: var(--muted); font-size: 11px; font-family: var(--sans); }
25
+ .ob .ob-legend { display: flex; flex-wrap: wrap; gap: 12px; font-size: 12.5px; color: var(--ink-2); }
26
+ .ob .ob-key { display: inline-flex; align-items: center; gap: 6px; }
27
+ .ob .ob-key i { width: 10px; height: 10px; border-radius: 2px; display: inline-block; }
28
+ .ob details summary { cursor: pointer; color: var(--muted); font-size: 12.5px; }
29
+ .ob .ob-scroll { overflow-x: auto; max-width: 100%; }
30
+ .ob table { border-collapse: collapse; font-size: 12.5px; margin-top: 6px; }
31
+ .ob th, .ob td { border-bottom: 1px solid var(--line); padding: 4px 12px 4px 0; text-align: left; font-weight: 400; vertical-align: top; }
32
+ .ob thead th { color: var(--muted); font-weight: 550; white-space: nowrap; }
33
+ .ob thead th button { all: unset; cursor: pointer; }
34
+ .ob thead th button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
35
+ .ob td.num { text-align: right; font-variant-numeric: tabular-nums; }
36
+ .ob .ob-metrics { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; }
37
+ .ob .ob-metric { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; display: grid; gap: 2px; min-width: 0; }
38
+ .ob .ob-metric b { font: 600 20px/1.2 var(--sans); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
39
+ .ob .ob-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; }
40
+ .ob .ob-pcard { border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; display: grid; gap: 6px; align-content: start; min-width: 0; background: var(--panel); text-align: left; font: inherit; color: inherit; }
41
+ .ob button.ob-pcard { cursor: pointer; }
42
+ .ob button.ob-pcard:hover { border-color: var(--line-strong); }
43
+ .ob button.ob-pcard[aria-checked="true"] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
44
+ .ob .ob-pcard ul { margin: 0; padding-left: 18px; font-size: 13px; }
45
+ .ob .ob-pcard .ob-pro { color: var(--ok, var(--ink-2)); }
46
+ .ob .ob-pcard .ob-con { color: var(--warn, var(--ink-2)); }
47
+ .ob .ob-timeline { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
48
+ .ob .ob-timeline li { display: grid; grid-template-columns: minmax(64px, max-content) minmax(0, 1fr); gap: 4px 12px; }
49
+ .ob .ob-timeline time { color: var(--muted); font-size: 12.5px; font-variant-numeric: tabular-nums; }
50
+ .ob .ob-check { display: grid; gap: 6px; border-bottom: 1px solid var(--line); padding: 6px 0; }
51
+ .ob .ob-check:last-child { border-bottom: 0; }
52
+ .ob .ob-rank { list-style: none; margin: 0; padding: 0; }
53
+ .ob .ob-rank .ob-check { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
54
+ .ob { --s1: #2a78d6; --s2: #eb6834; --s3: #1baf7a; --s4: #eda100; --s5: #8a63d2; --s6: #6b7a8f; }
55
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .ob { --s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500; --s5: #9b78e0; --s6: #8593a6; } }
56
+ :root[data-theme="dark"] .ob { --s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500; --s5: #9b78e0; --s6: #8593a6; }
57
+ @media (max-width: 520px) { .ob .ob-timeline li { grid-template-columns: minmax(0, 1fr); } }
58
+ `;
59
+ function O(t) {
60
+ if (t.getElementById("omem-block-style")) return;
61
+ const n = t.createElement("style");
62
+ n.id = "omem-block-style", n.textContent = Z, t.head.appendChild(n);
63
+ }
64
+ function e(t, n, a = {}, ...o) {
65
+ const i = t.createElement(n);
66
+ for (const [b, c] of Object.entries(a))
67
+ c === void 0 || c === !1 || (typeof c == "function" ? i.addEventListener(b.replace(/^on/, ""), c) : i.setAttribute(b, c === !0 ? "" : String(c)));
68
+ for (const b of o) b != null && b !== !1 && i.append(typeof b == "string" ? t.createTextNode(b) : b);
69
+ return i;
70
+ }
71
+ const F = "http://www.w3.org/2000/svg";
72
+ function E(t, n, a = {}, o) {
73
+ const i = t.createElementNS(F, n);
74
+ for (const [b, c] of Object.entries(a)) i.setAttribute(b, String(c));
75
+ return o !== void 0 && (i.textContent = o), i;
76
+ }
77
+ const D = /* @__PURE__ */ new WeakMap();
78
+ function Q(t) {
79
+ for (const n of D.get(t) ?? []) n.disconnect();
80
+ D.delete(t);
81
+ }
82
+ function at(t, n, a) {
83
+ if (!P.includes(n.kind)) return !1;
84
+ if (O(t.ownerDocument), Q(t), n.kind === "view") {
85
+ const o = n.data, i = e(t.ownerDocument, "section", { class: "ob card pad", "aria-label": o.title || "展示" });
86
+ t.replaceChildren(i), o.title && i.append(e(t.ownerDocument, "h3", {}, o.title));
87
+ const b = e(t.ownerDocument, "div", { class: "ob" });
88
+ return i.append(b), R(b, o.components, a, t), !0;
89
+ }
90
+ return t.replaceChildren(tt(t, n, a)), !0;
91
+ }
92
+ function R(t, n, a = {}, o = t) {
93
+ const i = t.ownerDocument;
94
+ O(i), o === t && Q(t), t.classList.add("ob"), t.replaceChildren(...n.map((b) => G(i, b, a, o)));
95
+ }
96
+ function G(t, n, a, o) {
97
+ switch (n.type) {
98
+ case "markdown":
99
+ return T(t, n.text, a);
100
+ case "heading":
101
+ return e(t, "h4", {}, n.text);
102
+ case "table":
103
+ return J(t, n);
104
+ case "chart":
105
+ return U(t, n, o);
106
+ case "metric":
107
+ return e(t, "div", { class: "ob-metrics" }, ...n.items.map((i) => e(t, "div", { class: "ob-metric" }, e(t, "span", { class: "ob-muted" }, i.label), e(t, "b", {}, `${i.value}${i.unit ?? ""}`), i.change ? e(t, "span", { class: "ob-muted" }, i.change) : null)));
108
+ case "compare":
109
+ return e(t, "div", { class: "ob-field" }, n.title ? e(t, "span", { class: "ob-label" }, n.title) : null, e(t, "div", { class: "ob-cards" }, ...n.items.map((i) => H(t, e(t, "div", { class: "ob-pcard" }), i))));
110
+ case "page":
111
+ return e(t, "p", { class: "ob-muted" }, `交互页“${n.title || n.id}”:在 omem 的问答页里打开`);
112
+ case "timeline":
113
+ return e(t, "ol", { class: "ob-timeline" }, ...n.items.map((i) => e(t, "li", {}, e(t, "time", {}, i.time), e(t, "div", {}, e(t, "div", { class: "ob-label" }, i.title), i.text ? e(t, "p", { class: "ob-muted ob-text" }, i.text) : null))));
114
+ }
115
+ }
116
+ function T(t, n, a) {
117
+ const o = e(t, "div", { class: "ob-md" });
118
+ return a.markdown ? a.markdown(o, n) : (o.classList.add("ob-text"), o.textContent = n), o;
119
+ }
120
+ function H(t, n, a) {
121
+ const o = [
122
+ e(t, "span", { class: "ob-label" }, a.title),
123
+ a.summary ? e(t, "p", { class: "ob-text" }, a.summary) : null,
124
+ a.pros?.length ? e(t, "ul", { "aria-label": "优点" }, ...a.pros.map((i) => e(t, "li", { class: "ob-pro" }, i))) : null,
125
+ a.cons?.length ? e(t, "ul", { "aria-label": "代价" }, ...a.cons.map((i) => e(t, "li", { class: "ob-con" }, i))) : null
126
+ ];
127
+ return n.append(...o.filter((i) => !!i)), n;
128
+ }
129
+ const K = (t) => typeof t == "number" || typeof t == "string" && t.trim() !== "" && Number.isFinite(Number(t));
130
+ function J(t, n) {
131
+ let a = null;
132
+ const o = e(t, "tbody"), i = n.columns.map((f, h) => n.rows.length > 0 && n.rows.every((d) => d[h] === null || d[h] === void 0 || d[h] === "" || K(d[h]))), b = () => {
133
+ const f = [...n.rows];
134
+ if (a) {
135
+ const { col: h, dir: d } = a;
136
+ f.sort((s, l) => {
137
+ const r = s[h], g = l[h];
138
+ return (i[h] ? Number(r ?? -1 / 0) - Number(g ?? -1 / 0) : String(r ?? "").localeCompare(String(g ?? ""), "zh-CN")) * d;
139
+ });
140
+ }
141
+ o.replaceChildren(...f.map((h) => e(t, "tr", {}, ...n.columns.map((d, s) => e(t, "td", i[s] ? { class: "num" } : {}, h[s] === null || h[s] === void 0 ? "" : String(h[s]))))));
142
+ }, c = n.columns.map((f, h) => {
143
+ const d = e(t, "th", { scope: "col", "aria-sort": "none" }), s = e(t, "button", { type: "button", title: "排序" }, f);
144
+ return s.addEventListener("click", () => {
145
+ a = a?.col === h ? a.dir === 1 ? { col: h, dir: -1 } : null : { col: h, dir: 1 }, C.querySelectorAll("th").forEach((l, r) => l.setAttribute("aria-sort", a?.col === r ? a.dir === 1 ? "ascending" : "descending" : "none")), b();
146
+ }), d.append(s), d;
147
+ }), C = e(t, "thead", {}, e(t, "tr", {}, ...c));
148
+ return b(), e(t, "div", { class: "ob-field" }, n.title ? e(t, "span", { class: "ob-label" }, n.title) : null, e(t, "div", { class: "ob-scroll" }, e(t, "table", {}, C, o)), n.note ? e(t, "p", { class: "ob-muted" }, n.note) : null);
149
+ }
150
+ function U(t, n, a) {
151
+ const o = e(t, "div", { class: "ob-field" });
152
+ let i = 0;
153
+ const b = () => {
154
+ const c = Math.max(280, Math.min(900, Math.round(o.clientWidth || a.clientWidth || 600)));
155
+ Math.abs(c - i) < 8 || (i = c, o.replaceChildren(...X(t, n, c)));
156
+ };
157
+ if (b(), typeof ResizeObserver < "u") {
158
+ const c = new ResizeObserver(b);
159
+ c.observe(o), D.set(a, [...D.get(a) ?? [], c]);
160
+ }
161
+ return o;
162
+ }
163
+ const q = (t) => Math.abs(t) >= 1e3 ? t.toLocaleString() : String(Math.round(t * 100) / 100), A = (t) => `var(--s${t % 6 + 1})`;
164
+ function X(t, n, a) {
165
+ const o = e(t, "span", { class: "ob-label" }, `${n.title}${n.unit ? `(${n.unit})` : ""}`), i = n.kind === "pie" ? n.series.slice(0, 1) : n.series, b = e(
166
+ t,
167
+ "details",
168
+ {},
169
+ e(t, "summary", {}, "看数据"),
170
+ e(t, "div", { class: "ob-scroll" }, e(t, "table", {}, e(t, "thead", {}, e(t, "tr", {}, e(t, "th", {}, ""), ...i.map((u) => e(t, "th", {}, u.name)))), e(t, "tbody", {}, ...n.labels.map((u, y) => e(t, "tr", {}, e(t, "th", {}, u), ...i.map((v) => e(t, "td", { class: "num" }, `${q(v.values[y])}${n.unit ?? ""}`)))))))
171
+ ), c = n.note ? e(t, "p", { class: "ob-muted" }, n.note) : null;
172
+ if (n.kind === "pie") {
173
+ const u = i[0].values.map((S) => Math.max(0, S)), y = u.reduce((S, $) => S + $, 0) || 1, v = 180, M = 80, L = v / 2, k = v / 2, N = E(t, "svg", { viewBox: `0 0 ${v} ${v}`, role: "img", "aria-label": n.title, style: `max-width:${v}px` });
174
+ let w = -Math.PI / 2;
175
+ u.forEach((S, $) => {
176
+ const I = w + S / y * Math.PI * 2, B = I - w > Math.PI ? 1 : 0, V = S >= y ? E(t, "circle", { cx: L, cy: k, r: M, fill: A($) }) : E(t, "path", { d: `M${L},${k} L${L + M * Math.cos(w)},${k + M * Math.sin(w)} A${M},${M} 0 ${B} 1 ${L + M * Math.cos(I)},${k + M * Math.sin(I)} Z`, fill: A($), stroke: "var(--panel)", "stroke-width": 1.5 });
177
+ V.append(E(t, "title", {}, `${n.labels[$]}:${q(S)}${n.unit ?? ""}(${Math.round(S / y * 100)}%)`)), N.append(V), w = I;
178
+ });
179
+ const _ = e(t, "div", { class: "ob-legend" }, ...n.labels.map((S, $) => e(t, "span", { class: "ob-key" }, e(t, "i", { style: `background:${A($)}` }), `${S} ${Math.round(u[$] / y * 100)}%`)));
180
+ return [o, N, _, c, b].filter((S) => !!S);
181
+ }
182
+ const C = 200, f = 36, h = 8, d = 10, s = 26, l = i.flatMap((u) => u.values), r = Math.min(0, ...l), g = Math.max(0, ...l) || 1, p = (u) => d + (C - d - s) * (1 - (u - r) / (g - r)), x = (a - f - h) / n.labels.length, m = E(t, "svg", { viewBox: `0 0 ${a} ${C}`, role: "img", "aria-label": `${n.title}${n.unit ? `(${n.unit})` : ""}` });
183
+ for (const u of [r, (r + g) / 2, g])
184
+ m.append(E(t, "line", { x1: f, x2: a - h, y1: p(u), y2: p(u), class: "ob-grid" })), m.append(E(t, "text", { x: f - 6, y: p(u) + 4, "text-anchor": "end", class: "ob-tick" }, q(u)));
185
+ m.append(E(t, "line", { x1: f, x2: a - h, y1: p(0), y2: p(0), class: "ob-axis" }));
186
+ const z = Math.max(1, Math.ceil(n.labels.length / Math.max(2, Math.floor(a / 56))));
187
+ if (n.labels.forEach((u, y) => {
188
+ y % z === 0 && m.append(E(t, "text", { x: f + x * (y + 0.5), y: C - 8, "text-anchor": "middle", class: "ob-tick" }, u.length > 8 ? u.slice(0, 7) + "…" : u));
189
+ }), n.kind === "line")
190
+ i.forEach((u, y) => {
191
+ const v = u.values.map((M, L) => [f + x * (L + 0.5), p(M)]);
192
+ m.append(E(t, "polyline", { points: v.map((M) => M.join(",")).join(" "), fill: "none", stroke: A(y), "stroke-width": 2, "stroke-linejoin": "round", "stroke-linecap": "round" })), v.forEach(([M, L], k) => {
193
+ const N = E(t, "circle", { cx: M, cy: L, r: 4, fill: A(y), stroke: "var(--panel)", "stroke-width": 2 });
194
+ N.append(E(t, "title", {}, `${n.labels[k]} · ${u.name}:${q(u.values[k])}${n.unit ?? ""}`)), m.append(N);
195
+ });
196
+ });
197
+ else {
198
+ const u = i.length, y = 2, v = Math.max(2, Math.min(28, (x * 0.7 - y * (u - 1)) / u));
199
+ i.forEach((M, L) => {
200
+ M.values.forEach((k, N) => {
201
+ const w = f + x * (N + 0.5) - (u * v + y * (u - 1)) / 2 + L * (v + y), _ = p(Math.max(k, 0)), S = Math.max(0, Math.abs(p(k) - p(0))), $ = Math.min(4, v / 2, S), I = k >= 0 ? `M${w},${p(0)} V${_ + $} Q${w},${_} ${w + $},${_} H${w + v - $} Q${w + v},${_} ${w + v},${_ + $} V${p(0)} Z` : `M${w},${p(0)} V${p(k) - $} Q${w},${p(k)} ${w + $},${p(k)} H${w + v - $} Q${w + v},${p(k)} ${w + v},${p(k) - $} V${p(0)} Z`, B = E(t, "path", { d: I, fill: A(L) });
202
+ B.append(E(t, "title", {}, `${n.labels[N]} · ${M.name}:${q(k)}${n.unit ?? ""}`)), m.append(B);
203
+ });
204
+ });
205
+ }
206
+ const j = i.length > 1 ? e(t, "div", { class: "ob-legend" }, ...i.map((u, y) => e(t, "span", { class: "ob-key" }, e(t, "i", { style: `background:${A(y)}` }), u.name))) : null;
207
+ return [o, j, m, c, b].filter((u) => !!u);
208
+ }
209
+ function Y(t, n) {
210
+ if (!t.show_if) return !0;
211
+ const a = n[t.show_if.field], o = Array.isArray(a) ? a.map(String) : a == null || a === "" ? [] : [String(a)];
212
+ return t.show_if.in ? t.show_if.in.some((i) => o.includes(i)) : t.show_if.equals !== void 0 ? o.includes(String(t.show_if.equals)) : o.length > 0;
213
+ }
214
+ function W(t) {
215
+ const n = {};
216
+ for (const a of t)
217
+ "default" in a && a.default !== void 0 && (n[a.id] = a.default), a.type === "rank" && (n[a.id] = a.items.map((o) => o.id)), a.type === "table" && (n[a.id] = a.rows.length ? a.rows.map((o) => ({ ...o })) : [{}]);
218
+ return n;
219
+ }
220
+ function tt(t, n, a) {
221
+ const o = t.ownerDocument, i = n.data, b = n.status === "open", c = e(o, "section", { class: "ob card pad", "aria-label": "需要你回答" });
222
+ if (c.append(T(o, i.question, a)), i.view?.length) {
223
+ const s = e(o, "div", { class: "ob" });
224
+ c.append(s), R(s, i.view, a, t);
225
+ }
226
+ const C = e(o, "span", { class: "ob-err", role: "alert" }), f = async (s, l) => {
227
+ l && (l.disabled = !0), C.textContent = "";
228
+ try {
229
+ await a.submit(s);
230
+ } catch (r) {
231
+ C.textContent = r.message, l && (l.disabled = !1);
232
+ }
233
+ };
234
+ if (!b) {
235
+ const s = n.result;
236
+ return c.append(e(o, "p", { class: "ob-muted" }, s?.cancelled ? "已失效" : "已回答")), s?.answer && c.append(e(o, "p", { class: "ob-value" }, s.answer)), c;
237
+ }
238
+ const h = { ...W(i.fields ?? []) }, d = i.allowText ? e(o, i.fields?.length ? "textarea" : "input", { class: i.fields?.length ? "textarea" : "input", rows: 2, placeholder: i.fields?.length ? "补充说明(可不填)" : i.options.length ? "也可以写别的回答" : "你的回答", "aria-label": "文字回答" }) : null;
239
+ if (i.fields?.length) {
240
+ const s = e(o, "div", { class: "ob" }), l = () => s.replaceChildren(...i.fields.filter((g) => Y(g, h)).map((g) => et(o, n.id, g, h, l)));
241
+ l(), c.append(s), d && c.append(d);
242
+ const r = e(o, "button", { type: "button", class: "btn primary" }, i.submitLabel || "提交");
243
+ return r.addEventListener("click", () => f({ value: h, ...d?.value.trim() ? { text: d.value.trim() } : {} }, r)), c.append(e(o, "div", { class: "ob-foot" }, C, e(o, "span", { class: "ob-spacer" }), r)), c;
244
+ }
245
+ if (i.options.length && c.append(e(o, "div", { class: "ob-options" }, ...i.options.map((s, l) => {
246
+ const r = e(o, "button", { type: "button", class: `btn sm${l === 0 ? " primary" : ""}` }, s.label);
247
+ return r.addEventListener("click", () => f({ choice: l, ...d?.value.trim() ? { text: d.value.trim() } : {} }, r)), r;
248
+ }))), d) {
249
+ const s = e(o, "button", { type: "button", class: "btn sm" }, "回答");
250
+ s.addEventListener("click", () => d.value.trim() && f({ text: d.value.trim() }, s)), c.append(e(o, "div", { class: "ob-foot" }, d, s));
251
+ }
252
+ return c.append(C), c;
253
+ }
254
+ function et(t, n, a, o, i) {
255
+ const b = `ob-${n}-${a.id}`, c = e(t, "span", { class: "ob-label", id: b }, a.label, a.required ? e(t, "span", { class: "ob-req", "aria-hidden": "true" }, "*") : null), C = a.help ? e(t, "span", { class: "ob-muted" }, a.help) : null, f = (s, l = !1) => {
256
+ o[a.id] = s, l && i();
257
+ }, h = !0;
258
+ let d;
259
+ switch (a.type) {
260
+ case "textarea":
261
+ d = e(t, "textarea", { class: "textarea", rows: 3, placeholder: a.placeholder, "aria-labelledby": b, oninput: (s) => f(s.target.value) }), d.value = String(o[a.id] ?? "");
262
+ break;
263
+ case "text":
264
+ case "number":
265
+ case "date":
266
+ case "datetime": {
267
+ const s = a.type === "datetime" ? "datetime-local" : a.type;
268
+ d = e(t, "input", { class: "input", type: s, placeholder: "placeholder" in a ? a.placeholder : void 0, min: "min" in a ? a.min : void 0, max: "max" in a ? a.max : void 0, "aria-labelledby": b, oninput: (l) => f(l.target.value), onchange: () => i() }), d.value = String(o[a.id] ?? "");
269
+ break;
270
+ }
271
+ case "toggle": {
272
+ const s = e(t, "button", { type: "button", class: "btn sm ob-opt", "aria-pressed": String(!!o[a.id]), "aria-labelledby": b }, o[a.id] ? "是" : "否");
273
+ s.addEventListener("click", () => f(!o[a.id], h)), d = s;
274
+ break;
275
+ }
276
+ case "pick":
277
+ d = e(t, "div", { class: "ob-cards", role: "radiogroup", "aria-labelledby": b }, ...a.items.map((s) => {
278
+ const l = H(t, e(t, "button", { type: "button", role: "radio", class: "ob-pcard", "aria-checked": String(o[a.id] === s.id) }), s);
279
+ return l.addEventListener("click", () => f(s.id, h)), l;
280
+ }));
281
+ break;
282
+ case "rank": {
283
+ const s = o[a.id];
284
+ d = e(t, "ol", { class: "ob-rank", "aria-labelledby": b }, ...s.map((l, r) => {
285
+ const g = a.items.find((x) => x.id === l), p = (x) => {
286
+ const m = [...s];
287
+ [m[r], m[r + x]] = [m[r + x], m[r]], f(m, !0);
288
+ };
289
+ return e(t, "li", { class: "ob-check" }, e(t, "span", {}, `${r + 1}. ${g.title}`), e(
290
+ t,
291
+ "span",
292
+ { class: "ob-options" },
293
+ e(t, "button", { type: "button", class: "btn sm", disabled: r === 0, "aria-label": `${g.title} 上移`, onclick: () => p(-1) }, "上移"),
294
+ e(t, "button", { type: "button", class: "btn sm", disabled: r === s.length - 1, "aria-label": `${g.title} 下移`, onclick: () => p(1) }, "下移")
295
+ ));
296
+ }));
297
+ break;
298
+ }
299
+ case "table": {
300
+ const s = o[a.id], l = e(t, "tr", {}, ...a.columns.map((p) => e(t, "th", {}, p.label)), e(t, "th", {}, "")), r = s.map((p, x) => e(t, "tr", {}, ...a.columns.map((m) => {
301
+ const z = m.type === "choice" ? e(t, "select", { class: "input", "aria-label": `第 ${x + 1} 行 ${m.label}` }, e(t, "option", { value: "" }, ""), ...(m.options ?? []).map((j) => e(t, "option", { value: j }, j))) : e(t, "input", { class: "input", type: m.type === "number" ? "number" : "text", "aria-label": `第 ${x + 1} 行 ${m.label}` });
302
+ return z.value = p[m.id] == null ? "" : String(p[m.id]), z.addEventListener("input", () => p[m.id] = z.value), e(t, "td", {}, z);
303
+ }), e(t, "td", {}, e(t, "button", { type: "button", class: "btn sm", "aria-label": `删除第 ${x + 1} 行`, onclick: () => f(s.filter((m, z) => z !== x), !0) }, "删除")))), g = e(t, "button", { type: "button", class: "btn sm", disabled: s.length >= a.max_rows, onclick: () => f([...s, {}], !0) }, "加一行");
304
+ d = e(t, "div", { class: "ob-field" }, e(t, "div", { class: "ob-scroll" }, e(t, "table", { "aria-labelledby": b }, e(t, "thead", {}, l), e(t, "tbody", {}, ...r))), g);
305
+ break;
306
+ }
307
+ case "checklist": {
308
+ const s = o[a.id] ?? {};
309
+ o[a.id] = s, d = e(t, "div", { role: "group", "aria-labelledby": b }, ...a.items.map((l) => {
310
+ const r = e(t, "div", { class: "ob-check" }, e(t, "span", {}, l.title), l.detail ? e(t, "span", { class: "ob-muted ob-text" }, l.detail) : null), g = e(t, "div", { class: "ob-options", role: "radiogroup", "aria-label": l.title }, ...a.choices.map((p) => {
311
+ const x = e(t, "button", { type: "button", role: "radio", class: "btn sm ob-opt", "aria-checked": String(s[l.id]?.choice === p) }, p);
312
+ return x.addEventListener("click", () => {
313
+ s[l.id] = { ...s[l.id], choice: p }, g.querySelectorAll("button").forEach((m) => m.setAttribute("aria-checked", String(m.textContent === p)));
314
+ }), x;
315
+ }));
316
+ if (r.append(g), a.note) {
317
+ const p = e(t, "input", { class: "input", placeholder: "备注(可不填)", "aria-label": `${l.title} 的备注` });
318
+ p.value = s[l.id]?.note ?? "", p.addEventListener("input", () => s[l.id] = { choice: s[l.id]?.choice ?? "", note: p.value }), r.append(p);
319
+ }
320
+ return r;
321
+ }));
322
+ break;
323
+ }
324
+ default: {
325
+ const s = a.type === "scale" ? ["1", "2", "3", "4", "5"] : a.options, l = a.type === "multi";
326
+ d = e(t, "div", { class: "ob-options", role: l ? "group" : "radiogroup", "aria-labelledby": b }, ...s.map((r) => {
327
+ const g = o[a.id], p = l ? (g ?? []).includes(r) : String(g ?? "") === r, x = e(t, "button", { type: "button", class: "btn sm ob-opt", ...l ? { "aria-pressed": String(p) } : { role: "radio", "aria-checked": String(p) } }, r);
328
+ return x.addEventListener("click", () => {
329
+ if (l) {
330
+ const m = new Set(o[a.id] ?? []);
331
+ m.has(r) ? m.delete(r) : m.add(r), f([...m], h);
332
+ } else f(a.type === "scale" ? Number(r) : r, h);
333
+ }), x;
334
+ }));
335
+ }
336
+ }
337
+ return e(t, "div", { class: "ob-field" }, c, C, d);
338
+ }
339
+ export {
340
+ P as GENERIC_KINDS,
341
+ Y as fieldVisible,
342
+ W as initialValues,
343
+ at as renderBlock,
344
+ R as renderView
345
+ };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The plugin page's side of the bridge (docs/v2/plugins.md). The page runs in a sandboxed
3
+ * iframe without omem's origin: it cannot read the owner's token or call /api itself. It asks
4
+ * the shell (web/src/views/Plugin.vue) by postMessage, and the shell forwards only paths under
5
+ * /api/plugins/<this plugin>/. The shell also sends the theme and the server events of this plugin.
6
+ */
7
+ export type OmemEvent = {
8
+ type: "plugin";
9
+ plugin: string;
10
+ conversationId: string;
11
+ blockId?: string;
12
+ settings?: boolean;
13
+ } | {
14
+ type: "run";
15
+ runId: string;
16
+ status: string;
17
+ };
18
+ export { renderBlock, renderView, GENERIC_KINDS, type BlockView, type ViewComponent, type UiField } from "./blocks";
19
+ export type Omem = {
20
+ plugin: string;
21
+ /** The query of the shell's route (#/plugin/<id>?session=…): a link can open a given session. */
22
+ params: Record<string, string>;
23
+ /** Paths are relative to /api/plugins/<id>/ (e.g. "sessions"). */
24
+ get<T = any>(path: string): Promise<T>;
25
+ post<T = any>(path: string, body?: unknown): Promise<T>;
26
+ on(fn: (e: OmemEvent) => void): () => void;
27
+ /** Open an omem page in the shell (e.g. "/learn"). */
28
+ navigate(to: string): void;
29
+ /** Open the shell's settings dialog for this plugin; a saved change arrives as a plugin event with settings: true. */
30
+ openSettings(): void;
31
+ /**
32
+ * A WebSocket to one of the plugin's streams (its service, started if needed), opened by the shell
33
+ * as the owner and relayed here. Binary messages arrive as ArrayBuffer.
34
+ */
35
+ stream(name: string): OmemStream;
36
+ /**
37
+ * A voice conversation (the manifest says `voice: true`). The shell takes the microphone and talks to
38
+ * the voice model of settings → AI → 语音 with `instructions` and no tools; this page gets the
39
+ * transcript as it grows and the whole of it at the end, never the audio. Call it from a click: the
40
+ * shell refuses a start the person did not just ask for (the promise rejects, `code: "gesture"`).
41
+ */
42
+ voice(o: {
43
+ instructions: string;
44
+ onTurns?: (turns: VoiceTurn[]) => void;
45
+ onState?: (state: VoiceState, detail?: string) => void;
46
+ }): Promise<OmemVoice>;
47
+ /** Whether voice can be used now, and why not (not declared, no voice model yet: `detail` says where to set it up). */
48
+ voiceStatus(): Promise<VoiceStatus>;
49
+ };
50
+ export type VoiceTurn = {
51
+ role: "user" | "assistant";
52
+ text: string;
53
+ final: boolean;
54
+ };
55
+ export type VoiceState = "connecting" | "live" | "ended" | "failed";
56
+ export type VoiceStatus = {
57
+ allowed: boolean;
58
+ ready: boolean;
59
+ detail: string;
60
+ api: "live" | "realtime" | null;
61
+ model: string | null;
62
+ };
63
+ /** What a finished conversation leaves: both sides as text, when it ran, on which model. */
64
+ export type VoiceRecord = {
65
+ transcript: {
66
+ role: "user" | "assistant";
67
+ text: string;
68
+ }[];
69
+ startedAt: string;
70
+ endedAt: string;
71
+ api: string;
72
+ model: string;
73
+ };
74
+ export type OmemVoice = {
75
+ /** End it (or take what is left after the other side ended it). */
76
+ stop(): Promise<VoiceRecord>;
77
+ mute(on: boolean): void;
78
+ /** Resolves when the conversation ends, by stop(), by the shell's own “结束” button, or by a dropped connection. */
79
+ ended: Promise<VoiceRecord>;
80
+ };
81
+ export type OmemStream = {
82
+ send(data: string | ArrayBuffer): void;
83
+ close(): void;
84
+ onopen?: () => void;
85
+ onmessage?: (data: string | ArrayBuffer) => void;
86
+ onclose?: (reason: string) => void;
87
+ };
88
+ export declare function connect(): Promise<Omem>;
package/dist/client.js ADDED
@@ -0,0 +1,73 @@
1
+ import { GENERIC_KINDS as M, renderBlock as h, renderView as k } from "./blocks.js";
2
+ let f = 0;
3
+ const g = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Set(), v = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map(), r = (d) => window.parent.postMessage({ omem: 1, ...d }, "*");
4
+ function E(d, c) {
5
+ const e = document.documentElement;
6
+ for (const [t, a] of Object.entries(d)) e.style.setProperty(t, a);
7
+ e.style.colorScheme = c, e.dataset.theme = c;
8
+ }
9
+ let w = null;
10
+ function T() {
11
+ return w ??= new Promise((d) => {
12
+ window.addEventListener("message", (c) => {
13
+ if (c.source !== window.parent) return;
14
+ const e = c.data;
15
+ if (!(!e || e.omem !== 1)) {
16
+ if ((e.type === "init" || e.type === "theme") && E(e.vars, String(e.scheme)), e.type === "init") {
17
+ const t = String(e.plugin), a = (n, s, i) => new Promise((o, p) => {
18
+ const l = ++f;
19
+ g.set(l, { resolve: o, reject: p }), r({ type: "request", id: l, method: n, path: s, body: i });
20
+ });
21
+ d({
22
+ plugin: t,
23
+ params: e.params ?? {},
24
+ get: (n) => a("GET", n),
25
+ post: (n, s) => a("POST", n, s ?? {}),
26
+ on: (n) => (y.add(n), () => y.delete(n)),
27
+ navigate: (n) => r({ type: "navigate", to: n }),
28
+ openSettings: () => r({ type: "settings" }),
29
+ stream: (n) => {
30
+ const s = ++f, i = {
31
+ send: (o) => typeof o == "string" ? r({ type: "stream-send", sid: s, data: o }) : window.parent.postMessage({ omem: 1, type: "stream-send", sid: s, data: o }, "*", [o]),
32
+ close: () => {
33
+ v.delete(s), r({ type: "stream-close", sid: s });
34
+ }
35
+ };
36
+ return v.set(s, i), r({ type: "stream-open", sid: s, name: n }), i;
37
+ },
38
+ voiceStatus: () => a("GET", "voice"),
39
+ voice: (n) => new Promise((s, i) => {
40
+ const o = ++f;
41
+ let p;
42
+ const l = new Promise((u) => p = u), S = {
43
+ stop: () => (r({ type: "voice-stop", vid: o }), l),
44
+ mute: (u) => r({ type: "voice-mute", vid: o, on: u }),
45
+ ended: l
46
+ };
47
+ m.set(o, { started: { resolve: s, reject: i }, ended: p, onTurns: n.onTurns, onState: n.onState, voice: S }), r({ type: "voice-start", vid: o, instructions: n.instructions });
48
+ })
49
+ });
50
+ } else if (e.type === "response") {
51
+ const t = g.get(e.id);
52
+ if (!t) return;
53
+ g.delete(e.id), e.ok ? t.resolve(e.data) : t.reject(new Error(String(e.error ?? "请求失败")));
54
+ } else if (e.type === "event") for (const t of y) t(e.event);
55
+ else if (e.type === "voice-event") {
56
+ const t = m.get(e.vid);
57
+ if (!t) return;
58
+ e.event === "turns" ? t.onTurns?.(e.turns) : e.event === "state" ? t.onState?.(e.state, e.detail ? String(e.detail) : void 0) : e.event === "started" ? (t.started?.resolve(t.voice), t.started = null) : e.event === "error" ? (t.started?.reject(Object.assign(new Error(String(e.error ?? "语音没有连上")), { code: e.code ? String(e.code) : void 0 })), m.delete(e.vid)) : e.event === "ended" && (t.ended(e.record), m.delete(e.vid));
59
+ } else if (e.type === "stream-event") {
60
+ const t = v.get(e.sid);
61
+ if (!t) return;
62
+ e.event === "open" ? t.onopen?.() : e.event === "message" ? t.onmessage?.(e.data) : e.event === "close" && (v.delete(e.sid), t.onclose?.(String(e.reason ?? "")));
63
+ }
64
+ }
65
+ }), r({ type: "ready" });
66
+ }), w;
67
+ }
68
+ export {
69
+ M as GENERIC_KINDS,
70
+ T as connect,
71
+ h as renderBlock,
72
+ k as renderView
73
+ };
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@omem-ai/plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "SDK for omem plugin pages and services: talk to omem through the shell, draw its forms and charts, serve HTTP and WebSocket to omem.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": { "types": "./dist/client.d.ts", "default": "./dist/client.js" },
9
+ "./blocks": { "types": "./dist/blocks.d.ts", "default": "./dist/blocks.js" },
10
+ "./service": "./service.mjs"
11
+ },
12
+ "files": ["dist", "service.mjs", "README.md"],
13
+ "scripts": {
14
+ "build": "vite build && tsc -p tsconfig.json"
15
+ },
16
+ "devDependencies": {
17
+ "typescript": "5.9.3",
18
+ "vite": "7.3.1"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/lejunyang/omem.git",
23
+ "directory": "packages/plugin-sdk"
24
+ },
25
+ "publishConfig": { "access": "public" }
26
+ }
package/service.mjs ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * A plugin service's side (docs/v2/plugins.md), without dependencies: a plugin in the data directory
3
+ * cannot install packages, so its service imports this through OMEM_SERVICE_SDK:
4
+ *
5
+ * const { serve } = await import(process.env.OMEM_SERVICE_SDK);
6
+ * serve({
7
+ * http: (req, res) => { res.end("ok"); },
8
+ * socket: (ws) => { ws.on("message", (data, binary) => ws.send(data)); },
9
+ * });
10
+ *
11
+ * It listens on 127.0.0.1:OMEM_SERVICE_PORT and refuses anything that does not carry omem's token,
12
+ * so only omem (which checked the owner) reaches it. WebSocket: text and binary messages, ping,
13
+ * close; messages up to 16 MB.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { EventEmitter } from "node:events";
17
+ import { createServer } from "node:http";
18
+
19
+ const MAX = 16 * 1024 * 1024;
20
+
21
+ export function serve({ http, socket } = {}) {
22
+ const port = Number(process.env.OMEM_SERVICE_PORT);
23
+ const token = process.env.OMEM_SERVICE_TOKEN;
24
+ if (!port || !token) throw new Error("not started by omem: OMEM_SERVICE_PORT / OMEM_SERVICE_TOKEN missing");
25
+ const authed = (req) => req.headers.authorization === `Bearer ${token}`;
26
+ const server = createServer((req, res) => {
27
+ if (!authed(req)) return void (res.writeHead(401), res.end());
28
+ if (http) return http(req, res);
29
+ res.writeHead(404);
30
+ res.end();
31
+ });
32
+ server.on("upgrade", (req, sock, head) => {
33
+ if (!authed(req) || !socket || String(req.headers.upgrade).toLowerCase() !== "websocket" || !req.headers["sec-websocket-key"]) return void sock.destroy();
34
+ const accept = createHash("sha1").update(`${req.headers["sec-websocket-key"]}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64");
35
+ sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
36
+ socket(wrap(sock, head), req);
37
+ });
38
+ server.listen(port, "127.0.0.1");
39
+ return server;
40
+ }
41
+
42
+ function frame(opcode, payload) {
43
+ const len = payload.length;
44
+ const head = len < 126 ? Buffer.from([0x80 | opcode, len]) : len < 65536 ? Buffer.from([0x80 | opcode, 126, len >> 8, len & 255]) : Buffer.concat([Buffer.from([0x80 | opcode, 127]), (() => { const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(len)); return b; })()]);
45
+ return Buffer.concat([head, payload]);
46
+ }
47
+
48
+ function wrap(sock, head) {
49
+ const ws = new EventEmitter();
50
+ let buf = head?.length ? Buffer.from(head) : Buffer.alloc(0);
51
+ let parts = [];
52
+ let partOp = 0;
53
+ let open = true;
54
+ ws.send = (data) => {
55
+ if (!open) return;
56
+ const binary = typeof data !== "string";
57
+ sock.write(frame(binary ? 2 : 1, binary ? Buffer.from(data) : Buffer.from(data, "utf8")));
58
+ };
59
+ ws.close = () => {
60
+ if (!open) return;
61
+ open = false;
62
+ sock.end(frame(8, Buffer.alloc(0)));
63
+ };
64
+ const parse = () => {
65
+ for (;;) {
66
+ if (buf.length < 2) return;
67
+ const fin = buf[0] & 0x80;
68
+ const op = buf[0] & 0x0f;
69
+ const masked = buf[1] & 0x80;
70
+ let len = buf[1] & 0x7f;
71
+ let at = 2;
72
+ if (len === 126) {
73
+ if (buf.length < 4) return;
74
+ len = buf.readUInt16BE(2);
75
+ at = 4;
76
+ } else if (len === 127) {
77
+ if (buf.length < 10) return;
78
+ len = Number(buf.readBigUInt64BE(2));
79
+ at = 10;
80
+ }
81
+ if (len > MAX) return void sock.destroy();
82
+ const maskAt = at;
83
+ if (masked) at += 4;
84
+ if (buf.length < at + len) return;
85
+ let payload = buf.subarray(at, at + len);
86
+ if (masked) {
87
+ payload = Buffer.from(payload);
88
+ for (let i = 0; i < payload.length; i++) payload[i] ^= buf[maskAt + (i % 4)];
89
+ }
90
+ buf = buf.subarray(at + len);
91
+ if (op === 8) return ws.close();
92
+ if (op === 9) { sock.write(frame(10, payload)); continue; }
93
+ if (op === 10) continue;
94
+ if (op === 1 || op === 2) partOp = op;
95
+ parts.push(payload);
96
+ if (fin) {
97
+ const data = Buffer.concat(parts);
98
+ parts = [];
99
+ ws.emit("message", partOp === 1 ? data.toString("utf8") : data, partOp === 2);
100
+ }
101
+ }
102
+ };
103
+ sock.on("data", (d) => {
104
+ buf = Buffer.concat([buf, d]);
105
+ parse();
106
+ });
107
+ const gone = () => {
108
+ if (!open && ws.closed) return;
109
+ open = false;
110
+ ws.closed = true;
111
+ ws.emit("close");
112
+ };
113
+ sock.on("close", gone);
114
+ sock.on("error", gone);
115
+ if (buf.length) setImmediate(parse);
116
+ return ws;
117
+ }