@sanity/runtime-cli 17.20.0 → 17.20.1-next.g1660a2b

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 +19 -19
  2. package/dist/actions/blueprints/logs-polling.js +7 -1
  3. package/dist/actions/functions/env/list.d.ts +5 -1
  4. package/dist/actions/functions/env/list.js +5 -5
  5. package/dist/actions/functions/env/remove.d.ts +1 -1
  6. package/dist/actions/functions/env/remove.js +2 -2
  7. package/dist/actions/functions/env/update.d.ts +1 -1
  8. package/dist/actions/functions/env/update.js +2 -2
  9. package/dist/actions/functions/list.js +3 -6
  10. package/dist/actions/functions/logs.d.ts +6 -2
  11. package/dist/actions/functions/logs.js +6 -7
  12. package/dist/constants.js +1 -0
  13. package/dist/cores/functions/test.js +18 -14
  14. package/dist/utils/functions/api-error.d.ts +6 -0
  15. package/dist/utils/functions/api-error.js +25 -0
  16. package/dist/utils/functions/callback/routes.d.ts +10 -0
  17. package/dist/utils/functions/callback/routes.js +34 -0
  18. package/dist/utils/functions/child-process-wrapper.js +17 -1
  19. package/dist/utils/functions/child-runtime/callback.d.ts +15 -0
  20. package/dist/utils/functions/child-runtime/callback.js +152 -0
  21. package/dist/utils/functions/child-runtime/durable.js +25 -0
  22. package/dist/utils/functions/child-runtime/getBatchResults.d.ts +6 -0
  23. package/dist/utils/functions/child-runtime/getBatchResults.js +1 -2
  24. package/dist/utils/functions/child-runtime/step-history.d.ts +1 -1
  25. package/dist/utils/functions/durable-logs.js +5 -0
  26. package/dist/utils/functions/invoke/local.js +79 -2
  27. package/dist/utils/functions/invoke/nested.js +2 -1
  28. package/dist/utils/types.d.ts +42 -2
  29. package/oclif.manifest.json +1052 -1052
  30. package/package.json +1 -1
