@copilotkit/react-native 1.67.1 → 1.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-C0xms8kb.cjs +34 -0
- package/dist/components/index.cjs +146 -33
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.mjs +144 -32
- package/dist/components/index.mjs.map +1 -1
- package/dist/headless.cjs +40 -4
- package/dist/headless.d.cts +3 -3
- package/dist/headless.d.mts +3 -3
- package/dist/headless.mjs +5 -4
- package/dist/index.cjs +43 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -4
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills/encoding.cjs +1 -1
- package/dist/polyfills/streams.cjs +1 -1
- package/dist/useRenderTool-BBxnOOeJ.d.mts +161 -0
- package/dist/useRenderTool-BWo11PCL.d.cts +161 -0
- package/dist/{useRenderTool-DLavcsVB.cjs → useRenderTool-CKEPq7MQ.cjs} +20 -34
- package/dist/useRenderTool-CKEPq7MQ.cjs.map +1 -0
- package/dist/{useRenderTool-DUqpS97B.mjs → useRenderTool-l7M-I8rT.mjs} +18 -33
- package/dist/useRenderTool-l7M-I8rT.mjs.map +1 -0
- package/package.json +9 -6
- package/scripts/__tests__/fixtures/stray-react-dom-headless.js +16 -0
- package/scripts/__tests__/fixtures/tiny-headless.js +10 -0
- package/scripts/__tests__/fixtures/warning-headless.js +13 -0
- package/scripts/__tests__/measure-headless.test.mjs +275 -0
- package/scripts/measure-headless.mjs +310 -0
- package/src/CopilotKitProvider.tsx +1 -2
- package/src/__mocks__/test-copilotkit.tsx +116 -0
- package/src/__mocks__/tool-fixtures.ts +50 -0
- package/src/__tests__/headless-entry-surface.test.ts +464 -46
- package/src/__tests__/headless-integration.test.tsx +12 -1
- package/src/__tests__/headless-value-exports.test.ts +369 -0
- package/src/components/CopilotChat.tsx +218 -32
- package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -126
- package/src/components/__tests__/CopilotChat.test.tsx +5 -49
- package/src/components/__tests__/CopilotChatToolCalls.test.tsx +468 -0
- package/src/headless.ts +36 -14
- package/src/hooks/__tests__/render-tool-call.integration.test.tsx +181 -0
- package/src/hooks/__tests__/useRenderTool.test.tsx +232 -267
- package/src/hooks/index.ts +1 -7
- package/src/hooks/render-tool-types.ts +55 -0
- package/src/hooks/useRenderTool.ts +29 -57
- package/src/index.ts +13 -5
- package/dist/RenderToolContext-CBNKcJqz.cjs +0 -126
- package/dist/RenderToolContext-CBNKcJqz.cjs.map +0 -1
- package/dist/RenderToolContext-D8M-JhD1.mjs +0 -75
- package/dist/RenderToolContext-D8M-JhD1.mjs.map +0 -1
- package/dist/useRenderTool-9YDIfZ0D.d.mts +0 -164
- package/dist/useRenderTool-BugVTDoM.d.cts +0 -164
- package/dist/useRenderTool-DLavcsVB.cjs.map +0 -1
- package/dist/useRenderTool-DUqpS97B.mjs.map +0 -1
- package/src/hooks/RenderToolContext.tsx +0 -150
- package/src/hooks/__tests__/RenderToolContext.test.tsx +0 -264
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_chunk = require('./chunk-C0xms8kb.cjs');
|
|
2
2
|
let react = require("react");
|
|
3
|
-
react =
|
|
3
|
+
react = require_chunk.__toESM(react);
|
|
4
4
|
let _copilotkit_react_core_v2_context = require("@copilotkit/react-core/v2/context");
|
|
5
5
|
let _copilotkit_react_core_v2_headless = require("@copilotkit/react-core/v2/headless");
|
|
6
6
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
@@ -110,7 +110,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, creden
|
|
|
110
110
|
value: contextValue,
|
|
111
111
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_react_core_v2_context.LicenseContext.Provider, {
|
|
112
112
|
value: licenseContextValue,
|
|
113
|
-
children
|
|
113
|
+
children
|
|
114
114
|
})
|
|
115
115
|
});
|
|
116
116
|
};
|
|
@@ -118,46 +118,32 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, creden
|
|
|
118
118
|
//#endregion
|
|
119
119
|
//#region src/hooks/useRenderTool.ts
|
|
120
120
|
/**
|
|
121
|
-
*
|
|
121
|
+
* Registers a frontend tool AND its renderer.
|
|
122
122
|
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
* {status === "executing" && <ActivityIndicator />}
|
|
137
|
-
* </View>
|
|
138
|
-
* ),
|
|
139
|
-
* handler: async ({ city }) => {
|
|
140
|
-
* return { forecast: "sunny" };
|
|
141
|
-
* },
|
|
142
|
-
* });
|
|
143
|
-
* ```
|
|
123
|
+
* Registration goes through react-core's `useFrontendTool`, which writes the
|
|
124
|
+
* renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
|
|
125
|
+
* that RN's provider already instantiates. There is deliberately NO React
|
|
126
|
+
* Native-local registry: this package previously kept its own Map, which meant
|
|
127
|
+
* `useComponent` (registering into core's) rendered nowhere on RN, and renderers
|
|
128
|
+
* were dropped from chat history on unmount.
|
|
129
|
+
*/
|
|
130
|
+
/**
|
|
131
|
+
* @param deps Optional dependency array. The `render` function is captured at
|
|
132
|
+
* registration and only refreshed when `deps` change — it does NOT re-read the
|
|
133
|
+
* latest closure on every render. If your `render` closes over component state
|
|
134
|
+
* or props that change over time, you MUST pass those values in `deps`, or the
|
|
135
|
+
* chat will keep painting with the stale closure.
|
|
144
136
|
*/
|
|
145
137
|
function useRenderTool(options, deps) {
|
|
146
138
|
const { name, description, parameters, render, handler, agentId } = options;
|
|
147
|
-
const { register } = require_RenderToolContext.useRenderToolContext();
|
|
148
139
|
(0, _copilotkit_react_core_v2_headless.useFrontendTool)({
|
|
149
140
|
name,
|
|
150
141
|
description,
|
|
151
142
|
parameters,
|
|
152
143
|
handler,
|
|
153
|
-
agentId
|
|
144
|
+
agentId,
|
|
145
|
+
render
|
|
154
146
|
}, deps);
|
|
155
|
-
const renderRef = (0, react.useRef)(render);
|
|
156
|
-
renderRef.current = render;
|
|
157
|
-
(0, react.useEffect)(() => {
|
|
158
|
-
const stableRender = (props) => renderRef.current(props);
|
|
159
|
-
return register(name, stableRender);
|
|
160
|
-
}, [name, register]);
|
|
161
147
|
}
|
|
162
148
|
|
|
163
149
|
//#endregion
|
|
@@ -173,4 +159,4 @@ Object.defineProperty(exports, 'useRenderTool', {
|
|
|
173
159
|
return useRenderTool;
|
|
174
160
|
}
|
|
175
161
|
});
|
|
176
|
-
//# sourceMappingURL=useRenderTool-
|
|
162
|
+
//# sourceMappingURL=useRenderTool-CKEPq7MQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useRenderTool-CKEPq7MQ.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./render-tool-types\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /** Schema describing the tool's parameters (any StandardSchemaV1 library). */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function returning a React Native element for the tool call.\n * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.\n *\n * Arguments STREAM: on `status: \"inProgress\"` the props are partial, because\n * the model has not finished writing the JSON. Write renderers that tolerate\n * missing fields — that is what makes UI build progressively.\n */\n render: RenderToolFunction<T>;\n /** Optional handler. Omit for render-only (display IS the effect). */\n handler?: (args: T) => Promise<unknown>;\n /** Scope this tool to a single agent. */\n agentId?: string;\n}\n\n/**\n * Registers a frontend tool AND its renderer.\n *\n * Registration goes through react-core's `useFrontendTool`, which writes the\n * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry\n * that RN's provider already instantiates. There is deliberately NO React\n * Native-local registry: this package previously kept its own Map, which meant\n * `useComponent` (registering into core's) rendered nowhere on RN, and renderers\n * were dropped from chat history on unmount.\n */\n/**\n * @param deps Optional dependency array. The `render` function is captured at\n * registration and only refreshed when `deps` change — it does NOT re-read the\n * latest closure on every render. If your `render` closes over component state\n * or props that change over time, you MUST pass those values in `deps`, or the\n * chat will keep painting with the stale closure.\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>[\"render\"],\n // and RenderToolFunction is derived from exactly that props type, returning\n // ReactElement | null (assignable to ComponentType's ReactNode).\n render,\n },\n deps,\n );\n}\n\nexport type { RenderToolProps, RenderToolFunction } from \"./render-tool-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,yCACE,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,4CACE,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,kCAA2D,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAIA,uDAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,4BAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,4BAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,qEAErB,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,+CAE3B,OAAU;CAGZ,MAAM,+BAAoB,QAAQ;AAClC,4BAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,4BAAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,yCACG;EACL;EACA;EACD,GACD,CAAC,YAAY,qBAAqB,CACnC;CAGD,MAAM,iGAC4B,qBAAqB,EACrD,CAAC,qBAAqB,CACvB;AAED,QACE,2CAACC,oDAAkB;EAAS,OAAO;YACjC,2CAACC,iDAAe;GAAS,OAAO;GAC7B;IACuB;GACC;;;;;;;;;;;;;;;;;;;;;;AC7LjC,SAAgB,cAEd,SAAkC,MAAqC;CACvE,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,YAAY;AAEpE,yDACE;EACE;EACA;EACA;EACA;EACA;EAIA;EACD,EACD,KACD"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { n as useRenderToolContext, t as RenderToolProvider } from "./RenderToolContext-D8M-JhD1.mjs";
|
|
2
1
|
import React, { useEffect, useMemo, useRef, useState } from "react";
|
|
3
2
|
import { CopilotKitContext, LicenseContext } from "@copilotkit/react-core/v2/context";
|
|
4
3
|
import { CopilotKitCoreReact, useFrontendTool } from "@copilotkit/react-core/v2/headless";
|
|
@@ -109,7 +108,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, creden
|
|
|
109
108
|
value: contextValue,
|
|
110
109
|
children: /* @__PURE__ */ jsx(LicenseContext.Provider, {
|
|
111
110
|
value: licenseContextValue,
|
|
112
|
-
children
|
|
111
|
+
children
|
|
113
112
|
})
|
|
114
113
|
});
|
|
115
114
|
};
|
|
@@ -117,48 +116,34 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, creden
|
|
|
117
116
|
//#endregion
|
|
118
117
|
//#region src/hooks/useRenderTool.ts
|
|
119
118
|
/**
|
|
120
|
-
*
|
|
119
|
+
* Registers a frontend tool AND its renderer.
|
|
121
120
|
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* {status === "executing" && <ActivityIndicator />}
|
|
136
|
-
* </View>
|
|
137
|
-
* ),
|
|
138
|
-
* handler: async ({ city }) => {
|
|
139
|
-
* return { forecast: "sunny" };
|
|
140
|
-
* },
|
|
141
|
-
* });
|
|
142
|
-
* ```
|
|
121
|
+
* Registration goes through react-core's `useFrontendTool`, which writes the
|
|
122
|
+
* renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
|
|
123
|
+
* that RN's provider already instantiates. There is deliberately NO React
|
|
124
|
+
* Native-local registry: this package previously kept its own Map, which meant
|
|
125
|
+
* `useComponent` (registering into core's) rendered nowhere on RN, and renderers
|
|
126
|
+
* were dropped from chat history on unmount.
|
|
127
|
+
*/
|
|
128
|
+
/**
|
|
129
|
+
* @param deps Optional dependency array. The `render` function is captured at
|
|
130
|
+
* registration and only refreshed when `deps` change — it does NOT re-read the
|
|
131
|
+
* latest closure on every render. If your `render` closes over component state
|
|
132
|
+
* or props that change over time, you MUST pass those values in `deps`, or the
|
|
133
|
+
* chat will keep painting with the stale closure.
|
|
143
134
|
*/
|
|
144
135
|
function useRenderTool(options, deps) {
|
|
145
136
|
const { name, description, parameters, render, handler, agentId } = options;
|
|
146
|
-
const { register } = useRenderToolContext();
|
|
147
137
|
useFrontendTool({
|
|
148
138
|
name,
|
|
149
139
|
description,
|
|
150
140
|
parameters,
|
|
151
141
|
handler,
|
|
152
|
-
agentId
|
|
142
|
+
agentId,
|
|
143
|
+
render
|
|
153
144
|
}, deps);
|
|
154
|
-
const renderRef = useRef(render);
|
|
155
|
-
renderRef.current = render;
|
|
156
|
-
useEffect(() => {
|
|
157
|
-
const stableRender = (props) => renderRef.current(props);
|
|
158
|
-
return register(name, stableRender);
|
|
159
|
-
}, [name, register]);
|
|
160
145
|
}
|
|
161
146
|
|
|
162
147
|
//#endregion
|
|
163
148
|
export { CopilotKitProvider as n, useRenderTool as t };
|
|
164
|
-
//# sourceMappingURL=useRenderTool-
|
|
149
|
+
//# sourceMappingURL=useRenderTool-l7M-I8rT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useRenderTool-l7M-I8rT.mjs","names":[],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./render-tool-types\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /** Schema describing the tool's parameters (any StandardSchemaV1 library). */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function returning a React Native element for the tool call.\n * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.\n *\n * Arguments STREAM: on `status: \"inProgress\"` the props are partial, because\n * the model has not finished writing the JSON. Write renderers that tolerate\n * missing fields — that is what makes UI build progressively.\n */\n render: RenderToolFunction<T>;\n /** Optional handler. Omit for render-only (display IS the effect). */\n handler?: (args: T) => Promise<unknown>;\n /** Scope this tool to a single agent. */\n agentId?: string;\n}\n\n/**\n * Registers a frontend tool AND its renderer.\n *\n * Registration goes through react-core's `useFrontendTool`, which writes the\n * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry\n * that RN's provider already instantiates. There is deliberately NO React\n * Native-local registry: this package previously kept its own Map, which meant\n * `useComponent` (registering into core's) rendered nowhere on RN, and renderers\n * were dropped from chat history on unmount.\n */\n/**\n * @param deps Optional dependency array. The `render` function is captured at\n * registration and only refreshed when `deps` change — it does NOT re-read the\n * latest closure on every render. If your `render` closes over component state\n * or props that change over time, you MUST pass those values in `deps`, or the\n * chat will keep painting with the stale closure.\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>[\"render\"],\n // and RenderToolFunction is derived from exactly that props type, returning\n // ReactElement | null (assignable to ComponentType's ReactNode).\n render,\n },\n deps,\n );\n}\n\nexport type { RenderToolProps, RenderToolFunction } from \"./render-tool-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,gBAAgB,cACd,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,mBAAmB,cACjB,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,gBAAgB,OAA2C,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAI,oBAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,iBAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,iBAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,2BAA2B,+BAEhD,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,2BAA2B,SAEtD,OAAU;CAGZ,MAAM,aAAa,OAAO,QAAQ;AAClC,iBAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,iBAAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,eAAuC,eACpC;EACL;EACA;EACD,GACD,CAAC,YAAY,qBAAqB,CACnC;CAGD,MAAM,sBAAsB,cACpB,0BAA0B,qBAAqB,EACrD,CAAC,qBAAqB,CACvB;AAED,QACE,oBAAC,kBAAkB;EAAS,OAAO;YACjC,oBAAC,eAAe;GAAS,OAAO;GAC7B;IACuB;GACC;;;;;;;;;;;;;;;;;;;;;;AC7LjC,SAAgB,cAEd,SAAkC,MAAqC;CACvE,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,YAAY;AAEpE,iBACE;EACE;EACA;EACA;EACA;EACA;EAIA;EACD,EACD,KACD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkit/react-native",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.68.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -72,13 +72,14 @@
|
|
|
72
72
|
"@ag-ui/client": "0.0.57",
|
|
73
73
|
"text-encoding": "^0.7.0",
|
|
74
74
|
"web-streams-polyfill": "^4.2.0",
|
|
75
|
-
"@copilotkit/core": "1.
|
|
76
|
-
"@copilotkit/
|
|
77
|
-
"@copilotkit/
|
|
75
|
+
"@copilotkit/core": "1.68.0",
|
|
76
|
+
"@copilotkit/shared": "1.68.0",
|
|
77
|
+
"@copilotkit/react-core": "1.68.0"
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
80
|
"@testing-library/react": "^16.3.0",
|
|
81
81
|
"@types/react": "^19.2.0",
|
|
82
|
+
"esbuild": "^0.27.0",
|
|
82
83
|
"jsdom": "^26.1.0",
|
|
83
84
|
"react": "^19.1.0",
|
|
84
85
|
"react-dom": "^19.1.0",
|
|
@@ -123,11 +124,13 @@
|
|
|
123
124
|
"scripts": {
|
|
124
125
|
"build": "tsdown",
|
|
125
126
|
"dev": "tsdown --watch",
|
|
126
|
-
"test": "vitest run",
|
|
127
|
+
"test": "vitest run && pnpm run test:scripts",
|
|
128
|
+
"test:scripts": "node --test scripts/__tests__/measure-headless.test.mjs",
|
|
127
129
|
"check-types": "tsc --noEmit",
|
|
128
130
|
"publint": "publint .",
|
|
129
131
|
"attw": "attw --pack . --profile node16 --ignore-rules internal-resolution-error",
|
|
130
132
|
"link:global": "pnpm link --global",
|
|
131
|
-
"unlink:global": "pnpm unlink --global"
|
|
133
|
+
"unlink:global": "pnpm unlink --global",
|
|
134
|
+
"size:headless": "node scripts/measure-headless.mjs"
|
|
132
135
|
}
|
|
133
136
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Same shape as tiny-headless.js plus the failure this guards against: a stray
|
|
2
|
+
// web-oriented edge into react-dom/client. Used to prove HEADLESS_EXTERNAL
|
|
3
|
+
// actually keeps react-dom OUT of the measured graph.
|
|
4
|
+
//
|
|
5
|
+
// react-dom/client (not bare react-dom) is the edge worth simulating: bare
|
|
6
|
+
// react-dom is a ~7 kB wrapper, while react-dom/client drags in
|
|
7
|
+
// react-dom-client.production.js (~536 kB raw) and is what would visibly
|
|
8
|
+
// inflate the reported figure.
|
|
9
|
+
import { createRoot } from "react-dom/client";
|
|
10
|
+
|
|
11
|
+
export const CopilotKitProvider = () => createRoot;
|
|
12
|
+
export const useAgent = () => null;
|
|
13
|
+
export const useFrontendTool = () => null;
|
|
14
|
+
export const useRenderTool = () => null;
|
|
15
|
+
export const useRenderToolCall = () => null;
|
|
16
|
+
export const useComponent = () => null;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Minimal stand-in for @copilotkit/react-native/headless, used by
|
|
2
|
+
// measure-headless.test.mjs. It exports exactly the symbols the measurement
|
|
3
|
+
// imports, so the bundling pipeline can be exercised without depending on the
|
|
4
|
+
// package's built dist.
|
|
5
|
+
export const CopilotKitProvider = () => null;
|
|
6
|
+
export const useAgent = () => null;
|
|
7
|
+
export const useFrontendTool = () => null;
|
|
8
|
+
export const useRenderTool = () => null;
|
|
9
|
+
export const useRenderToolCall = () => null;
|
|
10
|
+
export const useComponent = () => null;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Same shape as tiny-headless.js plus one construct esbuild warns about
|
|
2
|
+
// (a duplicate object key). Used to prove measureHeadlessBundle RETURNS
|
|
3
|
+
// esbuild's warnings rather than dropping them on the floor — `logLevel:
|
|
4
|
+
// "silent"` stops esbuild printing them, so the script must surface them.
|
|
5
|
+
export const CopilotKitProvider = () => null;
|
|
6
|
+
export const useAgent = () => null;
|
|
7
|
+
export const useFrontendTool = () => null;
|
|
8
|
+
export const useRenderTool = () => null;
|
|
9
|
+
export const useRenderToolCall = () => null;
|
|
10
|
+
// The duplicate key is the POINT of this fixture — it is what makes esbuild
|
|
11
|
+
// emit a warning. Silence the linter rather than the test's subject.
|
|
12
|
+
// oxlint-disable-next-line no-dupe-keys
|
|
13
|
+
export const useComponent = () => ({ duplicated: 1, duplicated: 2 });
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// Standalone Node test (not vitest) — the script under test calls esbuild,
|
|
2
|
+
// which trips vitest's jsdom env probe, and the package-wide vitest setup uses
|
|
3
|
+
// jsdom-only globals. Running with `node --test` keeps this isolated. This
|
|
4
|
+
// mirrors react-core's scripts/__tests__/measure-copilotchat.test.mjs.
|
|
5
|
+
//
|
|
6
|
+
// Invoked from package.json `test:scripts` and the chained `test` command.
|
|
7
|
+
//
|
|
8
|
+
// What this locks down: measure-headless.mjs prints the number that a bundle
|
|
9
|
+
// claim rests on, so its FAILURE modes are the thing worth testing — a zero or
|
|
10
|
+
// implausible total must be rejected, esbuild warnings must survive
|
|
11
|
+
// `logLevel: "silent"`, and an unbuilt package must say "run the build".
|
|
12
|
+
import { describe, it } from "node:test";
|
|
13
|
+
import assert from "node:assert/strict";
|
|
14
|
+
import { spawnSync } from "node:child_process";
|
|
15
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import {
|
|
20
|
+
assertBuilt,
|
|
21
|
+
BUILD_COMMAND,
|
|
22
|
+
BUILT_ENTRY_FILE,
|
|
23
|
+
HEADLESS_EXTERNAL,
|
|
24
|
+
implausibleTotalReason,
|
|
25
|
+
isEntrypoint,
|
|
26
|
+
measureHeadlessBundle,
|
|
27
|
+
MIN_PLAUSIBLE_BYTES,
|
|
28
|
+
} from "../measure-headless.mjs";
|
|
29
|
+
|
|
30
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
31
|
+
const fixtureDir = path.join(here, "fixtures");
|
|
32
|
+
const tinyEntry = path.join(fixtureDir, "tiny-headless.js");
|
|
33
|
+
const warningEntry = path.join(fixtureDir, "warning-headless.js");
|
|
34
|
+
const strayReactDomEntry = path.join(fixtureDir, "stray-react-dom-headless.js");
|
|
35
|
+
|
|
36
|
+
describe("measureHeadlessBundle", () => {
|
|
37
|
+
it("bundles a tiny headless fixture and returns a positive gzip total", async () => {
|
|
38
|
+
const result = await measureHeadlessBundle({
|
|
39
|
+
pkgRoot: fixtureDir,
|
|
40
|
+
entry: tinyEntry,
|
|
41
|
+
});
|
|
42
|
+
assert.ok(result.totalBytes > 0, "totalBytes should be > 0");
|
|
43
|
+
assert.ok(result.outputCount >= 1, "outputCount should be >= 1");
|
|
44
|
+
assert.equal(result.warnings.length, 0);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("returns a deterministic gzip total across two runs", async () => {
|
|
48
|
+
const a = await measureHeadlessBundle({
|
|
49
|
+
pkgRoot: fixtureDir,
|
|
50
|
+
entry: tinyEntry,
|
|
51
|
+
});
|
|
52
|
+
const b = await measureHeadlessBundle({
|
|
53
|
+
pkgRoot: fixtureDir,
|
|
54
|
+
entry: tinyEntry,
|
|
55
|
+
});
|
|
56
|
+
assert.equal(b.totalBytes, a.totalBytes);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("surfaces esbuild warnings instead of swallowing them", async () => {
|
|
60
|
+
const { warnings } = await measureHeadlessBundle({
|
|
61
|
+
pkgRoot: fixtureDir,
|
|
62
|
+
entry: warningEntry,
|
|
63
|
+
});
|
|
64
|
+
assert.equal(warnings.length, 1);
|
|
65
|
+
assert.match(warnings[0].text, /Duplicate key/);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("throws with esbuild's error text and the build command when the entry does not resolve", async () => {
|
|
69
|
+
await assert.rejects(
|
|
70
|
+
() =>
|
|
71
|
+
measureHeadlessBundle({
|
|
72
|
+
pkgRoot: fixtureDir,
|
|
73
|
+
entry: "@copilotkit/react-native/definitely-not-an-entry",
|
|
74
|
+
}),
|
|
75
|
+
(error) => {
|
|
76
|
+
assert.match(error.message, /Could not resolve/);
|
|
77
|
+
assert.ok(
|
|
78
|
+
error.message.includes(BUILD_COMMAND),
|
|
79
|
+
`error should name the build command, got:\n${error.message}`,
|
|
80
|
+
);
|
|
81
|
+
return true;
|
|
82
|
+
},
|
|
83
|
+
);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe("HEADLESS_EXTERNAL", () => {
|
|
88
|
+
it("externalizes the host-provided packages, react-dom included", () => {
|
|
89
|
+
// react-dom is the defensive one: it is not reachable from the headless
|
|
90
|
+
// entry today, so nothing else would notice if it were dropped, and a
|
|
91
|
+
// later stray edge would silently inflate the reported figure.
|
|
92
|
+
for (const pkg of ["react", "react-native", "react-dom"]) {
|
|
93
|
+
assert.ok(
|
|
94
|
+
HEADLESS_EXTERNAL.includes(pkg),
|
|
95
|
+
`${pkg} must stay external — it is provided by the host app, so bundling it would measure the host's cost, not ours. Got: ${HEADLESS_EXTERNAL.join(", ")}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("keeps a stray react-dom/client edge out of the measured graph", async () => {
|
|
101
|
+
// A/B over the same fixture: the only difference is whether react-dom is
|
|
102
|
+
// externalized. This is what makes the react-dom entry load-bearing rather
|
|
103
|
+
// than decorative — and it also proves esbuild's package-path prefix match
|
|
104
|
+
// covers the /client subpath without an entry of its own.
|
|
105
|
+
const guarded = await measureHeadlessBundle({
|
|
106
|
+
pkgRoot: fixtureDir,
|
|
107
|
+
entry: strayReactDomEntry,
|
|
108
|
+
});
|
|
109
|
+
const unguarded = await measureHeadlessBundle({
|
|
110
|
+
pkgRoot: fixtureDir,
|
|
111
|
+
entry: strayReactDomEntry,
|
|
112
|
+
external: HEADLESS_EXTERNAL.filter((pkg) => pkg !== "react-dom"),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
assert.ok(
|
|
116
|
+
unguarded.totalBytes > guarded.totalBytes * 5,
|
|
117
|
+
`dropping react-dom from external should visibly inflate the figure, ` +
|
|
118
|
+
`but guarded=${guarded.totalBytes} B and unguarded=${unguarded.totalBytes} B`,
|
|
119
|
+
);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe("implausibleTotalReason", () => {
|
|
124
|
+
it("rejects a zero total — the '0.0 kB looks like a huge win' failure", () => {
|
|
125
|
+
assert.match(implausibleTotalReason(0), /no output/);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("rejects a total under the plausibility floor", () => {
|
|
129
|
+
const reason = implausibleTotalReason(MIN_PLAUSIBLE_BYTES - 1);
|
|
130
|
+
assert.match(reason, /plausibility floor/);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("accepts a realistic headless total", () => {
|
|
134
|
+
assert.equal(implausibleTotalReason(92 * 1024), null);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("rejects a total that rounds to the misleading 0.0 kB print", () => {
|
|
138
|
+
// An empty bundle measures ~20-35 B (the gzip envelope alone), which
|
|
139
|
+
// renders as "0.0 kB" at one decimal place — the headline failure. A
|
|
140
|
+
// zero-only guard would let this through, so assert the floor catches it.
|
|
141
|
+
assert.ok(implausibleTotalReason(33) !== null);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("assertBuilt", () => {
|
|
146
|
+
it("names the build command when the built entry is missing", () => {
|
|
147
|
+
const emptyRoot = fs.mkdtempSync(path.join(os.tmpdir(), "rn-unbuilt-"));
|
|
148
|
+
try {
|
|
149
|
+
assert.throws(
|
|
150
|
+
() => assertBuilt(emptyRoot),
|
|
151
|
+
(error) => {
|
|
152
|
+
assert.match(error.message, /dist\/headless\.mjs is missing/);
|
|
153
|
+
assert.ok(
|
|
154
|
+
error.message.includes(BUILD_COMMAND),
|
|
155
|
+
`error should name the build command, got:\n${error.message}`,
|
|
156
|
+
);
|
|
157
|
+
return true;
|
|
158
|
+
},
|
|
159
|
+
);
|
|
160
|
+
} finally {
|
|
161
|
+
fs.rmSync(emptyRoot, { recursive: true, force: true });
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("passes once the built entry exists", () => {
|
|
166
|
+
const builtRoot = fs.mkdtempSync(path.join(os.tmpdir(), "rn-built-"));
|
|
167
|
+
try {
|
|
168
|
+
const built = path.join(builtRoot, BUILT_ENTRY_FILE);
|
|
169
|
+
fs.mkdirSync(path.dirname(built), { recursive: true });
|
|
170
|
+
fs.writeFileSync(built, "export {};\n");
|
|
171
|
+
assert.doesNotThrow(() => assertBuilt(builtRoot));
|
|
172
|
+
} finally {
|
|
173
|
+
fs.rmSync(builtRoot, { recursive: true, force: true });
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// This script only prints its number if its CLI block actually RUNS. The first
|
|
179
|
+
// version of that guard compared `import.meta.url` to a `file://`-concatenated
|
|
180
|
+
// `process.argv[1]`, which is false whenever the checkout path needs URL encoding
|
|
181
|
+
// (a SPACE) or is reached through a symlink — so the script exited 0 having
|
|
182
|
+
// measured nothing. Same cover as react-core's assert-headless-purity.test.mjs.
|
|
183
|
+
describe("isEntrypoint (the CLI entry guard)", () => {
|
|
184
|
+
/** A real file under a real directory whose name contains a space. */
|
|
185
|
+
const withSpaceFixture = () => {
|
|
186
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rn-entry-guard-"));
|
|
187
|
+
const dir = path.join(root, "dir with space");
|
|
188
|
+
fs.mkdirSync(dir);
|
|
189
|
+
const file = path.join(dir, "script.mjs");
|
|
190
|
+
fs.writeFileSync(file, "export {};\n");
|
|
191
|
+
return { root, file };
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
it("holds for a plain path", () => {
|
|
195
|
+
const self = fileURLToPath(import.meta.url);
|
|
196
|
+
assert.equal(isEntrypoint(import.meta.url, self), true);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("holds when the path contains a space (the percent-encoding trap)", () => {
|
|
200
|
+
const { root, file } = withSpaceFixture();
|
|
201
|
+
try {
|
|
202
|
+
const url = pathToFileURL(file).href;
|
|
203
|
+
// Guard the guard: without %20 in the URL this would pass vacuously.
|
|
204
|
+
assert.ok(url.includes("%20"), `expected an encoded URL, got ${url}`);
|
|
205
|
+
assert.notEqual(
|
|
206
|
+
url,
|
|
207
|
+
`file://${file}`,
|
|
208
|
+
"the naive string comparison must be the thing that fails here",
|
|
209
|
+
);
|
|
210
|
+
assert.equal(isEntrypoint(url, file), true);
|
|
211
|
+
} finally {
|
|
212
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it("holds when argv[1] reaches the script through a symlink", () => {
|
|
217
|
+
const { root, file } = withSpaceFixture();
|
|
218
|
+
const link = path.join(root, "link.mjs");
|
|
219
|
+
try {
|
|
220
|
+
fs.symlinkSync(file, link);
|
|
221
|
+
// Node resolves `import.meta.url` to the realpath but leaves argv[1] as
|
|
222
|
+
// typed, so these two strings genuinely differ.
|
|
223
|
+
assert.notEqual(link, file);
|
|
224
|
+
assert.equal(isEntrypoint(pathToFileURL(file).href, link), true);
|
|
225
|
+
} finally {
|
|
226
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("is false for a different file, for no argv[1], and for a non-file URL", () => {
|
|
231
|
+
const self = fileURLToPath(import.meta.url);
|
|
232
|
+
assert.equal(
|
|
233
|
+
isEntrypoint(import.meta.url, path.join(path.dirname(self), "other.mjs")),
|
|
234
|
+
false,
|
|
235
|
+
);
|
|
236
|
+
assert.equal(isEntrypoint(import.meta.url, undefined), false);
|
|
237
|
+
assert.equal(isEntrypoint(import.meta.url, ""), false);
|
|
238
|
+
assert.equal(isEntrypoint("data:text/javascript,0", self), false);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it("runs the real CLI block when spawned through a symlinked path with a space", () => {
|
|
242
|
+
// End-to-end, because the unit cases above cannot catch the call site
|
|
243
|
+
// regressing back to a string comparison. The alias is a symlink to this
|
|
244
|
+
// package root whose name contains a space, so argv[1] differs from
|
|
245
|
+
// `import.meta.url` in BOTH ways at once; relative resolution inside the
|
|
246
|
+
// script still works because Node realpaths the module it loads.
|
|
247
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "rn-entry-guard-cli-"));
|
|
248
|
+
const alias = path.join(root, "react native with space");
|
|
249
|
+
fs.symlinkSync(path.resolve(here, "../.."), alias, "dir");
|
|
250
|
+
let result;
|
|
251
|
+
try {
|
|
252
|
+
result = spawnSync(
|
|
253
|
+
process.execPath,
|
|
254
|
+
[path.join(alias, "scripts", "measure-headless.mjs")],
|
|
255
|
+
{ encoding: "utf8" },
|
|
256
|
+
);
|
|
257
|
+
} finally {
|
|
258
|
+
// Unlink the symlink itself before removing the temp dir: never hand a
|
|
259
|
+
// recursive remove a link that points at the package root.
|
|
260
|
+
fs.unlinkSync(alias);
|
|
261
|
+
fs.rmdirSync(root);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const output = `${result.stdout}${result.stderr}`;
|
|
265
|
+
assert.notEqual(
|
|
266
|
+
output.trim(),
|
|
267
|
+
"",
|
|
268
|
+
"the CLI block printed nothing — the entry guard skipped the measurement",
|
|
269
|
+
);
|
|
270
|
+
// State-agnostic: a built package prints the gzip figure for the headless
|
|
271
|
+
// entry, an unbuilt one names dist/headless.mjs as missing. Either proves the
|
|
272
|
+
// main block ran.
|
|
273
|
+
assert.match(output, /headless/);
|
|
274
|
+
});
|
|
275
|
+
});
|