@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,3 +1,5 @@
1
+ import { createAuthorizationHeader, getCredentialToken } from "./auth.mjs";
2
+
1
3
  //#region \0rolldown/runtime.js
2
4
  var __defProp = Object.defineProperty;
3
5
  var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
@@ -13947,4 +13949,640 @@ var import_dist = require_dist();
13947
13949
  (0, import_dist.extendZodWithOpenApi)(external_exports);
13948
13950
 
13949
13951
  //#endregion
13950
- export { discriminatedUnion as a, object as c, union as d, unknown as f, custom as i, record as l, array as n, literal as o, boolean$1 as r, number$1 as s, _enum as t, string$1 as u };
13952
+ //#region ../api-contract/dist/errors.mjs
13953
+ /**
13954
+ * Error shape returned by every `/api/v1` machine operation (and by the shared
13955
+ * auth guard). Each operation registers its own error schema component in the
13956
+ * OpenAPI document, so this is a factory rather than a single shared instance.
13957
+ */
13958
+ function createApiErrorResponseSchema() {
13959
+ return object({
13960
+ error: string$1(),
13961
+ issues: array(unknown()).optional()
13962
+ });
13963
+ }
13964
+ const apiErrorResponseSchema = createApiErrorResponseSchema();
13965
+ /**
13966
+ * Canonical error codes for the `/api/v1` resource operations. Machine
13967
+ * operations keep the flat `{ error: string }` shape above unchanged; the
13968
+ * nested envelope below applies to resource operations only.
13969
+ */
13970
+ const resourceErrorCodeSchema = _enum([
13971
+ "bad_request",
13972
+ "unauthenticated",
13973
+ "forbidden",
13974
+ "not_found",
13975
+ "conflict",
13976
+ "payload_too_large",
13977
+ "rate_limited",
13978
+ "capability_disabled",
13979
+ "upstream_error",
13980
+ "internal_error"
13981
+ ]);
13982
+ /** Factory, matching `createApiErrorResponseSchema`, for per-route OpenAPI components. */
13983
+ function createResourceApiErrorResponseSchema() {
13984
+ return object({ error: object({
13985
+ code: resourceErrorCodeSchema,
13986
+ message: string$1(),
13987
+ issues: array(unknown()).optional(),
13988
+ retryable: boolean$1().optional()
13989
+ }) });
13990
+ }
13991
+ const resourceApiErrorResponseSchema = createResourceApiErrorResponseSchema();
13992
+
13993
+ //#endregion
13994
+ //#region ../api-contract/dist/xgraph.mjs
13995
+ const looseRecordSchema = record(string$1(), unknown());
13996
+ const pointSchema = object({
13997
+ x: number$1(),
13998
+ y: number$1()
13999
+ });
14000
+ const nodeDataSchema = looseRecordSchema.refine((data) => !("parentId" in data), "XGraph node data must not contain parentId; use node.parentId.");
14001
+ const xgraphNodeSchema = object({
14002
+ id: string$1(),
14003
+ type: string$1().optional(),
14004
+ parentId: string$1().nullable().optional(),
14005
+ sourceId: string$1().optional(),
14006
+ targetId: string$1().optional(),
14007
+ label: string$1().nullable().optional(),
14008
+ data: nodeDataSchema.optional(),
14009
+ x: number$1().optional(),
14010
+ y: number$1().optional(),
14011
+ width: number$1().optional(),
14012
+ height: number$1().optional(),
14013
+ position: pointSchema.optional(),
14014
+ dx: number$1().optional(),
14015
+ dy: number$1().optional()
14016
+ }).passthrough();
14017
+ const xgraphEdgeSchema = object({
14018
+ id: string$1(),
14019
+ type: string$1().optional(),
14020
+ sourceId: string$1(),
14021
+ targetId: string$1(),
14022
+ label: string$1().nullable().optional(),
14023
+ data: unknown(),
14024
+ x: number$1().optional(),
14025
+ y: number$1().optional(),
14026
+ width: number$1().optional(),
14027
+ height: number$1().optional(),
14028
+ position: pointSchema.optional(),
14029
+ dx: number$1().optional(),
14030
+ dy: number$1().optional()
14031
+ }).passthrough();
14032
+ /** XGraph wire shape accepted and emitted at API boundaries. */
14033
+ const xgraphSchema = object({
14034
+ xgraphSchemaVersion: literal("1.0.0").optional(),
14035
+ id: string$1(),
14036
+ type: string$1().optional(),
14037
+ parentId: string$1().nullable().optional(),
14038
+ initialNodeId: string$1().nullable().optional(),
14039
+ nodes: array(xgraphNodeSchema),
14040
+ edges: array(xgraphEdgeSchema),
14041
+ data: unknown().optional(),
14042
+ layout: unknown().nullable().optional(),
14043
+ annotations: array(unknown()).optional(),
14044
+ direction: _enum([
14045
+ "up",
14046
+ "down",
14047
+ "left",
14048
+ "right"
14049
+ ]).optional(),
14050
+ style: looseRecordSchema.optional()
14051
+ }).passthrough();
14052
+
14053
+ //#endregion
14054
+ //#region ../api-contract/dist/resources.mjs
14055
+ /**
14056
+ * Canonical schemas for persistent `/api/v1` resources plus the owned,
14057
+ * deterministic code-extraction operation.
14058
+ *
14059
+ * These models are canonical, not upstream-shaped: providers (e.g. the Stately
14060
+ * Registry adapter) are responsible for translating upstream envelopes,
14061
+ * identifier quirks and casing into these shapes. No `{ data }` envelope
14062
+ * appears anywhere; all timestamps are ISO strings.
14063
+ */
14064
+ /**
14065
+ * XState major versions the editor targets (see
14066
+ * `packages/editor/src/formats/xstate.ts`).
14067
+ */
14068
+ const xstateVersionSchema = union([literal(5), literal(6)]);
14069
+ const projectVisibilitySchema = _enum([
14070
+ "public",
14071
+ "unlisted",
14072
+ "private"
14073
+ ]);
14074
+ const verifyResultSchema = object({
14075
+ valid: literal(true),
14076
+ tokenScope: _enum(["user", "project"])
14077
+ });
14078
+ /**
14079
+ * Entitlements for the authenticated caller.
14080
+ *
14081
+ * Internal contract: this is not published as an `/api/v1` operation. Editor
14082
+ * feature gating resolves it server-side through the resource provider and
14083
+ * hands the mapped result to the client (see
14084
+ * `packages/editor/src/entitlements`).
14085
+ *
14086
+ * `entitlements` is an open set of provider-defined strings; unknown values are
14087
+ * ignored rather than rejected.
14088
+ */
14089
+ const entitlementsResultSchema = object({
14090
+ subscription: object({
14091
+ tier: string$1(),
14092
+ status: string$1()
14093
+ }).nullable(),
14094
+ entitlements: array(string$1())
14095
+ });
14096
+ /**
14097
+ * Which editor format a machine's stored definition is in: `digraph` is the
14098
+ * original (legacy) editor's format, `xgraph` the current one.
14099
+ */
14100
+ const machineDefinitionFormatSchema = _enum(["digraph", "xgraph"]);
14101
+ /**
14102
+ * `name` and `updatedAt` are optional: some upstream project envelopes only
14103
+ * return machine ids. Providers that can supply them cheaply should.
14104
+ */
14105
+ const projectMachineSummarySchema = object({
14106
+ machineId: string$1(),
14107
+ name: string$1().optional(),
14108
+ updatedAt: string$1().optional(),
14109
+ format: machineDefinitionFormatSchema.optional()
14110
+ });
14111
+ /**
14112
+ * A project list row. It carries the project's machine roster, not just its
14113
+ * metadata, so a client can mount a whole workspace from one `projects.list`
14114
+ * response and fetch definitions lazily.
14115
+ */
14116
+ const projectSummarySchema = object({
14117
+ projectId: string$1(),
14118
+ projectVersionId: string$1(),
14119
+ name: string$1(),
14120
+ description: string$1().nullable(),
14121
+ visibility: projectVisibilitySchema,
14122
+ createdAt: string$1(),
14123
+ updatedAt: string$1(),
14124
+ rootMachineId: string$1().nullable().optional(),
14125
+ machines: array(projectMachineSummarySchema).optional(),
14126
+ permissions: object({ canEdit: boolean$1() }).optional(),
14127
+ allowedVisibility: array(projectVisibilitySchema).optional()
14128
+ });
14129
+ const projectSchema = projectSummarySchema.extend({
14130
+ rootMachineId: string$1().nullable(),
14131
+ machines: array(projectMachineSummarySchema),
14132
+ permissions: object({ canEdit: boolean$1() })
14133
+ });
14134
+ const machineSchema = object({
14135
+ machineId: string$1(),
14136
+ name: string$1(),
14137
+ projectId: string$1().optional(),
14138
+ projectVersionId: string$1(),
14139
+ definition: unknown(),
14140
+ graph: xgraphSchema.optional(),
14141
+ createdAt: string$1().optional(),
14142
+ updatedAt: string$1().optional(),
14143
+ format: machineDefinitionFormatSchema.optional()
14144
+ });
14145
+ const machineVersionSchema = object({
14146
+ machineVersionId: string$1(),
14147
+ machineId: string$1(),
14148
+ versionNumber: number$1(),
14149
+ name: string$1(),
14150
+ definition: unknown(),
14151
+ createdAt: string$1(),
14152
+ updatedAt: string$1(),
14153
+ format: machineDefinitionFormatSchema.optional()
14154
+ });
14155
+ /** Version-history row without the definition payload. */
14156
+ const machineVersionSummarySchema = object({
14157
+ machineVersionId: string$1(),
14158
+ machineId: string$1(),
14159
+ versionNumber: number$1(),
14160
+ name: string$1().nullable(),
14161
+ status: string$1(),
14162
+ parentVersionId: string$1().nullable(),
14163
+ createdAt: string$1(),
14164
+ updatedAt: string$1(),
14165
+ format: machineDefinitionFormatSchema.optional()
14166
+ });
14167
+ /** Result of converting a machine's stored definition to XGraph in place. */
14168
+ const machinesConvertResultSchema = object({
14169
+ machine: machineSchema,
14170
+ created: boolean$1(),
14171
+ version: object({
14172
+ machineVersionId: string$1(),
14173
+ versionNumber: number$1(),
14174
+ name: string$1().nullable()
14175
+ })
14176
+ });
14177
+ /**
14178
+ * A project the caller may fork a machine into, with the version ids a fork
14179
+ * can target. `projectVersionIds` is ordered as the provider reports it.
14180
+ */
14181
+ const projectDestinationProjectSchema = object({
14182
+ projectId: string$1(),
14183
+ name: string$1(),
14184
+ visibility: projectVisibilitySchema,
14185
+ projectVersionIds: array(string$1())
14186
+ });
14187
+ /**
14188
+ * Fork destinations grouped by owner. The caller's personal projects are one
14189
+ * owner alongside each team; `ownerId` is opaque and provider-defined.
14190
+ */
14191
+ const projectDestinationSchema = object({
14192
+ ownerId: string$1(),
14193
+ name: string$1(),
14194
+ projects: array(projectDestinationProjectSchema)
14195
+ });
14196
+ /** Result of forking a machine into a new or existing project version. */
14197
+ const machinesForkResultSchema = object({
14198
+ machine: machineSchema,
14199
+ projectVersionId: string$1(),
14200
+ projectId: string$1()
14201
+ });
14202
+ /**
14203
+ * The version holding a machine's pre-conversion (legacy editor) definition.
14204
+ * `versionId` is `null` when the machine has no such version, which is the
14205
+ * signal that the legacy editor cannot be re-entered for it.
14206
+ */
14207
+ const machineLegacyVersionSchema = object({ versionId: string$1().nullable() });
14208
+ /** Result of restoring a machine's legacy-editor definition. */
14209
+ const machinesRestoreLegacyResultSchema = object({
14210
+ machine: machineSchema,
14211
+ version: object({
14212
+ machineVersionId: string$1(),
14213
+ versionNumber: number$1(),
14214
+ name: string$1().nullable()
14215
+ })
14216
+ });
14217
+ /**
14218
+ * Result of restoring a machine to one of its own versions.
14219
+ *
14220
+ * `capturedVersion` is the new version holding the machine's *pre-restore*
14221
+ * definition, so the restore itself is undoable. It is `null` when the restore
14222
+ * was a no-op (the machine already held that version's definition), which is
14223
+ * the signal that no history row was added.
14224
+ */
14225
+ const machinesRestoreVersionResultSchema = object({
14226
+ machine: machineSchema,
14227
+ capturedVersion: machineVersionSummarySchema.nullable()
14228
+ });
14229
+ const extractedMachinesSchema = object({ machines: array(object({
14230
+ config: record(string$1(), unknown()),
14231
+ machineIndex: number$1().int().nonnegative().optional()
14232
+ })) });
14233
+ const projectsCreateRequestSchema = object({
14234
+ name: string$1().min(1),
14235
+ visibility: projectVisibilitySchema
14236
+ });
14237
+ const projectsUpdateRequestSchema = object({
14238
+ name: string$1().min(1).optional(),
14239
+ description: string$1().nullable().optional(),
14240
+ visibility: projectVisibilitySchema.optional()
14241
+ }).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." });
14242
+ const machinesCreateRequestSchema = object({
14243
+ projectVersionId: string$1().min(1),
14244
+ xstateVersion: xstateVersionSchema,
14245
+ name: string$1().min(1).optional(),
14246
+ definition: unknown().optional()
14247
+ });
14248
+ const machinesUpdateRequestSchema = object({
14249
+ name: string$1().min(1).optional(),
14250
+ definition: unknown().optional(),
14251
+ expectedUpdatedAt: string$1().min(1).optional()
14252
+ }).refine((value) => value.name !== void 0 || value.definition !== void 0, { message: "At least one of `name` or `definition` is required." });
14253
+ /**
14254
+ * `status` is canonical lowercase; providers map it to their own casing.
14255
+ * Omitting `definition` snapshots the machine's current definition.
14256
+ */
14257
+ const machineVersionsCreateRequestSchema = object({
14258
+ name: string$1().min(1).optional(),
14259
+ definition: unknown().optional(),
14260
+ status: _enum(["committed", "auto"]).optional(),
14261
+ parentVersionId: string$1().min(1).optional()
14262
+ });
14263
+ const machinesConvertRequestSchema = object({
14264
+ definition: xgraphSchema,
14265
+ expectedUpdatedAt: string$1().min(1),
14266
+ keepOriginalVersion: boolean$1().optional()
14267
+ });
14268
+ /**
14269
+ * Fork a machine into exactly one target: an existing project version, or a
14270
+ * new project to create for it. Both, or neither, is a client bug.
14271
+ */
14272
+ const machinesForkRequestSchema = object({
14273
+ targetProjectVersionId: string$1().min(1).optional(),
14274
+ targetProject: object({
14275
+ name: string$1().min(1),
14276
+ visibility: projectVisibilitySchema,
14277
+ teamId: string$1().min(1).optional()
14278
+ }).optional(),
14279
+ machineName: string$1().min(1).optional(),
14280
+ xstateVersion: xstateVersionSchema.optional()
14281
+ }).refine((value) => value.targetProjectVersionId === void 0 !== (value.targetProject === void 0), { message: "Exactly one of `targetProjectVersionId` or `targetProject` is required." });
14282
+ const machinesRestoreLegacyRequestSchema = object({
14283
+ versionId: string$1().min(1).optional(),
14284
+ expectedUpdatedAt: string$1().min(1),
14285
+ reason: string$1().optional()
14286
+ });
14287
+ const machinesRestoreVersionRequestSchema = object({ expectedUpdatedAt: string$1().min(1).optional() });
14288
+ const codeExtractMachinesRequestSchema = object({
14289
+ code: string$1().min(1),
14290
+ xstateVersion: xstateVersionSchema.optional()
14291
+ });
14292
+ const authVerifyResponseSchema = verifyResultSchema;
14293
+ const projectsListResponseSchema = array(projectSummarySchema);
14294
+ const projectsGetResponseSchema = projectSchema;
14295
+ const projectsCreateResponseSchema = projectSchema;
14296
+ const projectsUpdateResponseSchema = projectSchema;
14297
+ const projectsDeleteResponseSchema = object({ projectId: string$1() });
14298
+ const projectsListMachinesResponseSchema = array(projectMachineSummarySchema);
14299
+ const projectsDestinationsResponseSchema = array(projectDestinationSchema);
14300
+ const machinesCreateResponseSchema = machineSchema;
14301
+ const machinesGetResponseSchema = machineSchema;
14302
+ const machinesUpdateResponseSchema = machineSchema;
14303
+ const machinesGetVersionResponseSchema = machineVersionSchema;
14304
+ const machineVersionsListResponseSchema = array(machineVersionSummarySchema);
14305
+ const machineVersionsCreateResponseSchema = machineVersionSchema;
14306
+ const machinesConvertDefinitionResponseSchema = machinesConvertResultSchema;
14307
+ const machinesForkResponseSchema = machinesForkResultSchema;
14308
+ const machinesGetLegacyVersionResponseSchema = machineLegacyVersionSchema;
14309
+ const machinesRestoreLegacyResponseSchema = machinesRestoreLegacyResultSchema;
14310
+ const machinesRestoreVersionResponseSchema = machinesRestoreVersionResultSchema;
14311
+ const codeExtractMachinesResponseSchema = extractedMachinesSchema;
14312
+ /**
14313
+ * Request/response schema pairs keyed by resource capability name. Kept here
14314
+ * rather than on the `Capability` metadata entries so that the capability
14315
+ * registry stays plain, serialisable data.
14316
+ */
14317
+ const resourceOperationSchemas = {
14318
+ "auth.verify": { response: authVerifyResponseSchema },
14319
+ "projects.list": { response: projectsListResponseSchema },
14320
+ "projects.create": {
14321
+ request: projectsCreateRequestSchema,
14322
+ response: projectsCreateResponseSchema
14323
+ },
14324
+ "projects.get": { response: projectsGetResponseSchema },
14325
+ "projects.update": {
14326
+ request: projectsUpdateRequestSchema,
14327
+ response: projectsUpdateResponseSchema
14328
+ },
14329
+ "projects.delete": { response: projectsDeleteResponseSchema },
14330
+ "projects.listMachines": { response: projectsListMachinesResponseSchema },
14331
+ "projects.destinations": { response: projectsDestinationsResponseSchema },
14332
+ "machines.create": {
14333
+ request: machinesCreateRequestSchema,
14334
+ response: machinesCreateResponseSchema
14335
+ },
14336
+ "machines.get": { response: machinesGetResponseSchema },
14337
+ "machines.getVersion": { response: machinesGetVersionResponseSchema },
14338
+ "machines.update": {
14339
+ request: machinesUpdateRequestSchema,
14340
+ response: machinesUpdateResponseSchema
14341
+ },
14342
+ "machines.versions.list": { response: machineVersionsListResponseSchema },
14343
+ "machines.versions.create": {
14344
+ request: machineVersionsCreateRequestSchema,
14345
+ response: machineVersionsCreateResponseSchema
14346
+ },
14347
+ "machines.convertDefinition": {
14348
+ request: machinesConvertRequestSchema,
14349
+ response: machinesConvertDefinitionResponseSchema
14350
+ },
14351
+ "machines.fork": {
14352
+ request: machinesForkRequestSchema,
14353
+ response: machinesForkResponseSchema
14354
+ },
14355
+ "machines.getLegacyVersion": { response: machinesGetLegacyVersionResponseSchema },
14356
+ "machines.restoreLegacy": {
14357
+ request: machinesRestoreLegacyRequestSchema,
14358
+ response: machinesRestoreLegacyResponseSchema
14359
+ },
14360
+ "machines.restoreVersion": {
14361
+ request: machinesRestoreVersionRequestSchema,
14362
+ response: machinesRestoreVersionResponseSchema
14363
+ }
14364
+ };
14365
+ /** Provider-independent operations implemented by this repository. */
14366
+ const codeOperationSchemas = { "code.extractMachines": {
14367
+ request: codeExtractMachinesRequestSchema,
14368
+ response: codeExtractMachinesResponseSchema
14369
+ } };
14370
+ /** Every owned API operation with a canonical request/response contract. */
14371
+ const operationSchemas = {
14372
+ ...resourceOperationSchemas,
14373
+ ...codeOperationSchemas
14374
+ };
14375
+
14376
+ //#endregion
14377
+ //#region src/studio.ts
14378
+ /**
14379
+ * Remote client for the owned Stately resource contract (`/api/v1/*`).
14380
+ *
14381
+ * Every method targets our own routes (never the legacy Registry API), sends
14382
+ * JSON bodies with a bearer credential, and validates responses against the
14383
+ * canonical Zod schemas from `@statelyai/api-contract`. Responses are canonical
14384
+ * values directly: there is no `{ data }` envelope. Errors use the nested
14385
+ * envelope `{ error: { code, message, issues?, retryable? } }`.
14386
+ */
14387
+ /** Default base URL of the editor/API deployment hosting `/api/v1`. */
14388
+ const DEFAULT_STATELY_BASE_URL = "https://editor.stately.ai";
14389
+ var StudioApiError = class extends Error {
14390
+ status;
14391
+ /** Canonical resource error code, when the server sent one. */
14392
+ code;
14393
+ issues;
14394
+ retryable;
14395
+ constructor(message, status, options = {}) {
14396
+ super(message);
14397
+ this.name = "StudioApiError";
14398
+ this.status = status;
14399
+ this.code = options.code;
14400
+ this.issues = options.issues;
14401
+ this.retryable = options.retryable;
14402
+ }
14403
+ };
14404
+ function getFetch(fetchImpl) {
14405
+ const resolvedFetch = fetchImpl ?? globalThis.fetch;
14406
+ if (!resolvedFetch) throw new Error("No fetch implementation available. Pass one via createStatelyClient({ fetch }).");
14407
+ return resolvedFetch;
14408
+ }
14409
+ function joinApiUrl(baseUrl, path) {
14410
+ return `${baseUrl.replace(/\/+$/, "")}/api/v1${path}`;
14411
+ }
14412
+ async function parseJson(response) {
14413
+ if (!response.headers.get("content-type")?.includes("application/json")) return null;
14414
+ return response.json().catch(() => null);
14415
+ }
14416
+ function toApiError(data, status) {
14417
+ const parsed = resourceApiErrorResponseSchema.safeParse(data);
14418
+ if (parsed.success) {
14419
+ const { code, message, issues, retryable } = parsed.data.error;
14420
+ return new StudioApiError(message, status, {
14421
+ code,
14422
+ issues,
14423
+ retryable
14424
+ });
14425
+ }
14426
+ if (typeof data === "object" && data !== null && "error" in data && typeof data.error === "string") return new StudioApiError(data.error, status);
14427
+ return new StudioApiError(`HTTP ${status}`, status);
14428
+ }
14429
+ function normalizeVisibility(visibility) {
14430
+ return visibility.toLowerCase();
14431
+ }
14432
+ function normalizeXStateVersion(xstateVersion) {
14433
+ return xstateVersion === void 0 || xstateVersion === 4 ? 5 : xstateVersion;
14434
+ }
14435
+ function normalizeExtractXStateVersion(xstateVersion) {
14436
+ return xstateVersion === 4 ? 5 : xstateVersion;
14437
+ }
14438
+ function withMachineAlias(machine) {
14439
+ return {
14440
+ ...machine,
14441
+ definition: machine.definition,
14442
+ id: machine.machineId
14443
+ };
14444
+ }
14445
+ function withProjectAlias(project) {
14446
+ return {
14447
+ ...project,
14448
+ id: project.projectVersionId
14449
+ };
14450
+ }
14451
+ function isCredentialLike(value) {
14452
+ if (typeof value === "string") return true;
14453
+ return typeof value === "object" && value !== null && "type" in value && (value.type === "api_key" || value.type === "oauth");
14454
+ }
14455
+ function createStatelyClient(options = {}) {
14456
+ const baseUrl = options.baseUrl ?? DEFAULT_STATELY_BASE_URL;
14457
+ const fetchImpl = getFetch(options.fetch);
14458
+ const defaultCredential = options.credential ?? (options.apiKey ? {
14459
+ type: "api_key",
14460
+ token: options.apiKey
14461
+ } : void 0);
14462
+ const defaultAuthMode = options.authMode ?? "auto";
14463
+ async function request(path, init, schema, requestOptions = {}) {
14464
+ const headers = new Headers(init.headers);
14465
+ const authMode = requestOptions.authMode ?? defaultAuthMode;
14466
+ const credential = requestOptions.credential ?? defaultCredential;
14467
+ if (authMode !== "none") {
14468
+ const token = getCredentialToken(credential);
14469
+ 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" });
14470
+ if (token && credential) headers.set("Authorization", createAuthorizationHeader(credential));
14471
+ }
14472
+ const response = await fetchImpl(joinApiUrl(baseUrl, path), {
14473
+ ...init,
14474
+ headers,
14475
+ ...requestOptions.signal ? { signal: requestOptions.signal } : {}
14476
+ });
14477
+ const data = await parseJson(response);
14478
+ if (!response.ok) throw toApiError(data, response.status);
14479
+ const parsed = schema.safeParse(data);
14480
+ if (!parsed.success) throw new StudioApiError(`Unexpected response for ${path}: ${parsed.error.message}`, response.status, {
14481
+ code: "internal_error",
14482
+ issues: [...parsed.error.issues]
14483
+ });
14484
+ return parsed.data;
14485
+ }
14486
+ function jsonInit(method, body) {
14487
+ return {
14488
+ method,
14489
+ headers: { "Content-Type": "application/json" },
14490
+ body: JSON.stringify(body)
14491
+ };
14492
+ }
14493
+ const projects = {
14494
+ list(requestOptions) {
14495
+ return request("/projects", { method: "GET" }, projectsListResponseSchema, requestOptions);
14496
+ },
14497
+ create(input, requestOptions) {
14498
+ return request("/projects", jsonInit("POST", {
14499
+ name: input.name,
14500
+ visibility: normalizeVisibility(input.visibility)
14501
+ }), projectSchema, requestOptions).then(withProjectAlias);
14502
+ },
14503
+ get(projectId, requestOptions) {
14504
+ return request(`/projects/${encodeURIComponent(projectId)}`, { method: "GET" }, projectSchema, requestOptions).then(withProjectAlias);
14505
+ },
14506
+ update(projectId, input, requestOptions) {
14507
+ return request(`/projects/${encodeURIComponent(projectId)}`, jsonInit("PATCH", {
14508
+ ...input.name !== void 0 ? { name: input.name } : {},
14509
+ ...input.description !== void 0 ? { description: input.description } : {},
14510
+ ...input.visibility !== void 0 ? { visibility: normalizeVisibility(input.visibility) } : {}
14511
+ }), projectSchema, requestOptions).then(withProjectAlias);
14512
+ },
14513
+ delete(projectId, requestOptions) {
14514
+ return request(`/projects/${encodeURIComponent(projectId)}`, { method: "DELETE" }, projectsDeleteResponseSchema, requestOptions);
14515
+ },
14516
+ listMachines(projectId, requestOptions) {
14517
+ return request(`/projects/${encodeURIComponent(projectId)}/machines`, { method: "GET" }, projectsListMachinesResponseSchema, requestOptions);
14518
+ },
14519
+ async ensure(input, requestOptions) {
14520
+ if (input.matchConnectedRepo !== false) {
14521
+ const match = (await projects.list(requestOptions)).find((candidate) => candidate.name === input.name);
14522
+ if (match) return projects.get(match.projectId, requestOptions);
14523
+ }
14524
+ return projects.create(input, requestOptions);
14525
+ }
14526
+ };
14527
+ const machines = {
14528
+ create(input, requestOptions) {
14529
+ return request("/machines", jsonInit("POST", {
14530
+ projectVersionId: input.projectVersionId,
14531
+ xstateVersion: normalizeXStateVersion(input.xstateVersion),
14532
+ ...input.name !== void 0 ? { name: input.name } : {},
14533
+ ...input.definition !== void 0 ? { definition: input.definition } : {}
14534
+ }), machineSchema, requestOptions).then((machine) => withMachineAlias(machine));
14535
+ },
14536
+ async createMany(input, requestOptions) {
14537
+ return [await machines.create(input, requestOptions)];
14538
+ },
14539
+ get(machineId, getOptions = {}) {
14540
+ return request(`/machines/${encodeURIComponent(machineId)}`, { method: "GET" }, machineSchema, getOptions).then((machine) => withMachineAlias(machine));
14541
+ },
14542
+ getVersion(machineId, versionId, requestOptions) {
14543
+ return request(`/machines/${encodeURIComponent(machineId)}/versions/${encodeURIComponent(versionId)}`, { method: "GET" }, machineVersionSchema, requestOptions);
14544
+ },
14545
+ update(machineIdOrInput, inputOrOptions, maybeOptions) {
14546
+ const machineId = typeof machineIdOrInput === "string" ? machineIdOrInput : machineIdOrInput.machineId ?? machineIdOrInput.id;
14547
+ if (!machineId) throw new StudioApiError("machines.update requires a machine id.", 400, { code: "bad_request" });
14548
+ const input = (typeof machineIdOrInput === "string" ? inputOrOptions : machineIdOrInput) ?? {};
14549
+ const requestOptions = typeof machineIdOrInput === "string" ? maybeOptions : inputOrOptions;
14550
+ return request(`/machines/${encodeURIComponent(machineId)}`, jsonInit("PATCH", {
14551
+ ...input.name !== void 0 ? { name: input.name } : {},
14552
+ ...input.definition !== void 0 ? { definition: input.definition } : {},
14553
+ ...input.expectedUpdatedAt !== void 0 ? { expectedUpdatedAt: input.expectedUpdatedAt } : {}
14554
+ }), machineSchema, requestOptions).then((machine) => withMachineAlias(machine));
14555
+ }
14556
+ };
14557
+ return {
14558
+ auth: { verify(credentialOrOptions, verifyOptions) {
14559
+ return request("/auth/verify", { method: "GET" }, verifyResultSchema, isCredentialLike(credentialOrOptions) ? {
14560
+ ...verifyOptions,
14561
+ credential: credentialOrOptions
14562
+ } : credentialOrOptions ?? verifyOptions ?? {});
14563
+ } },
14564
+ projects,
14565
+ machines,
14566
+ code: { extractMachines(codeOrInput, extractOptions = {}) {
14567
+ const input = typeof codeOrInput === "string" ? {
14568
+ code: codeOrInput,
14569
+ xstateVersion: extractOptions.xstateVersion
14570
+ } : codeOrInput;
14571
+ const legacyOptions = extractOptions;
14572
+ const credential = legacyOptions.credential ?? (legacyOptions.apiKey ? {
14573
+ type: "api_key",
14574
+ token: legacyOptions.apiKey
14575
+ } : void 0);
14576
+ return request("/code/extract-machines", jsonInit("POST", {
14577
+ code: input.code,
14578
+ xstateVersion: normalizeExtractXStateVersion(input.xstateVersion)
14579
+ }), extractedMachinesSchema, {
14580
+ ...extractOptions,
14581
+ credential
14582
+ });
14583
+ } }
14584
+ };
14585
+ }
14586
+
14587
+ //#endregion
14588
+ export { StudioApiError as n, createStatelyClient as r, DEFAULT_STATELY_BASE_URL as t };
@@ -1,5 +1,5 @@
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-A5CMACoO.mjs";
2
- import { n as StatelyCredential, t as StatelyAuthMode } from "./auth-CVFc85uF.mjs";
1
+ import { S as $strip, _ as ZodString, b as output, c as ZodArray, d as ZodLiteral, f as ZodNullable, g as ZodRecord, h as ZodOptional, l as ZodBoolean, m as ZodObject, p as ZodNumber, u as ZodEnum, v as ZodUnion, x as $loose, y as ZodUnknown } from "./index-CoxF4Saw.mjs";
2
+ import { StatelyAuthMode, StatelyCredential } from "./auth.mjs";
3
3
 
4
4
  //#region ../api-contract/dist/errors.d.mts
5
5
  /**
@@ -343,6 +343,8 @@ type CreateMachineTemplate = 'blank' | 'starter';
343
343
  interface UpdateMachineInput<TDefinition = unknown> {
344
344
  name?: string;
345
345
  definition?: TDefinition;
346
+ /** Reject the write if the machine changed after this timestamp. */
347
+ expectedUpdatedAt?: string;
346
348
  }
347
349
  /** @deprecated Pass the machine id as the first argument instead. */
348
350
  interface LegacyUpdateMachineInput<TDefinition = unknown> extends UpdateMachineInput<TDefinition> {
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-CFN3-0-2.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-DvEgrtk1.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
- import "./openapi-BTDjYWXd.mjs";
2
- import { n as StudioApiError, r as createStatelyClient, t as DEFAULT_STATELY_BASE_URL } from "./studio-BZP6DaIO.mjs";
1
+ import { n as StudioApiError, r as createStatelyClient, t as DEFAULT_STATELY_BASE_URL } from "./studio-DhzM6zFx.mjs";
2
+ import "./auth.mjs";
3
3
 
4
4
  export { DEFAULT_STATELY_BASE_URL, StudioApiError, createStatelyClient };