@sanity/runtime-cli 17.21.3 → 17.21.4-next.g63b83f1

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 (30) hide show
  1. package/README.md +20 -20
  2. package/dist/commands/blueprints/destroy.js +1 -1
  3. package/dist/cores/blueprints/destroy.js +8 -4
  4. package/dist/cores/functions/test.js +2 -3
  5. package/dist/utils/bundles/stamp-config-version.js +8 -27
  6. package/dist/utils/functions/child-process-wrapper.js +15 -4
  7. package/dist/utils/functions/child-runtime/callback.d.ts +10 -10
  8. package/dist/utils/functions/child-runtime/callback.js +4 -29
  9. package/dist/utils/functions/child-runtime/durables/delegate.js +44 -0
  10. package/dist/utils/functions/child-runtime/durables/durable.d.ts +29 -0
  11. package/dist/utils/functions/child-runtime/durables/durable.js +91 -0
  12. package/dist/utils/functions/child-runtime/durables/eventsFactoryPlugin.js +171 -0
  13. package/dist/utils/functions/child-runtime/durables/fanout.js +24 -0
  14. package/dist/utils/functions/child-runtime/durables/index.js +45 -0
  15. package/dist/utils/functions/child-runtime/durables/logger.js +31 -0
  16. package/dist/utils/functions/child-runtime/durables/retry.js +60 -0
  17. package/dist/utils/functions/child-runtime/durables/run.js +23 -0
  18. package/dist/utils/functions/child-runtime/durables/utils.js +20 -0
  19. package/dist/utils/functions/child-runtime/durables/wait.js +11 -0
  20. package/dist/utils/functions/child-runtime/durables/waitForCallback.js +40 -0
  21. package/dist/utils/functions/child-runtime/durables/waitForCondition.js +44 -0
  22. package/oclif.manifest.json +2 -2
  23. package/package.json +4 -2
  24. package/skills/blueprints-destroy.md +1 -1
  25. package/dist/utils/functions/child-runtime/durable.d.ts +0 -18
  26. package/dist/utils/functions/child-runtime/durable.js +0 -264
  27. package/dist/utils/functions/child-runtime/getBatchResults.d.ts +0 -6
  28. package/dist/utils/functions/child-runtime/getBatchResults.js +0 -74
  29. package/dist/utils/functions/child-runtime/step-history.d.ts +0 -15
  30. 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.3/src/commands/blueprints/add.ts)_
93
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/config.ts)_
130
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/deploy.ts)_
186
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/src/commands/blueprints/deploy.ts)_
187
187
 
188
188
  ## `sanity-run blueprints destroy`
189
189
 
@@ -206,7 +206,7 @@ DESCRIPTION
206
206
  Destroy a remote Stack deployment and its resources
207
207
 
208
208
  Permanently removes the remote Stack and all its provisioned resources. Your Blueprint manifest and resource files
209
- remain intact; "stackId" is unset in your local config.
209
+ remain intact; "stackId" is unset in your local config once destruction completes (or immediately with --no-wait).
210
210
 
211
211
  This is a destructive operation. You will be prompted to confirm unless --force is specified.
212
212
 
@@ -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.3/src/commands/blueprints/destroy.ts)_
224
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/doctor.ts)_
256
+ _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/info.ts)_
294
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/init.ts)_
358
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/logs.ts)_
404
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/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.4-next.g63b83f1/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.3/src/commands/blueprints/plan.ts)_
482
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/promote.ts)_
518
+ _See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/blueprints/stacks.ts)_
559
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/functions/add.ts)_
611
+ _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/functions/dev.ts)_
646
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/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.4-next.g63b83f1/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.3/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.4-next.g63b83f1/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.3/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.4-next.g63b83f1/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.3/src/commands/functions/logs.ts)_
781
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/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.3/src/commands/functions/test.ts)_
839
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.4-next.g63b83f1/src/commands/functions/test.ts)_
840
840
 
841
841
  ## `sanity-run help [COMMAND]`
842
842
 
