@trigger.dev/convex 0.0.1 → 4.8.3

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2023] [Trigger.dev]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,202 @@
1
1
  # @trigger.dev/convex
2
2
 
3
- Placeholder release. The Trigger.dev Convex component will be published here in an upcoming release.
3
+ Run Trigger.dev tasks from Convex mutations and read their status and results through Convex reactive queries.
4
+
5
+ Use Convex for application state and Trigger.dev for work that needs longer execution, more memory, ffmpeg, Playwright, Python, or other system dependencies. Tasks are still written and deployed normally with Trigger.dev.
6
+
7
+ **Experimental MVP.** No HTTP routes, webhooks, Trigger lifecycle hooks, or changes to your Trigger server are required.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @trigger.dev/convex convex
13
+ npx convex env set TRIGGER_SECRET_KEY tr_dev_...
14
+ ```
15
+
16
+ Choose the Trigger environment's secret key. Never expose it to browser code.
17
+
18
+ ```ts
19
+ // convex/convex.config.ts
20
+ import { defineApp } from "convex/server";
21
+ import trigger from "@trigger.dev/convex/convex.config.js";
22
+
23
+ const app = defineApp();
24
+ app.use(trigger);
25
+ export default app;
26
+ ```
27
+
28
+ Run `npx convex dev` to generate your application's component references.
29
+
30
+ ```ts
31
+ // convex/trigger.ts
32
+ import { Trigger } from "@trigger.dev/convex";
33
+ import { components, internal } from "./_generated/api";
34
+
35
+ export const trigger: Trigger = new Trigger(components.trigger, {
36
+ onComplete: internal.jobs.onComplete, // Optional internal mutation
37
+ });
38
+ ```
39
+
40
+ The explicit `Trigger` annotation avoids circular type inference through Convex's generated API when configuring a completion callback.
41
+
42
+ ## Example: request work and read the result
43
+
44
+ The example assumes a Trigger task named `render-video` exists. Type-only task imports do not bundle task code into Convex.
45
+
46
+ ```ts
47
+ // convex/schema.ts
48
+ import { defineSchema, defineTable } from "convex/server";
49
+ import { v } from "convex/values";
50
+
51
+ export default defineSchema({
52
+ jobs: defineTable({
53
+ owner: v.string(),
54
+ runId: v.optional(v.string()),
55
+ status: v.string(),
56
+ output: v.optional(v.any()),
57
+ }).index("by_runId", ["runId"]),
58
+ });
59
+ ```
60
+
61
+ ```ts
62
+ // convex/jobs.ts
63
+ import { vRun } from "@trigger.dev/convex";
64
+ import { v } from "convex/values";
65
+ import { mutation, query, internalMutation } from "./_generated/server";
66
+ import { trigger } from "./trigger";
67
+ import type { renderVideo } from "../trigger/renderVideo";
68
+
69
+ export const request = mutation({
70
+ args: { videoUrl: v.string() },
71
+ handler: async (ctx, { videoUrl }) => {
72
+ const user = await ctx.auth.getUserIdentity();
73
+ if (!user) throw new Error("Unauthorized");
74
+
75
+ const jobId = await ctx.db.insert("jobs", {
76
+ owner: user.subject,
77
+ status: "PENDING",
78
+ });
79
+ const runId = await trigger.trigger<typeof renderVideo>(
80
+ ctx,
81
+ "render-video",
82
+ { videoUrl },
83
+ { tags: [`job:${jobId}`] },
84
+ );
85
+ await ctx.db.patch(jobId, { runId });
86
+ return jobId;
87
+ },
88
+ });
89
+
90
+ export const status = query({
91
+ args: { jobId: v.id("jobs") },
92
+ handler: async (ctx, { jobId }) => {
93
+ const user = await ctx.auth.getUserIdentity();
94
+ const job = await ctx.db.get(jobId);
95
+ if (!user || !job || job.owner !== user.subject) return null;
96
+ return job.runId ? trigger.getRun(ctx, job.runId) : null;
97
+ },
98
+ });
99
+
100
+ export const onComplete = internalMutation({
101
+ args: { run: vRun },
102
+ handler: async (ctx, { run }) => {
103
+ const job = await ctx.db.query("jobs")
104
+ .withIndex("by_runId", q => q.eq("runId", run.id))
105
+ .unique();
106
+ if (job) await ctx.db.patch(job._id, {
107
+ status: run.status,
108
+ output: run.output,
109
+ });
110
+ },
111
+ });
112
+ ```
113
+
114
+ ```tsx
115
+ // React
116
+ const run = useQuery(api.jobs.status, { jobId });
117
+ // run.status, run.output, run.error, run.metadata, run.syncStatus
118
+ ```
119
+
120
+ The ID returned by `trigger.trigger` identifies the **component record**, not the Trigger.dev run. The latter becomes available as `run.runId` after submission.
121
+
122
+ ## API
123
+
124
+ - `trigger(ctx, taskId, payload, options?)`: enqueue work. Calling from a mutation makes the request atomic with your application's writes.
125
+ - `getRun(ctx, id)`: read one record reactively.
126
+ - `listRuns(ctx, paginationOpts)`: paginate records, newest first, up to 100 per page and a bounded read budget.
127
+ - `refresh(ctx, id)`: schedule an earlier status check for an active, submitted run. Returns `null` after scheduling, not the updated run.
128
+ - `resume(ctx, id)`: resume paused synchronization using the current credentials.
129
+
130
+ Trigger options include tags, delay, queue name, concurrency key, machine, metadata, max attempts, max duration, TTL, and a component-level idempotency key.
131
+
132
+ An optional `idempotencyKey` deduplicates requests across this component instance, regardless of task. Reusing a key returns the original record, even if its payload or task differs. Keys remain reserved while records exist.
133
+
134
+ The constructor accepts `secretKey` (defaults to `TRIGGER_SECRET_KEY`), `baseUrl` (defaults to `https://api.trigger.dev`), and `onComplete`. HTTP base URLs are permitted only for localhost development.
135
+
136
+ **Authorization belongs in your application's functions.** The component has no tenant or user model. Do not expose arbitrary record IDs or `listRuns` to clients without enforcing ownership. Queries never return stored credentials or request payloads.
137
+
138
+ ## Realtime progress and faster result delivery
139
+
140
+ Use [Trigger Realtime](https://trigger.dev/docs/realtime/overview) for responsive browser progress, and Convex queries for durable application state. When Realtime reports that a run is complete, call an ownership-checked application mutation that requests a component refresh:
141
+
142
+ ```ts
143
+ // convex/jobs.ts
144
+ export const refresh = mutation({
145
+ args: { jobId: v.id("jobs") },
146
+ handler: async (ctx, { jobId }) => {
147
+ const user = await ctx.auth.getUserIdentity();
148
+ const job = await ctx.db.get(jobId);
149
+ if (!user || !job || job.owner !== user.subject) throw new Error("Unauthorized");
150
+ if (job.runId) await trigger.refresh(ctx, job.runId);
151
+ },
152
+ });
153
+ ```
154
+
155
+ Pass the component record ID to `refresh`, not the remote Trigger run ID. Your browser subscribes to the latter, available as `run.runId` from `getRun`.
156
+
157
+ A refresh is only a hint: the component retrieves status and output directly from Trigger and uses the same validation, completion callback, and credential cleanup as normal polling. It never accepts client-supplied status or output. Observe `getRun` or your application query for the persisted result; awaiting `refresh` does not wait for that result.
158
+
159
+ - Refresh requests are coalesced per run. Status checks requested this way start at least five seconds after the previous status check.
160
+ - A hint received during a check queues one follow-up instead of interrupting or discarding the in-flight response. If that response completes the run, no follow-up is needed.
161
+ - Pending submissions, paused synchronization, and completed records are no-ops. Refresh never submits a task or resumes paused work; use `resume` after repairing a paused synchronization.
162
+ - Call refresh when Realtime observes completion, including an already-completed run after reconnecting. Do not call it on every metadata update to animate progress.
163
+ - Scheduled polling and its watchdog remain enabled. Convex can still finish the run if the browser closes, the subscription disconnects, or the refresh request fails. No persistent subscription inside a Convex action is required.
164
+
165
+ **Realtime token safety:** authenticate the token request, verify job ownership, and issue a short-lived token scoped to the exact remote run. Keep the root Trigger key server-side. A run-read token can also read the run through REST, including its payload; Realtime `skipColumns` is not a restriction on REST access. Keep worker credentials, storage-upload capabilities, and other secrets out of token-readable payloads, outputs, metadata, and errors. Application mutations must enforce ownership even when component refreshes are coalesced.
166
+
167
+ ## Execution and reliability
168
+
169
+ 1. The calling mutation writes a component record and schedules submission. If the transaction rolls back, neither survives.
170
+ 2. A short action submits to the existing Trigger API with a stable key derived from the record ID.
171
+ 3. Scheduled actions retrieve status with backoff from approximately 15 to 60 seconds between checks. Nothing runs in Convex between checks.
172
+ 4. A terminal state, including cancellation, is persisted. The optional completion mutation runs in the same transaction, then stored request data and credentials are deleted.
173
+
174
+ A scheduled watchdog is committed before each network action. An interrupted action is retried on the next check; obsolete responses cannot overwrite newer observations.
175
+
176
+ Remote submission uses a 24-hour idempotency TTL. Automatic submission retries stop within one hour of creating the record, well before that TTL. This is **not an unlimited exactly-once guarantee**.
177
+
178
+ Permanent API errors pause synchronization immediately. Eight consecutive transient or callback failures also pause it. Check `syncStatus === "paused"` and `syncError`. Fix the cause, then call `resume` from an authorized mutation. If submission has not been confirmed, it can only resume within the original one-hour window. After that, reconcile with the Trigger dashboard before creating new work.
179
+
180
+ Keep the same Trigger environment when resuming. Changing credentials does not migrate remote runs between environments. Existing requests retain their original credentials until resumed.
181
+
182
+ Completion callbacks should be short mutations. If a callback throws, completion and its application writes roll back together and are retried. A broken callback can therefore delay the component's completion state; `syncError` reports synchronization trouble. No callback is needed to use reactive results.
183
+
184
+ ## Limits
185
+
186
+ - Polling costs Convex executions and Trigger API requests. This MVP is for validating the integration, not high-volume fan-out or subsecond progress.
187
+ - Payload plus trigger options must fit within 256 KiB. Pass storage references for larger inputs.
188
+ - Output, error, and metadata each have a 256 KiB inline budget. Oversized output is omitted with `outputOmitted: true`. Oversized error or metadata is omitted.
189
+ - Trigger's `outputPresignedUrl`, when supplied, is preserved rather than downloaded. These URLs expire. Retrieve the run again through the Trigger API when you need a fresh URL.
190
+ - Run records are retained. Paused requests retain their payload and credentials for recovery. Automatic retention cleanup is not included.
191
+ - No batch API, cancellation command, waitpoint completion, schedules, or streaming yet. Trigger tasks themselves can use those features normally.
192
+
193
+ ## Development
194
+
195
+ From the repository root:
196
+
197
+ ```sh
198
+ pnpm --filter @trigger.dev/convex build
199
+ pnpm --filter @trigger.dev/convex test
200
+ ```
201
+
202
+ Tests use Convex's in-memory test runtime and real HTTP requests to a local server.
@@ -0,0 +1,39 @@
1
+ import { type FunctionReference, type GenericDataModel, type GenericMutationCtx, type GenericQueryCtx, type PaginationOptions } from "convex/server";
2
+ import type { ComponentApi } from "../component/_generated/component.js";
3
+ import type { Run, TriggerOptions } from "../component/shared.js";
4
+ export { vRun } from "../component/shared.js";
5
+ export type { Run, TriggerOptions, ComponentApi };
6
+ type MutationCtx = Pick<GenericMutationCtx<GenericDataModel>, "runMutation">;
7
+ type QueryCtx = Pick<GenericQueryCtx<GenericDataModel>, "runQuery">;
8
+ type TaskLike = {
9
+ id: string;
10
+ trigger: (...args: any[]) => any;
11
+ };
12
+ export type TriggerConfig = {
13
+ secretKey?: string;
14
+ baseUrl?: string;
15
+ onComplete?: FunctionReference<"mutation", "internal", {
16
+ run: Run;
17
+ }, any>;
18
+ };
19
+ export declare class Trigger {
20
+ private component;
21
+ private config;
22
+ constructor(component: ComponentApi, config?: TriggerConfig);
23
+ private runtimeConfig;
24
+ trigger<TTask extends TaskLike = TaskLike>(ctx: MutationCtx, taskId: TTask["id"], payload: Parameters<TTask["trigger"]>[0], options?: TriggerOptions & {
25
+ idempotencyKey?: string;
26
+ }): Promise<string>;
27
+ getRun(ctx: QueryCtx, id: string): Promise<Run | null>;
28
+ listRuns(ctx: QueryCtx, paginationOpts: PaginationOptions): Promise<{
29
+ page: Run[];
30
+ isDone: boolean;
31
+ continueCursor: string;
32
+ }>;
33
+ /**
34
+ * Request an earlier status check without accepting client-supplied run data.
35
+ * The check is scheduled, coalesced, and rate-limited; observe getRun for its result.
36
+ */
37
+ refresh(ctx: MutationCtx, id: string): Promise<null>;
38
+ resume(ctx: MutationCtx, id: string): Promise<null>;
39
+ }
@@ -0,0 +1,52 @@
1
+ import { createFunctionHandle, } from "convex/server";
2
+ export { vRun } from "../component/shared.js";
3
+ export class Trigger {
4
+ component;
5
+ config;
6
+ constructor(component, config = {}) {
7
+ this.component = component;
8
+ this.config = config;
9
+ }
10
+ runtimeConfig() {
11
+ const secretKey = this.config.secretKey ?? process.env.TRIGGER_SECRET_KEY;
12
+ if (!secretKey)
13
+ throw new Error("Set TRIGGER_SECRET_KEY or pass secretKey");
14
+ const url = new URL(this.config.baseUrl ?? "https://api.trigger.dev");
15
+ if (url.protocol !== "https:" &&
16
+ !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
17
+ throw new Error("baseUrl must use HTTPS, except for local development");
18
+ }
19
+ if (url.username || url.password || url.search || url.hash)
20
+ throw new Error("Invalid baseUrl");
21
+ return { secretKey, baseUrl: url.toString().replace(/\/$/, "") };
22
+ }
23
+ async trigger(ctx, taskId, payload, options = {}) {
24
+ const { idempotencyKey, ...triggerOptions } = options;
25
+ return ctx.runMutation(this.component.runs.trigger, {
26
+ taskId,
27
+ payload,
28
+ options: triggerOptions,
29
+ idempotencyKey,
30
+ config: this.runtimeConfig(),
31
+ callback: this.config.onComplete
32
+ ? await createFunctionHandle(this.config.onComplete)
33
+ : undefined,
34
+ });
35
+ }
36
+ async getRun(ctx, id) {
37
+ return ctx.runQuery(this.component.runs.get, { id });
38
+ }
39
+ async listRuns(ctx, paginationOpts) {
40
+ return ctx.runQuery(this.component.runs.list, { paginationOpts });
41
+ }
42
+ /**
43
+ * Request an earlier status check without accepting client-supplied run data.
44
+ * The check is scheduled, coalesced, and rate-limited; observe getRun for its result.
45
+ */
46
+ async refresh(ctx, id) {
47
+ return ctx.runMutation(this.component.runs.refresh, { id });
48
+ }
49
+ async resume(ctx, id) {
50
+ return ctx.runMutation(this.component.runs.resume, { id, config: this.runtimeConfig() });
51
+ }
52
+ }
@@ -0,0 +1,11 @@
1
+ import type { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
2
+ import type * as runs from "../runs.js";
3
+ type PublicApi = FilterApi<ApiFromModules<{
4
+ runs: typeof runs;
5
+ }>, FunctionReference<any, "public">>;
6
+ export type ComponentApi<Name extends string | undefined = string | undefined> = {
7
+ runs: {
8
+ [Key in keyof PublicApi["runs"]]: PublicApi["runs"][Key] extends FunctionReference<infer Type, any, infer Args, infer Result> ? FunctionReference<Type, "internal", Args, Result, Name> : never;
9
+ };
10
+ };
11
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { type ApiFromModules, type FilterApi, type FunctionReference } from "convex/server";
2
+ import type * as runs from "./runs.js";
3
+ import type * as worker from "./worker.js";
4
+ type Api = ApiFromModules<{
5
+ runs: typeof runs;
6
+ worker: typeof worker;
7
+ }>;
8
+ export declare const internal: FilterApi<Api, FunctionReference<any, "internal">>;
9
+ export {};
@@ -0,0 +1,2 @@
1
+ import { anyApi } from "convex/server";
2
+ export const internal = anyApi;
@@ -0,0 +1,10 @@
1
+ import { type Config } from "./shared.js";
2
+ export declare class ApiError extends Error {
3
+ retryable: boolean;
4
+ constructor(message: string, retryable: boolean);
5
+ }
6
+ export declare function request(config: Config, path: string, body?: unknown): Promise<Record<string, unknown>>;
7
+ export declare function inlineValue(value: unknown): {
8
+ value?: any;
9
+ omitted: boolean;
10
+ };
@@ -0,0 +1,48 @@
1
+ import { MAX_INLINE_BYTES, REQUEST_TIMEOUT_MS } from "./shared.js";
2
+ export class ApiError extends Error {
3
+ retryable;
4
+ constructor(message, retryable) {
5
+ super(message);
6
+ this.retryable = retryable;
7
+ }
8
+ }
9
+ export async function request(config, path, body) {
10
+ const controller = new AbortController();
11
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
12
+ try {
13
+ const response = await fetch(config.baseUrl + path, {
14
+ method: body === undefined ? "GET" : "POST",
15
+ headers: { Authorization: `Bearer ${config.secretKey}`, "Content-Type": "application/json" },
16
+ body: body === undefined ? undefined : JSON.stringify(body),
17
+ signal: controller.signal,
18
+ redirect: "error",
19
+ });
20
+ if (!response.ok) {
21
+ await response.body?.cancel();
22
+ const retryHeader = response.headers.get("x-should-retry");
23
+ // Never persist response bodies, which could contain credentials or payloads.
24
+ throw new ApiError(`Trigger.dev API returned HTTP ${response.status}`, retryHeader === "true" ||
25
+ (retryHeader !== "false" &&
26
+ (response.status === 408 ||
27
+ response.status === 409 ||
28
+ response.status === 429 ||
29
+ response.status >= 500)));
30
+ }
31
+ const data = await response.json();
32
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
33
+ throw new ApiError("Invalid Trigger.dev response", true);
34
+ }
35
+ return data;
36
+ }
37
+ finally {
38
+ clearTimeout(timeout);
39
+ }
40
+ }
41
+ export function inlineValue(value) {
42
+ if (value === undefined)
43
+ return { omitted: false };
44
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_INLINE_BYTES) {
45
+ return { omitted: true };
46
+ }
47
+ return { value, omitted: false };
48
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("convex/server").ComponentDefinition<any, {}>;
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import { defineComponent } from "convex/server";
2
+ export default defineComponent("trigger");