@statelyai/sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,9 +1,11 @@
1
- import { a as ExportCallOptions, c as InitOptions, i as EmbedMode, l as ProtocolMessage, n as EmbedEventMap, o as ExportFormat, r as EmbedEventName, s as ExportFormatMap, t as EmbedEventHandler } from "./protocol-BC-_s3if.mjs";
2
- import { StatelyEmbed, StatelyEmbedOptions, createStatelyEmbed } from "./embed.mjs";
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-C-7ZK_nK.mjs";
1
+ 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-BfezxFKJ.mjs";
2
+ import { a as ProjectMachine, c as StudioClientOptions, i as ProjectData, l as VerifyApiKeyResponse, n as ExtractedMachine, o as StudioApiError, r as GetMachineOptions, s as StudioClient, t as ExtractMachinesResponse, u as createStatelyClient } from "./studio-D2uQhrvX.mjs";
3
+ import { PlanSyncOptions, PullSyncResult, ResolvedSyncInput, SyncInputFormat, SyncPlan, SyncPlanSummary } from "./sync.mjs";
4
+ import { a as EmbedMode, c as ExportFormatMap, d as UploadResult, i as EmbedEventName, l as InitOptions, n as EmbedEventHandler, o as ExportCallOptions, r as EmbedEventMap, s as ExportFormat, t as CommentsConfig, u as ProtocolMessage } from "./protocol-BgXSkIuc.mjs";
5
+ import { AssetConfig, StatelyEmbed, StatelyEmbedOptions, createStatelyEmbed } from "./embed.mjs";
4
6
  import { CreateInspectorOptions, InspectOptions, Inspector, createStatelyInspector } from "./inspect.mjs";
5
- import { ExtractMachinesResponse, ExtractedMachine, GetMachineOptions, ProjectData, ProjectMachine, StudioApiError, StudioClient, StudioClientOptions, VerifyApiKeyResponse, createStatelyClient } from "./studio.mjs";
6
- import { PlanSyncOptions, PullSyncResult, ResolvedSyncInput, SyncInputFormat, SyncPlan, SyncPlanSummary, planSync, pullSync } from "./sync.mjs";
7
+ import { JSONSchema7 } from "json-schema";
8
+ import { UnknownMachineConfig } from "xstate";
7
9
 
8
10
  //#region src/transport.d.ts
