@ahmedramez-org/chat 0.0.0-stage → 0.6.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/README.md +373 -2
- package/contract/bridge.d.ts +119 -0
- package/contract/bridge.js +249 -0
- package/contract/conformance.d.ts +51 -0
- package/contract/conformance.js +335 -0
- package/contract/host.d.ts +213 -0
- package/contract/host.js +380 -0
- package/contract/index.d.ts +922 -0
- package/contract/index.js +94 -0
- package/contract/launch.d.ts +110 -0
- package/contract/launch.js +164 -0
- package/index.d.ts +51 -0
- package/index.js +424 -0
- package/package.json +77 -4
- package/react.d.ts +129 -0
- package/react.js +312 -0
- package/window.js +515 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The embed page's message protocol (`embed.html`, HOST-INTEGRATION §4c): what the chat page
|
|
3
|
+
* and the page or app that shows it say to each other, in both directions. Framework-free,
|
|
4
|
+
* like the rest of the contract, so the chat and every app compile against this one file.
|
|
5
|
+
*
|
|
6
|
+
* `@incorta/chat/bridge`
|
|
7
|
+
*
|
|
8
|
+
* Every message names itself in `incortaChat`. The chat page and the cookie embed's window
|
|
9
|
+
* stamp `v: CONTRACT_VERSION` (`./index`) on every message they send, `createTokenModeLink` on
|
|
10
|
+
* its `hello`. `v` is checked at the handshake only:
|
|
11
|
+
* - the app refuses a `loaded` whose `v` is not its `CONTRACT_VERSION` (a missing one
|
|
12
|
+
* included): the launch fails `incompatible` and the page gets no `hello` and no token
|
|
13
|
+
* (nor does a page that has not said `loaded` yet: the app hears nothing before it);
|
|
14
|
+
* - the chat page refuses such a `hello`: `ready` with `mounted: false` and reason
|
|
15
|
+
* `incompatible`, and the chat never starts on that page (one already up ends).
|
|
16
|
+
* Every other message is read whatever its `v`, and an unknown one is ignored.
|
|
17
|
+
*/
|
|
18
|
+
import { SURFACE_NAMES, } from './index.js';
|
|
19
|
+
import { LAUNCH_FAILURES, LAUNCH_STEPS } from './launch.js';
|
|
20
|
+
const WINDOW_MODES = ['floating', 'docked', 'fullscreen'];
|
|
21
|
+
const isMode = (mode) => WINDOW_MODES.includes(mode);
|
|
22
|
+
const ACTIVITIES = [
|
|
23
|
+
'prompt',
|
|
24
|
+
'human-input',
|
|
25
|
+
'cancel',
|
|
26
|
+
'upload',
|
|
27
|
+
'history-mutation',
|
|
28
|
+
];
|
|
29
|
+
const surfaceNames = (value) => Array.isArray(value) ? SURFACE_NAMES.filter((name) => value.includes(name)) : [];
|
|
30
|
+
const text = (value) => typeof value === 'string';
|
|
31
|
+
/** The handshake's `v` as sent, when it is a number: the side that reads it compares it. */
|
|
32
|
+
const version = (v) => (typeof v === 'number' ? { v } : {});
|
|
33
|
+
/** A user's name as `hello` carries it, or `undefined` for none (or an empty one). */
|
|
34
|
+
const userName = (raw) => {
|
|
35
|
+
const { name } = Object(raw);
|
|
36
|
+
return text(name) && name.trim() ? name : undefined;
|
|
37
|
+
};
|
|
38
|
+
/** An intent with exactly the fields its type needs, or `undefined`. */
|
|
39
|
+
function intent(raw) {
|
|
40
|
+
const { surface, type, pickerId, canvasId, id, query, title, sessionId, files, more, value } = Object(raw);
|
|
41
|
+
if (surface === 'header') {
|
|
42
|
+
if (type === 'newChat' || type === 'openHistory')
|
|
43
|
+
return { surface, type };
|
|
44
|
+
if (!text(sessionId))
|
|
45
|
+
return undefined;
|
|
46
|
+
if (type === 'delete' || type === 'openLogs' || type === 'reportIssue') {
|
|
47
|
+
return { surface, type, sessionId };
|
|
48
|
+
}
|
|
49
|
+
return type === 'rename' && text(title) ? { surface, type, sessionId, title } : undefined;
|
|
50
|
+
}
|
|
51
|
+
if (surface === 'canvas') {
|
|
52
|
+
// A close names the canvas it was drawn from, or none (an app from before `canvasId`).
|
|
53
|
+
if (type === 'close' && canvasId === undefined)
|
|
54
|
+
return { surface: 'canvas', type };
|
|
55
|
+
if (!Number.isInteger(canvasId))
|
|
56
|
+
return undefined;
|
|
57
|
+
const shown = { surface: 'canvas', canvasId: canvasId };
|
|
58
|
+
if (type === 'close')
|
|
59
|
+
return { ...shown, type };
|
|
60
|
+
return type === 'action' && text(id) ? { ...shown, type, id } : undefined;
|
|
61
|
+
}
|
|
62
|
+
if (surface === 'model') {
|
|
63
|
+
if (type === 'dismiss')
|
|
64
|
+
return { surface, type };
|
|
65
|
+
return type === 'select' && text(value) ? { surface, type, value } : undefined;
|
|
66
|
+
}
|
|
67
|
+
if (surface === 'history') {
|
|
68
|
+
if (type === 'open' || type === 'dismiss' || type === 'more')
|
|
69
|
+
return { surface, type };
|
|
70
|
+
if (type === 'query')
|
|
71
|
+
return text(query) ? { surface, type, query } : undefined;
|
|
72
|
+
if (!text(id))
|
|
73
|
+
return undefined;
|
|
74
|
+
if (type === 'select' || type === 'delete')
|
|
75
|
+
return { surface, type, id };
|
|
76
|
+
return type === 'rename' && text(title) ? { surface, type, id, title } : undefined;
|
|
77
|
+
}
|
|
78
|
+
if (surface !== 'picker')
|
|
79
|
+
return undefined;
|
|
80
|
+
if (type === 'open')
|
|
81
|
+
return { surface, type };
|
|
82
|
+
if (!Number.isInteger(pickerId))
|
|
83
|
+
return undefined;
|
|
84
|
+
const opened = { surface: 'picker', pickerId: pickerId };
|
|
85
|
+
if (type === 'back' || type === 'more' || type === 'dismiss')
|
|
86
|
+
return { ...opened, type };
|
|
87
|
+
if (type === 'query')
|
|
88
|
+
return text(query) ? { ...opened, type, query } : undefined;
|
|
89
|
+
if (type === 'drill' || type === 'pick')
|
|
90
|
+
return text(id) ? { ...opened, type, id } : undefined;
|
|
91
|
+
if (type !== 'upload' || !text(id) || !Array.isArray(files))
|
|
92
|
+
return undefined;
|
|
93
|
+
const picked = files.flatMap((file) => {
|
|
94
|
+
const { name, type: mediaType, data } = Object(file);
|
|
95
|
+
return text(name) && text(mediaType) && text(data) && BASE64.test(data)
|
|
96
|
+
? [{ name, type: mediaType, data }]
|
|
97
|
+
: [];
|
|
98
|
+
});
|
|
99
|
+
return picked.length === files.length
|
|
100
|
+
? { ...opened, type, id, files: picked, ...(more === true ? { more } : {}) }
|
|
101
|
+
: undefined;
|
|
102
|
+
}
|
|
103
|
+
/** A computed CSS colour as a browser reports it: `rgb(16, 24, 27)` or `rgba(0, 0, 0, 0.5)`. */
|
|
104
|
+
const RGB = /^rgba?\(\s*\d{1,3}(?:\s*,\s*\d{1,3}){2}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/;
|
|
105
|
+
/** A file's bytes as the host sends them: base64, padded or not. */
|
|
106
|
+
const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
107
|
+
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
108
|
+
function windowState(raw) {
|
|
109
|
+
const { docked, canDock, mode, modes, hidden } = Object(raw);
|
|
110
|
+
const named = Array.isArray(modes) ? modes.filter(isMode) : undefined;
|
|
111
|
+
return {
|
|
112
|
+
docked: docked === true,
|
|
113
|
+
canDock: canDock === true,
|
|
114
|
+
// A newer page names its window and the others it can switch to.
|
|
115
|
+
...(isMode(mode) && named ? { mode, modes: named } : {}),
|
|
116
|
+
// The page minimized the window: the chat is still here, out of sight.
|
|
117
|
+
...(hidden === true ? { hidden: true } : {}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** The lists each published surface must carry; the app reads them without a check. */
|
|
121
|
+
const SURFACE_LISTS = {
|
|
122
|
+
header: [],
|
|
123
|
+
picker: ['rows', 'path'],
|
|
124
|
+
history: ['rows'],
|
|
125
|
+
model: ['options'],
|
|
126
|
+
canvas: ['actions'],
|
|
127
|
+
};
|
|
128
|
+
const isObject = (value) => typeof value === 'object' && value !== null;
|
|
129
|
+
/** Keeps each surface that is an object with its lists of objects; drops the others (absent: closed). */
|
|
130
|
+
function surfaceState(raw) {
|
|
131
|
+
const state = {};
|
|
132
|
+
for (const name of SURFACE_NAMES) {
|
|
133
|
+
const surface = raw[name];
|
|
134
|
+
if (isObject(surface) &&
|
|
135
|
+
SURFACE_LISTS[name].every((key) => {
|
|
136
|
+
const list = surface[key];
|
|
137
|
+
return Array.isArray(list) && list.every(isObject);
|
|
138
|
+
})) {
|
|
139
|
+
state[name] = surface;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return state;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Reads one message off the bridge, in either direction: the message, typed and with
|
|
146
|
+
* every field checked, or `undefined` for anything that is not one (another sender's
|
|
147
|
+
* message, an unknown name, a token that is not a string). A `surfaces` state is checked
|
|
148
|
+
* surface by surface: one that is not an object, lacks its lists or lists something that is
|
|
149
|
+
* not an object is dropped; the fields of a row are not checked. Each side handles the names
|
|
150
|
+
* it knows and ignores the rest.
|
|
151
|
+
*/
|
|
152
|
+
export function parse(data) {
|
|
153
|
+
if (typeof data !== 'object' || data === null)
|
|
154
|
+
return undefined;
|
|
155
|
+
const raw = data;
|
|
156
|
+
switch (raw.incortaChat) {
|
|
157
|
+
case 'loaded':
|
|
158
|
+
return { incortaChat: 'loaded', ...version(raw.v) };
|
|
159
|
+
case 'close':
|
|
160
|
+
case 'signedOut':
|
|
161
|
+
case 'active':
|
|
162
|
+
case 'signOut':
|
|
163
|
+
case 'openAccount':
|
|
164
|
+
case 'microphoneBlocked':
|
|
165
|
+
return { incortaChat: raw.incortaChat };
|
|
166
|
+
case 'ready':
|
|
167
|
+
return {
|
|
168
|
+
incortaChat: 'ready',
|
|
169
|
+
mounted: raw.mounted === true,
|
|
170
|
+
...(Array.isArray(raw.surfaces) ? { surfaces: surfaceNames(raw.surfaces) } : {}),
|
|
171
|
+
...(LAUNCH_FAILURES.includes(raw.reason)
|
|
172
|
+
? { reason: raw.reason }
|
|
173
|
+
: {}),
|
|
174
|
+
...(raw.topInset === true ? { topInset: true } : {}),
|
|
175
|
+
};
|
|
176
|
+
case 'progress':
|
|
177
|
+
return LAUNCH_STEPS.includes(raw.step)
|
|
178
|
+
? { incortaChat: 'progress', step: raw.step }
|
|
179
|
+
: undefined;
|
|
180
|
+
case 'hello': {
|
|
181
|
+
const name = userName(raw.user);
|
|
182
|
+
return {
|
|
183
|
+
incortaChat: 'hello',
|
|
184
|
+
...version(raw.v),
|
|
185
|
+
surfaces: surfaceNames(raw.surfaces),
|
|
186
|
+
...(raw.files === true ? { files: true } : {}),
|
|
187
|
+
...(raw.conversationLoader === true ? { conversationLoader: true } : {}),
|
|
188
|
+
...(raw.account === true ? { account: true } : {}),
|
|
189
|
+
...(raw.focusNewChat === true ? { focusNewChat: true } : {}),
|
|
190
|
+
...(raw.systemFont === true ? { systemFont: true } : {}),
|
|
191
|
+
...(name ? { user: { name } } : {}),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
case 'background':
|
|
195
|
+
return typeof raw.color === 'string' && RGB.test(raw.color)
|
|
196
|
+
? { incortaChat: 'background', color: raw.color }
|
|
197
|
+
: undefined;
|
|
198
|
+
case 'file':
|
|
199
|
+
return typeof raw.name === 'string' &&
|
|
200
|
+
raw.name &&
|
|
201
|
+
typeof raw.type === 'string' &&
|
|
202
|
+
typeof raw.data === 'string'
|
|
203
|
+
? { incortaChat: 'file', name: raw.name, type: raw.type, data: raw.data }
|
|
204
|
+
: undefined;
|
|
205
|
+
case 'intent': {
|
|
206
|
+
const read = intent(raw.intent);
|
|
207
|
+
return read ? { incortaChat: 'intent', intent: read } : undefined;
|
|
208
|
+
}
|
|
209
|
+
// From the chat page itself: the app draws what it publishes.
|
|
210
|
+
case 'surfaces':
|
|
211
|
+
return typeof raw.state === 'object' && raw.state !== null
|
|
212
|
+
? { incortaChat: 'surfaces', state: surfaceState(raw.state) }
|
|
213
|
+
: undefined;
|
|
214
|
+
case 'activity':
|
|
215
|
+
return ACTIVITIES.includes(raw.activity)
|
|
216
|
+
? { incortaChat: 'activity', activity: raw.activity }
|
|
217
|
+
: undefined;
|
|
218
|
+
case 'mode':
|
|
219
|
+
return isMode(raw.mode) ? { incortaChat: 'mode', mode: raw.mode } : undefined;
|
|
220
|
+
case 'dock':
|
|
221
|
+
return { incortaChat: 'dock', docked: raw.docked === true };
|
|
222
|
+
case 'authRequired':
|
|
223
|
+
return raw.reason === 'rejected'
|
|
224
|
+
? { incortaChat: 'authRequired', reason: 'rejected' }
|
|
225
|
+
: { incortaChat: 'authRequired' };
|
|
226
|
+
case 'auth':
|
|
227
|
+
if (typeof raw.token !== 'string' || !raw.token)
|
|
228
|
+
return undefined;
|
|
229
|
+
return {
|
|
230
|
+
incortaChat: 'auth',
|
|
231
|
+
token: raw.token,
|
|
232
|
+
...(finite(raw.expiresAt) ? { expiresAt: raw.expiresAt } : {}),
|
|
233
|
+
};
|
|
234
|
+
case 'style':
|
|
235
|
+
return {
|
|
236
|
+
incortaChat: 'style',
|
|
237
|
+
...(raw.theme === 'light' || raw.theme === 'dark' ? { theme: raw.theme } : {}),
|
|
238
|
+
...(typeof raw.locale === 'string' && raw.locale ? { locale: raw.locale } : {}),
|
|
239
|
+
...(finite(raw.remBase) ? { remBase: raw.remBase } : {}),
|
|
240
|
+
...(raw.window ? { window: windowState(raw.window) } : {}),
|
|
241
|
+
...(finite(raw.keyboardInset) && raw.keyboardInset >= 0
|
|
242
|
+
? { keyboardInset: raw.keyboardInset }
|
|
243
|
+
: {}),
|
|
244
|
+
...(finite(raw.topInset) && raw.topInset >= 0 ? { topInset: raw.topInset } : {}),
|
|
245
|
+
};
|
|
246
|
+
default:
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type HostArtifactRendererCapability, type ChatArtifact, type ChatOptions } from './index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Executable conformance checks for the chat's host contract.
|
|
4
|
+
*
|
|
5
|
+
* Every host builds its options in its own stack — web-react with Redux,
|
|
6
|
+
* Hikari with TanStack Query — so "it compiles against the types" proves very
|
|
7
|
+
* little. These checks exercise what the remote actually depends on: a valid
|
|
8
|
+
* environment, subscription teardown, well-formed contexts, triggers and
|
|
9
|
+
* actions, and the mount lifecycle of a host-native renderer.
|
|
10
|
+
*
|
|
11
|
+
* Deliberately free of any test framework. Consumers run it from whatever
|
|
12
|
+
* runner they already have and assert on the report, and the remote can expose
|
|
13
|
+
* it over federation so a consumer verifies the exact build it loads.
|
|
14
|
+
*/
|
|
15
|
+
export type ContractCheckStatus = 'passed' | 'failed' | 'skipped';
|
|
16
|
+
export interface ContractCheckResult {
|
|
17
|
+
id: string;
|
|
18
|
+
title: string;
|
|
19
|
+
status: ContractCheckStatus;
|
|
20
|
+
/** Why it failed, or why there was nothing to check. */
|
|
21
|
+
detail?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface HostContractReport {
|
|
24
|
+
results: readonly ContractCheckResult[];
|
|
25
|
+
failures: readonly ContractCheckResult[];
|
|
26
|
+
skipped: readonly ContractCheckResult[];
|
|
27
|
+
passed: boolean;
|
|
28
|
+
}
|
|
29
|
+
export interface ArtifactRendererContractOptions {
|
|
30
|
+
/**
|
|
31
|
+
* Artifacts the consumer claims to render natively. At least one is required:
|
|
32
|
+
* the lifecycle cannot be observed without a payload the host accepts.
|
|
33
|
+
*/
|
|
34
|
+
artifacts: readonly ChatArtifact[];
|
|
35
|
+
/** Overridable so a consumer can supply a container inside its own tree. */
|
|
36
|
+
createElement?: () => HTMLElement;
|
|
37
|
+
}
|
|
38
|
+
export interface HostContractOptions {
|
|
39
|
+
renderer?: ArtifactRendererContractOptions;
|
|
40
|
+
/** Consumer test hook that changes one environment source (theme, locale) in place. */
|
|
41
|
+
triggerEnvironmentChange?: () => void | Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Verifies the mount lifecycle the remote relies on: the host paints only into
|
|
45
|
+
* the element it is given, keeps that element across an update, and leaves it
|
|
46
|
+
* empty on unmount so the remote can reuse or discard it.
|
|
47
|
+
*/
|
|
48
|
+
export declare function checkArtifactRendererContract(capability: HostArtifactRendererCapability, options: ArtifactRendererContractOptions): Promise<HostContractReport>;
|
|
49
|
+
export declare function checkHostContract(options: ChatOptions, checkOptions?: HostContractOptions): Promise<HostContractReport>;
|
|
50
|
+
/** Human-readable summary for a consumer's test failure output. */
|
|
51
|
+
export declare function formatHostContractReport(report: HostContractReport): string;
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { BUILT_IN_CONTEXT_KINDS, CONTRACT_VERSION, SURFACE_NAMES, } from './index.js';
|
|
2
|
+
class CheckCollector {
|
|
3
|
+
results = [];
|
|
4
|
+
async run(id, title, check) {
|
|
5
|
+
try {
|
|
6
|
+
await check();
|
|
7
|
+
this.results.push({ id, title, status: 'passed' });
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
catch (cause) {
|
|
11
|
+
this.results.push({
|
|
12
|
+
id,
|
|
13
|
+
title,
|
|
14
|
+
status: 'failed',
|
|
15
|
+
detail: cause instanceof Error ? cause.message : String(cause),
|
|
16
|
+
});
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
skip(id, title, detail) {
|
|
21
|
+
this.results.push({ id, title, status: 'skipped', detail });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function ensure(condition, message) {
|
|
25
|
+
if (!condition)
|
|
26
|
+
throw new Error(message);
|
|
27
|
+
}
|
|
28
|
+
function toReport(results) {
|
|
29
|
+
const failures = results.filter((result) => result.status === 'failed');
|
|
30
|
+
return {
|
|
31
|
+
results,
|
|
32
|
+
failures,
|
|
33
|
+
skipped: results.filter((result) => result.status === 'skipped'),
|
|
34
|
+
passed: failures.length === 0,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function renderRequest(artifact, placement) {
|
|
38
|
+
return {
|
|
39
|
+
artifact,
|
|
40
|
+
messageId: 'contract-check-message',
|
|
41
|
+
taskId: 'contract-check-task',
|
|
42
|
+
placement,
|
|
43
|
+
isHistorical: false,
|
|
44
|
+
appearance: { theme: 'light', direction: 'ltr', locale: 'en' },
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Verifies the mount lifecycle the remote relies on: the host paints only into
|
|
49
|
+
* the element it is given, keeps that element across an update, and leaves it
|
|
50
|
+
* empty on unmount so the remote can reuse or discard it.
|
|
51
|
+
*/
|
|
52
|
+
export async function checkArtifactRendererContract(capability, options) {
|
|
53
|
+
const checks = new CheckCollector();
|
|
54
|
+
const createElement = options.createElement ?? (() => document.createElement('div'));
|
|
55
|
+
const accepted = options.artifacts.filter((artifact) => {
|
|
56
|
+
try {
|
|
57
|
+
return capability.canRender(renderRequest(artifact, 'canvas'));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
await checks.run('renderer.canRender.total', 'canRender never throws', () => {
|
|
64
|
+
options.artifacts.forEach((artifact) => {
|
|
65
|
+
capability.canRender(renderRequest(artifact, 'canvas'));
|
|
66
|
+
capability.canRender(renderRequest(artifact, 'inline'));
|
|
67
|
+
const title = capability.getTitle?.(artifact);
|
|
68
|
+
ensure(title === undefined || (typeof title === 'string' && title.trim().length > 0), 'The optional renderer title must be a non-empty string or undefined.');
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
await checks.run('renderer.canRender.declines', 'canRender declines unknown artifact kinds', () => {
|
|
72
|
+
const declined = capability.canRender(renderRequest({ id: 'contract-check-unknown', kind: 'contract-check-unknown', data: null }, 'canvas'));
|
|
73
|
+
ensure(declined === false, 'canRender accepted an artifact of an unknown kind; the remote would render an empty frame.');
|
|
74
|
+
});
|
|
75
|
+
if (accepted.length === 0) {
|
|
76
|
+
const detail = 'No supplied artifact was accepted by canRender, so the mount lifecycle could not be observed.';
|
|
77
|
+
[
|
|
78
|
+
'renderer.mount.paints',
|
|
79
|
+
'renderer.mount.isolated',
|
|
80
|
+
'renderer.update.keepsElement',
|
|
81
|
+
'renderer.unmount.empties',
|
|
82
|
+
'renderer.unmount.idempotent',
|
|
83
|
+
].forEach((id) => checks.skip(id, id, detail));
|
|
84
|
+
return toReport(checks.results);
|
|
85
|
+
}
|
|
86
|
+
const artifact = accepted[0];
|
|
87
|
+
await checks.run('renderer.mount.paints', 'mount paints into the supplied element', async () => {
|
|
88
|
+
const element = createElement();
|
|
89
|
+
const mount = capability.mount(element, renderRequest(artifact, 'canvas'));
|
|
90
|
+
const painted = await paintsWithin(element);
|
|
91
|
+
mount.unmount();
|
|
92
|
+
await settle();
|
|
93
|
+
ensure(painted, 'mount produced no DOM inside the element supplied by the remote.');
|
|
94
|
+
});
|
|
95
|
+
await checks.run('renderer.mount.isolated', 'mount touches no element but its own', async () => {
|
|
96
|
+
const scope = document.createElement('div');
|
|
97
|
+
const element = createElement();
|
|
98
|
+
scope.appendChild(element);
|
|
99
|
+
const bodyChildren = new Set(document.body.children);
|
|
100
|
+
const headChildren = new Set(document.head.children);
|
|
101
|
+
document.body.appendChild(scope);
|
|
102
|
+
try {
|
|
103
|
+
const mount = capability.mount(element, renderRequest(artifact, 'canvas'));
|
|
104
|
+
await settle();
|
|
105
|
+
const leakedToBody = [...document.body.children].some((child) => child !== scope && !bodyChildren.has(child));
|
|
106
|
+
const leakedInsideScope = [...scope.children].some((child) => child !== element);
|
|
107
|
+
// A new <style> in the head is not a leak. Every CSS-in-JS host injects
|
|
108
|
+
// one on first render — antd's token sheet, emotion, styled-components —
|
|
109
|
+
// and that sheet is how the host's own BI content gets styled at all. It
|
|
110
|
+
// is deduplicated by the library and shared with the rest of the host
|
|
111
|
+
// page. What must not appear is anything else: a script, an iframe, or a
|
|
112
|
+
// stylesheet <link> the remote never asked for.
|
|
113
|
+
const leakedToHead = [...document.head.children].some((child) => !headChildren.has(child) && child.tagName !== 'STYLE');
|
|
114
|
+
mount.unmount();
|
|
115
|
+
await settle();
|
|
116
|
+
ensure(!leakedToBody && !leakedInsideScope && !leakedToHead, 'mount wrote DOM outside the element supplied by the remote.');
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
scope.remove();
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
await checks.run('renderer.update.keepsElement', 'update re-paints in place', async () => {
|
|
123
|
+
const element = createElement();
|
|
124
|
+
let supportedViews = [];
|
|
125
|
+
const request = {
|
|
126
|
+
...renderRequest(artifact, 'canvas'),
|
|
127
|
+
onSupportedViewsChange: (views) => {
|
|
128
|
+
supportedViews = views;
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
const mount = capability.mount(element, request);
|
|
132
|
+
try {
|
|
133
|
+
await paintsWithin(element);
|
|
134
|
+
ensure(Array.isArray(supportedViews) &&
|
|
135
|
+
supportedViews.every((view) => view === 'chart' || view === 'table') &&
|
|
136
|
+
new Set(supportedViews).size === supportedViews.length, 'The renderer advertised invalid or duplicate artifact views.');
|
|
137
|
+
for (const view of supportedViews) {
|
|
138
|
+
mount.update({ ...request, view });
|
|
139
|
+
ensure(await paintsStablyWithin(element), `The advertised ${view} view did not remain painted.`);
|
|
140
|
+
}
|
|
141
|
+
mount.update(renderRequest(artifact, 'inline'));
|
|
142
|
+
ensure(await paintsStablyWithin(element), 'update emptied the element instead of re-painting it.');
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
mount.unmount();
|
|
146
|
+
await settle();
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
await checks.run('renderer.unmount.empties', 'unmount leaves the element empty', async () => {
|
|
150
|
+
const element = createElement();
|
|
151
|
+
const mount = capability.mount(element, renderRequest(artifact, 'canvas'));
|
|
152
|
+
await settle();
|
|
153
|
+
mount.unmount();
|
|
154
|
+
await settle();
|
|
155
|
+
ensure(element.childElementCount === 0, 'unmount left DOM behind; the remote reuses and removes these elements.');
|
|
156
|
+
});
|
|
157
|
+
await checks.run('renderer.unmount.idempotent', 'unmount and post-unmount update are safe', async () => {
|
|
158
|
+
const element = createElement();
|
|
159
|
+
const mount = capability.mount(element, renderRequest(artifact, 'canvas'));
|
|
160
|
+
await settle();
|
|
161
|
+
mount.unmount();
|
|
162
|
+
await settle();
|
|
163
|
+
mount.unmount();
|
|
164
|
+
mount.update(renderRequest(artifact, 'canvas'));
|
|
165
|
+
await settle();
|
|
166
|
+
ensure(element.childElementCount === 0, 'an update after unmount re-painted a detached element.');
|
|
167
|
+
});
|
|
168
|
+
return toReport(checks.results);
|
|
169
|
+
}
|
|
170
|
+
/** Lets a host root commit and flush its own microtask-deferred teardown. */
|
|
171
|
+
function settle() {
|
|
172
|
+
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
173
|
+
}
|
|
174
|
+
const RENDER_STABILITY_MS = 50;
|
|
175
|
+
/**
|
|
176
|
+
* Polls for the element to paint, bounded. A host UI framework schedules its
|
|
177
|
+
* first commit, and in a real browser that can land a frame or two after
|
|
178
|
+
* `mount` returns — the contract requires painting, not painting within one
|
|
179
|
+
* macrotask (found by Hikari's built-remote e2e, the first consumer to run
|
|
180
|
+
* the renderer checks in a real browser). Timers only, so it behaves the same
|
|
181
|
+
* headless and under jsdom, where an immediate commit returns on the first
|
|
182
|
+
* probe.
|
|
183
|
+
*/
|
|
184
|
+
async function paintsWithin(element, timeoutMs = 2_000) {
|
|
185
|
+
const deadline = Date.now() + timeoutMs;
|
|
186
|
+
for (;;) {
|
|
187
|
+
if (element.childElementCount > 0)
|
|
188
|
+
return true;
|
|
189
|
+
if (Date.now() >= deadline)
|
|
190
|
+
return false;
|
|
191
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* An update starts with DOM from the previous render. Looking immediately can
|
|
196
|
+
* therefore miss a scheduled clear. Cross one scheduler boundary before
|
|
197
|
+
* probing, then require the element to remain painted for a defined stability
|
|
198
|
+
* window. This checks lifecycle continuity, not whether visual content changed.
|
|
199
|
+
*/
|
|
200
|
+
async function paintsStablyWithin(element) {
|
|
201
|
+
await settle();
|
|
202
|
+
if (!(await paintsWithin(element)))
|
|
203
|
+
return false;
|
|
204
|
+
await new Promise((resolve) => setTimeout(resolve, RENDER_STABILITY_MS));
|
|
205
|
+
return element.childElementCount > 0;
|
|
206
|
+
}
|
|
207
|
+
const CONTEXT_KINDS = [
|
|
208
|
+
'business-view',
|
|
209
|
+
'physical-table',
|
|
210
|
+
'insight',
|
|
211
|
+
'knowledge-store',
|
|
212
|
+
'ai-container',
|
|
213
|
+
];
|
|
214
|
+
const TRIGGER_CHARS = ['@', '#'];
|
|
215
|
+
export async function checkHostContract(options, checkOptions = {}) {
|
|
216
|
+
const checks = new CheckCollector();
|
|
217
|
+
const { connection, environment, chat, actions } = options;
|
|
218
|
+
await checks.run('version', 'declares the supported contract version', () => {
|
|
219
|
+
ensure(options.version === CONTRACT_VERSION, `version must be ${CONTRACT_VERSION}; received ${String(options.version)}.`);
|
|
220
|
+
});
|
|
221
|
+
await checks.run('connection', 'connection names a client and a chat service root', async () => {
|
|
222
|
+
ensure(typeof connection?.client === 'string' && connection.client.trim().length > 0, 'connection.client is required.');
|
|
223
|
+
ensure(typeof connection.url === 'string', 'connection.url is required.');
|
|
224
|
+
ensure(!/\/a2a\/?$/i.test(connection.url.trim()), `connection.url is the chat service's root, without /a2a; received ${JSON.stringify(connection.url)}.`);
|
|
225
|
+
if (connection.headers) {
|
|
226
|
+
const headers = await connection.headers();
|
|
227
|
+
ensure(headers && typeof headers === 'object', 'connection.headers() must return an object.');
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
await checks.run('environment', 'environment.get returns a theme and a locale', () => {
|
|
231
|
+
const snapshot = environment.get();
|
|
232
|
+
ensure(snapshot && typeof snapshot === 'object', 'environment.get did not return an object.');
|
|
233
|
+
ensure(snapshot.theme === 'light' || snapshot.theme === 'dark', `theme must be "light" or "dark"; received ${JSON.stringify(snapshot.theme)}.`);
|
|
234
|
+
ensure(typeof snapshot.locale === 'string' && snapshot.locale.length > 0, 'locale is required.');
|
|
235
|
+
});
|
|
236
|
+
await checks.run('environment.subscribe', 'subscribe returns a working unsubscribe', async () => {
|
|
237
|
+
let notifications = 0;
|
|
238
|
+
const unsubscribe = environment.subscribe(() => {
|
|
239
|
+
notifications += 1;
|
|
240
|
+
});
|
|
241
|
+
ensure(typeof unsubscribe === 'function', 'subscribe did not return an unsubscribe function.');
|
|
242
|
+
if (checkOptions.triggerEnvironmentChange) {
|
|
243
|
+
await checkOptions.triggerEnvironmentChange();
|
|
244
|
+
await settle();
|
|
245
|
+
ensure(notifications > 0, 'subscribe did not notify after an environment source changed.');
|
|
246
|
+
}
|
|
247
|
+
unsubscribe();
|
|
248
|
+
// The chat unsubscribes on unmount, and a host may tear a mount down
|
|
249
|
+
// twice; the second call must not throw.
|
|
250
|
+
unsubscribe();
|
|
251
|
+
if (checkOptions.triggerEnvironmentChange) {
|
|
252
|
+
const before = notifications;
|
|
253
|
+
await checkOptions.triggerEnvironmentChange();
|
|
254
|
+
await settle();
|
|
255
|
+
ensure(notifications === before, 'unsubscribe did not detach the listener.');
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
await checks.run('chat.contexts', 'each context is a built-in kind or a source with a loader', () => {
|
|
259
|
+
const kinds = (chat?.contexts ?? []).map((spec) => {
|
|
260
|
+
if (typeof spec === 'string') {
|
|
261
|
+
ensure(BUILT_IN_CONTEXT_KINDS.includes(spec), `unknown context ${JSON.stringify(spec)}; a bare string is one of the built-in kinds: ${BUILT_IN_CONTEXT_KINDS.join(', ')}.`);
|
|
262
|
+
return spec;
|
|
263
|
+
}
|
|
264
|
+
ensure(CONTEXT_KINDS.includes(spec.kind), `unknown context kind ${JSON.stringify(spec.kind)}.`);
|
|
265
|
+
ensure(typeof spec.load === 'function', `the ${spec.kind} source has no load().`);
|
|
266
|
+
return spec.kind;
|
|
267
|
+
});
|
|
268
|
+
ensure(new Set(kinds).size === kinds.length, 'a context kind is listed twice (a source replaces its bare kind: list only the source).');
|
|
269
|
+
});
|
|
270
|
+
await checks.run('chat.triggers', 'each trigger is a bare @ or #, or one with a search', () => {
|
|
271
|
+
const chars = (chat?.triggers ?? []).map((trigger) => {
|
|
272
|
+
if (typeof trigger === 'string') {
|
|
273
|
+
ensure(TRIGGER_CHARS.includes(trigger), `unknown trigger ${JSON.stringify(trigger)}; a bare string is one of: ${TRIGGER_CHARS.join(', ')}.`);
|
|
274
|
+
ensure(connection?.incortaApi?.type === 'bff', `the bare ${trigger} trigger needs a connection.incortaApi of type 'bff'.`);
|
|
275
|
+
return trigger;
|
|
276
|
+
}
|
|
277
|
+
ensure(TRIGGER_CHARS.includes(trigger.char), `unknown trigger ${JSON.stringify(trigger.char)}.`);
|
|
278
|
+
ensure(typeof trigger.search === 'function', `the ${trigger.char} trigger has no search().`);
|
|
279
|
+
return trigger.char;
|
|
280
|
+
});
|
|
281
|
+
ensure(new Set(chars).size === chars.length, 'a trigger is listed twice.');
|
|
282
|
+
});
|
|
283
|
+
await checks.run('chat.surfaces', 'each surface the host draws is named once', () => {
|
|
284
|
+
const owned = chat?.surfaces?.owned ?? [];
|
|
285
|
+
ensure(Array.isArray(owned), 'chat.surfaces.owned must be an array.');
|
|
286
|
+
owned.forEach((name) => ensure(SURFACE_NAMES.includes(name), `unknown surface ${JSON.stringify(name)}; one of: ${SURFACE_NAMES.join(', ')}.`));
|
|
287
|
+
ensure(new Set(owned).size === owned.length, 'a surface is listed twice.');
|
|
288
|
+
});
|
|
289
|
+
const sessionLink = chat?.sessionLink;
|
|
290
|
+
if (!sessionLink) {
|
|
291
|
+
checks.skip('chat.sessionLink', 'links reopen a conversation', 'No session link declared.');
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
await checks.run('chat.sessionLink', 'links reopen a conversation', () => {
|
|
295
|
+
const link = sessionLink('contract-check-session');
|
|
296
|
+
let absolute = false;
|
|
297
|
+
try {
|
|
298
|
+
absolute = typeof link === 'string' && /^https?:$/.test(new URL(link).protocol);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
// A relative path throws: the link must carry the host's origin.
|
|
302
|
+
}
|
|
303
|
+
ensure(absolute, `chat.sessionLink must return an absolute URL; received ${JSON.stringify(link)}.`);
|
|
304
|
+
ensure(link.includes('contract-check-session'), 'chat.sessionLink must carry the conversation id.');
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
await checks.run('actions', 'each action has can() and run()', () => {
|
|
308
|
+
Object.entries(actions ?? {}).forEach(([name, action]) => {
|
|
309
|
+
if (action === undefined)
|
|
310
|
+
return;
|
|
311
|
+
ensure(typeof action.can === 'function' && typeof action.run === 'function', `actions.${name} needs both can() and run(). Omit it rather than supplying a placeholder.`);
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
const renderer = chat?.renderers;
|
|
315
|
+
if (!renderer) {
|
|
316
|
+
checks.skip('renderers', 'provides a host-native renderer', 'No renderer declared.');
|
|
317
|
+
}
|
|
318
|
+
else if (!checkOptions.renderer) {
|
|
319
|
+
checks.skip('renderers', 'provides a host-native renderer', 'No renderable artifacts were supplied, so the renderer lifecycle was not exercised.');
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
const report = await checkArtifactRendererContract(renderer, checkOptions.renderer);
|
|
323
|
+
checks.results.push(...report.results);
|
|
324
|
+
}
|
|
325
|
+
return toReport(checks.results);
|
|
326
|
+
}
|
|
327
|
+
/** Human-readable summary for a consumer's test failure output. */
|
|
328
|
+
export function formatHostContractReport(report) {
|
|
329
|
+
return report.results
|
|
330
|
+
.map((result) => {
|
|
331
|
+
const mark = result.status === 'passed' ? '✓' : result.status === 'failed' ? '✗' : '–';
|
|
332
|
+
return `${mark} ${result.id} — ${result.title}${result.detail ? `\n ${result.detail}` : ''}`;
|
|
333
|
+
})
|
|
334
|
+
.join('\n');
|
|
335
|
+
}
|