@sanity/runtime-cli 17.21.4 → 17.21.5-next.g162b704

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/README.md +19 -19
  2. package/dist/cores/functions/test.js +2 -3
  3. package/dist/utils/bundles/prepare-asset.js +1 -6
  4. package/dist/utils/functions/child-process-wrapper.js +15 -4
  5. package/dist/utils/functions/child-runtime/callback.d.ts +10 -10
  6. package/dist/utils/functions/child-runtime/callback.js +4 -29
  7. package/dist/utils/functions/child-runtime/durables/delegate.js +44 -0
  8. package/dist/utils/functions/child-runtime/durables/durable.d.ts +29 -0
  9. package/dist/utils/functions/child-runtime/durables/durable.js +91 -0
  10. package/dist/utils/functions/child-runtime/durables/eventsFactoryPlugin.js +171 -0
  11. package/dist/utils/functions/child-runtime/durables/fanout.js +24 -0
  12. package/dist/utils/functions/child-runtime/durables/index.js +45 -0
  13. package/dist/utils/functions/child-runtime/durables/logger.js +31 -0
  14. package/dist/utils/functions/child-runtime/durables/retry.js +60 -0
  15. package/dist/utils/functions/child-runtime/durables/run.js +23 -0
  16. package/dist/utils/functions/child-runtime/durables/utils.js +20 -0
  17. package/dist/utils/functions/child-runtime/durables/wait.js +11 -0
  18. package/dist/utils/functions/child-runtime/durables/waitForCallback.js +40 -0
  19. package/dist/utils/functions/child-runtime/durables/waitForCondition.js +44 -0
  20. package/oclif.manifest.json +1 -1
  21. package/package.json +7 -5
  22. package/dist/utils/functions/child-runtime/durable.d.ts +0 -18
  23. package/dist/utils/functions/child-runtime/durable.js +0 -264
  24. package/dist/utils/functions/child-runtime/getBatchResults.d.ts +0 -6
  25. package/dist/utils/functions/child-runtime/getBatchResults.js +0 -74
  26. package/dist/utils/functions/child-runtime/step-history.d.ts +0 -15
  27. package/dist/utils/functions/child-runtime/step-history.js +0 -52
package/README.md CHANGED
@@ -90,7 +90,7 @@ EXAMPLES
90
90
  $ sanity-run blueprints add function --name my-function --fn-type document-create --fn-type document-update --lang js
91
91
  ```
92
92
 
93
- _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/add.ts)_
93
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/add.ts)_
94
94
 
95
95
  ## `sanity-run blueprints config`
96
96
 
@@ -127,7 +127,7 @@ EXAMPLES
127
127
  $ sanity-run blueprints config --edit --project-id <projectId> --stack <name-or-id>
128
128
  ```
129
129
 
130
- _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/config.ts)_
130
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/config.ts)_
131
131
 
132
132
  ## `sanity-run blueprints deploy`
133
133
 
@@ -183,7 +183,7 @@ EXAMPLES
183
183
  $ sanity-run blueprints deploy --new-stack-name <new-name>
184
184
  ```
185
185
 
186
- _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/deploy.ts)_
186
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/deploy.ts)_
187
187
 
188
188
  ## `sanity-run blueprints destroy`
189
189
 
@@ -221,7 +221,7 @@ EXAMPLES
221
221
  $ sanity-run blueprints destroy --stack <name-or-id> --project-id <projectId> --force --no-wait
222
222
  ```
223
223
 
224
- _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/destroy.ts)_
224
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/destroy.ts)_
225
225
 
226
226
  ## `sanity-run blueprints doctor`
227
227
 
@@ -253,7 +253,7 @@ EXAMPLES
253
253
  $ sanity-run blueprints doctor --fix
254
254
  ```
255
255
 
256
- _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/doctor.ts)_
256
+ _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/doctor.ts)_
257
257
 
258
258
  ## `sanity-run blueprints info`
259
259
 
@@ -291,7 +291,7 @@ EXAMPLES
291
291
  $ sanity-run blueprints info --organization-id <orgId> --stack <name-or-id>
292
292
  ```
