@statelyai/sdk 0.34.2 → 0.36.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 (39) hide show
  1. package/README.md +20 -34
  2. package/dist/assetStorage.d.mts +1 -1
  3. package/dist/auth.d.mts +14 -1
  4. package/dist/bin.mjs +1 -3
  5. package/dist/editor-sync-types-U5uryWOk.d.mts +55 -0
  6. package/dist/editorHostProtocol.d.mts +203 -0
  7. package/dist/{editorHostProtocol-B2_t3Le7.mjs → editorHostProtocol.mjs} +1 -1
  8. package/dist/embed.d.mts +3 -3
  9. package/dist/embed.mjs +2 -2
  10. package/dist/{graph-DVfx7FwN.d.mts → graph-B6xUxqR5.d.mts} +1 -1
  11. package/dist/graph.d.mts +1 -1
  12. package/dist/{index-A5CMACoO.d.mts → index-CoxF4Saw.d.mts} +8 -255
  13. package/dist/index.d.mts +8 -31
  14. package/dist/index.mjs +5 -9
  15. package/dist/{inspect-ZVDq9tK2.mjs → inspect-BoMln78S.mjs} +1 -1
  16. package/dist/{inspect-DBH9oOAd.d.mts → inspect-Douvt5k_.d.mts} +1 -1
  17. package/dist/inspect.d.mts +2 -2
  18. package/dist/inspect.mjs +2 -2
  19. package/dist/patchTypes.d.mts +1 -1
  20. package/dist/{protocol-CCf9j_SZ.d.mts → protocol-CP3DSl5u.d.mts} +27 -5
  21. package/dist/protocol.d.mts +1 -1
  22. package/dist/relay.d.mts +1 -1
  23. package/dist/{openapi-BTDjYWXd.mjs → studio-DhzM6zFx.mjs} +639 -1
  24. package/dist/{studio-CFN3-0-2.d.mts → studio-DvEgrtk1.d.mts} +4 -2
  25. package/dist/studio.d.mts +1 -1
  26. package/dist/studio.mjs +2 -2
  27. package/dist/{version-CUFh-PYe.mjs → version-DS2izNeF.mjs} +1 -1
  28. package/package.json +20 -16
  29. package/dist/auth-CVFc85uF.d.mts +0 -15
  30. package/dist/dist-DsOTTfYv.mjs +0 -8361
  31. package/dist/editor-sync-types-D7YYz6fb.d.mts +0 -98
  32. package/dist/editorHostSession-DCTHhBqC.mjs +0 -912
  33. package/dist/editorHostSession-yGUKdLjq.d.mts +0 -325
  34. package/dist/editorHostSession.d.mts +0 -2
  35. package/dist/editorHostSession.mjs +0 -6
  36. package/dist/statelyPragma-YtVaBuIe.mjs +0 -102
  37. package/dist/studio-BZP6DaIO.mjs +0 -638
  38. package/dist/sync.d.mts +0 -86
  39. package/dist/sync.mjs +0 -4646
