@statelyai/sdk 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +10 -1
  2. package/dist/assetStorage.d.mts +1 -1
  3. package/dist/auth.d.mts +1 -1
  4. package/dist/{statelyPragma-Cg1KzBZr.mjs → dist-BQEaIgBI.mjs} +172 -139
  5. package/dist/{editor-sync-types-DB1N6QUK.d.mts → editor-sync-types-CPpzTSnT.d.mts} +4 -0
  6. package/dist/{editorHostSession-vSt07IJV.d.mts → editorHostSession-BHr3WBHT.d.mts} +105 -6
  7. package/dist/{editorHostSession-DNpXPNAc.mjs → editorHostSession-Dm5i4mg_.mjs} +380 -20
  8. package/dist/editorHostSession.d.mts +2 -2
  9. package/dist/editorHostSession.mjs +3 -2
  10. package/dist/embed.d.mts +3 -4
  11. package/dist/embed.mjs +6 -2
  12. package/dist/{graph-5X1Ilppq.d.mts → graph-CehpcL7P.d.mts} +1 -1
  13. package/dist/graph.d.mts +1 -1
  14. package/dist/{index-DNDfA-YC.d.mts → index-ZlKF1x_z.d.mts} +81 -2
  15. package/dist/index.d.mts +8 -9
  16. package/dist/index.mjs +7 -6
  17. package/dist/{inspect-DYFQzEsh.mjs → inspect-BD6fDWzd.mjs} +1 -1
  18. package/dist/{inspect-D61HS-t7.d.mts → inspect-BgYRNJF9.d.mts} +1 -2
  19. package/dist/inspect.d.mts +2 -2
  20. package/dist/inspect.mjs +2 -2
  21. package/dist/patchTypes.d.mts +1 -1
  22. package/dist/protocol-DOt1Vz-5.d.mts +842 -0
  23. package/dist/protocol.d.mts +2 -819
  24. package/dist/relay.d.mts +1 -1
  25. package/dist/statelyPragma-D46lczJR.mjs +102 -0
  26. package/dist/{studio-QQRLjF5V.d.mts → studio-GZ6E_xns.d.mts} +34 -11
  27. package/dist/{studio-DpCW5V4a.mjs → studio-rSI54Ese.mjs} +149 -7
  28. package/dist/studio.d.mts +1 -1
  29. package/dist/studio.mjs +1 -1
  30. package/dist/sync.d.mts +2 -2
  31. package/dist/sync.mjs +74 -26
  32. package/dist/{version-BJPr6idb.mjs → version-DbnY8nLV.mjs} +4 -3
  33. package/package.json +3 -3
  34. package/schemas/statelyai.schema.json +6 -0
  35. package/dist/embedPanel-Bpbq4sfJ.d.mts +0 -13
  36. /package/dist/{auth-BPyCCHYo.d.mts → auth-Dg7prjeL.d.mts} +0 -0
package/dist/relay.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ProtocolMessage } from "./protocol.mjs";
1
+ import { dt as ProtocolMessage } from "./protocol-DOt1Vz-5.mjs";
2
2
 
3
3
  //#region src/relay.d.ts
4
4
  type InspectionRelayRole = 'producer' | 'viewer';
