@sanity/functions 1.6.9 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ import type {FunctionContext} from './context'
2
+ import type {GenericEvent} from './functions'
3
+ import type {BlueprintResource} from './resources'
4
+
5
+ /**
6
+ * Durable alias of FunctionsContext
7
+ * @alpha Using durables is considered experimental and may change in the future.
8
+ * @hidden
9
+ */
10
+ export type DurableContext = FunctionContext
11
+
12
+ /**
13
+ * Logger interface for durables.
14
+ * @alpha Using durables is considered experimental and may change in the future.
15
+ * @hidden
16
+ */
17
+ export interface DurableLogger {
18
+ debug(...params: unknown[]): void
19
+ info(...params: unknown[]): void
20
+ warn(...params: unknown[]): void
21
+ error(...params: unknown[]): void
22
+ log(...params: unknown[]): void
23
+ }
24
+
25
+ /**
26
+ * @alpha Using durables is considered experimental and may change in the future.
27
+ * @hidden
28
+ */
29
+ export interface DurableStepCallbackContext {
30
+ logger: DurableLogger
31
+ }
32
+
33
+ /**
34
+ * Arguments passed to callbacks that execute a durable attempt.
35
+ * step.run & step.waitForCondition
36
+ * @alpha Using durables is considered experimental and may change in the future.
37
+ * @hidden
38
+ */
39
+ export interface DurableStepAttemptContext extends DurableStepCallbackContext {
40
+ /** Current attempt number, starting at 1. */
41
+ attempt: number
42
+ }
43
+
44
+ /**
45
+ * The signature of the duration object passed to the `wait` method of a durable function.
46
+ * It can be specified in days, hours, minutes, or seconds.
47
+ * @alpha Using durables is considered experimental and may change in the future.
48
+ * @hidden
49
+ */
50
+ export type DurableDuration =
51
+ | {days: number; hours?: number; minutes?: number; seconds?: number}
52
+ | {hours: number; minutes?: number; seconds?: number}
53
+ | {minutes: number; seconds?: number}
54
+ | {seconds: number}
55
+
56
+ /**
57
+ * @alpha: Using durables is considered experimental and may change in the future.
58
+ * @hidden
59
+ */
60
+ export type DurableJitterStrategy = 'none' | 'full' | 'half'
61
+
62
+ /**
63
+ * @alpha: Using durables is considered experimental and may change in the future.
64
+ * @hidden
65
+ */
66
+ export interface DurableRetryStrategy {
67
+ maxAttempts?: number
68
+ initialDelay?: DurableDuration
69
+ maxDelay?: DurableDuration
70
+ backoffRate?: number
71
+ jitter?: DurableJitterStrategy
72
+ retryableErrors?: (string | RegExp)[]
73
+ retryableErrorTypes?: (new () => Error)[]
74
+ }
75
+
76
+ /**
77
+ * @alpha: Using durables is considered experimental and may change in the future.
78
+ * @hidden
79
+ */
80
+ export type DurableStepSemantics = 'at-most-once-per-retry' | 'at-least-once-per-retry'
81
+
82
+ /**
83
+ * @alpha: Using durables is considered experimental and may change in the future.
84
+ * @hidden
85
+ */
86
+ export interface DurableStepConfig {
87
+ strategy?: DurableRetryStrategy
88
+ semantics?: DurableStepSemantics
89
+ }
90
+
91
+ /**
92
+ * Allowed operations in a retry code block
93
+ * @alpha: Using durables is considered experimental and may change in the future.
94
+ * @hidden
95
+ */
96
+ export type DurableRetryOperations = Pick<DurableOperations, 'delegate' | 'waitForCallback' | 'waitForCondition'>
97
+
98
+ /**
99
+ * @alpha: Using durables is considered experimental and may change in the future.
100
+ * @hidden
101
+ */
102
+ export type DurableRetryBlock<T> = (envelope: {step: DurableRetryOperations; attempt: number}) => Promise<T>
103
+
104
+ /**
105
+ * @alpha: Using durables is considered experimental and may change in the future.
106
+ * @hidden
107
+ */
108
+ export type DurableRetry = <T>(name: string | undefined, config: DurableRetryStrategy, block: DurableRetryBlock<T>) => Promise<T>
109
+
110
+ /**
111
+ * @alpha Using durables is considered experimental and may change in the future.
112
+ * @hidden
113
+ */
114
+ export type DurableWaitForConditionDecision = {shouldRetry: true; delay: DurableDuration} | {shouldRetry: false}
115
+
116
+ /**
117
+ * @alpha Using durables is considered experimental and may change in the future.
118
+ * @hidden
119
+ */
120
+ export type DurableStepHandler<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn
121
+
122
+ /**
123
+ * @alpha Using durables is considered experimental and may change in the future.
124
+ * @hidden
125
+ */
126
+ export type DurableStepRunHandler<T = unknown> = DurableStepHandler<[context: DurableStepAttemptContext], T | Promise<T>>
127
+
128
+ /**
129
+ * @alpha Using durables is considered experimental and may change in the future.
130
+ * @hidden
131
+ */
132
+ export type DurableStepWaitForCallbackHandler = DurableStepHandler<[callbackId: string, context: DurableStepCallbackContext], Promise<void>>
133
+
134
+ /**
135
+ * @alpha Using durables is considered experimental and may change in the future.
136
+ * @hidden
137
+ */
138
+ export type DurableWaitForConditionPoller<T = unknown> = DurableStepHandler<[state: T, context: DurableStepAttemptContext], Promise<T>>
139
+
140
+ /**
141
+ * @alpha Using durables is considered experimental and may change in the future.
142
+ * @hidden
143
+ */
144
+ export type DurableWaitForConditionNext<T = unknown> = DurableStepHandler<
145
+ [state: T, context: Pick<DurableStepAttemptContext, 'attempt'>],
146
+ DurableWaitForConditionDecision
147
+ >
148
+
149
+ /**
150
+ * The interface defining the operations available to a durable function.
151
+ * These operations are steps that delegate to other functions, and wait for external callbacks.
152
+ * @alpha Using durables is considered experimental and may change in the future.
153
+ * @hidden
154
+ */
155
+ export type DurableOperations = {
156
+ /**
157
+ * Runs a named step. Its result is recorded, so if the workflow re-runs the step
158
+ * is not executed again. Failures are retried on their own.
159
+ * similar to ctx.step()
160
+ * @remarks cannot be nested inside another step
161
+ * @example
162
+ * ```ts
163
+ * step.run({
164
+ * name: 'run-step',
165
+ * handler: async ({logger}) => {
166
+ * logger.log('Running step')
167
+ * }})
168
+ * ```
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * // With a retry config
173
+ * step.run({
174
+ * name: 'run-with-retry'
175
+ * handler: () => { // handler code }
176
+ * retry: { strategy: { maxAttempts: 2 } }
177
+ * })
178
+ * ```
179
+ * @param name - Step name
180
+ * @param handler - function being executed
181
+ * @param retry - retry configuration
182
+ * @returns The value returned by the executed function
183
+ */
184
+ run<T>({name, handler, retry}: {name?: string; handler: DurableStepRunHandler<T>; retry?: DurableStepConfig}): Promise<T>
185
+ /**
186
+ * Calls another function and awaits its result.
187
+ * similar to ctx.invoke()
188
+ * @remarks cannot be nested inside another step
189
+ * @example
190
+ * ```ts
191
+ * // my-delegated-function/index.ts
192
+ * export const handler = pubSubEventHandler({event}) => {
193
+ * ...
194
+ * }
195
+ *
196
+ * // my-resource/index.ts
197
+ * export const handler = pubSubEventHandler({event}) => {
198
+ * ...
199
+ * }
200
+ *
201
+ * // my-durable-function/index.ts
202
+ * createDurable(({step, context}) => {
203
+ * // With a function name
204
+ * step.delegate({name: 'my-function', handler: 'my-delegated-function', input: {}})
205
+ * // With a resource object
206
+ * step.delegate({name: 'another-function', handler: context.resource.function('my-resource'), input: {}})
207
+ * })
208
+ * ```
209
+ * @param name - Step name
210
+ * @param handler - Function to be invoked
211
+ * @param input - Data passed to the called function
212
+ * @returns The value returned by the called function
213
+ */
214
+ delegate<T>({
215
+ name,
216
+ handler,
217
+ input,
218
+ }: {
219
+ name?: string
220
+ handler: string | BlueprintResource<`sanity.function.${string}`>
221
+ input?: unknown
222
+ }): Promise<T>
223
+
224
+ /**
225
+ * Waits for an external callback
226
+ * similar to ctx.waitForCallback()
227
+ * @remarks cannot be nested inside another step
228
+ * @param name - Step name
229
+ * @param handler - Receives the generated callbackId and returns a delivered promise
230
+ * @returns The value returned by the executed function
231
+ */
232
+ waitForCallback<T>({name, handler}: {name?: string; handler: DurableStepWaitForCallbackHandler}): Promise<T>
233
+
234
+ /**
235
+ * Waits for a specified duration
236
+ * similar to ctx.wait()
237
+ * @remarks cannot be nested inside another step
238
+ * @example
239
+ * Wait for 30 seconds
240
+ * ```ts
241
+ * await step.wait({name: 'wait30Sec', duration: { seconds: 30 }});
242
+ * ```
243
+ * Wait for 2 days and 3 hours
244
+ * ```ts
245
+ * await step.wait({name: 'waitALongTime', duration: { days: 2, hours: 3 }});
246
+ * ```
247
+ * @param name - Step name
248
+ * @param duration - Amount of time the function will wait before continuing.
249
+ * Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
250
+ * @returns Resolves after the duration
251
+ */
252
+ wait({name, duration}: {name?: string; duration: DurableDuration}): Promise<void>
253
+
254
+ /**
255
+ * Waits for a specified condition to be met
256
+ * similar to ctx.waitForCondition()
257
+ * @remarks cannot be nested inside another step
258
+ * @example
259
+ * ```ts
260
+ * await step.waitForCondition({{
261
+ * name: 'waitForCondition',
262
+ * initial: {
263
+ * article: null,
264
+ * },
265
+ * poller: async (state, {attempt}) => {
266
+ * const client = createClient({
267
+ * apiVersion: '2026-08-05',
268
+ * ...context.clientOptions,
269
+ * })
270
+ * const article = await client.fetch<Article | null>(
271
+ * '*[_type == "article"][0]',
272
+ * )
273
+ * return {...state, article}
274
+ * }
275
+ * next: (state, {attempt}) => {
276
+ * if (state.article) return {shouldRetry: false}
277
+ *
278
+ * return {
279
+ * shouldRetry: true,
280
+ * delay: {
281
+ * seconds: Math.min(attempt * 2, 60),
282
+ * },
283
+ * }
284
+ * },
285
+ * },
286
+ * )
287
+ * ```
288
+ * @param name - Step name
289
+ * @param initial - Initial state passed to the first poller call.
290
+ * @param poller - Called on each attempt with the current state and condition context.
291
+ * @param next - A function that determines whether the condition has been met or another check should be run.
292
+ * Returns a promise resolving to the updated state,
293
+ * which is passed to next to determine whether the condition has been met or another check should be run.
294
+ * @returns The value returned by the executed function
295
+ */
296
+ waitForCondition<T>({
297
+ name,
298
+ initial,
299
+ next,
300
+ poller,
301
+ }: {
302
+ name?: string
303
+ initial: T
304
+ poller: DurableWaitForConditionPoller<T>
305
+ next: DurableWaitForConditionNext<T>
306
+ }): Promise<T>
307
+ }
308
+
309
+ /**
310
+ * @alpha Using durables is considered experimental and may change in the future.
311
+ * @hidden
312
+ */
313
+ export type DurableHandler = (envelope: {
314
+ context: DurableContext
315
+ event?: GenericEvent
316
+ step: DurableOperations
317
+ logger: DurableLogger
318
+ retry: DurableRetry
319
+ }) => unknown | Promise<unknown>
@@ -0,0 +1,103 @@
1
+ import type {FunctionContext, GenericContext, ScheduledFunctionContext, SyncTagInvalidateContext} from './context'
2
+
3
+ /**
4
+ * The event object received by the function handler in the case of a document event,
5
+ * such as a publish, unpublish, delete or mutation event and similar.
6
+ */
7
+ export interface DocumentEvent<IData = any> {
8
+ /**
9
+ * The data delivered to the function. This is the result of applying any configured
10
+ * GROQ-projection to the changed document. If no projection is configured, this is
11
+ * the document itself.
12
+ */
13
+ data: IData
14
+ }
15
+
16
+ /**
17
+ * The event object received by the function handler in the case of a sync-tag-invalidate event.
18
+ */
19
+ export interface SyncTagInvalidateEvent {
20
+ /**
21
+ * The sync tags for use with cache invalidation and notifying the callback endpoint once tags are invalidated.
22
+ */
23
+ data: {
24
+ /** Array of sync tags to be invalidated. */
25
+ syncTags: string[]
26
+ }
27
+ }
28
+
29
+ /**
30
+ * A function handler for a document event.
31
+ */
32
+ export type DocumentEventHandler<IData = any> = (envelope: {context: FunctionContext; event: DocumentEvent<IData>}) => void | Promise<void>
33
+
34
+ /**
35
+ * A function handler for a schedule event.
36
+ */
37
+ export type ScheduledEventHandler = (envelope: {context: ScheduledFunctionContext}) => void | Promise<void>
38
+
39
+ /**
40
+ * A generic function event type which supports all function types
41
+ */
42
+ export type GenericEvent = DocumentEvent | SyncTagInvalidateEvent
43
+
44
+ /**
45
+ * A function handler for a pubsub event.
46
+ *
47
+ * A pubsub function can be triggered by any event source, so the envelope is intentionally
48
+ * permissive and needs no narrowing: `context` is any supported context, `event` is any
49
+ * supported event, and `done` is optional (present only for sync-tag-invalidate events).
50
+ *
51
+ * `IResult` is the value the handler resolves to and defaults to `void`. Pubsub is the one
52
+ * function type that may be invoked with {@link invoke | `invoke(name, payload, {sync: true})`},
53
+ * which returns the handler's resolved value to the caller.
54
+ */
55
+ export type PubSubEventHandler<IData = any, IResult = void> = (envelope: {
56
+ context: GenericContext
57
+ event: DocumentEvent<IData> | SyncTagInvalidateEvent
58
+ done?: SyncTagInvalidateCallback
59
+ }) => IResult | Promise<IResult>
60
+
61
+ /**
62
+ * A generic function handler that can receive the payload of any function type.
63
+ *
64
+ * @deprecated Renamed to {@link PubSubEventHandler}. This alias will be removed in the next
65
+ * major version.
66
+ */
67
+ export type EventHandler<IData = any, IResult = void> = PubSubEventHandler<IData, IResult>
68
+
69
+ /**
70
+ * A callback function to invoke once a sync-tag-invalidate event has been processed. Signals to Sanity that sync tag invalidation has completed.
71
+ */
72
+ export type SyncTagInvalidateCallback = (syncTags: string[]) => Promise<Response>
73
+
74
+ /**
75
+ * A function handler for a sync-tag-invalidate event.
76
+ */
77
+ export type SyncTagInvalidateEventHandler = (envelope: {
78
+ context: SyncTagInvalidateContext
79
+ event: SyncTagInvalidateEvent
80
+ done: SyncTagInvalidateCallback
81
+ }) => void | Promise<void>
82
+
83
+ /**
84
+ * The payload for the `invoke` method
85
+ */
86
+ export type FunctionPayload = {
87
+ event: GenericEvent
88
+ context: GenericContext
89
+ }
90
+
91
+ /**
92
+ * The definition of a function resource in our resource discovery table
93
+ */
94
+ export type FunctionResource = {
95
+ logicalResourceId: string
96
+ physicalResourceId: string
97
+ }
98
+
99
+ type FunctionResourceKey = 'eventsourcemapping' | 'function' | 'parameter' | 'queue' | 'schedule' | 'subscription' | 'topic'
100
+
101
+ export type FunctionResourceEnvelope = {
102
+ [K in FunctionResourceKey]-?: {[P in K]: FunctionResource} & {[P in Exclude<FunctionResourceKey, K>]?: FunctionResource}
103
+ }[FunctionResourceKey]
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Callback provided by Sanity CLI when doing local development.
3
+ *
4
+ * The CLI receives the event data alone: it delivers it to the target function as
5
+ * `event.data` and derives the target's context from the calling function's own context.
6
+ */
7
+ export type InvokeCallback = <T = unknown>(name: string, payload?: Record<string, unknown>, options?: InvokeOptions) => Promise<T>
8
+
9
+ /**
10
+ * Options provided to invoke
11
+ */
12
+ export type InvokeOptions = {
13
+ // Whether the function should be invoked synchronously
14
+ sync?: boolean
15
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * An interface to describe resources found in a Blueprint
3
+ */
4
+ export interface BlueprintResource<TType extends string = string> {
5
+ id: string
6
+ name: string
7
+ type: TType
8
+ }
9
+
10
+ export interface ResourcesApi {
11
+ /** Cross-type lookup by name: `context.resources('my-proj')`. */
12
+ (name: string): BlueprintResource | undefined
13
+ /** Flat array of every resource across types. */
14
+ all(): BlueprintResource[]
15
+ /** Iterate every resource: `for (const r of context.resources)`. */
16
+ [Symbol.iterator](): IterableIterator<BlueprintResource>
17
+ /** Type specific lookup by name: `context.cors('my-cors')` */
18
+ cors(name: string): BlueprintResource | undefined
19
+ dataset(name: string): BlueprintResource | undefined
20
+ function(name: string): BlueprintResource<`sanity.function.${string}`> | undefined
21
+ project(name: string): BlueprintResource | undefined
22
+ role(name: string): BlueprintResource | undefined
23
+ webhook(name: string): BlueprintResource | undefined
24
+ }