@copilotkit/react-native 1.84.2-canary.openbot-intel-fixes → 1.86.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.
Files changed (55) hide show
  1. package/README.md +341 -2
  2. package/USAGE.md +388 -21
  3. package/dist/{CopilotKitProvider-DBq4AhRP.d.cts → CopilotKitProvider-CQ-DpvY1.d.cts} +2 -2
  4. package/dist/{CopilotKitProvider-D8sn7G_C.mjs → CopilotKitProvider-CXQGv39c.mjs} +1 -1
  5. package/dist/{CopilotKitProvider-D8sn7G_C.mjs.map → CopilotKitProvider-CXQGv39c.mjs.map} +1 -1
  6. package/dist/{CopilotKitProvider-fW21Gb7T.d.mts → CopilotKitProvider-Dc1Vbv7K.d.mts} +1 -1
  7. package/dist/{CopilotKitProvider-CjoPnabW.cjs → CopilotKitProvider-zSfbWwIg.cjs} +1 -1
  8. package/dist/{CopilotKitProvider-CjoPnabW.cjs.map → CopilotKitProvider-zSfbWwIg.cjs.map} +1 -1
  9. package/dist/components/index.cjs +1 -0
  10. package/dist/components/index.cjs.map +1 -1
  11. package/dist/components/index.mjs +1 -0
  12. package/dist/components/index.mjs.map +1 -1
  13. package/dist/generative-ui/index.cjs +612 -0
  14. package/dist/generative-ui/index.cjs.map +1 -0
  15. package/dist/generative-ui/index.d.cts +341 -0
  16. package/dist/generative-ui/index.d.mts +341 -0
  17. package/dist/generative-ui/index.mjs +549 -0
  18. package/dist/generative-ui/index.mjs.map +1 -0
  19. package/dist/headless.cjs +1 -1
  20. package/dist/headless.d.cts +1 -1
  21. package/dist/headless.d.mts +1 -1
  22. package/dist/headless.mjs +1 -1
  23. package/dist/index.cjs +2 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +2 -2
  26. package/dist/index.d.mts +1 -1
  27. package/dist/index.mjs +2 -1
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/polyfills.cjs +218 -2
  30. package/dist/polyfills.cjs.map +1 -1
  31. package/dist/polyfills.mjs +217 -1
  32. package/dist/polyfills.mjs.map +1 -1
  33. package/package.json +13 -5
  34. package/project.json +6 -1
  35. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  36. package/scripts/verify-polyfill-barrel.mjs +154 -5
  37. package/src/__tests__/generative-ui-harness.tsx +243 -0
  38. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  39. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  40. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  41. package/src/__tests__/generative-ui.test.tsx +1000 -0
  42. package/src/__tests__/headless-entry-surface.test.ts +964 -34
  43. package/src/components/index.ts +6 -0
  44. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  45. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  46. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  47. package/src/generative-ui/host.tsx +138 -0
  48. package/src/generative-ui/index.ts +99 -0
  49. package/src/generative-ui/internal.ts +55 -0
  50. package/src/index.ts +8 -3
  51. package/tsdown.config.ts +1 -0
  52. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  53. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  54. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  55. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -1,16 +1,29 @@
1
- import { describe, it, expect, beforeAll } from "vitest";
1
+ import { describe, it, expect, beforeAll, vi } from "vitest";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ import { createRequire } from "node:module";
4
5
  // Type-only, so it is erased and does NOT statically pull the entry this file
5
6
  // deliberately loads at runtime (and is not part of the walked graph either —
6
- // the walk starts at src/headless.ts / src/index.ts, not at this test).
7
+ // the walks start at the package's published entries, ENTRIES and
8
+ // generativeUIEntry below, never at this test).
7
9
  import type * as HeadlessEntry from "../headless";
8
10
  // Same reason, and additionally: the identity assertion below needs the module
9
11
  // this entry re-exports FROM, to compare bindings rather than merely count them.
10
12
  import type * as CoreHeadlessEntry from "@copilotkit/react-core/v2/headless";
11
13
 
