@statelyai/sdk 0.15.0 → 0.16.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/README.md CHANGED
@@ -153,15 +153,14 @@ Resource operations always require a credential.
153
153
 
154
154
  <!-- createInspector API from src/inspect.ts -->
155
155
 
156
- Stream live actor-system state to the Stately inspector over WebSockets, with support for automatic XState actor adoption and manual actor registration.
156
+ Stream live actor-system state to the hosted Stately inspector. Zero-config
157
+ inspection needs no API key or local relay.
157
158
 
158
159
  ```ts
159
160
  import { createActor } from 'xstate';
160
161
  import { createInspector } from '@statelyai/sdk';
161
162
 
162
- const inspector = createInspector({
163
- url: 'ws://localhost:4242',
164
- });
163
+ const inspector = createInspector();
165
164
  const { inspect } = inspector;
166
165
 
167
166
  const actor = createActor(machine, { inspect });
@@ -176,13 +175,23 @@ completed request-scoped runs stay available for inspection.
176
175
 
177
176
  XState v5 and v6 inspection events normalize to independent actor, event,
178
177
  snapshot, and stop observations before crossing the WebSocket protocol.
178
+ `actorId` is system-local; `sessionId` is globally unique.
179
179
  Observations captured before the first transport registration replay in order
180
180
  after the initial actor-tree baseline. Reconnects use the latest checkpoint.
181
181
  In Node, the inspector opens in the default browser automatically. The SDK
182
- generates a cryptographically random session capability; hosted inspectors open
183
- without requiring login. The session capability controls access to the live
184
- session. AI-backed features remain separately authenticated. The Node process
185
- does not need a Stately API key.
182
+ connects to `wss://sky.stately.ai` and generates a UUID v4 `?r=` room bearer
183
+ capability. Multiple producers and viewers can share that room. Anyone with the
184
+ URL can inspect its data, so keep it private. Hosted replay expires after 24
185
+ hours without activity. Only actor checkpoints and observations are replayed;
186
+ export traffic is live-only, and auth/upload/embed-control messages are rejected.
187
+ AI-backed features remain separately authenticated.
188
+
189
+ Set `autoOpen: false`, await `inspector.ready`, and navigate to
190
+ `inspector.inspectorUrl` when a test runner or another process owns the browser.
191
+ `inspectorBaseUrl` targets an inspector UI hosted separately from the WebSocket
192
+ relay. An explicit `url` wins over `STATELY_INSPECT_URL`, which wins over the
193
+ hosted default. See `@statelyai/sdk/protocol` for the versioned message and
194
+ `?r=` query contract.
186
195
 
187
196
  ### CLI and sync
188
197
 
@@ -231,6 +240,22 @@ const embed = createStatelyEmbed({
231
240
  });