293
293
 
294
- _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/info.ts)_
294
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/info.ts)_
295
295
 
296
296
  ## `sanity-run blueprints init [DIR]`
297
297
 
@@ -355,7 +355,7 @@ EXAMPLES
355
355
  $ sanity-run blueprints init old-stack --type <json|js|ts> --project-id <projectId> --stack-id <existingStackId>
356
356
  ```
357
357
 
358
- _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/init.ts)_
358
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/init.ts)_
359
359
 
360
360
  ## `sanity-run blueprints logs`
361
361
 
@@ -401,7 +401,7 @@ EXAMPLES
401
401
  $ sanity-run blueprints logs --before 2026-05-01T00:00:00Z
402
402
  ```
403
403
 
404
- _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/logs.ts)_
404
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/logs.ts)_
405
405
 
406
406
  ## `sanity-run blueprints mint-deploy-token`
407
407
 
@@ -446,7 +446,7 @@ EXAMPLES
446
446
  $ sanity-run blueprints mint-deploy-token --organization-id <orgId>
447
447
  ```
448
448
 
449
- _See code: [src/commands/blueprints/mint-deploy-token.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/mint-deploy-token.ts)_
449
+ _See code: [src/commands/blueprints/mint-deploy-token.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/mint-deploy-token.ts)_
450
450
 
451
451
  ## `sanity-run blueprints plan`
452
452
 
@@ -479,7 +479,7 @@ EXAMPLES
479
479
  $ sanity-run blueprints plan --organization-id <orgId> --stack <name-or-id>
480
480
  ```
481
481
 
482
- _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/plan.ts)_
482
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/plan.ts)_
483
483
 
484
484
  ## `sanity-run blueprints promote`
485
485
 
@@ -515,7 +515,7 @@ EXAMPLES
515
515
  $ sanity-run blueprints promote --new-stack-name <new-name>
516
516
  ```
517
517
 
518
- _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/promote.ts)_
518
+ _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/promote.ts)_
519
519
 
520
520
  ## `sanity-run blueprints stacks`
521
521
 
@@ -556,7 +556,7 @@ EXAMPLES
556
556
  $ sanity-run blueprints stacks --organization-id <organizationId> --include-projects
557
557
  ```
558
558
 
559
- _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/blueprints/stacks.ts)_
559
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/blueprints/stacks.ts)_
560
560
 
561
561
  ## `sanity-run functions add`
562
562
 
@@ -608,7 +608,7 @@ EXAMPLES
608
608
  $ sanity-run functions add --name my-function --type document-create --type document-update --lang js
609
609
  ```
610
610
 
611
- _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/add.ts)_
611
+ _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/add.ts)_
612
612
 
613
613
  ## `sanity-run functions dev`
614
614
 
@@ -643,7 +643,7 @@ EXAMPLES
643
643
  $ sanity-run functions dev --timeout 60
644
644
  ```
645
645
 
646
- _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/dev.ts)_
646
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/dev.ts)_
647
647
 
648
648
  ## `sanity-run functions env add NAME KEY VALUE`
649
649
 
@@ -676,7 +676,7 @@ EXAMPLES
676
676
  $ sanity-run functions env add --stack <name-or-id> MyFunction API_URL https://api.example.com/
677
677
  ```
678
678
 
679
- _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/env/add.ts)_
679
+ _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/env/add.ts)_
680
680
 
681
681
  ## `sanity-run functions env list NAME`
682
682
 
@@ -706,7 +706,7 @@ EXAMPLES
706
706
  $ sanity-run functions env list --stack <name-or-id> MyFunction
707
707
  ```
708
708
 
709
- _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/env/list.ts)_
709
+ _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/env/list.ts)_
710
710
 
711
711
  ## `sanity-run functions env remove NAME KEY`
712
712
 
@@ -738,7 +738,7 @@ EXAMPLES
738
738
  $ sanity-run functions env remove --stack <name-or-id> MyFunction API_URL
