@xpert-ai/plugin-sdk 3.23.0 → 3.23.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.
Files changed (55) hide show
  1. package/_object_without_properties_loose.cjs.js +16 -0
  2. package/_object_without_properties_loose.esm.js +14 -0
  3. package/analytics-result.cjs.js +212 -0
  4. package/analytics-result.esm.js +201 -0
  5. package/analytics.cjs.default.js +1 -0
  6. package/analytics.cjs.js +17 -0
  7. package/analytics.cjs.mjs +2 -0
  8. package/analytics.d.ts +1 -0
  9. package/analytics.esm.js +2 -0
  10. package/artifact-document.cjs.default.js +1 -0
  11. package/artifact-document.cjs.js +581 -0
  12. package/artifact-document.cjs.mjs +2 -0
  13. package/artifact-document.d.ts +1 -0
  14. package/artifact-document.esm.js +563 -0
  15. package/data-workbench.cjs.js +23 -6
  16. package/data-workbench.esm.js +23 -6
  17. package/docs/analytics.md +66 -0
  18. package/docs/artifact-documents.md +74 -0
  19. package/docs/artifact-drafts.md +24 -0
  20. package/docs/json-encoded-schema.md +19 -0
  21. package/docs/workspace-dataset-pipelines.md +120 -0
  22. package/docs/workspace-file-tools.md +60 -0
  23. package/index.cjs.js +84 -19
  24. package/index.esm.js +127 -82
  25. package/model-provider-toolset.cjs.js +1 -1
  26. package/model-provider-toolset.esm.js +1 -1
  27. package/model-provider.cjs.js +37 -1
  28. package/model-provider.esm.js +33 -2
  29. package/package.json +14 -2
  30. package/src/analytics.d.ts +3 -0
  31. package/src/artifact-document.d.ts +5 -0
  32. package/src/lib/agent/handoff/agent-runtime-message.contract.d.ts +10 -10
  33. package/src/lib/artifact-document/dependencies.d.ts +101 -0
  34. package/src/lib/artifact-document/host.d.ts +30 -0
  35. package/src/lib/artifact-document/protocol.d.ts +60 -0
  36. package/src/lib/artifact-document/runtime.d.ts +4 -0
  37. package/src/lib/artifact-document/sha256.d.ts +2 -0
  38. package/src/lib/core/index.d.ts +1 -0
  39. package/src/lib/core/json-encoded-schema.d.ts +15 -0
  40. package/src/lib/data/analytics/analytics-provider.d.ts +74 -0
  41. package/src/lib/data/analytics/analytics-result.d.ts +4 -0
  42. package/src/lib/data/analytics/analytics.registry.d.ts +10 -0
  43. package/src/lib/data/analytics/analytics.schema.d.ts +206 -0
  44. package/src/lib/data/analytics/index.d.ts +4 -0
  45. package/src/lib/data/datasource/index.d.ts +1 -0
  46. package/src/lib/data/datasource/workbench-adapter.d.ts +11 -1
  47. package/src/lib/data/datasource/workbench-sql.d.ts +12 -0
  48. package/src/lib/runtime/capabilities/artifact-drafts.d.ts +29 -0
  49. package/src/lib/runtime/capabilities/artifacts.d.ts +10 -0
  50. package/src/lib/runtime/capabilities/index.d.ts +1 -0
  51. package/src/lib/runtime/capabilities/sandbox-jobs.d.ts +36 -2
  52. package/src/lib/runtime/index.d.ts +2 -0
  53. package/src/lib/runtime/mutation-evidence.d.ts +7 -0
  54. package/src/lib/runtime/workspace-file-tools.d.ts +11 -0
  55. package/src/lib/sandbox/runtime-provider.d.ts +4 -0
