@uibot/runtime 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.
@@ -0,0 +1,26 @@
1
+ import React from "react";
2
+ import type { CompiledUIBotSpec, GapReport } from "@uibot/contracts";
3
+ import { type UIBotLiveRendererProps, type ReactRegistry } from "@uibot/renderer-react";
4
+ import type { UIBotAppRuntimeAdapter, UIBotPageResolution } from "./live-runtime-adapter.js";
5
+ export interface UIBotAppHostProps {
6
+ spec: CompiledUIBotSpec;
7
+ registry: ReactRegistry;
8
+ adapter: UIBotAppRuntimeAdapter;
9
+ pageId?: string;
10
+ pagePath?: string;
11
+ /** Compile gaps. A non-empty list refuses to mount the live page. */
12
+ gaps?: readonly GapReport[];
13
+ loading?: React.ReactNode;
14
+ fallback?: (resolution: Exclude<UIBotPageResolution, {
15
+ status: "ready";
16
+ }>) => React.ReactNode;
17
+ onResolution?: (resolution: UIBotPageResolution) => void;
18
+ onMountError?: UIBotLiveRendererProps["onMountError"];
19
+ }
20
+ /**
21
+ * Client-safe router/auth gate for live specs.
22
+ *
23
+ * The page is resolved and authorized before `UIBotLiveRenderer` is mounted,
24
+ * so a denied page cannot run lifecycle actions or issue connection requests.
25
+ */
26
+ export declare function UIBotAppHost(props: UIBotAppHostProps): React.ReactElement | null;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Browser-neutral creation-data dispatch. Original UIBot code under the repository MIT license.
3
+ * The host owns policy and rows. This module does not store, fetch, query, or authorize.
4
+ */
5
+ import { CREATION_DATA_WEB_PROTOCOL, CREATION_DATA_WEB_V2_PROTOCOL } from "@uibot/contracts";
6
+ import type { CreationDataHost, CreationDataResult, CreationDataWebHost, CreationDataWebV2Host } from "@uibot/contracts";
7
+ export { CREATION_DATA_WEB_PROTOCOL, CREATION_DATA_WEB_V2_PROTOCOL, CREATION_DATA_WRITE_PROTOCOL, CreationDataPortRejection, } from "@uibot/contracts";
8
+ export type { CreationDataAuthorizeEntity, CreationDataCreateMetadata, CreationDataErrorCode, CreationDataFailure, CreationDataHost, CreationDataGenericHost, CreationDataJson, CreationDataMutationMetadata, CreationDataOperation, CreationDataPort, CreationDataRecord, CreationDataRequest, CreationDataResult, CreationDataSuccess, CreationDataWriteProtocol, CreationDataWebClient, CreationDataWebHost, CreationDataWebPort, CreationDataWebRequest, CreationDataWebRow, CreationDataWebV2Client, CreationDataWebV2Host, CreationDataWebV2Port, CreationDataWebV2Request, } from "@uibot/contracts";
9
+ /**
10
+ * Validate one message, ask the host whether the entity is allowed now, then
11
+ * call the injected port. No allowlist is stored between calls.
12
+ */
13
+ export declare function dispatchCreationData(message: unknown, host: CreationDataHost | CreationDataWebHost | CreationDataWebV2Host): Promise<CreationDataResult>;
14
+ /**
15
+ * Pure source builder for an explicitly installed, document-bound iframe client.
16
+ * The host injects the script, binds the response port and preview identity,
17
+ * and authorizes each request. Writes never retry or mint an operationId here.
18
+ */
19
+ export interface CreationDataWebShimOptions {
20
+ previewToken: string;
21
+ requestSource: string;
22
+ responseSource: string;
23
+ compatibilityGlobalName?: string;
24
+ /** Defaults to v1; v2 adds only the explicitly requested remove method. */
25
+ protocol?: typeof CREATION_DATA_WEB_PROTOCOL | typeof CREATION_DATA_WEB_V2_PROTOCOL;
26
+ }
27
+ export declare function createCreationDataWebShimSource(options: CreationDataWebShimOptions): string;
@@ -0,0 +1,11 @@
1
+ import type React from "react";
2
+ import type { CompileWarning, GapReport } from "@uibot/contracts";
3
+ export interface UIBotDiagnosticsProps {
4
+ gaps?: readonly GapReport[];
5
+ warnings?: readonly CompileWarning[];
6
+ droppedEventFields?: readonly string[];
7
+ /** Defaults to on outside production. */
8
+ enabled?: boolean;
9
+ }
10
+ /** Development overlay listing compile diagnostics and dropped event fields. */
11
+ export declare function UIBotDiagnostics(props: UIBotDiagnosticsProps): React.ReactElement | null;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@uibot/runtime` — client-safe spec live-runtime assembly.
3
+ *
4
+ * Sits above `@uibot/engine` + `@uibot/renderer-react` and below
5
+ * `@uibot/application`. It owns the single seam that wires a compiled spec's
6
+ * engine + lifecycle into the {@link UIBotRuntimeAdapter} the live renderer
7
+ * consumes — without pulling in any server-only / AI-framework dependencies, so
8
+ * Studio (pure client), `@uibot/application` (server), and examples can all
9
+ * import the same implementation instead of mirroring it.
10
+ */
11
+ export { createLiveRuntimeAdapter, UIBotPageAccessError, type CreateLiveAdapterOptions, type UIBotAppRuntimeAdapter, type UIBotAuthorizationContext, type UIBotNavigationRequest, type UIBotPageResolution, type UIBotPageTarget, } from "./live-runtime-adapter.js";
12
+ export { UIBotAppHost, type UIBotAppHostProps } from "./app-host.js";
13
+ export { bindUrlState, type UrlStateIO } from "./url-state.js";
14
+ export { CREATION_DATA_WEB_PROTOCOL, CREATION_DATA_WEB_V2_PROTOCOL, CREATION_DATA_WRITE_PROTOCOL, CreationDataPortRejection, createCreationDataWebShimSource, dispatchCreationData, } from "./creation-data.js";
15
+ export type { CreationDataAuthorizeEntity, CreationDataCreateMetadata, CreationDataErrorCode, CreationDataFailure, CreationDataHost, CreationDataGenericHost, CreationDataJson, CreationDataMutationMetadata, CreationDataOperation, CreationDataPort, CreationDataRecord, CreationDataRequest, CreationDataResult, CreationDataSuccess, CreationDataWriteProtocol, CreationDataWebClient, CreationDataWebHost, CreationDataWebPort, CreationDataWebRequest, CreationDataWebRow, CreationDataWebV2Client, CreationDataWebV2Host, CreationDataWebV2Port, CreationDataWebV2Request, CreationDataWebShimOptions, } from "./creation-data.js";
16
+ export { UIBotDiagnostics } from "./diagnostics.js";
17
+ export { UIBotLiveRenderer, UIBotRenderer } from "@uibot/renderer-react";
18
+ export type { UIBotRuntimeAdapter, UIBotLiveRendererProps, UIBotRendererProps, } from "@uibot/renderer-react";
19
+ export { assembleInstalledUIBotLibrary, InstalledUIBotLibraryError, type InstalledUIBotLibrary, type InstalledUIBotLibraryInput, type InstalledUIBotTemplate, } from "./installed-library.js";
package/dist/index.js ADDED
@@ -0,0 +1,162 @@
1
+ import{createEngine as q,createLifecycleController as H}from"@uibot/engine";function L(e,t){if(t.enum&&!t.enum.includes(e))return t.default??"";if(typeof t.default==="number"){let n=Number(e);return Number.isFinite(n)?n:t.default}if(typeof t.default==="boolean"){if(e==="true")return!0;if(e==="false")return!1;return t.default}return e}function M(e,t){let n=e;if(t.enum&&(typeof n!=="string"||!t.enum.includes(n)))n=t.default;if(n===void 0||n===null||n==="")return null;if(t.default!==void 0&&Object.is(n,t.default))return null;if(typeof n==="string"||typeof n==="number"||typeof n==="boolean")return String(n);return null}function x(e,t,n){let i=new URLSearchParams(n.read()),l=!1;for(let[a,c]of Object.entries(t)){let u=M(e.get(a),c),r=i.get(c.param);if(u===null){if(r!==null)i.delete(c.param),l=!0}else if(r!==u)i.set(c.param,u),l=!0}if(l)n.write(i,{replace:!0})}function D(e,t,n){let i=n.read(),l={};for(let[c,u]of Object.entries(t)){let r=i.get(u.param);if(r===null)continue;l[c]=L(r,u)}if(Object.keys(l).length>0)e.setMany(l);let a=e.onWrite((c)=>{let u=new Set(Object.keys(t));if(!c.some((r)=>u.has(r.split(".")[0]??r)))return;x(e,t,n)});return x(e,t,n),a}var U=new WeakSet;function z(e,t){if(U.has(e))return;U.add(e),e.onWrite(()=>{for(let n of t)n()})}function G(e){let{spec:t}=e,n=t.pages[0],i=e.engine??q(n?.state??{});for(let r of t.connections??[])i.connections.registerConnection(r);for(let r of e.drivers??[])i.connections.registerDriver(r.type,r);if(e.resolveSecret)i.connections.setSecretResolver(e.resolveSecret);let l=new Set;z(i.store,l);let a=[];if(e.urlState){let r={};for(let s of t.pages)Object.assign(r,s.urlState);if(Object.keys(r).length>0)a.push(D(i.store,r,e.urlState))}let c=i.bus.on("navigate",(r)=>{if(!e.navigate||!r||typeof r!=="object")return;let s=r;if(typeof s.destination!=="string")return;let o={destination:s.destination,target:s.target==="_blank"?"_blank":"_self"};try{Promise.resolve(e.navigate(o)).catch(()=>{e.onNavigationError?.(o)})}catch{e.onNavigationError?.(o)}}),u=async(r={})=>{let s=r.pagePath?E(r.pagePath):void 0,o=t.pages.find((p)=>{if(r.pageId&&p.id!==r.pageId)return!1;if(s&&E(p.path)!==s)return!1;return Boolean(r.pageId||s)})??(!r.pageId&&!s?n:void 0);if(!o)return{status:"not-found",...r.pageId?{pageId:r.pageId}:{},...s?{pagePath:s}:{}};let d;try{d=e.authorize?await e.authorize(o,{user:i.session.getUser()}):!o.auth?.role||i.session.hasRole(o.auth.role)}catch{return{status:"error",message:"Page access check failed"}}if(!d)return{status:"unauthorized",pageId:o.id,pagePath:o.path,...o.auth?.redirect?{redirect:o.auth.redirect}:{}};return{status:"ready",pageId:o.id,pagePath:o.path}};return{resolvePage:u,snapshot(){return i.store.view()},async dispatch(r,s){await i.runner.run(r,s)},subscribeAny(r){return l.add(r),()=>{l.delete(r)}},async mountPage(r){let s=await u({pageId:r});if(s.status!=="ready")throw new I(r,s);let o=t.pages.find((p)=>p.id===s.pageId);if(!o)throw new I(r,{status:"not-found",pageId:r});let d=H({store:i.store,session:i.session,...o?.computed?{computed:o.computed}:{},...o?.lifecycle?.onMount?{onMount:o.lifecycle.onMount}:{},...o?.lifecycle?.onUnmount?{onUnmount:o.lifecycle.onUnmount}:{},...o?.lifecycle?.onStateChange?{onStateChange:o.lifecycle.onStateChange}:{},runChain:(p)=>i.runner.run(p)});try{await d.mount()}catch(p){if(typeof console<"u")console.warn(`[live-runtime] page "${r}" onMount failed; rendering from snapshot`,p)}return()=>{d.dispose()}},dispose(){for(let r of a)r();c(),l.clear()}}}function E(e){let t=e.split("#",1)[0]??e;return(t.split("?",1)[0]??t)||"/"}class I extends Error{resolution;constructor(e,t){super(t.status==="unauthorized"?`Page "${e}" is not authorized`:`Page "${e}" is unavailable`);this.resolution=t;this.name="UIBotPageAccessError"}}import C from"react";import{UIBotLiveRenderer as J,UIBotMountError as F}from"@uibot/renderer-react";import{jsxDEV as R,Fragment as P}from"react/jsx-dev-runtime";function K(e){let{spec:t,registry:n,adapter:i,pageId:l,pagePath:a,gaps:c=[],loading:u=null,fallback:r,onResolution:s,onMountError:o}=e,d=c.length>0,p=C.useRef(o);p.current=o,C.useEffect(()=>{if(!d)return;let b=c[0];p.current?.(new F("compile",Error(b?.context??`${c.length} compile gaps`),b?.elementKey))},[d,c]);let y=`${l??""}\x00${a??""}`,[m,V]=C.useState(null),S=C.useRef(s);if(S.current=s,C.useEffect(()=>{let b=!0,j={...l?{pageId:l}:{},...a?{pagePath:a}:{}};return i.resolvePage(j).then((A)=>{if(!b)return;V({key:y,resolution:A}),S.current?.(A)}),()=>{b=!1}},[i,l,a,y]),d)return R(P,{children:r?.({status:"error",message:`${c.length} compile gaps`})??null},void 0,!1,void 0,this);if(!m||m.key!==y)return R(P,{children:u},void 0,!1,void 0,this);if(m.resolution.status!=="ready")return R(P,{children:r?.(m.resolution)??null},void 0,!1,void 0,this);return R(J,{spec:t,registry:n,adapter:i,pageId:m.resolution.pageId,...o?{onMountError:o}:{}},void 0,!1,void 0,this)}import{CREATION_DATA_WEB_PROTOCOL as O,CREATION_DATA_WEB_V2_PROTOCOL as W,CREATION_DATA_WEB_MAX_DEPTH as X,CREATION_DATA_WEB_MAX_TEXT_BYTES as Z,CREATION_DATA_WEB_MAX_VALUES as Y,CREATION_DATA_WRITE_PROTOCOL as k,CreationDataPortRejection as Q,readCreationDataJson as ee,readCreationDataWebJson as te,readCreationDataWebResult as re,validateCreationDataMessage as oe}from"@uibot/contracts";import{CREATION_DATA_WEB_PROTOCOL as fe,CREATION_DATA_WEB_V2_PROTOCOL as me,CREATION_DATA_WRITE_PROTOCOL as ge,CreationDataPortRejection as ye}from"@uibot/contracts";var ae="Entity is not allowed.",h="Data port failed.",w="Creation data host is incomplete.",B="Data port returned a non-JSON result.",ne="Web data request exceeds JSON limits.",ie="Data port rejected the operation.",T="The original data write outcome is unknown; reconcile it before another attempt.";function f(e,t){return{ok:!1,code:e,message:t}}function se(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.list==="function"&&typeof t.get==="function"&&typeof t.create==="function"&&typeof t.update==="function"&&typeof t.remove==="function"}function N(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.writeProtocol===k&&typeof t.list==="function"&&typeof t.get==="function"&&typeof t.create==="function"&&typeof t.update==="function"}function le(e){return N(e)&&typeof e.remove==="function"}function ue(e,t){switch(t.op){case"list":return t.filter===void 0?e.list(t.entity):e.list(t.entity,t.filter);case"get":return e.get(t.entity,t.id);case"create":return e.create(t.entity,t.record,{operationId:t.operationId});case"update":return e.update(t.entity,t.id,t.patch,{operationId:t.operationId,expectedVersion:t.expectedVersion});case"remove":if(!("remove"in e)||typeof e.remove!=="function")throw Error("Creation data remove port is missing");return e.remove(t.entity,t.id,{operationId:t.operationId,expectedVersion:t.expectedVersion})}}function _(e){return e.op==="create"||e.op==="update"||e.op==="remove"}function ce(e){let t=e.publicMessage;if(typeof t!=="string"||t.trim()==="")return ie;return t}async function de(e,t){try{let n=typeof t==="object"&&t!==null?t.webProtocol:void 0,i=n===O,l=n===W,a=i||l,c=a?te(e):null;if(c&&!c.ok)return f("invalid-request",ne);let u=oe(c?.ok?c.value:e);if(!u.ok)return u;if(typeof t!=="object"||t===null||typeof t.authorizeEntity!=="function"||!(l?le(t.dataPort):i?N(t.dataPort):se(t.dataPort)))return f("invalid-host",w);if(t.webProtocol!==void 0&&!a)return f("invalid-host",w);let r=l||i&&u.request.op!=="remove"?u.request:null;if(i&&!r)return f("unknown-op","The Web data bridge does not support removal.");let s;try{s=await t.authorizeEntity(u.request.entity)}catch{return f("host-failed",h)}if(s===!1)return f("entity-not-allowed",ae);if(s!==!0)return f("host-failed",h);if(_(u.request)&&t.dataPort.writeProtocol!==k)return f("invalid-host",w);try{let o=await ue(t.dataPort,u.request);if(r){let p=re(r.op,o);if(!p.ok)return _(u.request)?f("unknown",T):f("invalid-result",B);return{ok:!0,data:p.data}}let d=ee(o);if(!d.ok)return f("invalid-result",B);return{ok:!0,data:d.value}}catch(o){if(a&&_(u.request))return f("unknown",T);if(a)return f("host-failed",h);if(o instanceof Q)return f("host-rejected",ce(o));return f("host-failed",h)}}catch{return f("host-failed",h)}}function pe(e){let t=e.protocol??O,n=/^[A-Za-z0-9_-]{16,128}$/,i=/^[A-Za-z0-9_-]{1,128}$/,l=/^__[A-Za-z][A-Za-z0-9_]{0,62}$/;if(!n.test(e.previewToken)||!i.test(e.requestSource)||!i.test(e.responseSource)||![O,W].includes(t)||e.compatibilityGlobalName!==void 0&&(!l.test(e.compatibilityGlobalName)||["__uibotData","__uibotDataWebV1Shim","__proto__"].includes(e.compatibilityGlobalName)))throw Error("Invalid creation data Web bridge configuration");let a=JSON.stringify(e.requestSource),c=JSON.stringify(e.responseSource),u=JSON.stringify(e.previewToken),r=JSON.stringify(e.compatibilityGlobalName??null),s=JSON.stringify(t);return`(function(){
2
+ var seq = 0, requestSource = ${a}, responseSource = ${c};
3
+ var previewToken = ${u}, compatibilityGlobalName = ${r};
4
+ var webProtocol = ${s}, isV2 = webProtocol === 'uibot.creation-data.web.v2';
5
+ if (window.__uibotDataWebV1Shim || window.__uibotData !== undefined ||
6
+ (compatibilityGlobalName && window[compatibilityGlobalName] !== undefined))
7
+ throw new Error('creation_data_bridge_collision');
8
+ var maxDepth = ${X}, maxValues = ${Y};
9
+ var maxTextBytes = ${Z};
10
+ function plain(value){
11
+ if (value === null || typeof value !== 'object' || Array.isArray(value) || Object.prototype.toString.call(value) !== '[object Object]') return false;
12
+ var proto = Object.getPrototypeOf(value);
13
+ if (proto === null || proto === Object.prototype) return true;
14
+ if (Object.getPrototypeOf(proto) !== null) return false;
15
+ var constructor = Object.getOwnPropertyDescriptor(proto, 'constructor');
16
+ return !!constructor && typeof constructor.value === 'function' && constructor.value.name === 'Object';
17
+ }
18
+ function addText(value, budget){
19
+ for (var i = 0; i < value.length; i++) {
20
+ var unit = value.charCodeAt(i);
21
+ if (unit < 0x80) budget.bytes++;
22
+ else if (unit < 0x800) budget.bytes += 2;
23
+ else if (unit >= 0xd800 && unit <= 0xdbff) {
24
+ var next = value.charCodeAt(i + 1);
25
+ if (next >= 0xdc00 && next <= 0xdfff) { budget.bytes += 4; i++; }
26
+ else budget.bytes += 3;
27
+ } else budget.bytes += 3;
28
+ if (budget.bytes > maxTextBytes) return false;
29
+ }
30
+ return true;
31
+ }
32
+ function visit(value, depth, budget){
33
+ if (++budget.values > maxValues || depth > maxDepth) return false;
34
+ if (value === null || typeof value === 'boolean') return true;
35
+ if (typeof value === 'number') return Number.isFinite(value);
36
+ if (typeof value === 'string') return addText(value, budget);
37
+ if (typeof value !== 'object' || budget.active.has(value)) return false;
38
+ budget.active.add(value);
39
+ try {
40
+ if (Array.isArray(value)) {
41
+ if (value.length > maxValues - budget.values || Reflect.ownKeys(value).length !== value.length + 1) return false;
42
+ for (var i = 0; i < value.length; i++) {
43
+ var item = Object.getOwnPropertyDescriptor(value, i);
44
+ if (!item || !Object.prototype.hasOwnProperty.call(item, 'value') || !visit(item.value, depth + 1, budget)) return false;
45
+ }
46
+ return true;
47
+ }
48
+ if (!plain(value)) return false;
49
+ var keys = Reflect.ownKeys(value);
50
+ if (keys.length > maxValues - budget.values) return false;
51
+ for (var j = 0; j < keys.length; j++) {
52
+ if (typeof keys[j] !== 'string' || !addText(keys[j], budget)) return false;
53
+ var property = Object.getOwnPropertyDescriptor(value, keys[j]);
54
+ if (!property || !Object.prototype.hasOwnProperty.call(property, 'value') || !visit(property.value, depth + 1, budget)) return false;
55
+ }
56
+ return true;
57
+ } finally { budget.active.delete(value); }
58
+ }
59
+ function bounded(value){
60
+ try { return visit(value, 1, { values: 0, bytes: 0, active: new WeakSet() }); }
61
+ catch (_) { return false; }
62
+ }
63
+ function row(value){
64
+ if (!plain(value)) return false;
65
+ var keys = Object.keys(value);
66
+ return keys.length === 3 && keys.indexOf('id') !== -1 && keys.indexOf('version') !== -1 && keys.indexOf('values') !== -1 &&
67
+ typeof value.id === 'string' && value.id.length > 0 && Number.isSafeInteger(value.version) && value.version >= 1 &&
68
+ plain(value.values);
69
+ }
70
+ function result(op, data){
71
+ if (op === 'remove' && (data === null || data === undefined)) return true;
72
+ if (op === 'list') {
73
+ if (!Array.isArray(data)) return false;
74
+ for (var i = 0; i < data.length; i++) if (!Object.prototype.hasOwnProperty.call(data, i) || !row(data[i])) return false;
75
+ return true;
76
+ }
77
+ if (op === 'get' && data === null) return true;
78
+ if (op === 'remove') return false;
79
+ return row(data);
80
+ }
81
+ function failure(reason, op, metadata){
82
+ var safeReason = reason === 'http_409' ? 'conflict' :
83
+ (reason === 'invalid_result' ? 'invalid_result' :
84
+ (reason === 'bridge_timeout' ? 'bridge_timeout' : 'bridge_unavailable'));
85
+ var error = new Error(safeReason);
86
+ var write = op === 'create' || op === 'update' || op === 'remove';
87
+ error.code = safeReason === 'conflict' ? 'conflict' : (write ? 'unknown' : 'unavailable');
88
+ if (write) error.operationId = metadata.operationId;
89
+ return error;
90
+ }
91
+ function call(op, entity, id, payload, metadata){
92
+ return new Promise(function(resolve, reject){
93
+ var write = op === 'create' || op === 'update' || op === 'remove';
94
+ var operationId, expectedVersion;
95
+ try {
96
+ if (write) operationId = metadata && metadata.operationId;
97
+ if (op === 'update' || op === 'remove') expectedVersion = metadata && metadata.expectedVersion;
98
+ } catch (_) {
99
+ var invalidGetter = new Error('invalid_write_metadata'); invalidGetter.code = 'invalid-request'; reject(invalidGetter); return;
100
+ }
101
+ if (write && (typeof operationId !== 'string' || !operationId.trim() || operationId.length > 128 ||
102
+ ((op === 'update' || op === 'remove') && (!Number.isSafeInteger(expectedVersion) || expectedVersion < 1)))) {
103
+ var invalid = new Error('invalid_write_metadata'); invalid.code = 'invalid-request'; reject(invalid); return;
104
+ }
105
+ var safeMetadata = { operationId: operationId, expectedVersion: expectedVersion };
106
+ var reqId = 'r' + (++seq) + '_' + Date.now();
107
+ var request = { op: op, entity: entity };
108
+ if (id !== undefined) request.id = id;
109
+ if (payload !== undefined) request[op === 'list' ? 'filter' : (op === 'create' ? 'record' : 'patch')] = payload;
110
+ if (write) request.operationId = operationId;
111
+ if (op === 'update' || op === 'remove') request.expectedVersion = expectedVersion;
112
+ if (!bounded(request)) {
113
+ var invalidPayload = new Error('invalid_request'); invalidPayload.code = 'invalid-request'; reject(invalidPayload); return;
114
+ }
115
+ var frame = { source: requestSource, reqId: reqId, op: op, entity: entity, previewToken: previewToken };
116
+ if (id !== undefined) frame.id = id;
117
+ if (payload !== undefined) frame.payload = payload;
118
+ if (write) frame.operationId = operationId;
119
+ if (op === 'update' || op === 'remove') frame.expectedVersion = expectedVersion;
120
+ var channel;
121
+ try { channel = new MessageChannel(); }
122
+ catch (_) { reject(failure('bridge_unavailable', op, safeMetadata)); return; }
123
+ var settled = false;
124
+ function finish(reason, data){
125
+ if (settled) return; settled = true;
126
+ clearTimeout(timer);
127
+ try { channel.port1.close(); } catch (_) {}
128
+ try {
129
+ if (reason) reject(failure(reason, op, safeMetadata));
130
+ else if (!result(op, data)) reject(failure('invalid_result', op, safeMetadata));
131
+ else resolve(data);
132
+ } catch (_) { reject(failure('invalid_result', op, safeMetadata)); }
133
+ }
134
+ var timer = setTimeout(function(){ finish('bridge_timeout'); }, op === 'remove' && isV2 ? 300000 : 10000);
135
+ channel.port1.onmessage = function(event){
136
+ try {
137
+ var response = event.data;
138
+ if (!response || response.source !== responseSource || response.reqId !== reqId) return;
139
+ if (typeof response.ok !== 'boolean' ||
140
+ (response.ok && !(op === 'remove' && response.data === undefined) && !bounded(response.data))) {
141
+ finish('invalid_result'); return;
142
+ }
143
+ finish(response.ok ? null : (response.error === 'http_409' ? 'http_409' : 'bridge_error'), response.data);
144
+ } catch (_) { finish('invalid_result'); }
145
+ };
146
+ try {
147
+ window.parent.postMessage(frame, '*', [channel.port2]);
148
+ } catch (_) { try { channel.port2.close(); } catch (_) {} finish('bridge_unavailable'); }
149
+ });
150
+ }
151
+ var client = {
152
+ protocol: webProtocol,
153
+ list: function(entity, filter){ return call('list', entity, undefined, filter); },
154
+ get: function(entity, id){ return call('get', entity, id); },
155
+ create: function(entity, record, metadata){ return call('create', entity, undefined, record, metadata); },
156
+ update: function(entity, id, patch, metadata){ return call('update', entity, id, patch, metadata); }
157
+ };
158
+ if (isV2) client.remove = function(entity, id, metadata){ return call('remove', entity, id, undefined, metadata); };
159
+ window.__uibotData = client;
160
+ if (compatibilityGlobalName) window[compatibilityGlobalName] = client;
161
+ window.__uibotDataWebV1Shim = true;
162
+ })();`}import{jsxDEV as v}from"react/jsx-dev-runtime";function ve(){return globalThis.process?.env?.NODE_ENV==="production"}function be(e){if(!(e.enabled??!ve()))return null;let n=e.gaps??[],i=e.warnings??[],l=e.droppedEventFields??[];if(n.length+i.length+l.length===0)return null;return v("aside",{"data-uibot-diagnostics":"true",style:{position:"fixed",right:12,bottom:12,maxWidth:360,padding:12,background:"var(--uibot-surface, #fff)",color:"var(--uibot-text, #111)",border:"1px solid var(--uibot-border, #ccc)",font:"12px/1.4 var(--uibot-font, sans-serif)"},children:[v("strong",{children:"UIBot diagnostics"},void 0,!1,void 0,this),v("ul",{children:[n.map((a)=>v("li",{children:[a.code??a.reason," ",a.elementKey," ",a.path??a.missingType]},`gap:${a.elementKey}:${a.path??a.missingType}`,!0,void 0,this)),i.map((a)=>v("li",{children:[a.code," ",a.elementKey," ",a.path]},`warn:${a.elementKey??""}:${a.path??a.code}`,!0,void 0,this)),l.map((a)=>v("li",{children:["dropped event field ",a]},`drop:${a}`,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{UIBotLiveRenderer as Ge,UIBotRenderer as Je}from"@uibot/renderer-react";import{defineCatalog as Ce,parseUIBotRegistryItemDescriptor as he}from"@uibot/contracts";import{defineRegistry as Ie}from"@uibot/renderer-react";class g extends Error{constructor(e){super(`installed UIBot library: ${e}`);this.name="InstalledUIBotLibraryError"}}function Re(e){let t={},n=new Map,i=new Map,l={};for(let[c,u]of Object.entries(e.descriptors)){let r=he(u),s=c.slice(0,c.lastIndexOf("/")+1);for(let o of r.components??[]){let d=n.get(o.name);if(d)throw new g(`component "${o.name}" is provided by both "${d}" and "${r.item}"`);let p=`${s}${o.module}`,y=e.modules[p];if(!y)throw new g(`"${r.item}" needs ${p}, which is not installed`);let m=y[o.export];if(typeof m!=="function")throw new g(`${p} has no component export "${o.export}" for "${o.name}"`);n.set(o.name,r.item),t[o.name]=o.catalog,l[o.name]={category:o.catalog.category,sourcePlugin:`registry:${r.item}`,component:m}}if(r.template){let o=r.template.contract.name;if(i.has(o))throw new g(`template "${o}" is installed twice`);let d=e.templateSources?.[`${s}${r.template.file}`];if(e.templateSources&&d===void 0)throw new g(`template "${o}" needs ${s}${r.template.file}, which is not installed`);i.set(o,{contract:r.template.contract,...d===void 0?{}:{source:d}})}}let a=Object.fromEntries(i);return{catalog:Ce({components:t,templates:Object.fromEntries(Object.entries(a).map(([c,u])=>[c,u.contract]))}),registry:Ie(l),templates:a}}export{fe as CREATION_DATA_WEB_PROTOCOL,me as CREATION_DATA_WEB_V2_PROTOCOL,ge as CREATION_DATA_WRITE_PROTOCOL,ye as CreationDataPortRejection,g as InstalledUIBotLibraryError,K as UIBotAppHost,be as UIBotDiagnostics,Ge as UIBotLiveRenderer,I as UIBotPageAccessError,Je as UIBotRenderer,Re as assembleInstalledUIBotLibrary,D as bindUrlState,pe as createCreationDataWebShimSource,G as createLiveRuntimeAdapter,de as dispatchCreationData};
@@ -0,0 +1,42 @@
1
+ import { type Catalog, type TemplateContract } from "@uibot/contracts";
2
+ import { type ReactRegistry } from "@uibot/renderer-react";
3
+ /**
4
+ * Files a host installed from the UIBot shadcn registry (ADR 0012), keyed by a
5
+ * path shared by all three maps — typically `import.meta.glob` output:
6
+ *
7
+ * ```ts
8
+ * assembleInstalledUIBotLibrary({
9
+ * descriptors: import.meta.glob("./components/uibot/*.uibot.json", { eager: true, import: "default" }),
10
+ * modules: import.meta.glob("./components/uibot/*.{ts,tsx}", { eager: true }),
11
+ * templateSources: import.meta.glob("./lib/uibot/templates/*.uibot.yaml", { eager: true, query: "?raw", import: "default" }),
12
+ * });
13
+ * ```
14
+ *
15
+ * Template descriptors go into `descriptors` as well.
16
+ */
17
+ export interface InstalledUIBotLibraryInput {
18
+ descriptors: Readonly<Record<string, unknown>>;
19
+ modules: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
20
+ templateSources?: Readonly<Record<string, string>>;
21
+ }
22
+ export interface InstalledUIBotTemplate {
23
+ contract: TemplateContract;
24
+ /** Raw Spec source (YAML); parse it with `@uibot/compiler` `parseConfig`. */
25
+ source?: string;
26
+ }
27
+ export interface InstalledUIBotLibrary {
28
+ /** Spec catalog of the installed components and templates. */
29
+ catalog: Catalog;
30
+ /** Renderer registry binding each installed component type to its export. */
31
+ registry: ReactRegistry;
32
+ templates: Record<string, InstalledUIBotTemplate>;
33
+ }
34
+ export declare class InstalledUIBotLibraryError extends Error {
35
+ constructor(detail: string);
36
+ }
37
+ /**
38
+ * Rebuild the Spec catalog and renderer registry from the items a host actually
39
+ * installed. Fails closed on a missing module or export, a duplicate component
40
+ * type, or a malformed descriptor, so a stale install never renders silently.
41
+ */
42
+ export declare function assembleInstalledUIBotLibrary(input: InstalledUIBotLibraryInput): InstalledUIBotLibrary;
@@ -0,0 +1,74 @@
1
+ import type { CompiledPage, CompiledUIBotSpec, ConnectionDriver, ConnectionDriverContext } from "@uibot/contracts";
2
+ import { type Engine, type SessionUser } from "@uibot/engine";
3
+ import type { UIBotRuntimeAdapter } from "@uibot/renderer-react";
4
+ import { type UrlStateIO } from "./url-state.js";
5
+ export interface UIBotPageTarget {
6
+ pageId?: string;
7
+ pagePath?: string;
8
+ }
9
+ export type UIBotPageResolution = {
10
+ status: "ready";
11
+ pageId: string;
12
+ pagePath: string;
13
+ } | {
14
+ status: "unauthorized";
15
+ pageId: string;
16
+ pagePath: string;
17
+ redirect?: string;
18
+ } | {
19
+ status: "not-found";
20
+ pageId?: string;
21
+ pagePath?: string;
22
+ } | {
23
+ status: "error";
24
+ message: string;
25
+ };
26
+ export interface UIBotNavigationRequest {
27
+ destination: string;
28
+ target: "_self" | "_blank";
29
+ }
30
+ export interface UIBotAuthorizationContext {
31
+ user: SessionUser | null;
32
+ }
33
+ export interface UIBotAppRuntimeAdapter extends UIBotRuntimeAdapter {
34
+ resolvePage(target?: UIBotPageTarget): Promise<UIBotPageResolution>;
35
+ dispose(): void;
36
+ }
37
+ export interface CreateLiveAdapterOptions {
38
+ spec: CompiledUIBotSpec;
39
+ /** Pre-wired engine; defaults to `createEngine(firstPage.state)`. */
40
+ engine?: Engine;
41
+ /** Host-provided connection drivers; this package never imports concrete drivers. */
42
+ drivers?: readonly ConnectionDriver[];
43
+ /** Host-owned secret resolver; omitted means secret lookup is unavailable. */
44
+ resolveSecret?: ConnectionDriverContext["resolveSecret"];
45
+ /** Optional host authorization policy; defaults to the engine session roles. */
46
+ authorize?: (page: CompiledPage, context: UIBotAuthorizationContext) => boolean | Promise<boolean>;
47
+ /** Host router bridge used by declarative Link actions. */
48
+ navigate?: (request: UIBotNavigationRequest) => void | Promise<void>;
49
+ /** Called when an async host navigation rejects; receives no raw exception. */
50
+ onNavigationError?: (request: UIBotNavigationRequest) => void;
51
+ /**
52
+ * Host-owned query-string bridge. UIBot reads and writes the params declared
53
+ * by each page's `urlState`; it does not take over the router.
54
+ */
55
+ urlState?: UrlStateIO;
56
+ }
57
+ /**
58
+ * Adapt a `@uibot/engine` {@link Engine} into the {@link UIBotRuntimeAdapter}
59
+ * consumed by `@uibot/renderer-react`'s `UIBotLiveRenderer`.
60
+ *
61
+ * This is the single place that imports both `@uibot/engine` and
62
+ * `@uibot/renderer-react`, keeping the two domain modules independent. It is
63
+ * client-safe (pulls in no server-only / AI-framework deps), so studio,
64
+ * application, and examples all assemble the live runtime from here.
65
+ */
66
+ export declare function createLiveRuntimeAdapter(opts: CreateLiveAdapterOptions): UIBotAppRuntimeAdapter;
67
+ export declare class UIBotPageAccessError extends Error {
68
+ readonly resolution: Exclude<UIBotPageResolution, {
69
+ status: "ready";
70
+ }>;
71
+ constructor(pageId: string, resolution: Exclude<UIBotPageResolution, {
72
+ status: "ready";
73
+ }>);
74
+ }
@@ -0,0 +1,13 @@
1
+ import type { UrlStateBinding } from "@uibot/contracts";
2
+ import type { StateStore } from "@uibot/engine";
3
+ export interface UrlStateIO {
4
+ read(): URLSearchParams;
5
+ write(params: URLSearchParams, options: {
6
+ replace: true;
7
+ }): void;
8
+ }
9
+ /**
10
+ * Read declared query params into the store, then write them back when those
11
+ * keys change. The host still owns routing.
12
+ */
13
+ export declare function bindUrlState(store: StateStore, bindings: Record<string, UrlStateBinding>, io: UrlStateIO): () => void;
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@uibot/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/Foundj/uibot.git",
8
+ "directory": "packages/runtime"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.js",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "!dist/**/*.map",
23
+ "!dist/**/*.test.d.ts",
24
+ "!dist/**/*.spec.d.ts"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "peerDependencies": {
30
+ "react": ">=18"
31
+ },
32
+ "dependencies": {
33
+ "@uibot/contracts": "^0.2.0",
34
+ "@uibot/engine": "^0.2.0",
35
+ "@uibot/renderer-react": "^0.2.0"
36
+ },
37
+ "scripts": {
38
+ "build": "rm -rf dist && bun build --minify ./src/index.ts --tsconfig-override ../../scripts/tsconfig.bundle.json --outdir ./dist --format esm --target browser --packages external --external react --external react/* --external @uibot/contracts --external @uibot/engine --external @uibot/renderer-react && bun x tsc -p tsconfig.json",
39
+ "typecheck": "bun x tsc -p tsconfig.json --noEmit",
40
+ "test": "bun test"
41
+ }
42
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.