@@ -5,7 +5,7 @@ import { Logger } from '../../utils/logger.js';
5
5
  export default class DestroyCommand extends ResolvedCommand {
6
6
  static needs = ['scope'];
7
7
  static summary = 'Destroy a remote Stack deployment and its resources';
8
- static description = `Permanently removes the remote Stack and all its provisioned resources. Your Blueprint manifest and resource files remain intact; "stackId" is unset in your local config.
8
+ static description = `Permanently removes the remote Stack and all its provisioned resources. Your Blueprint manifest and resource files remain intact; "stackId" is unset in your local config once destruction completes (or immediately with --no-wait).
9
9
 
10
10
  This is a destructive operation. You will be prompted to confirm unless --force is specified.
11
11
 
@@ -27,7 +27,6 @@ export async function blueprintDestroyCore(options) {
27
27
  if (!ok) {
28
28
  return { success: false, error: error || 'Failed to destroy Stack deployment', requestId };
29
29
  }
30
- clearLocalStackIdFromConfig(blueprintConfig, stack.id, log);
31
30
  return afterDestroyAccepted({
32
31
  stackId: stack.id,
33
32
  stackName: stack.name,
@@ -38,6 +37,7 @@ export async function blueprintDestroyCore(options) {
38
37
  log,
39
38
  bin,
40
39
  verbose,
40
+ blueprintConfig,
41
41
  });
42
42
  }
43
43
  if (!scopeType || !scopeId)
@@ -107,7 +107,6 @@ export async function blueprintDestroyCore(options) {
107
107
  return { success: false, error: error || 'Failed to destroy Stack deployment', requestId };
108
108
  }
109
109
  destroySpinner.stop().clear();
110
- clearLocalStackIdFromConfig(blueprintConfig, stack.id, log);
111
110
  return afterDestroyAccepted({
112
111
  stackId: stack.id,
113
112
  stackName: stack.name,
@@ -118,6 +117,7 @@ export async function blueprintDestroyCore(options) {
118
117
  log,
119
118
  bin,
120
119
  verbose,
120
+ blueprintConfig,
121
121
  });
122
122
  }
123
123
  catch (error) {
@@ -139,10 +139,12 @@ function clearLocalStackIdFromConfig(blueprintConfig, destroyedStackId, log) {
139
139
  }
140
140
  }
141
141
  function afterDestroyAccepted(options) {
142
- const { stackId, stackName, requestId, noWait, log, verbose = false } = options;
142
+ const { stackId, stackName, requestId, noWait, log, verbose = false, blueprintConfig } = options;
143
143
  if (requestId)
144
144
  log.verbose(styleText('dim', `Request ID: ${requestId}`));
145
145
  if (noWait) {
146
+ // Optimistic: the request was accepted, so unset stackId without waiting for completion.
147
+ clearLocalStackIdFromConfig(blueprintConfig, stackId, log);
146
148
  log(styleText(['bold', 'magenta'], 'Stack destruction started!'));
147
149
  if (requestId && !verbose)
148
150
  log(styleText('dim', `Request ID: ${requestId}`));
@@ -151,7 +153,7 @@ function afterDestroyAccepted(options) {
151
153
  return waitForDestruction(options);
152
154
  }
153
155
  async function waitForDestruction(options) {
154
- const { stackId, stackName, operationId, requestId, auth, log, bin, verbose = false } = options;
156
+ const { stackId, stackName, operationId, requestId, auth, log, bin, verbose = false, blueprintConfig, } = options;
155
157
  log(styleText('dim', 'Stack destruction progress:'));
156
158
  log('');
157
159
  const outcome = await waitForOperation({
@@ -165,6 +167,8 @@ async function waitForDestruction(options) {
165
167
  progressNoun: 'destruction',
166
168
  });
167
169
  if (outcome.type === 'completed') {
170
+ // Only clear stackId once destruction is confirmed; a failed or unconfirmed destruction may leave Stack state in blueprints
171
+ clearLocalStackIdFromConfig(blueprintConfig, stackId, log);
168
172
  log(styleText(['bold', 'magenta'], 'Stack destruction completed!'));
169
173
  return { success: true, json: { stackId, stackName, requestId } };
170
174
  }
@@ -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';
@@ -5,41 +5,22 @@ import { SANITY_INSTALLATION_CONFIG, SANITY_STUDIO } from '../../constants.js';
5
5
  * Stamps the installed `sanity` version onto each media-library config resource and studio resource.
6
6
  */
7
7
  export const stampConfigVersion = async (resource, blueprintFileDir) => {
8
- let update;
9
- let root;
10
- if (resource.type === SANITY_INSTALLATION_CONFIG) {
8
+ if (resource.type === SANITY_INSTALLATION_CONFIG || resource.type === SANITY_STUDIO) {
11
9
  const config = resource;
12
- if (config.appType !== 'media-library')
10
+ // skip non-media library configs
11
+ if (resource.type === SANITY_INSTALLATION_CONFIG &&
12
+ 'appType' in config &&
13
+ config.appType !== 'media-library')
13
14
  return;
14
- // Leave values included in the blueprint.
15
+ // Leave values included in the blueprint
15
16
  if (config.version !== undefined)
16
17
  return;
17
- root = config.root;
18
- update = (version) => {
19
- config.version = version;
20
- };
21
- }
22
- else if (resource.type === SANITY_STUDIO) {
23
- const config = resource;
24
- // Leave values included in the blueprint.
25
- if (config.autoUpdates?.version !== undefined)
26
- return;
27
- root = config.root;
28
- update = (version) => {
29
- if (config.autoUpdates) {
30
- config.autoUpdates.version = version;
31
- }
32
- else {
33
- config.autoUpdates = { enabled: true, version };
34
- }
35
- };
36
- }
37
- if (update && root) {
18
+ const root = config.root;
38
19
  const workDir = resolve(blueprintFileDir, root);
39
20
  const version = await getLocalPackageVersion('sanity', workDir);
40
21
  if (!version) {
41
22
  throw new Error(`Unable to determine the installed 'sanity' version for resource '${resource.name}'; is 'sanity' installed in '${root}'?`);
42
23
  }
43
- update(version);
24
+ config.version = version;
44
25
  }
45
26
  };
@@ -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}