@@ -0,0 +1,563 @@
1
+ import { z } from 'zod/v3';
2
+ import { _ as _object_without_properties_loose } from './_object_without_properties_loose.esm.js';
3
+
4
+ /** Wire namespace/version shared by the trusted host and its isolated document bootstrap. */ const ARTIFACT_DOCUMENT_CHANNEL = 'xpert.artifact-document';
5
+ const ARTIFACT_DOCUMENT_VERSION = 1;
6
+ /** Portable binding/control identifier; shape validation never grants resource access. */ const artifactDocumentId = z.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,79}$/);
7
+ const artifactDocumentValue = z.union([
8
+ z.string().max(4000),
9
+ z.number().finite(),
10
+ z.boolean(),
11
+ z.null()
12
+ ]);
13
+ const artifactDocumentControls = z.record(artifactDocumentId, artifactDocumentValue).refine((value)=>Object.keys(value).length <= 24, 'Too many controls');
14
+ /** The entire untrusted query envelope. Provider definitions, SQL and identity fields are forbidden. */ const artifactDocumentQuery = z.object({
15
+ type: z.literal('query'),
16
+ requestId: z.string().min(1).max(80),
17
+ bindingId: artifactDocumentId,
18
+ controls: artifactDocumentControls
19
+ }).strict();
20
+ /** Only public presentation context may cross into the untrusted frame. Never include credentials here. */ const artifactDocumentContext = z.object({
21
+ bindingIds: z.array(artifactDocumentId).max(64).refine((ids)=>new Set(ids).size === ids.length, 'Duplicate binding IDs'),
22
+ defaults: artifactDocumentControls,
23
+ theme: z.enum([
24
+ 'light',
25
+ 'dark'
26
+ ]),
27
+ locale: z.string().min(1).max(80)
28
+ }).strict();
29
+ /** Format/UTF-8 size gate, not a sanitizer. Isolation and server authorization enforce security. */ const artifactDocumentHtml = z.string().min(1).max(300000).superRefine((html, ctx)=>{
30
+ if (new TextEncoder().encode(html).byteLength > 300000 || !/<html[\s>]/i.test(html) || !/<body[\s>]/i.test(html)) ctx.addIssue({
31
+ code: 'custom',
32
+ message: 'Supply a complete UTF-8 HTML document, at most 300 KB'
33
+ });
34
+ });
35
+
36
+ // Why this exists: dependency verification is synchronous and also runs on HTTP
37
+ // intranets and in opaque-origin documents, where Web Crypto may be unavailable.
38
+ // SHA-256 per FIPS 180-4 sections 5/6.2; only for bounded public asset integrity.
39
+ // https://doi.org/10.6028/NIST.FIPS.180-4
40
+ const ROUND_CONSTANTS = new Uint32Array([
41
+ 0x428a2f98,
42
+ 0x71374491,
43
+ 0xb5c0fbcf,
44
+ 0xe9b5dba5,
45
+ 0x3956c25b,
46
+ 0x59f111f1,
47
+ 0x923f82a4,
48
+ 0xab1c5ed5,
49
+ 0xd807aa98,
50
+ 0x12835b01,
51
+ 0x243185be,
52
+ 0x550c7dc3,
53
+ 0x72be5d74,
54
+ 0x80deb1fe,
55
+ 0x9bdc06a7,
56
+ 0xc19bf174,
57
+ 0xe49b69c1,
58
+ 0xefbe4786,
59
+ 0x0fc19dc6,
60
+ 0x240ca1cc,
61
+ 0x2de92c6f,
62
+ 0x4a7484aa,
63
+ 0x5cb0a9dc,
64
+ 0x76f988da,
65
+ 0x983e5152,
66
+ 0xa831c66d,
67
+ 0xb00327c8,
68
+ 0xbf597fc7,
69
+ 0xc6e00bf3,
70
+ 0xd5a79147,
71
+ 0x06ca6351,
72
+ 0x14292967,
73
+ 0x27b70a85,
74
+ 0x2e1b2138,
75
+ 0x4d2c6dfc,
76
+ 0x53380d13,
77
+ 0x650a7354,
78
+ 0x766a0abb,
79
+ 0x81c2c92e,
80
+ 0x92722c85,
81
+ 0xa2bfe8a1,
82
+ 0xa81a664b,
83
+ 0xc24b8b70,
84
+ 0xc76c51a3,
85
+ 0xd192e819,
86
+ 0xd6990624,
87
+ 0xf40e3585,
88
+ 0x106aa070,
89
+ 0x19a4c116,
90
+ 0x1e376c08,
91
+ 0x2748774c,
92
+ 0x34b0bcb5,
93
+ 0x391c0cb3,
94
+ 0x4ed8aa4a,
95
+ 0x5b9cca4f,
96
+ 0x682e6ff3,
97
+ 0x748f82ee,
98
+ 0x78a5636f,
99
+ 0x84c87814,
100
+ 0x8cc70208,
101
+ 0x90befffa,
102
+ 0xa4506ceb,
103
+ 0xbef9a3f7,
104
+ 0xc67178f2
105
+ ]);
106
+ const rotateRight = (value, bits)=>value >>> bits | value << 32 - bits;
107
+ /** Internal one-shot digest. Callers bound asset sizes before allocating hashing buffers. */ function sha256Hex(bytes) {
108
+ const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64);
109
+ padded.set(bytes);
110
+ padded[bytes.length] = 0x80;
111
+ const view = new DataView(padded.buffer);
112
+ // SHA-256 appends the original bit length as a big-endian 64-bit integer.
113
+ view.setUint32(padded.length - 8, Math.floor(bytes.length / 0x20000000));
114
+ view.setUint32(padded.length - 4, bytes.length * 8 >>> 0);
115
+ const state = new Uint32Array([
116
+ 0x6a09e667,
117
+ 0xbb67ae85,
118
+ 0x3c6ef372,
119
+ 0xa54ff53a,
120
+ 0x510e527f,
121
+ 0x9b05688c,
122
+ 0x1f83d9ab,
123
+ 0x5be0cd19
124
+ ]);
125
+ const words = new Uint32Array(64);
126
+ for(let offset = 0; offset < padded.length; offset += 64){
127
+ for(let i = 0; i < 16; i++)words[i] = view.getUint32(offset + i * 4);
128
+ for(let i = 16; i < 64; i++){
129
+ const x = words[i - 15], y = words[i - 2];
130
+ const s0 = rotateRight(x, 7) ^ rotateRight(x, 18) ^ x >>> 3;
131
+ const s1 = rotateRight(y, 17) ^ rotateRight(y, 19) ^ y >>> 10;
132
+ words[i] = words[i - 16] + s0 + words[i - 7] + s1 >>> 0;
133
+ }
134
+ let [a, b, c, d, e, f, g, h] = state;
135
+ for(let i = 0; i < 64; i++){
136
+ const s1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
137
+ const choice = e & f ^ ~e & g;
138
+ const t1 = h + s1 + choice + ROUND_CONSTANTS[i] + words[i] >>> 0;
139
+ const s0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
140
+ const majority = a & b ^ a & c ^ b & c;
141
+ const t2 = s0 + majority >>> 0;
142
+ h = g;
143
+ g = f;
144
+ f = e;
145
+ e = d + t1 >>> 0;
146
+ d = c;
147
+ c = b;
148
+ b = a;
149
+ a = t1 + t2 >>> 0;
150
+ }
151
+ state[0] = state[0] + a >>> 0;
152
+ state[1] = state[1] + b >>> 0;
153
+ state[2] = state[2] + c >>> 0;
154
+ state[3] = state[3] + d >>> 0;
155
+ state[4] = state[4] + e >>> 0;
156
+ state[5] = state[5] + f >>> 0;
157
+ state[6] = state[6] + g >>> 0;
158
+ state[7] = state[7] + h >>> 0;
159
+ }
160
+ return Array.from(state, (word)=>word.toString(16).padStart(8, '0')).join('');
161
+ }
162
+
163
+ /** A lock is public metadata; only the trusted host resolves it to packaged, immutable bytes. */ const dependencyLockObject = z.object({
164
+ id: artifactDocumentId,
165
+ version: z.string().regex(/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/),
166
+ format: z.literal('classic-script'),
167
+ global: z.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]{0,79}$/).refine((value)=>![
168
+ 'window',
169
+ 'self',
170
+ 'globalThis',
171
+ 'document',
172
+ 'parent',
173
+ 'top',
174
+ 'location',
175
+ 'xpertLiveArtifact',
176
+ '__proto__',
177
+ 'constructor',
178
+ 'prototype'
179
+ ].includes(value)),
180
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
181
+ }).strict();
182
+ // Explicit outputs keep required fields in declarations emitted by non-strict host tsconfigs.
183
+ const artifactDocumentDependencyLock = dependencyLockObject.transform((value)=>({
184
+ id: value.id,
185
+ version: value.version,
186
+ format: 'classic-script',
187
+ global: value.global,
188
+ sha256: value.sha256
189
+ }));
190
+ const artifactDocumentDependencyLocks = z.array(artifactDocumentDependencyLock).max(8).superRefine((values, ctx)=>{
191
+ if (new Set(values.map((value)=>value.id)).size !== values.length || new Set(values.map((value)=>value.global)).size !== values.length) ctx.addIssue({
192
+ code: 'custom',
193
+ message: 'Duplicate dependency ID or global'
194
+ });
195
+ });
196
+ const artifactDocumentDependencyAssets = z.array(dependencyLockObject.extend({
197
+ source: z.string().min(1).max(4000000)
198
+ }).strict().transform((value)=>({
199
+ id: value.id,
200
+ version: value.version,
201
+ format: 'classic-script',
202
+ global: value.global,
203
+ sha256: value.sha256,
204
+ source: value.source
205
+ }))).max(8);
206
+ /** Browser/server identical verification. Integrity is not authorization: the caller owns library admission. */ function verifyArtifactDocumentDependencies(input, expected) {
207
+ const assets = artifactDocumentDependencyAssets.parse(input);
208
+ const locks = artifactDocumentDependencyLocks.parse(assets.map((_param)=>{
209
+ var { source } = _param, lock = _object_without_properties_loose(_param, [
210
+ "source"
211
+ ]);
212
+ return lock;
213
+ }));
214
+ let total = 0;
215
+ for (const asset of assets){
216
+ const bytes = new TextEncoder().encode(asset.source);
217
+ total += bytes.length;
218
+ if (bytes.length > 4000000 || total > 8000000) throw new Error('DOCUMENT_DEPENDENCY_TOO_LARGE');
219
+ if (sha256Hex(bytes) !== asset.sha256) throw new Error('DOCUMENT_DEPENDENCY_INTEGRITY_FAILED');
220
+ }
221
+ if (expected && JSON.stringify(artifactDocumentDependencyLocks.parse(expected)) !== JSON.stringify(locks)) throw new Error('DOCUMENT_DEPENDENCY_LOCK_MISMATCH');
222
+ return assets.map((asset)=>({
223
+ id: asset.id,
224
+ version: asset.version,
225
+ global: asset.global,
226
+ sha256: asset.sha256,
227
+ source: asset.source,
228
+ format: 'classic-script'
229
+ }));
230
+ }
231
+ /** Assign script.textContent to preserve exact bytes without eval or HTML parser termination hazards. */ function renderArtifactDocumentDependencies(assets) {
232
+ const literal = (value)=>JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e');
233
+ return verifyArtifactDocumentDependencies(assets).map((asset)=>`<script>(()=>{const s=document.createElement('script');s.textContent=${literal(asset.source)};document.head.appendChild(s);s.remove();if(typeof window[${literal(asset.global)}]==='undefined')throw new Error('DOCUMENT_DEPENDENCY_GLOBAL_MISSING');})();</script>`).join('');
234
+ }
235
+
236
+ const ARTIFACT_DOCUMENT_CSP = [
237
+ "default-src 'none'",
238
+ "script-src 'unsafe-inline'",
239
+ "style-src 'unsafe-inline'",
240
+ 'img-src data: blob:',
241
+ 'font-src data:',
242
+ "connect-src 'none'",
243
+ "frame-src 'none'",
244
+ "worker-src 'none'",
245
+ "object-src 'none'",
246
+ "base-uri 'none'",
247
+ "form-action 'none'"
248
+ ].join('; ');
249
+ /** Host-owned prefix precedes all authored markup, including malformed/duplicate heads. */ function renderArtifactDocument(html, sessionId, dependencies = []) {
250
+ artifactDocumentHtml.parse(html);
251
+ if (!/^[a-f0-9]{32}$/.test(sessionId)) throw new Error('Invalid Artifact document session ID');
252
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${ARTIFACT_DOCUMENT_CSP}"><script>${ARTIFACT_DOCUMENT_RUNTIME.replace('__XPERT_DOCUMENT_SESSION__', sessionId)}</script>${renderArtifactDocumentDependencies(dependencies)}${html}`;
253
+ }
254
+ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
255
+ ;(() => {
256
+ 'use strict'
257
+ const SESSION_ID = '__XPERT_DOCUMENT_SESSION__'
258
+ const CHANNEL = 'xpert.artifact-document',
259
+ VERSION = 1,
260
+ pending = new Map(),
261
+ listeners = new Map(),
262
+ lastControls = new Map(),
263
+ latest = new Map()
264
+ let port,
265
+ context,
266
+ sequence = 0,
267
+ resolveReady
268
+ const ready = new Promise((resolve) => (resolveReady = resolve))
269
+ const emit = (id, dataset) => {
270
+ for (const fn of listeners.get(id) || [])
271
+ try {
272
+ fn(dataset)
273
+ } catch (e) {
274
+ console.error(e)
275
+ }
276
+ }
277
+ const fail = (code) => Object.assign(new Error(code), { code })
278
+ const query = async (bindingId, controls = {}) => {
279
+ await ready
280
+ if (!context.bindingIds.includes(bindingId)) {
281
+ port.postMessage({ type: 'diagnostic', code: 'DOCUMENT_BINDING_DENIED' })
282
+ throw fail('DOCUMENT_BINDING_DENIED')
283
+ }
284
+ const requestId = 'q' + ++sequence,
285
+ values = { ...context.defaults, ...controls }
286
+ lastControls.set(bindingId, values)
287
+ latest.set(bindingId, requestId)
288
+ return new Promise((resolve, reject) => {
289
+ const timer = setTimeout(() => {
290
+ pending.delete(requestId)
291
+ reject(fail('DOCUMENT_QUERY_TIMEOUT'))
292
+ }, 45000)
293
+ pending.set(requestId, { resolve, reject, timer, bindingId })
294
+ port.postMessage({ type: 'query', requestId, bindingId, controls: values })
295
+ })
296
+ }
297
+ const subscribe = (id, fn) => {
298
+ if (typeof fn !== 'function') throw fail('DOCUMENT_INVALID_LISTENER')
299
+ const set = listeners.get(id) || new Set()
300
+ set.add(fn)
301
+ listeners.set(id, set)
302
+ return () => set.delete(fn)
303
+ }
304
+ const refresh = async (id) => query(id, lastControls.get(id) || {})
305
+ const bindSelect = (element, config) => {
306
+ if (
307
+ !element ||
308
+ element.tagName !== 'SELECT' ||
309
+ !config ||
310
+ typeof config.bindingId !== 'string' ||
311
+ typeof config.controlId !== 'string' ||
312
+ typeof config.fieldId !== 'string'
313
+ )
314
+ throw fail('DOCUMENT_INVALID_SELECT')
315
+ const allValue = config.allValue === undefined ? null : config.allValue,
316
+ known = new Set(),
317
+ append = (value, label) => {
318
+ const key = JSON.stringify(value)
319
+ if (known.has(key)) return
320
+ known.add(key)
321
+ const option = document.createElement('option')
322
+ option.value = key
323
+ option.textContent = label
324
+ element.append(option)
325
+ }
326
+ element.replaceChildren()
327
+ append(allValue, config.allLabel || 'All')
328
+ const update = (dataset) => {
329
+ const selected = (lastControls.get(config.bindingId) || context.defaults)[config.controlId]
330
+ for (const row of dataset.rows || []) {
331
+ const value = row[config.fieldId]
332
+ if (value !== null && ['string', 'number', 'boolean'].includes(typeof value)) append(value, String(value))
333
+ }
334
+ const key = JSON.stringify(selected === undefined ? allValue : selected)
335
+ if (known.has(key)) element.value = key
336
+ }
337
+ const unsubscribe = subscribe(config.bindingId, update),
338
+ change = () =>
339
+ ready
340
+ .then(() =>
341
+ query(config.bindingId, {
342
+ ...(lastControls.get(config.bindingId) || context.defaults),
343
+ [config.controlId]: JSON.parse(element.value)
344
+ })
345
+ )
346
+ .catch((error) =>
347
+ element.dispatchEvent(new CustomEvent('xpert-query-error', { detail: { code: error.code }, bubbles: true }))
348
+ )
349
+ element.addEventListener('change', change)
350
+ return () => {
351
+ unsubscribe()
352
+ element.removeEventListener('change', change)
353
+ }
354
+ }
355
+ Object.defineProperty(window, 'xpertLiveArtifact', {
356
+ value: Object.freeze({ ready: () => ready, query, subscribe, refresh, bindSelect }),
357
+ writable: false,
358
+ configurable: false
359
+ })
360
+ window.addEventListener('message', (event) => {
361
+ const data = event.data
362
+ if (
363
+ port ||
364
+ event.source !== parent ||
365
+ !data ||
366
+ data.channel !== CHANNEL ||
367
+ data.version !== VERSION ||
368
+ data.type !== 'init' ||
369
+ data.sessionId !== SESSION_ID ||
370
+ !event.ports[0]
371
+ )
372
+ return
373
+ port = event.ports[0]
374
+ context = data.context
375
+ document.documentElement.dataset.theme = context.theme
376
+ document.documentElement.style.colorScheme = context.theme
377
+ port.onmessage = (event) => {
378
+ const data = event.data
379
+ if (data.type === 'refresh') {
380
+ for (const id of new Set([...listeners.keys(), ...lastControls.keys()])) refresh(id).catch(console.error)
381
+ return
382
+ }
383
+ if (data.type !== 'result') return
384
+ const entry = pending.get(data.requestId)
385
+ if (!entry) return
386
+ pending.delete(data.requestId)
387
+ clearTimeout(entry.timer)
388
+ if (latest.get(entry.bindingId) !== data.requestId) {
389
+ entry.reject(fail('DOCUMENT_QUERY_SUPERSEDED'))
390
+ return
391
+ }
392
+ if (data.ok) {
393
+ emit(entry.bindingId, data.dataset)
394
+ entry.resolve(data.dataset)
395
+ } else entry.reject(fail(data.code || 'DOCUMENT_QUERY_FAILED'))
396
+ }
397
+ port.start()
398
+ resolveReady(context)
399
+ })
400
+ parent.postMessage({ channel: CHANNEL, version: VERSION, type: 'ready', sessionId: SESSION_ID }, '*')
401
+ })()
402
+ `;
403
+
404
+ // Invariants: a frame WindowProxy survives navigation, so source checks alone
405
+ // cannot identify a document generation. Each mount owns one handshake nonce,
406
+ // one MessagePort and a snapshot of the declared binding IDs.
407
+ const readySchema = z.object({
408
+ channel: z.literal(ARTIFACT_DOCUMENT_CHANNEL),
409
+ version: z.literal(ARTIFACT_DOCUMENT_VERSION),
410
+ type: z.literal('ready'),
411
+ sessionId: z.string().regex(/^[a-f0-9]{32}$/)
412
+ }).strict();
413
+ const diagnosticSchema = z.object({
414
+ type: z.literal('diagnostic'),
415
+ code: z.literal('DOCUMENT_BINDING_DENIED')
416
+ }).strict();
417
+ /** Dedicated query bridge. Requires a dedicated host document with installArtifactDocumentFramePolicy installed. */ function mountArtifactDocument(frame, options) {
418
+ if (!frame.ownerDocument.querySelector('meta[data-xpert-document-policy]')) {
419
+ throw new Error('Install the Artifact document frame policy before mounting a document');
420
+ }
421
+ const context = artifactDocumentContext.parse(options.context);
422
+ const sessionId = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte)=>byte.toString(16).padStart(2, '0')).join('');
423
+ // Validate/render before allocating a channel or installing listeners.
424
+ const source = renderArtifactDocument(options.html, sessionId, options.dependencies);
425
+ const channel = new MessageChannel();
426
+ const bindingIds = new Set(context.bindingIds);
427
+ const requestIds = new Set();
428
+ const activeIds = new Set();
429
+ const latest = new Map();
430
+ const hostWindow = frame.ownerDocument.defaultView;
431
+ let connected = false, disposed = false, requests = 0, started = Date.now();
432
+ frame.setAttribute('sandbox', 'allow-scripts');
433
+ frame.referrerPolicy = 'no-referrer';
434
+ // Host UI observers cannot leave query accounting stuck or alter protocol completion.
435
+ const observe = (callback, value)=>{
436
+ try {
437
+ callback == null ? void 0 : callback(value);
438
+ } catch (e) {
439
+ /* The query channel must survive a failing UI observer. */ }
440
+ };
441
+ const post = (message)=>{
442
+ if (!disposed) channel.port1.postMessage(message);
443
+ };
444
+ const reject = (requestId, code)=>{
445
+ post({
446
+ type: 'result',
447
+ requestId,
448
+ ok: false,
449
+ code
450
+ });
451
+ observe(options.onError, code);
452
+ };
453
+ channel.port1.onmessage = async (event)=>{
454
+ if (disposed) return;
455
+ const diagnostic = diagnosticSchema.safeParse(event.data);
456
+ if (diagnostic.success) {
457
+ observe(options.onError, diagnostic.data.code);
458
+ return;
459
+ }
460
+ const parsed = artifactDocumentQuery.safeParse(event.data);
461
+ if (!parsed.success) {
462
+ observe(options.onError, 'DOCUMENT_INVALID_REQUEST');
463
+ return;
464
+ }
465
+ const input = {
466
+ type: parsed.data.type,
467
+ requestId: parsed.data.requestId,
468
+ bindingId: parsed.data.bindingId,
469
+ controls: parsed.data.controls
470
+ };
471
+ if (!bindingIds.has(input.bindingId)) {
472
+ reject(input.requestId, 'DOCUMENT_BINDING_DENIED');
473
+ return;
474
+ }
475
+ if (Date.now() - started >= 60000) {
476
+ requests = 0;
477
+ started = Date.now();
478
+ requestIds.clear();
479
+ }
480
+ // Keep in-flight IDs protected even after the one-minute replay/rate window rolls over.
481
+ if (activeIds.has(input.requestId) || requestIds.has(input.requestId)) {
482
+ reject(input.requestId, 'DOCUMENT_REQUEST_REPLAY');
483
+ return;
484
+ }
485
+ if (activeIds.size >= 8 || ++requests > 60) {
486
+ reject(input.requestId, 'DOCUMENT_QUERY_LIMIT');
487
+ return;
488
+ }
489
+ requestIds.add(input.requestId);
490
+ activeIds.add(input.requestId);
491
+ latest.set(input.bindingId, input.requestId);
492
+ observe(options.onBusy, true);
493
+ try {
494
+ const dataset = await options.query(input);
495
+ if (!disposed) {
496
+ post({
497
+ type: 'result',
498
+ requestId: input.requestId,
499
+ ok: true,
500
+ dataset
501
+ });
502
+ if (latest.get(input.bindingId) === input.requestId) observe(options.onResult, dataset);
503
+ }
504
+ } catch (e) {
505
+ if (!disposed) {
506
+ post({
507
+ type: 'result',
508
+ requestId: input.requestId,
509
+ ok: false,
510
+ code: 'DOCUMENT_QUERY_FAILED'
511
+ });
512
+ if (latest.get(input.bindingId) === input.requestId) observe(options.onError, 'DOCUMENT_QUERY_FAILED');
513
+ }
514
+ } finally{
515
+ activeIds.delete(input.requestId);
516
+ if (!disposed) observe(options.onBusy, activeIds.size > 0);
517
+ }
518
+ };
519
+ const ready = (event)=>{
520
+ var _frame_contentWindow;
521
+ if (disposed || connected || event.source !== frame.contentWindow) return;
522
+ const parsed = readySchema.safeParse(event.data);
523
+ if (!parsed.success || parsed.data.sessionId !== sessionId) return;
524
+ connected = true;
525
+ (_frame_contentWindow = frame.contentWindow) == null ? void 0 : _frame_contentWindow.postMessage({
526
+ channel: ARTIFACT_DOCUMENT_CHANNEL,
527
+ version: ARTIFACT_DOCUMENT_VERSION,
528
+ type: 'init',
529
+ sessionId,
530
+ context
531
+ }, '*', [
532
+ channel.port2
533
+ ]);
534
+ };
535
+ hostWindow.addEventListener('message', ready);
536
+ channel.port1.start();
537
+ frame.srcdoc = source;
538
+ return {
539
+ refresh () {
540
+ post({
541
+ type: 'refresh'
542
+ });
543
+ },
544
+ dispose () {
545
+ if (disposed) return;
546
+ disposed = true;
547
+ hostWindow.removeEventListener('message', ready);
548
+ channel.port1.close();
549
+ channel.port2.close();
550
+ observe(options.onBusy, false);
551
+ }
552
+ };
553
+ }
554
+ /** Installs a document-wide policy once. Use a dedicated host: all URL-based child frames are denied; srcdoc works. */ function installArtifactDocumentFramePolicy(hostDocument) {
555
+ if (hostDocument.querySelector('meta[data-xpert-document-policy]')) return;
556
+ const meta = hostDocument.createElement('meta');
557
+ meta.httpEquiv = 'Content-Security-Policy';
558
+ meta.content = "frame-src 'none'";
559
+ meta.dataset['xpertDocumentPolicy'] = '1';
560
+ hostDocument.head.prepend(meta);
561
+ }
562
+
563
+ export { ARTIFACT_DOCUMENT_CHANNEL, ARTIFACT_DOCUMENT_CSP, ARTIFACT_DOCUMENT_VERSION, artifactDocumentContext, artifactDocumentControls, artifactDocumentDependencyAssets, artifactDocumentDependencyLock, artifactDocumentDependencyLocks, artifactDocumentHtml, artifactDocumentId, artifactDocumentQuery, artifactDocumentValue, installArtifactDocumentFramePolicy, mountArtifactDocument, renderArtifactDocument, renderArtifactDocumentDependencies, verifyArtifactDocumentDependencies };
@@ -194,11 +194,17 @@ const FORBIDDEN = new Set([
194
194
  'ATTACH',
195
195
  'DETACH'
196
196
  ]);
197
- const SAFE_FUNCTIONS = new Set('ABS ACOS ASIN ATAN ATAN2 AVG CAST CEIL CEILING COALESCE CONCAT CONCAT_WS CONVERT COS COUNT CURDATE CURRENT_DATE CURRENT_TIMESTAMP DATE DATE_ADD DATE_SUB DATE_FORMAT DATEDIFF DAY DAYOFMONTH DAYOFWEEK EXTRACT FLOOR FORMAT GREATEST GROUP_CONCAT IF IFNULL JSON_EXTRACT JSON_LENGTH JSON_UNQUOTE LEAST LEFT LENGTH LN LOG LOWER LPAD LTRIM MAX MD5 MIN MOD MONTH NOW NULLIF POWER RAND REPLACE REVERSE RIGHT ROUND ROW_NUMBER RANK DENSE_RANK LAG LEAD FIRST_VALUE LAST_VALUE LPAD RPAD RTRIM SIGN SIN SQRT STDDEV STDDEV_POP STDDEV_SAMP SUBSTR SUBSTRING SUM TAN TO_CHAR TO_DATE TO_TIMESTAMP TRIM TRUNC UPPER VAR_POP VAR_SAMP VERSION WEEK YEAR DATABASE CURRENT_DATABASE CURRENT_SCHEMA ARRAY_AGG STRING_AGG JSON_AGG JSON_BUILD_OBJECT PG_GET_VIEWDEF'.split(' '));
197
+ // Legacy SQL Workbench policy shared by supported database plugins.
198
+ // TODO: separate dialect function policies through plugin-owned strategies; preserve fail-closed checks.
199
+ // Allowlisting permits parsing; the selected database still determines function availability.
200
+ const SAFE_FUNCTIONS = new Set('ABS ACOS ASIN ATAN ATAN2 AVG CAST CEIL CEILING COALESCE CONCAT CONCAT_WS CONVERT COS COUNT CURDATE CURRENT_DATE CURRENT_TIMESTAMP DATE DATE_TRUNC DATE_ADD DATE_SUB DATE_FORMAT DATEDIFF DAY DAYOFMONTH DAYOFWEEK EXTRACT FLOOR FORMAT GREATEST GROUP_CONCAT IF IFNULL JSON_EXTRACT JSON_LENGTH JSON_UNQUOTE LEAST LEFT LENGTH LN LOG LOWER LPAD LTRIM MAX MD5 MIN MOD MONTH NOW NULLIF POWER RAND REPLACE REVERSE RIGHT ROUND ROW_NUMBER RANK DENSE_RANK LAG LEAD FIRST_VALUE LAST_VALUE LPAD RPAD RTRIM SIGN SIN SQRT STDDEV STDDEV_POP STDDEV_SAMP SUBSTR SUBSTRING SUM TAN TO_CHAR TO_DATE TO_TIMESTAMP TRIM TRUNC UPPER VAR_POP VAR_SAMP VERSION WEEK YEAR DATABASE CURRENT_DATABASE CURRENT_SCHEMA ARRAY_AGG STRING_AGG JSON_AGG JSON_BUILD_OBJECT PG_GET_VIEWDEF'.split(' '));
198
201
  // FROM/JOIN can introduce a parenthesized subquery, not a function call.
199
202
  const SQL_PARENS = new Set('IN AS EXISTS OVER PARTITION VALUES SELECT WITH FROM JOIN AND OR NOT ON USING FILTER GROUPING ROLLUP CUBE DISTINCT EXPLAIN'.split(' '));
200
203
  const UNSAFE_FUNCTIONS = /\b(pg_sleep|sleep|benchmark|dblink\w*|lo_\w+|pg_(?:read|write|ls|stat|terminate|cancel|reload|rotate|log|create|drop|promote|switch|backup|replication|advisory)\w*|get_lock|release_lock|load_file|nextval|setval|set_config|http\w*|s3|hdfs|jdbc|mysql|postgresql|file|url)\s*\(/i;
201
- function splitWorkbenchSql(source) {
204
+ /**
205
+ * @deprecated Mixed-dialect Workbench policy. New adapters should own dialect-aware statement
206
+ * validation. Existing callers must retain this guard until an equivalent replacement is in place.
207
+ */ function splitWorkbenchSql(source) {
202
208
  const { masked, tokens } = lexWorkbenchSql(source);
203
209
  const statements = [];
204
210
  let start = 0;
@@ -238,12 +244,18 @@ function splitWorkbenchSql(source) {
238
244
  if (!statements.length || statements.length > 50) throw new Error('statement_count_exceeded');
239
245
  return statements;
240
246
  }
241
- function requireReadStatement(sql) {
247
+ /**
248
+ * @deprecated Uses the legacy mixed-dialect policy. New adapters should enforce read-only execution
249
+ * with dialect-aware validation and database permissions. Keep this guard until safely migrated.
250
+ */ function requireReadStatement(sql) {
242
251
  const statements = splitWorkbenchSql(sql);
243
252
  if (statements.length !== 1 || statements[0].effect !== 'read') throw new Error('read_only_violation');
244
253
  return statements[0].sql;
245
254
  }
246
- function quoteDatabaseIdentifier(name, engine) {
255
+ /**
256
+ * @deprecated Built-in engine switch. New adapters should own dialect-specific identifier quoting
257
+ * while preserving identifier validation and escaping.
258
+ */ function quoteDatabaseIdentifier(name, engine) {
247
259
  // eslint-disable-next-line no-control-regex -- intentional: reject control characters in identifiers
248
260
  if (!name || name.length > 256 || /[\0-\x1f]/.test(name)) throw new Error('invalid_identifier');
249
261
  const quote = engine === 'postgres' ? '"' : '`';