@@ -0,0 +1,102 @@
1
+ import ts from "typescript";
2
+
3
+ //#region src/statelyPragma.ts
4
+ function findStatelyPragmaAttachments(sourceText, fileName = "machine.ts") {
5
+ const sourceFile = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, true, getScriptKind(fileName));
6
+ const attachments = [];
7
+ const visit = (node) => {
8
+ if (ts.isCallExpression(node) && isCreateMachineExpression(node.expression)) {
9
+ const attachNode = findAttachNode(node);
10
+ if (attachNode) attachments.push({
11
+ machineStart: getMachineExpressionStart(node.expression, sourceFile),
12
+ attachStart: attachNode.getStart(sourceFile),
13
+ pragma: findAttachedStatelyPragma(sourceText, attachNode)
14
+ });
15
+ }
16
+ ts.forEachChild(node, visit);
17
+ };
18
+ visit(sourceFile);
19
+ return attachments;
20
+ }
21
+ function getStatelyPragma(sourceText, fileName = "machine.ts", machineIndex = 0) {
22
+ return findStatelyPragmaAttachments(sourceText, fileName)[machineIndex]?.pragma;
23
+ }
24
+ function upsertStatelyPragma(sourceText, id, options = {}) {
25
+ const attachment = findStatelyPragmaAttachments(sourceText, options.fileName ?? "machine.ts")[options.machineIndex ?? 0];
26
+ if (!attachment) return sourceText;
27
+ const lineEnding = options.lineEnding ?? detectLineEnding(sourceText);
28
+ const canonicalComment = `// @statelyai id=${id}`;
29
+ if (attachment.pragma) return sourceText.slice(0, attachment.pragma.start) + canonicalComment + sourceText.slice(attachment.pragma.end);
30
+ const insertText = `${getIndentationAtOffset(sourceText, attachment.attachStart)}${canonicalComment}${lineEnding}`;
31
+ return sourceText.slice(0, attachment.attachStart) + insertText + sourceText.slice(attachment.attachStart);
32
+ }
33
+ function findAttachedStatelyPragma(sourceText, node) {
34
+ const comments = ts.getLeadingCommentRanges(sourceText, node.getFullStart()) ?? [];
35
+ for (let index = comments.length - 1; index >= 0; index -= 1) {
36
+ const comment = comments[index];
37
+ const parsed = parseStatelyPragma(sourceText, comment.pos, comment.end);
38
+ if (parsed) return parsed;
39
+ }
40
+ }
41
+ function parseStatelyPragma(sourceText, start, end) {
42
+ const match = normalizeCommentContent(sourceText.slice(start, end)).match(/^@statelyai(?:\s+(.*))?$/s);
43
+ if (!match) return;
44
+ const fields = parseFields(match[1] ?? "");
45
+ return {
46
+ tag: "@statelyai",
47
+ id: fields.id,
48
+ fields,
49
+ start,
50
+ end
51
+ };
52
+ }
53
+ function normalizeCommentContent(rawComment) {
54
+ if (rawComment.startsWith("//")) return rawComment.slice(2).trim();
55
+ if (rawComment.startsWith("/*")) return rawComment.slice(2, rawComment.endsWith("*/") ? -2 : void 0).split(/\r?\n/).map((line) => line.replace(/^\s*\*\s?/, "")).join(" ").trim();
56
+ return rawComment.trim();
57
+ }
58
+ function parseFields(input) {
59
+ const fields = {};
60
+ for (const token of input.split(/\s+/)) {
61
+ if (!token) continue;
62
+ const equalsIndex = token.indexOf("=");
63
+ if (equalsIndex <= 0) continue;
64
+ const key = token.slice(0, equalsIndex);
65
+ const value = token.slice(equalsIndex + 1);
66
+ if (!key || !value) continue;
67
+ fields[key] = value;
68
+ }
69
+ return fields;
70
+ }
71
+ function findAttachNode(node) {
72
+ let current = node;
73
+ while (current?.parent) {
74
+ if (ts.isVariableStatement(current.parent) || ts.isExpressionStatement(current.parent) || ts.isExportAssignment(current.parent)) return current.parent;
75
+ current = current.parent;
76
+ }
77
+ return current;
78
+ }
79
+ function isCreateMachineExpression(expression) {
80
+ const isMachineFactoryName = (name) => name === "createMachine" || name === "createMachineFromConfig";
81
+ return ts.isIdentifier(expression) && isMachineFactoryName(expression.text) || ts.isPropertyAccessExpression(expression) && isMachineFactoryName(expression.name.text);
82
+ }
83
+ function getMachineExpressionStart(expression, sourceFile) {
84
+ if (ts.isPropertyAccessExpression(expression)) return expression.name.getStart(sourceFile);
85
+ return expression.getStart(sourceFile);
86
+ }
87
+ function getIndentationAtOffset(sourceText, offset) {
88
+ const lineStart = sourceText.lastIndexOf("\n", Math.max(0, offset - 1)) + 1;
89
+ return sourceText.slice(lineStart, offset).match(/^[ \t]*/)?.[0] ?? "";
90
+ }
91
+ function detectLineEnding(sourceText) {
92
+ return sourceText.includes("\r\n") ? "\r\n" : "\n";
93
+ }
94
+ function getScriptKind(fileName) {
95
+ if (fileName.endsWith(".tsx")) return ts.ScriptKind.TSX;
96
+ if (fileName.endsWith(".jsx")) return ts.ScriptKind.JSX;
97
+ if (fileName.endsWith(".js")) return ts.ScriptKind.JS;
98
+ return ts.ScriptKind.TS;
99
+ }
100
+
101
+ //#endregion
102
+ export { getStatelyPragma as n, upsertStatelyPragma as r, findStatelyPragmaAttachments as t };
@@ -1,5 +1,5 @@
1
- import { A as ZodOptional, D as ZodNullable, E as ZodLiteral, F as output, I as $loose, L as $strip, M as ZodString, N as ZodUnion, O as ZodNumber, P as ZodUnknown, T as ZodEnum, j as ZodRecord, k as ZodObject, w as ZodArray } from "./index-DNDfA-YC.mjs";
2
- import { n as StatelyCredential, t as StatelyAuthMode } from "./auth-BPyCCHYo.mjs";
1
+ import { A as ZodObject, D as ZodLiteral, E as ZodEnum, F as ZodUnknown, I as output, L as $loose, M as ZodRecord, N as ZodString, O as ZodNullable, P as ZodUnion, R as $strip, T as ZodBoolean, j as ZodOptional, k as ZodNumber, w as ZodArray } from "./index-ZlKF1x_z.mjs";
2
+ import { n as StatelyCredential, t as StatelyAuthMode } from "./auth-Dg7prjeL.mjs";
3
3
 
4
4
  //#region ../api-contract/dist/errors.d.mts