@@ -1,638 +0,0 @@
1
- import { c as object, d as union, f as unknown, l as record, n as array, o as literal, r as boolean, s as number, t as _enum, u as string } from "./openapi-BTDjYWXd.mjs";
2
- import { createAuthorizationHeader, getCredentialToken } from "./auth.mjs";
3
-
4
- //#region ../api-contract/dist/errors.mjs
5
- /**
6
- * Error shape returned by every `/api/v1` machine operation (and by the shared
7
- * auth guard). Each operation registers its own error schema component in the
8
- * OpenAPI document, so this is a factory rather than a single shared instance.
9
- */
10
- function createApiErrorResponseSchema() {
11
- return object({
12
- error: string(),
13
- issues: array(unknown()).optional()
14
- });
15
- }
16
- const apiErrorResponseSchema = createApiErrorResponseSchema();
17
- /**
18
- * Canonical error codes for the `/api/v1` resource operations. Machine
19
- * operations keep the flat `{ error: string }` shape above unchanged; the
20
- * nested envelope below applies to resource operations only.
21
- */
22
- const resourceErrorCodeSchema = _enum([
23
- "bad_request",
24
- "unauthenticated",
25
- "forbidden",
26
- "not_found",
27
- "conflict",
28
- "payload_too_large",
29
- "rate_limited",
30
- "capability_disabled",
31
- "upstream_error",
32
- "internal_error"
33
- ]);
34
- /** Factory, matching `createApiErrorResponseSchema`, for per-route OpenAPI components. */
35
- function createResourceApiErrorResponseSchema() {
36
- return object({ error: object({
37
- code: resourceErrorCodeSchema,
38
- message: string(),
39
- issues: array(unknown()).optional(),
40
- retryable: boolean().optional()
41
- }) });
42
- }
43
- const resourceApiErrorResponseSchema = createResourceApiErrorResponseSchema();
44
-
45
- //#endregion
46
- //#region ../api-contract/dist/xgraph.mjs
47
- const looseRecordSchema = record(string(), unknown());
48
- const pointSchema = object({
49
- x: number(),
50
- y: number()
51
- });
52
- const nodeDataSchema = looseRecordSchema.refine((data) => !("parentId" in data), "XGraph node data must not contain parentId; use node.parentId.");
53
- const xgraphNodeSchema = object({
54
- id: string(),
55
- type: string().optional(),
56
- parentId: string().nullable().optional(),
57
- sourceId: string().optional(),
58
- targetId: string().optional(),
59
- label: string().nullable().optional(),
60
- data: nodeDataSchema.optional(),
61
- x: number().optional(),
62
- y: number().optional(),
63
- width: number().optional(),
64
- height: number().optional(),
65
- position: pointSchema.optional(),
66
- dx: number().optional(),
67
- dy: number().optional()
68
- }).passthrough();
69
- const xgraphEdgeSchema = object({
70
- id: string(),
71
- type: string().optional(),
72
- sourceId: string(),
73
- targetId: string(),
74
- label: string().nullable().optional(),
75
- data: unknown(),
76
- x: number().optional(),
77
- y: number().optional(),
78
- width: number().optional(),
79
- height: number().optional(),
80
- position: pointSchema.optional(),
81
- dx: number().optional(),
82
- dy: number().optional()
83
- }).passthrough();
84
- /** XGraph wire shape accepted and emitted at API boundaries. */
85
- const xgraphSchema = object({
86
- xgraphSchemaVersion: literal("1.0.0").optional(),
87
- id: string(),
88
- type: string().optional(),
89
- parentId: string().nullable().optional(),
90
- initialNodeId: string().nullable().optional(),
91
- nodes: array(xgraphNodeSchema),
92
- edges: array(xgraphEdgeSchema),
93
- data: unknown().optional(),
94
- layout: unknown().nullable().optional(),
95
- annotations: array(unknown()).optional(),
96
- direction: _enum([
97
- "up",
98
- "down",
99
- "left",
100
- "right"
101
- ]).optional(),
102
- style: looseRecordSchema.optional()
103
- }).passthrough();
104
-
105
- //#endregion
106
- //#region ../api-contract/dist/resources.mjs
107
- /**
108
- * Canonical schemas for persistent `/api/v1` resources plus the owned,
109
- * deterministic code-extraction operation.
110
- *
111
- * These models are canonical, not upstream-shaped: providers (e.g. the Stately
112
- * Registry adapter) are responsible for translating upstream envelopes,
113
- * identifier quirks and casing into these shapes. No `{ data }` envelope
114
- * appears anywhere; all timestamps are ISO strings.
115
- */
116
- /**
117
- * XState major versions the editor targets (see
118
- * `packages/editor/src/formats/xstate.ts`).
119
- */
120
- const xstateVersionSchema = union([literal(5), literal(6)]);
121
- const projectVisibilitySchema = _enum([
122
- "public",
123
- "unlisted",
124
- "private"
125
- ]);
126
- const verifyResultSchema = object({
127
- valid: literal(true),
128
- tokenScope: _enum(["user", "project"])
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
- });
148
- /**
149
- * Which editor format a machine's stored definition is in: `digraph` is the
150
- * original (legacy) editor's format, `xgraph` the current one.
151
- */
152
- const machineDefinitionFormatSchema = _enum(["digraph", "xgraph"]);
153
- /**
154
- * `name` and `updatedAt` are optional: some upstream project envelopes only
155
- * return machine ids. Providers that can supply them cheaply should.
156
- */
157
- const projectMachineSummarySchema = object({
158
- machineId: string(),
159
- name: string().optional(),
160
- updatedAt: string().optional(),
161
- format: machineDefinitionFormatSchema.optional()
162
- });
163
- /**
164
- * A project list row. It carries the project's machine roster, not just its
165
- * metadata, so a client can mount a whole workspace from one `projects.list`
166
- * response and fetch definitions lazily.
167
- */
168
- const projectSummarySchema = object({
169
- projectId: string(),
170
- projectVersionId: string(),
171
- name: string(),
172
- description: string().nullable(),
173
- visibility: projectVisibilitySchema,
174
- createdAt: string(),
175
- updatedAt: string(),
176
- rootMachineId: string().nullable().optional(),
177
- machines: array(projectMachineSummarySchema).optional(),
178
- permissions: object({ canEdit: boolean() }).optional(),
179
- allowedVisibility: array(projectVisibilitySchema).optional()
180
- });
181
- const projectSchema = projectSummarySchema.extend({
182
- rootMachineId: string().nullable(),
183
- machines: array(projectMachineSummarySchema),
184
- permissions: object({ canEdit: boolean() })
185
- });
186
- const machineSchema = object({
187
- machineId: string(),
188
- name: string(),
189
- projectId: string().optional(),
190
- projectVersionId: string(),
191
- definition: unknown(),
192
- graph: xgraphSchema.optional(),
193
- createdAt: string().optional(),
194
- updatedAt: string().optional(),
195
- format: machineDefinitionFormatSchema.optional()
196
- });
197
- const machineVersionSchema = object({
198
- machineVersionId: string(),
199
- machineId: string(),
200
- versionNumber: number(),
201
- name: string(),
202
- definition: unknown(),
203
- createdAt: string(),
204
- updatedAt: string(),
205
- format: machineDefinitionFormatSchema.optional()
206
- });
207
- /** Version-history row without the definition payload. */
208
- const machineVersionSummarySchema = object({
209
- machineVersionId: string(),
210
- machineId: string(),
211
- versionNumber: number(),
212
- name: string().nullable(),
213
- status: string(),
214
- parentVersionId: string().nullable(),
215
- createdAt: string(),
216
- updatedAt: string(),
217
- format: machineDefinitionFormatSchema.optional()
218
- });
219
- /** Result of converting a machine's stored definition to XGraph in place. */
220
- const machinesConvertResultSchema = object({
221
- machine: machineSchema,
222
- created: boolean(),
223
- version: object({
224
- machineVersionId: string(),
225
- versionNumber: number(),
226
- name: string().nullable()
227
- })
228
- });
229
- /**
230
- * A project the caller may fork a machine into, with the version ids a fork
231
- * can target. `projectVersionIds` is ordered as the provider reports it.
232
- */
233
- const projectDestinationProjectSchema = object({
234
- projectId: string(),
235
- name: string(),
236
- visibility: projectVisibilitySchema,
237
- projectVersionIds: array(string())
238
- });
239
- /**
240
- * Fork destinations grouped by owner. The caller's personal projects are one
241
- * owner alongside each team; `ownerId` is opaque and provider-defined.
242
- */
243
- const projectDestinationSchema = object({
244
- ownerId: string(),
245
- name: string(),
246
- projects: array(projectDestinationProjectSchema)
247
- });
248
- /** Result of forking a machine into a new or existing project version. */
249
- const machinesForkResultSchema = object({
250
- machine: machineSchema,
251
- projectVersionId: string(),
252
- projectId: string()
253
- });
254
- /**
255
- * The version holding a machine's pre-conversion (legacy editor) definition.
256
- * `versionId` is `null` when the machine has no such version, which is the
257
- * signal that the legacy editor cannot be re-entered for it.
258
- */
259
- const machineLegacyVersionSchema = object({ versionId: string().nullable() });
260
- /** Result of restoring a machine's legacy-editor definition. */
261
- const machinesRestoreLegacyResultSchema = object({
262
- machine: machineSchema,
263
- version: object({
264
- machineVersionId: string(),
265
- versionNumber: number(),
266
- name: string().nullable()
267
- })
268
- });
269
- /**
270
- * Result of restoring a machine to one of its own versions.
271
- *
272
- * `capturedVersion` is the new version holding the machine's *pre-restore*
273
- * definition, so the restore itself is undoable. It is `null` when the restore
274
- * was a no-op (the machine already held that version's definition), which is
275
- * the signal that no history row was added.
276
- */
277
- const machinesRestoreVersionResultSchema = object({
278
- machine: machineSchema,
279
- capturedVersion: machineVersionSummarySchema.nullable()
280
- });
281
- const extractedMachinesSchema = object({ machines: array(object({
282
- config: record(string(), unknown()),
283
- machineIndex: number().int().nonnegative().optional()
284
- })) });
285
- const projectsCreateRequestSchema = object({
286
- name: string().min(1),
287
- visibility: projectVisibilitySchema
288
- });
289
- const projectsUpdateRequestSchema = object({
290
- name: string().min(1).optional(),
291
- description: string().nullable().optional(),
292
- visibility: projectVisibilitySchema.optional()
293
- }).refine((value) => value.name !== void 0 || value.description !== void 0 || value.visibility !== void 0, { message: "At least one of `name`, `description` or `visibility` is required." });
294
- const machinesCreateRequestSchema = object({
295
- projectVersionId: string().min(1),
296
- xstateVersion: xstateVersionSchema,
297
- name: string().min(1).optional(),
298
- definition: unknown().optional()
299
- });
300
- const machinesUpdateRequestSchema = object({
301
- name: string().min(1).optional(),
302
- definition: unknown().optional()
303
- }).refine((value) => value.name !== void 0 || value.definition !== void 0, { message: "At least one of `name` or `definition` is required." });
304
- /**
305
- * `status` is canonical lowercase; providers map it to their own casing.
306
- * Omitting `definition` snapshots the machine's current definition.
307
- */
308
- const machineVersionsCreateRequestSchema = object({
309
- name: string().min(1).optional(),
310
- definition: unknown().optional(),
311
- status: _enum(["committed", "auto"]).optional(),
312
- parentVersionId: string().min(1).optional()
313
- });
314
- const machinesConvertRequestSchema = object({
315
- definition: xgraphSchema,
316
- expectedUpdatedAt: string().min(1),
317
- keepOriginalVersion: boolean().optional()
318
- });
319
- /**
320
- * Fork a machine into exactly one target: an existing project version, or a
321
- * new project to create for it. Both, or neither, is a client bug.
322
- */
323
- const machinesForkRequestSchema = object({
324
- targetProjectVersionId: string().min(1).optional(),
325
- targetProject: object({
326
- name: string().min(1),
327
- visibility: projectVisibilitySchema,
328
- teamId: string().min(1).optional()
329
- }).optional(),
330
- machineName: string().min(1).optional(),
331
- xstateVersion: xstateVersionSchema.optional()
332
- }).refine((value) => value.targetProjectVersionId === void 0 !== (value.targetProject === void 0), { message: "Exactly one of `targetProjectVersionId` or `targetProject` is required." });
333
- const machinesRestoreLegacyRequestSchema = object({
334
- versionId: string().min(1).optional(),
335
- expectedUpdatedAt: string().min(1),
336
- reason: string().optional()
337
- });
338
- const machinesRestoreVersionRequestSchema = object({ expectedUpdatedAt: string().min(1).optional() });
339
- const codeExtractMachinesRequestSchema = object({
340
- code: string().min(1),
341
- xstateVersion: xstateVersionSchema.optional()
342
- });
343
- const authVerifyResponseSchema = verifyResultSchema;
344
- const projectsListResponseSchema = array(projectSummarySchema);
345
- const projectsGetResponseSchema = projectSchema;
346
- const projectsCreateResponseSchema = projectSchema;
347
- const projectsUpdateResponseSchema = projectSchema;
348
- const projectsDeleteResponseSchema = object({ projectId: string() });
349
- const projectsListMachinesResponseSchema = array(projectMachineSummarySchema);
350
- const projectsDestinationsResponseSchema = array(projectDestinationSchema);
351
- const machinesCreateResponseSchema = machineSchema;
352
- const machinesGetResponseSchema = machineSchema;
353
- const machinesUpdateResponseSchema = machineSchema;
354
- const machinesGetVersionResponseSchema = machineVersionSchema;
355
- const machineVersionsListResponseSchema = array(machineVersionSummarySchema);
356
- const machineVersionsCreateResponseSchema = machineVersionSchema;
357
- const machinesConvertDefinitionResponseSchema = machinesConvertResultSchema;
358
- const machinesForkResponseSchema = machinesForkResultSchema;
359
- const machinesGetLegacyVersionResponseSchema = machineLegacyVersionSchema;
360
- const machinesRestoreLegacyResponseSchema = machinesRestoreLegacyResultSchema;
361
- const machinesRestoreVersionResponseSchema = machinesRestoreVersionResultSchema;
362
- const codeExtractMachinesResponseSchema = extractedMachinesSchema;
363
- /**
364
- * Request/response schema pairs keyed by resource capability name. Kept here
365
- * rather than on the `Capability` metadata entries so that the capability
366
- * registry stays plain, serialisable data.
367
- */
368
- const resourceOperationSchemas = {
369
- "auth.verify": { response: authVerifyResponseSchema },
370
- "projects.list": { response: projectsListResponseSchema },
371
- "projects.create": {
372
- request: projectsCreateRequestSchema,
373
- response: projectsCreateResponseSchema
374
- },
375
- "projects.get": { response: projectsGetResponseSchema },
376
- "projects.update": {
377
- request: projectsUpdateRequestSchema,
378
- response: projectsUpdateResponseSchema
379
- },
380
- "projects.delete": { response: projectsDeleteResponseSchema },
381
- "projects.listMachines": { response: projectsListMachinesResponseSchema },
382
- "projects.destinations": { response: projectsDestinationsResponseSchema },
383
- "machines.create": {
384
- request: machinesCreateRequestSchema,
385
- response: machinesCreateResponseSchema
386
- },
387
- "machines.get": { response: machinesGetResponseSchema },
388
- "machines.getVersion": { response: machinesGetVersionResponseSchema },
389
- "machines.update": {
390
- request: machinesUpdateRequestSchema,
391
- response: machinesUpdateResponseSchema
392
- },
393
- "machines.versions.list": { response: machineVersionsListResponseSchema },
394
- "machines.versions.create": {
395
- request: machineVersionsCreateRequestSchema,
396
- response: machineVersionsCreateResponseSchema
397
- },
398
- "machines.convertDefinition": {
399
- request: machinesConvertRequestSchema,
400
- response: machinesConvertDefinitionResponseSchema
401
- },
402
- "machines.fork": {
403
- request: machinesForkRequestSchema,
404
- response: machinesForkResponseSchema
405
- },
406
- "machines.getLegacyVersion": { response: machinesGetLegacyVersionResponseSchema },
407
- "machines.restoreLegacy": {
408
- request: machinesRestoreLegacyRequestSchema,
409
- response: machinesRestoreLegacyResponseSchema
410
- },
411
- "machines.restoreVersion": {
412
- request: machinesRestoreVersionRequestSchema,
413
- response: machinesRestoreVersionResponseSchema
414
- }
415
- };
416
- /** Provider-independent operations implemented by this repository. */
417
- const codeOperationSchemas = { "code.extractMachines": {
418
- request: codeExtractMachinesRequestSchema,
419
- response: codeExtractMachinesResponseSchema
420
- } };
421
- /** Every owned API operation with a canonical request/response contract. */
422
- const operationSchemas = {
423
- ...resourceOperationSchemas,
424
- ...codeOperationSchemas
425
- };
426
-
427
- //#endregion
428
- //#region src/studio.ts
429
- /**
430
- * Remote client for the owned Stately resource contract (`/api/v1/*`).
431
- *
432
- * Every method targets our own routes (never the legacy Registry API), sends
433
- * JSON bodies with a bearer credential, and validates responses against the
434
- * canonical Zod schemas from `@statelyai/api-contract`. Responses are canonical
435
- * values directly: there is no `{ data }` envelope. Errors use the nested
436
- * envelope `{ error: { code, message, issues?, retryable? } }`.
437
- */
438
- /** Default base URL of the editor/API deployment hosting `/api/v1`. */
439
- const DEFAULT_STATELY_BASE_URL = "https://editor.stately.ai";
440
- var StudioApiError = class extends Error {
441
- status;
442
- /** Canonical resource error code, when the server sent one. */
443
- code;
444
- issues;
445
- retryable;
446
- constructor(message, status, options = {}) {
447
- super(message);
448
- this.name = "StudioApiError";
449
- this.status = status;
450
- this.code = options.code;
451
- this.issues = options.issues;
452
- this.retryable = options.retryable;
453
- }
454
- };
455
- function getFetch(fetchImpl) {
456
- const resolvedFetch = fetchImpl ?? globalThis.fetch;
457
- if (!resolvedFetch) throw new Error("No fetch implementation available. Pass one via createStatelyClient({ fetch }).");
458
- return resolvedFetch;
459
- }
460
- function joinApiUrl(baseUrl, path) {
461
- return `${baseUrl.replace(/\/+$/, "")}/api/v1${path}`;
462
- }
463
- async function parseJson(response) {
464
- if (!response.headers.get("content-type")?.includes("application/json")) return null;
465
- return response.json().catch(() => null);
466
- }
467
- function toApiError(data, status) {
468
- const parsed = resourceApiErrorResponseSchema.safeParse(data);
469
- if (parsed.success) {
470
- const { code, message, issues, retryable } = parsed.data.error;
471
- return new StudioApiError(message, status, {
472
- code,
473
- issues,
474
- retryable
475
- });
476
- }
477
- if (typeof data === "object" && data !== null && "error" in data && typeof data.error === "string") return new StudioApiError(data.error, status);
478
- return new StudioApiError(`HTTP ${status}`, status);
479
- }
480
- function normalizeVisibility(visibility) {
481
- return visibility.toLowerCase();
482
- }
483
- function normalizeXStateVersion(xstateVersion) {
484
- return xstateVersion === void 0 || xstateVersion === 4 ? 5 : xstateVersion;
485
- }
486
- function normalizeExtractXStateVersion(xstateVersion) {
487
- return xstateVersion === 4 ? 5 : xstateVersion;
488
- }
489
- function withMachineAlias(machine) {
490
- return {
491
- ...machine,
492
- definition: machine.definition,
493
- id: machine.machineId
494
- };
495
- }
496
- function withProjectAlias(project) {
497
- return {
498
- ...project,
499
- id: project.projectVersionId
500
- };
501
- }
502
- function isCredentialLike(value) {
503
- if (typeof value === "string") return true;
504
- return typeof value === "object" && value !== null && "type" in value && (value.type === "api_key" || value.type === "oauth");
505
- }
506
- function createStatelyClient(options = {}) {
507
- const baseUrl = options.baseUrl ?? DEFAULT_STATELY_BASE_URL;
508
- const fetchImpl = getFetch(options.fetch);
509
- const defaultCredential = options.credential ?? (options.apiKey ? {
510
- type: "api_key",
511
- token: options.apiKey
512
- } : void 0);
513
- const defaultAuthMode = options.authMode ?? "auto";
514
- async function request(path, init, schema, requestOptions = {}) {
515
- const headers = new Headers(init.headers);
516
- const authMode = requestOptions.authMode ?? defaultAuthMode;
517
- const credential = requestOptions.credential ?? defaultCredential;
518
- if (authMode !== "none") {
519
- const token = getCredentialToken(credential);
520
- if (authMode === "bearer" && (!token || !credential)) throw new StudioApiError("No Stately credential configured. Pass createStatelyClient({ credential }) or use authMode: \"auto\" to let the server decide whether authentication is required.", 401, { code: "unauthenticated" });
521
- if (token && credential) headers.set("Authorization", createAuthorizationHeader(credential));
522
- }
523
- const response = await fetchImpl(joinApiUrl(baseUrl, path), {
524
- ...init,
525
- headers,
526
- ...requestOptions.signal ? { signal: requestOptions.signal } : {}
527
- });
528
- const data = await parseJson(response);
529
- if (!response.ok) throw toApiError(data, response.status);
530
- const parsed = schema.safeParse(data);
531
- if (!parsed.success) throw new StudioApiError(`Unexpected response for ${path}: ${parsed.error.message}`, response.status, {
532
- code: "internal_error",
533
- issues: [...parsed.error.issues]
534
- });
535
- return parsed.data;
536
- }
537
- function jsonInit(method, body) {
538
- return {
539
- method,
540
- headers: { "Content-Type": "application/json" },
541
- body: JSON.stringify(body)
542
- };
543
- }
544
- const projects = {
545
- list(requestOptions) {
546
- return request("/projects", { method: "GET" }, projectsListResponseSchema, requestOptions);
547
- },
548
- create(input, requestOptions) {
549
- return request("/projects", jsonInit("POST", {
550
- name: input.name,
551
- visibility: normalizeVisibility(input.visibility)
552
- }), projectSchema, requestOptions).then(withProjectAlias);
553
- },
554
- get(projectId, requestOptions) {
555
- return request(`/projects/${encodeURIComponent(projectId)}`, { method: "GET" }, projectSchema, requestOptions).then(withProjectAlias);
556
- },
557
- update(projectId, input, requestOptions) {
558
- return request(`/projects/${encodeURIComponent(projectId)}`, jsonInit("PATCH", {
559
- ...input.name !== void 0 ? { name: input.name } : {},
560
- ...input.description !== void 0 ? { description: input.description } : {},
561
- ...input.visibility !== void 0 ? { visibility: normalizeVisibility(input.visibility) } : {}
562
- }), projectSchema, requestOptions).then(withProjectAlias);
563
- },
564
- delete(projectId, requestOptions) {
565
- return request(`/projects/${encodeURIComponent(projectId)}`, { method: "DELETE" }, projectsDeleteResponseSchema, requestOptions);
566
- },
567
- listMachines(projectId, requestOptions) {
568
- return request(`/projects/${encodeURIComponent(projectId)}/machines`, { method: "GET" }, projectsListMachinesResponseSchema, requestOptions);
569
- },
570
- async ensure(input, requestOptions) {
571
- if (input.matchConnectedRepo !== false) {
572
- const match = (await projects.list(requestOptions)).find((candidate) => candidate.name === input.name);
573
- if (match) return projects.get(match.projectId, requestOptions);
574
- }
575
- return projects.create(input, requestOptions);
576
- }
577
- };
578
- const machines = {
579
- create(input, requestOptions) {
580
- return request("/machines", jsonInit("POST", {
581
- projectVersionId: input.projectVersionId,
582
- xstateVersion: normalizeXStateVersion(input.xstateVersion),
583
- ...input.name !== void 0 ? { name: input.name } : {},
584
- ...input.definition !== void 0 ? { definition: input.definition } : {}
585
- }), machineSchema, requestOptions).then((machine) => withMachineAlias(machine));
586
- },
587
- async createMany(input, requestOptions) {
588
- return [await machines.create(input, requestOptions)];
589
- },
590
- get(machineId, getOptions = {}) {
591
- return request(`/machines/${encodeURIComponent(machineId)}`, { method: "GET" }, machineSchema, getOptions).then((machine) => withMachineAlias(machine));
592
- },
593
- getVersion(machineId, versionId, requestOptions) {
594
- return request(`/machines/${encodeURIComponent(machineId)}/versions/${encodeURIComponent(versionId)}`, { method: "GET" }, machineVersionSchema, requestOptions);
595
- },
596
- update(machineIdOrInput, inputOrOptions, maybeOptions) {
597
- const machineId = typeof machineIdOrInput === "string" ? machineIdOrInput : machineIdOrInput.machineId ?? machineIdOrInput.id;
598
- if (!machineId) throw new StudioApiError("machines.update requires a machine id.", 400, { code: "bad_request" });
599
- const input = (typeof machineIdOrInput === "string" ? inputOrOptions : machineIdOrInput) ?? {};
600
- const requestOptions = typeof machineIdOrInput === "string" ? maybeOptions : inputOrOptions;
601
- return request(`/machines/${encodeURIComponent(machineId)}`, jsonInit("PATCH", {
602
- ...input.name !== void 0 ? { name: input.name } : {},
603
- ...input.definition !== void 0 ? { definition: input.definition } : {}
604
- }), machineSchema, requestOptions).then((machine) => withMachineAlias(machine));
605
- }
606
- };
607
- return {
608
- auth: { verify(credentialOrOptions, verifyOptions) {
609
- return request("/auth/verify", { method: "GET" }, verifyResultSchema, isCredentialLike(credentialOrOptions) ? {
610
- ...verifyOptions,
611
- credential: credentialOrOptions
612
- } : credentialOrOptions ?? verifyOptions ?? {});
613
- } },
614
- projects,
615
- machines,
616
- code: { extractMachines(codeOrInput, extractOptions = {}) {
617
- const input = typeof codeOrInput === "string" ? {
618
- code: codeOrInput,
619
- xstateVersion: extractOptions.xstateVersion
620
- } : codeOrInput;
621
- const legacyOptions = extractOptions;
622
- const credential = legacyOptions.credential ?? (legacyOptions.apiKey ? {
623
- type: "api_key",
624
- token: legacyOptions.apiKey
625
- } : void 0);
626
- return request("/code/extract-machines", jsonInit("POST", {
627
- code: input.code,
628
- xstateVersion: normalizeExtractXStateVersion(input.xstateVersion)
629
- }), extractedMachinesSchema, {
630
- ...extractOptions,
631
- credential
632
- });
633
- } }
634
- };
635
- }
636
-
637
- //#endregion
638
- export { StudioApiError as n, createStatelyClient as r, DEFAULT_STATELY_BASE_URL as t };