232
241
  ```
233
242
 
243
+ For inspection, run your own relay and pass its URL explicitly:
244
+
245
+ ```bash
246
+ npx @statelyai/sdk relay
247
+ ```
248
+
249
+ ```ts
250
+ const inspector = createInspector({
251
+ url: 'ws://localhost:4242',
252
+ inspectorBaseUrl: 'http://localhost:3000/inspect',
253
+ });
254
+ ```
255
+
256
+ This repository's `packages/sky` is an optional Cloudflare Durable Object
257
+ reference deployment.
258
+
234
259
  Key environment variables for self-hosted deployments:
235
260
 
236
261
  | Variable | Purpose |
package/dist/bin.d.mts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/bin.mjs ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import { createNodeInspectionRelay } from "./node-relay.mjs";
3
+
4
+ //#region src/bin.ts
5
+ function readFlag(name, fallback) {
6
+ const index = process.argv.indexOf(`--${name}`);
7
+ return index >= 0 ? process.argv[index + 1] ?? fallback : fallback;
8
+ }
9
+ async function main() {
10
+ const command = process.argv[2];
11
+ if (command !== "relay") {
12
+ console.info("Usage: stately-sdk relay [--host 127.0.0.1] [--port 4242]");
13
+ process.exitCode = command ? 1 : 0;
14
+ return;
15
+ }
16
+ const relay = createNodeInspectionRelay({
17
+ host: readFlag("host", process.env.STATELY_HOST ?? "127.0.0.1"),
18
+ port: Number(readFlag("port", process.env.STATELY_PORT ?? "4242")),
19
+ logger: console
20
+ });
21
+ await relay.start();
22
+ const shutdown = async () => {
23
+ await relay.stop();
24
+ process.exit(0);
25
+ };
26
+ process.on("SIGINT", () => void shutdown());
27
+ process.on("SIGTERM", () => void shutdown());
28
+ }
29
+ main().catch((error) => {
30
+ console.error(error);
31
+ process.exit(1);
32
+ });
33
+
34
+ //#endregion
35
+ export { };
package/dist/embed.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as createPendingExportManager, i as createEventRegistry, n as createPostMessageTransport, o as toInitMessage } from "./transport-D2Ud05yg.mjs";
1
+ import { a as toInitMessage, i as createPendingExportManager, r as createEventRegistry, t as createPostMessageTransport } from "./transport-B_ig9Znn.mjs";
2
2
 
3
3
  //#region src/embed.ts
4
4
  function buildEmbedUrl(options) {
package/dist/index.d.mts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { StatelyApiClientOptions, StatelyApiError, StatelyApiUrlOptions, createStatelyApiClient, createStatelyApiUrl } from "./api.mjs";
2
2
  import { _ as serializeJS, c as MachineConfigOptions, d as contextSchemaToTSType, f as eventsSchemaToTSType, g as raw, h as jsonSchemaToTSType, i as CodeGenGraph, l as RawCode, m as graphToXStateTS, o as GraphPatch, p as graphToMachineConfig, t as ActionLocation, u as XStateTSOptions } from "./index-ag6K2iAS.mjs";
3
3
  import { C as EventTypeData, S as DigraphNodeConfig, _ as studioMachineConverter, a as StatelyGraphData, b as DigraphConfig, c as StatelyInvoke, d as StudioAction, f as StudioEdge, g as fromStudioMachine, h as StudioNode, i as StatelyGraph, l as StatelyNodeData, m as StudioMachine, o as StatelyGuard, r as StatelyEdgeData, t as StatelyAction, v as toStudioMachine, w as StateNodeJSONData, x as DigraphEdgeConfig, y as DigraphAction } from "./graph-DuOeLGvh.mjs";
4
- import { CapabilityDeniedCapability, CapabilityDeniedEvent, CommentsConfig, EditorCapabilities, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ExportCallOptions, ExportFormat, ExportFormatMap, INSPECTION_PROTOCOL_VERSION, InitOptions, InspectionAction, InspectionSentEvent, InspectionTakenTransition, ProjectEmbedMachine, UploadResult } from "./protocol.mjs";
4
+ import { CapabilityDeniedCapability, CapabilityDeniedEvent, CommentsConfig, EditorCapabilities, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ExportCallOptions, ExportFormat, ExportFormatMap, INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, InitOptions, InspectionAction, InspectionSentEvent, InspectionTakenTransition, ProjectEmbedMachine, UploadResult, createInspectionRoomUrls, getInspectionRoomId } from "./protocol.mjs";
5
5
  import { AssetUploadAdapter, AssetUploadContext, AssetUploadRequest, CreateS3AssetUploadAdapterOptions, CreateSupabaseAssetUploadAdapterOptions, S3UploadTarget, SupabaseStorageClient, createS3AssetUploadAdapter, createSupabaseAssetUploadAdapter } from "./assetStorage.mjs";
6
6
  import { i as getCredentialToken, n as StatelyCredential, r as createAuthorizationHeader, t as StatelyAuthMode } from "./auth-2Thaw42j.mjs";
7
7
  import { AssetConfig, StatelyEmbed, StatelyEmbedOptions, createStatelyEmbed } from "./embed.mjs";
8
- import { _ as createPostMessageTransport, a as InspectedTransition, c as InspectorInspectionEvent, d as createStatelyInspector, f as MultiplexedChannelOptions, g as createMultiplexedWebSocketConnection, h as Transport, i as InspectedSnapshot, l as ManualActorOptions, m as MultiplexedWebSocketConnectionOptions, n as CreateInspectorOptions, o as Inspector, p as MultiplexedWebSocketConnection, r as InspectedEvent, s as InspectorEvents, t as AdoptedActor, u as createInspector, v as createWebSocketTransport } from "./inspect-DenVP7IE.mjs";
9
- import { A as Machine, C as StudioMachineRecord, D as VerifyApiKeyResponse, E as UpdateProjectInput, F as ProjectVisibility, I as VerifyResult, L as XStateVersion, M as Project, N as ProjectMachineSummary, O as createStatelyClient, P as ProjectSummary, R as ResourceErrorCode, S as StudioClientOptions, T as UpdateMachineInput, _ as ProjectMachine, a as CreateMachineTemplate, b as StudioApiErrorOptions, c as EnsureProjectInput, d as ExtractedMachine, f as GetMachineOptions, g as ProjectData, h as LegacyUpdateMachineInput, i as CreateMachineInput, j as MachineVersion, k as ExtractedMachines, l as ExtractMachinesInput, m as LegacyProjectVisibility, n as CreateMachineFromDefinitionInput, o as CreateProjectInput, r as CreateMachineFromTemplateInput, s as DEFAULT_STATELY_BASE_URL, t as ConnectedRepo, u as ExtractMachinesResponse, v as RepoType, w as StudioRequestOptions, x as StudioClient, y as StudioApiError } from "./studio-Da5pyxv6.mjs";
8
+ import { a as InspectedTransition, c as InspectorInspectionEvent, d as createStatelyInspector, f as Transport, h as createWebSocketTransport, i as InspectedSnapshot, l as ManualActorOptions, m as createPostMessageTransport, n as CreateInspectorOptions, o as Inspector, p as TransportFailure, r as InspectedEvent, s as InspectorEvents, t as AdoptedActor, u as createInspector } from "./inspect-CduY_2Fa.mjs";
9
+ import { A as Machine, C as StudioMachineRecord, D as VerifyApiKeyResponse, E as UpdateProjectInput, F as ProjectVisibility, I as VerifyResult, L as XStateVersion, M as Project, N as ProjectMachineSummary, O as createStatelyClient, P as ProjectSummary, R as ResourceErrorCode, S as StudioClientOptions, T as UpdateMachineInput, _ as ProjectMachine, a as CreateMachineTemplate, b as StudioApiErrorOptions, c as EnsureProjectInput, d as ExtractedMachine, f as GetMachineOptions, g as ProjectData, h as LegacyUpdateMachineInput, i as CreateMachineInput, j as MachineVersion, k as ExtractedMachines, l as ExtractMachinesInput, m as LegacyProjectVisibility, n as CreateMachineFromDefinitionInput, o as CreateProjectInput, r as CreateMachineFromTemplateInput, s as DEFAULT_STATELY_BASE_URL, t as ConnectedRepo, u as ExtractMachinesResponse, v as RepoType, w as StudioRequestOptions, x as StudioClient, y as StudioApiError } from "./studio-Bk_u41gu.mjs";
10
10
  import { OAuthAuthorizationServerMetadata, OAuthClientRegistrationResponse, OAuthProtectedResourceMetadata, OAuthTokenResponse, PkcePair, buildAuthorizeUrl, createPkcePair, discoverAuthorizationServer, discoverProtectedResource, exchangeCodeForToken, refreshToken, registerOAuthClient } from "./oauth.mjs";
11
11
  import { PlanSyncOptions, PullSyncResult, PushLocalMachineLinksResult, PushSyncOptions, PushSyncProjectOptions, PushSyncResult, ResolvedSyncInput, SyncInputFormat, SyncPlan, SyncPlanSummary } from "./sync.mjs";
12
12
  import { CreateInspectionRelayOptions, InspectionRelay, InspectionRelayEffect, InspectionRelayPeer, InspectionRelayRole, InspectionRelaySnapshot, createInspectionRelay } from "./relay.mjs";
@@ -32,4 +32,4 @@ declare function findStatelyPragmaAttachments(sourceText: string, fileName?: str
32
32
  declare function getStatelyPragma(sourceText: string, fileName?: string, machineIndex?: number): StatelyPragma | undefined;
33
33
  declare function upsertStatelyPragma(sourceText: string, id: string, options?: UpsertStatelyPragmaOptions): string;
34
34
  //#endregion
35
- export { type ActionLocation, type AdoptedActor, type AssetConfig, type AssetUploadAdapter, type AssetUploadContext, type AssetUploadRequest, type CapabilityDeniedCapability, type CapabilityDeniedEvent, type CodeGenGraph, type CommentsConfig, type ConnectedRepo, type CreateInspectionRelayOptions, type CreateInspectorOptions, type CreateMachineFromDefinitionInput, type CreateMachineFromTemplateInput, type CreateMachineInput, type CreateMachineTemplate, type CreateProjectInput, type CreateS3AssetUploadAdapterOptions, type CreateSupabaseAssetUploadAdapterOptions, DEFAULT_STATELY_BASE_URL, type DigraphAction, type DigraphConfig, type DigraphEdgeConfig, type DigraphNodeConfig, type EditorCapabilities, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type EnsureProjectInput, type EventTypeData, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type ExtractMachinesInput, type ExtractMachinesResponse, type ExtractedMachine, type ExtractedMachines, type GetMachineOptions, type GraphPatch, INSPECTION_PROTOCOL_VERSION, type InitOptions, type InspectedEvent, type InspectedSnapshot, type InspectedTransition, type InspectionAction, type InspectionRelay, type InspectionRelayEffect, type InspectionRelayPeer, type InspectionRelayRole, type InspectionRelaySnapshot, type InspectionSentEvent, type InspectionTakenTransition, type Inspector, type InspectorEvents, type InspectorInspectionEvent, type LegacyProjectVisibility, type LegacyUpdateMachineInput, type Machine, type MachineConfigOptions, type MachineVersion, type ManualActorOptions, type MultiplexedChannelOptions, type MultiplexedWebSocketConnection, type MultiplexedWebSocketConnectionOptions, type OAuthAuthorizationServerMetadata, type OAuthClientRegistrationResponse, type OAuthProtectedResourceMetadata, type OAuthTokenResponse, type PkcePair, type PlanSyncOptions, type Project, type ProjectData, type ProjectEmbedMachine, type ProjectMachine, type ProjectMachineSummary, type ProjectSummary, type ProjectVisibility, type PullSyncResult, type PushLocalMachineLinksResult, type PushSyncOptions, type PushSyncProjectOptions, type PushSyncResult, RawCode, type RepoType, type ResolvedSyncInput, type ResourceErrorCode, type S3UploadTarget, type StateNodeJSONData, type StatelyAction, type StatelyApiClientOptions, StatelyApiError, type StatelyApiUrlOptions, type StatelyAuthMode, type StatelyCredential, type StatelyEdgeData, type StatelyEmbed, type StatelyEmbedOptions, type StatelyGraph, type StatelyGraphData, type StatelyGuard, type StatelyInvoke, type StatelyNodeData, type StatelyPragma, type StatelyPragmaAttachment, type StudioAction, StudioApiError, type StudioApiErrorOptions, type StudioClient, type StudioClientOptions, type StudioEdge, type StudioMachine, type StudioMachineRecord, type StudioNode, type StudioRequestOptions, type SupabaseStorageClient, type SyncInputFormat, type SyncPlan, type SyncPlanSummary, type Transport, type UpdateMachineInput, type UpdateProjectInput, type UploadResult, type UpsertStatelyPragmaOptions, type VerifyApiKeyResponse, type VerifyResult, type XStateTSOptions, type XStateVersion, buildAuthorizeUrl, contextSchemaToTSType, createAuthorizationHeader, createInspectionRelay, createInspector, createMultiplexedWebSocketConnection, createPkcePair, createPostMessageTransport, createS3AssetUploadAdapter, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createSupabaseAssetUploadAdapter, createWebSocketTransport, discoverAuthorizationServer, discoverProtectedResource, eventsSchemaToTSType, exchangeCodeForToken, findStatelyPragmaAttachments, fromStudioMachine, getCredentialToken, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, refreshToken, registerOAuthClient, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
35
+ export { type ActionLocation, type AdoptedActor, type AssetConfig, type AssetUploadAdapter, type AssetUploadContext, type AssetUploadRequest, type CapabilityDeniedCapability, type CapabilityDeniedEvent, type CodeGenGraph, type CommentsConfig, type ConnectedRepo, type CreateInspectionRelayOptions, type CreateInspectorOptions, type CreateMachineFromDefinitionInput, type CreateMachineFromTemplateInput, type CreateMachineInput, type CreateMachineTemplate, type CreateProjectInput, type CreateS3AssetUploadAdapterOptions, type CreateSupabaseAssetUploadAdapterOptions, DEFAULT_STATELY_BASE_URL, type DigraphAction, type DigraphConfig, type DigraphEdgeConfig, type DigraphNodeConfig, type EditorCapabilities, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type EnsureProjectInput, type EventTypeData, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type ExtractMachinesInput, type ExtractMachinesResponse, type ExtractedMachine, type ExtractedMachines, type GetMachineOptions, type GraphPatch, INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, type InitOptions, type InspectedEvent, type InspectedSnapshot, type InspectedTransition, type InspectionAction, type InspectionRelay, type InspectionRelayEffect, type InspectionRelayPeer, type InspectionRelayRole, type InspectionRelaySnapshot, type InspectionSentEvent, type InspectionTakenTransition, type Inspector, type InspectorEvents, type InspectorInspectionEvent, type LegacyProjectVisibility, type LegacyUpdateMachineInput, type Machine, type MachineConfigOptions, type MachineVersion, type ManualActorOptions, type OAuthAuthorizationServerMetadata, type OAuthClientRegistrationResponse, type OAuthProtectedResourceMetadata, type OAuthTokenResponse, type PkcePair, type PlanSyncOptions, type Project, type ProjectData, type ProjectEmbedMachine, type ProjectMachine, type ProjectMachineSummary, type ProjectSummary, type ProjectVisibility, type PullSyncResult, type PushLocalMachineLinksResult, type PushSyncOptions, type PushSyncProjectOptions, type PushSyncResult, RawCode, type RepoType, type ResolvedSyncInput, type ResourceErrorCode, type S3UploadTarget, type StateNodeJSONData, type StatelyAction, type StatelyApiClientOptions, StatelyApiError, type StatelyApiUrlOptions, type StatelyAuthMode, type StatelyCredential, type StatelyEdgeData, type StatelyEmbed, type StatelyEmbedOptions, type StatelyGraph, type StatelyGraphData, type StatelyGuard, type StatelyInvoke, type StatelyNodeData, type StatelyPragma, type StatelyPragmaAttachment, type StudioAction, StudioApiError, type StudioApiErrorOptions, type StudioClient, type StudioClientOptions, type StudioEdge, type StudioMachine, type StudioMachineRecord, type StudioNode, type StudioRequestOptions, type SupabaseStorageClient, type SyncInputFormat, type SyncPlan, type SyncPlanSummary, type Transport, type TransportFailure, type UpdateMachineInput, type UpdateProjectInput, type UploadResult, type UpsertStatelyPragmaOptions, type VerifyApiKeyResponse, type VerifyResult, type XStateTSOptions, type XStateVersion, buildAuthorizeUrl, contextSchemaToTSType, createAuthorizationHeader, createInspectionRelay, createInspectionRoomUrls, createInspector, createPkcePair, createPostMessageTransport, createS3AssetUploadAdapter, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createSupabaseAssetUploadAdapter, createWebSocketTransport, discoverAuthorizationServer, discoverProtectedResource, eventsSchemaToTSType, exchangeCodeForToken, findStatelyPragmaAttachments, fromStudioMachine, getCredentialToken, getInspectionRoomId, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, refreshToken, registerOAuthClient, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
- import { n as createPostMessageTransport, r as createWebSocketTransport, t as createMultiplexedWebSocketConnection } from "./transport-D2Ud05yg.mjs";
2
- import { INSPECTION_PROTOCOL_VERSION } from "./protocol.mjs";
1
+ import { n as createWebSocketTransport, t as createPostMessageTransport } from "./transport-B_ig9Znn.mjs";
2
+ import { INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, createInspectionRoomUrls, getInspectionRoomId } from "./protocol.mjs";
3
3
  import { createStatelyEmbed } from "./embed.mjs";
4
4
  import { createS3AssetUploadAdapter, createSupabaseAssetUploadAdapter } from "./assetStorage.mjs";
5
- import { n as createStatelyInspector, t as createInspector } from "./inspect-DWDTNMEc.mjs";
5
+ import { n as createStatelyInspector, t as createInspector } from "./inspect-BwVdM4R8.mjs";
6
6
  import { n as StudioApiError, r as createStatelyClient, t as DEFAULT_STATELY_BASE_URL } from "./studio-txdyJHD7.mjs";
7
- import { a as RawCode, c as eventsSchemaToTSType, d as jsonSchemaToTSType, f as raw, l as graphToMachineConfig, n as getStatelyPragma, o as contextSchemaToTSType, p as serializeJS, r as upsertStatelyPragma, t as findStatelyPragmaAttachments, u as graphToXStateTS } from "./statelyPragma-Bm9O4XV6.mjs";
7
+ import { a as RawCode, c as eventsSchemaToTSType, d as jsonSchemaToTSType, f as raw, l as graphToMachineConfig, n as getStatelyPragma, o as contextSchemaToTSType, p as serializeJS, r as upsertStatelyPragma, t as findStatelyPragmaAttachments, u as graphToXStateTS } from "./statelyPragma-Th0gdXfx.mjs";
8
8
  import { createAuthorizationHeader, getCredentialToken } from "./auth.mjs";
9
9
  import { buildAuthorizeUrl, createPkcePair, discoverAuthorizationServer, discoverProtectedResource, exchangeCodeForToken, refreshToken, registerOAuthClient } from "./oauth.mjs";
10
10
  import { StatelyApiError, createStatelyApiClient, createStatelyApiUrl } from "./api.mjs";
11
11
  import { fromStudioMachine, studioMachineConverter, toStudioMachine } from "./graph.mjs";
12
12
  import { createInspectionRelay } from "./relay.mjs";
13
13
 
14
- export { DEFAULT_STATELY_BASE_URL, INSPECTION_PROTOCOL_VERSION, RawCode, StatelyApiError, StudioApiError, buildAuthorizeUrl, contextSchemaToTSType, createAuthorizationHeader, createInspectionRelay, createInspector, createMultiplexedWebSocketConnection, createPkcePair, createPostMessageTransport, createS3AssetUploadAdapter, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createSupabaseAssetUploadAdapter, createWebSocketTransport, discoverAuthorizationServer, discoverProtectedResource, eventsSchemaToTSType, exchangeCodeForToken, findStatelyPragmaAttachments, fromStudioMachine, getCredentialToken, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, refreshToken, registerOAuthClient, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
14
+ export { DEFAULT_STATELY_BASE_URL, INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, RawCode, StatelyApiError, StudioApiError, buildAuthorizeUrl, contextSchemaToTSType, createAuthorizationHeader, createInspectionRelay, createInspectionRoomUrls, createInspector, createPkcePair, createPostMessageTransport, createS3AssetUploadAdapter, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createSupabaseAssetUploadAdapter, createWebSocketTransport, discoverAuthorizationServer, discoverProtectedResource, eventsSchemaToTSType, exchangeCodeForToken, findStatelyPragmaAttachments, fromStudioMachine, getCredentialToken, getInspectionRoomId, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, refreshToken, registerOAuthClient, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
@@ -1,5 +1,5 @@
1
- import { a as createPendingExportManager, i as createEventRegistry, r as createWebSocketTransport } from "./transport-D2Ud05yg.mjs";
2
- import { INSPECTION_PROTOCOL_VERSION } from "./protocol.mjs";
1
+ import { i as createPendingExportManager, n as createWebSocketTransport, r as createEventRegistry } from "./transport-B_ig9Znn.mjs";
2
+ import { INSPECTION_PROTOCOL_VERSION, createInspectionRoomUrls, getInspectionRoomId } from "./protocol.mjs";
3
3
 
4
4
  //#region src/openBrowser.ts
5
5
  async function openBrowser(url) {
@@ -37,25 +37,23 @@ function isStoppedSnapshot(snapshot) {
37
37
  const status = snapshot?.status;
38
38
  return status === "done" || status === "stopped" || status === "error";
39
39
  }
40
- function generateSessionId() {
41
- if (!globalThis.crypto?.randomUUID) throw new Error("createInspector() requires crypto.randomUUID() to generate a secure session capability. Pass sessionId explicitly in older runtimes.");
40
+ function generateRoomId() {
41
+ if (!globalThis.crypto?.randomUUID) throw new Error("createInspector() requires crypto.randomUUID() to generate a secure room capability. Pass roomId explicitly in older runtimes.");
42
42
  return globalThis.crypto.randomUUID();
43
43
  }
44
- function createInspectorLaunchUrl(websocketUrl, sessionId) {
45
- try {
46
- const launchUrl = new URL(websocketUrl);
47
- if (launchUrl.protocol === "ws:") launchUrl.protocol = "http:";
48
- else if (launchUrl.protocol === "wss:") launchUrl.protocol = "https:";
49
- else return null;
50
- launchUrl.searchParams.set("session", sessionId);
51
- return launchUrl.toString();
52
- } catch {
53
- return null;
54
- }
55
- }
56
44
  function createInspector(options = {}) {
57
- const { url = "ws://localhost:4242", autoOpen = true, name, serializeSnapshot = defaultSerializeSnapshot, extractMachineConfig = defaultExtractMachineConfig, selectedActorId, panels, theme, readOnly, depth, capabilities, transport: injectedTransport } = options;
58
- const sessionId = options.sessionId ?? generateSessionId();
45
+ const environmentUrl = typeof process !== "undefined" ? process.env?.STATELY_INSPECT_URL : void 0;
46
+ const url = options.url ?? environmentUrl ?? "wss://sky.stately.ai";
47
+ const { inspectorBaseUrl, autoOpen = true, name, serializeSnapshot = defaultSerializeSnapshot, extractMachineConfig = defaultExtractMachineConfig, selectedSessionId: configuredSelectedSessionId, selectedActorId, panels, theme, readOnly, depth, capabilities, transport: injectedTransport } = options;
48
+ const roomId = options.roomId ?? options.sessionId ?? getInspectionRoomId(url) ?? generateRoomId();
49
+ const producerId = options.producerId ?? generateRoomId();
50
+ const roomUrls = injectedTransport ? null : createInspectionRoomUrls({
51
+ url,
52
+ roomId,
53
+ inspectorBaseUrl
54
+ });
55
+ const relayUrl = roomUrls?.relayUrl ?? null;
56
+ const inspectorUrl = roomUrls?.inspectorUrl ?? null;
59
57
  const displayName = name ?? "system:manual";
60
58
  let destroyed = false;
61
59
  let initSent = false;
@@ -63,13 +61,21 @@ function createInspector(options = {}) {
63
61
  let pendingTransportReady = false;
64
62
  let transportWasReady = false;
65
63
  let didAutoOpen = false;
64
+ let resolveReady;
65
+ let rejectReady;
66
+ let readySettled = false;
67
+ const ready = new Promise((resolve, reject) => {
68
+ resolveReady = resolve;
69
+ rejectReady = reject;
70
+ });
71
+ ready.catch(() => {});
66
72
  const pendingMessages = [];
67
73
  const events = createEventRegistry();
68
74
  const localListeners = {};
69
75
  const transport = injectedTransport ?? createWebSocketTransport({
70
- url,
71
- role: "client",
72
- sessionId,
76
+ url: relayUrl,
77
+ role: "producer",
78
+ producerId,
73
79
  metadata: { name: displayName }
74
80
  });
75
81
  const ownsTransport = !injectedTransport;
@@ -87,6 +93,8 @@ function createInspector(options = {}) {
87
93
  if (!initSent) sendInit();
88
94
  const queued = pendingMessages.splice(0);
89
95
  for (const message of queued) transport.send(message);
96
+ readySettled = true;
97
+ resolveReady();
90
98
  } else {
91
99
  pendingMessages.length = 0;
92
100
  initSent = false;
@@ -94,8 +102,7 @@ function createInspector(options = {}) {
94
102
  }
95
103
  if (autoOpen && !didAutoOpen && ownsTransport) {
96
104
  didAutoOpen = true;
97
- const launchUrl = createInspectorLaunchUrl(url, sessionId);
98
- if (launchUrl) openBrowser(launchUrl).catch((error) => {
105
+ if (inspectorUrl) openBrowser(inspectorUrl).catch((error) => {
99
106
  const failure = {
100
107
  code: "open_failed",
101
108
  message: error instanceof Error ? error.message : "Unable to open the inspector browser"
@@ -112,6 +119,15 @@ function createInspector(options = {}) {
112
119
  }
113
120
  handleTransportReady();
114
121
  });
122
+ transport.onError?.((failure) => {
123
+ const error = new Error(failure.message);
124
+ if (!readySettled) {
125
+ readySettled = true;
126
+ rejectReady(error);
127
+ }
128
+ emitLocal("error", failure);
129
+ events.emit("error", failure);
130
+ });
115
131
  transport.onMessage((msg) => {
116
132
  if (destroyed) return;
117
133
  switch (msg.type) {
@@ -120,6 +136,10 @@ function createInspector(options = {}) {
120
136
  break;
121
137
  case "@statelyai.error":
122
138
  exportManager.reject(new Error(msg.message), msg.requestId);
139
+ if (!readySettled) {
140
+ readySettled = true;
141
+ rejectReady(new Error(msg.message));
142
+ }
123
143
  emitLocal("error", {
124
144
  code: msg.code,
125
145
  message: msg.message
@@ -138,13 +158,14 @@ function createInspector(options = {}) {
138
158
  for (const handler of set) handler(data);
139
159
  }
140
160
  const actors = /* @__PURE__ */ new Map();
161
+ const manualSessionIds = /* @__PURE__ */ new Map();
141
162
  /** Tracks which actors we've already emitted local actor events for. */
142
163
  const locallyRegistered = /* @__PURE__ */ new Set();
143
164
  /** v5 emits transition facets separately; accumulate them until snapshot. */
144
165
  const pendingTransitions = /* @__PURE__ */ new Map();
145
166
  function emitRegisterOnce(entry) {
146
- if (locallyRegistered.has(entry.actorId)) return;
147
- locallyRegistered.add(entry.actorId);
167
+ if (locallyRegistered.has(entry.sessionId)) return;
168
+ locallyRegistered.add(entry.sessionId);
148
169
  emitLocal("actor", entry);
149
170
  emitLocal("register", entry);
150
171
  }
@@ -164,10 +185,10 @@ function createInspector(options = {}) {
164
185
  }
165
186
  function toEntry(actorRef, rootActorId, details) {
166
187
  return {
167
- actorId: actorRef.sessionId,
168
- parentActorId: details?.parentRef?.sessionId ?? actorRef._parent?.sessionId ?? null,
169
- rootId: rootActorId,
170
- id: details?.id ?? actorRef.id ?? actorRef.sessionId,
188
+ sessionId: actorRef.sessionId,
189
+ actorId: details?.id ?? actorRef.id ?? actorRef.sessionId,
190
+ parentSessionId: details?.parentRef?.sessionId ?? actorRef._parent?.sessionId ?? null,
191
+ rootSessionId: rootActorId,
171
192
  systemId: actorRef.systemId,
172
193
  snapshot: details?.snapshot ? serializeSnapshot(details.snapshot) : snapshotValue(actorRef),
173
194
  stopped: stoppedValue(actorRef, details?.snapshot),
@@ -176,9 +197,9 @@ function createInspector(options = {}) {
176
197
  }
177
198
  function toSystemEntry(entry) {
178
199
  return {
200
+ sessionId: entry.sessionId,
179
201
  actorId: entry.actorId,
180
- parentActorId: entry.parentActorId,
181
- id: entry.id,
202
+ parentSessionId: entry.parentSessionId,
182
203
  machine: entry.machineConfig,
183
204
  snapshot: entry.snapshot ?? void 0,
184
205
  ...entry.stopped && { stopped: true }
@@ -195,7 +216,7 @@ function createInspector(options = {}) {
195
216
  const snapshot = actorRef.getSnapshot();
196
217
  existing.snapshot = serializeSnapshot(snapshot);
197
218
  existing.stopped ||= isStoppedSnapshot(snapshot);
198
- } else actors.set(entry.actorId, entry);
219
+ } else actors.set(entry.sessionId, entry);
199
220
  emitRegisterOnce(entry);
200
221
  const children = actorRef.getSnapshot()?.children ?? {};
201
222
  for (const child of Object.values(children)) if (child) backfillActorTree(child, rootActorId);
@@ -204,12 +225,14 @@ function createInspector(options = {}) {
204
225
  const observedRootIds = /* @__PURE__ */ new Set();
205
226
  function sendInit() {
206
227
  for (const [rootActorId, { actor }] of inspectedRoots) backfillActorTree(actor, rootActorId);
228
+ const allEntries = Array.from(actors.values());
229
+ const selectedSessionId = configuredSelectedSessionId ?? selectedActorId ?? observedRootIds.values().next().value ?? allEntries[0]?.sessionId;
207
230
  send({
208
231
  type: "@statelyai.system.init",
209
232
  protocolVersion: INSPECTION_PROTOCOL_VERSION,
210
233
  mode: "inspecting",
211
- actors: Array.from(actors.values()).map(toSystemEntry),
212
- selectedActorId: selectedActorId ?? observedRootIds.values().next().value ?? sessionId,
234
+ actors: allEntries.map(toSystemEntry),
235
+ ...selectedSessionId && { selectedSessionId },
213
236
  ...theme && { theme },
214
237
  ...readOnly !== void 0 && { readOnly },
215
238
  ...depth !== void 0 && { depth },
@@ -223,13 +246,13 @@ function createInspector(options = {}) {
223
246
  function handleActor(actorRef, rootActorId, details) {
224
247
  if (actors.has(actorRef.sessionId)) return;
225
248
  const entry = toEntry(actorRef, rootActorId, details);
226
- actors.set(entry.actorId, entry);
249
+ actors.set(entry.sessionId, entry);
227
250
  emitRegisterOnce(entry);
228
251
  if (initSent) send({
229
252
  type: "@statelyai.system.actorRegistered",
253
+ sessionId: entry.sessionId,
230
254
  actorId: entry.actorId,
231
- parentActorId: entry.parentActorId,
232
- id: entry.id,
255
+ parentSessionId: entry.parentSessionId,
233
256
  machine: entry.machineConfig,
234
257
  snapshot: entry.snapshot ?? void 0
235
258
  });
@@ -254,7 +277,7 @@ function createInspector(options = {}) {
254
277
  }
255
278
  function normalizeSentEvent(sentEvent) {
256
279
  return {
257
- ...sentEvent.targetRef?.sessionId && { targetActorId: sentEvent.targetRef.sessionId },
280
+ ...sentEvent.targetRef?.sessionId && { targetSessionId: sentEvent.targetRef.sessionId },
258
281
  targetId: sentEvent.targetId,
259
282
  event: sentEvent.event,
260
283
  ...sentEvent.delay !== void 0 && { delay: sentEvent.delay },
@@ -265,23 +288,23 @@ function createInspector(options = {}) {
265
288
  return {
266
289
  previousSnapshot: actors.get(actorRef.sessionId)?.snapshot ?? null,
267
290
  event,
268
- sourceActorId: sourceRef?.sessionId ?? null,
291
+ sourceSessionId: sourceRef?.sessionId ?? null,
269
292
  actions: [],
270
293
  transitions: [],
271
294
  sent: []
272
295
  };
273
296
  }
274
- function handleEvent(actorId, event, sourceActorId) {
297
+ function handleEvent(sessionId, event, sourceSessionId) {
275
298
  const inspectedEvent = {
276
- actorId,
277
- sourceActorId,
299
+ sessionId,
300
+ sourceSessionId,
278
301
  event
279
302
  };
280
303
  if (initSent) send({
281
304
  type: "@statelyai.system.actorEvent",
282
- actorId,
305
+ sessionId,
283
306
  event,
284
- sourceActorId
307
+ sourceSessionId
285
308
  });
286
309
  emitLocal("event", inspectedEvent);
287
310
  }
@@ -298,8 +321,8 @@ function createInspector(options = {}) {
298
321
  if (!entry) return;
299
322
  const serialized = serializeSnapshot(snapshot);
300
323
  const inspectedSnapshot = {
301
- actorId: entry.actorId,
302
- sourceActorId: transition.sourceActorId,
324
+ sessionId: entry.sessionId,
325
+ sourceSessionId: transition.sourceSessionId,
303
326
  previousSnapshot: transition.previousSnapshot,
304
327
  snapshot: serialized,
305
328
  event: triggeringEvent ?? transition.event ?? null,
@@ -311,14 +334,14 @@ function createInspector(options = {}) {
311
334
  entry.snapshot = serialized;
312
335
  const stopped = isStoppedSnapshot(snapshot);
313
336
  entry.stopped ||= stopped;
314
- pendingTransitions.delete(entry.actorId);
337
+ pendingTransitions.delete(entry.sessionId);
315
338
  if (initSent) send({
316
339
  type: "@statelyai.system.actorSnapshot",
317
- actorId: entry.actorId,
340
+ sessionId: entry.sessionId,
318
341
  previousSnapshot: inspectedSnapshot.previousSnapshot,
319
342
  snapshot: inspectedSnapshot.snapshot,
320
343
  event: inspectedSnapshot.event,
321
- sourceActorId: inspectedSnapshot.sourceActorId,
344
+ sourceSessionId: inspectedSnapshot.sourceSessionId,
322
345
  actions: inspectedSnapshot.actions,
323
346
  transitions: inspectedSnapshot.transitions,
324
347
  sent: inspectedSnapshot.sent
@@ -326,12 +349,12 @@ function createInspector(options = {}) {
326
349
  emitLocal("snapshot", inspectedSnapshot);
327
350
  emitLocal("transition", inspectedSnapshot);
328
351
  if (stopped && !wasStopped) {
329
- pendingTransitions.delete(entry.actorId);
352
+ pendingTransitions.delete(entry.sessionId);
330
353
  if (initSent) send({
331
354
  type: "@statelyai.system.actorStopped",
332
- actorId: entry.actorId
355
+ sessionId: entry.sessionId
333
356
  });
334
- const stopped = { actorId: entry.actorId };
357
+ const stopped = { sessionId: entry.sessionId };
335
358
  emitLocal("stop", stopped);
336
359
  emitLocal("stopped", stopped);
337
360
  }
@@ -372,7 +395,7 @@ function createInspector(options = {}) {
372
395
  handleTransition(event.actorRef, event.snapshot, event.event, rootActorId, {
373
396
  previousSnapshot: actors.get(event.actorRef.sessionId)?.snapshot ?? null,
374
397
  event: event.event,
375
- sourceActorId: event.sourceRef?.sessionId ?? null,
398
+ sourceSessionId: event.sourceRef?.sessionId ?? null,
376
399
  actions: event.actions.map(normalizeAction),
377
400
  transitions: event.microsteps.map(normalizeTakenTransition),
378
401
  sent: event.sent.map(normalizeSentEvent)
@@ -400,37 +423,44 @@ function createInspector(options = {}) {
400
423
  inspectedRoots.delete(rootActorId);
401
424
  } };
402
425
  }
426
+ function getManualSessionId(actorId) {
427
+ return manualSessionIds.get(actorId) ?? `${producerId}:${actorId}`;
428
+ }
403
429
  function manualRegister(id, opts) {
404
- if (actors.has(id)) return;
430
+ const sessionId = getManualSessionId(id);
431
+ if (actors.has(sessionId)) return;
432
+ manualSessionIds.set(id, sessionId);
433
+ const parentSessionId = opts?.parent ? getManualSessionId(opts.parent) : null;
405
434
  const entry = {
435
+ sessionId,
406
436
  actorId: id,
407
- parentActorId: opts?.parent ?? null,
408
- rootId: sessionId,
409
- id,
437
+ parentSessionId,
438
+ rootSessionId: (parentSessionId && actors.get(parentSessionId)?.rootSessionId) ?? sessionId,
410
439
  systemId: opts?.systemId,
411
440
  snapshot: opts?.snapshot ?? null,
412
441
  stopped: false,
413
442
  machineConfig: opts?.machine ?? null
414
443
  };
415
- actors.set(id, entry);
444
+ actors.set(sessionId, entry);
416
445
  if (!initSent) sendInit();
417
446
  else send({
418
447
  type: "@statelyai.system.actorRegistered",
448
+ sessionId,
419
449
  actorId: id,
420
- parentActorId: entry.parentActorId,
421
- id,
450
+ parentSessionId: entry.parentSessionId,
422
451
  machine: entry.machineConfig,
423
452
  snapshot: entry.snapshot ?? void 0
424
453
  });
425
454
  emitRegisterOnce(entry);
426
455
  }
427
456
  function manualSnapshot(actorId, snapshot, event) {
428
- if (!actors.has(actorId)) manualRegister(actorId);
429
- const entry = actors.get(actorId);
457
+ const sessionId = getManualSessionId(actorId);
458
+ if (!actors.has(sessionId)) manualRegister(actorId);
459
+ const entry = actors.get(sessionId);
430
460
  const previousSnapshot = entry.snapshot;
431
461
  const inspectedSnapshot = {
432
- actorId,
433
- sourceActorId: null,
462
+ sessionId,
463
+ sourceSessionId: null,
434
464
  previousSnapshot,
435
465
  snapshot,
436
466
  event: event ?? null,
@@ -441,11 +471,11 @@ function createInspector(options = {}) {
441
471
  entry.snapshot = snapshot;
442
472
  if (initSent) send({
443
473
  type: "@statelyai.system.actorSnapshot",
444
- actorId,
474
+ sessionId,
445
475
  previousSnapshot,
446
476
  snapshot,
447
477
  event: event ?? null,
448
- sourceActorId: null,
478
+ sourceSessionId: null,
449
479
  actions: [],
450
480
  transitions: [],
451
481
  sent: []
@@ -455,18 +485,20 @@ function createInspector(options = {}) {
455
485
  }
456
486
  function manualEvent(actorId, event, eventOpts) {
457
487
  const eventObj = typeof event === "string" ? { type: event } : { ...event };
458
- if (!actors.has(actorId)) manualRegister(actorId);
459
- handleEvent(actorId, eventObj, eventOpts?.source ?? null);
488
+ const sessionId = getManualSessionId(actorId);
489
+ if (!actors.has(sessionId)) manualRegister(actorId);
490
+ handleEvent(sessionId, eventObj, eventOpts?.source ? getManualSessionId(eventOpts.source) : null);
460
491
  }
461
492
  function manualStop(actorId) {
462
- const entry = actors.get(actorId);
493
+ const sessionId = getManualSessionId(actorId);
494
+ const entry = actors.get(sessionId);
463
495
  if (!entry || entry.stopped) return;
464
496
  entry.stopped = true;
465
497
  if (initSent) send({
466
498
  type: "@statelyai.system.actorStopped",
467
- actorId
499
+ sessionId
468
500
  });
469
- const stopped = { actorId };
501
+ const stopped = { sessionId };
470
502
  emitLocal("stop", stopped);
471
503
  emitLocal("stopped", stopped);
472
504
  }
@@ -477,9 +509,14 @@ function createInspector(options = {}) {
477
509
  }
478
510
  return {
479
511
  actors,
512
+ roomId,
513
+ relayUrl,
514
+ producerId,
480
515
  get sessionId() {
481
- return sessionId;
516
+ return roomId;
482
517
  },
518
+ inspectorUrl,
519
+ ready,
483
520
  inspect: handleInspectionEvent,
484
521
  attach: attachActor,
485
522
  on(event, handler) {