5
5
  /**
@@ -44,6 +44,17 @@ declare const verifyResultSchema: ZodObject<{
44
44
  }>;
45
45
  }, $strip>;
46
46
  type VerifyResult = output<typeof verifyResultSchema>;
47
+ /**
48
+ * Entitlements for the authenticated caller.
49
+ *
50
+ * Internal contract: this is not published as an `/api/v1` operation. Editor
51
+ * feature gating resolves it server-side through the resource provider and
52
+ * hands the mapped result to the client (see
53
+ * `packages/editor/src/entitlements`).
54
+ *
55
+ * `entitlements` is an open set of provider-defined strings; unknown values are
56
+ * ignored rather than rejected.
57
+ */
47
58
  declare const projectSummarySchema: ZodObject<{
48
59
  projectId: ZodString;
49
60
  projectVersionId: ZodString;
@@ -58,6 +69,16 @@ declare const projectSummarySchema: ZodObject<{
58
69
  updatedAt: ZodString;
59
70
  }, $strip>;
60
71
  type ProjectSummary = output<typeof projectSummarySchema>;
72
+ /**
73
+ * `name` and `updatedAt` are optional: some upstream project envelopes only
74
+ * return machine ids. Providers that can supply them cheaply should.
75
+ */
76
+ declare const projectMachineSummarySchema: ZodObject<{
77
+ machineId: ZodString;
78
+ name: ZodOptional<ZodString>;
79
+ updatedAt: ZodOptional<ZodString>;
80
+ }, $strip>;
81
+ type ProjectMachineSummary = output<typeof projectMachineSummarySchema>;
61
82
  declare const projectSchema: ZodObject<{
62
83
  projectId: ZodString;
63
84
  projectVersionId: ZodString;
@@ -73,18 +94,19 @@ declare const projectSchema: ZodObject<{
73
94
  rootMachineId: ZodNullable<ZodString>;
74
95
  machines: ZodArray<ZodObject<{
75
96
  machineId: ZodString;
97
+ name: ZodOptional<ZodString>;
98
+ updatedAt: ZodOptional<ZodString>;
76
99
  }, $strip>>;
100
+ permissions: ZodObject<{
101
+ canEdit: ZodBoolean;
102
+ }, $strip>;
103
+ allowedVisibility: ZodOptional<ZodArray<ZodEnum<{
104
+ public: "public";
105
+ unlisted: "unlisted";
106
+ private: "private";
107
+ }>>>;
77
108
  }, $strip>;
78
109
  type Project = output<typeof projectSchema>;
79
- /**
80
- * `name` is optional: the Registry project envelope only returns machine ids.
81
- * Providers that can supply names cheaply should.
82
- */
83
- declare const projectMachineSummarySchema: ZodObject<{
84
- machineId: ZodString;
85
- name: ZodOptional<ZodString>;
86
- }, $strip>;
87
- type ProjectMachineSummary = output<typeof projectMachineSummarySchema>;
88
110
  declare const machineSchema: ZodObject<{
89
111
  machineId: ZodString;
90
112
  name: ZodString;
@@ -159,6 +181,7 @@ declare const machineVersionSchema: ZodObject<{
159
181
  updatedAt: ZodString;
160
182
  }, $strip>;
161
183
  type MachineVersion = output<typeof machineVersionSchema>;
184
+ /** Version-history row without the definition payload. */
162
185
  declare const extractedMachinesSchema: ZodObject<{
163
186
  machines: ZodArray<ZodObject<{
164
187
  config: ZodRecord<ZodString, ZodUnknown>;
@@ -127,6 +127,24 @@ const verifyResultSchema = object({
127
127
  valid: literal(true),
128
128
  tokenScope: _enum(["user", "project"])
129
129
  });
130
+ /**
131
+ * Entitlements for the authenticated caller.
132
+ *
133
+ * Internal contract: this is not published as an `/api/v1` operation. Editor
134
+ * feature gating resolves it server-side through the resource provider and
135
+ * hands the mapped result to the client (see
136
+ * `packages/editor/src/entitlements`).
137
+ *
138
+ * `entitlements` is an open set of provider-defined strings; unknown values are
139
+ * ignored rather than rejected.
140
+ */
141
+ const entitlementsResultSchema = object({
142
+ subscription: object({
143
+ tier: string(),
144
+ status: string()
145
+ }).nullable(),
146
+ entitlements: array(string())
147
+ });
130
148
  const projectSummarySchema = object({
131
149
  projectId: string(),
132
150
  projectVersionId: string(),
@@ -136,17 +154,20 @@ const projectSummarySchema = object({
136
154
  createdAt: string(),
137
155
  updatedAt: string()
138
156
  });
139
- const projectSchema = projectSummarySchema.extend({
140
- rootMachineId: string().nullable(),
141
- machines: array(object({ machineId: string() }))
142
- });
143
157
  /**
144
- * `name` is optional: the Registry project envelope only returns machine ids.
145
- * Providers that can supply names cheaply should.
158
+ * `name` and `updatedAt` are optional: some upstream project envelopes only
159
+ * return machine ids. Providers that can supply them cheaply should.
146
160
  */
147
161
  const projectMachineSummarySchema = object({
148
162
  machineId: string(),
149
- name: string().optional()
163
+ name: string().optional(),
164
+ updatedAt: string().optional()
165
+ });
166
+ const projectSchema = projectSummarySchema.extend({
167
+ rootMachineId: string().nullable(),
168
+ machines: array(projectMachineSummarySchema),
169
+ permissions: object({ canEdit: boolean() }),
170
+ allowedVisibility: array(projectVisibilitySchema).optional()
150
171
  });
151
172
  const machineSchema = object({
152
173
  machineId: string(),
@@ -167,6 +188,67 @@ const machineVersionSchema = object({
167
188
  createdAt: string(),
168
189
  updatedAt: string()
169
190
  });
191
+ /** Version-history row without the definition payload. */
192
+ const machineVersionSummarySchema = object({
193
+ machineVersionId: string(),
194
+ machineId: string(),
195
+ versionNumber: number(),
196
+ name: string().nullable(),
197
+ status: string(),
198
+ parentVersionId: string().nullable(),
199
+ createdAt: string(),
200
+ updatedAt: string()
201
+ });
202
+ /** Result of converting a machine's stored definition to XGraph in place. */
203
+ const machinesConvertResultSchema = object({
204
+ machine: machineSchema,
205
+ created: boolean(),
206
+ version: object({
207
+ machineVersionId: string(),
208
+ versionNumber: number(),
209
+ name: string().nullable()
210
+ })
211
+ });
212
+ /**
213
+ * A project the caller may fork a machine into, with the version ids a fork
214
+ * can target. `projectVersionIds` is ordered as the provider reports it.
215
+ */
216
+ const projectDestinationProjectSchema = object({
217
+ projectId: string(),
218
+ name: string(),
219
+ visibility: projectVisibilitySchema,
220
+ projectVersionIds: array(string())
221
+ });
222
+ /**
223
+ * Fork destinations grouped by owner. The caller's personal projects are one
224
+ * owner alongside each team; `ownerId` is opaque and provider-defined.
225
+ */
226
+ const projectDestinationSchema = object({
227
+ ownerId: string(),
228
+ name: string(),
229
+ projects: array(projectDestinationProjectSchema)
230
+ });
231
+ /** Result of forking a machine into a new or existing project version. */
232
+ const machinesForkResultSchema = object({
233
+ machine: machineSchema,
234
+ projectVersionId: string(),
235
+ projectId: string()
236
+ });
237
+ /**
238
+ * The version holding a machine's pre-conversion (legacy editor) definition.
239
+ * `versionId` is `null` when the machine has no such version, which is the
240
+ * signal that the legacy editor cannot be re-entered for it.
241
+ */
242
+ const machineLegacyVersionSchema = object({ versionId: string().nullable() });
243
+ /** Result of restoring a machine's legacy-editor definition. */
244
+ const machinesRestoreLegacyResultSchema = object({
245
+ machine: machineSchema,
246
+ version: object({
247
+ machineVersionId: string(),
248
+ versionNumber: number(),
249
+ name: string().nullable()
250
+ })
251
+ });
170
252
  const extractedMachinesSchema = object({ machines: array(object({
171
253
  config: record(string(), unknown()),
172
254
  machineIndex: number().int().nonnegative().optional()
@@ -190,6 +272,40 @@ const machinesUpdateRequestSchema = object({
190
272
  name: string().min(1).optional(),
191
273
  definition: unknown().optional()
192
274
  }).refine((value) => value.name !== void 0 || value.definition !== void 0, { message: "At least one of `name` or `definition` is required." });
275
+ /**
276
+ * `status` is canonical lowercase; providers map it to their own casing.
277
+ * Omitting `definition` snapshots the machine's current definition.
278
+ */
279
+ const machineVersionsCreateRequestSchema = object({
280
+ name: string().min(1).optional(),
281
+ definition: unknown().optional(),
282
+ status: _enum(["committed", "auto"]).optional(),
283
+ parentVersionId: string().min(1).optional()
284
+ });
285
+ const machinesConvertRequestSchema = object({
286
+ definition: xgraphSchema,
287
+ expectedUpdatedAt: string().min(1),
288
+ keepOriginalVersion: boolean().optional()
289
+ });
290
+ /**
291
+ * Fork a machine into exactly one target: an existing project version, or a
292
+ * new project to create for it. Both, or neither, is a client bug.
293
+ */
294
+ const machinesForkRequestSchema = object({
295
+ targetProjectVersionId: string().min(1).optional(),
296
+ targetProject: object({
297
+ name: string().min(1),
298
+ visibility: projectVisibilitySchema,
299
+ teamId: string().min(1).optional()
300
+ }).optional(),
301
+ machineName: string().min(1).optional(),
302
+ xstateVersion: xstateVersionSchema.optional()
303
+ }).refine((value) => value.targetProjectVersionId === void 0 !== (value.targetProject === void 0), { message: "Exactly one of `targetProjectVersionId` or `targetProject` is required." });
304
+ const machinesRestoreLegacyRequestSchema = object({
305
+ versionId: string().min(1).optional(),
306
+ expectedUpdatedAt: string().min(1),
307
+ reason: string().optional()
308
+ });
193
309
  const codeExtractMachinesRequestSchema = object({
194
310
  code: string().min(1),
195
311
  xstateVersion: xstateVersionSchema.optional()
@@ -201,10 +317,17 @@ const projectsCreateResponseSchema = projectSchema;
201
317
  const projectsUpdateResponseSchema = projectSchema;
202
318
  const projectsDeleteResponseSchema = object({ projectId: string() });
203
319
  const projectsListMachinesResponseSchema = array(projectMachineSummarySchema);
320
+ const projectsDestinationsResponseSchema = array(projectDestinationSchema);
204
321
  const machinesCreateResponseSchema = machineSchema;
205
322
  const machinesGetResponseSchema = machineSchema;
206
323
  const machinesUpdateResponseSchema = machineSchema;
207
324
  const machinesGetVersionResponseSchema = machineVersionSchema;
325
+ const machineVersionsListResponseSchema = array(machineVersionSummarySchema);
326
+ const machineVersionsCreateResponseSchema = machineVersionSchema;
327
+ const machinesConvertDefinitionResponseSchema = machinesConvertResultSchema;
328
+ const machinesForkResponseSchema = machinesForkResultSchema;
329
+ const machinesGetLegacyVersionResponseSchema = machineLegacyVersionSchema;
330
+ const machinesRestoreLegacyResponseSchema = machinesRestoreLegacyResultSchema;
208
331
  const codeExtractMachinesResponseSchema = extractedMachinesSchema;
209
332
  /**
210
333
  * Request/response schema pairs keyed by resource capability name. Kept here
@@ -225,6 +348,7 @@ const resourceOperationSchemas = {
225
348
  },
226
349
  "projects.delete": { response: projectsDeleteResponseSchema },
227
350
  "projects.listMachines": { response: projectsListMachinesResponseSchema },
351
+ "projects.destinations": { response: projectsDestinationsResponseSchema },
228
352
  "machines.create": {
229
353
  request: machinesCreateRequestSchema,
230
354
  response: machinesCreateResponseSchema
@@ -234,6 +358,24 @@ const resourceOperationSchemas = {
234
358
  "machines.update": {
235
359
  request: machinesUpdateRequestSchema,
236
360
  response: machinesUpdateResponseSchema
361
+ },
362
+ "machines.versions.list": { response: machineVersionsListResponseSchema },
363
+ "machines.versions.create": {
364
+ request: machineVersionsCreateRequestSchema,
365
+ response: machineVersionsCreateResponseSchema
366
+ },
367
+ "machines.convertDefinition": {
368
+ request: machinesConvertRequestSchema,
369
+ response: machinesConvertDefinitionResponseSchema
370
+ },
371
+ "machines.fork": {
372
+ request: machinesForkRequestSchema,
373
+ response: machinesForkResponseSchema
374
+ },
375
+ "machines.getLegacyVersion": { response: machinesGetLegacyVersionResponseSchema },
376
+ "machines.restoreLegacy": {
377
+ request: machinesRestoreLegacyRequestSchema,
378
+ response: machinesRestoreLegacyResponseSchema
237
379
  }
238
380
  };
239
381
  /** Provider-independent operations implemented by this repository. */
package/dist/studio.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- 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, p as LegacyExtractMachinesOptions, 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-QQRLjF5V.mjs";
1
+ 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, p as LegacyExtractMachinesOptions, 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-GZ6E_xns.mjs";
2
2
  export { ConnectedRepo, CreateMachineFromDefinitionInput, CreateMachineFromTemplateInput, CreateMachineInput, CreateMachineTemplate, CreateProjectInput, DEFAULT_STATELY_BASE_URL, EnsureProjectInput, ExtractMachinesInput, ExtractMachinesResponse, ExtractedMachine, ExtractedMachines, GetMachineOptions, LegacyExtractMachinesOptions, LegacyProjectVisibility, LegacyUpdateMachineInput, Machine, MachineVersion, Project, ProjectData, ProjectMachine, ProjectMachineSummary, ProjectSummary, ProjectVisibility, RepoType, ResourceErrorCode, StudioApiError, StudioApiErrorOptions, StudioClient, StudioClientOptions, StudioMachineRecord, StudioRequestOptions, UpdateMachineInput, UpdateProjectInput, VerifyApiKeyResponse, VerifyResult, XStateVersion, createStatelyClient };
package/dist/studio.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  import "./openapi-BTDjYWXd.mjs";
2
- import { n as StudioApiError, r as createStatelyClient, t as DEFAULT_STATELY_BASE_URL } from "./studio-DpCW5V4a.mjs";
2
+ import { n as StudioApiError, r as createStatelyClient, t as DEFAULT_STATELY_BASE_URL } from "./studio-rSI54Ese.mjs";
3
3
 
4
4
  export { DEFAULT_STATELY_BASE_URL, StudioApiError, createStatelyClient };
package/dist/sync.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as DigraphConfig, i as StatelyGraph } from "./graph-5X1Ilppq.mjs";
2
- import { C as StudioMachineRecord, L as XStateVersion, g as ProjectData, o as CreateProjectInput, x as StudioClient } from "./studio-QQRLjF5V.mjs";
1
+ import { b as DigraphConfig, i as StatelyGraph } from "./graph-CehpcL7P.mjs";
2
+ import { C as StudioMachineRecord, L as XStateVersion, g as ProjectData, o as CreateProjectInput, x as StudioClient } from "./studio-GZ6E_xns.mjs";
3
3
  import { GraphDiff } from "@statelyai/graph";
4
4
 
5
5
  //#region src/sync.d.ts
package/dist/sync.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import "./openapi-BTDjYWXd.mjs";
2
- import { r as createStatelyClient } from "./studio-DpCW5V4a.mjs";
3
- import { b as serializeJS, c as detectXStateSourceProfile, f as graphChangeToPatchesResult, h as graphToXStateTS, i as INLINE_EXPRESSION_DIRECTIVE_FIELDS, l as diffGraphsSemantically, n as getStatelyPragma, o as alignCompareGraphIds, p as graphToMachineConfig, r as upsertStatelyPragma, t as findStatelyPragmaAttachments, v as normalizeMachineProfile, x as xstateSourceToConfig } from "./statelyPragma-Cg1KzBZr.mjs";
2
+ import { r as createStatelyClient } from "./studio-rSI54Ese.mjs";
3
+ import { a as detectXStateSourceProfile, c as extractXStateMachineConfigEntries, d as graphToMachineConfig, g as normalizeMachineProfile, o as diffGraphsSemantically, p as graphToXStateTS, r as alignCompareGraphIds, t as INLINE_EXPRESSION_DIRECTIVE_FIELDS, u as graphChangeToPatchesResult, v as serializeJS } from "./dist-BQEaIgBI.mjs";
4
+ import { n as getStatelyPragma, r as upsertStatelyPragma, t as findStatelyPragmaAttachments } from "./statelyPragma-D46lczJR.mjs";
4
5
  import { fromStudioMachine, toStudioMachine } from "./graph.mjs";
5
6
  import * as ts$1 from "typescript";
6
7
  import ts from "typescript";
@@ -580,9 +581,10 @@ function resolveIdentifierObject(expression, bindings) {
580
581
  }
581
582
  function resolveObjectLiteralProperty(objectLiteral, propertyName, bindings) {
582
583
  for (const property of objectLiteral.properties) {
583
- if (!ts$1.isPropertyAssignment(property)) continue;
584
+ if (!ts$1.isPropertyAssignment(property) && !ts$1.isShorthandPropertyAssignment(property)) continue;
584
585
  if (getPropertyNameText$2(property.name) !== propertyName) continue;
585
- const inlineObject = unwrapObjectLiteralExpression$1(property.initializer);
586
+ const initializer = ts$1.isShorthandPropertyAssignment(property) ? property.name : property.initializer;
587
+ const inlineObject = unwrapObjectLiteralExpression$1(initializer);
586
588
  if (inlineObject) return {
587
589
  object: inlineObject,
588
590
  kind: "inline",
@@ -591,15 +593,15 @@ function resolveObjectLiteralProperty(objectLiteral, propertyName, bindings) {
591
593
  uri: getSourceFileUri(property.getSourceFile()),
592
594
  bindings
593
595
  };
594
- if (ts$1.isIdentifier(property.initializer)) {
595
- const binding = bindings.get(property.initializer.text);
596
+ if (ts$1.isIdentifier(initializer)) {
597
+ const binding = bindings.get(initializer.text);
596
598
  if (binding?.kind !== "objectReference") return null;
597
599
  return {
598
600
  object: binding.node,
599
601
  kind: binding.kind,
600
- symbol: property.initializer.text,
602
+ symbol: initializer.text,
601
603
  keyRange: toSourceRange$1(property.getSourceFile(), property.name),
602
- referenceRange: toSourceRange$1(property.getSourceFile(), property.initializer),
604
+ referenceRange: toSourceRange$1(property.getSourceFile(), initializer),
603
605
  sourceFile: binding.sourceFile,
604
606
  uri: binding.uri,
605
607
  bindings: binding.bindings
@@ -809,7 +811,7 @@ function parseSourceToMachine(text, document, options = {}) {
809
811
  const statesText = readHydratedStatesObject(sourceLocations.statesObject.uri, sourceLocations.statesObject.range, sourceLocations.states, options.resolver);
810
812
  return statesText ? [{
811
813
  range: sourceLocations.statesObject.referenceRange,
812
- newText: statesText
814
+ newText: areSourceRangesEqual(sourceLocations.statesObject.referenceRange, sourceLocations.statesObject.keyRange) ? `states: ${statesText}` : statesText
813
815
  }] : [];
814
816
  })() : [];
815
817
  const importReplacements = collectHydratedImportReplacements(text, document, new Set([...sourceLocations.states.filter((location) => location.path.length === 1 && location.referenceRange).map((location) => location.symbol).filter((symbol) => typeof symbol === "string"), ...sourceLocations.statesObject?.symbol ? [sourceLocations.statesObject.symbol] : []]));
@@ -819,11 +821,15 @@ function parseSourceToMachine(text, document, options = {}) {
819
821
  ...statesObjectReplacements,
820
822
  ...importReplacements
821
823
  ].filter(removeOverlappingRanges).sort(compareSourceRangesDescending));
822
- if (sourceLocations.profile === "xstate-v6-alpha") {
824
+ if (sourceLocations.profile === "xstate-v6-alpha" || options.machineIndex !== void 0) {
823
825
  const importedTransitionSources = collectImportedXStateTransitionSources(text, document, options);
826
+ const parseText = importedTransitionSources.length ? `${hydratedText}\n${importedTransitionSources.join("\n")}` : hydratedText;
827
+ const selectedMachineIndex = options.machineIndex ?? 0;
828
+ const config = extractXStateMachineConfigEntries(parseText, { profile: sourceLocations.profile }).find((entry) => entry.machineIndex === selectedMachineIndex)?.config;
829
+ if (!config) throw new Error(`No machine at index ${selectedMachineIndex} was found in ${document.fileName}.`);
824
830
  return `import { createMachine } from "xstate";
825
831
 
826
- export const machine = createMachine(${serializeJS(xstateSourceToConfig(importedTransitionSources.length ? `${hydratedText}\n${importedTransitionSources.join("\n")}` : hydratedText, { profile: "xstate-v6-alpha" }), 0)});
832
+ export const machine = createMachine(${serializeJS(config, 0)});
827
833
  `;
828
834
  }
829
835
  return hydratedText;
@@ -1091,12 +1097,13 @@ function offsetAtRangePosition$1(sourceText, line, character) {
1091
1097
  function applyMachineToSource(machineConfig, document, options = {}) {
1092
1098
  if (!isMachineConfig(machineConfig)) return [];
1093
1099
  const sourceFile = createSourceFile(document, document.getText());
1094
- const machineConfigNode = findMachineConfigObjectLiteral(sourceFile, options.machineIndex);
1100
+ const machineConfigNode = getMappedRootObjectLiteral(document, sourceFile, options.sourceLocations) ?? findMachineConfigObjectLiteral(sourceFile, options.machineIndex);
1095
1101
  if (!machineConfigNode) return [];
1102
+ if (options.sourceUpdateStrategy === "rewrite") return addCodeImportReplacements(document, sourceFile, machineConfig, [createRewriteReplacement(document, sourceFile, machineConfigNode, machineConfig)]).sort(compareReplacementRangesDescending);
1096
1103
  const parsedPatches = parseGraphPatches(options.patches);
1097
1104
  const prevGraph = parseGraph(options.prevGraph);
1098
1105
  const nextGraph = parseGraph(options.nextGraph);
1099
- const rootNode = getMappedRootObjectLiteral(document, sourceFile, options.sourceLocations) ?? machineConfigNode;
1106
+ const rootNode = machineConfigNode;
1100
1107
  if (!parsedPatches || !prevGraph || !nextGraph || parsedPatches.length === 0) {
1101
1108
  if (wouldDeModularizeRootReplacement(options.sourceLocations)) return [];
1102
1109
  return [createReplacement(document, sourceFile, rootNode, machineConfig)];
@@ -1170,6 +1177,7 @@ async function applyMachineToSourceDocuments(machineConfig, document, options =
1170
1177
  const sourceFile = createSourceFile(document, document.getText());
1171
1178
  const machineConfigNode = getMappedRootObjectLiteral(document, sourceFile, options.sourceLocations) ?? findMachineConfigObjectLiteral(sourceFile, options.machineIndex);
1172
1179
  if (!machineConfigNode) return [];
1180
+ if (options.sourceUpdateStrategy === "rewrite") return addCodeImportReplacements(document, sourceFile, machineConfig, [createRewriteReplacement(document, sourceFile, machineConfigNode, machineConfig)]).sort(compareReplacementRangesDescending);
1173
1181
  const parsedPatches = parseGraphPatches(options.patches);
1174
1182
  const prevGraph = parseGraph(options.prevGraph);
1175
1183
  const nextGraph = parseGraph(options.nextGraph);
@@ -1318,8 +1326,8 @@ async function createTransitionReplacementForDocuments(document, sourceFile, mac
1318
1326
  if (transitionSource && transitionTarget.previousEventType === transitionTarget.eventType) return [createPropertyValueReplacement(targetDocument, targetSourceFile, transitionSource.eventProperty, nextTransitionValue)];
1319
1327
  if (transitionSource) return [createPropertyAssignmentReplacement(targetDocument, targetSourceFile, transitionSource.eventProperty, transitionTarget.eventType, nextTransitionValue)];
1320
1328
  const onObject = getObjectLiteralProperty(stateObject, "on");
1321
- if (onObject) return [createObjectLiteralPropertyInsertion(targetDocument, targetSourceFile, onObject, transitionTarget.eventType, nextTransitionValue)];
1322
- return [createObjectLiteralPropertyInsertion(targetDocument, targetSourceFile, stateObject, "on", { [transitionTarget.eventType]: nextTransitionValue })];
1329
+ if (onObject) return createObjectLiteralPropertyInsertion(targetDocument, targetSourceFile, onObject, transitionTarget.eventType, nextTransitionValue);
1330
+ return createObjectLiteralPropertyInsertion(targetDocument, targetSourceFile, stateObject, "on", { [transitionTarget.eventType]: nextTransitionValue });
1323
1331
  }
1324
1332
  async function createStatePropertiesReplacementForDocuments(document, sourceFile, machineConfigNode, machineConfig, path, propertyNames, sourceLocations, openTextDocument) {
1325
1333
  const nextStateConfig = getStateConfigByPath(machineConfig, path);
@@ -1484,8 +1492,30 @@ function createPropertyAssignmentReplacement(document, sourceFile, property, key
1484
1492
  return createOffsetReplacement(document, property.getStart(sourceFile), property.getEnd(), text);
1485
1493
  }
1486
1494
  function createObjectLiteralPropertyInsertion(document, sourceFile, objectLiteral, key, nextValue) {
1487
- const text = objectPropertyTextForInsertion(objectLiteral, printObjectLiteralProperty(key, nextValue, sourceFile, getFormattingContext(document, sourceFile, objectLiteral)));
1488
- return createOffsetReplacement(document, objectLiteral.properties.end, objectLiteral.properties.end, text);
1495
+ const propertyText = objectPropertyTextForInsertion(objectLiteral, printObjectLiteralProperty(key, nextValue, sourceFile, getFormattingContext(document, sourceFile, objectLiteral)));
1496
+ return createObjectPropertyInsertionReplacements(document, objectLiteral, getObjectLiteralPropertyInsertionOffset(sourceFile, objectLiteral), propertyText);
1497
+ }
1498
+ function getObjectLiteralPropertyInsertionOffset(sourceFile, objectLiteral) {
1499
+ const propertiesEnd = objectLiteral.properties.end;
1500
+ const objectEnd = objectLiteral.getEnd() - 1;
1501
+ const trailingTrivia = sourceFile.text.slice(propertiesEnd, objectEnd);
1502
+ const commentMatch = /^[ \t]*(\/\/|\/\*)/.exec(trailingTrivia);
1503
+ if (!commentMatch) return propertiesEnd;
1504
+ const commentStart = propertiesEnd + commentMatch.index + commentMatch[0].length - 2;
1505
+ if (commentMatch[1] === "//") {
1506
+ const lineFeed = sourceFile.text.indexOf("\n", commentStart);
1507
+ const lineEnd = lineFeed === -1 ? objectEnd : Math.min(lineFeed, objectEnd);
1508
+ return lineEnd > commentStart && sourceFile.text.charCodeAt(lineEnd - 1) === 13 ? lineEnd - 1 : lineEnd;
1509
+ }
1510
+ const commentEnd = sourceFile.text.indexOf("*/", commentStart + 2);
1511
+ return commentEnd === -1 ? propertiesEnd : Math.min(commentEnd + 2, objectEnd);
1512
+ }
1513
+ function createObjectPropertyInsertionReplacements(document, objectLiteral, insertionOffset, propertyText) {
1514
+ const propertiesEnd = objectLiteral.properties.end;
1515
+ const needsComma = objectLiteral.properties.length > 0 && !objectLiteral.properties.hasTrailingComma;
1516
+ const replacements = [createOffsetReplacement(document, insertionOffset, insertionOffset, `${needsComma && insertionOffset === propertiesEnd ? "," : ""}${propertyText}`)];
1517
+ if (needsComma && insertionOffset !== propertiesEnd) replacements.push(createOffsetReplacement(document, propertiesEnd, propertiesEnd, ","));
1518
+ return replacements;
1489
1519
  }
1490
1520
  function getArrayElementDeletionRange(sourceFile, arrayLiteral, element) {
1491
1521
  const elements = [...arrayLiteral.elements];
@@ -1582,14 +1612,16 @@ function createImplementationCreateReplacements(document, sourceFile, implementa
1582
1612
  if (!implementation.id || !implementationCode) return null;
1583
1613
  const categoryObject = getObjectLiteralProperty(implementationRoot, categoryName);
1584
1614
  if (!categoryObject) {
1585
- const text = objectPropertyTextForInsertion(implementationRoot, `${propertyNameTextForSource(categoryName)}: {\n${getIndentForNewObjectProperty(sourceFile, implementationRoot)}${propertyNameTextForSource(implementation.id)}: ${implementationCode},\n${getIndentForObjectClose(sourceFile, implementationRoot)}}`);
1586
- return [createOffsetReplacement(document, implementationRoot.properties.end, implementationRoot.properties.end, text)];
1615
+ const propertyText = objectPropertyTextForInsertion(implementationRoot, `${propertyNameTextForSource(categoryName)}: {\n${getIndentForNewObjectProperty(sourceFile, implementationRoot)}${propertyNameTextForSource(implementation.id)}: ${implementationCode},\n${getIndentForObjectClose(sourceFile, implementationRoot)}}`);
1616
+ return createObjectPropertyInsertionReplacements(document, implementationRoot, getObjectLiteralPropertyInsertionOffset(sourceFile, implementationRoot), propertyText);
1587
1617
  }
1588
- const text = objectPropertyTextForInsertion(categoryObject, `${propertyNameTextForSource(implementation.id)}: ${implementationCode}`);
1589
- return [createOffsetReplacement(document, categoryObject.properties.end, categoryObject.properties.end, text)];
1618
+ const propertyText = objectPropertyTextForInsertion(categoryObject, `${propertyNameTextForSource(implementation.id)}: ${implementationCode}`);
1619
+ return createObjectPropertyInsertionReplacements(document, categoryObject, getObjectLiteralPropertyInsertionOffset(sourceFile, categoryObject), propertyText);
1590
1620
  }
1591
1621
  function objectPropertyTextForInsertion(objectLiteral, propertyText) {
1592
- return `${objectLiteral.properties.length > 0 ? "," : ""}${getLineBreak(objectLiteral.getSourceFile())}${getIndentForNewObjectProperty(objectLiteral.getSourceFile(), objectLiteral)}${propertyText}`;
1622
+ const lineBreak = getLineBreak(objectLiteral.getSourceFile());
1623
+ const indent = getIndentForNewObjectProperty(objectLiteral.getSourceFile(), objectLiteral);
1624
+ return `${lineBreak}${indent}${propertyText.startsWith(indent) ? propertyText.slice(indent.length) : propertyText}`;
1593
1625
  }
1594
1626
  function getLineBreak(sourceFile) {
1595
1627
  return sourceFile.text.includes("\r\n") ? "\r\n" : "\n";
@@ -1885,7 +1917,7 @@ function getObjectLiteralPropertyDeletionRange(sourceFile, objectLiteral, proper
1885
1917
  const propertyEnd = property.getEnd();
1886
1918
  if (properties.length === 1) return {
1887
1919
  start: propertyStart,
1888
- end: propertyEnd
1920
+ end: objectLiteral.properties.hasTrailingComma ? objectLiteral.properties.end : propertyEnd
1889
1921
  };
1890
1922
  if (propertyIndex === properties.length - 1) {
1891
1923
  const previousProperty = properties[propertyIndex - 1];
@@ -2253,6 +2285,21 @@ function createReplacement(document, sourceFile, node, value) {
2253
2285
  newText: printExpression(valueToExpression(value, node), sourceFile, formatting)
2254
2286
  };
2255
2287
  }
2288
+ function createRewriteReplacement(document, sourceFile, node, value) {
2289
+ const start = document.positionAt(node.getStart(sourceFile));
2290
+ const end = document.positionAt(node.getEnd());
2291
+ const formatting = getFormattingContext(document, sourceFile, node);
2292
+ return {
2293
+ uri: getDocumentUri(document),
2294
+ range: {
2295
+ startLine: start.line,
2296
+ startChar: start.character,
2297
+ endLine: end.line,
2298
+ endChar: end.character
2299
+ },
2300
+ newText: printExpression(valueToExpression(value), sourceFile, formatting)
2301
+ };
2302
+ }
2256
2303
  function addCodeImportReplacements(document, sourceFile, machineConfig, replacements) {
2257
2304
  const importReplacements = createCodeImportReplacements(document, sourceFile, collectCodeImports(machineConfig));
2258
2305
  return [...replacements, ...importReplacements];
@@ -3164,11 +3211,12 @@ const xstateAdapter = {
3164
3211
  return collectXStateSourceLocations(text, document, options);
3165
3212
  },
3166
3213
  async applyMachineToDocument(machineConfig, document, options) {
3167
- const rootSourceLocation = collectXStateSourceLocations(document.getText(), document, { machineIndex: options?.machineIndex })?.root ?? options?.sourceLocations?.root;
3214
+ const detectedSourceLocations = collectXStateSourceLocations(document.getText(), document, { machineIndex: options?.machineIndex });
3215
+ const rootSourceLocation = options?.sourceLocations?.root ?? detectedSourceLocations?.root;
3168
3216
  const sanitizedMachineConfig = options?.preserveStatelyMetadata === false ? stripStatelyMetadata(machineConfig) : machineConfig;
3169
3217
  if (!options?.patches?.length) return [];
3170
3218
  const replacements = await applyMachineToSourceDocuments(sanitizedMachineConfig, document, options);
3171
- if (replacements.some(containsXStateExpressionPlaceholder) || replacements.some((replacement) => isImplicitRootReplacement(replacement, rootSourceLocation))) return [];
3219
+ if (replacements.some(containsXStateExpressionPlaceholder) || options?.sourceUpdateStrategy !== "rewrite" && replacements.some((replacement) => isImplicitRootReplacement(replacement, rootSourceLocation))) return [];
3172
3220
  return replacements;
3173
3221
  }
3174
3222
  };
@@ -3502,7 +3550,7 @@ async function extractMachinesFromLocalSource(sourcePath, contents, machineIndex
3502
3550
  return { machines: extractMachineConfigsFromAst(sourcePath, parseSourceToMachine(contents, createTextDocument(sourcePath, contents), {
3503
3551
  machineIndex,
3504
3552
  resolver: createFileSourceDocumentResolver()
3505
- }), machineIndex) };
3553
+ }), machineIndex === void 0 ? void 0 : 0) };
3506
3554
  } catch (error) {
3507
3555
  return {
3508
3556
  machines: [],