@pcific/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kit.js ADDED
@@ -0,0 +1,208 @@
1
+ import { PcificConfigError } from "./errors.js";
2
+ export const DEFAULT_PCIFIC_KIT_BASE_URL = "https://business.pcific.ai";
3
+ const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
4
+ const KIT_SCRIPT_PATH = "/static/templates/kit.js";
5
+ export const PCIFIC_KIT_TOOLS = [
6
+ "orbit",
7
+ "safeguard",
8
+ "ask",
9
+ "pixel-trace",
10
+ "trust",
11
+ "chat",
12
+ ];
13
+ export const PCIFIC_KIT_FONTS = [
14
+ "business",
15
+ "inherit",
16
+ "Inter",
17
+ "Work Sans",
18
+ "Georgia",
19
+ "Arial",
20
+ "Verdana",
21
+ "Times New Roman",
22
+ "Courier New",
23
+ "system-ui",
24
+ "sans-serif",
25
+ "serif",
26
+ "monospace",
27
+ ];
28
+ const inflightLoads = new Map();
29
+ function readBrowserGlobals() {
30
+ // SAFETY: globalThis may provide document and customElements in browser runtimes and omit them in SSR/Node.
31
+ return globalThis;
32
+ }
33
+ function normalizeBaseUrl(rawBaseUrl) {
34
+ const candidate = (rawBaseUrl ?? DEFAULT_PCIFIC_KIT_BASE_URL).trim();
35
+ if (!candidate) {
36
+ throw new PcificConfigError("PCIFIC Kit baseUrl cannot be empty.", {
37
+ code: "INVALID_KIT_BASE_URL",
38
+ tryThis: `Pass a valid http(s) baseUrl or omit it to use ${DEFAULT_PCIFIC_KIT_BASE_URL}.`,
39
+ });
40
+ }
41
+ let parsed;
42
+ try {
43
+ parsed = new URL(candidate);
44
+ }
45
+ catch {
46
+ throw new PcificConfigError(`Invalid PCIFIC Kit baseUrl "${candidate}".`, {
47
+ code: "INVALID_KIT_BASE_URL",
48
+ tryThis: `Pass a valid http(s) origin such as "${DEFAULT_PCIFIC_KIT_BASE_URL}".`,
49
+ });
50
+ }
51
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
52
+ throw new PcificConfigError(`Unsupported PCIFIC Kit baseUrl protocol "${parsed.protocol}".`, {
53
+ code: "INVALID_KIT_BASE_URL",
54
+ tryThis: `Use an https:// or http:// origin such as "${DEFAULT_PCIFIC_KIT_BASE_URL}".`,
55
+ });
56
+ }
57
+ return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, "");
58
+ }
59
+ export function getPcificKitScriptUrl(baseUrl) {
60
+ return `${normalizeBaseUrl(baseUrl)}${KIT_SCRIPT_PATH}`;
61
+ }
62
+ function findExistingKitScript(doc, scriptUrl) {
63
+ const scripts = doc.querySelectorAll("script[src]");
64
+ for (const node of Array.from(scripts)) {
65
+ const attrSrc = node.getAttribute("src");
66
+ if (attrSrc === scriptUrl || node.src === scriptUrl) {
67
+ return node;
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+ /**
73
+ * Idempotently loads the PCIFIC Kit web components script in browser environments.
74
+ * Safe against concurrent calls and duplicate script tags.
75
+ */
76
+ export function loadPcificKit(options = {}) {
77
+ const scriptUrl = getPcificKitScriptUrl(options.baseUrl);
78
+ const timeoutMs = options.timeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS;
79
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
80
+ return Promise.reject(new PcificConfigError("PCIFIC Kit timeoutMs must be a positive number.", {
81
+ code: "INVALID_KIT_TIMEOUT",
82
+ tryThis: "Pass a positive number of milliseconds for timeoutMs, or omit it to use 15000.",
83
+ }));
84
+ }
85
+ const globals = readBrowserGlobals();
86
+ const doc = globals.document;
87
+ const registry = globals.customElements;
88
+ if (!doc || !registry) {
89
+ if (options.ignoreSsr) {
90
+ return Promise.resolve();
91
+ }
92
+ return Promise.reject(new PcificConfigError("loadPcificKit() can only run in a browser environment with document and customElements.", {
93
+ code: "PCIFIC_KIT_BROWSER_ONLY",
94
+ tryThis: "Call loadPcificKit() inside a client-side effect (such as useEffect or onMount), or pass { ignoreSsr: true } if calling during SSR.",
95
+ }));
96
+ }
97
+ if (registry.get("pcific-orbit")) {
98
+ return Promise.resolve();
99
+ }
100
+ const inflight = inflightLoads.get(scriptUrl);
101
+ if (inflight) {
102
+ return inflight;
103
+ }
104
+ const existing = findExistingKitScript(doc, scriptUrl);
105
+ if (existing?.getAttribute("data-pcific-kit-loaded") === "true") {
106
+ return Promise.resolve();
107
+ }
108
+ const loadPromise = new Promise((resolve, reject) => {
109
+ const script = existing ?? doc.createElement("script");
110
+ let settled = false;
111
+ const cleanup = () => {
112
+ clearTimeout(timer);
113
+ script.removeEventListener("load", onLoad);
114
+ script.removeEventListener("error", onError);
115
+ };
116
+ const fail = (error) => {
117
+ if (settled)
118
+ return;
119
+ settled = true;
120
+ cleanup();
121
+ inflightLoads.delete(scriptUrl);
122
+ reject(error);
123
+ };
124
+ const succeed = () => {
125
+ if (settled)
126
+ return;
127
+ settled = true;
128
+ cleanup();
129
+ script.setAttribute("data-pcific-kit-loaded", "true");
130
+ inflightLoads.delete(scriptUrl);
131
+ resolve();
132
+ };
133
+ const onLoad = () => {
134
+ if (registry.get("pcific-orbit")) {
135
+ succeed();
136
+ return;
137
+ }
138
+ if (registry.whenDefined) {
139
+ registry.whenDefined("pcific-orbit").then(() => succeed(), () => succeed());
140
+ return;
141
+ }
142
+ succeed();
143
+ };
144
+ const onError = () => {
145
+ fail(new PcificConfigError(`Failed to load PCIFIC Kit script from ${scriptUrl}.`, {
146
+ code: "PCIFIC_KIT_LOAD_FAILED",
147
+ tryThis: `Check that ${scriptUrl} is reachable and allowed by your Content-Security-Policy.`,
148
+ }));
149
+ };
150
+ const timer = setTimeout(() => {
151
+ fail(new PcificConfigError(`Timed out after ${timeoutMs}ms waiting for PCIFIC Kit script (${scriptUrl}).`, {
152
+ code: "PCIFIC_KIT_LOAD_TIMEOUT",
153
+ tryThis: "Check network connectivity or raise timeoutMs, then retry loadPcificKit().",
154
+ }));
155
+ }, timeoutMs);
156
+ script.addEventListener("load", onLoad, { once: true });
157
+ script.addEventListener("error", onError, { once: true });
158
+ if (!existing) {
159
+ script.type = "module";
160
+ script.src = scriptUrl;
161
+ script.setAttribute("data-pcific-kit", "true");
162
+ const target = doc.head ?? doc.documentElement;
163
+ if (!target) {
164
+ fail(new PcificConfigError("Cannot mount PCIFIC Kit script: document has no head or root element.", {
165
+ code: "PCIFIC_KIT_NO_DOCUMENT_TARGET",
166
+ tryThis: "Call loadPcificKit() after the page document has been initialized.",
167
+ }));
168
+ return;
169
+ }
170
+ target.appendChild(script);
171
+ }
172
+ });
173
+ inflightLoads.set(scriptUrl, loadPromise);
174
+ return loadPromise;
175
+ }
176
+ /**
177
+ * Attaches a typed listener for any PCIFIC custom event (`pcific:result`, `pcific:state`,
178
+ * `pcific:problem`, etc.) and returns a cleanup function that removes it.
179
+ */
180
+ export function onPcificEvent(element, eventName, handler, options) {
181
+ const listener = (rawEvent) => {
182
+ // SAFETY: The listener is registered specifically for eventName, which PCIFIC Kit dispatches as CustomEvent<PcificKitEventDetailMap[K]>.
183
+ const customEvent = rawEvent;
184
+ handler(customEvent.detail, customEvent);
185
+ };
186
+ element.addEventListener(eventName, listener, options);
187
+ return () => {
188
+ element.removeEventListener(eventName, listener, options);
189
+ };
190
+ }
191
+ /**
192
+ * Creates a reusable handle configured with a baseUrl for loading PCIFIC Kit
193
+ * and subscribing to typed web component events.
194
+ */
195
+ export function createPcificKit(options = {}) {
196
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
197
+ const scriptUrl = `${baseUrl}${KIT_SCRIPT_PATH}`;
198
+ return {
199
+ baseUrl,
200
+ scriptUrl,
201
+ load: () => loadPcificKit({ ...options, baseUrl }),
202
+ onEvent: onPcificEvent,
203
+ };
204
+ }
205
+ /** Clears internal in-flight script cache. Intended for test isolation. */
206
+ export function resetPcificKitLoader() {
207
+ inflightLoads.clear();
208
+ }
@@ -0,0 +1,23 @@
1
+ export interface UploadFileDescriptor {
2
+ data: Blob | Uint8Array | ArrayBuffer;
3
+ filename?: string;
4
+ contentType?: string;
5
+ }
6
+ export type UploadInput = Blob | Uint8Array | ArrayBuffer | UploadFileDescriptor;
7
+ export interface NormalizedUpload {
8
+ blob: Blob;
9
+ filename: string;
10
+ contentType: string;
11
+ }
12
+ /**
13
+ * Normalizes Blob, File, Uint8Array, ArrayBuffer, or descriptor objects into a Blob with filename and contentType.
14
+ */
15
+ export declare function normalizeUpload(input: UploadInput, defaultFilename?: string, defaultContentType?: string): NormalizedUpload;
16
+ /**
17
+ * Serializes a FormData instance to exact bytes and its boundary Content-Type header
18
+ * so request signing covers the exact transmitted payload.
19
+ */
20
+ export declare function serializeFormData(formData: FormData): Promise<{
21
+ body: Uint8Array;
22
+ contentType: string;
23
+ }>;
@@ -0,0 +1,61 @@
1
+ function isFileLike(value) {
2
+ return typeof File !== "undefined" && value instanceof File;
3
+ }
4
+ function isDescriptor(value) {
5
+ return (typeof value === "object" &&
6
+ value !== null &&
7
+ !(value instanceof Blob) &&
8
+ !(value instanceof Uint8Array) &&
9
+ !(value instanceof ArrayBuffer) &&
10
+ "data" in value);
11
+ }
12
+ function toArrayBufferSlice(bytes) {
13
+ const copy = new Uint8Array(bytes.byteLength);
14
+ copy.set(bytes);
15
+ return copy.buffer;
16
+ }
17
+ /**
18
+ * Normalizes Blob, File, Uint8Array, ArrayBuffer, or descriptor objects into a Blob with filename and contentType.
19
+ */
20
+ export function normalizeUpload(input, defaultFilename = "upload.jpg", defaultContentType = "application/octet-stream") {
21
+ if (isDescriptor(input)) {
22
+ const contentType = input.contentType ??
23
+ (input.data instanceof Blob && input.data.type ? input.data.type : defaultContentType);
24
+ const filename = input.filename ?? (isFileLike(input.data) && input.data.name ? input.data.name : defaultFilename);
25
+ const blob = input.data instanceof Blob
26
+ ? input.data.type === contentType
27
+ ? input.data
28
+ : new Blob([input.data], { type: contentType })
29
+ : input.data instanceof Uint8Array
30
+ ? new Blob([toArrayBufferSlice(input.data)], { type: contentType })
31
+ : new Blob([input.data], { type: contentType });
32
+ return { blob, filename, contentType };
33
+ }
34
+ if (input instanceof Blob) {
35
+ const contentType = input.type || defaultContentType;
36
+ const filename = isFileLike(input) && input.name ? input.name : defaultFilename;
37
+ return { blob: input, filename, contentType };
38
+ }
39
+ if (input instanceof Uint8Array) {
40
+ return {
41
+ blob: new Blob([toArrayBufferSlice(input)], { type: defaultContentType }),
42
+ filename: defaultFilename,
43
+ contentType: defaultContentType,
44
+ };
45
+ }
46
+ return {
47
+ blob: new Blob([input], { type: defaultContentType }),
48
+ filename: defaultFilename,
49
+ contentType: defaultContentType,
50
+ };
51
+ }
52
+ /**
53
+ * Serializes a FormData instance to exact bytes and its boundary Content-Type header
54
+ * so request signing covers the exact transmitted payload.
55
+ */
56
+ export async function serializeFormData(formData) {
57
+ const response = new Response(formData);
58
+ const contentType = response.headers.get("content-type") ?? "multipart/form-data";
59
+ const body = new Uint8Array(await response.arrayBuffer());
60
+ return { body, contentType };
61
+ }
package/dist/sse.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { type JsonValue } from "./json.js";
2
+ export interface SseFrame<T extends JsonValue = JsonValue> {
3
+ event: string;
4
+ data: T;
5
+ rawData: string;
6
+ id?: string;
7
+ }
8
+ /**
9
+ * Decodes a Server-Sent Events (text/event-stream) ReadableStream into structured frames,
10
+ * handling arbitrary chunk splits, multi-byte UTF-8 sequences, CRLF/LF line endings, and comments.
11
+ */
12
+ export declare function parseSseStream<T extends JsonValue = JsonValue>(stream: ReadableStream<Uint8Array>): AsyncGenerator<SseFrame<T>, void, undefined>;
package/dist/sse.js ADDED
@@ -0,0 +1,99 @@
1
+ import { parseJsonValue } from "./json.js";
2
+ function tryParseFrameData(raw) {
3
+ try {
4
+ return parseJsonValue(raw);
5
+ }
6
+ catch {
7
+ return raw;
8
+ }
9
+ }
10
+ /**
11
+ * Decodes a Server-Sent Events (text/event-stream) ReadableStream into structured frames,
12
+ * handling arbitrary chunk splits, multi-byte UTF-8 sequences, CRLF/LF line endings, and comments.
13
+ */
14
+ export async function* parseSseStream(stream) {
15
+ const reader = stream.getReader();
16
+ const decoder = new TextDecoder("utf-8");
17
+ let buffer = "";
18
+ let eventName = "message";
19
+ let dataLines = [];
20
+ let lastEventId;
21
+ const flushFrame = () => {
22
+ if (dataLines.length === 0) {
23
+ eventName = "message";
24
+ return null;
25
+ }
26
+ const rawData = dataLines.join("\n");
27
+ // SAFETY: Caller supplies T matching the endpoint's SSE JSON contract; non-JSON frames retain their raw string.
28
+ const data = tryParseFrameData(rawData);
29
+ const frame = {
30
+ event: eventName,
31
+ data,
32
+ rawData,
33
+ };
34
+ if (lastEventId !== undefined) {
35
+ frame.id = lastEventId;
36
+ }
37
+ eventName = "message";
38
+ dataLines = [];
39
+ return frame;
40
+ };
41
+ const processLine = (line) => {
42
+ if (line === "") {
43
+ return flushFrame();
44
+ }
45
+ if (line.startsWith(":")) {
46
+ return null;
47
+ }
48
+ const colon = line.indexOf(":");
49
+ const field = colon === -1 ? line : line.slice(0, colon);
50
+ let value = colon === -1 ? "" : line.slice(colon + 1);
51
+ if (value.startsWith(" ")) {
52
+ value = value.slice(1);
53
+ }
54
+ if (field === "event") {
55
+ eventName = value || "message";
56
+ }
57
+ else if (field === "data") {
58
+ dataLines.push(value);
59
+ }
60
+ else if (field === "id" && !value.includes("\0")) {
61
+ lastEventId = value;
62
+ }
63
+ return null;
64
+ };
65
+ try {
66
+ while (true) {
67
+ const { value, done } = await reader.read();
68
+ if (done) {
69
+ buffer += decoder.decode();
70
+ break;
71
+ }
72
+ buffer += decoder.decode(value, { stream: true });
73
+ let newlineIndex = buffer.indexOf("\n");
74
+ while (newlineIndex !== -1) {
75
+ let line = buffer.slice(0, newlineIndex);
76
+ if (line.endsWith("\r")) {
77
+ line = line.slice(0, -1);
78
+ }
79
+ buffer = buffer.slice(newlineIndex + 1);
80
+ const frame = processLine(line);
81
+ if (frame)
82
+ yield frame;
83
+ newlineIndex = buffer.indexOf("\n");
84
+ }
85
+ }
86
+ if (buffer.length > 0) {
87
+ const trailing = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
88
+ const frame = processLine(trailing);
89
+ if (frame)
90
+ yield frame;
91
+ }
92
+ const finalFrame = flushFrame();
93
+ if (finalFrame)
94
+ yield finalFrame;
95
+ }
96
+ finally {
97
+ reader.releaseLock();
98
+ }
99
+ }
@@ -0,0 +1,114 @@
1
+ import { type JsonObject } from "./json.js";
2
+ export interface Ed25519Jwk {
3
+ kty: "OKP";
4
+ crv: "Ed25519";
5
+ x: string;
6
+ kid: string;
7
+ use?: string;
8
+ alg?: string;
9
+ }
10
+ export interface JsonWebKeySet {
11
+ keys: Ed25519Jwk[];
12
+ }
13
+ export interface SignRequestOptions {
14
+ method: string;
15
+ url: string;
16
+ bodyBytes?: Uint8Array;
17
+ secret: string;
18
+ timestamp?: number;
19
+ }
20
+ export interface VerifyWebhookSignatureOptions {
21
+ rawBody: string | Uint8Array;
22
+ signatureHeader: string | null | undefined;
23
+ secret: string;
24
+ toleranceSeconds?: number;
25
+ now?: number;
26
+ }
27
+ export type VerifyWebhookSignatureResult = {
28
+ valid: true;
29
+ timestamp: number;
30
+ } | {
31
+ valid: false;
32
+ reason: string;
33
+ };
34
+ export interface VerifyPixelTraceManifestOptions {
35
+ manifest: string;
36
+ signature: string;
37
+ keyId: string;
38
+ jwksUrl?: string;
39
+ jwks?: JsonWebKeySet;
40
+ allowTest?: boolean;
41
+ fetch?: typeof globalThis.fetch;
42
+ cacheTtlMs?: number;
43
+ now?: number;
44
+ }
45
+ export type VerifyPixelTraceManifestResult = {
46
+ valid: true;
47
+ keyId: string;
48
+ manifest: JsonObject;
49
+ } | {
50
+ valid: false;
51
+ reason: string;
52
+ error: string;
53
+ };
54
+ export interface ParsedMcr1Receipt {
55
+ format: "mcr1";
56
+ verdict: "allow" | "mask_warn" | "confirm" | "block";
57
+ enforce: boolean;
58
+ shadow: boolean;
59
+ expires: number;
60
+ expiresAt: string;
61
+ checkId: string;
62
+ }
63
+ export interface VerifyMessageCheckReceiptOptions {
64
+ receipt: string;
65
+ text: string;
66
+ maskedText?: string;
67
+ conversationId?: string;
68
+ senderId?: string;
69
+ jwksUrl?: string;
70
+ jwks?: JsonWebKeySet;
71
+ fetch?: typeof globalThis.fetch;
72
+ cacheTtlMs?: number;
73
+ now?: number;
74
+ }
75
+ export type VerifyMessageCheckReceiptResult = {
76
+ valid: true;
77
+ verdict: string;
78
+ enforce: boolean;
79
+ shadow: boolean;
80
+ checkId: string;
81
+ expiresAt: string;
82
+ claims: JsonObject;
83
+ } | {
84
+ valid: false;
85
+ reason: string;
86
+ error: string;
87
+ parsed?: ParsedMcr1Receipt;
88
+ };
89
+ export declare function clearJwksCache(): void;
90
+ /**
91
+ * Signs an outbound API request using PCIFIC's request signing contract:
92
+ * HMAC-SHA256 over "{t}.{METHOD}.{pathname}{search}.{exact body bytes}".
93
+ */
94
+ export declare function signRequest(options: SignRequestOptions): Promise<string>;
95
+ /**
96
+ * Verifies an inbound PCIFIC webhook PCIFIC-Signature header using constant-time comparison:
97
+ * HMAC-SHA256 over "{t}.{rawBody}".
98
+ */
99
+ export declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<VerifyWebhookSignatureResult>;
100
+ /**
101
+ * Verifies a PixelTrace signed manifest offline using PCIFIC's Ed25519 JWKS
102
+ * (GET /api/v1/pixel-trace/jwks.json or /.well-known/jwks.json).
103
+ */
104
+ export declare function verifyPixelTraceManifest(options: VerifyPixelTraceManifestOptions): Promise<VerifyPixelTraceManifestResult>;
105
+ /**
106
+ * Structurally parses a PCIFIC Message Check mcr1 receipt token without verifying its server-side MAC.
107
+ */
108
+ export declare function parseMessageCheckReceipt(receipt: string): ParsedMcr1Receipt | null;
109
+ /**
110
+ * Verifies a Message Check receipt offline when given an Ed25519 JWS receipt,
111
+ * or reports clearly when given a server-HMAC mcr1 receipt that requires online verification
112
+ * via POST /api/v1/message-check/receipts/verify (client.messageCheck.verifyReceiptOnline).
113
+ */
114
+ export declare function verifyMessageCheckReceipt(options: VerifyMessageCheckReceiptOptions): Promise<VerifyMessageCheckReceiptResult>;