739
739
  ```
740
740
 
741
- _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/env/remove.ts)_
741
+ _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/env/remove.ts)_
742
742
 
743
743
  ## `sanity-run functions logs [NAME]`
744
744
 
@@ -778,7 +778,7 @@ EXAMPLES
778
778
  $ sanity-run functions logs <name> --delete
779
779
  ```
780
780
 
781
- _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/logs.ts)_
781
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/logs.ts)_
782
782
 
783
783
  ## `sanity-run functions test [NAME]`
784
784
 
@@ -836,7 +836,7 @@ EXAMPLES
836
836
  $ sanity-run functions test <name> --event update --data-before '{ "title": "before" }' --data-after '{ "title": "after" }'
837
837
  ```
838
838
 
839
- _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4/src/commands/functions/test.ts)_
839
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.5-next.g162b704/src/commands/functions/test.ts)_
840
840
 
841
841
  ## `sanity-run help [COMMAND]`
842
842
 
@@ -154,9 +154,8 @@ export async function functionTestCore(options) {
154
154
  }
155
155
  continue;
156
156
  }
157
- // Only show nested logs for invoked functions.
158
- // @todo: we may have to show for other events as we add more steps
159
- if (event.kind === 'delegate') {
157
+ // nested logs for durables, emitted in order
158
+ if (event.kind === 'delegate' || event.kind === 'wait-for-callback') {
160
159
  logNestedRuns();
161
160
  }
162
161
  const willRetry = event.phase === 'error' && typeof event.retryDelayMs === 'number';
@@ -110,10 +110,6 @@ async function buildStudioBundle({ resource, appId, workDir, outDir, output, eve
110
110
  // this has been checked before we got here but this helps the type checker
111
111
  if (!appId)
112
112
  throw new Error(`Unable to determine appId for ${resource.type} resource '${resource.name}'`);
113
- // currently we only support hard-coded project, support for dynamic project id to be added
114
- const projectId = resource.project;
115
- if (!projectId || projectId.startsWith('$.'))
116
- throw new Error(`Unable to determine project for ${resource.type} resource '${resource.name}'`);
117
113
  let mismatchedPackages;
118
114
  const { mfManifest } = await buildStudio({
119
115
  appId,
@@ -125,7 +121,7 @@ async function buildStudioBundle({ resource, appId, workDir, outDir, output, eve
125
121
  return result;
126
122
  },
127
123
  determineBasePath() {
128
- return resource.basePath ?? '/';
124
+ return '/';
129
125
  },
130
126
  isApp: false,
131
127
  isBlueprints: true,
@@ -152,7 +148,6 @@ async function buildStudioBundle({ resource, appId, workDir, outDir, output, eve
152
148
  configPath: resource.root,
153
149
  isExternal: false,
154
150
  outPath: outDir,
155
- projectId,
156
151
  schemaRequired: false,
157
152
  verbose: false,
158
153
  workDir,
@@ -4,13 +4,13 @@ import process from 'node:process'
4
4
  import {pathToFileURL} from 'node:url'
5
5
  import {createCallbackHandler} from './child-runtime/callback.js'
6
6
  import {installConsole} from './child-runtime/console.js'
7
- import {runDurable} from './child-runtime/durable.js'
8
7
  import {createInvoker} from './child-runtime/invoke.js'
9
8
  import {createResourcesApi} from './child-runtime/resources.js'
10
9
 
11
10
  installConsole()
12
11
  const invoker = createInvoker()
13
12
  const callback = createCallbackHandler()
13
+ let durableCallbackResponse = null
14
14
 
15
15
  export function getFunctionSource(src) {
16
16
  const pathToCheck = isAbsolute(src) ? src : join(process.cwd(), src)
@@ -42,6 +42,11 @@ process.on('message', async (data) => {
42
42
  }
43
43
 
44
44
  if (jsonData?.type === 'callback-response') {
45
+ if (jsonData.attempt === undefined && durableCallbackResponse) {
46
+ durableCallbackResponse(jsonData)
47
+ return
48
+ }
49
+
45
50
  callback.handleResponse(jsonData)
46
51
  return
47
52
  }
@@ -94,16 +99,22 @@ process.on('message', async (data) => {
94
99
  }
95
100
 
96
101
  if (isDurable) {
102
+ const {runDurable} = await import('./child-runtime/durables/durable.js')
97
103
  json = await runDurable(
98
104
  handler,
99
105
  {context, event},
100
106
  {
101
107
  emit: (e) => process.send(JSON.stringify({type: 'step-event', event: e})),
102
- wait: (ms) => new Promise((resolve) => setTimeout(resolve, noWait ? 0 : ms)),
103
108
  invoke: invoker.delegate,
104
- registerCallback: callback.register,
105
- cancelCallback: callback.cancel,
109
+ registerCallback: ({callbackId, name}) =>
110
+ process.send(JSON.stringify({type: 'callback-register', callbackId, name})),
111
+ cancelCallback: (callbackId) =>
112
+ process.send(JSON.stringify({type: 'callback-cancel', callbackId})),
113
+ onCallbackResponse: (fn) => {
114
+ durableCallbackResponse = fn
115
+ },
106
116
  },
117
+ {noWait},
107
118
  )
108
119
  } else {
109
120
  json = await handler({
@@ -1,15 +1,15 @@
1
1
  import type {ParentToChildMessage} from '../../types.js'
2
2
 
3
+ type CallbackRequest = {
4
+ method?: string
5
+ url: string
6
+ body?: unknown
7
+ timeout?: number | false | {total?: number}
8
+ signal?: AbortSignal
9
+ }
10
+
3
11
  export function createCallbackHandler(): {
4
- cancel: (callbackId: string) => void
5
- register: ({
6
- callbackId,
7
- name,
8
- timeout,
9
- }: {
10
- callbackId: string
11
- name: string
12
- timeout: number
13
- }) => Promise<unknown>
12
+ handleRequest: (request: CallbackRequest, next: (request: CallbackRequest) => unknown) => unknown
14
13
  handleResponse: (msg: Extract<ParentToChildMessage, {type: 'callback-response'}>) => void
14
+ removeRequest: (attempt: number) => unknown
15
15
  }
@@ -11,21 +11,6 @@ export const createCallbackHandler = () => {
11
11
  const pendingRequests = new Map([])
12
12
  let nextAttempt = 0
13
13
 
14
- // Register a callback with the parent process. Returns a Promise that resolves when the callback is invoked, or rejects if the callback times out.
15
- const register = ({callbackId, name, timeout}) => {
16
- return new Promise((resolve, reject) => {
17
- const timer = timeout
18
- ? setTimeout(() => {
19
- cancel(callbackId)
20
- reject(new Error(`Callback ${callbackId} timed out after ${timeout}ms`))
21
- }, timeout)
22
- : undefined
23
-
24
- pendingResponses.set(callbackId, {resolve, reject, timer})
25
- process.send(JSON.stringify({type: 'callback-register', callbackId, name}))
26
- })
27
- }
28
-
29
14
  /**
30
15
  * Handle a response from the parent process for a registered callback. This is called when the parent process sends a `callback-response` message.
31
16
  */
@@ -75,7 +60,9 @@ export const createCallbackHandler = () => {
75
60
  return next(request)
76
61
  }
77
62
 
78
- const [, callbackId, outcome] = match
63
+ // Sanity client url encodes the callbackId, so we need to decode it
64
+ const [, encodedId, outcome] = match
65
+ const callbackId = decodeURIComponent(encodedId)
79
66
  const {body, timeout} = request
80
67
  if (typeof body !== 'string') {
81
68
  throw new TypeError('Callback body must be serialized JSON')
@@ -99,6 +86,7 @@ export const createCallbackHandler = () => {
99
86
  cleanup: () => signal?.removeEventListener('abort', onAbort),
100
87
  })
101
88
  signal?.addEventListener('abort', onAbort, {once: true})
89
+
102
90
  try {
103
91
  process.send(
104
92
  JSON.stringify({type: 'callback-request', callbackId, attempt, outcome, body}),
@@ -131,20 +119,7 @@ export const createCallbackHandler = () => {
131
119
  for (const attempt of pendingRequests.keys()) removeRequest(attempt)?.reject(error)
132
120
  })
133
121
 
134
- /**
135
- * Cancel a pending callback request. This is called when the parent process sends a `callback-cancel` message.
136
- */
137
- const cancel = (callbackId) => {
138
- const pendingEntry = pendingResponses.get(callbackId)
139
- if (!pendingEntry) return
140
- pendingResponses.delete(callbackId)
141
- clearTimeout(pendingEntry?.timer)
142
- process.send(JSON.stringify({type: 'callback-cancel', callbackId}))
143
- }
144
-
145
122
  return {
146
- cancel,
147
- register,
148
123
  handleRequest,
149
124
  handleResponse,
150
125
  removeRequest,
@@ -0,0 +1,44 @@
1
+ import {withRetry} from '@aws/durable-execution-sdk-js'
2
+ import {createStepRetryStrategy} from './retry.js'
3
+
4
+ const createDelegateFunction = (durableContext, runtime) => {
5
+ return async ({name, handler, event, retry}) => {
6
+ const functionName = typeof handler === 'string' ? handler : handler?.name
7
+ if (!functionName) {
8
+ throw new Error(
9
+ 'step.delegate requires a handler: pass a function name or a context.resource entry.',
10
+ )
11
+ }
12
+
13
+ const delegatee = runtime.resources(functionName)
14
+ if (!delegatee?.type.startsWith('sanity.function.')) {
15
+ throw new Error(
16
+ `step.delegate handler function name '${functionName}' is not a function resource within your blueprint!`,
17
+ )
18
+ }
19
+
20
+ const payload = event?.data ?? {}
21
+
22
+ const invoke = (ctx) =>
23
+ name ? ctx.invoke(name, functionName, payload) : ctx.invoke(functionName, payload)
24
+
25
+ if (!retry) {
26
+ return await invoke(durableContext)
27
+ }
28
+
29
+ const config = {
30
+ retryStrategy: createStepRetryStrategy(name || functionName, retry, runtime.retries),
31
+ childContextConfig: {
32
+ // by default, in case of an invoke error (like the delegatee throwing), aws exec sdk would wrap in a ChildContextError
33
+ // this error mapper, instead, just returns the InvokeError directly; one less Error layer to deal with
34
+ errorMapper: (err) => err,
35
+ },
36
+ }
37
+
38
+ return name
39
+ ? await withRetry(durableContext, name, invoke, config)
40
+ : await withRetry(durableContext, invoke, config)
41
+ }
42
+ }
43
+
44
+ export {createDelegateFunction}
@@ -0,0 +1,29 @@
1
+ import type {DurableContext, DurableHandler, GenericEvent} from '@sanity/functions'
2
+ import type {DurableRuntimeEvent} from '../../../types.js'
3
+
4
+ type RunDurableArgs = {
5
+ context: DurableContext
6
+ event: GenericEvent
7
+ }
8
+
9
+ type CallbackResponse = {
10
+ callbackId: string
11
+ ok: boolean
12
+ result?: unknown
13
+ error?: {name?: string; message?: string}
14
+ }
15
+
16
+ export type DurableIo = {
17
+ emit: (event: DurableRuntimeEvent) => void
18
+ invoke: (name: string, payload: unknown) => Promise<unknown>
19
+ registerCallback: (args: {callbackId: string; name: string}) => void
20
+ cancelCallback: (callbackId: string) => void
21
+ onCallbackResponse: (fn: (msg: CallbackResponse) => void) => void
22
+ }
23
+
24
+ export function runDurable(
25
+ handler: DurableHandler,
26
+ args: RunDurableArgs,
27
+ io: DurableIo,
28
+ options?: {noWait?: boolean},
29
+ ): Promise<unknown>
@@ -0,0 +1,91 @@
1
+ import {LocalDurableTestRunner} from '@aws/durable-execution-sdk-js-testing'
2
+ import {createEventsFactoryPlugin} from './eventsFactoryPlugin.js'
3
+ import {durableHandler} from './index.js'
4
+ import {createDurableLogger} from './logger.js'
5
+ import {createRetryTracker} from './retry.js'
6
+
7
+ /**
8
+ * Outputs the StepError as a user-facing Error with the original stack trace.
9
+ */
10
+ const toUserError = (result, runtime, eventsPlugin) => {
11
+ const {errorType, errorMessage, stackTrace} = result.getError()
12
+ const error = new Error(errorMessage)
13
+ error.name = errorType ?? 'Error'
14
+ const original = runtime.lastHandlerError ?? eventsPlugin.lastFailedStepError()
15
+ error.stack = original?.stack ?? stackTrace?.join('\n') ?? `${error.name}: ${error.message}`
16
+ return error
17
+ }
18
+
19
+ const runDurable = async (handler, {context, event}, io, {noWait}) => {
20
+ const RealDate = Date
21
+ const realNow = performance.now.bind(performance)
22
+ const realNextTick = process.nextTick
23
+ const realQueueMicrotask = globalThis.queueMicrotask
24
+
25
+ await LocalDurableTestRunner.setupTestEnvironment({
26
+ skipTime: noWait,
27
+ })
28
+
29
+ /**
30
+ * fake timers in AWS and messages between vitetest and the SDK get dropped in the CI
31
+ * https://github.com/aws/aws-durable-execution-sdk-js/blob/2057d89efe636584203e7b97ee0b87b0b71ecaea/packages/aws-durable-execution-sdk-js-testing/src/test-runner/local/local-durable-test-runner.ts#L540
32
+ */
33
+ process.nextTick = realNextTick
34
+ globalThis.queueMicrotask = realQueueMicrotask
35
+
36
+ try {
37
+ const runtime = {
38
+ io,
39
+ realNow,
40
+ resources: context.resources,
41
+ retries: createRetryTracker(),
42
+ logger: createDurableLogger(io, RealDate),
43
+ callbackOperationIds: new Set(),
44
+ lastHandlerError: undefined,
45
+ }
46
+ const eventsPlugin = createEventsFactoryPlugin(runtime)
47
+
48
+ const runner = new LocalDurableTestRunner({
49
+ handlerFunction: durableHandler(handler, {context, event, runtime, eventsPlugin}),
50
+ })
51
+
52
+ // stand-in for step.delegate since there is no AWS locally
53
+ const functions = context.resources.all().filter((r) => r.type?.startsWith('sanity.function.'))
54
+ for (const resource of functions) {
55
+ runner.registerFunction(
56
+ resource.name,
57
+ async (payload) => (await io.invoke(resource.name, payload)) ?? null,
58
+ )
59
+ }
60
+
61
+ // Callback success/failure messages
62
+ // Find the AWS callback operation and complete it
63
+ io.onCallbackResponse(async (msg) => {
64
+ for (const id of runtime.callbackOperationIds) {
65
+ const operation = runner.getOperationById(id)
66
+ if (operation.getCallbackDetails()?.callbackId !== msg.callbackId) continue
67
+ if (msg.ok) {
68
+ await operation.sendCallbackSuccess(JSON.stringify(msg.result))
69
+ } else {
70
+ await operation.sendCallbackFailure({
71
+ ErrorMessage: msg.error?.message,
72
+ ErrorType: msg.error?.name ?? 'Error',
73
+ })
74
+ }
75
+ return
76
+ }
77
+ })
78
+
79
+ const result = await runner.run({payload: {}})
80
+ if (result.getStatus() === 'SUCCEEDED') {
81
+ return result.getResult()
82
+ }
83
+
84
+ throw toUserError(result, runtime, eventsPlugin)
85
+ } finally {
86
+ // stops server and removes the fake clock
87
+ await LocalDurableTestRunner.teardownTestEnvironment()
88
+ }
89
+ }
90
+
91
+ export {runDurable}