12
14
  /**
13
- * Guards the `@copilotkit/react-native/headless` entry (src/headless.ts).
15
+ * Guards the import graphs of the published entries of
16
+ * `@copilotkit/react-native`, with `/headless` (src/headless.ts) as the strict
17
+ * case. ENTRIES is derived from package.json `exports`, so the default barrel,
18
+ * `/components` and the polyfill subpaths are walked as well.
19
+ *
20
+ * The second `describe` covers the opt-in `/generative-ui` entry
21
+ * (src/generative-ui/index.ts): it may reach react-core only through `/v2/context`
22
+ * and the DOM-free `/v2/generative-ui/native`, it may reach the `zod` optional
23
+ * peer, it owns no registry, and no OTHER entry may reach it or any
24
+ * generative-UI subpath of a workspace package (that deny-list is derived from
25
+ * the packages' `exports` maps). The third `describe` checks react-core's built
26
+ * dist for a second copy of a generative UI context module.
14
27
  *
15
28
  * The whole point of the headless entry is that a consumer using only the
16
29
  * provider + agent/tool hooks does NOT have to install (or Metro-stub) the
@@ -26,7 +39,7 @@ import type * as CoreHeadlessEntry from "@copilotkit/react-core/v2/headless";
26
39
  *
27
40
  * ─── Why the walker looks the way it does ──────────────────────────────────
28
41
  * A guard that under-reports is worse than no guard, because it is trusted. The
29
- * first version of this file had four blind spots, each of which let a REAL
42
+ * first version of this file had five blind spots, each of which let a REAL
30
43
  * violation through (or flagged a non-violation), so the walker below is written
31
44
  * to close them and each is covered by a test:
32
45
  *
@@ -155,6 +168,91 @@ const FORBIDDEN_HEAVY = [
155
168
  "@copilotkit/runtime-client-gql",
156
169
  ];
157
170
 
171
+ /**
172
+ * Deliberate exceptions to FORBIDDEN_REGISTRY_APIS. Each one removes exactly
173
+ * the declaration it names from that one file before the scan, so a second
174
+ * context (or any other registry API) in the same file still trips the ban.
175
+ *
176
+ * `file` is POSIX-style relative to src/, and is compared after normalising
177
+ * `path.relative`'s separators (which are `\` on Windows).
178
+ *
179
+ * Every declaration must match exactly once in the file it names. One that no
180
+ * longer matches (the declaration was reformatted, renamed or removed, or the
181
+ * file moved) is reported as a STALE exemption, naming the exemption and its
182
+ * reason, rather than doing nothing and leaving the identifier ban to blame
183
+ * `createContext` for what is really an out-of-date exemption.
184
+ */
185
+ interface RegistryApiExemption {
186
+ file: string;
187
+ /** Each is replaced by its group 1 (what to keep), once. */
188
+ declarations: RegExp[];
189
+ reason: string;
190
+ }
191
+
192
+ const REGISTRY_API_EXEMPTIONS: readonly RegistryApiExemption[] = [
193
+ {
194
+ file: "generative-ui/GenerativeUIProvider.tsx",
195
+ declarations: [
196
+ /(import React, \{ )createContext, /,
197
+ /()export const GenerativeUIProviderPresentContext = createContext\(false\);/,
198
+ ],
199
+ reason:
200
+ "a boolean that tells the components below 'no provider' from 'a provider without ui'; it holds no tools or renderers",
201
+ },
202
+ ];
203
+
204
+ /** A path relative to src/, with `/` separators on every platform. */
205
+ const srcRelative = (file: string) =>
206
+ path.relative(srcDir, file).replace(/\\/g, "/");
207
+
208
+ /** How many times `re` matches `code`, ignoring its own `g` flag. */
209
+ const countMatches = (code: string, re: RegExp) =>
210
+ [...code.matchAll(new RegExp(re.source, re.flags.replace("g", "") + "g"))]
211
+ .length;
212
+
213
+ /**
214
+ * Every use of a FORBIDDEN_REGISTRY_APIS identifier in the given modules, as
215
+ * `file: identifier — why`, plus every stale exemption among the files given.
216
+ * Comments are stripped first: the modules name these APIs in prose to explain
217
+ * why they do NOT call them, and a raw text match would fail on the
218
+ * documentation.
219
+ */
220
+ function registryOffenders(
221
+ files: Iterable<string>,
222
+ exemptions: readonly RegistryApiExemption[] = REGISTRY_API_EXEMPTIONS,
223
+ ): string[] {
224
+ const offenders: string[] = [];
225
+ for (const file of files) {
226
+ const here = srcRelative(file);
227
+ let code = stripComments(fs.readFileSync(file, "utf8"));
228
+ const applied = exemptions.filter((e) => e.file === here);
229
+ for (const exemption of applied) {
230
+ for (const declaration of exemption.declarations) {
231
+ const matches = countMatches(code, declaration);
232
+ if (matches !== 1) {
233
+ offenders.push(
234
+ `${here}: stale exemption — ${declaration} matched ${matches} ` +
235
+ `time(s), not once. Update or remove the exemption for ` +
236
+ `"${exemption.reason}"`,
237
+ );
238
+ }
239
+ code = code.replace(declaration, "$1");
240
+ }
241
+ }
242
+ for (const [identifier, why] of FORBIDDEN_REGISTRY_APIS) {
243
+ if (new RegExp(`\\b${identifier}\\b`).test(code)) {
244
+ const exempted = applied.length
245
+ ? ` (this file's exemption, "${applied
246
+ .map((e) => e.reason)
247
+ .join("; ")}", does not cover this use)`
248
+ : "";
249
+ offenders.push(`${here}: ${identifier} — ${why}${exempted}`);
250
+ }
251
+ }
252
+ }
253
+ return offenders;
254
+ }
255
+
158
256
  const indexEntry = path.join(srcDir, "index.ts");
159
257
  const pkgJsonPath = path.resolve(srcDir, "..", "package.json");
160
258
 
@@ -187,9 +285,22 @@ interface PkgManifest {
187
285
  * allow-list, and it is READ from package.json rather than hand-copied so it
188
286
  * cannot drift from the manifest it is meant to describe. Anything else in the
189
287
  * graph is a package the consumer may not have: every optional peer
190
- * (`@gorhom/bottom-sheet`, `expo-*`, `react-native-streamdown`, `zod`), any
191
- * brand-new third-party edge, and any Node builtin (which RN has no business
192
- * reaching). This package's OWN name is deliberately absent, which is what keeps
288
+ * (`@gorhom/bottom-sheet`, `expo-document-picker`, `expo-file-system`,
289
+ * `react-native-gesture-handler`, `react-native-reanimated`,
290
+ * `react-native-streamdown`, `zod`), any brand-new third-party edge, and any
291
+ * Node builtin (which RN has no business reaching).
292
+ *
293
+ * The walk covers this package's OWN sources only, so this set bounds what
294
+ * THEY import, not what the consumer must install in total. `zod` is the case
295
+ * in point: it is an optional peer here, and no module of this package imports
296
+ * it, yet every entry needs it at runtime — react-core's `/v2/headless`, which
297
+ * both entries import, loads `zod` on import, and react-core declares it as a
298
+ * REQUIRED peer (`>=3.25`). It stays an optional peer at `>=3.0.0` here only
299
+ * because making a peer required, or narrowing its range, is a breaking change
300
+ * under scripts/release/lib/breaking-change-gate.ts; react-core's own peer is
301
+ * what makes the consumer install it, at `>=3.25`.
302
+ *
303
+ * This package's OWN name is deliberately absent, which is what keeps
193
304
  * this test doubling as the comment-stripping regression: the eight phantom
194
305
  * `@copilotkit/react-native…` specifiers that JSDoc examples used to harvest are
195
306
  * all self-references, so if `stripComments` regresses they fail here.
@@ -225,6 +336,14 @@ function packageNameOf(spec: string): string {
225
336
  return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!;
226
337
  }
227
338
 
339
+ /**
340
+ * `@copilotkit/react-core` or one of its subpaths — by package name, not by
341
+ * prefix, so a sibling package such as `@copilotkit/react-core-foo` is not
342
+ * mistaken for an entry of react-core.
343
+ */
344
+ const isReactCoreSpec = (spec: string) =>
345
+ packageNameOf(spec) === "@copilotkit/react-core";
346
+
228
347
  /**
229
348
  * Comment / string / template alternation, scanned left-to-right in ONE pass.
230
349
  *
@@ -397,12 +516,137 @@ function graphFor(entry: string): Graph {
397
516
  const rel = (files: Iterable<string>) =>
398
517
  [...files].map((f) => path.relative(srcDir, f)).sort();
399
518
 
400
- const ENTRIES: [label: string, entry: string][] = [
401
- ["headless", headlessEntry],
402
- ["default barrel", indexEntry],
519
+ interface ExportingManifest extends PkgManifest {
520
+ name?: string;
521
+ exports?: unknown;
522
+ }
523
+
524
+ const readManifest = (file: string) =>
525
+ JSON.parse(fs.readFileSync(file, "utf8")) as ExportingManifest;
526
+
527
+ /**
528
+ * The file an export resolves to for `import` (else `require`, else
529
+ * `default`), following nested condition objects; null for anything else.
530
+ */
531
+ function exportTarget(value: unknown): string | null {
532
+ if (typeof value === "string") return value;
533
+ if (value && typeof value === "object") {
534
+ for (const condition of ["import", "require", "default"]) {
535
+ const target = exportTarget(
536
+ (value as Record<string, unknown>)[condition],
537
+ );
538
+ if (target) return target;
539
+ }
540
+ }
541
+ return null;
542
+ }
543
+
544
+ /** `./dist/a/b.mjs` -> the `src/a/b.ts(x)` tsdown built it from, if any. */
545
+ function sourceOfDistTarget(target: string): string | null {
546
+ const m = /^\.\/dist\/(.+)\.(?:mjs|cjs|js)$/.exec(target);
547
+ if (!m) return null;
548
+ const base = path.join(srcDir, ...m[1]!.split("/"));
549
+ return [`${base}.ts`, `${base}.tsx`].find((c) => fs.existsSync(c)) ?? null;
550
+ }
551
+
552
+ /** An export subpath, or bare specifier, with a `generative-ui` segment. */
553
+ const hasGenerativeUISegment = (subpath: string) =>
554
+ subpath.split("/").includes("generative-ui");
555
+
556
+ /** Export keys of this package that carry no module to walk, and why. */
557
+ const NON_CODE_EXPORTS: Record<string, string> = {
558
+ "./package.json": "the manifest itself",
559
+ };
560
+
561
+ /**
562
+ * The entries to walk, DERIVED from this package's `exports` map rather than
563
+ * typed in: a hand-written list missed the published `/components` entry, so
564
+ * none of the per-entry bans below applied to it. Every code export lands in
565
+ * exactly one place — `entries` (all the bans below), or `generativeUI` (the
566
+ * opt-in entry, walked by its own `describe`) — and anything that cannot be
567
+ * mapped back to a source module is a `problem`, which a test fails on.
568
+ *
569
+ * Runs at collection time, so it must not throw (blind spot #4 above):
570
+ * failures are collected, not raised.
571
+ */
572
+ function deriveEntries(): {
573
+ entries: [label: string, entry: string][];
574
+ generativeUI: string[];
575
+ problems: string[];
576
+ } {
577
+ const entries: [string, string][] = [];
578
+ const generativeUI: string[] = [];
579
+ const problems: string[] = [];
580
+ try {
581
+ const exportsMap = readManifest(pkgJsonPath).exports;
582
+ if (!exportsMap || typeof exportsMap !== "object") {
583
+ return { entries, generativeUI, problems: ["no `exports` map"] };
584
+ }
585
+ for (const [key, value] of Object.entries(exportsMap)) {
586
+ if (key in NON_CODE_EXPORTS) continue;
587
+ const target = exportTarget(value);
588
+ const source = target ? sourceOfDistTarget(target) : null;
589
+ if (!source) {
590
+ problems.push(
591
+ `${key} -> ${target ?? JSON.stringify(value)}: no src/ module found ` +
592
+ `for it. Teach sourceOfDistTarget the new layout, or add the key ` +
593
+ `to NON_CODE_EXPORTS with a reason.`,
594
+ );
595
+ } else if (hasGenerativeUISegment(key)) {
596
+ generativeUI.push(source);
597
+ } else {
598
+ entries.push([`@copilotkit/react-native${key.slice(1)}`, source]);
599
+ }
600
+ }
601
+ } catch (err) {
602
+ problems.push(`could not read the exports of ${pkgJsonPath}: ${err}`);
603
+ }
604
+ return { entries, generativeUI, problems };
605
+ }
606
+
607
+ const DERIVED_ENTRIES = deriveEntries();
608
+
609
+ // Never empty at collection, so the it.each tables below always register: if
610
+ // the derivation broke, they fall back to the two entries this guard was first
611
+ // written for, and the derivation test reports why.
612
+ const ENTRIES: [label: string, entry: string][] = DERIVED_ENTRIES.entries.length
613
+ ? DERIVED_ENTRIES.entries
614
+ : [
615
+ ["@copilotkit/react-native/headless", headlessEntry],
616
+ ["@copilotkit/react-native", indexEntry],
617
+ ];
618
+
619
+ /** Entries the derivation must find. A floor, not the list. */
620
+ const REQUIRED_ENTRIES = [
621
+ headlessEntry,
622
+ indexEntry,
623
+ path.join(srcDir, "components", "index.ts"),
403
624
  ];
404
625
 
405
626
  describe("@copilotkit/react-native/headless entry", () => {
627
+ it("walks every code export of package.json", () => {
628
+ expect(
629
+ DERIVED_ENTRIES.problems,
630
+ `package.json exports that this guard cannot map to an entry module:\n ` +
631
+ DERIVED_ENTRIES.problems.join("\n "),
632
+ ).toEqual([]);
633
+ const walked = ENTRIES.map(([, entry]) => entry);
634
+ const missing = REQUIRED_ENTRIES.filter((e) => !walked.includes(e));
635
+ expect(
636
+ missing,
637
+ `the entries derived from package.json exports do not include ` +
638
+ `${rel(missing).join(", ")} — the derivation is broken. Derived: ` +
639
+ `${rel(walked).join(", ")}`,
640
+ ).toEqual([]);
641
+ // The opt-in entry is walked by its own describe below, against the path
642
+ // it hard-codes; make sure that path is the one package.json publishes.
643
+ expect(
644
+ DERIVED_ENTRIES.generativeUI,
645
+ "package.json's generative-ui export(s) do not resolve to the entry the " +
646
+ "generative UI describe walks",
647
+ ).toEqual([path.join(srcDir, "generative-ui", "index.ts")]);
648
+ });
649
+
406
650
  // Runs for real now: nothing walks the graph before collection finishes, so a
407
651
  // missing entry file reports HERE instead of erroring the whole suite out.
408
652
  it.each(ENTRIES)("has a %s entry file", (_label, entry) => {
@@ -515,20 +759,7 @@ describe("@copilotkit/react-native/headless entry", () => {
515
759
  const { seen } = graphFor(headlessEntry);
516
760
  // Non-vacuity comes from REQUIRED_HEADLESS_MODULES above (a truncated walk
517
761
  // fails there first), so this only has to be a deny-list.
518
- const offenders: string[] = [];
519
- for (const file of seen) {
520
- // Comments stripped: this file's own graph is heavily documented and the
521
- // modules in it name these APIs in prose to explain why they do NOT call
522
- // them. A raw text match would fail on the documentation.
523
- const code = stripComments(fs.readFileSync(file, "utf8"));
524
- for (const [identifier, why] of FORBIDDEN_REGISTRY_APIS) {
525
- if (new RegExp(`\\b${identifier}\\b`).test(code)) {
526
- offenders.push(
527
- `${path.relative(srcDir, file)}: ${identifier} — ${why}`,
528
- );
529
- }
530
- }
531
- }
762
+ const offenders = registryOffenders(seen);
532
763
  expect(
533
764
  offenders,
534
765
  `module(s) in the headless graph touch registry internals directly:\n ` +
@@ -539,11 +770,11 @@ describe("@copilotkit/react-native/headless entry", () => {
539
770
  });
540
771
 
541
772
  /**
542
- * The four checks below need the entry EVALUATED, not just read: they assert
773
+ * The six checks below need the entry EVALUATED, not just read: they assert
543
774
  * that the named exports exist as runtime values (a re-export of a name that
544
775
  * no longer exists is a runtime hole a static read cannot see). So the import
545
776
  * stays — but it is paid exactly once, in a hook, rather than being raced by
546
- * four tests against the default per-test budget.
777
+ * six tests against the default per-test budget.
547
778
  *
548
779
  * Why the budget below is what it is. Nothing here is hung or polling — the
549
780
  * cost is a ONE-TIME module-graph load (resolve + transform + evaluate), paid
@@ -554,10 +785,11 @@ describe("@copilotkit/react-native/headless entry", () => {
554
785
  * workspace dists this entry pulls are transformed rather than loaded
555
786
  * natively: ~283 KB (core ~218 KB, react-core v2/headless ~55 KB, plus
556
787
  * v2/context and shared), on top of the 11 RN source modules.
557
- * - Measured on one dev machine: ~0.9–1.8s inside the full 22-file suite
558
- * (n=8), ~0.7–1.1s for this file alone (n=8) — but 4568ms on the run
559
- * straight after a cold `nx build`, i.e. 91% of the 5s budget, and the
560
- * 4 independent agents who hit this hit it as an outright timeout. Bare
788
+ * - Measured on one dev machine: ~0.9–1.8s inside the full suite as it
789
+ * was then (22 test files; there are more now) (n=8), ~0.7–1.1s for
790
+ * this file alone (n=8) — but 4568ms on the run straight after a cold
791
+ * `nx build`, i.e. 91% of the 5s budget, and the 4 independent
792
+ * agents who hit this hit it as an outright timeout. Bare
561
793
  * Node `import()` of the equivalent prebuilt dist is 461ms, so the spread
562
794
  * is resolve/transform and page-cache-cold I/O, both load-sensitive.
563
795
  *
@@ -566,7 +798,7 @@ describe("@copilotkit/react-native/headless entry", () => {
566
798
  * ~0ms. A genuinely hung import still fails, just not spuriously. Lowering it
567
799
  * re-introduces the flake; lowering the COST would mean not inlining
568
800
  * `@copilotkit/core` for this suite, which is a shared-config change affecting
569
- * all 22 test files rather than something this file can do.
801
+ * every test file in this package rather than something this file can do.
570
802
  */
571
803
  const IMPORT_BUDGET_MS = 60_000;
572
804
 
@@ -720,9 +952,7 @@ describe("@copilotkit/react-native/headless entry", () => {
720
952
  (_label, entry) => {
721
953
  const { bareSpecs } = graphFor(entry);
722
954
  const offenders = [...bareSpecs].filter(
723
- (s) =>
724
- s.startsWith("@copilotkit/react-core") &&
725
- !ALLOWED_REACT_CORE_ENTRIES.includes(s),
955
+ (s) => isReactCoreSpec(s) && !ALLOWED_REACT_CORE_ENTRIES.includes(s),
726
956
  );
727
957
  expect(
728
958
  offenders,
@@ -743,3 +973,703 @@ describe("@copilotkit/react-native/headless entry", () => {
743
973
  },
744
974
  );
745
975
  });
976
+
977
+ // ─── @copilotkit/react-native/generative-ui ─────────────────────────────────
978
+ // The generative UI entry is opt-in. It may use react-core's DOM-free generative
979
+ // UI entry, and nothing else of react-core but the shared context; and no other
980
+ // entry may reach it, so a consumer that does not use generative UI never
981
+ // bundles the surface engine or the catalog schemas of @copilotkit/shared.
982
+ // (zod is in the bundle of every entry regardless, but for different reasons:
983
+ // the headless and default entries load it through react-core's /v2/headless,
984
+ // and this entry through react-core's /v2/generative-ui/native, whose chat
985
+ // chunk imports it.)
986
+ const generativeUIEntry = path.join(srcDir, "generative-ui", "index.ts");
987
+ const GENERATIVE_UI_REACT_CORE_ENTRIES = [
988
+ "@copilotkit/react-core/v2/context",
989
+ "@copilotkit/react-core/v2/generative-ui/native",
990
+ ];
991
+ const REQUIRED_GENERATIVE_UI_MODULES = [
992
+ path.join("generative-ui", "index.ts"),
993
+ path.join("generative-ui", "GenerativeUIProvider.tsx"),
994
+ path.join("generative-ui", "GenerativeUIActivity.tsx"),
995
+ path.join("generative-ui", "GenerativeUISurface.tsx"),
996
+ path.join("generative-ui", "host.tsx"),
997
+ ];
998
+
999
+ /**
1000
+ * Bare specifiers the generative UI graph MUST harvest. The same non-vacuity
1001
+ * floor as REQUIRED_HEADLESS_BARE: the react-core allow-list and the heavy/DOM
1002
+ * deny-lists below are all filters over `bareSpecs`, and every one of them
1003
+ * passes on an empty set. These two are the edges the entry exists for — the
1004
+ * catalog engine, and the host elements it renders into — so a walk that stops
1005
+ * harvesting them is a walk that is no longer checking anything.
1006
+ */
1007
+ const REQUIRED_GENERATIVE_UI_BARE = [
1008
+ "@copilotkit/react-core/v2/generative-ui/native",
1009
+ "react-native",
1010
+ ];
1011
+
1012
+ /**
1013
+ * Optional peers the generative UI entry is DELIBERATELY allowed to reach, on
1014
+ * top of guaranteedPackages().
1015
+ *
1016
+ * `zod` only. It is optional in package.json, but every consumer has it
1017
+ * already, because react-core declares it as a REQUIRED peer (`>=3.25`; see
1018
+ * guaranteedPackages). That peer is what this entry relies on: react-core's
1019
+ * `/v2/generative-ui/native`, which this entry imports, loads zod (its chat
1020
+ * chunk does `import { z } from "zod"`). `@copilotkit/core` and
1021
+ * `@copilotkit/shared` list zod in their own `dependencies`, so the copy they
1022
+ * load is theirs and says nothing about the consumer's install. So an edge to
1023
+ * zod from this graph asks the consumer for nothing they do not have. No RN
1024
+ * source module imports zod directly today (the walk stops at this package's
1025
+ * boundary), so this is a standing allowance, not a description of the
1026
+ * current graph.
1027
+ *
1028
+ * Every OTHER optional peer stays unsanctioned: the chat/attachment natives
1029
+ * (`@gorhom/bottom-sheet`, `expo-document-picker`, `expo-file-system`,
1030
+ * `react-native-streamdown`) and the gesture/animation peers
1031
+ * (`react-native-gesture-handler`, `react-native-reanimated`) are things a
1032
+ * generative-UI-only consumer has not been told to install. Extend this list
1033
+ * only with a reason, like zod's.
1034
+ */
1035
+ const GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS = ["zod"];
1036
+
1037
+ /**
1038
+ * Bare specifiers that ARE generative UI, matched exactly or as a subpath
1039
+ * prefix (never by substring, so an unrelated package whose name merely
1040
+ * contains "generative-ui" neither trips nor hides behind the check).
1041
+ *
1042
+ * DERIVED from the `exports` maps of every workspace package (and of every
1043
+ * `@copilotkit/*` dependency of this package, wherever it resolves): each
1044
+ * export subpath with a `generative-ui` segment. The hand-written list it
1045
+ * replaces missed `@copilotkit/shared/generative-ui` — the catalog schemas —
1046
+ * so the headless and default entries could have imported them unnoticed.
1047
+ *
1048
+ * GENERATIVE_UI_BARE_FLOOR is not the list. It is what the derivation must at
1049
+ * least find, so a derivation that silently finds nothing fails a test instead
1050
+ * of turning the ban off; and it is unioned in, so the ban holds meanwhile.
1051
+ */
1052
+ const matchesBare = (spec: string, dep: string) =>
1053
+ spec === dep || spec.startsWith(`${dep}/`);
1054
+
1055
+ const GENERATIVE_UI_BARE_FLOOR = [
1056
+ "@copilotkit/react-native/generative-ui",
1057
+ "@copilotkit/react-core/v2/generative-ui",
1058
+ "@copilotkit/core/generative-ui",
1059
+ "@copilotkit/shared/generative-ui",
1060
+ ];
1061
+
1062
+ const workspacePackagesDir = path.resolve(srcDir, "..", "..");
1063
+
1064
+ /**
1065
+ * name -> `exports` of every package the derivation reads. Collection-time
1066
+ * and must not throw (blind spot #4): failures are collected as problems.
1067
+ */
1068
+ function scanExportsMaps(): {
1069
+ manifests: Map<string, unknown>;
1070
+ problems: string[];
1071
+ } {
1072
+ const manifests = new Map<string, unknown>();
1073
+ const problems: string[] = [];
1074
+ const add = (file: string) => {
1075
+ try {
1076
+ const pkg = readManifest(file);
1077
+ if (pkg.name && !manifests.has(pkg.name))
1078
+ manifests.set(pkg.name, pkg.exports);
1079
+ } catch (err) {
1080
+ problems.push(`could not read ${file}: ${err}`);
1081
+ }
1082
+ };
1083
+ try {
1084
+ for (const dir of fs.readdirSync(workspacePackagesDir)) {
1085
+ const file = path.join(workspacePackagesDir, dir, "package.json");
1086
+ if (fs.existsSync(file)) add(file);
1087
+ }
1088
+ // Belt and braces for a dependency that is not (or no longer) a
1089
+ // workspace package: read the manifest the consumer would resolve.
1090
+ const own = readManifest(pkgJsonPath);
1091
+ const requireHere = createRequire(pkgJsonPath);
1092
+ for (const name of Object.keys({
1093
+ ...own.dependencies,
1094
+ ...own.peerDependencies,
1095
+ })) {
1096
+ if (!name.startsWith("@copilotkit/") || manifests.has(name)) continue;
1097
+ try {
1098
+ add(requireHere.resolve(`${name}/package.json`));
1099
+ } catch (err) {
1100
+ problems.push(`could not resolve ${name}/package.json: ${err}`);
1101
+ }
1102
+ }
1103
+ } catch (err) {
1104
+ problems.push(`could not scan ${workspacePackagesDir}: ${err}`);
1105
+ }
1106
+ return { manifests, problems };
1107
+ }
1108
+
1109
+ /** The derivation: every export subpath with a `generative-ui` segment. */
1110
+ function deriveGenerativeUIBare(manifests: Map<string, unknown>): string[] {
1111
+ const specs: string[] = [];
1112
+ for (const [name, exportsMap] of manifests) {
1113
+ if (!exportsMap || typeof exportsMap !== "object") continue;
1114
+ for (const key of Object.keys(exportsMap)) {
1115
+ if (hasGenerativeUISegment(key)) specs.push(`${name}${key.slice(1)}`);
1116
+ }
1117
+ }
1118
+ return specs.sort();
1119
+ }
1120
+
1121
+ /**
1122
+ * The cross-check, deliberately looser than the derivation: every export
1123
+ * whose subpath OR target mentions "generative-ui" at all (an export renamed
1124
+ * to `./genui` but still pointing at `dist/generative-ui/…`, or a
1125
+ * `./generative-ui-extras` subpath), that the derivation does not cover.
1126
+ */
1127
+ function uncoveredGenerativeUIExports(
1128
+ manifests: Map<string, unknown>,
1129
+ ): string[] {
1130
+ const derived = deriveGenerativeUIBare(manifests);
1131
+ const uncovered: string[] = [];
1132
+ for (const [name, exportsMap] of manifests) {
1133
+ if (!exportsMap || typeof exportsMap !== "object") continue;
1134
+ for (const [key, value] of Object.entries(exportsMap)) {
1135
+ const spec = `${name}${key.slice(1)}`;
1136
+ if (
1137
+ `${key} ${JSON.stringify(value)}`.includes("generative-ui") &&
1138
+ !derived.some((dep) => matchesBare(spec, dep))
1139
+ ) {
1140
+ uncovered.push(spec);
1141
+ }
1142
+ }
1143
+ }
1144
+ return uncovered.sort();
1145
+ }
1146
+
1147
+ const EXPORTS_SCAN = scanExportsMaps();
1148
+
1149
+ const GENERATIVE_UI_BARE = [
1150
+ ...new Set([
1151
+ ...deriveGenerativeUIBare(EXPORTS_SCAN.manifests),
1152
+ ...GENERATIVE_UI_BARE_FLOOR,
1153
+ ]),
1154
+ ].sort();
1155
+
1156
+ describe("@copilotkit/react-native/generative-ui entry", () => {
1157
+ it("has an entry file", () => {
1158
+ expect(
1159
+ fs.existsSync(generativeUIEntry),
1160
+ `missing entry file: ${generativeUIEntry}`,
1161
+ ).toBe(true);
1162
+ });
1163
+
1164
+ it("resolves every relative import and has no unanalyzable loader", () => {
1165
+ const { unresolved, opaque } = graphFor(generativeUIEntry);
1166
+ expect(
1167
+ unresolved,
1168
+ `unresolvable relative imports in the generative UI graph — the walker ` +
1169
+ `cannot see past these, so a forbidden import hidden behind one would ` +
1170
+ `read as clean: ${unresolved.join(", ")}`,
1171
+ ).toEqual([]);
1172
+ expect(
1173
+ opaque,
1174
+ `import()/require() with a non-literal specifier in the generative UI ` +
1175
+ `graph cannot be checked. Make it a literal: ${opaque.join(", ")}`,
1176
+ ).toEqual([]);
1177
+ });
1178
+
1179
+ // The non-vacuity floor for every deny-list in this block.
1180
+ it("reaches the modules and bare imports it must reach", () => {
1181
+ const { seen, bareSpecs } = graphFor(generativeUIEntry);
1182
+ const reached = rel(seen);
1183
+ const missing = REQUIRED_GENERATIVE_UI_MODULES.filter(
1184
+ (m) => !reached.includes(m),
1185
+ );
1186
+ expect(
1187
+ missing,
1188
+ `the walk did not reach ${missing.join(", ")} — the checks below are ` +
1189
+ `then reasoning about a truncated graph. Reached: ${reached.join(", ")}`,
1190
+ ).toEqual([]);
1191
+ const missingBare = REQUIRED_GENERATIVE_UI_BARE.filter(
1192
+ (s) => !bareSpecs.has(s),
1193
+ );
1194
+ expect(
1195
+ missingBare,
1196
+ `no edge to ${missingBare.join(", ")} was harvested from the generative ` +
1197
+ `UI graph — the allow- and deny-lists below would pass on an empty set. ` +
1198
+ `Harvested: ${[...bareSpecs].sort().join(", ")}`,
1199
+ ).toEqual([]);
1200
+ });
1201
+
1202
+ it("draws only on guaranteed packages, plus the optional peers it is allowed", () => {
1203
+ const { seen, bareSpecs } = graphFor(generativeUIEntry);
1204
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")) as PkgManifest;
1205
+ // An allowance for a package that is not even a declared optional peer is a
1206
+ // typo or a stale entry, and would quietly sanction nothing (or the wrong
1207
+ // thing); refuse it rather than trust it.
1208
+ const undeclared = GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS.filter(
1209
+ (name) =>
1210
+ !pkg.peerDependencies?.[name] ||
1211
+ !pkg.peerDependenciesMeta?.[name]?.optional,
1212
+ );
1213
+ expect(
1214
+ undeclared,
1215
+ `GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS names package(s) that are not ` +
1216
+ `optional peers in package.json: ${undeclared.join(", ")}`,
1217
+ ).toEqual([]);
1218
+ const allowed = new Set([
1219
+ ...guaranteedPackages(),
1220
+ ...GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS,
1221
+ ]);
1222
+ const unsanctioned = [...bareSpecs]
1223
+ .filter((spec) => !allowed.has(packageNameOf(spec)))
1224
+ .sort();
1225
+ expect(
1226
+ unsanctioned,
1227
+ `the generative UI graph reaches package(s) a consumer of this entry is ` +
1228
+ `not guaranteed or told to have installed: ${unsanctioned.join(", ")}. ` +
1229
+ `Make it a dependency or non-optional peer in package.json, add it to ` +
1230
+ `GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS with a reason, or drop the import. ` +
1231
+ `Graph: ${rel(seen).join(", ")}`,
1232
+ ).toEqual([]);
1233
+ });
1234
+
1235
+ it("imports only react-core's /v2/context and DOM-free /v2/generative-ui/native", () => {
1236
+ const { bareSpecs } = graphFor(generativeUIEntry);
1237
+ const offenders = [...bareSpecs].filter(
1238
+ (s) =>
1239
+ isReactCoreSpec(s) && !GENERATIVE_UI_REACT_CORE_ENTRIES.includes(s),
1240
+ );
1241
+ expect(
1242
+ offenders,
1243
+ `must import only ${GENERATIVE_UI_REACT_CORE_ENTRIES.join(" or ")} — ` +
1244
+ `found: ${offenders.join(", ")}. /v2/generative-ui carries the DOM ` +
1245
+ `standard catalog (react-dom portals, KaTeX, streamdown), and /v2 the ` +
1246
+ `chat render stack (#4893).`,
1247
+ ).toEqual([]);
1248
+ });
1249
+
1250
+ it("pulls in neither the heavy render stack, the DOM, nor the chat/attachment peers", () => {
1251
+ const { bareSpecs, seen } = graphFor(generativeUIEntry);
1252
+ const banned = [...FORBIDDEN_HEAVY, ...FORBIDDEN_BARE, "react-dom"];
1253
+ const leaked = banned.filter((dep) =>
1254
+ [...bareSpecs].some((s) => matchesBare(s, dep)),
1255
+ );
1256
+ expect(
1257
+ leaked,
1258
+ `generative UI graph must not import: ${leaked.join(", ")}`,
1259
+ ).toEqual([]);
1260
+ // Base-name SUBSTRING matching, as in the headless block: a directory that
1261
+ // merely contains a forbidden name does not trip this, and a chat module
1262
+ // moved to another directory does not escape it — but any file whose base
1263
+ // name contains one (a `useCopilotChatState.ts`, say) does trip it.
1264
+ const chatModules = [...seen].filter((f) =>
1265
+ FORBIDDEN_LOCAL.some((name) =>
1266
+ path
1267
+ .basename(f)
1268
+ .replace(/\.tsx?$/, "")
1269
+ .includes(name),
1270
+ ),
1271
+ );
1272
+ expect(
1273
+ chatModules,
1274
+ `generative UI graph must not reach the chat UI / useAttachments ` +
1275
+ `modules: ${rel(chatModules).join(", ")}`,
1276
+ ).toEqual([]);
1277
+ });
1278
+
1279
+ // The same ban as the headless block's. The generative UI provider registers
1280
+ // no tool (CopilotRuntime adds `render_ui` on the server), and the
1281
+ // `render_ui` renderer is written into CopilotKitCoreReact by react-core's
1282
+ // `GenerativeUIToolCallRenderer` (chat.tsx, via `setRenderToolCalls`), which
1283
+ // the provider mounts — in react-core, outside this walk. What this pins is
1284
+ // narrower: no RN module grows a registry (or a context to hold one) next to
1285
+ // CopilotKitCoreReact. Non-vacuity comes from REQUIRED_GENERATIVE_UI_MODULES.
1286
+ it("owns no tool/renderer registry of its own anywhere in the generative UI graph", () => {
1287
+ const { seen } = graphFor(generativeUIEntry);
1288
+ const offenders = registryOffenders(seen);
1289
+ expect(
1290
+ offenders,
1291
+ `module(s) in the generative UI graph touch registry internals ` +
1292
+ `directly:\n ${offenders.join("\n ")}\n` +
1293
+ `CopilotKitCoreReact is the single registry and this package must reach ` +
1294
+ `it only through react-core's hooks.`,
1295
+ ).toEqual([]);
1296
+ });
1297
+
1298
+ it("applies the registry exemption when path.relative uses Windows separators", () => {
1299
+ // `path.relative` returns `\\`-separated paths on Windows, which the
1300
+ // POSIX-style exemption path never equalled, so the exemption silently did
1301
+ // not apply there and this graph's legitimate context failed the ban.
1302
+ const { seen } = graphFor(generativeUIEntry);
1303
+ const posixRelative = path.relative;
1304
+ const spy = vi
1305
+ .spyOn(path, "relative")
1306
+ .mockImplementation((from, to) =>
1307
+ posixRelative(from, to).split("/").join("\\"),
1308
+ );
1309
+ try {
1310
+ expect(registryOffenders(seen)).toEqual([]);
1311
+ } finally {
1312
+ spy.mockRestore();
1313
+ }
1314
+ });
1315
+
1316
+ it("has no stale registry exemption", () => {
1317
+ // Inside registryOffenders, a declaration that no longer matches is
1318
+ // already reported — but only for a file the walk reaches. A file that
1319
+ // moved or left the graph would make its exemption dead without a word,
1320
+ // so check reachability here, against every graph this file walks.
1321
+ const walked = new Set([
1322
+ ...graphFor(generativeUIEntry).seen,
1323
+ ...ENTRIES.flatMap(([, entry]) => [...graphFor(entry).seen]),
1324
+ ]);
1325
+ const stale = REGISTRY_API_EXEMPTIONS.filter(
1326
+ (e) => ![...walked].some((f) => srcRelative(f) === e.file),
1327
+ ).map((e) => `${e.file} ("${e.reason}")`);
1328
+ expect(
1329
+ stale,
1330
+ `stale registry exemption(s): the file is not in any walked graph ` +
1331
+ `(moved, renamed or no longer imported). Update or remove: ` +
1332
+ stale.join(", "),
1333
+ ).toEqual([]);
1334
+ const exemptedFiles = [...walked].filter((f) =>
1335
+ REGISTRY_API_EXEMPTIONS.some((e) => e.file === srcRelative(f)),
1336
+ );
1337
+ // Every exempted file is scanned on its own, so a declaration that no
1338
+ // longer matches exactly once is named here as stale, whichever graph it
1339
+ // is in.
1340
+ expect(
1341
+ registryOffenders(exemptedFiles).filter((o) =>
1342
+ o.includes("stale exemption"),
1343
+ ),
1344
+ ).toEqual([]);
1345
+ });
1346
+
1347
+ it("reports an exemption that no longer matches as stale, naming its reason", () => {
1348
+ // Self-test of the mechanism above, against a deliberately stale copy of
1349
+ // the real exemption: the old code applied it as a silent no-op and then
1350
+ // blamed `createContext` for it.
1351
+ const file = path.join(srcDir, "generative-ui", "GenerativeUIProvider.tsx");
1352
+ const stale: RegistryApiExemption[] = REGISTRY_API_EXEMPTIONS.map((e) => ({
1353
+ ...e,
1354
+ declarations: [...e.declarations, /()createContext<boolean>\(false\);/],
1355
+ }));
1356
+ const offenders = registryOffenders([file], stale);
1357
+ expect(offenders).toHaveLength(1);
1358
+ expect(offenders[0]).toContain("stale exemption");
1359
+ expect(offenders[0]).toContain(REGISTRY_API_EXEMPTIONS[0]!.reason);
1360
+ });
1361
+
1362
+ it("derives the generative UI deny-list from every generative UI export", () => {
1363
+ expect(
1364
+ EXPORTS_SCAN.problems,
1365
+ `could not read every exports map the deny-list is derived from:\n ` +
1366
+ EXPORTS_SCAN.problems.join("\n "),
1367
+ ).toEqual([]);
1368
+ const derived = deriveGenerativeUIBare(EXPORTS_SCAN.manifests);
1369
+ const missingFloor = GENERATIVE_UI_BARE_FLOOR.filter(
1370
+ (s) => !derived.includes(s),
1371
+ );
1372
+ expect(
1373
+ missingFloor,
1374
+ `the exports-map derivation no longer finds ${missingFloor.join(", ")} — ` +
1375
+ `either the export was renamed or removed (update ` +
1376
+ `GENERATIVE_UI_BARE_FLOOR) or the derivation is broken. Derived: ` +
1377
+ derived.join(", "),
1378
+ ).toEqual([]);
1379
+ const uncovered = uncoveredGenerativeUIExports(EXPORTS_SCAN.manifests);
1380
+ expect(
1381
+ uncovered,
1382
+ `export(s) that mention generative-ui but are not covered by the ` +
1383
+ `derived deny-list: ${uncovered.join(", ")}. Give the export a ` +
1384
+ `\`generative-ui\` path segment, or teach deriveGenerativeUIBare about ` +
1385
+ `it, so the other entries are kept from reaching it.`,
1386
+ ).toEqual([]);
1387
+ });
1388
+
1389
+ it("the cross-check catches a generative UI export the derivation misses", () => {
1390
+ const manifests = new Map<string, unknown>([
1391
+ [
1392
+ "@copilotkit/example",
1393
+ {
1394
+ "./generative-ui": "./dist/generative-ui.mjs",
1395
+ "./genui": { import: "./dist/generative-ui/extra.mjs" },
1396
+ "./generative-ui-extras": "./dist/extras.mjs",
1397
+ "./other": "./dist/other.mjs",
1398
+ },
1399
+ ],
1400
+ ]);
1401
+ expect(deriveGenerativeUIBare(manifests)).toEqual([
1402
+ "@copilotkit/example/generative-ui",
1403
+ ]);
1404
+ expect(uncoveredGenerativeUIExports(manifests)).toEqual([
1405
+ "@copilotkit/example/generative-ui-extras",
1406
+ "@copilotkit/example/genui",
1407
+ ]);
1408
+ });
1409
+
1410
+ it.each(ENTRIES)(
1411
+ "the %s entry does not reach generative UI",
1412
+ (_label, entry) => {
1413
+ const { seen, bareSpecs } = graphFor(entry);
1414
+ const modules = rel(seen).filter((f) =>
1415
+ f.startsWith(`generative-ui${path.sep}`),
1416
+ );
1417
+ expect(
1418
+ modules,
1419
+ `this entry reaches the opt-in generative UI modules: ` +
1420
+ `${modules.join(", ")}. A consumer who never imports ` +
1421
+ `@copilotkit/react-native/generative-ui must not bundle them.`,
1422
+ ).toEqual([]);
1423
+ const specs = [...bareSpecs]
1424
+ .filter((s) => GENERATIVE_UI_BARE.some((dep) => matchesBare(s, dep)))
1425
+ .sort();
1426
+ expect(
1427
+ specs,
1428
+ `this entry imports generative UI: ${specs.join(", ")}. The surface ` +
1429
+ `engine and its catalog schemas belong only behind the opt-in ` +
1430
+ `@copilotkit/react-native/generative-ui entry.`,
1431
+ ).toEqual([]);
1432
+ },
1433
+ );
1434
+ });
1435
+
1436
+ // ─── react-core dist: one copy of each generative UI context ────────────────
1437
+ // The RN generative UI entry works only if the context its provider SETS and
1438
+ // the context its surfaces READ are the same object. GenerativeUIProvider puts
1439
+ // the runtime into react-core's `GenerativeUIRuntimeContext` and the host into
1440
+ // `GenerativeUIHostContext`, both imported from `/v2/generative-ui/native`;
1441
+ // react-core's own hooks and SurfaceView read them from whatever chunk they
1442
+ // were bundled into. react-core's tsdown config keeps `/v2/generative-ui/native`
1443
+ // in the main build precisely so that every entry shares ONE chunk carrying
1444
+ // these modules. If a config change inlined a second copy (native moved to its
1445
+ // own build, a chunking option), every typecheck and source-level test would
1446
+ // stay green — vitest and tsc see one source module — and a surface would
1447
+ // silently never see its runtime. react-core's context-singleton-preflight only
1448
+ // covers src/v2/context.ts, so this checks the generative UI context modules in
1449
+ // the BUILT dist, by the `//#region <src path>` banner tsdown writes for every
1450
+ // inlined module (the same marker that preflight relies on).
1451
+ const reactCoreDir = (() => {
1452
+ try {
1453
+ return path.dirname(
1454
+ createRequire(pkgJsonPath).resolve("@copilotkit/react-core/package.json"),
1455
+ );
1456
+ } catch {
1457
+ return path.join(workspacePackagesDir, "react-core");
1458
+ }
1459
+ })();
1460
+
1461
+ /** Context modules that MUST be bundled exactly once per format. A floor. */
1462
+ const REQUIRED_SINGLE_CONTEXT_MODULES = [
1463
+ "src/v2/generative-ui/runtime-context.ts",
1464
+ "src/v2/generative-ui/host.tsx",
1465
+ ];
1466
+
1467
+ /** Every file under `dir` (recursively) whose name matches `re`. */
1468
+ function filesUnder(dir: string, re: RegExp): string[] {
1469
+ const out: string[] = [];
1470
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1471
+ const full = path.join(dir, entry.name);
1472
+ if (entry.isDirectory()) {
1473
+ if (entry.name !== "__tests__") out.push(...filesUnder(full, re));
1474
+ } else if (re.test(entry.name)) {
1475
+ out.push(full);
1476
+ }
1477
+ }
1478
+ return out;
1479
+ }
1480
+
1481
+ describe("@copilotkit/react-core dist: one copy of each generative UI context", () => {
1482
+ it("bundles every generative UI context module at most once per format", () => {
1483
+ const distDir = path.join(reactCoreDir, "dist");
1484
+ expect(
1485
+ fs.existsSync(distDir),
1486
+ `${distDir} does not exist — build @copilotkit/react-core first`,
1487
+ ).toBe(true);
1488
+ // Derived from source: every generative UI module that calls
1489
+ // createContext, so a new context module is covered without listing it.
1490
+ const contextModules = filesUnder(
1491
+ path.join(reactCoreDir, "src", "v2", "generative-ui"),
1492
+ /\.tsx?$/,
1493
+ )
1494
+ .filter((f) =>
1495
+ /\bcreateContext\s*[<(]/.test(
1496
+ stripComments(fs.readFileSync(f, "utf8")),
1497
+ ),
1498
+ )
1499
+ .map((f) => path.relative(reactCoreDir, f).split(path.sep).join("/"))
1500
+ .sort();
1501
+ const missingFloor = REQUIRED_SINGLE_CONTEXT_MODULES.filter(
1502
+ (m) => !contextModules.includes(m),
1503
+ );
1504
+ expect(
1505
+ missingFloor,
1506
+ `no createContext found in ${missingFloor.join(", ")} — the source scan ` +
1507
+ `is broken or the module moved; update REQUIRED_SINGLE_CONTEXT_MODULES`,
1508
+ ).toEqual([]);
1509
+
1510
+ // UMD bundles are self-contained by design (as in react-core's own
1511
+ // preflight), so only the ESM and CJS module graphs are checked.
1512
+ const bundles = filesUnder(distDir, /\.(?:mjs|cjs)$/).map((f) => ({
1513
+ file: path.relative(distDir, f).split(path.sep).join("/"),
1514
+ code: fs.readFileSync(f, "utf8"),
1515
+ }));
1516
+ const problems: string[] = [];
1517
+ for (const contextModule of contextModules) {
1518
+ const marker = `//#region ${contextModule}\n`;
1519
+ for (const format of ["mjs", "cjs"]) {
1520
+ const carriers = bundles
1521
+ .filter(
1522
+ (b) => b.file.endsWith(`.${format}`) && b.code.includes(marker),
1523
+ )
1524
+ .map((b) => b.file);
1525
+ const required =
1526
+ REQUIRED_SINGLE_CONTEXT_MODULES.includes(contextModule);
1527
+ if (carriers.length > 1 || (required && carriers.length !== 1)) {
1528
+ problems.push(
1529
+ `${contextModule} is in ${carriers.length} .${format} file(s)` +
1530
+ (carriers.length ? `: ${carriers.join(", ")}` : "") +
1531
+ (required && !carriers.length
1532
+ ? " (expected exactly 1 — or tsdown's region banner changed, " +
1533
+ "and this check can no longer see duplicates)"
1534
+ : ""),
1535
+ );
1536
+ }
1537
+ }
1538
+ }
1539
+ expect(
1540
+ problems,
1541
+ `a generative UI context module is bundled more than once in ` +
1542
+ `@copilotkit/react-core's dist, so a provider and the components ` +
1543
+ `below it can hold different context objects:\n ` +
1544
+ problems.join("\n "),
1545
+ ).toEqual([]);
1546
+ });
1547
+ });
1548
+
1549
+ /**
1550
+ * The first module a source file loads at runtime, in source order: type-only
1551
+ * imports and re-exports are erased, so they are skipped. Null if it loads none.
1552
+ */
1553
+ function firstRuntimeSpecifier(code: string): string | null {
1554
+ const stripped = stripComments(code);
1555
+ const patterns = [
1556
+ /\b(import)\s+(type\s+)?[^;"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,
1557
+ /\b(import)\s*()["'`]([^"'`]+)["'`]/g,
1558
+ /\b(export)\s+(type\s+)?[^;"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,
1559
+ ];
1560
+ let first: { index: number; spec: string } | null = null;
1561
+ for (const re of patterns) {
1562
+ for (const m of stripped.matchAll(re)) {
1563
+ if (m[2]) continue;
1564
+ if (!first || m.index! < first.index) {
1565
+ first = { index: m.index!, spec: m[3]! };
1566
+ }
1567
+ }
1568
+ }
1569
+ return first?.spec ?? null;
1570
+ }
1571
+
1572
+ /** `src/polyfills.ts` and the five modules under `src/polyfills/`. */
1573
+ const polyfillsBarrel = path.join(srcDir, "polyfills.ts");
1574
+ const isPolyfillModule = (file: string) =>
1575
+ file === polyfillsBarrel ||
1576
+ path.dirname(file) === path.join(srcDir, "polyfills");
1577
+
1578
+ /**
1579
+ * Every published entry that loads CopilotKit code. The polyfill subpaths are
1580
+ * the polyfills themselves; everything else reaches @copilotkit/core or
1581
+ * @ag-ui/client, which need ReadableStream / TextEncoder / crypto at load time
1582
+ * on Hermes.
1583
+ */
1584
+ const CODE_ENTRIES: [label: string, entry: string][] = [
1585
+ ...ENTRIES.filter(([, entry]) => !isPolyfillModule(entry)),
1586
+ ...DERIVED_ENTRIES.generativeUI.map(
1587
+ (entry) =>
1588
+ ["@copilotkit/react-native/generative-ui", entry] as [string, string],
1589
+ ),
1590
+ ];
1591
+
1592
+ /**
1593
+ * A glob from package.json `sideEffects` -> a RegExp over `./`-relative paths.
1594
+ * Only the two wildcards this package uses: `**` (any depth) and `*`.
1595
+ */
1596
+ const regexLiteral = (part: string) =>
1597
+ part.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
1598
+
1599
+ function sideEffectsGlob(glob: string): RegExp {
1600
+ const body = glob
1601
+ .split("**/")
1602
+ .map((seg) =>
1603
+ seg
1604
+ .split("**")
1605
+ .map((part) => part.split("*").map(regexLiteral).join("[^/]*"))
1606
+ .join(".*"),
1607
+ )
1608
+ .join("(?:.*/)?");
1609
+ return new RegExp(`^${body}$`);
1610
+ }
1611
+
1612
+ describe("every published entry installs the polyfills before CopilotKit loads", () => {
1613
+ it("covers the root, /headless and /generative-ui entries at least", () => {
1614
+ const walked = CODE_ENTRIES.map(([, entry]) => entry);
1615
+ const floor = [
1616
+ indexEntry,
1617
+ headlessEntry,
1618
+ path.join(srcDir, "generative-ui", "index.ts"),
1619
+ ];
1620
+ expect(
1621
+ floor.filter((e) => !walked.includes(e)),
1622
+ `entries missing from the polyfill-order check; derived: ${rel(walked).join(", ")}`,
1623
+ ).toEqual([]);
1624
+ });
1625
+
1626
+ // An app that imports this entry BEFORE any other @copilotkit/react-native
1627
+ // entry must still get the polyfills first: on Hermes, @copilotkit/core and
1628
+ // @ag-ui/client fail at load time without them, with a ReferenceError that
1629
+ // says nothing about import order. Being imported first in the file is what
1630
+ // makes the bundler emit it as the built entry's first statement, which
1631
+ // scripts/verify-polyfill-barrel.mjs then checks in dist/.
1632
+ it.each(CODE_ENTRIES)(
1633
+ "%s imports ./polyfills as its first runtime import",
1634
+ (_label, entry) => {
1635
+ const first = firstRuntimeSpecifier(fs.readFileSync(entry, "utf8"));
1636
+ expect(
1637
+ first ? resolveLocal(entry, first) : null,
1638
+ `${srcRelative(entry)} must start with \`import "${path
1639
+ .relative(path.dirname(entry), polyfillsBarrel)
1640
+ .replace(/\\/g, "/")
1641
+ .replace(/\.ts$/, "")
1642
+ .replace(/^(?!\.)/, "./")}";\` — its first runtime import is ` +
1643
+ `${JSON.stringify(first)}`,
1644
+ ).toBe(polyfillsBarrel);
1645
+ },
1646
+ );
1647
+
1648
+ // A `sideEffects` list that misses an entry tells the consumer's bundler the
1649
+ // bare `import "./polyfills"` in it can be dropped.
1650
+ it.each(CODE_ENTRIES)(
1651
+ "%s is declared in package.json sideEffects, as source and as build output",
1652
+ (label, entry) => {
1653
+ const manifest = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")) as {
1654
+ sideEffects?: unknown;
1655
+ exports?: Record<string, unknown>;
1656
+ };
1657
+ const globs = Array.isArray(manifest.sideEffects)
1658
+ ? manifest.sideEffects.map((g) => sideEffectsGlob(String(g)))
1659
+ : [];
1660
+ const key = `.${label.slice("@copilotkit/react-native".length)}`;
1661
+ const exported = manifest.exports?.[key] as
1662
+ | Record<string, string>
1663
+ | undefined;
1664
+ const files = [
1665
+ `./${path.relative(path.dirname(pkgJsonPath), entry).replace(/\\/g, "/")}`,
1666
+ ...Object.values(exported ?? {}),
1667
+ ];
1668
+ expect(files.length, `no exports entry for ${key}`).toBeGreaterThan(1);
1669
+ expect(
1670
+ files.filter((file) => !globs.some((re) => re.test(file))),
1671
+ `not matched by any package.json sideEffects glob`,
1672
+ ).toEqual([]);
1673
+ },
1674
+ );
1675
+ });