@@ -0,0 +1,152 @@
1
+ import process from 'node:process'
2
+
3
+ export const createCallbackHandler = () => {
4
+ /**
5
+ * Pending nested `context.registerCallback()` calls, keyed by correlation id. Each entry
6
+ * holds the resolve/reject of the Promise returned to the user's handler; it is
7
+ * settled when the matching `callback-response` arrives from the parent.
8
+ * @type {Map<string, {resolve: (value: unknown) => void, reject: (reason: Error) => void, timer: ReturnType<typeof setTimeout> | undefined}>}
9
+ */
10
+ const pendingResponses = new Map([])
11
+ const pendingRequests = new Map([])
12
+ let nextAttempt = 0
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
+ /**
30
+ * Handle a response from the parent process for a registered callback. This is called when the parent process sends a `callback-response` message.
31
+ */
32
+ const handleResponse = (msg) => {
33
+ if (msg.attempt !== undefined) {
34
+ const entry = removeRequest(msg.attempt)
35
+
36
+ if (!entry) {
37
+ return
38
+ }
39
+
40
+ if (msg.ok) {
41
+ entry.resolve(msg.result)
42
+ } else {
43
+ entry.reject(new Error(msg.error.message))
44
+ }
45
+ return
46
+ }
47
+
48
+ const pendingEntry = pendingResponses.get(msg.callbackId)
49
+ if (!pendingEntry) return
50
+
51
+ pendingResponses.delete(msg.callbackId)
52
+ clearTimeout(pendingEntry?.timer)
53
+ if (msg.ok) {
54
+ pendingEntry.resolve(msg.result)
55
+ return
56
+ }
57
+
58
+ const {message, stack, name} = msg.error
59
+ const error = new Error(message)
60
+ error.stack = stack
61
+ error.name = name
62
+ pendingEntry.reject(error)
63
+ }
64
+
65
+ /**
66
+ * Handle a request from the parent process to invoke a registered callback. This is called when the parent process sends a `callback-request` message.
67
+ */
68
+ const handleRequest = (request, next) => {
69
+ // Match the request from the callback.sucess or callback.failure sanity client functions
70
+ const CALLBACK_URL =
71
+ /^https?:\/\/[^/?#]+\/v[^/?#]+\/functions\/durables\/callback\/([^/?#]+)\/(success|failure)(?:[?#].*)?$/
72
+
73
+ const match = request.method?.toUpperCase() === 'POST' && CALLBACK_URL.exec(request.url)
74
+ if (!match) {
75
+ return next(request)
76
+ }
77
+
78
+ const [, callbackId, outcome] = match
79
+ const {body, timeout} = request
80
+ if (typeof body !== 'string') {
81
+ throw new TypeError('Callback body must be serialized JSON')
82
+ }
83
+
84
+ const timeoutMs = typeof timeout === 'object' && timeout !== null ? timeout.total : timeout
85
+ const signals = [request.signal, timeoutMs > 0 && AbortSignal.timeout(timeoutMs)].filter(
86
+ Boolean,
87
+ )
88
+
89
+ const signal = signals.length > 0 ? AbortSignal.any(signals) : undefined
90
+ signal?.throwIfAborted()
91
+
92
+ return new Promise((resolve, reject) => {
93
+ const attempt = ++nextAttempt
94
+ const onAbort = () => removeRequest(attempt)?.reject(signal.reason)
95
+ pendingRequests.set(attempt, {
96
+ callbackId,
97
+ resolve,
98
+ reject,
99
+ cleanup: () => signal?.removeEventListener('abort', onAbort),
100
+ })
101
+ signal?.addEventListener('abort', onAbort, {once: true})
102
+ try {
103
+ process.send(
104
+ JSON.stringify({type: 'callback-request', callbackId, attempt, outcome, body}),
105
+ (error) => {
106
+ if (error) removeRequest(attempt)?.reject(error)
107
+ },
108
+ )
109
+ } catch (error) {
110
+ removeRequest(attempt)?.reject(error)
111
+ }
112
+ })
113
+ }
114
+
115
+ /**
116
+ * Remove a pending request from the map and clean up its resources. This is called when a request is completed or aborted.
117
+ */
118
+ const removeRequest = (attempt) => {
119
+ const entry = pendingRequests.get(attempt)
120
+ if (!entry) {
121
+ return
122
+ }
123
+
124
+ pendingRequests.delete(attempt)
125
+ entry.cleanup()
126
+ return entry
127
+ }
128
+
129
+ process.once('disconnect', () => {
130
+ const error = new Error('Local callback IPC disconnected')
131
+ for (const attempt of pendingRequests.keys()) removeRequest(attempt)?.reject(error)
132
+ })
133
+
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
+ return {
146
+ cancel,
147
+ register,
148
+ handleRequest,
149
+ handleResponse,
150
+ removeRequest,
151
+ }
152
+ }
@@ -1,3 +1,4 @@
1
+ import {randomUUID} from 'node:crypto'
1
2
  import {performance} from 'node:perf_hooks'
2
3
  import {inspect} from 'node:util'
3
4
  import {getBatchResults} from './getBatchResults.js'
@@ -205,6 +206,30 @@ export async function runDurable(handler, {context, event, branchName}, io) {
205
206
  }
206
207
  return state
207
208
  }),
209
+ waitForCallback: ({name, submitter, timeout, retry}) => {
210
+ return track(
211
+ name || '',
212
+ 'wait-for-callback',
213
+ async () => {
214
+ const callbackId = randomUUID()
215
+ const result = io.registerCallback({
216
+ callbackId,
217
+ name,
218
+ timeout: durationToMs(timeout),
219
+ })
220
+ io.emit({name, kind: 'wait-for-callback', phase: 'waiting', callbackId})
221
+ try {
222
+ await submitter({callbackId, logger})
223
+ } catch (err) {
224
+ io.cancelCallback(callbackId)
225
+ throw err
226
+ }
227
+
228
+ return await result
229
+ },
230
+ retry,
231
+ )
232
+ },
208
233
  wait: ({name, duration}) =>
