@sphereon/ssi-sdk.xstate-machine-persistence 0.36.1-next.11 → 0.36.1-next.115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -52,7 +52,9 @@ var require_plugin_schema = __commonJS({
52
52
  type: "string"
53
53
  }
54
54
  },
55
- required: ["instanceId"],
55
+ required: [
56
+ "instanceId"
57
+ ],
56
58
  additionalProperties: false
57
59
  },
58
60
  MachineStateGetArgs: {
@@ -109,7 +111,15 @@ var require_plugin_schema = __commonJS({
109
111
  type: "string"
110
112
  }
111
113
  },
112
- required: ["createdAt", "instanceId", "latestEventType", "machineName", "state", "updatedAt", "updatedCount"]
114
+ required: [
115
+ "createdAt",
116
+ "instanceId",
117
+ "latestEventType",
118
+ "machineName",
119
+ "state",
120
+ "updatedAt",
121
+ "updatedCount"
122
+ ]
113
123
  },
114
124
  SerializableState: {
115
125
  $ref: "#/components/schemas/XStateConfig<any,AnyEventObject>"
@@ -125,7 +135,10 @@ var require_plugin_schema = __commonJS({
125
135
  $ref: "#/components/schemas/SCXML.Event<AnyEventObject>"
126
136
  },
127
137
  _sessionid: {
128
- type: ["string", "null"]
138
+ type: [
139
+ "string",
140
+ "null"
141
+ ]
129
142
  },
130
143
  historyValue: {
131
144
  $ref: "#/components/schemas/HistoryValue"
@@ -162,7 +175,15 @@ var require_plugin_schema = __commonJS({
162
175
  },
163
176
  machine: {}
164
177
  },
165
- required: ["value", "context", "_event", "_sessionid", "configuration", "transitions", "children"],
178
+ required: [
179
+ "value",
180
+ "context",
181
+ "_event",
182
+ "_sessionid",
183
+ "configuration",
184
+ "transitions",
185
+ "children"
186
+ ],
166
187
  additionalProperties: false,
167
188
  description: "The configuration for the XState machine state. Simplified StateConfig object from XState so we have a minimal typed structure"
168
189
  },
@@ -192,7 +213,11 @@ var require_plugin_schema = __commonJS({
192
213
  },
193
214
  type: {
194
215
  type: "string",
195
- enum: ["platform", "internal", "external"],
216
+ enum: [
217
+ "platform",
218
+ "internal",
219
+ "external"
220
+ ],
196
221
  description: `This field describes the event type. The SCXML Processor must set it to: "platform" (for events raised by the platform itself, such as error events), "internal" (for events raised by <raise> and <send> with target '_internal') or "external" (for all other events).`
197
222
  },
198
223
  sendid: {
@@ -220,7 +245,12 @@ var require_plugin_schema = __commonJS({
220
245
  const: "scxml"
221
246
  }
222
247
  },
223
- required: ["name", "type", "data", "$$type"],
248
+ required: [
249
+ "name",
250
+ "type",
251
+ "data",
252
+ "$$type"
253
+ ],
224
254
  additionalProperties: false
225
255
  },
226
256
  AnyEventObject: {
@@ -231,7 +261,9 @@ var require_plugin_schema = __commonJS({
231
261
  description: "The type of event that is sent."
232
262
  }
233
263
  },
234
- required: ["type"]
264
+ required: [
265
+ "type"
266
+ ]
235
267
  },
236
268
  HistoryValue: {
237
269
  type: "object",
@@ -243,7 +275,9 @@ var require_plugin_schema = __commonJS({
243
275
  $ref: "#/components/schemas/StateValue"
244
276
  }
245
277
  },
246
- required: ["states"],
278
+ required: [
279
+ "states"
280
+ ],
247
281
  additionalProperties: false
248
282
  },
249
283
  "Record<string,(interface-434048446-6094-6223-434048446-0-57488|undefined)>": {
@@ -269,7 +303,9 @@ var require_plugin_schema = __commonJS({
269
303
  type: "number"
270
304
  }
271
305
  },
272
- required: ["size"],
306
+ required: [
307
+ "size"
308
+ ],
273
309
  additionalProperties: false
274
310
  },
275
311
  InitMachineStateArgs: {
@@ -307,11 +343,16 @@ var require_plugin_schema = __commonJS({
307
343
  $ref: "#/components/schemas/MachineStateInfo"
308
344
  }
309
345
  },
310
- required: ["machineName"]
346
+ required: [
347
+ "machineName"
348
+ ]
311
349
  },
312
350
  MachineStateInitType: {
313
351
  type: "string",
314
- enum: ["new", "existing"]
352
+ enum: [
353
+ "new",
354
+ "existing"
355
+ ]
315
356
  },
316
357
  MachineStateInit: {
317
358
  type: "object",
@@ -343,7 +384,12 @@ var require_plugin_schema = __commonJS({
343
384
  description: "Represents the expiration date"
344
385
  }
345
386
  },
346
- required: ["createdAt", "instanceId", "machineName", "stateType"]
387
+ required: [
388
+ "createdAt",
389
+ "instanceId",
390
+ "machineName",
391
+ "stateType"
392
+ ]
347
393
  },
348
394
  MachineStatePersistArgs: {
349
395
  type: "object",
@@ -381,7 +427,12 @@ var require_plugin_schema = __commonJS({
381
427
  $ref: "#/components/schemas/MachineStateInfo"
382
428
  }
383
429
  },
384
- required: ["instanceId", "machineName", "state", "stateType"],
430
+ required: [
431
+ "instanceId",
432
+ "machineName",
433
+ "state",
434
+ "stateType"
435
+ ],
385
436
  description: "Represents the arguments required to persist the machine state."
386
437
  },
387
438
  DeleteExpiredStatesArgs: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../plugin.schema.json","../src/index.ts","../src/agent/MachineStatePersistence.ts","../src/functions/machineRegistration.ts","../src/types/types.ts","../src/functions/stateEventEmitter.ts","../src/functions/stateMapper.ts"],"sourcesContent":["{\n \"IMachineStatePersistence\": {\n \"components\": {\n \"schemas\": {\n \"MachineStateDeleteArgs\": {\n \"$ref\": \"#/components/schemas/Pick<StoreMachineStateInfo,(\\\"instanceId\\\"|\\\"tenantId\\\")>\"\n },\n \"Pick<StoreMachineStateInfo,(\\\"instanceId\\\"|\\\"tenantId\\\")>\": {\n \"type\": \"object\",\n \"properties\": {\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\"instanceId\"],\n \"additionalProperties\": false\n },\n \"MachineStateGetArgs\": {\n \"$ref\": \"#/components/schemas/Pick<StoreMachineStateInfo,(\\\"instanceId\\\"|\\\"tenantId\\\")>\"\n },\n \"MachineStateInfo\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"state\": {\n \"$ref\": \"#/components/schemas/SerializableState\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"sessionId\": {\n \"type\": \"string\",\n \"description\": \"Session Id of the machine. Not necessarily unique\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"latestStateName\": {\n \"type\": \"string\",\n \"description\": \"The latest state name. Can be empty for a newly initialize machine\"\n },\n \"latestEventType\": {\n \"type\": \"string\",\n \"description\": \"event types like SET_TOC, SET_FIRSTNAME, .... Will be xstate.init on a newly initialized machine\"\n },\n \"createdAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the creation date\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n },\n \"updatedAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the update date\"\n },\n \"updatedCount\": {\n \"type\": \"number\",\n \"description\": \"Represents a counter for tracking updates.\"\n },\n \"completedAt\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\"createdAt\", \"instanceId\", \"latestEventType\", \"machineName\", \"state\", \"updatedAt\", \"updatedCount\"]\n },\n \"SerializableState\": {\n \"$ref\": \"#/components/schemas/XStateConfig<any,AnyEventObject>\"\n },\n \"XStateConfig<any,AnyEventObject>\": {\n \"type\": \"object\",\n \"properties\": {\n \"value\": {\n \"$ref\": \"#/components/schemas/StateValue\"\n },\n \"context\": {},\n \"_event\": {\n \"$ref\": \"#/components/schemas/SCXML.Event<AnyEventObject>\"\n },\n \"_sessionid\": {\n \"type\": [\"string\", \"null\"]\n },\n \"historyValue\": {\n \"$ref\": \"#/components/schemas/HistoryValue\"\n },\n \"history\": {},\n \"actions\": {\n \"type\": \"array\",\n \"items\": {}\n },\n \"activities\": {},\n \"meta\": {},\n \"events\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/AnyEventObject\"\n }\n },\n \"configuration\": {\n \"type\": \"array\",\n \"items\": {}\n },\n \"transitions\": {\n \"type\": \"array\",\n \"items\": {}\n },\n \"children\": {\n \"$ref\": \"#/components/schemas/Record<string,any>\"\n },\n \"done\": {\n \"type\": \"boolean\"\n },\n \"tags\": {\n \"$ref\": \"#/components/schemas/Set<string>\"\n },\n \"machine\": {}\n },\n \"required\": [\"value\", \"context\", \"_event\", \"_sessionid\", \"configuration\", \"transitions\", \"children\"],\n \"additionalProperties\": false,\n \"description\": \"The configuration for the XState machine state. Simplified StateConfig object from XState so we have a minimal typed structure\"\n },\n \"StateValue\": {\n \"anyOf\": [\n {\n \"type\": \"string\"\n },\n {\n \"$ref\": \"#/components/schemas/StateValueMap\"\n }\n ],\n \"description\": \"The string or object representing the state value relative to the parent state node.\\n\\n- For a child atomic state node, this is a string, e.g., `\\\"pending\\\"`.\\n- For complex state nodes, this is an object, e.g., `{ success: \\\"someChildState\\\" }`.\"\n },\n \"StateValueMap\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"$ref\": \"#/components/schemas/StateValue\"\n }\n },\n \"SCXML.Event<AnyEventObject>\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"This is a character string giving the name of the event. The SCXML Processor must set the name field to the name of this event. It is what is matched against the 'event' attribute of <transition>. Note that transitions can do additional tests by using the value of this field inside boolean expressions in the 'cond' attribute.\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\"platform\", \"internal\", \"external\"],\n \"description\": \"This field describes the event type. The SCXML Processor must set it to: \\\"platform\\\" (for events raised by the platform itself, such as error events), \\\"internal\\\" (for events raised by <raise> and <send> with target '_internal') or \\\"external\\\" (for all other events).\"\n },\n \"sendid\": {\n \"type\": \"string\",\n \"description\": \"If the sending entity has specified a value for this, the Processor must set this field to that value (see C Event I/O Processors for details). Otherwise, in the case of error events triggered by a failed attempt to send an event, the Processor must set this field to the send id of the triggering <send> element. Otherwise it must leave it blank.\"\n },\n \"origin\": {\n \"type\": \"string\",\n \"description\": \"This is a URI, equivalent to the 'target' attribute on the <send> element. For external events, the SCXML Processor should set this field to a value which, when used as the value of 'target', will allow the receiver of the event to <send> a response back to the originating entity via the Event I/O Processor specified in 'origintype'. For internal and platform events, the Processor must leave this field blank.\"\n },\n \"origintype\": {\n \"type\": \"string\",\n \"description\": \"This is equivalent to the 'type' field on the <send> element. For external events, the SCXML Processor should set this field to a value which, when used as the value of 'type', will allow the receiver of the event to <send> a response back to the originating entity at the URI specified by 'origin'. For internal and platform events, the Processor must leave this field blank.\"\n },\n \"invokeid\": {\n \"type\": \"string\",\n \"description\": \"If this event is generated from an invoked child process, the SCXML Processor must set this field to the invoke id of the invocation that triggered the child process. Otherwise it must leave it blank.\"\n },\n \"data\": {\n \"$ref\": \"#/components/schemas/AnyEventObject\",\n \"description\": \"This field contains whatever data the sending entity chose to include in this event. The receiving SCXML Processor should reformat this data to match its data model, but must not otherwise modify it.\\n\\nIf the conversion is not possible, the Processor must leave the field blank and must place an error 'error.execution' in the internal event queue.\"\n },\n \"$$type\": {\n \"type\": \"string\",\n \"const\": \"scxml\"\n }\n },\n \"required\": [\"name\", \"type\", \"data\", \"$$type\"],\n \"additionalProperties\": false\n },\n \"AnyEventObject\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"The type of event that is sent.\"\n }\n },\n \"required\": [\"type\"]\n },\n \"HistoryValue\": {\n \"type\": \"object\",\n \"properties\": {\n \"states\": {\n \"$ref\": \"#/components/schemas/Record<string,(interface-434048446-6094-6223-434048446-0-57488|undefined)>\"\n },\n \"current\": {\n \"$ref\": \"#/components/schemas/StateValue\"\n }\n },\n \"required\": [\"states\"],\n \"additionalProperties\": false\n },\n \"Record<string,(interface-434048446-6094-6223-434048446-0-57488|undefined)>\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [\n {\n \"$ref\": \"#/components/schemas/HistoryValue\"\n },\n {\n \"not\": {}\n }\n ]\n }\n },\n \"Record<string,any>\": {\n \"type\": \"object\"\n },\n \"Set<string>\": {\n \"type\": \"object\",\n \"properties\": {\n \"size\": {\n \"type\": \"number\"\n }\n },\n \"required\": [\"size\"],\n \"additionalProperties\": false\n },\n \"InitMachineStateArgs\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"cleanupAllOtherInstances\": {\n \"type\": \"boolean\"\n },\n \"customInstanceId\": {\n \"type\": \"string\"\n },\n \"existingInstanceId\": {\n \"type\": \"string\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"createdAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the creation date\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n },\n \"stateType\": {\n \"$ref\": \"#/components/schemas/MachineStateInitType\"\n },\n \"machineState\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"required\": [\"machineName\"]\n },\n \"MachineStateInitType\": {\n \"type\": \"string\",\n \"enum\": [\"new\", \"existing\"]\n },\n \"MachineStateInit\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"stateType\": {\n \"$ref\": \"#/components/schemas/MachineStateInitType\"\n },\n \"machineState\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"createdAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the creation date\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n }\n },\n \"required\": [\"createdAt\", \"instanceId\", \"machineName\", \"stateType\"]\n },\n \"MachineStatePersistArgs\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"cleanupOnFinalState\": {\n \"type\": \"boolean\"\n },\n \"updatedCount\": {\n \"type\": \"number\",\n \"description\": \"Represents a counter for tracking updates.\"\n },\n \"state\": {\n \"$ref\": \"#/components/schemas/SerializableState\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n },\n \"stateType\": {\n \"$ref\": \"#/components/schemas/MachineStateInitType\"\n },\n \"machineState\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"required\": [\"instanceId\", \"machineName\", \"state\", \"stateType\"],\n \"description\": \"Represents the arguments required to persist the machine state.\"\n },\n \"DeleteExpiredStatesArgs\": {\n \"$ref\": \"#/components/schemas/Pick<StoreMachineStateDeleteExpiredArgs,(\\\"deleteDoneStates\\\"|\\\"machineName\\\"|\\\"tenantId\\\")>\",\n \"description\": \"Represents the arguments for deleting expired states from a machine.\"\n },\n \"Pick<StoreMachineStateDeleteExpiredArgs,(\\\"deleteDoneStates\\\"|\\\"machineName\\\"|\\\"tenantId\\\")>\": {\n \"type\": \"object\",\n \"properties\": {\n \"deleteDoneStates\": {\n \"type\": \"boolean\"\n },\n \"machineName\": {\n \"type\": \"string\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n },\n \"DeleteStateResult\": {\n \"type\": \"number\"\n },\n \"FindActiveStatesArgs\": {\n \"$ref\": \"#/components/schemas/StoreMachineStatesFindActiveArgs\",\n \"description\": \"Represents the arguments for finding active states of a store machine.\"\n },\n \"StoreMachineStatesFindActiveArgs\": {\n \"$ref\": \"#/components/schemas/Partial<Pick<StoreMachineStateInfo,(\\\"machineName\\\"|\\\"tenantId\\\"|\\\"instanceId\\\")>>\"\n },\n \"Partial<Pick<StoreMachineStateInfo,(\\\"machineName\\\"|\\\"tenantId\\\"|\\\"instanceId\\\")>>\": {\n \"type\": \"object\",\n \"properties\": {\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n }\n },\n \"additionalProperties\": false\n }\n },\n \"methods\": {\n \"machineStateDelete\": {\n \"description\": \"Delete a particular machine state by instance id and tenant id\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/MachineStateDeleteArgs\"\n },\n \"returnType\": {\n \"type\": \"boolean\"\n }\n },\n \"machineStateGet\": {\n \"description\": \"Get a particular machine state by instance id and tenant id\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/MachineStateGetArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"machineStateInit\": {\n \"description\": \"Initializes a state object for a new machine. Does not persist anything\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/InitMachineStateArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/MachineStateInit\"\n }\n },\n \"machineStatePersist\": {\n \"description\": \"Persists the state\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/MachineStatePersistArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"machineStatesDeleteExpired\": {\n \"description\": \"Deletes the state of an xstate machine in the database.\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/DeleteExpiredStatesArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/DeleteStateResult\"\n }\n },\n \"machineStatesFindActive\": {\n \"description\": \"Loads the states of active xstate machines from the database.\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/FindActiveStatesArgs\"\n },\n \"returnType\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n }\n }\n }\n }\n }\n}\n","const schema = require('../plugin.schema.json')\nexport { schema }\nexport * from './agent/MachineStatePersistence'\nexport * from './types'\nexport * from './functions'\n","import { IAbstractMachineStateStore, StoreMachineStateInfo } from '@sphereon/ssi-sdk.data-store-types'\nimport { IAgentPlugin } from '@veramo/core'\nimport Debug from 'debug'\nimport { v4 as uuidv4 } from 'uuid'\nimport { deserializeMachineState, machineStateToMachineInit, machineStateToStoreInfo, serializeMachineState } from '../functions'\n\nimport {\n DeleteExpiredStatesArgs,\n DeleteStateResult,\n FindActiveStatesArgs,\n IMachineStatePersistence,\n InitMachineStateArgs,\n MachineStateDeleteArgs,\n MachineStateGetArgs,\n MachineStateInfo,\n MachineStateInit,\n MachineStatePersistArgs,\n MachineStatePersistEvent,\n MachineStatePersistEventType,\n MachineStatePersistOpts,\n RequiredContext,\n schema,\n} from '../index'\n\nconst debug = Debug('sphereon:ssi-sdk:machine-state:xstate-persistence')\n\n/**\n * This class implements the IMachineStatePersistence interface using a datastore.\n *\n * This allows you to store and retrieve the State of a state machine/application by their types.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport class MachineStatePersistence implements IAgentPlugin {\n readonly schema = schema.IMachineStatePersistence\n readonly methods: IMachineStatePersistence | {}\n readonly eventTypes: Array<string>\n private readonly _store?: IAbstractMachineStateStore\n\n get store(): IAbstractMachineStateStore {\n if (!this._store) {\n throw Error('No store available in options')\n }\n return this._store\n }\n\n constructor(opts: MachineStatePersistOpts) {\n const { store, eventTypes, isRESTClient } = opts\n this.eventTypes = eventTypes\n this.methods = {\n machineStatesFindActive: this.machineStatesFindActive.bind(this),\n machineStatesDeleteExpired: this.machineStatesDeleteExpired.bind(this),\n machineStateInit: this.machineStateInit.bind(this),\n machineStatePersist: this.machineStatePersist.bind(this),\n machineStateGet: this.machineStateGet.bind(this),\n machineStateDelete: this.machineStateDelete.bind(this),\n }\n this._store = store\n if (isRESTClient) {\n // Methods are delegated to the REMOTE Agent. We need the above eventTypes however, to ensure the local eventBus works\n // We do set the store, because we might have some local and some remote methods\n return\n } else if (!store) {\n throw Error('No store available in options')\n }\n }\n\n public async onEvent(event: MachineStatePersistEvent, context: RequiredContext): Promise<void> {\n debug(`Received machine state persistence event '${event.type}' counter: ${event.data._eventCounter}}`)\n if (!this.eventTypes.includes(event.type)) {\n console.log(`event type ${event.type} not registered for agent. Registered: ${JSON.stringify(this.eventTypes)}`)\n return\n }\n\n // Below we are calling the context of the agent instead of this to make sure the REST client is called when configured\n switch (event.type) {\n case MachineStatePersistEventType.INIT:\n await context.agent.machineStateInit({ ...event.data })\n break\n case MachineStatePersistEventType.EVERY:\n // We are keeping track of the update counter in the events, ensuring we do not process out of order\n await context.agent.machineStatePersist({\n ...event.data,\n cleanupOnFinalState: event.data.cleanupOnFinalState ?? event.data._cleanupOnFinalState,\n updatedCount: event.data._eventCounter ?? event.data.updatedCount,\n })\n break\n default:\n return Promise.reject(Error(`Event type ${event.type} not supported`))\n }\n }\n\n private async machineStateInit(args: InitMachineStateArgs, context: RequiredContext): Promise<MachineStateInit> {\n const { tenantId, machineName, expiresAt, customInstanceId, existingInstanceId, cleanupAllOtherInstances } = args\n debug(\n `machineStateInit for machine name ${machineName}, tenant ${tenantId}, custom instance ${customInstanceId}, existing id ${existingInstanceId}`,\n )\n if (customInstanceId && existingInstanceId) {\n return Promise.reject(new Error(`Cannot have both a custom and existing instance id at the same time`))\n }\n if (cleanupAllOtherInstances) {\n // First remove all states for this machine name and tenant that are in done state\n await context.agent.machineStatesDeleteExpired({ machineName, tenantId, deleteDoneStates: true })\n // Now cleanup all states for this machine name and tenant that are expired\n await context.agent.machineStatesDeleteExpired({ machineName, tenantId, deleteDoneStates: false })\n // Now remove all machines that are not equal to the existing instance id if provided, or all others if not provided\n const activeMachineStates = (await context.agent.machineStatesFindActive({ machineName, tenantId })).filter(\n (state) => !existingInstanceId || state.instanceId !== existingInstanceId,\n )\n await Promise.all(\n activeMachineStates.map((state) =>\n context.agent.machineStateDelete({\n instanceId: state.instanceId,\n tenantId,\n }),\n ),\n )\n }\n let machineInit: MachineStateInit | undefined = undefined\n let machineState: MachineStateInfo | undefined\n\n if (existingInstanceId) {\n // A existing instanceId is provided. First lookup whether this id is persisted, if not an error is thrown\n debug(`machineStateInit is using a previously persisted instance id (${existingInstanceId})`)\n machineState = await context.agent.machineStateGet({ tenantId, instanceId: existingInstanceId })\n machineInit = machineStateToMachineInit(\n {\n ...machineState,\n machineState: machineState,\n stateType: 'existing',\n },\n { ...machineState, state: serializeMachineState(machineState.state) },\n )\n }\n if (customInstanceId) {\n // A custom instanceId is provided.\n debug(`machineStateInit is using a custom instance id (${customInstanceId})`)\n }\n if (!machineInit) {\n machineInit = {\n machineName,\n tenantId,\n expiresAt,\n instanceId: customInstanceId ?? uuidv4(),\n createdAt: args.createdAt ?? new Date(),\n stateType: 'new',\n }\n }\n return machineInit\n }\n\n private async machineStatePersist(args: MachineStatePersistArgs, context: RequiredContext): Promise<MachineStateInfo> {\n const { instanceId, tenantId, machineName, updatedCount } = args\n const cleanupOnFinalState = args.cleanupOnFinalState !== false\n debug(`machineStatePersist for machine name ${machineName}, updateCount: ${updatedCount}, instance ${instanceId} and tenant ${tenantId}...`)\n try {\n const queriedStates = await this.store.findMachineStates({ filter: [{ instanceId, tenantId }] })\n const existingState = queriedStates.length === 1 ? queriedStates[0] : undefined\n\n const storeInfoArgs = machineStateToStoreInfo(args, existingState)\n let storedState: StoreMachineStateInfo\n if (updatedCount !== undefined && updatedCount > 1 && storeInfoArgs.latestEventType === 'xstate.init') {\n console.log(\n `Not persisting machine state for resumed init event for machine ${machineName}, tenant ${tenantId} and state with id ${instanceId}`,\n )\n storedState = storeInfoArgs\n } else {\n storedState = await this.store.persistMachineState(storeInfoArgs)\n }\n const machineStateInfo = { ...storedState, state: deserializeMachineState(storedState.state) }\n debug(\n `machineStatePersist success for machine name ${machineName}, instance ${instanceId}, update count ${machineStateInfo.updatedCount}, tenant ${tenantId}, last event: ${machineStateInfo.latestEventType}, last state: ${machineStateInfo.latestStateName}`,\n )\n if (cleanupOnFinalState && machineStateInfo.state.done) {\n debug(`reached final state for machine ${machineName} instance ${instanceId} and auto cleanup was enabled. Deleting machine state`)\n await context.agent.machineStateDelete(machineStateInfo)\n }\n return machineStateInfo\n } catch (error) {\n console.log(error)\n return Promise.reject(error)\n }\n }\n\n private async machineStatesFindActive(args: FindActiveStatesArgs): Promise<Array<MachineStateInfo>> {\n const { machineName, tenantId } = args\n debug(`machineStateFindActive for machine name ${machineName} and tenant ${tenantId}...`)\n const storedStates = await this.store.findActiveMachineStates(args)\n const machineStateInfos = storedStates.map((storedState: StoreMachineStateInfo) => {\n return { ...storedState, state: deserializeMachineState(storedState.state) }\n })\n debug(`machineStateFindActive returned ${machineStateInfos.length} results for machine name ${machineName} and tenant ${tenantId}`)\n return machineStateInfos\n }\n\n private async machineStatesDeleteExpired(args: DeleteExpiredStatesArgs): Promise<DeleteStateResult> {\n const { machineName, tenantId } = args\n debug(`machineStatesDeleteExpired for machine name ${machineName} and tenant ${tenantId}...`)\n const deleteResult = await this.store.deleteExpiredMachineStates(args)\n debug(`machineStatesDeleteExpired result for machine name ${machineName} and tenant ${tenantId}: ${deleteResult}`)\n return deleteResult\n }\n\n private async machineStateGet(args: MachineStateGetArgs, context: RequiredContext): Promise<MachineStateInfo> {\n const { instanceId, tenantId } = args\n debug(`machineStateGet for machine instance ${instanceId} and tenant ${tenantId}...`)\n const storedState = await this.store.getMachineState(args)\n const machineInfo = { ...storedState, state: deserializeMachineState(storedState.state) }\n debug(`machineStateGet success for machine instance ${instanceId} and tenant ${tenantId}`)\n return machineInfo\n }\n\n private async machineStateDelete(args: MachineStateDeleteArgs, context: RequiredContext): Promise<boolean> {\n const { instanceId, tenantId } = args\n debug(`machineStateDelete for machine instance ${instanceId} and tenant ${tenantId}...`)\n const deleteResult = await this.store.deleteMachineState(args)\n debug(`machineStateDelete result for machine instance ${instanceId} and tenant ${tenantId}: ${deleteResult}`)\n return deleteResult\n }\n}\n","import { IAgentContext, TAgent } from '@veramo/core'\nimport { DefaultContext, EventObject, Interpreter, State, StateSchema, TypegenDisabled, Typestate } from 'xstate'\nimport { waitFor } from 'xstate/lib/waitFor.js'\nimport {\n IMachineStatePersistence,\n InitMachineStateArgs,\n MachineStateInfo,\n MachineStateInit,\n MachineStateInitType,\n MachineStatePersistenceOpts,\n MachineStatePersistEventType,\n StartedInterpreterInfo,\n} from '../types'\nimport { emitMachineStatePersistEvent } from './stateEventEmitter'\nimport { machineStateToMachineInit, machineStateToStoreInfo } from './stateMapper'\n\n/**\n * Initialize the machine state persistence. Returns a unique instanceId and the machine name amongst others\n *\n * @param {Object} opts - The options for initializing the machine state persistence.\n * @param {InitMachineStateArgs} opts - The arguments for initializing the machine state.\n * @param {IAgentContext<any>} opts.context - The agent context.\n * @returns {Promise<MachineStateInit | undefined>} - A promise that resolves to the initialized machine state, or undefined if the agent isn't using the Xstate plugin.\n */\nexport const machineStatePersistInit = async (\n opts: InitMachineStateArgs &\n Pick<MachineStatePersistenceOpts, 'existingInstanceId' | 'customInstanceId'> & {\n context: IAgentContext<any> // We use any as this method could be called from an agent with access to, but not exposing this plugin\n },\n): Promise<MachineStateInit | undefined> => {\n // make sure the machine context does not end up in the machine state init args\n const { context, ...args } = opts\n if (!(context.agent.availableMethods().includes('machineStateInit') && 'machineStateInit' in context.agent)) {\n console.log(`IMachineStatePersistence was not exposed in the current agent. Not initializing new persistence object`)\n return\n }\n return await (context as IAgentContext<IMachineStatePersistence>).agent.machineStateInit(args)\n}\n\n/**\n * This function allows for the persistence of machine state on every xstate transition. It emits an event with the new state\n * and other relevant data to be handled by the persistence plugin when enabled.\n *\n * @param {Object} opts - The options object.\n * @param {Interpreter} opts.instance - The XState machine interpreter instance.\n * @param {IAgentContext<any>} opts.context - The agent context.\n * @param {MachineStateInit} opts.init - The initial persistence options, containing the unique instanceId.\n * @returns {Promise<void>} - A promise that resolves when the persistence event is emitted.\n */\nexport const machineStatePersistOnTransition = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(opts: {\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<any> // We use any as this method could be called from an agent with access to, but not exposing this plugin\n init: MachineStateInit\n cleanupOnFinalState?: boolean\n}): Promise<void> => {\n const { cleanupOnFinalState, context, init, interpreter } = opts\n const { machineState, ...initEventData } = init\n if (!(context.agent.availableMethods().includes('machineStatePersist') && 'machineStatePersist' in context.agent)) {\n console.log(`IMachineStatePersistence was not exposed in the current agent. Disabling machine state persistence events`)\n return\n }\n // We are using the event counter and evenDate to ensure we do not overwrite newer states. Events could come in out of order\n let _eventCounter = init.machineState?.updatedCount ?? 0\n\n // XState persistence plugin is available. So let's emit events on every transition, so it can persist the state\n interpreter.onChange(async (_machineContext) => {\n /*await (context.agent as TAgent<IMachineStatePersistence>).machineStatePersist({\n ...initEventData, // init value with machineState removed, as we are getting the latest state here\n state: interpreter.getSnapshot(),\n updatedCount: ++_eventCounter,\n cleanupOnFinalState: cleanupOnFinalState !== false,\n })*/\n emitMachineStatePersistEvent(\n {\n type: MachineStatePersistEventType.EVERY,\n data: {\n ...initEventData, // init value with machineState removed, as we are getting the latest state here\n state: interpreter.getSnapshot(),\n _eventCounter: ++_eventCounter,\n _eventDate: new Date(),\n _cleanupOnFinalState: cleanupOnFinalState !== false,\n },\n },\n context,\n )\n })\n if (cleanupOnFinalState && context.agent.availableMethods().includes('machineStateDelete')) {\n interpreter.onDone((doneEvent) => {\n ;(context.agent as TAgent<IMachineStatePersistence>).machineStateDelete({\n tenantId: initEventData.tenantId,\n instanceId: initEventData.instanceId,\n })\n })\n }\n}\n\n/**\n * Persist the initial state of a machine and register it with the given machine instance.\n *\n * @param {InitMachineStateArgs & {instance: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>, context: IAgentContext<any>}} args - The options for initializing\n * machine state and registering it.\n * @returns {Promise<MachineStateInit | undefined>} - A promise that resolves to the initial state of the machine, or undefined if the agent isn't using the Xstate plugin.\n */\nexport const machineStatePersistRegistration = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(\n args: Omit<InitMachineStateArgs, 'machineName'> &\n Partial<Pick<InitMachineStateArgs, 'machineName'>> &\n MachineStatePersistenceOpts & {\n cleanupOnFinalState?: boolean\n cleanupAllOtherInstances?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<any> // We use any as this method could be called from an agent with access to, but not exposing this plugin\n },\n): Promise<MachineStateInit | undefined> => {\n const { disablePersistence } = args\n if (disablePersistence === true) {\n return\n }\n\n // We use expires in MS first. If not provided, look at expires at. If not provided, the persistence will not expire\n const expiresAt = args.expireInMS ? new Date(Date.now() + args.expireInMS) : args.expiresAt\n const machineName = args.machineName ?? args.interpreter.machine.id ?? args.interpreter.id\n const init = await machineStatePersistInit({ ...args, machineName, expiresAt })\n if (init) {\n await machineStatePersistOnTransition({ ...args, init })\n }\n return init\n}\n\nconst assertNonExpired = (args: { expiresAt?: Date; machineName: string }) => {\n const { expiresAt, machineName } = args\n if (expiresAt && expiresAt.getTime() < Date.now()) {\n throw new Error(`Cannot resume ${machineName}. It expired at ${expiresAt.toLocaleString()}`)\n }\n}\n\n/**\n * Resumes the interpreter from a given state.\n *\n * @param {Object} args - The arguments for resuming the interpreter.\n * @param {MachineStateInfo} args.machineState - The machine state information.\n * @param {boolean} [args.noRegistration] - If true, no registration will be performed.\n * @param {Interpreter} args.interpreter - The interpreter instance.\n * @param {IAgentContext<IMachineStatePersistence>} args.context - The context for machine state persistence.\n *\n * @returns {Promise<Interpreter>} - A promise that resolves to the resumed interpreter.\n */\nexport const interpreterResumeFromState = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(args: {\n machineState: MachineStateInfo\n noRegistration?: boolean\n cleanupAllOtherInstances?: boolean\n cleanupOnFinalState?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<IMachineStatePersistence>\n}): Promise<StartedInterpreterInfo<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>> => {\n const { interpreter, machineState, context, noRegistration, cleanupAllOtherInstances, cleanupOnFinalState } = args\n const { machineName, instanceId, tenantId } = machineState\n assertNonExpired(machineState)\n if (noRegistration !== true) {\n await machineStatePersistRegistration({\n stateType: 'existing',\n machineName,\n tenantId,\n existingInstanceId: instanceId,\n cleanupAllOtherInstances,\n cleanupOnFinalState,\n context,\n interpreter,\n })\n }\n const state = State.from(machineState.state.value, machineState.state.context)\n // @ts-ignore\n interpreter.start(state)\n // @ts-ignore\n await waitFor(interpreter, (awaitState) => awaitState.matches(state.value))\n\n return {\n machineState,\n init: machineStateToMachineInit(\n {\n ...machineState,\n stateType: 'existing',\n },\n machineStateToStoreInfo({ ...machineState, stateType: 'existing' }),\n ),\n\n interpreter,\n }\n}\n\n/**\n * Resumes or starts the interpreter from the initial machine state.\n *\n * @async\n * @param {Object} args - The arguments for the function.\n * @param {MachineStateInit & {stateType?: MachineStateInitType}} args.init - The initialization state of the machine.\n * @param {boolean} args.noRegistration - Whether registration is required, defaults to false.\n * @param {Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>} args.interpreter - The interpreter object.\n * @param {IAgentContext<IMachineStatePersistence>} args.context - The context object.\n * @returns {Promise} - A promise that resolves to the interpreter instance.\n * @throws {Error} - If the machine name from init does not match the interpreter id.\n */\nexport const interpreterStartOrResumeFromInit = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(args: {\n init: MachineStateInit & { stateType?: MachineStateInitType }\n cleanupAllOtherInstances?: boolean\n cleanupOnFinalState?: boolean\n noRegistration?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<IMachineStatePersistence>\n}): Promise<StartedInterpreterInfo<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>> => {\n const { init, noRegistration, interpreter, cleanupOnFinalState, cleanupAllOtherInstances, context } = args\n const { stateType, instanceId, machineName, tenantId, expiresAt } = init\n if (init.machineName !== interpreter.id) {\n throw new Error(`Machine state init machine name ${init.machineName} does not match name from state machine interpreter ${interpreter.id}`)\n }\n assertNonExpired({ machineName, expiresAt })\n if (noRegistration !== true) {\n await machineStatePersistRegistration({\n stateType: stateType ?? 'existing',\n machineName,\n tenantId,\n ...(stateType === 'existing' && { existingInstanceId: instanceId }),\n ...(stateType === 'new' && { customInstanceId: instanceId }),\n cleanupAllOtherInstances,\n cleanupOnFinalState,\n context,\n interpreter,\n })\n }\n let machineState: MachineStateInfo | undefined\n if (stateType === 'new') {\n interpreter.start()\n } else {\n machineState = await context.agent.machineStateGet({ tenantId, instanceId })\n // @ts-ignore\n interpreter.start(machineState.state)\n }\n // We are waiting a bit\n await new Promise((res) => setTimeout(res, 50))\n return {\n interpreter,\n machineState,\n init,\n }\n}\n\n/**\n * Starts or resumes the given state machine interpreter.\n *\n * @async\n * @param {Object} args - The arguments for starting or resuming the interpreter.\n * @param {MachineStateInitType | 'auto'} [args.stateType] - The state type. Defaults to 'auto'.\n * @param {string} [args.instanceId] - The instance ID.\n * @param {string} [args.machineName] - The machine name.\n * @param {string} [args.tenantId] - The tenant ID.\n * @param {boolean} args.singletonCheck - Whether to perform a singleton check or not. If more than one machine instance is found an error will be thrown\n * @param {boolean} [args.noRegistration] - Whether to skip state change event registration or not.\n * @param {Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>} args.interpreter - The interpreter to start or resume.\n * @param {IAgentContext<IMachineStatePersistence>} args.context - The agent context.\n * @returns {Promise} A promise that resolves when the interpreter is started or resumed.\n * @throws {Error} If there are multiple active instances of the machine and singletonCheck is true.\n * @throws {Error} If a new instance was requested with the same ID as an existing active instance.\n * @throws {Error} If the existing state machine with the given machine name and instance ID cannot be found.\n */\nexport const interpreterStartOrResume = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(args: {\n stateType?: MachineStateInitType | 'auto'\n instanceId?: string\n machineName?: string\n tenantId?: string\n singletonCheck: boolean\n noRegistration?: boolean\n cleanupAllOtherInstances?: boolean\n cleanupOnFinalState?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<IMachineStatePersistence>\n}): Promise<StartedInterpreterInfo<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>> => {\n const { stateType, singletonCheck, instanceId, tenantId, noRegistration, context, interpreter, cleanupAllOtherInstances, cleanupOnFinalState } =\n args\n const machineName = args.machineName ?? interpreter.id\n let activeStates = await context.agent.machineStatesFindActive({\n machineName,\n tenantId,\n instanceId,\n })\n if (stateType === 'new' && activeStates.length > 0 && cleanupAllOtherInstances) {\n // We cleanup here to not influence the logic below. Normally the agent machineStateInit method does the cleanup\n await Promise.all(\n activeStates.map((state) =>\n context.agent.machineStateDelete({\n tenantId: args.tenantId,\n instanceId: state.instanceId,\n }),\n ),\n )\n // We search again, given the delete is using the passed in tenantId, instead of relying on the persisted tenantId. Should not matter, but just making sure\n activeStates = await context.agent.machineStatesFindActive({\n machineName,\n tenantId,\n instanceId,\n })\n }\n if (singletonCheck && activeStates.length > 0) {\n if (\n stateType === 'new' ||\n (stateType === 'existing' &&\n ((!instanceId && activeStates.length > 1) || (instanceId && activeStates.every((state) => state.instanceId !== instanceId))))\n ) {\n return Promise.reject(new Error(`Found ${activeStates.length} active '${machineName}' instances, but only one is allows at the same time`))\n }\n }\n if (stateType === 'new') {\n if (instanceId && activeStates.length > 0) {\n // Since an instanceId was provided it means the activeStates includes a machine with this instance. But stateType is 'new'\n return Promise.reject(\n new Error(`Found an active '${machineName}' instance with id ${instanceId}, but a new instance was requested with the same id`),\n )\n }\n const init = await context.agent.machineStateInit({\n stateType: 'new',\n customInstanceId: instanceId,\n machineName: machineName ?? interpreter.id,\n tenantId,\n cleanupAllOtherInstances,\n })\n return await interpreterStartOrResumeFromInit({\n init,\n noRegistration,\n interpreter,\n context,\n cleanupOnFinalState,\n cleanupAllOtherInstances,\n })\n }\n if (activeStates.length === 0) {\n if (stateType === 'existing') {\n return Promise.reject(new Error(`Could not find existing state machine ${machineName}, instanceId ${instanceId}`))\n }\n const init = await context.agent.machineStateInit({\n stateType: 'new',\n customInstanceId: instanceId,\n machineName: machineName ?? interpreter.id,\n tenantId,\n cleanupAllOtherInstances,\n })\n return await interpreterStartOrResumeFromInit({\n init,\n noRegistration,\n interpreter,\n context,\n cleanupOnFinalState,\n cleanupAllOtherInstances,\n })\n }\n\n // activeStates length >= 1\n const activeState = activeStates[0]\n return interpreterResumeFromState({\n machineState: activeState,\n noRegistration,\n interpreter,\n context,\n cleanupOnFinalState,\n cleanupAllOtherInstances,\n })\n}\n","import {\n IAbstractMachineStateStore,\n StoreMachineStateDeleteExpiredArgs,\n StoreMachineStateInfo,\n StoreMachineStatesFindActiveArgs,\n} from '@sphereon/ssi-sdk.data-store-types'\nimport { IAgentContext } from '@veramo/core'\nimport {\n AnyEventObject,\n DefaultContext,\n EventObject,\n HistoryValue,\n Interpreter,\n SCXML,\n StateSchema,\n StateValue,\n TypegenDisabled,\n Typestate,\n} from 'xstate'\n\nimport { IMachineStatePersistence } from './IMachineStatePersistence'\n\n/**\n * Represents the options for persisting machine state.\n *\n * @typedef {Object} MachineStatePersistOpts\n * @property {IAbstractMachineStateStore} store - The store used to persist the machine state.\n * @property {Array<string>} eventTypes - The types of events to be persisted.\n */\nexport type MachineStatePersistOpts = { store?: IAbstractMachineStateStore; eventTypes: Array<string>; isRESTClient?: boolean }\n\n/**\n * Enum representing the types of machine state persist events.\n * @enum {string}\n */\nexport enum MachineStatePersistEventType {\n INIT = 'INIT',\n EVERY = 'EVERY',\n}\n\n/**\n * Represents the arguments for deleting expired states from a machine.\n */\nexport type DeleteExpiredStatesArgs = Pick<StoreMachineStateDeleteExpiredArgs, 'deleteDoneStates' | 'machineName' | 'tenantId'>\n\n/**\n * Represents the arguments for finding active states of a store machine.\n */\nexport type FindActiveStatesArgs = StoreMachineStatesFindActiveArgs\n\n/**\n * Represents the result of a state deletion operation.\n *\n * @typedef {number} DeleteStateResult\n */\nexport type DeleteStateResult = number\n\n/**\n * Represents a machine state persist event.\n *\n * @typedef {Object} MachineStatePersistEvent\n * @property {MachineStatePersistEventType} type - The type of the persist event.\n * @property {MachineStatePersistArgs} data - The data associated with the persist event, along with additional properties `_eventCounter` and `_eventDate`.\n * @property {number} data._eventCounter - The counter for the persist event.\n * @property {Date} data._eventDate - The date and time the persist event occurred.\n */\nexport type MachineStatePersistEvent = {\n type: MachineStatePersistEventType\n data: Omit<MachineStatePersistArgs, 'machineState'> & {\n _eventCounter: number\n _eventDate: Date\n _cleanupOnFinalState: boolean\n }\n}\n\n/**\n * Represents a RequiredContext class, which is a type definition for the context required by an agent.\n * It is used to enforce that the agent context implements the necessary interfaces.\n *\n * @typeparam T - The type of the machine state persistence.\n */\nexport type RequiredContext = IAgentContext<IMachineStatePersistence>\n\n/**\n * Represents the information about the current state of a machine.\n * @typedef {Object} MachineStateInfo\n * @property {string} id - The ID of the machine.\n * @property {SerializableState} state - The serializable state of the machine.\n * @property {string} description - The description of the machine state.\n */\nexport type MachineStateInfo = Omit<StoreMachineStateInfo, 'state'> & {\n state: SerializableState\n}\n\nexport type MachineStatePersistenceOpts = {\n disablePersistence?: boolean // Disable persistence altogether\n customInstanceId?: string // Used when creating a machine using a custom new instance id\n existingInstanceId?: string // Used when creating a machine using an existing instance (rehydrating a persisted machine)\n expireInMS?: number // Expire in an amount of MS (takes precedence over date if both are provided!)\n expiresAt?: Date // Expire at a specific date\n}\n\nexport type MachineStateInitType = 'new' | 'existing'\n\n/**\n * Represents the initial state for a machine.\n *\n * @typedef {Object} MachineStateInit\n * @property {string} existingInstanceId - The unique identifier for the machine instance.\n * @property {string} machineName - The name of the machine.\n * @property {string} tenantId - The identifier for the tenant associated with the machine.\n * @property {Date} createdAt - The date and time when the machine was created.\n * @property {Date} expiresAt - The date and time when the machine's state expires.\n */\nexport type MachineStateInit = Pick<MachineStateInfo, 'instanceId' | 'machineName' | 'tenantId' | 'createdAt' | 'expiresAt'> & {\n stateType: MachineStateInitType\n machineState?: MachineStateInfo // Only available when stateType is 'existing'\n}\n\n/**\n * Represents the arguments required to initialize the machine state.\n * @typedef {Object} InitMachineStateArgs\n * @property {string} machineName - The name of the machine.\n * @property {Partial<MachineStateInit>} [additionalArgs] - Additional initialization arguments for the machine state.\n */\nexport type InitMachineStateArgs = Omit<Partial<MachineStateInit>, 'instanceId'> &\n Pick<MachineStateInfo, 'machineName'> &\n Pick<MachineStatePersistenceOpts, 'customInstanceId' | 'existingInstanceId'> & { cleanupAllOtherInstances?: boolean }\n\n/**\n * Represents the arguments required to persist the machine state.\n */\nexport type MachineStatePersistArgs = Omit<MachineStateInit, 'createdAt'> &\n Pick<MachineStateInfo, 'state' | 'instanceId'> &\n Partial<Pick<MachineStateInfo, 'updatedCount'>> & { cleanupOnFinalState?: boolean }\n\n/**\n * Represents the arguments required to get machine state.\n * @typedef {Object} MachineStateGetArgs\n * @property {string} existingInstanceId - The ID of the machine instance.\n * @property {string} tenantId - The ID of the tenant the machine belongs to.\n */\nexport type MachineStateGetArgs = Pick<StoreMachineStateInfo, 'instanceId' | 'tenantId'>\n\n/**\n * Represents the arguments required for deleting a machine state.\n *\n * @typedef {object} MachineStateDeleteArgs\n * @property {string} existingInstanceId - The ID of the machine instance to delete the state for.\n * @property {string} tenantId - The ID of the tenant owning the machine instance.\n */\nexport type MachineStateDeleteArgs = Pick<StoreMachineStateInfo, 'instanceId' | 'tenantId'>\n\n/**\n * Represents the information for a started interpreter.\n *\n * @template TContext The type of the context object.\n * @template TStateSchema The type of the state schema.\n * @template TEvent The type of the event object.\n * @template TTypestate The type of the typestate object.\n * @template TResolvedTypesMeta The type of the resolved types meta object.\n */\nexport type StartedInterpreterInfo<\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n> = {\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n machineState?: MachineStateInfo\n init: MachineStateInit\n}\n\n/**\n * Represents the serializable state of a machine.\n *\n * @typedef {Object} SerializableState\n * @property {XStateConfig<any, AnyEventObject>} config - The machine configuration.\n */\nexport type SerializableState = XStateConfig<any, AnyEventObject>\n\n/**\n * The configuration for the XState machine state. Simplified StateConfig object from XState so we have a minimal typed structure\n *\n * @template TContext - The context type for the state.\n * @template TEvent - The event type for the state.\n */\nexport interface XStateConfig<TContext, TEvent extends EventObject> {\n value: StateValue\n context: TContext\n _event: SCXML.Event<TEvent>\n _sessionid: string | null\n historyValue?: HistoryValue | undefined\n history?: any\n actions?: Array<any>\n activities?: any\n meta?: any\n events?: TEvent[]\n configuration: Array<any>\n transitions: Array<any>\n children: Record<string, any>\n done?: boolean\n tags?: Set<string>\n machine?: any\n}\n","import Debug from 'debug'\nimport { MachineStatePersistEvent, RequiredContext } from '../types'\n\nconst debug = Debug('sphereon:ssi-sdk:machine-state:xstate-persistence')\n\n/**\n * Emits a machine state persistence event.\n *\n * @param {MachineStatePersistEvent} event - The event to be emitted.\n * @param {RequiredContext} context - The required agent context for the event emission.\n * @returns {void}\n */\nexport const emitMachineStatePersistEvent = (event: MachineStatePersistEvent, context: RequiredContext) => {\n debug(\n `Emitting machine state persistence event '${event.type}' with counter: ${event.data._eventCounter} and state ${JSON.stringify(\n event.data.state.value,\n )}`,\n )\n void context.agent.emit(event.type, event.data)\n}\n","import { StoreMachineStateInfo } from '@sphereon/ssi-sdk.data-store-types'\nimport { State } from 'xstate'\nimport { EventObject } from 'xstate/lib/types'\nimport { MachineStateInfo, MachineStateInit, MachineStateInitType, MachineStatePersistArgs, SerializableState } from '../types'\n\n/**\n * Create a machine state info object useful for the store, based on the provided machine info and existing state.\n *\n * @param {MachineStatePersistArgs} machineInfo - The machine info object.\n * @param {Partial<StoreMachineStateInfo>} [existingState] - The optional existing state object.\n * @returns {StoreMachineStateInfo} - The store machine state info object.\n */\nexport const machineStateToStoreInfo = (\n machineInfo: MachineStatePersistArgs,\n existingState?: Partial<StoreMachineStateInfo>,\n): StoreMachineStateInfo => {\n const { state, machineName, tenantId, expiresAt, instanceId, updatedCount } = machineInfo\n\n const existing: Partial<StoreMachineStateInfo> = existingState ?? { machineName, createdAt: new Date(), expiresAt }\n const stateInstance = State.create(machineInfo.state)\n let latestStateName = undefined\n if (stateInstance.value) {\n latestStateName = typeof stateInstance.value === 'string' ? stateInstance.value : JSON.stringify(stateInstance.value)\n }\n if (latestStateName === '{}') {\n latestStateName = undefined\n }\n return {\n instanceId,\n updatedCount: updatedCount ?? (existing?.updatedCount ? existing.updatedCount++ : 0),\n sessionId: stateInstance._sessionid ?? undefined,\n machineName,\n state: serializeMachineState(state),\n tenantId,\n latestStateName,\n latestEventType: stateInstance.event.type,\n updatedAt: new Date(),\n expiresAt,\n createdAt: existing.createdAt ?? new Date(),\n completedAt: existing.completedAt ?? (stateInstance.done ? new Date() : undefined),\n }\n}\nexport const storeInfoToMachineInit = (\n args: StoreMachineStateInfo & { stateType: MachineStateInitType; machineState?: MachineStateInfo },\n): MachineStateInit => {\n const { instanceId, machineName, tenantId, expiresAt, createdAt, stateType, machineState } = args\n return {\n stateType,\n machineName,\n tenantId,\n expiresAt,\n instanceId,\n createdAt,\n machineState,\n }\n}\n\nexport const machineStateToMachineInit = (machineInfo: MachineStatePersistArgs, existingState: Partial<StoreMachineStateInfo>): MachineStateInit => {\n return storeInfoToMachineInit({\n ...machineStateToStoreInfo(machineInfo, existingState),\n stateType: 'existing',\n machineState: machineInfo.machineState,\n })\n}\n\n/**\n * Serializes a machine state to a string representation.\n *\n * @param {State<T, TEvent> | SerializableState | string} state - The machine state to serialize.\n * @returns {string} - The serialized machine state.\n */\nexport const serializeMachineState = <T, TEvent extends EventObject>(state: State<T, TEvent> | SerializableState | string): string => {\n if (typeof state === 'string') {\n return state\n }\n const jsonState = 'toJSON' in state ? state.toJSON() : state\n return JSON.stringify(jsonState)\n}\n/**\n * Deserializes a serialized machine state.\n *\n * @template T - The type of the machine's context.\n * @template TEvent - The type of the events that the machine handles.\n * @param {string} state - The serialized machine state.\n * @returns {State<T, TEvent>} - The deserialized machine state.\n */\nexport const deserializeMachineState = <T, TEvent extends EventObject>(state: string): State<T, TEvent> => {\n return State.create(JSON.parse(state))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,gCAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,0BAA4B;AAAA,QAC1B,YAAc;AAAA,UACZ,SAAW;AAAA,YACT,wBAA0B;AAAA,cACxB,MAAQ;AAAA,YACV;AAAA,YACA,yDAA6D;AAAA,cAC3D,MAAQ;AAAA,cACR,YAAc;AAAA,gBACZ,YAAc;AAAA,kBACZ,MAAQ;AAAA,kBACR,aAAe;AAAA,gBACjB;AAAA,gBACA,UAAY;AAAA,kBACV,MAAQ;AAAA,gBACV;AAAA,cACF;AAAA,cACA,UAAY,CAAC,YAAY;AAAA,cACzB,sBAAwB;AAAA,YAC1B;AAAA,YACA,qBAAuB;AAAA,cACrB,MAAQ;AAAA,YACV;AAAA,YACA,kBAAoB;AAAA,cAClB,MAAQ;AAAA,cACR,sBAAwB;AAAA,cACxB,YAAc;AAAA,gBACZ,OAAS;AAAA,kBACP,MAAQ;AAAA,gBACV;AAAA,gBAC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AAA,EAAU;AACzF,WAAO0C;EACT;EAEA,MAAchE,mBAAmBqB,MAA8BlB,SAA4C;AACzG,UAAM,EAAE6B,YAAYV,SAAQ,IAAKD;AACjCvC,IAAAA,OAAM,2CAA2CkD,UAAAA,eAAyBV,QAAAA,KAAa;AACvF,UAAMuC,eAAe,MAAM,KAAKvE,MAAM2E,mBAAmB5C,IAAAA;AACzDvC,IAAAA,OAAM,kDAAkDkD,UAAAA,eAAyBV,QAAAA,KAAauC,YAAAA,EAAc;AAC5G,WAAOA;EACT;AACF;;;AD3NA,IAAMK,SAASC;","names":["module","import_debug","import_xstate","MachineStatePersistEventType","debug","Debug","emitMachineStatePersistEvent","event","context","type","data","_eventCounter","JSON","stringify","state","value","agent","emit","machineStateToStoreInfo","machineInfo","existingState","state","machineName","tenantId","expiresAt","instanceId","updatedCount","existing","createdAt","Date","stateInstance","State","create","latestStateName","undefined","value","JSON","stringify","sessionId","_sessionid","serializeMachineState","latestEventType","event","type","updatedAt","completedAt","done","storeInfoToMachineInit","args","stateType","machineState","machineStateToMachineInit","jsonState","toJSON","deserializeMachineState","parse","machineStatePersistInit","opts","context","args","agent","availableMethods","includes","console","log","machineStateInit","machineStatePersistOnTransition","cleanupOnFinalState","init","interpreter","machineState","initEventData","_eventCounter","updatedCount","onChange","_machineContext","emitMachineStatePersistEvent","type","MachineStatePersistEventType","EVERY","data","state","getSnapshot","_eventDate","Date","_cleanupOnFinalState","onDone","doneEvent","machineStateDelete","tenantId","instanceId","machineStatePersistRegistration","disablePersistence","expiresAt","expireInMS","now","machineName","machine","id","assertNonExpired","getTime","Error","toLocaleString","interpreterResumeFromState","noRegistration","cleanupAllOtherInstances","stateType","existingInstanceId","State","from","value","start","waitFor","awaitState","matches","machineStateToMachineInit","machineStateToStoreInfo","interpreterStartOrResumeFromInit","customInstanceId","machineStateGet","Promise","res","setTimeout","interpreterStartOrResume","singletonCheck","activeStates","machineStatesFindActive","length","all","map","every","reject","activeState","debug","Debug","MachineStatePersistence","schema","IMachineStatePersistence","methods","eventTypes","_store","store","Error","opts","isRESTClient","machineStatesFindActive","bind","machineStatesDeleteExpired","machineStateInit","machineStatePersist","machineStateGet","machineStateDelete","onEvent","event","context","type","data","_eventCounter","includes","console","log","JSON","stringify","MachineStatePersistEventType","INIT","agent","EVERY","cleanupOnFinalState","_cleanupOnFinalState","updatedCount","Promise","reject","args","tenantId","machineName","expiresAt","customInstanceId","existingInstanceId","cleanupAllOtherInstances","deleteDoneStates","activeMachineStates","filter","state","instanceId","all","map","machineInit","undefined","machineState","machineStateToMachineInit","stateType","serializeMachineState","uuidv4","createdAt","Date","queriedStates","findMachineStates","existingState","length","storeInfoArgs","machineStateToStoreInfo","storedState","latestEventType","persistMachineState","machineStateInfo","deserializeMachineState","latestStateName","done","error","storedStates","findActiveMachineStates","machineStateInfos","deleteResult","deleteExpiredMachineStates","getMachineState","machineInfo","deleteMachineState","schema","require"]}