@@ -300,7 +312,11 @@ function quoteDatabaseIdentifier(name, engine) {
300
312
  const number = (value)=>Number(value != null ? value : 0);
301
313
  const string = (value)=>value == null ? '' : String(value);
302
314
  const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.name.toLowerCase() === name.toLowerCase())];
303
- /** One adapter per physical connection. A host session must not share it across users. */ class SqlDatabaseWorkbenchAdapter {
315
+ /**
316
+ * One adapter per physical connection. A host session must not share it across users.
317
+ * @deprecated Legacy SDK-owned SQL dialects. New plugins should implement DatabaseWorkbenchAdapter
318
+ * with plugin-owned dialect behavior. Retained for compatibility with existing plugins.
319
+ */ class SqlDatabaseWorkbenchAdapter {
304
320
  quote(name) {
305
321
  return quoteDatabaseIdentifier(name, this.engine);
306
322
  }
@@ -401,7 +417,7 @@ const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.
401
417
  var _object_schema, _ref, _object_database, _ref1;
402
418
  const namespace = this.engine === 'postgres' ? (_ref = (_object_schema = object.schema) != null ? _object_schema : this.initial.schema) != null ? _ref : 'public' : (_ref1 = (_object_database = object.database) != null ? _object_database : this.initial.database) != null ? _ref1 : '';
403
419
  const p = (i)=>this.engine === 'postgres' ? `$${i}` : '?';
404
- const metadata = await this.raw(this.engine === 'postgres' ? `SELECT a.attname AS column_name, pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable, a.attnum AS ordinal_position, pg_get_expr(d.adbin,d.adrelid) AS column_default FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE n.nspname=$1 AND c.relname=$2 AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum LIMIT 1000` : `SELECT column_name, column_type AS data_type, is_nullable, ordinal_position, column_default FROM information_schema.columns WHERE table_schema = ${p(1)} AND table_name = ${p(2)} ORDER BY ordinal_position LIMIT 1000`, [
420
+ const metadata = await this.raw(this.engine === 'postgres' ? `SELECT a.attname AS column_name, pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable, a.attnum AS ordinal_position, pg_get_expr(d.adbin,d.adrelid) AS column_default, pg_catalog.col_description(c.oid,a.attnum) AS column_comment FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE n.nspname=$1 AND c.relname=$2 AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum LIMIT 1000` : `SELECT column_name, column_type AS data_type, is_nullable, ordinal_position, column_default, column_comment FROM information_schema.columns WHERE table_schema = ${p(1)} AND table_name = ${p(2)} ORDER BY ordinal_position LIMIT 1000`, [
405
421
  namespace,
406
422
  object.name
407
423
  ]);
@@ -411,6 +427,7 @@ const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.
411
427
  dataType: string(cell(metadata, row, 'data_type')),
412
428
  nullable: string(cell(metadata, row, 'is_nullable')) === 'YES',
413
429
  ordinal: number(cell(metadata, row, 'ordinal_position')),
430
+ comment: string(cell(metadata, row, 'column_comment')) || undefined,
414
431
  defaultValue: cell(metadata, row, 'column_default') == null ? null : string(cell(metadata, row, 'column_default'))
415
432
  }));
416
433
  if (!columns.length) throw new Error('object_not_found_or_denied');