209
234
  track(name || '', 'wait', async () => {
210
235
  await io.wait(durationToMs(duration))
@@ -0,0 +1,6 @@
1
+ import type {BatchItem, BatchResult, CompletionReason} from '@sanity/functions'
2
+
3
+ export function getBatchResults(
4
+ outcomes: Array<BatchItem<unknown>>,
5
+ reason: CompletionReason,
6
+ ): Omit<BatchResult<unknown>, 'completionReason'> & {reason: CompletionReason}
@@ -18,8 +18,7 @@ export const getBatchResults = (outcomes, reason) => {
18
18
  /**
19
19
  * Returns an array of outcomes that have succeeded (status 'SUCCEEDED').
20
20
  */
21
- const succeeded = () =>
22
- all.filter((outcome) => outcome.result !== undefined && outcome.status === 'SUCCEEDED')
21
+ const succeeded = () => all.filter((outcome) => outcome.status === 'SUCCEEDED')
23
22
 
24
23
  /**
25
24
  * Returns an array of outcomes that are still in progress (status 'STARTED').
@@ -1,4 +1,4 @@
1
- import type {DurableStepEvent} from './types'
1
+ import type {DurableStepEvent} from '../../types.js'
2
2
 
3
3
  type PendingRetry = {index: number; event: DurableStepEvent; delayMs: number}
4
4
 
@@ -35,6 +35,11 @@ export const createDurableJsonCollector = () => {
35
35
  const step = activeSteps.get(event.name);
36
36
  if (!step)
37
37
  return;
38
+ if (event.phase === 'waiting') {
39
+ step.phase = 'waiting';
40
+ step.callbackId = event.callbackId;
41
+ return;
42
+ }
38
43
  step.phase = event.phase;
39
44
  step.durationMs = event.durationMs;
40
45
  if (event.phase === 'complete') {
@@ -8,6 +8,7 @@ import * as groq from 'groq-js';
8
8
  import config from '../../../config.js';
9
9
  import { SANITY_FUNCTION_DURABLE } from '../../../constants.js';
10
10
  import { groupBlueprintResources } from '../../blueprints/group-resources.js';
11
+ import { isRecord } from '../../is-record.js';
11
12
  import { isGroqContextOptions, } from '../../types.js';
12
13
  import { findFunctionEntryPoint } from '../find-entry-point.js';
13
14
  import { assertConsole } from './assert-console.js';
@@ -50,7 +51,7 @@ export default async function invoke(resource, payload, context, options) {
50
51
  if (!resource.src) {
51
52
  throw new Error(`Function resource "${resource.name}" is missing the 'src' property.`);
52
53
  }
53
- const { forceColor = true, timeout = 10, onNestedInvoke, depth = 0, callStack = [], onStepEvent = () => { }, noWait = false, } = options;
54
+ const { forceColor = true, timeout = 10, onNestedInvoke, depth = 0, callStack = [], onStepEvent = () => { }, noWait = false, callbackRoutes, } = options;
54
55
  // Ensure a user when running a durable is using the provided logger and not the `console`
55
56
  if (resource.type === SANITY_FUNCTION_DURABLE) {
56
57
  const sourcePath = resolve(context.blueprintFileDir, resource.src);
@@ -236,6 +237,80 @@ export default async function invoke(resource, payload, context, options) {
236
237
  catch {
237
238
  return;
238
239
  }
240
+ if (msg?.type === 'callback-register') {
241
+ // if the routes handler is not available, kill the process with an error
242
+ if (!callbackRoutes) {
243
+ child.send(JSON.stringify({
244
+ type: 'callback-response',
245
+ callbackId: msg.callbackId,
246
+ ok: false,
247
+ error: {
248
+ name: 'Error',
249
+ message: 'The callback server is not available',
250
+ },
251
+ }));
252
+ return;
253
+ }
254
+ pauseTimer();
255
+ callbackRoutes.set(msg.callbackId, async (result) => {
256
+ if (child && !child.killed) {
257
+ child.send(JSON.stringify({
258
+ type: 'callback-response',
259
+ callbackId: msg.callbackId,
260
+ ...result,
261
+ }));
262
+ }
263
+ resumeTimer();
264
+ });
265
+ return;
266
+ }
267
+ if (msg.type === 'callback-cancel') {
268
+ if (callbackRoutes?.remove(msg.callbackId)) {
269
+ resumeTimer();
270
+ }
271
+ return;
272
+ }
273
+ if (msg?.type === 'callback-request') {
274
+ const { callbackId, attempt, outcome, body } = msg;
275
+ let response;
276
+ try {
277
+ let value;
278
+ try {
279
+ value = JSON.parse(body);
280
+ }
281
+ catch {
282
+ throw new Error('Invalid callback payload');
283
+ }
284
+ let delivery = { ok: true, result: value };
285
+ if (outcome === 'failure') {
286
+ const fields = isRecord(value) ? value : {};
287
+ delivery = {
288
+ ok: false,
289
+ error: {
290
+ name: 'Error',
291
+ message: typeof fields.errorMessage === 'string' ? fields.errorMessage : '',
292
+ stack: Array.isArray(fields.stackTrace) ? fields.stackTrace.join('\n') : '',
293
+ },
294
+ };
295
+ }
296
+ const result = callbackRoutes?.deliver(callbackId, delivery) ?? 'unknown';
297
+ if (result !== 'ok')
298
+ throw new Error(`Local callback ${callbackId}: ${result}`);
299
+ response = { ok: true, result: null };
300
+ }
301
+ catch (err) {
302
+ response = {
303
+ ok: false,
304
+ error: {
305
+ name: err instanceof Error ? err.name : 'Error',
306
+ message: err instanceof Error ? err.message : String(err),
307
+ stack: err instanceof Error ? (err.stack ?? '') : '',
308
+ },
309
+ };
310
+ }
311
+ child.send(JSON.stringify({ type: 'callback-response', callbackId, attempt, ...response }));
312
+ return;
313
+ }
239
314
  if (msg?.type === 'step-event') {
240
315
  onStepEvent(msg.event);
241
316
  return;
@@ -321,7 +396,8 @@ export default async function invoke(resource, payload, context, options) {
321
396
  ...(isGroqContextOptions(context) && {
322
397
  clientOptions: {
323
398
  ...context.clientOptions,
324
- apiHost: config.apiUrl,
399
+ // trailing slash is being added, but not certain where. Strips it off here to remove `apiHost//vx/`
400
+ apiHost: (context.clientOptions.apiHost ?? config.apiUrl).replace(/\/+$/, ''),
325
401
  },
326
402
  }),
327
403
  },
@@ -332,6 +408,7 @@ export default async function invoke(resource, payload, context, options) {
332
408
  payload,
333
409
  isDurable: resource.type === SANITY_FUNCTION_DURABLE,
334
410
  noWait,
411
+ callbacks: Boolean(callbackRoutes),
335
412
  };
336
413
  child.send(JSON.stringify(startMessage));
337
414
  }
@@ -28,7 +28,7 @@ export function assertNestedInvokeAllowed(name, depth, callStack) {
28
28
  * stack extended by this function, and normalize timings.
29
29
  */
30
30
  export async function runFunction(resource, payload, context, options) {
31
- const { forceColor, timeout, depth = 0, callStack = [], onNestedInvoke, onStepEvent } = options;
31
+ const { forceColor, timeout, depth = 0, callStack = [], onNestedInvoke, onStepEvent, callbackRoutes, } = options;
32
32
  assertNestedInvokeAllowed(resource.name, depth, callStack);
33
33
  const response = await invoke(resource, payload, context, {
34
34
  forceColor,
@@ -37,6 +37,7 @@ export async function runFunction(resource, payload, context, options) {
37
37
  depth,
38
38
  callStack: [...callStack, resource.name],
39
39
  onStepEvent,
40
+ callbackRoutes,
40
41
  });
41
42
  return { ...response, timings: response.timings ?? {} };
42
43
  }
@@ -1,5 +1,6 @@
1
1
  import { type BlueprintCorsOriginResource, type BlueprintDatasetResource, type BlueprintDocumentFunctionResource, type BlueprintDocumentWebhookResource, type BlueprintDurableFunctionResource, type BlueprintMediaLibraryAssetFunctionResource, type BlueprintProjectResource, type BlueprintPubSubFunctionResource, type BlueprintResource, type BlueprintRobotResource, type BlueprintRoleResource, type BlueprintScheduledFunctionResource, type BlueprintStudioResource, type BlueprintSyncTagInvalidateFunctionResource } from '@sanity/blueprints';
2
2
  import { type SANITY_AGENT_TYPE } from '../constants.js';
3
+ import type { CallbackRoutes } from './functions/callback/routes.js';
3
4
  export type ScopeType = 'organization' | 'project';
4
5
  /** Result utility type */
5
6
  export type Result<T, E = string> = {
@@ -165,6 +166,7 @@ export interface InvokeGroqContextOptions extends BaseContextOptions {
165
166
  projectId?: string;
166
167
  organizationId?: string;
167
168
  token?: string;
169
+ apiHost?: string;
168
170
  };
169
171
  /** The resource type of the event source; resource type that invoked the function. */
170
172
  eventResourceType: string;
@@ -201,7 +203,18 @@ export interface InvokeExecutionOptions {
201
203
  onStepEvent?: (event: DurableRuntimeEvent) => void;
202
204
  /** Don't wait the full duration during a wait durable event @internal */
203
205
  noWait?: boolean;
206
+ callbackRoutes?: CallbackRoutes;
204
207
  }
208
+ /**
209
+ * @internal
210
+ */
211
+ export type CallbackResponse = {
212
+ ok: true;
213
+ result: unknown;
214
+ } | {
215
+ ok: false;
216
+ error: InvocationError;
217
+ };
205
218
  export type NestedInvokeMetadata = {
206
219
  origin?: 'step.delegate';
207
220
  };
@@ -223,6 +236,7 @@ export type ParentToChildMessage = {
223
236
  payload: unknown;
224
237
  isDurable?: boolean;
225
238
  noWait?: boolean;
239
+ callbacks?: boolean;
226
240
  } | {
227
241
  type: 'invoke-response';
228
242
  id: string;
@@ -238,6 +252,18 @@ export type ParentToChildMessage = {
238
252
  } | {
239
253
  type: 'step-event';
240
254
  event: DurableRuntimeEvent;
255
+ } | {
256
+ type: 'callback-response';
257
+ callbackId: string;
258
+ ok: true;
259
+ result: unknown;
260
+ attempt?: number;
261
+ } | {
262
+ type: 'callback-response';
263
+ callbackId: string;
264
+ ok: false;
265
+ error: InvocationError;
266
+ attempt?: number;
241
267
  };
242
268
  /**
243
269
  * IPC messages sent from a function child process back up to the parent.
@@ -261,6 +287,19 @@ export type ChildToParentMessage = {
261
287
  } | {
262
288
  type: 'step-event';
263
289
  event: DurableRuntimeEvent;
290
+ } | {
291
+ type: 'callback-register';
292
+ callbackId: string;
293
+ name: string;
294
+ } | {
295
+ type: 'callback-cancel';
296
+ callbackId: string;
297
+ } | {
298
+ type: 'callback-request';
299
+ attempt: number;
300
+ callbackId: string;
301
+ outcome: 'success' | 'failure';
302
+ body: string;
264
303
  };
265
304
  /** @internal */
266
305
  export interface InvocationResponse {
@@ -381,9 +420,9 @@ export type Warning = {
381
420
  suggestions: string[];
382
421
  };
383
422
  /** @internal */
384
- export type DurableOperationSteps = 'run' | 'wait' | 'waitForCondition' | 'delegate';
423
+ export type DurableOperationSteps = 'run' | 'delegate' | 'fanout' | 'wait' | 'wait-for-condition' | 'wait-for-callback';
385
424
  /** @internal */
386
- export type DurableStepPhase = 'start' | 'complete' | 'error';
425
+ export type DurableStepPhase = 'start' | 'complete' | 'error' | 'waiting';
387
426
  /**
388
427
  * Represents a single step in a durable operation
389
428
  */
@@ -398,6 +437,7 @@ export interface DurableStepEvent {
398
437
  attempt?: number;
399
438
  retries?: number;
400
439
  maxAttempts?: number;
440
+ callbackId?: string;
401
441
  }
402
442
  export interface DurableLogEvent {
403
443
  kind: 'log';