1
+ {"version":3,"sources":["../plugin.schema.json","../src/index.ts","../src/agent/MachineStatePersistence.ts","../src/functions/machineRegistration.ts","../src/types/types.ts","../src/functions/stateEventEmitter.ts","../src/functions/stateMapper.ts"],"sourcesContent":["{\n \"IMachineStatePersistence\": {\n \"components\": {\n \"schemas\": {\n \"MachineStateDeleteArgs\": {\n \"$ref\": \"#/components/schemas/Pick<StoreMachineStateInfo,(\\\"instanceId\\\"|\\\"tenantId\\\")>\"\n },\n \"Pick<StoreMachineStateInfo,(\\\"instanceId\\\"|\\\"tenantId\\\")>\": {\n \"type\": \"object\",\n \"properties\": {\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"instanceId\"\n ],\n \"additionalProperties\": false\n },\n \"MachineStateGetArgs\": {\n \"$ref\": \"#/components/schemas/Pick<StoreMachineStateInfo,(\\\"instanceId\\\"|\\\"tenantId\\\")>\"\n },\n \"MachineStateInfo\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"state\": {\n \"$ref\": \"#/components/schemas/SerializableState\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"sessionId\": {\n \"type\": \"string\",\n \"description\": \"Session Id of the machine. Not necessarily unique\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"latestStateName\": {\n \"type\": \"string\",\n \"description\": \"The latest state name. Can be empty for a newly initialize machine\"\n },\n \"latestEventType\": {\n \"type\": \"string\",\n \"description\": \"event types like SET_TOC, SET_FIRSTNAME, .... Will be xstate.init on a newly initialized machine\"\n },\n \"createdAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the creation date\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n },\n \"updatedAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the update date\"\n },\n \"updatedCount\": {\n \"type\": \"number\",\n \"description\": \"Represents a counter for tracking updates.\"\n },\n \"completedAt\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"createdAt\",\n \"instanceId\",\n \"latestEventType\",\n \"machineName\",\n \"state\",\n \"updatedAt\",\n \"updatedCount\"\n ]\n },\n \"SerializableState\": {\n \"$ref\": \"#/components/schemas/XStateConfig<any,AnyEventObject>\"\n },\n \"XStateConfig<any,AnyEventObject>\": {\n \"type\": \"object\",\n \"properties\": {\n \"value\": {\n \"$ref\": \"#/components/schemas/StateValue\"\n },\n \"context\": {},\n \"_event\": {\n \"$ref\": \"#/components/schemas/SCXML.Event<AnyEventObject>\"\n },\n \"_sessionid\": {\n \"type\": [\n \"string\",\n \"null\"\n ]\n },\n \"historyValue\": {\n \"$ref\": \"#/components/schemas/HistoryValue\"\n },\n \"history\": {},\n \"actions\": {\n \"type\": \"array\",\n \"items\": {}\n },\n \"activities\": {},\n \"meta\": {},\n \"events\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/AnyEventObject\"\n }\n },\n \"configuration\": {\n \"type\": \"array\",\n \"items\": {}\n },\n \"transitions\": {\n \"type\": \"array\",\n \"items\": {}\n },\n \"children\": {\n \"$ref\": \"#/components/schemas/Record<string,any>\"\n },\n \"done\": {\n \"type\": \"boolean\"\n },\n \"tags\": {\n \"$ref\": \"#/components/schemas/Set<string>\"\n },\n \"machine\": {}\n },\n \"required\": [\n \"value\",\n \"context\",\n \"_event\",\n \"_sessionid\",\n \"configuration\",\n \"transitions\",\n \"children\"\n ],\n \"additionalProperties\": false,\n \"description\": \"The configuration for the XState machine state. Simplified StateConfig object from XState so we have a minimal typed structure\"\n },\n \"StateValue\": {\n \"anyOf\": [\n {\n \"type\": \"string\"\n },\n {\n \"$ref\": \"#/components/schemas/StateValueMap\"\n }\n ],\n \"description\": \"The string or object representing the state value relative to the parent state node.\\n\\n- For a child atomic state node, this is a string, e.g., `\\\"pending\\\"`.\\n- For complex state nodes, this is an object, e.g., `{ success: \\\"someChildState\\\" }`.\"\n },\n \"StateValueMap\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"$ref\": \"#/components/schemas/StateValue\"\n }\n },\n \"SCXML.Event<AnyEventObject>\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"This is a character string giving the name of the event. The SCXML Processor must set the name field to the name of this event. It is what is matched against the 'event' attribute of <transition>. Note that transitions can do additional tests by using the value of this field inside boolean expressions in the 'cond' attribute.\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"platform\",\n \"internal\",\n \"external\"\n ],\n \"description\": \"This field describes the event type. The SCXML Processor must set it to: \\\"platform\\\" (for events raised by the platform itself, such as error events), \\\"internal\\\" (for events raised by <raise> and <send> with target '_internal') or \\\"external\\\" (for all other events).\"\n },\n \"sendid\": {\n \"type\": \"string\",\n \"description\": \"If the sending entity has specified a value for this, the Processor must set this field to that value (see C Event I/O Processors for details). Otherwise, in the case of error events triggered by a failed attempt to send an event, the Processor must set this field to the send id of the triggering <send> element. Otherwise it must leave it blank.\"\n },\n \"origin\": {\n \"type\": \"string\",\n \"description\": \"This is a URI, equivalent to the 'target' attribute on the <send> element. For external events, the SCXML Processor should set this field to a value which, when used as the value of 'target', will allow the receiver of the event to <send> a response back to the originating entity via the Event I/O Processor specified in 'origintype'. For internal and platform events, the Processor must leave this field blank.\"\n },\n \"origintype\": {\n \"type\": \"string\",\n \"description\": \"This is equivalent to the 'type' field on the <send> element. For external events, the SCXML Processor should set this field to a value which, when used as the value of 'type', will allow the receiver of the event to <send> a response back to the originating entity at the URI specified by 'origin'. For internal and platform events, the Processor must leave this field blank.\"\n },\n \"invokeid\": {\n \"type\": \"string\",\n \"description\": \"If this event is generated from an invoked child process, the SCXML Processor must set this field to the invoke id of the invocation that triggered the child process. Otherwise it must leave it blank.\"\n },\n \"data\": {\n \"$ref\": \"#/components/schemas/AnyEventObject\",\n \"description\": \"This field contains whatever data the sending entity chose to include in this event. The receiving SCXML Processor should reformat this data to match its data model, but must not otherwise modify it.\\n\\nIf the conversion is not possible, the Processor must leave the field blank and must place an error 'error.execution' in the internal event queue.\"\n },\n \"$$type\": {\n \"type\": \"string\",\n \"const\": \"scxml\"\n }\n },\n \"required\": [\n \"name\",\n \"type\",\n \"data\",\n \"$$type\"\n ],\n \"additionalProperties\": false\n },\n \"AnyEventObject\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"The type of event that is sent.\"\n }\n },\n \"required\": [\n \"type\"\n ]\n },\n \"HistoryValue\": {\n \"type\": \"object\",\n \"properties\": {\n \"states\": {\n \"$ref\": \"#/components/schemas/Record<string,(interface-434048446-6094-6223-434048446-0-57488|undefined)>\"\n },\n \"current\": {\n \"$ref\": \"#/components/schemas/StateValue\"\n }\n },\n \"required\": [\n \"states\"\n ],\n \"additionalProperties\": false\n },\n \"Record<string,(interface-434048446-6094-6223-434048446-0-57488|undefined)>\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [\n {\n \"$ref\": \"#/components/schemas/HistoryValue\"\n },\n {\n \"not\": {}\n }\n ]\n }\n },\n \"Record<string,any>\": {\n \"type\": \"object\"\n },\n \"Set<string>\": {\n \"type\": \"object\",\n \"properties\": {\n \"size\": {\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"size\"\n ],\n \"additionalProperties\": false\n },\n \"InitMachineStateArgs\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"cleanupAllOtherInstances\": {\n \"type\": \"boolean\"\n },\n \"customInstanceId\": {\n \"type\": \"string\"\n },\n \"existingInstanceId\": {\n \"type\": \"string\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"createdAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the creation date\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n },\n \"stateType\": {\n \"$ref\": \"#/components/schemas/MachineStateInitType\"\n },\n \"machineState\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"required\": [\n \"machineName\"\n ]\n },\n \"MachineStateInitType\": {\n \"type\": \"string\",\n \"enum\": [\n \"new\",\n \"existing\"\n ]\n },\n \"MachineStateInit\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"stateType\": {\n \"$ref\": \"#/components/schemas/MachineStateInitType\"\n },\n \"machineState\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"createdAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the creation date\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n }\n },\n \"required\": [\n \"createdAt\",\n \"instanceId\",\n \"machineName\",\n \"stateType\"\n ]\n },\n \"MachineStatePersistArgs\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"cleanupOnFinalState\": {\n \"type\": \"boolean\"\n },\n \"updatedCount\": {\n \"type\": \"number\",\n \"description\": \"Represents a counter for tracking updates.\"\n },\n \"state\": {\n \"$ref\": \"#/components/schemas/SerializableState\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n },\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"expiresAt\": {\n \"type\": \"string\",\n \"description\": \"Represents the expiration date\"\n },\n \"stateType\": {\n \"$ref\": \"#/components/schemas/MachineStateInitType\"\n },\n \"machineState\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"required\": [\n \"instanceId\",\n \"machineName\",\n \"state\",\n \"stateType\"\n ],\n \"description\": \"Represents the arguments required to persist the machine state.\"\n },\n \"DeleteExpiredStatesArgs\": {\n \"$ref\": \"#/components/schemas/Pick<StoreMachineStateDeleteExpiredArgs,(\\\"deleteDoneStates\\\"|\\\"machineName\\\"|\\\"tenantId\\\")>\",\n \"description\": \"Represents the arguments for deleting expired states from a machine.\"\n },\n \"Pick<StoreMachineStateDeleteExpiredArgs,(\\\"deleteDoneStates\\\"|\\\"machineName\\\"|\\\"tenantId\\\")>\": {\n \"type\": \"object\",\n \"properties\": {\n \"deleteDoneStates\": {\n \"type\": \"boolean\"\n },\n \"machineName\": {\n \"type\": \"string\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n },\n \"DeleteStateResult\": {\n \"type\": \"number\"\n },\n \"FindActiveStatesArgs\": {\n \"$ref\": \"#/components/schemas/StoreMachineStatesFindActiveArgs\",\n \"description\": \"Represents the arguments for finding active states of a store machine.\"\n },\n \"StoreMachineStatesFindActiveArgs\": {\n \"$ref\": \"#/components/schemas/Partial<Pick<StoreMachineStateInfo,(\\\"machineName\\\"|\\\"tenantId\\\"|\\\"instanceId\\\")>>\"\n },\n \"Partial<Pick<StoreMachineStateInfo,(\\\"machineName\\\"|\\\"tenantId\\\"|\\\"instanceId\\\")>>\": {\n \"type\": \"object\",\n \"properties\": {\n \"machineName\": {\n \"type\": \"string\",\n \"description\": \"Machine name\"\n },\n \"tenantId\": {\n \"type\": \"string\"\n },\n \"instanceId\": {\n \"type\": \"string\",\n \"description\": \"Unique instance ID of the machine\"\n }\n },\n \"additionalProperties\": false\n }\n },\n \"methods\": {\n \"machineStateDelete\": {\n \"description\": \"Delete a particular machine state by instance id and tenant id\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/MachineStateDeleteArgs\"\n },\n \"returnType\": {\n \"type\": \"boolean\"\n }\n },\n \"machineStateGet\": {\n \"description\": \"Get a particular machine state by instance id and tenant id\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/MachineStateGetArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"machineStateInit\": {\n \"description\": \"Initializes a state object for a new machine. Does not persist anything\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/InitMachineStateArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/MachineStateInit\"\n }\n },\n \"machineStatePersist\": {\n \"description\": \"Persists the state\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/MachineStatePersistArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n },\n \"machineStatesDeleteExpired\": {\n \"description\": \"Deletes the state of an xstate machine in the database.\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/DeleteExpiredStatesArgs\"\n },\n \"returnType\": {\n \"$ref\": \"#/components/schemas/DeleteStateResult\"\n }\n },\n \"machineStatesFindActive\": {\n \"description\": \"Loads the states of active xstate machines from the database.\",\n \"arguments\": {\n \"$ref\": \"#/components/schemas/FindActiveStatesArgs\"\n },\n \"returnType\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/MachineStateInfo\"\n }\n }\n }\n }\n }\n }\n}","const schema = require('../plugin.schema.json')\nexport { schema }\nexport * from './agent/MachineStatePersistence'\nexport * from './types'\nexport * from './functions'\n","import { IAbstractMachineStateStore, StoreMachineStateInfo } from '@sphereon/ssi-sdk.data-store-types'\nimport { IAgentPlugin } from '@veramo/core'\nimport Debug from 'debug'\nimport { v4 as uuidv4 } from 'uuid'\nimport { deserializeMachineState, machineStateToMachineInit, machineStateToStoreInfo, serializeMachineState } from '../functions'\n\nimport {\n DeleteExpiredStatesArgs,\n DeleteStateResult,\n FindActiveStatesArgs,\n IMachineStatePersistence,\n InitMachineStateArgs,\n MachineStateDeleteArgs,\n MachineStateGetArgs,\n MachineStateInfo,\n MachineStateInit,\n MachineStatePersistArgs,\n MachineStatePersistEvent,\n MachineStatePersistEventType,\n MachineStatePersistOpts,\n RequiredContext,\n schema,\n} from '../index'\n\nconst debug = Debug('sphereon:ssi-sdk:machine-state:xstate-persistence')\n\n/**\n * This class implements the IMachineStatePersistence interface using a datastore.\n *\n * This allows you to store and retrieve the State of a state machine/application by their types.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport class MachineStatePersistence implements IAgentPlugin {\n readonly schema = schema.IMachineStatePersistence\n readonly methods: IMachineStatePersistence | {}\n readonly eventTypes: Array<string>\n private readonly _store?: IAbstractMachineStateStore\n\n get store(): IAbstractMachineStateStore {\n if (!this._store) {\n throw Error('No store available in options')\n }\n return this._store\n }\n\n constructor(opts: MachineStatePersistOpts) {\n const { store, eventTypes, isRESTClient } = opts\n this.eventTypes = eventTypes\n this.methods = {\n machineStatesFindActive: this.machineStatesFindActive.bind(this),\n machineStatesDeleteExpired: this.machineStatesDeleteExpired.bind(this),\n machineStateInit: this.machineStateInit.bind(this),\n machineStatePersist: this.machineStatePersist.bind(this),\n machineStateGet: this.machineStateGet.bind(this),\n machineStateDelete: this.machineStateDelete.bind(this),\n }\n this._store = store\n if (isRESTClient) {\n // Methods are delegated to the REMOTE Agent. We need the above eventTypes however, to ensure the local eventBus works\n // We do set the store, because we might have some local and some remote methods\n return\n } else if (!store) {\n throw Error('No store available in options')\n }\n }\n\n public async onEvent(event: MachineStatePersistEvent, context: RequiredContext): Promise<void> {\n debug(`Received machine state persistence event '${event.type}' counter: ${event.data._eventCounter}}`)\n if (!this.eventTypes.includes(event.type)) {\n console.log(`event type ${event.type} not registered for agent. Registered: ${JSON.stringify(this.eventTypes)}`)\n return\n }\n\n // Below we are calling the context of the agent instead of this to make sure the REST client is called when configured\n switch (event.type) {\n case MachineStatePersistEventType.INIT:\n await context.agent.machineStateInit({ ...event.data })\n break\n case MachineStatePersistEventType.EVERY:\n // We are keeping track of the update counter in the events, ensuring we do not process out of order\n await context.agent.machineStatePersist({\n ...event.data,\n cleanupOnFinalState: event.data.cleanupOnFinalState ?? event.data._cleanupOnFinalState,\n updatedCount: event.data._eventCounter ?? event.data.updatedCount,\n })\n break\n default:\n return Promise.reject(Error(`Event type ${event.type} not supported`))\n }\n }\n\n private async machineStateInit(args: InitMachineStateArgs, context: RequiredContext): Promise<MachineStateInit> {\n const { tenantId, machineName, expiresAt, customInstanceId, existingInstanceId, cleanupAllOtherInstances } = args\n debug(\n `machineStateInit for machine name ${machineName}, tenant ${tenantId}, custom instance ${customInstanceId}, existing id ${existingInstanceId}`,\n )\n if (customInstanceId && existingInstanceId) {\n return Promise.reject(new Error(`Cannot have both a custom and existing instance id at the same time`))\n }\n if (cleanupAllOtherInstances) {\n // First remove all states for this machine name and tenant that are in done state\n await context.agent.machineStatesDeleteExpired({ machineName, tenantId, deleteDoneStates: true })\n // Now cleanup all states for this machine name and tenant that are expired\n await context.agent.machineStatesDeleteExpired({ machineName, tenantId, deleteDoneStates: false })\n // Now remove all machines that are not equal to the existing instance id if provided, or all others if not provided\n const activeMachineStates = (await context.agent.machineStatesFindActive({ machineName, tenantId })).filter(\n (state) => !existingInstanceId || state.instanceId !== existingInstanceId,\n )\n await Promise.all(\n activeMachineStates.map((state) =>\n context.agent.machineStateDelete({\n instanceId: state.instanceId,\n tenantId,\n }),\n ),\n )\n }\n let machineInit: MachineStateInit | undefined = undefined\n let machineState: MachineStateInfo | undefined\n\n if (existingInstanceId) {\n // A existing instanceId is provided. First lookup whether this id is persisted, if not an error is thrown\n debug(`machineStateInit is using a previously persisted instance id (${existingInstanceId})`)\n machineState = await context.agent.machineStateGet({ tenantId, instanceId: existingInstanceId })\n machineInit = machineStateToMachineInit(\n {\n ...machineState,\n machineState: machineState,\n stateType: 'existing',\n },\n { ...machineState, state: serializeMachineState(machineState.state) },\n )\n }\n if (customInstanceId) {\n // A custom instanceId is provided.\n debug(`machineStateInit is using a custom instance id (${customInstanceId})`)\n }\n if (!machineInit) {\n machineInit = {\n machineName,\n tenantId,\n expiresAt,\n instanceId: customInstanceId ?? uuidv4(),\n createdAt: args.createdAt ?? new Date(),\n stateType: 'new',\n }\n }\n return machineInit\n }\n\n private async machineStatePersist(args: MachineStatePersistArgs, context: RequiredContext): Promise<MachineStateInfo> {\n const { instanceId, tenantId, machineName, updatedCount } = args\n const cleanupOnFinalState = args.cleanupOnFinalState !== false\n debug(`machineStatePersist for machine name ${machineName}, updateCount: ${updatedCount}, instance ${instanceId} and tenant ${tenantId}...`)\n try {\n const queriedStates = await this.store.findMachineStates({ filter: [{ instanceId, tenantId }] })\n const existingState = queriedStates.length === 1 ? queriedStates[0] : undefined\n\n const storeInfoArgs = machineStateToStoreInfo(args, existingState)\n let storedState: StoreMachineStateInfo\n if (updatedCount !== undefined && updatedCount > 1 && storeInfoArgs.latestEventType === 'xstate.init') {\n console.log(\n `Not persisting machine state for resumed init event for machine ${machineName}, tenant ${tenantId} and state with id ${instanceId}`,\n )\n storedState = storeInfoArgs\n } else {\n storedState = await this.store.persistMachineState(storeInfoArgs)\n }\n const machineStateInfo = { ...storedState, state: deserializeMachineState(storedState.state) }\n debug(\n `machineStatePersist success for machine name ${machineName}, instance ${instanceId}, update count ${machineStateInfo.updatedCount}, tenant ${tenantId}, last event: ${machineStateInfo.latestEventType}, last state: ${machineStateInfo.latestStateName}`,\n )\n if (cleanupOnFinalState && machineStateInfo.state.done) {\n debug(`reached final state for machine ${machineName} instance ${instanceId} and auto cleanup was enabled. Deleting machine state`)\n await context.agent.machineStateDelete(machineStateInfo)\n }\n return machineStateInfo\n } catch (error) {\n console.log(error)\n return Promise.reject(error)\n }\n }\n\n private async machineStatesFindActive(args: FindActiveStatesArgs): Promise<Array<MachineStateInfo>> {\n const { machineName, tenantId } = args\n debug(`machineStateFindActive for machine name ${machineName} and tenant ${tenantId}...`)\n const storedStates = await this.store.findActiveMachineStates(args)\n const machineStateInfos = storedStates.map((storedState: StoreMachineStateInfo) => {\n return { ...storedState, state: deserializeMachineState(storedState.state) }\n })\n debug(`machineStateFindActive returned ${machineStateInfos.length} results for machine name ${machineName} and tenant ${tenantId}`)\n return machineStateInfos\n }\n\n private async machineStatesDeleteExpired(args: DeleteExpiredStatesArgs): Promise<DeleteStateResult> {\n const { machineName, tenantId } = args\n debug(`machineStatesDeleteExpired for machine name ${machineName} and tenant ${tenantId}...`)\n const deleteResult = await this.store.deleteExpiredMachineStates(args)\n debug(`machineStatesDeleteExpired result for machine name ${machineName} and tenant ${tenantId}: ${deleteResult}`)\n return deleteResult\n }\n\n private async machineStateGet(args: MachineStateGetArgs, context: RequiredContext): Promise<MachineStateInfo> {\n const { instanceId, tenantId } = args\n debug(`machineStateGet for machine instance ${instanceId} and tenant ${tenantId}...`)\n const storedState = await this.store.getMachineState(args)\n const machineInfo = { ...storedState, state: deserializeMachineState(storedState.state) }\n debug(`machineStateGet success for machine instance ${instanceId} and tenant ${tenantId}`)\n return machineInfo\n }\n\n private async machineStateDelete(args: MachineStateDeleteArgs, context: RequiredContext): Promise<boolean> {\n const { instanceId, tenantId } = args\n debug(`machineStateDelete for machine instance ${instanceId} and tenant ${tenantId}...`)\n const deleteResult = await this.store.deleteMachineState(args)\n debug(`machineStateDelete result for machine instance ${instanceId} and tenant ${tenantId}: ${deleteResult}`)\n return deleteResult\n }\n}\n","import { IAgentContext, TAgent } from '@veramo/core'\nimport { DefaultContext, EventObject, Interpreter, State, StateSchema, TypegenDisabled, Typestate } from 'xstate'\nimport { waitFor } from 'xstate/lib/waitFor.js'\nimport {\n IMachineStatePersistence,\n InitMachineStateArgs,\n MachineStateInfo,\n MachineStateInit,\n MachineStateInitType,\n MachineStatePersistenceOpts,\n MachineStatePersistEventType,\n StartedInterpreterInfo,\n} from '../types'\nimport { emitMachineStatePersistEvent } from './stateEventEmitter'\nimport { machineStateToMachineInit, machineStateToStoreInfo } from './stateMapper'\n\n/**\n * Initialize the machine state persistence. Returns a unique instanceId and the machine name amongst others\n *\n * @param {Object} opts - The options for initializing the machine state persistence.\n * @param {InitMachineStateArgs} opts - The arguments for initializing the machine state.\n * @param {IAgentContext<any>} opts.context - The agent context.\n * @returns {Promise<MachineStateInit | undefined>} - A promise that resolves to the initialized machine state, or undefined if the agent isn't using the Xstate plugin.\n */\nexport const machineStatePersistInit = async (\n opts: InitMachineStateArgs &\n Pick<MachineStatePersistenceOpts, 'existingInstanceId' | 'customInstanceId'> & {\n context: IAgentContext<any> // We use any as this method could be called from an agent with access to, but not exposing this plugin\n },\n): Promise<MachineStateInit | undefined> => {\n // make sure the machine context does not end up in the machine state init args\n const { context, ...args } = opts\n if (!(context.agent.availableMethods().includes('machineStateInit') && 'machineStateInit' in context.agent)) {\n console.log(`IMachineStatePersistence was not exposed in the current agent. Not initializing new persistence object`)\n return\n }\n return await (context as IAgentContext<IMachineStatePersistence>).agent.machineStateInit(args)\n}\n\n/**\n * This function allows for the persistence of machine state on every xstate transition. It emits an event with the new state\n * and other relevant data to be handled by the persistence plugin when enabled.\n *\n * @param {Object} opts - The options object.\n * @param {Interpreter} opts.instance - The XState machine interpreter instance.\n * @param {IAgentContext<any>} opts.context - The agent context.\n * @param {MachineStateInit} opts.init - The initial persistence options, containing the unique instanceId.\n * @returns {Promise<void>} - A promise that resolves when the persistence event is emitted.\n */\nexport const machineStatePersistOnTransition = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(opts: {\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<any> // We use any as this method could be called from an agent with access to, but not exposing this plugin\n init: MachineStateInit\n cleanupOnFinalState?: boolean\n}): Promise<void> => {\n const { cleanupOnFinalState, context, init, interpreter } = opts\n const { machineState, ...initEventData } = init\n if (!(context.agent.availableMethods().includes('machineStatePersist') && 'machineStatePersist' in context.agent)) {\n console.log(`IMachineStatePersistence was not exposed in the current agent. Disabling machine state persistence events`)\n return\n }\n // We are using the event counter and evenDate to ensure we do not overwrite newer states. Events could come in out of order\n let _eventCounter = init.machineState?.updatedCount ?? 0\n\n // XState persistence plugin is available. So let's emit events on every transition, so it can persist the state\n interpreter.onChange(async (_machineContext) => {\n /*await (context.agent as TAgent<IMachineStatePersistence>).machineStatePersist({\n ...initEventData, // init value with machineState removed, as we are getting the latest state here\n state: interpreter.getSnapshot(),\n updatedCount: ++_eventCounter,\n cleanupOnFinalState: cleanupOnFinalState !== false,\n })*/\n emitMachineStatePersistEvent(\n {\n type: MachineStatePersistEventType.EVERY,\n data: {\n ...initEventData, // init value with machineState removed, as we are getting the latest state here\n state: interpreter.getSnapshot(),\n _eventCounter: ++_eventCounter,\n _eventDate: new Date(),\n _cleanupOnFinalState: cleanupOnFinalState !== false,\n },\n },\n context,\n )\n })\n if (cleanupOnFinalState && context.agent.availableMethods().includes('machineStateDelete')) {\n interpreter.onDone((doneEvent) => {\n ;(context.agent as TAgent<IMachineStatePersistence>).machineStateDelete({\n tenantId: initEventData.tenantId,\n instanceId: initEventData.instanceId,\n })\n })\n }\n}\n\n/**\n * Persist the initial state of a machine and register it with the given machine instance.\n *\n * @param {InitMachineStateArgs & {instance: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>, context: IAgentContext<any>}} args - The options for initializing\n * machine state and registering it.\n * @returns {Promise<MachineStateInit | undefined>} - A promise that resolves to the initial state of the machine, or undefined if the agent isn't using the Xstate plugin.\n */\nexport const machineStatePersistRegistration = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(\n args: Omit<InitMachineStateArgs, 'machineName'> &\n Partial<Pick<InitMachineStateArgs, 'machineName'>> &\n MachineStatePersistenceOpts & {\n cleanupOnFinalState?: boolean\n cleanupAllOtherInstances?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<any> // We use any as this method could be called from an agent with access to, but not exposing this plugin\n },\n): Promise<MachineStateInit | undefined> => {\n const { disablePersistence } = args\n if (disablePersistence === true) {\n return\n }\n\n // We use expires in MS first. If not provided, look at expires at. If not provided, the persistence will not expire\n const expiresAt = args.expireInMS ? new Date(Date.now() + args.expireInMS) : args.expiresAt\n const machineName = args.machineName ?? args.interpreter.machine.id ?? args.interpreter.id\n const init = await machineStatePersistInit({ ...args, machineName, expiresAt })\n if (init) {\n await machineStatePersistOnTransition({ ...args, init })\n }\n return init\n}\n\nconst assertNonExpired = (args: { expiresAt?: Date; machineName: string }) => {\n const { expiresAt, machineName } = args\n if (expiresAt && expiresAt.getTime() < Date.now()) {\n throw new Error(`Cannot resume ${machineName}. It expired at ${expiresAt.toLocaleString()}`)\n }\n}\n\n/**\n * Resumes the interpreter from a given state.\n *\n * @param {Object} args - The arguments for resuming the interpreter.\n * @param {MachineStateInfo} args.machineState - The machine state information.\n * @param {boolean} [args.noRegistration] - If true, no registration will be performed.\n * @param {Interpreter} args.interpreter - The interpreter instance.\n * @param {IAgentContext<IMachineStatePersistence>} args.context - The context for machine state persistence.\n *\n * @returns {Promise<Interpreter>} - A promise that resolves to the resumed interpreter.\n */\nexport const interpreterResumeFromState = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(args: {\n machineState: MachineStateInfo\n noRegistration?: boolean\n cleanupAllOtherInstances?: boolean\n cleanupOnFinalState?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<IMachineStatePersistence>\n}): Promise<StartedInterpreterInfo<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>> => {\n const { interpreter, machineState, context, noRegistration, cleanupAllOtherInstances, cleanupOnFinalState } = args\n const { machineName, instanceId, tenantId } = machineState\n assertNonExpired(machineState)\n if (noRegistration !== true) {\n await machineStatePersistRegistration({\n stateType: 'existing',\n machineName,\n tenantId,\n existingInstanceId: instanceId,\n cleanupAllOtherInstances,\n cleanupOnFinalState,\n context,\n interpreter,\n })\n }\n const state = State.from(machineState.state.value, machineState.state.context)\n // @ts-ignore\n interpreter.start(state)\n // @ts-ignore\n await waitFor(interpreter, (awaitState) => awaitState.matches(state.value))\n\n return {\n machineState,\n init: machineStateToMachineInit(\n {\n ...machineState,\n stateType: 'existing',\n },\n machineStateToStoreInfo({ ...machineState, stateType: 'existing' }),\n ),\n\n interpreter,\n }\n}\n\n/**\n * Resumes or starts the interpreter from the initial machine state.\n *\n * @async\n * @param {Object} args - The arguments for the function.\n * @param {MachineStateInit & {stateType?: MachineStateInitType}} args.init - The initialization state of the machine.\n * @param {boolean} args.noRegistration - Whether registration is required, defaults to false.\n * @param {Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>} args.interpreter - The interpreter object.\n * @param {IAgentContext<IMachineStatePersistence>} args.context - The context object.\n * @returns {Promise} - A promise that resolves to the interpreter instance.\n * @throws {Error} - If the machine name from init does not match the interpreter id.\n */\nexport const interpreterStartOrResumeFromInit = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(args: {\n init: MachineStateInit & { stateType?: MachineStateInitType }\n cleanupAllOtherInstances?: boolean\n cleanupOnFinalState?: boolean\n noRegistration?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<IMachineStatePersistence>\n}): Promise<StartedInterpreterInfo<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>> => {\n const { init, noRegistration, interpreter, cleanupOnFinalState, cleanupAllOtherInstances, context } = args\n const { stateType, instanceId, machineName, tenantId, expiresAt } = init\n if (init.machineName !== interpreter.id) {\n throw new Error(`Machine state init machine name ${init.machineName} does not match name from state machine interpreter ${interpreter.id}`)\n }\n assertNonExpired({ machineName, expiresAt })\n if (noRegistration !== true) {\n await machineStatePersistRegistration({\n stateType: stateType ?? 'existing',\n machineName,\n tenantId,\n ...(stateType === 'existing' && { existingInstanceId: instanceId }),\n ...(stateType === 'new' && { customInstanceId: instanceId }),\n cleanupAllOtherInstances,\n cleanupOnFinalState,\n context,\n interpreter,\n })\n }\n let machineState: MachineStateInfo | undefined\n if (stateType === 'new') {\n interpreter.start()\n } else {\n machineState = await context.agent.machineStateGet({ tenantId, instanceId })\n // @ts-ignore\n interpreter.start(machineState.state)\n }\n // We are waiting a bit\n await new Promise((res) => setTimeout(res, 50))\n return {\n interpreter,\n machineState,\n init,\n }\n}\n\n/**\n * Starts or resumes the given state machine interpreter.\n *\n * @async\n * @param {Object} args - The arguments for starting or resuming the interpreter.\n * @param {MachineStateInitType | 'auto'} [args.stateType] - The state type. Defaults to 'auto'.\n * @param {string} [args.instanceId] - The instance ID.\n * @param {string} [args.machineName] - The machine name.\n * @param {string} [args.tenantId] - The tenant ID.\n * @param {boolean} args.singletonCheck - Whether to perform a singleton check or not. If more than one machine instance is found an error will be thrown\n * @param {boolean} [args.noRegistration] - Whether to skip state change event registration or not.\n * @param {Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>} args.interpreter - The interpreter to start or resume.\n * @param {IAgentContext<IMachineStatePersistence>} args.context - The agent context.\n * @returns {Promise} A promise that resolves when the interpreter is started or resumed.\n * @throws {Error} If there are multiple active instances of the machine and singletonCheck is true.\n * @throws {Error} If a new instance was requested with the same ID as an existing active instance.\n * @throws {Error} If the existing state machine with the given machine name and instance ID cannot be found.\n */\nexport const interpreterStartOrResume = async <\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n>(args: {\n stateType?: MachineStateInitType | 'auto'\n instanceId?: string\n machineName?: string\n tenantId?: string\n singletonCheck: boolean\n noRegistration?: boolean\n cleanupAllOtherInstances?: boolean\n cleanupOnFinalState?: boolean\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n context: IAgentContext<IMachineStatePersistence>\n}): Promise<StartedInterpreterInfo<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>> => {\n const { stateType, singletonCheck, instanceId, tenantId, noRegistration, context, interpreter, cleanupAllOtherInstances, cleanupOnFinalState } =\n args\n const machineName = args.machineName ?? interpreter.id\n let activeStates = await context.agent.machineStatesFindActive({\n machineName,\n tenantId,\n instanceId,\n })\n if (stateType === 'new' && activeStates.length > 0 && cleanupAllOtherInstances) {\n // We cleanup here to not influence the logic below. Normally the agent machineStateInit method does the cleanup\n await Promise.all(\n activeStates.map((state) =>\n context.agent.machineStateDelete({\n tenantId: args.tenantId,\n instanceId: state.instanceId,\n }),\n ),\n )\n // We search again, given the delete is using the passed in tenantId, instead of relying on the persisted tenantId. Should not matter, but just making sure\n activeStates = await context.agent.machineStatesFindActive({\n machineName,\n tenantId,\n instanceId,\n })\n }\n if (singletonCheck && activeStates.length > 0) {\n if (\n stateType === 'new' ||\n (stateType === 'existing' &&\n ((!instanceId && activeStates.length > 1) || (instanceId && activeStates.every((state) => state.instanceId !== instanceId))))\n ) {\n return Promise.reject(new Error(`Found ${activeStates.length} active '${machineName}' instances, but only one is allows at the same time`))\n }\n }\n if (stateType === 'new') {\n if (instanceId && activeStates.length > 0) {\n // Since an instanceId was provided it means the activeStates includes a machine with this instance. But stateType is 'new'\n return Promise.reject(\n new Error(`Found an active '${machineName}' instance with id ${instanceId}, but a new instance was requested with the same id`),\n )\n }\n const init = await context.agent.machineStateInit({\n stateType: 'new',\n customInstanceId: instanceId,\n machineName: machineName ?? interpreter.id,\n tenantId,\n cleanupAllOtherInstances,\n })\n return await interpreterStartOrResumeFromInit({\n init,\n noRegistration,\n interpreter,\n context,\n cleanupOnFinalState,\n cleanupAllOtherInstances,\n })\n }\n if (activeStates.length === 0) {\n if (stateType === 'existing') {\n return Promise.reject(new Error(`Could not find existing state machine ${machineName}, instanceId ${instanceId}`))\n }\n const init = await context.agent.machineStateInit({\n stateType: 'new',\n customInstanceId: instanceId,\n machineName: machineName ?? interpreter.id,\n tenantId,\n cleanupAllOtherInstances,\n })\n return await interpreterStartOrResumeFromInit({\n init,\n noRegistration,\n interpreter,\n context,\n cleanupOnFinalState,\n cleanupAllOtherInstances,\n })\n }\n\n // activeStates length >= 1\n const activeState = activeStates[0]\n return interpreterResumeFromState({\n machineState: activeState,\n noRegistration,\n interpreter,\n context,\n cleanupOnFinalState,\n cleanupAllOtherInstances,\n })\n}\n","import {\n IAbstractMachineStateStore,\n StoreMachineStateDeleteExpiredArgs,\n StoreMachineStateInfo,\n StoreMachineStatesFindActiveArgs,\n} from '@sphereon/ssi-sdk.data-store-types'\nimport { IAgentContext } from '@veramo/core'\nimport {\n AnyEventObject,\n DefaultContext,\n EventObject,\n HistoryValue,\n Interpreter,\n SCXML,\n StateSchema,\n StateValue,\n TypegenDisabled,\n Typestate,\n} from 'xstate'\n\nimport { IMachineStatePersistence } from './IMachineStatePersistence'\n\n/**\n * Represents the options for persisting machine state.\n *\n * @typedef {Object} MachineStatePersistOpts\n * @property {IAbstractMachineStateStore} store - The store used to persist the machine state.\n * @property {Array<string>} eventTypes - The types of events to be persisted.\n */\nexport type MachineStatePersistOpts = { store?: IAbstractMachineStateStore; eventTypes: Array<string>; isRESTClient?: boolean }\n\n/**\n * Enum representing the types of machine state persist events.\n * @enum {string}\n */\nexport enum MachineStatePersistEventType {\n INIT = 'INIT',\n EVERY = 'EVERY',\n}\n\n/**\n * Represents the arguments for deleting expired states from a machine.\n */\nexport type DeleteExpiredStatesArgs = Pick<StoreMachineStateDeleteExpiredArgs, 'deleteDoneStates' | 'machineName' | 'tenantId'>\n\n/**\n * Represents the arguments for finding active states of a store machine.\n */\nexport type FindActiveStatesArgs = StoreMachineStatesFindActiveArgs\n\n/**\n * Represents the result of a state deletion operation.\n *\n * @typedef {number} DeleteStateResult\n */\nexport type DeleteStateResult = number\n\n/**\n * Represents a machine state persist event.\n *\n * @typedef {Object} MachineStatePersistEvent\n * @property {MachineStatePersistEventType} type - The type of the persist event.\n * @property {MachineStatePersistArgs} data - The data associated with the persist event, along with additional properties `_eventCounter` and `_eventDate`.\n * @property {number} data._eventCounter - The counter for the persist event.\n * @property {Date} data._eventDate - The date and time the persist event occurred.\n */\nexport type MachineStatePersistEvent = {\n type: MachineStatePersistEventType\n data: Omit<MachineStatePersistArgs, 'machineState'> & {\n _eventCounter: number\n _eventDate: Date\n _cleanupOnFinalState: boolean\n }\n}\n\n/**\n * Represents a RequiredContext class, which is a type definition for the context required by an agent.\n * It is used to enforce that the agent context implements the necessary interfaces.\n *\n * @typeparam T - The type of the machine state persistence.\n */\nexport type RequiredContext = IAgentContext<IMachineStatePersistence>\n\n/**\n * Represents the information about the current state of a machine.\n * @typedef {Object} MachineStateInfo\n * @property {string} id - The ID of the machine.\n * @property {SerializableState} state - The serializable state of the machine.\n * @property {string} description - The description of the machine state.\n */\nexport type MachineStateInfo = Omit<StoreMachineStateInfo, 'state'> & {\n state: SerializableState\n}\n\nexport type MachineStatePersistenceOpts = {\n disablePersistence?: boolean // Disable persistence altogether\n customInstanceId?: string // Used when creating a machine using a custom new instance id\n existingInstanceId?: string // Used when creating a machine using an existing instance (rehydrating a persisted machine)\n expireInMS?: number // Expire in an amount of MS (takes precedence over date if both are provided!)\n expiresAt?: Date // Expire at a specific date\n}\n\nexport type MachineStateInitType = 'new' | 'existing'\n\n/**\n * Represents the initial state for a machine.\n *\n * @typedef {Object} MachineStateInit\n * @property {string} existingInstanceId - The unique identifier for the machine instance.\n * @property {string} machineName - The name of the machine.\n * @property {string} tenantId - The identifier for the tenant associated with the machine.\n * @property {Date} createdAt - The date and time when the machine was created.\n * @property {Date} expiresAt - The date and time when the machine's state expires.\n */\nexport type MachineStateInit = Pick<MachineStateInfo, 'instanceId' | 'machineName' | 'tenantId' | 'createdAt' | 'expiresAt'> & {\n stateType: MachineStateInitType\n machineState?: MachineStateInfo // Only available when stateType is 'existing'\n}\n\n/**\n * Represents the arguments required to initialize the machine state.\n * @typedef {Object} InitMachineStateArgs\n * @property {string} machineName - The name of the machine.\n * @property {Partial<MachineStateInit>} [additionalArgs] - Additional initialization arguments for the machine state.\n */\nexport type InitMachineStateArgs = Omit<Partial<MachineStateInit>, 'instanceId'> &\n Pick<MachineStateInfo, 'machineName'> &\n Pick<MachineStatePersistenceOpts, 'customInstanceId' | 'existingInstanceId'> & { cleanupAllOtherInstances?: boolean }\n\n/**\n * Represents the arguments required to persist the machine state.\n */\nexport type MachineStatePersistArgs = Omit<MachineStateInit, 'createdAt'> &\n Pick<MachineStateInfo, 'state' | 'instanceId'> &\n Partial<Pick<MachineStateInfo, 'updatedCount'>> & { cleanupOnFinalState?: boolean }\n\n/**\n * Represents the arguments required to get machine state.\n * @typedef {Object} MachineStateGetArgs\n * @property {string} existingInstanceId - The ID of the machine instance.\n * @property {string} tenantId - The ID of the tenant the machine belongs to.\n */\nexport type MachineStateGetArgs = Pick<StoreMachineStateInfo, 'instanceId' | 'tenantId'>\n\n/**\n * Represents the arguments required for deleting a machine state.\n *\n * @typedef {object} MachineStateDeleteArgs\n * @property {string} existingInstanceId - The ID of the machine instance to delete the state for.\n * @property {string} tenantId - The ID of the tenant owning the machine instance.\n */\nexport type MachineStateDeleteArgs = Pick<StoreMachineStateInfo, 'instanceId' | 'tenantId'>\n\n/**\n * Represents the information for a started interpreter.\n *\n * @template TContext The type of the context object.\n * @template TStateSchema The type of the state schema.\n * @template TEvent The type of the event object.\n * @template TTypestate The type of the typestate object.\n * @template TResolvedTypesMeta The type of the resolved types meta object.\n */\nexport type StartedInterpreterInfo<\n TContext = DefaultContext,\n TStateSchema extends StateSchema = any,\n TEvent extends EventObject = EventObject,\n TTypestate extends Typestate<TContext> = {\n value: any\n context: TContext\n },\n TResolvedTypesMeta = TypegenDisabled,\n> = {\n interpreter: Interpreter<TContext, TStateSchema, TEvent, TTypestate, TResolvedTypesMeta>\n machineState?: MachineStateInfo\n init: MachineStateInit\n}\n\n/**\n * Represents the serializable state of a machine.\n *\n * @typedef {Object} SerializableState\n * @property {XStateConfig<any, AnyEventObject>} config - The machine configuration.\n */\nexport type SerializableState = XStateConfig<any, AnyEventObject>\n\n/**\n * The configuration for the XState machine state. Simplified StateConfig object from XState so we have a minimal typed structure\n *\n * @template TContext - The context type for the state.\n * @template TEvent - The event type for the state.\n */\nexport interface XStateConfig<TContext, TEvent extends EventObject> {\n value: StateValue\n context: TContext\n _event: SCXML.Event<TEvent>\n _sessionid: string | null\n historyValue?: HistoryValue | undefined\n history?: any\n actions?: Array<any>\n activities?: any\n meta?: any\n events?: TEvent[]\n configuration: Array<any>\n transitions: Array<any>\n children: Record<string, any>\n done?: boolean\n tags?: Set<string>\n machine?: any\n}\n","import Debug from 'debug'\nimport { MachineStatePersistEvent, RequiredContext } from '../types'\n\nconst debug = Debug('sphereon:ssi-sdk:machine-state:xstate-persistence')\n\n/**\n * Emits a machine state persistence event.\n *\n * @param {MachineStatePersistEvent} event - The event to be emitted.\n * @param {RequiredContext} context - The required agent context for the event emission.\n * @returns {void}\n */\nexport const emitMachineStatePersistEvent = (event: MachineStatePersistEvent, context: RequiredContext) => {\n debug(\n `Emitting machine state persistence event '${event.type}' with counter: ${event.data._eventCounter} and state ${JSON.stringify(\n event.data.state.value,\n )}`,\n )\n void context.agent.emit(event.type, event.data)\n}\n","import { StoreMachineStateInfo } from '@sphereon/ssi-sdk.data-store-types'\nimport { State } from 'xstate'\nimport { EventObject } from 'xstate/lib/types'\nimport { MachineStateInfo, MachineStateInit, MachineStateInitType, MachineStatePersistArgs, SerializableState } from '../types'\n\n/**\n * Create a machine state info object useful for the store, based on the provided machine info and existing state.\n *\n * @param {MachineStatePersistArgs} machineInfo - The machine info object.\n * @param {Partial<StoreMachineStateInfo>} [existingState] - The optional existing state object.\n * @returns {StoreMachineStateInfo} - The store machine state info object.\n */\nexport const machineStateToStoreInfo = (\n machineInfo: MachineStatePersistArgs,\n existingState?: Partial<StoreMachineStateInfo>,\n): StoreMachineStateInfo => {\n const { state, machineName, tenantId, expiresAt, instanceId, updatedCount } = machineInfo\n\n const existing: Partial<StoreMachineStateInfo> = existingState ?? { machineName, createdAt: new Date(), expiresAt }\n const stateInstance = State.create(machineInfo.state)\n let latestStateName = undefined\n if (stateInstance.value) {\n latestStateName = typeof stateInstance.value === 'string' ? stateInstance.value : JSON.stringify(stateInstance.value)\n }\n if (latestStateName === '{}') {\n latestStateName = undefined\n }\n return {\n instanceId,\n updatedCount: updatedCount ?? (existing?.updatedCount ? existing.updatedCount++ : 0),\n sessionId: stateInstance._sessionid ?? undefined,\n machineName,\n state: serializeMachineState(state),\n tenantId,\n latestStateName,\n latestEventType: stateInstance.event.type,\n updatedAt: new Date(),\n expiresAt,\n createdAt: existing.createdAt ?? new Date(),\n completedAt: existing.completedAt ?? (stateInstance.done ? new Date() : undefined),\n }\n}\nexport const storeInfoToMachineInit = (\n args: StoreMachineStateInfo & { stateType: MachineStateInitType; machineState?: MachineStateInfo },\n): MachineStateInit => {\n const { instanceId, machineName, tenantId, expiresAt, createdAt, stateType, machineState } = args\n return {\n stateType,\n machineName,\n tenantId,\n expiresAt,\n instanceId,\n createdAt,\n machineState,\n }\n}\n\nexport const machineStateToMachineInit = (machineInfo: MachineStatePersistArgs, existingState: Partial<StoreMachineStateInfo>): MachineStateInit => {\n return storeInfoToMachineInit({\n ...machineStateToStoreInfo(machineInfo, existingState),\n stateType: 'existing',\n machineState: machineInfo.machineState,\n })\n}\n\n/**\n * Serializes a machine state to a string representation.\n *\n * @param {State<T, TEvent> | SerializableState | string} state - The machine state to serialize.\n * @returns {string} - The serialized machine state.\n */\nexport const serializeMachineState = <T, TEvent extends EventObject>(state: State<T, TEvent> | SerializableState | string): string => {\n if (typeof state === 'string') {\n return state\n }\n const jsonState = 'toJSON' in state ? state.toJSON() : state\n return JSON.stringify(jsonState)\n}\n/**\n * Deserializes a serialized machine state.\n *\n * @template T - The type of the machine's context.\n * @template TEvent - The type of the events that the machine handles.\n * @param {string} state - The serialized machine state.\n * @returns {State<T, TEvent>} - The deserialized machine state.\n */\nexport const deserializeMachineState = <T, TEvent extends EventObject>(state: string): State<T, TEvent> => {\n return State.create(JSON.parse(state))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,gCAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,0BAA4B;AAAA,QAC1B,YAAc;AAAA,UACZ,SAAW;AAAA,YACT,wBAA0B;AAAA,cACxB,MAAQ;AAAA,YACV;AAAA,YACA,yDAA6D;AAAA,cAC3D,MAAQ;AAAA,cACR,YAAc;AAAA,gBACZ,YAAc;AAAA,kBACZ,MAAQ;AAAA,kBACR,aAAe;AAAA,gBACjB;AAAA,gBACA,UAAY;AAAA,kBACV,MAAQ;AAAA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,WAAAA,eAA0BD,QAAAA,KAAa;AAC5F,UAAMuC,eAAe,MAAM,KAAKvE,MAAMwE,2BAA2BzC,IAAAA;AACjEvC,IAAAA,OAAM,sDAAsDyC,WAAAA,eAA0BD,QAAAA,KAAauC,YAAAA,EAAc;AACjH,WAAOA;EACT;EAEA,MAAc9D,gBAAgBsB,MAA2BlB,SAAqD;AAC5G,UAAM,EAAE6B,YAAYV,SAAQ,IAAKD;AACjCvC,IAAAA,OAAM,wCAAwCkD,UAAAA,eAAyBV,QAAAA,KAAa;AACpF,UAAM4B,cAAc,MAAM,KAAK5D,MAAMyE,gBAAgB1C,IAAAA;AACrD,UAAM2C,cAAc;MAAE,GAAGd;MAAanB,OAAOuB,wBAAwBJ,YAAYnB,KAAK;IAAE;AACxFjD,IAAAA,OAAM,gDAAgDkD,UAAAA,eAAyBV,QAAAA,EAAU;AACzF,WAAO0C;EACT;EAEA,MAAchE,mBAAmBqB,MAA8BlB,SAA4C;AACzG,UAAM,EAAE6B,YAAYV,SAAQ,IAAKD;AACjCvC,IAAAA,OAAM,2CAA2CkD,UAAAA,eAAyBV,QAAAA,KAAa;AACvF,UAAMuC,eAAe,MAAM,KAAKvE,MAAM2E,mBAAmB5C,IAAAA;AACzDvC,IAAAA,OAAM,kDAAkDkD,UAAAA,eAAyBV,QAAAA,KAAauC,YAAAA,EAAc;AAC5G,WAAOA;EACT;AACF;;;AD3NA,IAAMK,SAASC;","names":["module","import_debug","import_xstate","MachineStatePersistEventType","debug","Debug","emitMachineStatePersistEvent","event","context","type","data","_eventCounter","JSON","stringify","state","value","agent","emit","machineStateToStoreInfo","machineInfo","existingState","state","machineName","tenantId","expiresAt","instanceId","updatedCount","existing","createdAt","Date","stateInstance","State","create","latestStateName","undefined","value","JSON","stringify","sessionId","_sessionid","serializeMachineState","latestEventType","event","type","updatedAt","completedAt","done","storeInfoToMachineInit","args","stateType","machineState","machineStateToMachineInit","jsonState","toJSON","deserializeMachineState","parse","machineStatePersistInit","opts","context","args","agent","availableMethods","includes","console","log","machineStateInit","machineStatePersistOnTransition","cleanupOnFinalState","init","interpreter","machineState","initEventData","_eventCounter","updatedCount","onChange","_machineContext","emitMachineStatePersistEvent","type","MachineStatePersistEventType","EVERY","data","state","getSnapshot","_eventDate","Date","_cleanupOnFinalState","onDone","doneEvent","machineStateDelete","tenantId","instanceId","machineStatePersistRegistration","disablePersistence","expiresAt","expireInMS","now","machineName","machine","id","assertNonExpired","getTime","Error","toLocaleString","interpreterResumeFromState","noRegistration","cleanupAllOtherInstances","stateType","existingInstanceId","State","from","value","start","waitFor","awaitState","matches","machineStateToMachineInit","machineStateToStoreInfo","interpreterStartOrResumeFromInit","customInstanceId","machineStateGet","Promise","res","setTimeout","interpreterStartOrResume","singletonCheck","activeStates","machineStatesFindActive","length","all","map","every","reject","activeState","debug","Debug","MachineStatePersistence","schema","IMachineStatePersistence","methods","eventTypes","_store","store","Error","opts","isRESTClient","machineStatesFindActive","bind","machineStatesDeleteExpired","machineStateInit","machineStatePersist","machineStateGet","machineStateDelete","onEvent","event","context","type","data","_eventCounter","includes","console","log","JSON","stringify","MachineStatePersistEventType","INIT","agent","EVERY","cleanupOnFinalState","_cleanupOnFinalState","updatedCount","Promise","reject","args","tenantId","machineName","expiresAt","customInstanceId","existingInstanceId","cleanupAllOtherInstances","deleteDoneStates","activeMachineStates","filter","state","instanceId","all","map","machineInit","undefined","machineState","machineStateToMachineInit","stateType","serializeMachineState","uuidv4","createdAt","Date","queriedStates","findMachineStates","existingState","length","storeInfoArgs","machineStateToStoreInfo","storedState","latestEventType","persistMachineState","machineStateInfo","deserializeMachineState","latestStateName","done","error","storedStates","findActiveMachineStates","machineStateInfos","deleteResult","deleteExpiredMachineStates","getMachineState","machineInfo","deleteMachineState","schema","require"]}