@copilotkit/shared 2.0.0-rc.5 → 2.0.0-rc.7
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/index.cjs +0 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -6
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +4 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -5
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +22 -187
- package/dist/index.umd.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/telemetry/lambda-client.cjs.map +1 -1
- package/dist/telemetry/lambda-client.d.cts.map +1 -1
- package/dist/telemetry/lambda-client.d.mts.map +1 -1
- package/dist/telemetry/lambda-client.mjs.map +1 -1
- package/dist/telemetry/telemetry-client.cjs +3 -3
- package/dist/telemetry/telemetry-client.cjs.map +1 -1
- package/dist/telemetry/telemetry-client.mjs +3 -3
- package/dist/telemetry/telemetry-client.mjs.map +1 -1
- package/dist/types/message.d.cts +1 -18
- package/dist/types/message.d.cts.map +1 -1
- package/dist/types/message.d.mts +1 -18
- package/dist/types/message.d.mts.map +1 -1
- package/dist/utils/errors.cjs +4 -42
- package/dist/utils/errors.cjs.map +1 -1
- package/dist/utils/errors.d.cts +16 -34
- package/dist/utils/errors.d.cts.map +1 -1
- package/dist/utils/errors.d.mts +16 -34
- package/dist/utils/errors.d.mts.map +1 -1
- package/dist/utils/errors.mjs +5 -41
- package/dist/utils/errors.mjs.map +1 -1
- package/dist/utils/index.cjs +0 -2
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +2 -4
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts +2 -4
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +2 -4
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/random-id.cjs +13 -26
- package/dist/utils/random-id.cjs.map +1 -1
- package/dist/utils/random-id.d.cts +6 -3
- package/dist/utils/random-id.d.cts.map +1 -1
- package/dist/utils/random-id.d.mts +6 -3
- package/dist/utils/random-id.d.mts.map +1 -1
- package/dist/utils/random-id.mjs +14 -25
- package/dist/utils/random-id.mjs.map +1 -1
- package/package.json +3 -6
- package/src/telemetry/lambda-client.ts +3 -2
- package/src/telemetry/telemetry-client.ts +3 -3
- package/src/types/message.ts +1 -19
- package/src/utils/__tests__/errors.test.ts +44 -0
- package/src/utils/__tests__/random-id.test.ts +37 -0
- package/src/utils/errors.ts +27 -85
- package/src/utils/index.ts +0 -2
- package/src/utils/random-id.ts +17 -37
- package/tsdown.config.ts +1 -10
- package/dist/utils/conditions.cjs +0 -32
- package/dist/utils/conditions.cjs.map +0 -1
- package/dist/utils/conditions.d.cts +0 -31
- package/dist/utils/conditions.d.cts.map +0 -1
- package/dist/utils/conditions.d.mts +0 -31
- package/dist/utils/conditions.d.mts.map +0 -1
- package/dist/utils/conditions.mjs +0 -31
- package/dist/utils/conditions.mjs.map +0 -1
- package/dist/utils/console-styling.cjs +0 -91
- package/dist/utils/console-styling.cjs.map +0 -1
- package/dist/utils/console-styling.d.cts +0 -65
- package/dist/utils/console-styling.d.cts.map +0 -1
- package/dist/utils/console-styling.d.mts +0 -65
- package/dist/utils/console-styling.d.mts.map +0 -1
- package/dist/utils/console-styling.mjs +0 -85
- package/dist/utils/console-styling.mjs.map +0 -1
- package/src/utils/__tests__/conditions.test.ts +0 -161
- package/src/utils/conditions.ts +0 -116
- package/src/utils/console-styling.ts +0 -126
package/dist/utils/index.mjs
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
import { copyToClipboard } from "./clipboard.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled, publicApiKeyRequired, styledConsole } from "./console-styling.mjs";
|
|
4
|
-
import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.mjs";
|
|
2
|
+
import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, isStructuredCopilotKitError } from "./errors.mjs";
|
|
5
3
|
import { actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.mjs";
|
|
6
4
|
import { parseInspectorMetadataV1 } from "./inspector-metadata.mjs";
|
|
7
5
|
import { parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.mjs";
|
|
8
6
|
import { shouldEnableInspector } from "./inspector-visibility.mjs";
|
|
9
7
|
import { RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE } from "./types.mjs";
|
|
10
|
-
import {
|
|
8
|
+
import { randomId, randomUUID } from "./random-id.mjs";
|
|
11
9
|
import { processEnv } from "./process-env.mjs";
|
|
12
10
|
import { readBody } from "./requests.mjs";
|
|
13
11
|
import { commitRowKeyStore, createRowKeyStore, pruneRowKeyStore, resolveRowRenderKeys, resolveRowRenderKeysById } from "./row-render-keys.mjs";
|
package/dist/utils/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\nexport * from \"./
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-learning\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./process-env\";\nexport * from \"./requests\";\nexport * from \"./row-render-keys\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n// Allow partial values of every type except unterminated numbers. A cut-off\n// number is a *different* number (`{\"max\":1` is about to become 100, not 1),\n// while a cut-off string is still the beginning of the final string. Numbers\n// therefore only appear once terminated by `,`, `}` or `]`.\nconst PARTIAL_JSON_ALLOW = PartialJSON.Allow.ALL & ~PartialJSON.Allow.NUM;\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json, PARTIAL_JSON_ALLOW);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;AAQzC,MAAM,qBAAqB,YAAY,MAAM,MAAM,CAAC,YAAY,MAAM;;;;;AAMtE,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAAS,YAAY,MAAM,MAAM,mBAAmB;AAC1D,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
|
package/dist/utils/random-id.cjs
CHANGED
|
@@ -1,38 +1,25 @@
|
|
|
1
|
-
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
2
|
-
let uuid = require("uuid");
|
|
3
1
|
|
|
4
2
|
//#region src/utils/random-id.ts
|
|
5
3
|
function randomId() {
|
|
6
|
-
return "ck-" + (
|
|
7
|
-
}
|
|
8
|
-
function randomUUID() {
|
|
9
|
-
return (0, uuid.v4)();
|
|
4
|
+
return "ck-" + randomUUID();
|
|
10
5
|
}
|
|
11
6
|
/**
|
|
12
|
-
*
|
|
7
|
+
* Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
|
|
8
|
+
* exists, and builds the UUID from `crypto.getRandomValues()` when it does not
|
|
9
|
+
* (React Native's Hermes has no `randomUUID`).
|
|
13
10
|
*/
|
|
14
|
-
function
|
|
15
|
-
|
|
16
|
-
if (
|
|
17
|
-
if (
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
return
|
|
23
|
-
}
|
|
24
|
-
function dataToUUID(input, namespace) {
|
|
25
|
-
const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
|
|
26
|
-
const boundNamespace = namespace ? (0, uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
|
|
27
|
-
return (0, uuid.v5)(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
|
|
28
|
-
}
|
|
29
|
-
function isValidUUID(uuid$1) {
|
|
30
|
-
return (0, uuid.validate)(uuid$1);
|
|
11
|
+
function randomUUID() {
|
|
12
|
+
const crypto = globalThis.crypto;
|
|
13
|
+
if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
|
|
14
|
+
if (typeof crypto?.getRandomValues !== "function") throw new Error("crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.");
|
|
15
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
16
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
17
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
18
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
|
19
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
|
31
20
|
}
|
|
32
21
|
|
|
33
22
|
//#endregion
|
|
34
|
-
exports.dataToUUID = dataToUUID;
|
|
35
|
-
exports.isValidUUID = isValidUUID;
|
|
36
23
|
exports.randomId = randomId;
|
|
37
24
|
exports.randomUUID = randomUUID;
|
|
38
25
|
//# sourceMappingURL=random-id.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"random-id.cjs","names":[
|
|
1
|
+
{"version":3,"file":"random-id.cjs","names":[],"sources":["../../src/utils/random-id.ts"],"sourcesContent":["export function randomId() {\n return \"ck-\" + randomUUID();\n}\n\n/**\n * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it\n * exists, and builds the UUID from `crypto.getRandomValues()` when it does not\n * (React Native's Hermes has no `randomUUID`).\n */\nexport function randomUUID(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n if (typeof crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.\",\n );\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n"],"mappings":";;AAAA,SAAgB,WAAW;AACzB,QAAO,QAAQ,YAAY;;;;;;;AAQ7B,SAAgB,aAAqB;CACnC,MAAM,SAAS,WAAW;AAC1B,KAAI,OAAO,QAAQ,eAAe,WAChC,QAAO,OAAO,YAAY;AAE5B,KAAI,OAAO,QAAQ,oBAAoB,WACrC,OAAM,IAAI,MACR,yHACD;CAEH,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,GAAG,CAAC;AACxD,OAAM,KAAM,MAAM,KAAM,KAAQ;AAChC,OAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC;AAC3E,QAAO,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,CAAC,KAAK,GAAG"}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
//#region src/utils/random-id.d.ts
|
|
2
2
|
declare function randomId(): string;
|
|
3
|
+
/**
|
|
4
|
+
* Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
|
|
5
|
+
* exists, and builds the UUID from `crypto.getRandomValues()` when it does not
|
|
6
|
+
* (React Native's Hermes has no `randomUUID`).
|
|
7
|
+
*/
|
|
3
8
|
declare function randomUUID(): string;
|
|
4
|
-
declare function dataToUUID(input: string | object, namespace?: string): string;
|
|
5
|
-
declare function isValidUUID(uuid: string): boolean;
|
|
6
9
|
//#endregion
|
|
7
|
-
export {
|
|
10
|
+
export { randomId, randomUUID };
|
|
8
11
|
//# sourceMappingURL=random-id.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"random-id.d.cts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"random-id.d.cts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";iBAAgB,QAAA,CAAA;AAAhB;;;;;AAAA,iBASgB,UAAA,CAAA"}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
//#region src/utils/random-id.d.ts
|
|
2
2
|
declare function randomId(): string;
|
|
3
|
+
/**
|
|
4
|
+
* Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
|
|
5
|
+
* exists, and builds the UUID from `crypto.getRandomValues()` when it does not
|
|
6
|
+
* (React Native's Hermes has no `randomUUID`).
|
|
7
|
+
*/
|
|
3
8
|
declare function randomUUID(): string;
|
|
4
|
-
declare function dataToUUID(input: string | object, namespace?: string): string;
|
|
5
|
-
declare function isValidUUID(uuid: string): boolean;
|
|
6
9
|
//#endregion
|
|
7
|
-
export {
|
|
10
|
+
export { randomId, randomUUID };
|
|
8
11
|
//# sourceMappingURL=random-id.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"random-id.d.mts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"random-id.d.mts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";iBAAgB,QAAA,CAAA;AAAhB;;;;;AAAA,iBASgB,UAAA,CAAA"}
|
package/dist/utils/random-id.mjs
CHANGED
|
@@ -1,34 +1,23 @@
|
|
|
1
|
-
import { v4, v5, validate } from "uuid";
|
|
2
|
-
|
|
3
1
|
//#region src/utils/random-id.ts
|
|
4
2
|
function randomId() {
|
|
5
|
-
return "ck-" +
|
|
6
|
-
}
|
|
7
|
-
function randomUUID() {
|
|
8
|
-
return v4();
|
|
3
|
+
return "ck-" + randomUUID();
|
|
9
4
|
}
|
|
10
5
|
/**
|
|
11
|
-
*
|
|
6
|
+
* Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
|
|
7
|
+
* exists, and builds the UUID from `crypto.getRandomValues()` when it does not
|
|
8
|
+
* (React Native's Hermes has no `randomUUID`).
|
|
12
9
|
*/
|
|
13
|
-
function
|
|
14
|
-
|
|
15
|
-
if (
|
|
16
|
-
if (
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return
|
|
22
|
-
}
|
|
23
|
-
function dataToUUID(input, namespace) {
|
|
24
|
-
const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
|
|
25
|
-
const boundNamespace = namespace ? v5(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
|
|
26
|
-
return v5(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
|
|
27
|
-
}
|
|
28
|
-
function isValidUUID(uuid) {
|
|
29
|
-
return validate(uuid);
|
|
10
|
+
function randomUUID() {
|
|
11
|
+
const crypto = globalThis.crypto;
|
|
12
|
+
if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
|
|
13
|
+
if (typeof crypto?.getRandomValues !== "function") throw new Error("crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.");
|
|
14
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
15
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
16
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
17
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
|
18
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
|
30
19
|
}
|
|
31
20
|
|
|
32
21
|
//#endregion
|
|
33
|
-
export {
|
|
22
|
+
export { randomId, randomUUID };
|
|
34
23
|
//# sourceMappingURL=random-id.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"random-id.mjs","names":[
|
|
1
|
+
{"version":3,"file":"random-id.mjs","names":[],"sources":["../../src/utils/random-id.ts"],"sourcesContent":["export function randomId() {\n return \"ck-\" + randomUUID();\n}\n\n/**\n * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it\n * exists, and builds the UUID from `crypto.getRandomValues()` when it does not\n * (React Native's Hermes has no `randomUUID`).\n */\nexport function randomUUID(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n if (typeof crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.\",\n );\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n"],"mappings":";AAAA,SAAgB,WAAW;AACzB,QAAO,QAAQ,YAAY;;;;;;;AAQ7B,SAAgB,aAAqB;CACnC,MAAM,SAAS,WAAW;AAC1B,KAAI,OAAO,QAAQ,eAAe,WAChC,QAAO,OAAO,YAAY;AAE5B,KAAI,OAAO,QAAQ,oBAAoB,WACrC,OAAM,IAAI,MACR,yHACD;CAEH,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,GAAG,CAAC;AACxD,OAAM,KAAM,MAAM,KAAM,KAAQ;AAChC,OAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC;AAC3E,QAAO,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,CAAC,KAAK,GAAG"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkit/shared",
|
|
3
|
-
"version": "2.0.0-rc.
|
|
3
|
+
"version": "2.0.0-rc.7",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -62,17 +62,13 @@
|
|
|
62
62
|
"@segment/analytics-node": "^2.1.2",
|
|
63
63
|
"@standard-schema/spec": "^1.0.0",
|
|
64
64
|
"clarinet": "^0.12.4",
|
|
65
|
-
"graphql": "^16.8.1",
|
|
66
65
|
"partial-json": "^0.1.7",
|
|
67
66
|
"rxjs": "7.8.1",
|
|
68
|
-
"
|
|
69
|
-
"zod": "^3.23.3",
|
|
70
|
-
"zod-to-json-schema": "^3.23.5"
|
|
67
|
+
"zod": "^3.23.3"
|
|
71
68
|
},
|
|
72
69
|
"devDependencies": {
|
|
73
70
|
"@ag-ui/core": "1.0.2",
|
|
74
71
|
"@types/clarinet": "^0.12.3",
|
|
75
|
-
"@types/uuid": "^10.0.0",
|
|
76
72
|
"@valibot/to-json-schema": "^1.5.0",
|
|
77
73
|
"arktype": "^2.1.29",
|
|
78
74
|
"eslint": "^8.56.0",
|
|
@@ -80,6 +76,7 @@
|
|
|
80
76
|
"typescript": "^5.2.3",
|
|
81
77
|
"valibot": "^1.2.0",
|
|
82
78
|
"vitest": "^3.2.4",
|
|
79
|
+
"zod-to-json-schema": "^3.23.5",
|
|
83
80
|
"tsconfig": "1.4.12"
|
|
84
81
|
},
|
|
85
82
|
"peerDependencies": {
|
|
@@ -136,8 +136,9 @@ export function parseTelemetryIdFromLicense(token?: string): string | null {
|
|
|
136
136
|
// Parse the telemetry_id from a license token AND emit the rollout smoke
|
|
137
137
|
// signal if the parse returned null. Returning the parsed id lets callers
|
|
138
138
|
// cache it in one step (avoiding a second parseTelemetryIdFromLicense
|
|
139
|
-
// pass) while keeping the warn text in lockstep between v1 (shared)
|
|
140
|
-
// v2 (runtime)
|
|
139
|
+
// pass) while keeping the warn text in lockstep between the v1 (shared)
|
|
140
|
+
// TelemetryClient.setLicenseToken and the v2 (runtime)
|
|
141
|
+
// TelemetryClient.setTelemetryIdentity.
|
|
141
142
|
export function parseAndWarnTelemetryId(licenseToken: string): string | null {
|
|
142
143
|
const telemetryId = parseTelemetryIdFromLicense(licenseToken);
|
|
143
144
|
if (!telemetryId) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Analytics } from "@segment/analytics-node";
|
|
2
2
|
import type { AnalyticsEvents } from "./events";
|
|
3
3
|
import { flattenObject } from "./utils";
|
|
4
|
-
import {
|
|
4
|
+
import { randomUUID } from "../utils/random-id";
|
|
5
5
|
import {
|
|
6
6
|
firstNonBlankTelemetryId,
|
|
7
7
|
lambdaClient,
|
|
@@ -62,7 +62,7 @@ export class TelemetryClient {
|
|
|
62
62
|
// Identified events (those whose license token yielded a telemetry_id)
|
|
63
63
|
// bypass the gate on both wires.
|
|
64
64
|
private segmentSampleRate: number = 0.05;
|
|
65
|
-
private anonymousId = `anon_${
|
|
65
|
+
private anonymousId = `anon_${randomUUID()}`;
|
|
66
66
|
|
|
67
67
|
constructor({
|
|
68
68
|
packageName,
|
|
@@ -165,7 +165,7 @@ export class TelemetryClient {
|
|
|
165
165
|
const eventMeta = {
|
|
166
166
|
telemetry_emitter: TELEMETRY_EMITTER_V1,
|
|
167
167
|
telemetry_surface: TELEMETRY_SURFACE_V1,
|
|
168
|
-
telemetry_event_id:
|
|
168
|
+
telemetry_event_id: randomUUID(),
|
|
169
169
|
};
|
|
170
170
|
|
|
171
171
|
const flattenedProperties = flattenObject(properties);
|
package/src/types/message.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as agui from "@ag-ui/core";
|
|
1
|
+
import type * as agui from "@ag-ui/core";
|
|
2
2
|
|
|
3
3
|
// Re-export AG-UI multimodal input types.
|
|
4
4
|
// Note: AG-UI names the text variant TextInputContent; we export it as TextInputPart for consistency.
|
|
@@ -14,18 +14,6 @@ export type {
|
|
|
14
14
|
DocumentInputPart,
|
|
15
15
|
} from "@ag-ui/core";
|
|
16
16
|
|
|
17
|
-
/**
|
|
18
|
-
* @deprecated Use `InputContentSource` from `@ag-ui/core` (re-exported from `@copilotkit/shared`) instead.
|
|
19
|
-
* `ImageData` only described base64 image payloads. `InputContentSource` supports
|
|
20
|
-
* data and URL sources for images, audio, video, and documents.
|
|
21
|
-
* See https://docs.copilotkit.ai/migration-guides/migrate-attachments
|
|
22
|
-
* @since 1.56.0
|
|
23
|
-
*/
|
|
24
|
-
export interface ImageData {
|
|
25
|
-
format: string;
|
|
26
|
-
bytes: string;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
17
|
// Pass through types
|
|
30
18
|
export type Role = agui.Role;
|
|
31
19
|
export type SystemMessage = agui.SystemMessage;
|
|
@@ -44,12 +32,6 @@ export type AIMessage = agui.AssistantMessage & {
|
|
|
44
32
|
generativeUIPosition?: "before" | "after";
|
|
45
33
|
agentName?: string;
|
|
46
34
|
state?: any;
|
|
47
|
-
/**
|
|
48
|
-
* @deprecated Use multimodal `content` array with `InputContent` parts instead.
|
|
49
|
-
* See https://docs.copilotkit.ai/migration-guides/migrate-attachments
|
|
50
|
-
* @since 1.56.0
|
|
51
|
-
*/
|
|
52
|
-
image?: ImageData;
|
|
53
35
|
runId?: string;
|
|
54
36
|
};
|
|
55
37
|
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
CopilotKitError,
|
|
4
|
+
CopilotKitErrorCode,
|
|
5
|
+
ConfigurationError,
|
|
6
|
+
ErrorVisibility,
|
|
7
|
+
Severity,
|
|
8
|
+
} from "../errors";
|
|
9
|
+
|
|
10
|
+
describe("CopilotKitError", () => {
|
|
11
|
+
it("is a plain Error that keeps the structured extensions", () => {
|
|
12
|
+
const error = new CopilotKitError({
|
|
13
|
+
message: "boom",
|
|
14
|
+
code: CopilotKitErrorCode.NOT_FOUND,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
expect(error).toBeInstanceOf(Error);
|
|
18
|
+
expect(error.message).toBe("boom");
|
|
19
|
+
expect(error.name).toBe("CopilotError");
|
|
20
|
+
expect(error.extensions).toMatchObject({
|
|
21
|
+
name: "CopilotError",
|
|
22
|
+
code: CopilotKitErrorCode.NOT_FOUND,
|
|
23
|
+
statusCode: 404,
|
|
24
|
+
visibility: ErrorVisibility.BANNER,
|
|
25
|
+
severity: Severity.CRITICAL,
|
|
26
|
+
originalError: { message: "boom" },
|
|
27
|
+
});
|
|
28
|
+
expect(error.extensions.troubleshootingUrl).toContain(
|
|
29
|
+
"network-errors-api-not-found",
|
|
30
|
+
);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("sets troubleshootingUrl to null when the code has none", () => {
|
|
34
|
+
const error = new CopilotKitError({ code: CopilotKitErrorCode.UNKNOWN });
|
|
35
|
+
expect(error.extensions.troubleshootingUrl).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("keeps subclasses instanceof both the subclass and CopilotKitError", () => {
|
|
39
|
+
const error = new ConfigurationError("bad config");
|
|
40
|
+
expect(error).toBeInstanceOf(ConfigurationError);
|
|
41
|
+
expect(error).toBeInstanceOf(CopilotKitError);
|
|
42
|
+
expect(error.extensions.code).toBe(CopilotKitErrorCode.CONFIGURATION_ERROR);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { randomId, randomUUID } from "../random-id";
|
|
3
|
+
|
|
4
|
+
const UUID_V4 =
|
|
5
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
6
|
+
|
|
7
|
+
describe("randomUUID", () => {
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
vi.unstubAllGlobals();
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("returns crypto.randomUUID() when it exists", () => {
|
|
13
|
+
vi.stubGlobal("crypto", {
|
|
14
|
+
randomUUID: () => "11111111-2222-4333-8444-555555555555",
|
|
15
|
+
});
|
|
16
|
+
expect(randomUUID()).toBe("11111111-2222-4333-8444-555555555555");
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("builds a v4 UUID from getRandomValues when randomUUID is missing", () => {
|
|
20
|
+
vi.stubGlobal("crypto", {
|
|
21
|
+
getRandomValues: (bytes: Uint8Array) => bytes.fill(0xff),
|
|
22
|
+
});
|
|
23
|
+
const id = randomUUID();
|
|
24
|
+
expect(id).toBe("ffffffff-ffff-4fff-bfff-ffffffffffff");
|
|
25
|
+
expect(id).toMatch(UUID_V4);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("throws a clear error when the runtime has no crypto", () => {
|
|
29
|
+
vi.stubGlobal("crypto", undefined);
|
|
30
|
+
expect(() => randomUUID()).toThrow(/getRandomValues/);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("prefixes randomId with ck-", () => {
|
|
34
|
+
expect(randomId()).toMatch(/^ck-/);
|
|
35
|
+
expect(randomId().slice(3)).toMatch(UUID_V4);
|
|
36
|
+
});
|
|
37
|
+
});
|
package/src/utils/errors.ts
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import { GraphQLError } from "graphql";
|
|
2
|
-
import { COPILOTKIT_VERSION } from "../index";
|
|
3
|
-
|
|
4
1
|
export enum Severity {
|
|
5
2
|
CRITICAL = "critical", // Critical errors that block core functionality
|
|
6
3
|
WARNING = "warning", // Configuration/setup issues that need attention
|
|
@@ -21,7 +18,6 @@ export const ERROR_NAMES = {
|
|
|
21
18
|
"CopilotKitRemoteEndpointDiscoveryError",
|
|
22
19
|
COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
|
|
23
20
|
COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
|
|
24
|
-
COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
|
|
25
21
|
RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
|
|
26
22
|
CONFIGURATION_ERROR: "ConfigurationError",
|
|
27
23
|
MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
|
|
@@ -134,7 +130,19 @@ export const ERROR_CONFIG = {
|
|
|
134
130
|
},
|
|
135
131
|
};
|
|
136
132
|
|
|
137
|
-
export
|
|
133
|
+
export interface CopilotKitErrorExtensions {
|
|
134
|
+
name: string;
|
|
135
|
+
statusCode: number;
|
|
136
|
+
code: CopilotKitErrorCode;
|
|
137
|
+
visibility: ErrorVisibility;
|
|
138
|
+
severity?: Severity;
|
|
139
|
+
troubleshootingUrl: string | null;
|
|
140
|
+
originalError: { message: string; stack?: string };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export class CopilotKitError extends Error {
|
|
144
|
+
/** Structured error details, kept in the shape GraphQL errors used in 1.x. */
|
|
145
|
+
extensions: CopilotKitErrorExtensions;
|
|
138
146
|
code: CopilotKitErrorCode;
|
|
139
147
|
statusCode: number;
|
|
140
148
|
severity?: Severity;
|
|
@@ -159,22 +167,21 @@ export class CopilotKitError extends GraphQLError {
|
|
|
159
167
|
const resolvedSeverity =
|
|
160
168
|
severity ?? ("severity" in config ? config.severity : undefined);
|
|
161
169
|
|
|
162
|
-
super(message
|
|
163
|
-
extensions: {
|
|
164
|
-
name,
|
|
165
|
-
statusCode,
|
|
166
|
-
code,
|
|
167
|
-
visibility: resolvedVisibility,
|
|
168
|
-
severity: resolvedSeverity,
|
|
169
|
-
troubleshootingUrl:
|
|
170
|
-
"troubleshootingUrl" in config ? config.troubleshootingUrl : null,
|
|
171
|
-
originalError: {
|
|
172
|
-
message,
|
|
173
|
-
stack: new Error().stack,
|
|
174
|
-
},
|
|
175
|
-
},
|
|
176
|
-
});
|
|
170
|
+
super(message);
|
|
177
171
|
|
|
172
|
+
this.extensions = {
|
|
173
|
+
name,
|
|
174
|
+
statusCode,
|
|
175
|
+
code,
|
|
176
|
+
visibility: resolvedVisibility,
|
|
177
|
+
severity: resolvedSeverity,
|
|
178
|
+
troubleshootingUrl:
|
|
179
|
+
"troubleshootingUrl" in config ? config.troubleshootingUrl : null,
|
|
180
|
+
originalError: {
|
|
181
|
+
message,
|
|
182
|
+
stack: new Error().stack,
|
|
183
|
+
},
|
|
184
|
+
};
|
|
178
185
|
this.code = code;
|
|
179
186
|
this.name = name;
|
|
180
187
|
this.statusCode = statusCode;
|
|
@@ -208,36 +215,6 @@ export class CopilotKitMisuseError extends CopilotKitError {
|
|
|
208
215
|
}
|
|
209
216
|
}
|
|
210
217
|
|
|
211
|
-
const getVersionMismatchErrorMessage = ({
|
|
212
|
-
reactCoreVersion,
|
|
213
|
-
runtimeVersion,
|
|
214
|
-
runtimeClientGqlVersion,
|
|
215
|
-
}: VersionMismatchResponse) =>
|
|
216
|
-
`Version mismatch detected: @copilotkit/runtime@${runtimeVersion ?? ""} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;
|
|
217
|
-
/**
|
|
218
|
-
* Error thrown when CPK versions does not match
|
|
219
|
-
*
|
|
220
|
-
* @extends CopilotKitError
|
|
221
|
-
*/
|
|
222
|
-
export class CopilotKitVersionMismatchError extends CopilotKitError {
|
|
223
|
-
constructor({
|
|
224
|
-
reactCoreVersion,
|
|
225
|
-
runtimeVersion,
|
|
226
|
-
runtimeClientGqlVersion,
|
|
227
|
-
}: VersionMismatchResponse) {
|
|
228
|
-
const code = CopilotKitErrorCode.VERSION_MISMATCH;
|
|
229
|
-
super({
|
|
230
|
-
message: getVersionMismatchErrorMessage({
|
|
231
|
-
reactCoreVersion,
|
|
232
|
-
runtimeVersion,
|
|
233
|
-
runtimeClientGqlVersion,
|
|
234
|
-
}),
|
|
235
|
-
code,
|
|
236
|
-
});
|
|
237
|
-
this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
218
|
/**
|
|
242
219
|
* Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
|
|
243
220
|
* This typically occurs when:
|
|
@@ -477,41 +454,6 @@ export function ensureStructuredError<T extends CopilotKitError>(
|
|
|
477
454
|
return isStructuredCopilotKitError(error) ? error : converter(error);
|
|
478
455
|
}
|
|
479
456
|
|
|
480
|
-
interface VersionMismatchResponse {
|
|
481
|
-
runtimeVersion?: string;
|
|
482
|
-
runtimeClientGqlVersion: string;
|
|
483
|
-
reactCoreVersion: string;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
export async function getPossibleVersionMismatch({
|
|
487
|
-
runtimeVersion,
|
|
488
|
-
runtimeClientGqlVersion,
|
|
489
|
-
}: {
|
|
490
|
-
runtimeVersion?: string;
|
|
491
|
-
runtimeClientGqlVersion: string;
|
|
492
|
-
}) {
|
|
493
|
-
if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion)
|
|
494
|
-
return;
|
|
495
|
-
if (
|
|
496
|
-
COPILOTKIT_VERSION !== runtimeVersion ||
|
|
497
|
-
COPILOTKIT_VERSION !== runtimeClientGqlVersion ||
|
|
498
|
-
runtimeVersion !== runtimeClientGqlVersion
|
|
499
|
-
) {
|
|
500
|
-
return {
|
|
501
|
-
runtimeVersion,
|
|
502
|
-
runtimeClientGqlVersion,
|
|
503
|
-
reactCoreVersion: COPILOTKIT_VERSION,
|
|
504
|
-
message: getVersionMismatchErrorMessage({
|
|
505
|
-
runtimeVersion,
|
|
506
|
-
runtimeClientGqlVersion,
|
|
507
|
-
reactCoreVersion: COPILOTKIT_VERSION,
|
|
508
|
-
}),
|
|
509
|
-
};
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
return;
|
|
513
|
-
}
|
|
514
|
-
|
|
515
457
|
const resolveLowLevelErrorMessage = ({
|
|
516
458
|
errorCode,
|
|
517
459
|
url,
|
package/src/utils/index.ts
CHANGED
package/src/utils/random-id.ts
CHANGED
|
@@ -1,45 +1,25 @@
|
|
|
1
|
-
import { v4 as uuidv4, validate, v5 as uuidv5 } from "uuid";
|
|
2
|
-
|
|
3
1
|
export function randomId() {
|
|
4
|
-
return "ck-" +
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export function randomUUID() {
|
|
8
|
-
return uuidv4();
|
|
2
|
+
return "ck-" + randomUUID();
|
|
9
3
|
}
|
|
10
4
|
|
|
11
5
|
/**
|
|
12
|
-
*
|
|
6
|
+
* Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
|
|
7
|
+
* exists, and builds the UUID from `crypto.getRandomValues()` when it does not
|
|
8
|
+
* (React Native's Hermes has no `randomUUID`).
|
|
13
9
|
*/
|
|
14
|
-
function
|
|
15
|
-
|
|
16
|
-
|
|
10
|
+
export function randomUUID(): string {
|
|
11
|
+
const crypto = globalThis.crypto;
|
|
12
|
+
if (typeof crypto?.randomUUID === "function") {
|
|
13
|
+
return crypto.randomUUID();
|
|
17
14
|
}
|
|
18
|
-
if (
|
|
19
|
-
|
|
15
|
+
if (typeof crypto?.getRandomValues !== "function") {
|
|
16
|
+
throw new Error(
|
|
17
|
+
"crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.",
|
|
18
|
+
);
|
|
20
19
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return result;
|
|
27
|
-
}
|
|
28
|
-
return value;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function dataToUUID(input: string | object, namespace?: string): string {
|
|
32
|
-
const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
|
|
33
|
-
// Since namespace needs to be a uuid, we are creating a uuid for it.
|
|
34
|
-
const boundNamespace = namespace
|
|
35
|
-
? uuidv5(namespace, BASE_NAMESPACE)
|
|
36
|
-
: BASE_NAMESPACE;
|
|
37
|
-
|
|
38
|
-
const stringInput =
|
|
39
|
-
typeof input === "string" ? input : JSON.stringify(toSerializable(input));
|
|
40
|
-
return uuidv5(stringInput, boundNamespace);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function isValidUUID(uuid: string) {
|
|
44
|
-
return validate(uuid);
|
|
20
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
21
|
+
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
|
|
22
|
+
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
|
|
23
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
|
24
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
|
45
25
|
}
|