9
11
  interface Transport {
@@ -35,4 +37,143 @@ interface WebSocketTransportOptions {
35
37
  }
36
38
  declare function createWebSocketTransport(options: WebSocketTransportOptions): Transport;
37
39
  //#endregion
38
- export { type CreateInspectorOptions, type DigraphAction, type DigraphConfig, type DigraphEdgeConfig, type DigraphNodeConfig, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type EventTypeData, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type ExtractMachinesResponse, type ExtractedMachine, type GetMachineOptions, type InitOptions, type InspectOptions, type Inspector, type PlanSyncOptions, type ProjectData, type ProjectMachine, type PullSyncResult, type ResolvedSyncInput, type StateNodeJSONData, type StatelyAction, type StatelyEdgeData, type StatelyEmbed, type StatelyEmbedOptions, type StatelyGraph, type StatelyGraphData, type StatelyGuard, type StatelyInvoke, type StatelyNodeData, type StudioAction, StudioApiError, type StudioClient, type StudioClientOptions, type StudioEdge, type StudioMachine, type StudioNode, type SyncInputFormat, type SyncPlan, type SyncPlanSummary, type Transport, type VerifyApiKeyResponse, createPostMessageTransport, createStatelyClient, createStatelyEmbed, createStatelyInspector, createWebSocketTransport, fromStudioMachine, planSync, pullSync, studioMachineConverter, toStudioMachine };
40
+ //#region src/codegenTypes.d.ts
41
+ interface CodeGenAction {
42
+ type: string;
43
+ params?: Record<string, unknown>;
44
+ code?: string;
45
+ }
46
+ interface CodeGenGuard {
47
+ type: string;
48
+ code?: string;
49
+ params?: Record<string, unknown>;
50
+ }
51
+ interface CodeGenInvoke {
52
+ src: string;
53
+ id: string;
54
+ input?: unknown;
55
+ }
56
+ interface CodeGenNodeData {
57
+ key: string;
58
+ type?: 'normal' | 'parallel' | 'final' | 'history' | null;
59
+ initialId?: string | null;
60
+ history?: 'shallow' | 'deep' | boolean;
61
+ entry?: CodeGenAction[];
62
+ exit?: CodeGenAction[];
63
+ invokes?: CodeGenInvoke[];
64
+ tags?: Array<string | {
65
+ name: string;
66
+ }>;
67
+ description?: string | null;
68
+ meta?: Record<string, unknown> | null;
69
+ color?: string;
70
+ parentId?: string | null;
71
+ temp?: boolean;
72
+ }
73
+ interface CodeGenEdgeData {
74
+ eventType: string;
75
+ transitionType?: 'normal' | 'targetless' | 'reenter';
76
+ guard?: CodeGenGuard | null;
77
+ actions?: CodeGenAction[];
78
+ description?: string | null;
79
+ color?: string;
80
+ meta?: Record<string, unknown> | null;
81
+ temp?: boolean;
82
+ }
83
+ interface CodeGenImplementation {
84
+ id: string;
85
+ name: string;
86
+ description?: string | null;
87
+ icon?: string;
88
+ paramsSchema?: JSONSchema7 | null;
89
+ code?: {
90
+ body: string;
91
+ lang?: string;
92
+ } | null;
93
+ }
94
+ interface CodeGenActorImplementation {
95
+ id: string;
96
+ name: string;
97
+ description?: string | null;
98
+ icon?: string;
99
+ inputSchema?: JSONSchema7 | null;
100
+ outputSchema?: JSONSchema7 | null;
101
+ code?: {
102
+ body: string;
103
+ lang?: string;
104
+ } | null;
105
+ }
106
+ interface CodeGenGraphData {
107
+ schemas?: {
108
+ context?: Record<string, JSONSchema7> | null;
109
+ events?: Record<string, JSONSchema7> | null;
110
+ input?: JSONSchema7 | null;
111
+ output?: JSONSchema7 | null;
112
+ } | null;
113
+ implementations?: {
114
+ actions: CodeGenImplementation[];
115
+ guards: CodeGenImplementation[];
116
+ actors: CodeGenActorImplementation[];
117
+ delays: CodeGenImplementation[];
118
+ } | null;
119
+ }
120
+ interface CodeGenNode {
121
+ id: string;
122
+ parentId?: string | null;
123
+ data: CodeGenNodeData;
124
+ }
125
+ interface CodeGenEdge {
126
+ id: string;
127
+ sourceId: string;
128
+ targetId: string;
129
+ data: CodeGenEdgeData;
130
+ }
131
+ interface CodeGenGraph {
132
+ id: string;
133
+ nodes: CodeGenNode[];
134
+ edges: CodeGenEdge[];
135
+ data: CodeGenGraphData;
136
+ }
137
+ //#endregion
138
+ //#region src/graphToMachineConfig.d.ts
139
+ interface MachineConfigOptions {
140
+ showDescriptions?: boolean;
141
+ showMeta?: boolean;
142
+ }
143
+ declare function graphToMachineConfig(graph: CodeGenGraph, options?: MachineConfigOptions): UnknownMachineConfig;
144
+ //#endregion
145
+ //#region src/graphToXStateTS.d.ts
146
+ interface XStateTSOptions extends MachineConfigOptions {
147
+ exportStyle?: 'named' | 'default' | 'none';
148
+ }
149
+ declare function graphToXStateTS(graph: CodeGenGraph, options?: XStateTSOptions): string;
150
+ //#endregion
151
+ //#region src/serializeJS.d.ts
152
+ /**
153
+ * Serializes JavaScript values as JS source code (not JSON).
154
+ * - Unquoted keys for valid identifiers
155
+ * - Single-quoted strings
156
+ * - Omits undefined values
157
+ * - Supports RawCode for verbatim expressions
158
+ */
159
+ declare class RawCode {
160
+ code: string;
161
+ constructor(code: string);
162
+ }
163
+ declare function raw(code: string): RawCode;
164
+ declare function serializeJS(value: unknown, indent?: number, step?: number): string;
165
+ //#endregion
166
+ //#region src/jsonSchemaToTSType.d.ts
167
+ declare function jsonSchemaToTSType(schema: JSONSchema7 | undefined | null): string;
168
+ /**
169
+ * Build an inline context type string from the schemas.context record.
170
+ * Each key is a context property name, value is its JSONSchema7.
171
+ */
172
+ declare function contextSchemaToTSType(context: Record<string, JSONSchema7> | null | undefined): string | null;
173
+ /**
174
+ * Build an event union type from the schemas.events record.
175
+ * Each key is the event type name, value describes the payload properties.
176
+ */
177
+ declare function eventsSchemaToTSType(events: Record<string, JSONSchema7> | null | undefined): string | null;
178
+ //#endregion
179
+ export { type AssetConfig, type CodeGenGraph, type CommentsConfig, type CreateInspectorOptions, type DigraphAction, type DigraphConfig, type DigraphEdgeConfig, type DigraphNodeConfig, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type EventTypeData, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type ExtractMachinesResponse, type ExtractedMachine, type GetMachineOptions, type InitOptions, type InspectOptions, type Inspector, type MachineConfigOptions, type PlanSyncOptions, type ProjectData, type ProjectMachine, type PullSyncResult, RawCode, type ResolvedSyncInput, type StateNodeJSONData, type StatelyAction, type StatelyEdgeData, type StatelyEmbed, type StatelyEmbedOptions, type StatelyGraph, type StatelyGraphData, type StatelyGuard, type StatelyInvoke, type StatelyNodeData, type StudioAction, StudioApiError, type StudioClient, type StudioClientOptions, type StudioEdge, type StudioMachine, type StudioNode, type SyncInputFormat, type SyncPlan, type SyncPlanSummary, type Transport, type UploadResult, type VerifyApiKeyResponse, type XStateTSOptions, contextSchemaToTSType, createPostMessageTransport, createStatelyClient, createStatelyEmbed, createStatelyInspector, createWebSocketTransport, eventsSchemaToTSType, fromStudioMachine, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, serializeJS, studioMachineConverter, toStudioMachine };
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { n as createWebSocketTransport, t as createPostMessageTransport } from "./transport-D352iKKa.mjs";
1
+ import { n as createWebSocketTransport, t as createPostMessageTransport } from "./transport-C1fRAuv-.mjs";
2
2
  import { createStatelyEmbed } from "./embed.mjs";
3
3
  import { createStatelyInspector } from "./inspect.mjs";
4
4
  import { StudioApiError, createStatelyClient } from "./studio.mjs";
5
5
  import { fromStudioMachine, studioMachineConverter, toStudioMachine } from "./graph.mjs";
6
- import { n as pullSync, t as planSync } from "./sync-CzEOizjx.mjs";
6
+ import { a as graphToMachineConfig, c as serializeJS, i as jsonSchemaToTSType, n as contextSchemaToTSType, o as RawCode, r as eventsSchemaToTSType, s as raw, t as graphToXStateTS } from "./graphToXStateTS-C6HQUrBB.mjs";
7
7
 
8
- export { StudioApiError, createPostMessageTransport, createStatelyClient, createStatelyEmbed, createStatelyInspector, createWebSocketTransport, fromStudioMachine, planSync, pullSync, studioMachineConverter, toStudioMachine };
8
+ export { RawCode, StudioApiError, contextSchemaToTSType, createPostMessageTransport, createStatelyClient, createStatelyEmbed, createStatelyInspector, createWebSocketTransport, eventsSchemaToTSType, fromStudioMachine, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, serializeJS, studioMachineConverter, toStudioMachine };
@@ -1,4 +1,4 @@
1
- import { a as ExportCallOptions, c as InitOptions, i as EmbedMode, n as EmbedEventMap, o as ExportFormat, r as EmbedEventName, s as ExportFormatMap, t as EmbedEventHandler } from "./protocol-BC-_s3if.mjs";
1
+ import { a as EmbedMode, c as ExportFormatMap, i as EmbedEventName, n as EmbedEventHandler, o as ExportCallOptions, r as EmbedEventMap, s as ExportFormat } from "./protocol-BgXSkIuc.mjs";
2
2
 
3
3
  //#region src/inspect.d.ts
4
4
  interface CreateInspectorOptions {
@@ -38,8 +38,12 @@ interface InspectOptions {
38
38
  theme?: 'light' | 'dark';
39
39
  readOnly?: boolean;
40
40
  depth?: number;
41
- panels?: InitOptions['panels'];
41
+ panels?: {
42
+ leftPanels?: string[];
43
+ rightPanels?: string[];
44
+ activePanels?: string[];
45
+ };
42
46
  }
43
47
  declare function createStatelyInspector(options?: CreateInspectorOptions): Inspector;
44
48
  //#endregion
45
- export { CreateInspectorOptions, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type InitOptions, InspectOptions, Inspector, createStatelyInspector };
49
+ export { CreateInspectorOptions, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type ExportCallOptions, type ExportFormat, type ExportFormatMap, InspectOptions, Inspector, createStatelyInspector };
package/dist/inspect.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as createRequestId, i as createPendingExportManager, n as createWebSocketTransport, o as toInitMessage, r as createEventRegistry } from "./transport-D352iKKa.mjs";
1
+ import { a as createRequestId, i as createPendingExportManager, n as createWebSocketTransport, o as toInitMessage, r as createEventRegistry } from "./transport-C1fRAuv-.mjs";
2
2
 
3
3
  //#region src/inspect.ts
4
4
  function generateId() {
@@ -1,5 +1,12 @@
1
1
  //#region src/protocol.d.ts
2
2
  type EmbedMode = 'editing' | 'viewing' | 'simulating' | 'inspecting';
3
+ interface CommentsConfig {
4
+ roomId: string;
5
+ userId?: string | null;
6
+ publicApiKey?: string;
7
+ authEndpoint?: string;
8
+ baseUrl?: string;
9
+ }
3
10
  interface ExportFormatMap {
4
11
  xstate: {
5
12
  options: {
@@ -72,6 +79,7 @@ interface InitOptions {
72
79
  rightPanels?: string[];
73
80
  activePanels?: string[];
74
81
  };
82
+ comments?: CommentsConfig;
75
83
  }
76
84
  interface InitMessage {
77
85
  type: '@statelyai.init';
@@ -84,6 +92,7 @@ interface InitMessage {
84
92
  leftPanels?: string[];
85
93
  rightPanels?: string[];
86
94
  activePanels?: string[];
95
+ comments?: CommentsConfig;
87
96
  }
88
97
  interface UpdateMessage {
89
98
  type: '@statelyai.update';
@@ -114,8 +123,6 @@ interface InspectSnapshotMessage {
114
123
  snapshot: unknown;
115
124
  event: unknown | null;
116
125
  }
117
- /** All messages a client (embed/inspector) can send to the viz. */
118
- type ClientMessage = InitMessage | UpdateMessage | SetModeMessage | SetThemeMessage | RetrieveMessage | ToastMessage | InspectSnapshotMessage;
119
126
  interface ReadyMessage {
120
127
  type: '@statelyai.ready';
121
128
  version: string;
@@ -145,8 +152,50 @@ interface ErrorMessage {
145
152
  message: string;
146
153
  requestId?: string;
147
154
  }
155
+ /** File metadata sent from viz to SDK when a file needs uploading. */
156
+ interface UploadFileInfo {
157
+ /** Original filename (e.g. "screenshot.png") */
158
+ name: string;
159
+ /** MIME type (e.g. "image/png") */
160
+ mimeType: string;
161
+ /** File size in bytes */
162
+ size: number;
163
+ /** File content as base64-encoded string */
164
+ data: string;
165
+ }
166
+ /** The result the consumer returns after uploading. */
167
+ interface UploadResult {
168
+ /** The publicly accessible URL of the uploaded file */
169
+ url: string;
170
+ /** Optional display name (defaults to original filename) */
171
+ name?: string;
172
+ /** Optional metadata stored on the asset */
173
+ metadata?: Record<string, unknown>;
174
+ }
175
+ /** Viz requests the parent to upload a file. */
176
+ interface UploadRequestMessage {
177
+ type: '@statelyai.uploadRequest';
178
+ requestId: string;
179
+ file: UploadFileInfo;
180
+ stateNodeId: string;
181
+ }
182
+ /** Parent tells the viz the upload capabilities on init. */
183
+ interface UploadCapabilitiesMessage {
184
+ type: '@statelyai.uploadCapabilities';
185
+ enabled: boolean;
186
+ accept?: string[];
187
+ maxFileSize?: number;
188
+ }
189
+ /** Parent sends the upload result back to the viz. */
190
+ interface UploadResponseMessage {
191
+ type: '@statelyai.uploadResponse';
192
+ requestId: string;
193
+ result: UploadResult;
194
+ }
195
+ /** All messages a client (embed/inspector) can send to the viz. */
196
+ type ClientMessage = InitMessage | UpdateMessage | SetModeMessage | SetThemeMessage | RetrieveMessage | ToastMessage | InspectSnapshotMessage | UploadCapabilitiesMessage | UploadResponseMessage | ErrorMessage;
148
197
  /** All messages the viz can send back to a client. */
149
- type VizMessage = ReadyMessage | LoadedMessage | ChangeMessage | SaveMessage | RetrievedMessage | ErrorMessage;
198
+ type VizMessage = ReadyMessage | LoadedMessage | ChangeMessage | SaveMessage | RetrievedMessage | ErrorMessage | UploadRequestMessage;
150
199
  interface RegisterMessage {
151
200
  type: '@statelyai.register';
152
201
  role: 'client' | 'viz';
@@ -169,4 +218,4 @@ type SessionMessage = RegisterMessage | RegisteredMessage | RequestOpenMessage;
169
218
  /** Any valid protocol message. */
170
219
  type ProtocolMessage = ClientMessage | VizMessage | SessionMessage;
171
220
  //#endregion
172
- export { ExportCallOptions as a, InitOptions as c, EmbedMode as i, ProtocolMessage as l, EmbedEventMap as n, ExportFormat as o, EmbedEventName as r, ExportFormatMap as s, EmbedEventHandler as t };
221
+ export { EmbedMode as a, ExportFormatMap as c, UploadResult as d, EmbedEventName as i, InitOptions as l, EmbedEventHandler as n, ExportCallOptions as o, EmbedEventMap as r, ExportFormat as s, CommentsConfig as t, ProtocolMessage as u };
@@ -0,0 +1,54 @@
1
+ //#region src/studio.d.ts
2
+ interface StudioClientOptions {
3
+ baseUrl?: string;
4
+ apiKey?: string;
5
+ fetch?: typeof fetch;
6
+ }
7
+ interface VerifyApiKeyResponse {
8
+ valid: boolean;
9
+ }
10
+ interface ProjectMachine {
11
+ machineId: string;
12
+ name: string;
13
+ }
14
+ interface ProjectData {
15
+ projectId: string;
16
+ machines: ProjectMachine[];
17
+ }
18
+ interface ExtractedMachine {
19
+ id?: string;
20
+ config: Record<string, unknown>;
21
+ setupConfig?: Record<string, unknown>;
22
+ implementations?: Record<string, unknown>;
23
+ _type: 'setup.createMachine' | 'createMachine';
24
+ }
25
+ interface ExtractMachinesResponse {
26
+ machines: ExtractedMachine[];
27
+ error?: string;
28
+ }
29
+ interface GetMachineOptions {
30
+ version?: string;
31
+ }
32
+ declare class StudioApiError extends Error {
33
+ readonly status: number;
34
+ constructor(message: string, status: number);
35
+ }
36
+ interface StudioClient {
37
+ auth: {
38
+ verify(apiKey?: string): Promise<VerifyApiKeyResponse>;
39
+ };
40
+ projects: {
41
+ get(projectId: string): Promise<ProjectData>;
42
+ };
43
+ machines: {
44
+ get<TMachine = Record<string, unknown>>(machineId: string, options?: GetMachineOptions): Promise<TMachine>;
45
+ };
46
+ code: {
47
+ extractMachines(code: string, options?: {
48
+ apiKey?: string | null;
49
+ }): Promise<ExtractMachinesResponse>;
50
+ };
51
+ }
52
+ declare function createStatelyClient(options?: StudioClientOptions): StudioClient;
53
+ //#endregion
54
+ export { ProjectMachine as a, StudioClientOptions as c, ProjectData as i, VerifyApiKeyResponse as l, ExtractedMachine as n, StudioApiError as o, GetMachineOptions as r, StudioClient as s, ExtractMachinesResponse as t, createStatelyClient as u };
package/dist/studio.d.mts CHANGED
@@ -1,54 +1,2 @@
1
- //#region src/studio.d.ts
2
- interface StudioClientOptions {
3
- baseUrl?: string;
4
- apiKey?: string;
5
- fetch?: typeof fetch;
6
- }
7
- interface VerifyApiKeyResponse {
8
- valid: boolean;
9
- }
10
- interface ProjectMachine {
11
- machineId: string;
12
- name: string;
13
- }
14
- interface ProjectData {
15
- projectId: string;
16
- machines: ProjectMachine[];
17
- }
18
- interface ExtractedMachine {
19
- id?: string;
20
- config: Record<string, unknown>;
21
- setupConfig?: Record<string, unknown>;
22
- implementations?: Record<string, unknown>;
23
- _type: 'setup.createMachine' | 'createMachine';
24
- }
25
- interface ExtractMachinesResponse {
26
- machines: ExtractedMachine[];
27
- error?: string;
28
- }
29
- interface GetMachineOptions {
30
- version?: string;
31
- }
32
- declare class StudioApiError extends Error {
33
- readonly status: number;
34
- constructor(message: string, status: number);
35
- }
36
- interface StudioClient {
37
- auth: {
38
- verify(apiKey?: string): Promise<VerifyApiKeyResponse>;
39
- };
40
- projects: {
41
- get(projectId: string): Promise<ProjectData>;
42
- };
43
- machines: {
44
- get<TMachine = Record<string, unknown>>(machineId: string, options?: GetMachineOptions): Promise<TMachine>;
45
- };
46
- code: {
47
- extractMachines(code: string, options?: {
48
- apiKey?: string | null;
49
- }): Promise<ExtractMachinesResponse>;
50
- };
51
- }
52
- declare function createStatelyClient(options?: StudioClientOptions): StudioClient;
53
- //#endregion
1
+ import { a as ProjectMachine, c as StudioClientOptions, i as ProjectData, l as VerifyApiKeyResponse, n as ExtractedMachine, o as StudioApiError, r as GetMachineOptions, s as StudioClient, t as ExtractMachinesResponse, u as createStatelyClient } from "./studio-D2uQhrvX.mjs";
54
2
  export { ExtractMachinesResponse, ExtractedMachine, GetMachineOptions, ProjectData, ProjectMachine, StudioApiError, StudioClient, StudioClientOptions, VerifyApiKeyResponse, createStatelyClient };
package/dist/sync.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as StatelyGraph } from "./graph-C-7ZK_nK.mjs";
2
- import { StudioClient } from "./studio.mjs";
1
+ import { i as StatelyGraph } from "./graph-BfezxFKJ.mjs";
2
+ import { s as StudioClient } from "./studio-D2uQhrvX.mjs";
3
3
  import { GraphDiff } from "@statelyai/graph";
4
4
 
5
5
  //#region src/sync.d.ts
package/dist/sync.mjs CHANGED
@@ -1,5 +1,255 @@
1
- import "./studio.mjs";
2
- import "./graph.mjs";
3
- import { n as pullSync, t as planSync } from "./sync-CzEOizjx.mjs";
1
+ import { createStatelyClient } from "./studio.mjs";
2
+ import { fromStudioMachine, toStudioMachine } from "./graph.mjs";
3
+ import { t as graphToXStateTS } from "./graphToXStateTS-C6HQUrBB.mjs";
4
+ import { getDiff, isEmptyDiff } from "@statelyai/graph";
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
4
7
 
8
+ //#region src/sync.ts
9
+ function isUrl(value) {
10
+ try {
11
+ const url = new URL(value);
12
+ return url.protocol === "http:" || url.protocol === "https:";
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+ async function fileExists(filePath) {
18
+ try {
19
+ await fs.access(filePath);
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+ function normalizeActions(value) {
26
+ if (value == null) return [];
27
+ return (Array.isArray(value) ? value : [value]).map((item) => {
28
+ if (typeof item === "string") return { type: item };
29
+ if (typeof item === "object" && item !== null && "type" in item) {
30
+ const type = item.type;
31
+ const params = "params" in item && typeof item.params === "object" && item.params ? item.params : void 0;
32
+ return {
33
+ type,
34
+ ...params ? { params } : {}
35
+ };
36
+ }
37
+ return { type: String(item) };
38
+ });
39
+ }
40
+ function normalizeTags(value) {
41
+ if (!value) return [];
42
+ if (Array.isArray(value)) return value.map((tag) => String(tag));
43
+ return [String(value)];
44
+ }
45
+ function normalizeInvoke(value) {
46
+ if (!value) return [];
47
+ return (Array.isArray(value) ? value : [value]).map((invoke, index) => ({
48
+ src: invoke.src,
49
+ id: invoke.id ?? `invoke[${index}]`,
50
+ ...invoke.input ? { input: invoke.input } : {}
51
+ }));
52
+ }
53
+ function resolveTargetId(sourceParentPath, target) {
54
+ if (!target) return;
55
+ if (target.startsWith("#")) {
56
+ const stripped = target.slice(1);
57
+ const machineIndex = stripped.indexOf(".");
58
+ if (machineIndex >= 0) return `(machine).${stripped.slice(machineIndex + 1)}`;
59
+ return `(machine).${stripped}`;
60
+ }
61
+ if (target.startsWith("(machine)")) return target;
62
+ if (target.includes(".")) return `(machine).${target}`;
63
+ return `${sourceParentPath}.${target}`;
64
+ }
65
+ function appendTransitionEdges(edges, sourceId, sourceParentPath, eventType, transition, edgeCounts) {
66
+ const transitions = Array.isArray(transition) ? transition : [transition];
67
+ for (const item of transitions) {
68
+ const normalized = typeof item === "string" ? { target: item } : item;
69
+ const targetId = resolveTargetId(sourceParentPath, Array.isArray(normalized.target) ? normalized.target[0] : normalized.target);
70
+ const groupKey = `${sourceId}:${eventType}`;
71
+ const index = edgeCounts.get(groupKey) ?? 0;
72
+ edgeCounts.set(groupKey, index + 1);
73
+ edges.push({
74
+ type: "edge",
75
+ id: `${sourceId}#${eventType}[${index}]`,
76
+ sourceId,
77
+ targetId: targetId ?? sourceId,
78
+ label: eventType,
79
+ data: {
80
+ eventType,
81
+ transitionType: normalized.reenter === true ? "reenter" : normalized.internal === true || !targetId ? "targetless" : "normal",
82
+ ...normalized.guard ? { guard: typeof normalized.guard === "string" ? { type: normalized.guard } : {
83
+ type: normalized.guard.type,
84
+ ...normalized.guard.params ? { params: normalized.guard.params } : {}
85
+ } } : {},
86
+ actions: normalizeActions(normalized.actions),
87
+ ...normalized.description ? { description: normalized.description } : {}
88
+ }
89
+ });
90
+ }
91
+ }
92
+ function fromXStateConfig(config) {
93
+ const nodes = [];
94
+ const edges = [];
95
+ const edgeCounts = /* @__PURE__ */ new Map();
96
+ function visitNode(key, nodeConfig, parentId, parentPath) {
97
+ const nodeId = parentPath ? `${parentPath}.${key}` : "(machine)";
98
+ const currentPath = parentPath ? nodeId : "(machine)";
99
+ const initialId = nodeConfig.initial ? `${currentPath}.${nodeConfig.initial}` : void 0;
100
+ nodes.push({
101
+ type: "node",
102
+ id: nodeId,
103
+ parentId,
104
+ label: key,
105
+ ...initialId ? { initialNodeId: initialId } : {},
106
+ data: {
107
+ key,
108
+ ...nodeConfig.type ? { type: nodeConfig.type } : {},
109
+ ...nodeConfig.history ? { history: nodeConfig.history } : {},
110
+ ...initialId ? { initialId } : {},
111
+ entry: normalizeActions(nodeConfig.entry),
112
+ exit: normalizeActions(nodeConfig.exit),
113
+ invokes: normalizeInvoke(nodeConfig.invoke),
114
+ tags: normalizeTags(nodeConfig.tags),
115
+ ...nodeConfig.description ? { description: nodeConfig.description } : {}
116
+ }
117
+ });
118
+ for (const [eventType, transition] of Object.entries(nodeConfig.on ?? {})) appendTransitionEdges(edges, nodeId, parentPath ?? "(machine)", eventType, transition, edgeCounts);
119
+ if (nodeConfig.always) appendTransitionEdges(edges, nodeId, parentPath ?? "(machine)", "", nodeConfig.always, edgeCounts);
120
+ for (const [childKey, childConfig] of Object.entries(nodeConfig.states ?? {})) visitNode(childKey, childConfig, nodeId, currentPath);
121
+ }
122
+ visitNode("(machine)", config, null, null);
123
+ return {
124
+ id: config.id ?? "machine",
125
+ nodes,
126
+ edges,
127
+ data: {}
128
+ };
129
+ }
130
+ async function resolveLocalFile(locator, options) {
131
+ const filePath = path.resolve(options.cwd ?? process.cwd(), locator);
132
+ const contents = await fs.readFile(filePath, "utf8");
133
+ const extension = path.extname(filePath).toLowerCase();
134
+ if (extension === ".ts" || extension === ".tsx" || extension === ".js" || extension === ".jsx") {
135
+ const config = (await (options.client ?? createStatelyClient({
136
+ apiKey: options.apiKey,
137
+ baseUrl: options.baseUrl,
138
+ fetch: options.fetch
139
+ })).code.extractMachines(contents)).machines[0]?.config;
140
+ if (!config) throw new Error(`No machines extracted from ${filePath}`);
141
+ return {
142
+ kind: "local-file",
143
+ locator: filePath,
144
+ format: "xstate",
145
+ graph: fromXStateConfig(config)
146
+ };
147
+ }
148
+ const parsed = JSON.parse(contents);
149
+ if ("rootNode" in parsed && "edges" in parsed) return {
150
+ kind: "local-file",
151
+ locator: filePath,
152
+ format: "digraph",
153
+ graph: fromStudioMachine(parsed)
154
+ };
155
+ if ("nodes" in parsed && "edges" in parsed) return {
156
+ kind: "local-file",
157
+ locator: filePath,
158
+ format: "graph",
159
+ graph: parsed
160
+ };
161
+ if ("states" in parsed) return {
162
+ kind: "local-file",
163
+ locator: filePath,
164
+ format: "xstate",
165
+ graph: fromXStateConfig(parsed)
166
+ };
167
+ throw new Error(`Unsupported local sync input: ${filePath}`);
168
+ }
169
+ function inferWritableTargetFormat(filePath) {
170
+ if (filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".js") || filePath.endsWith(".jsx")) return "xstate";
171
+ if (filePath.endsWith(".digraph.json")) return "digraph";
172
+ if (filePath.endsWith(".graph.json")) return "graph";
173
+ return null;
174
+ }
175
+ function serializeGraph(graph, format) {
176
+ switch (format) {
177
+ case "digraph": return `${JSON.stringify(toStudioMachine(graph), null, 2)}\n`;
178
+ case "graph": return `${JSON.stringify(graph, null, 2)}\n`;
179
+ case "xstate": return graphToXStateTS(graph);
180
+ default: {
181
+ const exhaustive = format;
182
+ throw new Error(`Unsupported sync output format: ${exhaustive}`);
183
+ }
184
+ }
185
+ }
186
+ async function resolveRemoteMachine(machineId, baseUrl, kind, locator, options) {
187
+ return {
188
+ kind,
189
+ locator,
190
+ format: "digraph",
191
+ graph: fromStudioMachine(await (options.client ?? createStatelyClient({
192
+ apiKey: options.apiKey,
193
+ baseUrl,
194
+ fetch: options.fetch
195
+ })).machines.get(machineId))
196
+ };
197
+ }
198
+ async function resolveSyncInput(locator, options) {
199
+ if (await fileExists(path.resolve(options.cwd ?? process.cwd(), locator))) return resolveLocalFile(locator, options);
200
+ if (isUrl(locator)) {
201
+ const url = new URL(locator);
202
+ const machineId = url.pathname.split("/").filter(Boolean).at(-1);
203
+ if (!machineId) throw new Error(`Could not resolve machine ID from URL: ${locator}`);
204
+ return resolveRemoteMachine(machineId, url.origin, "studio-url", locator, options);
205
+ }
206
+ return resolveRemoteMachine(locator, options.baseUrl, "studio-machine-id", locator, options);
207
+ }
208
+ function summarizeDiff(diff) {
209
+ const nodeChanges = diff.nodes.added.length + diff.nodes.removed.length + diff.nodes.updated.length;
210
+ const edgeChanges = diff.edges.added.length + diff.edges.removed.length + diff.edges.updated.length;
211
+ return {
212
+ hasChanges: !isEmptyDiff(diff),
213
+ nodeChanges,
214
+ edgeChanges
215
+ };
216
+ }
217
+ async function planSync(options) {
218
+ const source = await resolveSyncInput(options.source, options);
219
+ const target = await resolveSyncInput(options.target, options);
220
+ const diff = getDiff(source.graph, target.graph);
221
+ return {
222
+ source,
223
+ target,
224
+ diff,
225
+ summary: summarizeDiff(diff),
226
+ warnings: []
227
+ };
228
+ }
229
+ async function pullSync(options) {
230
+ const source = await resolveSyncInput(options.source, options);
231
+ const outputPath = path.resolve(options.cwd ?? process.cwd(), options.target);
232
+ const fallbackFormat = inferWritableTargetFormat(outputPath);
233
+ let targetFormat = fallbackFormat;
234
+ if (await fileExists(outputPath)) try {
235
+ targetFormat = (await resolveLocalFile(options.target, options)).format;
236
+ } catch (error) {
237
+ if (!fallbackFormat) throw error;
238
+ }
239
+ if (!targetFormat) throw new Error(`Could not infer a writable target format from ${outputPath}. Use an existing digraph/graph file or a .digraph.json/.graph.json target.`);
240
+ const serialized = serializeGraph(source.graph, targetFormat);
241
+ await fs.writeFile(outputPath, serialized, "utf8");
242
+ return {
243
+ source,
244
+ target: {
245
+ kind: "local-file",
246
+ locator: outputPath,
247
+ format: targetFormat,
248
+ graph: source.graph
249
+ },
250
+ outputPath
251
+ };
252
+ }
253
+
254
+ //#endregion
5
255
  export { planSync, pullSync };