@systemfsoftware/trigger.dev_cli
Version:
The Trigger.dev CLI
644 lines (569 loc) • 77.1 kB
JavaScript
#!/usr/bin/env node
var Lt=Object.defineProperty;var a=(t,e)=>Lt(t,"name",{value:e,configurable:!0});import{Command as Zn}from"commander";import Ke from"inquirer";import ee from"inquirer";import k from"node:path";import fr from"ora";import{z as K}from"zod";import We from"path";import{fileURLToPath as Gt}from"url";var Wt=Gt(import.meta.url),zt=We.dirname(Wt),ze=We.join(zt,"../"),Be=`
_____ _ _
|_ _| ___ |_| ___ ___ ___ ___ _| | ___ _ _
| | | _|| || . || . || -_|| _| _ | . || -_|| | |
|_| |_| |_||_ ||_ ||___||_| |_||___||___| \\_/
|___||___|
`;var z="@systemfsoftware/trigger.dev_cli";var B="https://cloud.trigger.dev",oe="https://api.trigger.dev";import Qt from"chalk";import{execa as Ie}from"execa";import ce from"ora";import er from"path";import Yt from"path";import Z,{writeFile as Bt}from"fs/promises";import Vt from"fs";import Ve from"path";async function Ye(t,e){return await Z.mkdir(Ve.dirname(t),{recursive:!0}),await Z.writeFile(t,e),t}a(Ye,"createFile");async function f(t){try{return await Z.access(t),!0}catch{return!1}}a(f,"pathExists");async function ae(t,e){for(let r=0;r<e.length;r++){let n=e[r];if(!n)continue;let o=Ve.join(t,n);if(await f(o))return!0}return!1}a(ae,"someFileExists");async function je(t){return await Z.readFile(t,"utf8")}a(je,"readFile");async function S(t){let e=await Z.readFile(t,"utf8");return JSON.parse(e)}a(S,"readJSONFile");async function X(t,e){await Bt(t,JSON.stringify(e,null,2))}a(X,"writeJSONFile");function se(t){let e=Vt.readFileSync(t,"utf8");return JSON.parse(e)}a(se,"readJSONFileSync");async function E(t){try{return await qt(t)}catch{return Ht()}}a(E,"getUserPackageManager");function Ht(){let t=process.env.npm_config_user_agent;return t?t.startsWith("yarn")?"yarn":t.startsWith("pnpm")?"pnpm":"npm":"npm"}a(Ht,"detectPackageManagerFromCurrentCommand");async function qt(t){let e=[{name:"yarn.lock",pm:"yarn"},{name:"pnpm-lock.yaml",pm:"pnpm"},{name:"package-lock.json",pm:"npm"},{name:"npm-shrinkwrap.json",pm:"npm"}];for(let{name:r,pm:n}of e)if(await f(Yt.join(t,r)))return n;throw new Error("Could not detect package manager from artifacts")}a(qt,"detectPackageManagerFromArtifacts");import He from"fs/promises";import Zt from"node-fetch";import{ProxyAgent as Xt}from"proxy-agent";function j(t,e){let r={...e};return r.agent||(r.agent=new Xt),Zt(t,r)}a(j,"fetch");import{z as ie}from"zod";async function qe(t,e){let r=await E(t),n=ce("Adding @trigger.dev dependencies to package.json...").start(),o=await tr(t,e);n.succeed(Qt.green(`Successfully added dependencies to package.json: ${o.map(s=>`${s.name}@${s.version}`).join(", ")}`)),(await or(r,t)||ce()).stop()}a(qe,"addDependencies");async function tr(t,e){let r=er.join(t,"package.json"),n=await He.readFile(r),o=JSON.parse(n.toString()),i=await nr(e);return o.dependencies={...o.dependencies,...Object.fromEntries(i.map(s=>[s.name,`^${s.version}`]))},await He.writeFile(r,JSON.stringify(o,null,2)),i}a(tr,"addDependenciesToPackageJson");var rr=ie.object({name:ie.string(),"dist-tags":ie.record(ie.string())});async function Q(t,e){let r=await j(`https://registry.npmjs.org/${t}`);if(!r.ok)return;let n=await r.json(),o=rr.safeParse(n);if(!o.success)return;let i=o.data["dist-tags"][e];if(i)return{name:t,version:i}}a(Q,"getLatestPackageVersion");async function nr(t){return(await Promise.all(t.map(r=>Q(r.name,r.tag)))).filter(Boolean)}a(nr,"getLatestPackageVersions");async function or(t,e){switch(t){case"npm":return await Ie(t,["install"],{cwd:e,stderr:"inherit"}),null;case"pnpm":let r=ce("Running pnpm install...").start(),n=Ie(t,["install"],{cwd:e,stdout:"pipe"});return await new Promise((s,p)=>{n.stdout?.on("data",l=>{let u=l.toString();u.includes("Progress")&&(r.text=u.includes("|")?u.split(" | ")[1]??"":u)}),n.on("error",l=>p(l)),n.on("close",()=>s())}),r;case"yarn":let o=ce("Running yarn...").start(),i=Ie(t,[],{cwd:e,stdout:"pipe"});return await new Promise((s,p)=>{i.stdout?.on("data",l=>{o.text=l.toString()}),i.on("error",l=>p(l)),i.on("close",()=>s())}),o}}a(or,"runInstallCommand");import{OpenAI as ar}from"openai";import{z as Ze}from"zod";function Xe(t){return`
Here is an example of what the files should look like for the package "${t.packageName}" using the SDK package "${t.sdkPackage}".
(Note that these files are formatted as a pair of JSON key/values, where the key is the file name and the value is the file contents.)
${JSON.stringify(t.files,null,2)}
`}a(Xe,"createExampleResponse");function Re(t,e,r){return`'I'm wanting to know what the minimal starting point index.ts, types.ts, and tasks.ts files should look like for the package "${t}" using the SDK package "${e}". ${r??""}`}a(Re,"createPrompt");function sr(){return[{role:"user",content:Re("@trigger.dev.slack","@slack/web-api",'Note that the only auth method support for slack is OAuth2 so so authSource() should be "HOSTED"')},{role:"assistant",content:Xe({packageName:"@systemfsoftware/trigger.dev_slack",sdkPackage:"@slack/web-api",files:{"index.ts":`
import type {
Block,
ChatPostMessageResponse,
KnownBlock,
MessageAttachment,
MessageMetadata,
WebAPIPlatformError,
} from "@slack/web-api";
import { WebClient } from "@slack/web-api";
import {
retry,
type ConnectionAuth,
type IO,
type IOTask,
type IntegrationTaskKey,
type Json,
type RunTaskErrorCallback,
type RunTaskOptions,
type TriggerIntegration,
} from "@systemfsoftware/trigger.dev_sdk";
export type SlackIntegrationOptions = {
id: string;
};
type ConversationsJoinResponse = Awaited<ReturnType<SlackClientType["conversations"]["join"]>>;
type SlackClientType = InstanceType<typeof WebClient>;
export type ChatPostMessageArguments = {
channel: string;
text?: string;
as_user?: boolean;
attachments?: MessageAttachment[];
blocks?: (KnownBlock | Block)[];
icon_emoji?: string;
icon_url?: string;
metadata?: MessageMetadata;
link_names?: boolean;
mrkdwn?: boolean;
parse?: "full" | "none";
reply_broadcast?: boolean;
thread_ts?: string;
unfurl_links?: boolean;
unfurl_media?: boolean;
username?: string;
};
export class Slack implements TriggerIntegration {
private _options: SlackIntegrationOptions;
private _client?: WebClient;
private _io?: IO;
private _connectionKey?: string;
constructor(private options: SlackIntegrationOptions) {
this._options = options;
}
get authSource() {
return "HOSTED" as const;
}
get id() {
return this.options.id;
}
get metadata() {
return { id: "slack", name: "Slack.com" };
}
cloneForRun(io: IO, connectionKey: string, auth?: ConnectionAuth) {
const slack = new Slack(this._options);
slack._io = io;
slack._connectionKey = connectionKey;
if (!auth) {
throw new Error("No auth");
}
slack._client = new WebClient(auth.accessToken);
return slack;
}
runTask<T, TResult extends Json<T> | void>(
key: IntegrationTaskKey,
callback: (client: WebClient, task: IOTask, io: IO) => Promise<TResult>,
options?: RunTaskOptions,
errorCallback?: RunTaskErrorCallback
): Promise<TResult> {
if (!this._io) throw new Error("No IO");
if (!this._connectionKey) throw new Error("No connection key");
return this._io.runTask<TResult>(
key,
(task, io) => {
if (!this._client) throw new Error("No client");
return callback(this._client, task, io);
},
{
icon: "slack",
retry: retry.standardBackoff,
...(options ?? {}),
connectionKey: this._connectionKey,
},
errorCallback
);
}
postMessage(
key: IntegrationTaskKey,
params: ChatPostMessageArguments
): Promise<ChatPostMessageResponse> {
return this.runTask(
key,
async (client) => {
try {
return client.chat.postMessage(params);
} catch (error) {
if (isPlatformError(error)) {
if (error.data.error === "not_in_channel") {
const joinResponse = await this.joinConversation(\`Join \${params.channel}\`, {
channel: params.channel,
});
if (joinResponse.ok) {
return client.chat.postMessage(params);
}
}
}
throw error;
}
},
{
name: "Post Message",
params,
icon: "slack",
properties: [
{
label: "Channel ID",
text: params.channel,
},
...(params.text ? [{ label: "Message", text: params.text }] : []),
],
}
);
}
joinConversation(
key: IntegrationTaskKey,
params: { channel: string }
): Promise<ConversationsJoinResponse> {
return this.runTask(
key,
async (client) => {
return client.conversations.join(params);
},
{
name: "Join Channel",
params,
icon: "slack",
properties: [
{
label: "Channel ID",
text: params.channel,
},
],
}
);
}
}
function isPlatformError(error: unknown): error is WebAPIPlatformError {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
typeof error.code === "string" &&
error.code === "slack_webapi_platform_error"
);
}
`}})},{role:"user",content:Re("@systemfsoftware/trigger.dev_typeform","@typeform/api-client",'Note that the only auth method support for typeform is API Key so authSource() should be "LOCAL"')},{role:"assistant",content:Xe({packageName:"@systemfsoftware/trigger.dev_typeform",sdkPackage:"@typeform/api-client",files:{"index.ts":`
import { safeParseBody } from "@systemfsoftware/trigger.dev_integration-kit";
import {
ConnectionAuth,
EventSpecification,
ExternalSource,
ExternalSourceTrigger,
HandlerEvent,
IO,
IOTask,
IntegrationTaskKey,
Json,
Logger,
RunTaskErrorCallback,
RunTaskOptions,
TriggerIntegration,
retry,
} from "@systemfsoftware/trigger.dev_sdk";
import { createClient } from "@typeform/api-client";
import { createHmac } from "node:crypto";
import { z } from "zod";
import { Forms } from "./forms";
import { Responses } from "./responses";
import {
FormResponseEvent,
GetWebhookResponse,
TypeformIntegrationOptions,
TypeformSDK,
} from "./types";
export * from "./types";
type TypeformSource = ReturnType<typeof createWebhookEventSource>;
type TypeformTrigger = ReturnType<typeof createWebhookEventTrigger>;
export type TypeformRunTask = InstanceType<typeof Typeform>["runTask"];
export class Typeform implements TriggerIntegration {
private _options: TypeformIntegrationOptions;
private _client?: TypeformSDK;
private _io?: IO;
private _connectionKey?: string;
constructor(private options: TypeformIntegrationOptions) {
if (Object.keys(options).includes("token") && !options.token) {
throw \`Can't create Typeform integration (\${options.id}) as token was undefined\`;
}
this._options = options;
}
get authSource() {
return "LOCAL" as const;
}
get id() {
return this.options.id;
}
get metadata() {
return { id: "typeform", name: "Typeform" };
}
cloneForRun(io: IO, connectionKey: string, auth?: ConnectionAuth) {
const typeform = new Typeform(this._options);
typeform._io = io;
typeform._connectionKey = connectionKey;
typeform._client = createClient({ token: this._options.token });
return typeform;
}
runTask<T, TResult extends Json<T> | void>(
key: IntegrationTaskKey,
callback: (client: TypeformSDK, task: IOTask, io: IO) => Promise<TResult>,
options?: RunTaskOptions,
errorCallback?: RunTaskErrorCallback
): Promise<TResult> {
if (!this._io) throw new Error("No IO");
if (!this._connectionKey) throw new Error("No connection key");
return this._io.runTask(
key,
(task, io) => {
if (!this._client) throw new Error("No client");
return callback(this._client, task, io);
},
{
icon: "typeform",
retry: retry.standardBackoff,
...(options ?? {}),
connectionKey: this._connectionKey,
},
errorCallback
);
}
get forms() {
return new Forms(this.runTask.bind(this));
}
get responses() {
return new Responses(this.runTask.bind(this));
}
}
`,"forms.ts":`
import { IntegrationTaskKey } from "@systemfsoftware/trigger.dev_sdk";
import { GetFormParams, GetFormResponse, ListFormsParams, TypeformRunTask } from ".";
import { Typeform } from "@typeform/api-client";
export class Forms {
runTask: TypeformRunTask;
constructor(runTask: TypeformRunTask) {
this.runTask = runTask;
}
list(key: IntegrationTaskKey, params: ListFormsParams): Promise<Typeform.API.Forms.List> {
return this.runTask(
key,
async (client, task) => {
return client.forms.list(params ?? {});
},
{
name: "List Forms",
params,
properties: [
...(params?.workspaceId ? [{ label: "Workspace ID", text: params.workspaceId }] : []),
...(params?.search ? [{ label: "Search", text: params.search }] : []),
...(params?.page ? [{ label: "Page", text: String(params.page) }] : []),
...(params?.pageSize ? [{ label: "Page Size", text: String(params.pageSize) }] : []),
],
}
);
}
get(key: IntegrationTaskKey, params: GetFormParams): Promise<GetFormResponse> {
return this.runTask(
key,
async (client, task) => {
return client.forms.get(params);
},
{
name: "Get Form",
params,
properties: [
{
label: "Form ID",
text: params.uid,
},
],
}
);
}
}
`,"responses.ts":`
import { IntegrationTaskKey } from "@systemfsoftware/trigger.dev_sdk";
import {
GetAllResponsesParams,
GetAllResponsesResponse,
ListResponsesParams,
ListResponsesResponse,
TypeformRunTask,
} from ".";
export class Responses {
runTask: TypeformRunTask;
constructor(runTask: TypeformRunTask) {
this.runTask = runTask;
}
list(key: IntegrationTaskKey, params: ListResponsesParams): Promise<ListResponsesResponse> {
return this.runTask(
key,
async (client, task) => {
return client.responses.list(params);
},
{
name: "List Responses",
params,
properties: [
{
label: "Form ID",
text: params.uid,
},
],
}
);
}
all(key: IntegrationTaskKey, params: GetAllResponsesParams): Promise<GetAllResponsesResponse> {
const pageSize = 50;
const listResponsesForPage = (before?: string) => {
const pageParams = {
...params,
submitted_at: "desc",
before,
pageSize: pageSize,
};
return this.list(\`page\${before ? \`-before-\${before}\` : ""}\`, pageParams);
};
return this.runTask(
key,
async (client, task) => {
// We're going to create a subtask for each page of responses
const firstPage = await listResponsesForPage();
let token = firstPage.items[firstPage.items.length - 1].token;
const totalPages = Math.ceil(firstPage.total_items / pageSize);
const allResponses = firstPage.items;
for (let i = 1; i < totalPages; i++) {
const page = await listResponsesForPage(token);
token = page.items[page.items.length - 1].token;
allResponses.push(...page.items);
}
return allResponses;
},
{
name: "Get All Responses",
params,
properties: [
{
label: "Form ID",
text: params.uid,
},
],
}
);
}
}
`,"types.ts":`
import { Prettify } from "@systemfsoftware/trigger.dev_integration-kit";
import { Typeform, createClient } from "@typeform/api-client";
export type TypeformIntegrationOptions = {
id: string;
token: string;
apiBaseUrl?: string;
};
export type TypeformSDK = ReturnType<typeof createClient>;
export type ListFormsParams = {
page?: number;
pageSize?: number;
search?: string;
workspaceId?: string;
} | void;
export type ListFormsResponse = Prettify<Typeform.API.Forms.List>;
export type ListResponsesParams = {
uid: string;
pageSize?: number;
since?: string;
until?: string;
after?: string;
before?: string;
ids?: string | string[];
completed?: boolean;
sort?: string;
query?: string;
fields?: string | string[];
};
//fix because the Typeform SDK doesn't have the \`token\` property on an item\u2026
type ResponseListItem = Prettify<Typeform.API.Responses.List["items"][number]> & {
token?: string;
};
export type ListResponsesResponse = Prettify<
Omit<Typeform.API.Responses.List, "items"> & { items: ResponseListItem[] }
>;
export type GetFormParams = {
uid: string;
};
export type GetFormResponse = Prettify<Typeform.Form>;
export type GetAllResponsesParams = Prettify<Omit<ListResponsesParams, "pageSize">>;
export type GetAllResponsesResponse = Prettify<Typeform.API.Responses.List["items"]>;
export type GetWebhookResponse = Prettify<Typeform.Webhook>;
export type ListWebhooksParams = {
uid: string;
};
export type ListWebhooksResponse = Prettify<Typeform.API.Webhooks.List>;
export type CreateWebhookParams = {
uid: string;
tag: string;
url: string;
enabled?: boolean;
secret?: string;
verifySSL?: boolean;
};
export type UpdateWebhookParams = {
uid: string;
tag: string;
url: string;
enabled?: boolean;
secret?: string;
verifySSL?: boolean;
};
export type GetWebhookParams = {
uid: string;
tag: string;
};
export type DeleteWebhookParams = {
uid: string;
tag: string;
};
export type DeleteWebhookResponse = null;
export type FormResponseEvent = {
event_id: string;
event_type: "form_response";
form_response: {
form_id: string;
token: string;
landed_at: string;
submitted_at: string;
calculated: {
score: number;
};
variables: Array<
| {
key: string;
type: "number";
number: number;
}
| {
key: string;
type: "text";
text: string;
}
>;
hidden: Record<string, string>;
definition: {
id: string;
title: string;
fields: Array<{
id: string;
ref: string;
type: string;
title: string;
allow_multiple_selections?: boolean;
allow_other_choice?: boolean;
properties?: Record<string, string | boolean | number>;
choices?: Array<{
id: string;
label: string;
}>;
}>;
ending: {
id: string;
title: string;
ref: string;
type: string;
properties?: Record<string, string | boolean | number>;
};
};
answers: Array<FormResponseAnswer>;
ending: {
id: string;
ref: string;
};
};
};
type FormResponseAnswerBase = {
field: {
id: string;
type: string;
ref: string;
};
};
type FormResponseAnswerEmail = Prettify<
FormResponseAnswerBase & {
type: "email";
email: string;
}
>;
type FormResponseAnswerText = Prettify<
FormResponseAnswerBase & {
type: "text";
text: string;
}
>;
type FormResponseAnswerNumber = Prettify<
FormResponseAnswerBase & {
type: "number";
number: number;
}
>;
type FormResponseAnswerBoolean = Prettify<
FormResponseAnswerBase & {
type: "boolean";
boolean: boolean;
}
>;
type FormResponseAnswerDate = Prettify<
FormResponseAnswerBase & {
type: "date";
date: string;
}
>;
type FormResponseAnswerChoice = Prettify<
FormResponseAnswerBase & {
type: "choice";
choice: {
label: string;
};
}
>;
type FormResponseAnswer = Prettify<
| FormResponseAnswerEmail
| FormResponseAnswerText
| FormResponseAnswerNumber
| FormResponseAnswerBoolean
| FormResponseAnswerDate
| FormResponseAnswerChoice
>;
`}})}]}a(sr,"createExampleMessages");async function Qe(t,e,r){if(!e)return;let n=new ar({apiKey:e,organization:r});try{let i=(await n.chat.completions.create({model:"gpt-4",messages:[{role:"system",content:"You will be provided with the task of creating the typescript files necessary for a new Trigger.dev integration package. You will be provided the name of the integration package and the name of the SDK package."},...sr(),{role:"user",content:Re(t.packageName,t.sdkPackage,t.extraInfo)}],function_call:{name:"createTypescriptFiles"},functions:[{name:"createTypescriptFiles",description:"Creates the initial typescript files for a new Trigger.dev package",parameters:{type:"object",properties:{"index.ts":{type:"string",description:"The contents of the index.ts file"}}}}]})).choices[0];if(!i)return;let s=i.message;if(!s||!s.function_call||!s.function_call.arguments)return;let p=ir(s.function_call.arguments);if(!p)return;let u=Ze.record(Ze.string()).safeParse(p);return u.success?u.data:void 0}catch(o){console.error(o);return}}a(Qe,"generateIntegrationFiles");function ir(t){try{return JSON.parse(t)}catch{return null}}a(ir,"safeJsonParse");function et(t){return t.split("/")[1]??""}a(et,"getPackageName");import pe from"chalk";var c={error(...t){console.log(pe.red(...t))},warn(...t){console.log(pe.yellow(...t))},info(...t){console.log(pe.cyan(...t))},success(...t){console.log(pe.green(...t))},table(t){console.table(t)}};import Ae from"ora";import cr from"chalk";import{execa as Ee}from"execa";async function le(t){c.info("Installing dependencies...");let e=await E(t);(await pr(e,t)||Ae()).succeed(cr.green(`Successfully installed dependencies!
`))}a(le,"installDependencies");async function pr(t,e){switch(t){case"npm":return await Ee(t,["install"],{cwd:e,stderr:"inherit"}),null;case"pnpm":let r=Ae("Running pnpm install...").start(),n=Ee(t,["install"],{cwd:e,stdout:"pipe"});return await new Promise((s,p)=>{n.stdout?.on("data",l=>{let u=l.toString();u.includes("Progress")&&(r.text=u.includes("|")?u.split(" | ")[1]??"":u)}),n.on("error",l=>p(l)),n.on("close",()=>s())}),r;case"yarn":let o=Ae("Running yarn...").start(),i=Ee(t,[],{cwd:e,stdout:"pipe"});return await new Promise((s,p)=>{i.stdout?.on("data",l=>{o.text=l.toString()}),i.on("error",l=>p(l)),i.on("close",()=>s())}),o}}a(pr,"runInstallCommand");import tt from"path";var A=a(t=>tt.resolve(process.cwd(),t),"resolvePath"),rt=a(t=>tt.relative(process.cwd(),t),"relativePath");import ot from"fs/promises";import{Liquid as dr}from"liquidjs";import at from"path";import nt from"path";import{fileURLToPath as lr}from"url";function ur(){let t=lr(import.meta.url);return nt.dirname(t)}a(ur,"rootPath");function D(){let t=ur();return nt.join(t,"templates")}a(D,"templatesPath");var mr=at.join(D(),"integration"),gr=new dr({root:mr,trimTagRight:!0,trimOutputRight:!0});async function st(t){if(await f(t.outputPath))return{success:!0,alreadyExisted:!0};try{let e=await gr.renderFile(t.relativeTemplatePath,t.variables),r=at.dirname(t.outputPath);return await ot.mkdir(r,{recursive:!0}),await ot.writeFile(t.outputPath,e),{success:!0,alreadyExisted:!1}}catch(e){return e instanceof Error?{success:!1,error:e.message}:{success:!1,error:JSON.stringify(e)}}}a(st,"createIntegrationFileFromTemplate");var hr=K.object({packageName:K.string().optional(),sdkPackage:K.string().optional(),extraInfo:K.string().optional(),skipGeneratingCode:K.coerce.boolean().optional(),authMethod:K.enum(["api-key","oauth","both-methods"]).optional(),openaiKey:K.string().optional(),openaiOrg:K.string().optional()});async function ct(t,e){let r=hr.safeParse(e);r.success||(c.error(r.error.message),process.exit(1));let n=r.data,o=A(t);await f(o)&&(c.error(`The path ${o} already exists. Please try again with a different path.`),process.exit(1));let s=await wr(n,o),p=await Q(s.sdkPackage,"latest");p||(c.error(`Could not find the latest version of ${s.sdkPackage}. Please try again later.`),process.exit(1));let l=await br(o),u=await Fe({path:"packages/trigger-sdk",packageName:"@systemfsoftware/trigger.dev_sdk",tag:"latest",monorepoPath:l});u||(c.error("Could not find the latest version of @systemfsoftware/trigger.dev_sdk. Please try again later."),process.exit(1));let d=await Fe({path:"packages/integration-kit",packageName:"@systemfsoftware/trigger.dev_integration-kit",tag:"latest",monorepoPath:l});d||(c.error("Could not find the latest version of @systemfsoftware/trigger.dev_integration-kit. Please try again later."),process.exit(1));let y=await Fe({path:"integrations/github",packageName:"@systemfsoftware/trigger.dev_github",tag:"latest",monorepoPath:l,prependWorkspace:!1});y||(c.error("Could not find the latest version of @systemfsoftware/trigger.dev_github. Please try again later."),process.exit(1));let m={packageName:s.packageName,sdkPackage:s.sdkPackage,integrationVersion:y,latestVersion:p,sdkVersion:u,integrationKitVersion:d,triggerMonorepoPath:l},v=a(w=>k.join(o,w),"getOutputPath"),P=[{relativeTemplatePath:"package.json.j2",outputPath:v("package.json")},{relativeTemplatePath:`tsconfig-${l?"internal":"external"}.json.j2`,outputPath:v("tsconfig.json")},{relativeTemplatePath:`tsup.config-${l?"internal":"external"}.js.j2`,outputPath:v("tsup.config.ts")},{relativeTemplatePath:"README.md.j2",outputPath:v("README.md")}];if(await it(P,m),s.skipGeneratingCode){let w=a(G=>v(k.join("src",G)),"getSrcOutputPath"),J=[{relativeTemplatePath:k.join("payload-examples","index.js.j2"),outputPath:w(k.join("payload-examples","index.ts"))},{relativeTemplatePath:"events.js.j2",outputPath:w("events.ts")},{relativeTemplatePath:"index.js.j2",outputPath:w("index.ts")},{relativeTemplatePath:"models.js.j2",outputPath:w("models.ts")},{relativeTemplatePath:"schemas.js.j2",outputPath:w("schemas.ts")},{relativeTemplatePath:"types.js.j2",outputPath:w("types.ts")},{relativeTemplatePath:"utils.js.j2",outputPath:w("utils.ts")},{relativeTemplatePath:"webhooks.js.j2",outputPath:w("webhooks.ts")}],C=k.basename(t).replace(/[^a-zA-Z0-9]+/g,"").replace(/^[0-9]+/g,"");await it(J,{...m,apiKeyPropertyName:"apiKey",authMethod:s.authMethod,identifier:C.length?C:"packageName"})}else await yr(k.join(o,"src"),s);l&&await _r(l,o,s),await le(o),c.success(`\u2714 Successfully initialized ${s.packageName} at ${o}`),c.info("Next steps:"),c.info(" 1. If you generated code, double check it for errors."),c.info(' 2. Read the "Creating an Integration" guide at https://trigger.dev/docs/integrations/create'),l&&c.info(" 3. Write some test jobs in the references/job-catalog")}a(ct,"createIntegrationCommand");async function yr(t,e){let r=fr("Generating integration code (may take ~30s)").start();function n(s,p){let l="";switch(s){case"api-key":{l="Note that the only auth method that this integration supports is API keys so can only useLocalAuth to true and don't use the clientFactory option";break}case"oauth":{l="Note that the only auth method that this integration supports is OAuth so can only useLocalAuth to false and make sure to use the clientFactory option";break}case"both-methods":{l="Note that this integration supports both API keys and OAuth so the options passed to the constructor must support both.";break}}return`${l}
${p??""}`}a(n,"generateExtraInfo");let o=n(e.authMethod,e.extraInfo),i=await Qe({packageName:e.packageName,sdkPackage:e.sdkPackage,extraInfo:o},e.openaiKey??process.env.OPENAI_API_KEY,e.openaiOrg??process.env.OPENAI_ORGANIZATION);i?(await Promise.all(Object.entries(i).map(([s,p])=>pt(t,s,p))),r.succeed(`Generated integration code in ${t}`)):r.fail("Failed to generate integration code")}a(yr,"attemptToGenerateIntegrationFiles");async function pt(t,e,r){await Ye(k.join(t,e),r)}a(pt,"createFileInPath");var wr=a(async(t,e)=>{let r={...t};try{t.packageName||(r.packageName=await kr(e)),t.sdkPackage||(r.sdkPackage=await vr()),!process.env.OPENAI_API_KEY&&!t.openaiKey&&(r.skipGeneratingCode=!0),r.authMethod=await xr(),r.skipGeneratingCode||(r.extraInfo=await Pr())}catch(n){if(n instanceof Error&&n.isTTYError){c.warn(`'${z} create-integration' needs an interactive terminal to provide options`);let{shouldContinue:o}=await ee.prompt({name:"shouldContinue",type:"confirm",message:"Continue initializing your trigger.dev project?",default:!0});o||(c.info("Exiting..."),process.exit(0))}else throw n}return r},"resolveOptionsWithPrompts"),kr=a(async t=>{let e=k.basename(t),{packageName:r}=await ee.prompt({type:"input",name:"packageName",default:`@systemfsoftware/trigger.dev_${e}`,message:"What is the name of your integration package?",validate:n=>n?!0:"Please enter a package name"});return r},"promptPackageName"),vr=a(async()=>{let{sdkPackage:t}=await ee.prompt({type:"input",name:"sdkPackage",message:"What is the name of the npm package for this API? (e.g. airtable)?",validate:e=>e?!0:"Please enter an SDK package name"});return t},"promptSdkPackage"),Pr=a(async()=>{let{extraInfo:t}=await ee.prompt({type:"input",name:"extraInfo",message:"Please describe in english anything else about using the SDK that might be useful (optional)"});return t},"promptExtraInfo"),xr=a(async()=>{let{authMethod:t}=await ee.prompt({type:"list",name:"authMethod",message:"What authentication method does this API use?",choices:[{name:"API Key",value:"api-key"},{name:"OAuth",value:"oauth"},{name:"Both API Key and OAuth",value:"both-methods"}]});return t},"promptAuthMethod");async function br(t){let e=await lt(t);if(!e)return;let r=k.join(e,"package.json");if(!await f(r))return;if((await S(r)).name==="triggerdotdev")return e}a(br,"detectTriggerMonorepoPath");async function Fe({packageName:t,tag:e,path:r,monorepoPath:n,prependWorkspace:o=!0}){if(!n)return await Q(t,e);let i=k.join(n,r,"package.json");if(!await f(i))return await Q(t,e);let p=await S(i);return{name:p.name,version:`${o?"workspace:^":""}${p.version}`}}a(Fe,"getInternalOrExternalPackageVersion");async function lt(t){let e=k.join(t,".git");if(await f(e))return t;let n=k.dirname(t);if(n!==t)return lt(n)}a(lt,"findGitPath");async function _r(t,e,r){let n=et(r.packageName),o=k.join(t,"references","job-catalog"),i=k.join(o,"src");await pt(i,`${n}.ts`,"export {}");let p=k.join(o,"package.json"),l=await S(p),u={...l,scripts:{...l.scripts,[n]:`nodemon --watch src/${n}.ts -r tsconfig-paths/register -r dotenv/config src/${n}.ts`},dependencies:{...l.dependencies,[r.packageName]:"workspace:*"}};if(u.scripts.hasOwnProperty("dev:trigger")){let v=u.scripts["dev:trigger"];delete u.scripts["dev:trigger"],u.scripts["dev:trigger"]=v}await X(p,u);let d=k.join(o,"tsconfig.json"),y=await S(d),m={...y,compilerOptions:{...y.compilerOptions,paths:{...y.compilerOptions.paths,[r.packageName]:[`../../integrations/${k.basename(e)}/src/index`],[`${r.packageName}/*`]:[`../../integrations/${k.basename(e)}/src/*`]}}};await X(d,m)}a(_r,"updateJobCatalogWithNewIntegration");var it=a(async(t,e)=>{for(let r of t){let n=await st({...r,variables:e});Tr(r.outputPath,n)}},"createIntegrationFiles"),Tr=a((t,e)=>{if(!e.success)throw new Error(`Failed to create ${k.basename(t)}: ${e.error}`);c.success(`\u2714 Created ${k.basename(t)} at ${rt(t)}`)},"handleCreateResult");import pn from"boxen";import ln from"child_process";import un from"chokidar";import Tt from"ngrok";import be from"ora";import jt,{AbortError as Et}from"p-retry";import dn from"util";import{z as L}from"zod";import mn from"https";var I=["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.json","pnpm-lock.yaml"],ut=/(node_modules)/;import{PostHog as Ir}from"posthog-node";import{nanoid as Rr}from"nanoid";import jr from"path";function $(){let t=jr.join(ze,"package.json");return se(t).version??"1.0.0"}a($,"getVersion");var Er="phc_9aSDbJCaDUMdZdHxxMPTvcj7A9fsl3mCgM1RBPmPsl7",Ce=class{static{a(this,"TelemetryClient")}#e;#t;#n;constructor(){this.#e=new Ir(Er,{host:"https://eu.posthog.com",flushAt:1}),this.#t=`cli-${Rr()}`,this.#n=$()}identify(e,r,n){n&&this.#e.alias({distinctId:n,alias:this.#t}),this.#e.groupIdentify({groupType:"organization",groupKey:e}),this.#e.groupIdentify({groupType:"project",groupKey:r})}init={started:e=>{this.#e.capture({distinctId:this.#t,event:"cli_init_started",properties:this.#r(e)})},isTypescriptProject:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_init_typescriptproject",properties:{...this.#r(r),isTypescriptProject:e}})},resolvedApiUrl:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_init_resolved_apiurl",properties:{...this.#r(r),apiUrl:e}})},resolvedApiKey:e=>{this.#e.capture({distinctId:this.#t,event:"cli_init_resolved_apikey",properties:this.#r(e)})},resolvedEndpointSlug:e=>{this.#e.capture({distinctId:this.#t,event:"cli_init_resolved_endpoint_slug",properties:this.#r(e)})},addedDependencies:e=>{this.#e.capture({distinctId:this.#t,event:"cli_init_added_dependencies",properties:this.#r(e)})},install:(e,r,n)=>{this.#e.capture({distinctId:this.#t,event:"cli_init_install",properties:{...this.#r(e),framework:r,...n}})},postInstall:(e,r,n)=>{this.#e.capture({distinctId:this.#t,event:"cli_init_post_install",properties:{...this.#r(e),framework:r,...n}})},completed:e=>{this.#e.capture({distinctId:this.#t,event:"cli_init_completed",properties:this.#r(e)})},warning:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_init_warning",properties:{...this.#r(r),reason:e}})},failed:(e,r,n)=>{let o=n instanceof Error?n.message:String(n);this.#e.capture({distinctId:this.#t,event:"cli_init_failed",properties:{...this.#r(r),reason:e,error:o}})}};dev={started:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_dev_started",properties:{...r,path:e}})},serverRunning:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_dev_server_running",properties:{...r,path:e}})},tunnelRunning:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_dev_tunnel_running",properties:{...r,path:e}})},connected:(e,r)=>{this.#e.capture({distinctId:this.#t,event:"cli_dev_connected",properties:{...r,path:e}})},failed:(e,r,n)=>{let o=n instanceof Error?n.message:String(n);this.#e.capture({distinctId:this.#t,event:"cli_dev_failed",properties:{...r,reason:e,error:o}})}};#r(e){return{version:this.#n,hadApiKey:e.apiKey!==void 0,triggerUrl:e.triggerUrl,endpointSlug:e.endpointSlug,apiUrl:e.apiUrl}}},g=new Ce;import ue from"fs/promises";import dt from"path";function Se(t){return t.replace(/tr_dev_[a-zA-Z0-9]{6}/g,"tr_dev_********")}a(Se,"renderApiKey");async function de(t,e){if(e.length===0)throw new Error("No possible names provided");for(let r=0;r<e.length;r++){let n=e[r];if(!n)continue;let o=dt.join(t,n);if(await f(o))return n}}a(de,"getEnvFilename");async function mt(t,e,r){await $e(t,e,"TRIGGER_API_KEY",r,!0,Se)}a(mt,"setApiKeyEnvironmentVariable");async function gt(t,e,r){await $e(t,e,"TRIGGER_API_URL",r,!0)}a(gt,"setApiUrlEnvironmentVariable");async function ft(t,e,r,n){await $e(t,e,r??"TRIGGER_PUBLIC_API_KEY",n,!0,Se)}a(ft,"setPublicApiKeyEnvironmentVariable");async function $e(t,e,r,n,o=!0,i=s=>s){let s=dt.join(t,e);await f(s)||await ue.writeFile(s,"");let l=await ue.readFile(s,"utf-8");if(l.includes(r)){if(!o){c.info(`\u2611 Skipping setting ${r}=${i(n)} because it already exists`);return}let u=l.replace(new RegExp(`${r}=.*\\n`,"g"),`${r}=${n}
`);await ue.writeFile(s,u),c.success(`\u2714 Set ${r}=${i(n)} in ${e}`)}else await ue.appendFile(s,`
${r}=${n}`),c.success(`\u2714 Added ${r}=${i(n)} to ${e}`)}a($e,"setEnvironmentVariable");function me(t){let e=Ar(t);return e?e.environment==="dev"&&e.type==="server"?{success:!0}:{success:!1,type:e}:{success:!1,type:void 0}}a(me,"checkApiKeyIsDevServer");function Ar(t){if(t.startsWith("tr_dev_"))return{environment:"dev",type:"server"};if(t.startsWith("pk_dev_"))return{environment:"dev",type:"public"};if(t.startsWith("tr_prod_"))return{environment:"prod",type:"server"};if(t.startsWith("pk_prod_"))return{environment:"prod",type:"public"}}a(Ar,"getApiKeyType");import ht from"path";import Fr from"dotenv";var Cr=[".env",".env.local",".env.development.local"];async function yt(t,e,r){let n=await Sr(t,e),o=n?{output:Fr.parse(n.content),filename:n.fileName}:{};return Object.fromEntries(r.map(i=>[i,$r(i)??Nr(i,o)]))}a(yt,"readEnvVariables");async function Sr(t,e){let r=ht.join(t,e);if(await f(r))return{content:await je(r),fileName:e};for(let o of Cr){let i=ht.join(t,o);if(await f(i))return{content:await je(i),fileName:o}}}a(Sr,"readEnvFilesWithBackups");function $r(t){let e=process.env[t];if(e)return{value:e,source:{type:"runtime"}}}a($r,"readFromRuntime");function Nr(t,e){let r=e.output?e.output[t]:void 0;if(r)return{value:r,source:{type:"file",name:e.filename}}}a(Nr,"readFromFile");async function W(t,e){let n=await yt(t,e,["TRIGGER_API_KEY","TRIGGER_API_URL"]),o=n.TRIGGER_API_KEY,i=n.TRIGGER_API_URL;if(!o){c.error(`You must add TRIGGER_API_KEY to your ${e} file or set as runtime environment variable.`);return}let s=me(o.value);if(!s.success){s.type?c.error(`Your TRIGGER_API_KEY isn't a secret dev API key, you've entered a ${s.type.environment} ${s.type.type} key`):c.error("Your TRIGGER_API_KEY isn't a secret dev API key. It should start with tr_dev_.");return}return{apiKey:o.value,apiUrl:i?.value??oe,apiKeySource:o.source.type==="runtime"?"process runtime":`${o.source.name} file`}}a(W,"getTriggerApiDetails");import F from"path";import Or from"path";import{parse as Ur}from"tsconfck";async function V({projectPath:t,isTypescriptProject:e,extraDirectories:r}){let n=e?"tsconfig.json":"jsconfig.json",o=Or.join(t,n),i=await f(o);if(!e&&!i)return;let{tsconfig:s}=await Ur(o),p=s?.compilerOptions?.paths;if(p===void 0)return;let l=Object.keys(p).find(u=>{let d=p[u];if(d.length===0)return!1;let y=d[0];return r&&r.length>0?y===`./${r.join("/")}/*`:y==="./*"});if(l)return l.slice(0,-2)}a(V,"getPathAlias");import Ne from"fs/promises";import Kr from"path";import Jr from"mock-fs";import Dr from"fs/promises";function wt(t){return Jr.bypass(async()=>await Dr.readFile(t,{encoding:"utf-8"}))}a(wt,"readFileIgnoringMock");async function _(t){let e="";if(t.mockTemplatePath===!0?e=await Ne.readFile(t.templatePath,"utf-8"):e=await wt(t.templatePath),await f(t.outputPath))return{success:!0,alreadyExisted:!0};try{let r=Mr(e,t.replacements),n=Kr.dirname(t.outputPath);return await Ne.mkdir(n,{recursive:!0}),await Ne.writeFile(t.outputPath,r),{success:!0,alreadyExisted:!1}}catch(r){return r instanceof Error?{success:!1,error:r.message}:{success:!1,error:JSON.stringify(r)}}}a(_,"createFileFromTemplate");function Mr(t,e){let r=t;for(let[n,o]of Object.entries(e))r=r.replace(new RegExp(`\\$\\{${n}\\}`,"g"),o);return r}a(Mr,"replaceAll");import Lr from"path";async function T(t){let e=Lr.join(t,"package.json");return S(e).then(r=>r).catch(()=>{})}a(T,"readPackageJson");var ge=class{static{a(this,"Astro")}id="astro";name="Astro";async isMatch(e,r){return!!(await ae(e,["astro.config.js","astro.config.mjs","astro.config.cjs","astro.config.ts"])||(await T(e))?.dependencies?.astro)}async dependencies(){return[{name:"@systemfsoftware/trigger.dev_sdk",tag:"latest"},{name:"@systemfsoftware/trigger.dev_astro",tag:"latest"},{name:"@systemfsoftware/trigger.dev_react",tag:"latest"}]}possibleEnvFilenames(){return[".env",".env.development"]}async install(e,{typescript:r,endpointSlug:n}){let o=await V({projectPath:e,isTypescriptProject:r,extraDirectories:["src"]}),i=F.join(D(),"astro"),s=F.join(e,"src"),p=r?".ts":".js",l=F.join(s,"pages","api",`trigger${p}`);if(!(await _({templatePath:F.join(i,"apiRoute.js"),replacements:{routePathPrefix:o?o+"/":"../../"},outputPath:l})).success)throw new Error("Failed to create API route file");c.success(`\u2714 Created API route at ${l}`);let d=F.join(s,`trigger${p}`);if(!(await _({templatePath:F.join(i,"trigger.js"),replacements:{endpointSlug:n},outputPath:d})).success)throw new Error("Failed to create trigger file");c.success(`\u2714 Created Trigger client at ${d}`);let m=F.join(s,"jobs",`example${p}`);if(!(await _({templatePath:F.join(i,"exampleJob.js"),replacements:{jobsPathPrefix:o?o+"/":"../"},outputPath:m})).success)throw new Error("Failed to create example job file");c.success(`\u2714 Created example job at ${m}`);let P=F.join(s,"jobs",`index${p}`);if(!(await _({templatePath:F.join(i,"jobsIndex.js"),replacements:{jobsPathPrefix:o?o+"/":"../"},outputPath:P})).success)throw new Error("Failed to create jobs index file");c.success(`\u2714 Created jobs index at ${P}`)}async postInstall(e,r){c.warn(`\u26A0\uFE0E Ensure your astro.config output is "server" or "hybrid":
https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project`)}defaultHostnames=["localhost","[::]"];defaultPorts=[4321,4322,4323,4324];watchFilePaths=I;watchIgnoreRegex=/(node_modules)/};import Gr from"boxen";var fe=class{static{a(this,"Express")}id="express";name="Express";async isMatch(e,r){return!!(await T(e))?.dependencies?.express}async dependencies(){return[{name:"@systemfsoftware/trigger.dev_sdk",tag:"latest"},{name:"@systemfsoftware/trigger.dev_express",tag:"latest"}]}possibleEnvFilenames(){return[".env"]}async install(e,{typescript:r,endpointSlug:n}){}async postInstall(e,r){}async printInstallationComplete(e){c.info(Gr(`Automatic installation isn't currently supported for Express.
Follow the steps in our manual installation guide: https://trigger.dev/docs/documentation/guides/manual/express`,{padding:1,margin:1,borderStyle:"double",borderColor:"magenta"}))}defaultHostnames=["localhost","[::]"];defaultPorts=[3e3,8e3,80,8080];watchFilePaths=I;watchIgnoreRegex=/(node_modules)/};import Wr from"boxen";var he=class{static{a(this,"Hono")}id="hono";name="Hono.dev";async isMatch(e,r){return!!(await T(e))?.dependencies?.hono}async dependencies(){return[{name:"@systemfsoftware/trigger.dev_sdk",tag:"latest"},{name:"@systemfsoftware/trigger.dev_hono",tag:"latest"}]}possibleEnvFilenames(){return[".dev.vars",".env"]}async install(e,{typescript:r,endpointSlug:n}){}async postInstall(e,r){}async printInstallationComplete(e){c.info(Wr(`Automatic installation isn't currently supported for Hono.dev.
Follow the steps in our quickstart installation guide: https://trigger.dev/docs/documentation/quickstarts/hono`,{padding:1,margin:1,borderStyle:"double",borderColor:"magenta"}))}defaultHostnames=["127.0.0.1","localhost","[::]"];defaultPorts=[3e3,8e3,80,8080];watchFilePaths=I;watchIgnoreRegex=/(node_modules)/};import Hr from"fs/promises";import b from"path";import qr from"boxen";import zr from"fs/promises";import Oe from"path";import{pathToRegexp as Br}from"path-to-regexp";async function kt(t,e){let r=await Ue(t),n=Oe.join(t,r?"src":"",`middleware.${e?"ts":"js"}`);try{return await Vr(t,e,n)}catch{return{hasMiddleware:!0,conflict:"possible",middlewarePath:Oe.relative(process.cwd(),n)}}}a(kt,"detectMiddlewareUsage");async function Vr(t,e,r){if(!await f(r))return{hasMiddleware:!1};let o=Oe.relative(process.cwd(),r),i=await Yr(r);return!i||i.length===0?{hasMiddleware:!0,conflict:"possible",middlewarePath:o}:i.length===0?{hasMiddleware:!0,conflict:"unlikely",middlewarePath:o}:i.map(p=>Br(p)).some(p=>p.test("/api/trigger"))?{hasMiddleware:!0,conflict:"likely",middlewarePath:o}:{hasMiddleware:!0,conflict:"possible",middlewarePath:o}}a(Vr,"detectMiddleware");async function Yr(t){let e=await zr.readFile(t,"utf-8"),n=/matcher:\s*(\[.*\]|["'].*["'])/g.exec(e);if(!n)return[];if(n.length<2)return[];let o=n[1];if(o.startsWith("[")&&o.endsWith("]")){o=o.slice(1,-1);let i=/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,s,p=[];for(;(s=i.exec(o))!==null;)p.push(s[1].slice(1,-1));return p}else return[o.slice(1,-1)]}a(Yr,"getMiddlewareConfigMatcher");var ye=class{static{a(this,"NextJs")}id="nextjs";name="Next.js";async isMatch(e,r){return await Zr(e)?!0:await Xr(e)}async dependencies(){return[{name:"@systemfsoftware/trigger.dev_sdk",tag:"latest"},{name:"@systemfsoftware/trigger.dev_nextjs",tag:"latest"},{name:"@systemfsoftware/trigger.dev_react",tag:"latest"}]}possibleEnvFilenames(){return[".env.local",".env"]}publicKeyEnvName="NEXT_PUBLIC_TRIGGER_PUBLIC_API_KEY";async install(e,r){let n=await Ue(e);n&&c.info("\u{1F4C1} Detected use of src directory");let o=await Qr(e),i=await en(e),s=b.join(e,n?"src":""),p=await V({projectPath:e,isTypescriptProject:r.typescript,extraDirectories:n?["src"]:void 0}),l=r.typescript?".ts":".js";if(o==="pages"){let u=b.join(s,"pages","api",`trigger${l}`);i&&i!=="latest"&&i<"13.5"?await Je({path:s,apiRoutePath:u,template:"pagesApiRoute.js",fileExtension:l,endpointSlug:r.endpointSlug,pathAlias:p}):await Je({path:s,apiRoutePath:u,template:"pagesApiRouteWithConfigObject.js",fileExtension:l,endpointSlug:r.endpointSlug,pathAlias:p})}else{let u=b.join(s,"app","api","trigger",`route${l}`);await Je({path:s,apiRoutePath:u,template:"appApiRoute.js",fileExtension:l,endpointSlug:r.endpointSlug,pathAlias:p})}}async postInstall(e,r){let n=await kt(e,r.typescript);if(n.hasMiddleware)switch(n.conflict){case"possible":{c.warn(`\u26A0\uFE0F \u26A0\uFE0F \u26A0\uFE0F It looks like there might be conflicting Next.js middleware in ${n.middlewarePath} which can cause issues with Trigger.dev. Please see https://trigger.dev/docs/documentation/guides/platforms/nextjs#middleware`),g.init.warning("middleware_conflict",{projectPath:e});break}case"likely":{c.warn(`\u{1F6A8} It looks like there might be conflicting Next.js middleware in ${n.middlewarePath} which will cause issues with Trigger.dev. Please see https://trigger.dev/docs/documentation/guides/platforms/nextjs#middleware`),g.init.warning("middleware_conflict",{projectPath:e});break}default:break}}defaultHostnames=["localhost"];defaultPorts=[3e3,3001,3002];watchFilePaths=I;watchIgnoreRegex=/(node_modules|\.next)/};async function Zr(t){return ae(t,["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"])}a(Zr,"detectNextConfigFile");async function Xr(t){let e=await T(t);return e?e.dependencies?.next!==void 0||e.devDependencies?.next!==void 0:!1}a(Xr,"detectNextDependency");async function Ue(t){try{return await Hr.access(b.join(t,"src")),!0}catch{return!1}}a(Ue,"detectUseOfSrcDir");async function Qr(t){let e=b.join(t,"app");if(await f(e))return"app";let r=b.join(t,"src","app");return await f(r)?"app":"pages"}a(Qr,"detectPagesOrAppDir");async function en(t){let e=await T(t);if(!e)return null;let r=/[\d.]+|latest/;return e.dependencies?.next!==void 0?e.dependencies?.next?.match(r)?.at(0)??null:e.devDependencies?.next!==void 0?e.devDependencies?.next?.match(r)?.at(0)??null:null}a(en,"detectNextVersion");async function Je(t){let{path:e,apiRoutePath:r,template:n,pathAlias:o,endpointSlug:i,fileExtension:s}=t,p=b.join(D(),"nextjs");if(!(await _({templatePath:b.join(p,n),replacements:{routePathPrefix:o?o+"/":"../../"},outputPath:r})).success)throw new Error("Failed to create API route file");c.success(`\u2714 Created API route at ${r}`),c.info(qr(`If you're deploying to Vercel, configure your max duration in ${r}`,{padding:1,margin:1,borderStyle:"double",borderColor:"magenta"})),await tn(e,i,s,o,p)}a(Je,"createTriggerRoute");async function tn(t,e,r,n,o){let i=b.join(t,`trigger${r}`);if(!(await _({templatePath:b.join(o,"trigger.js"),replacements:{endpointSlug:e},outputPath:i})).success)throw new Error("Failed to create trigger file");c.success(`\u2714 Created Trigger client at ${i}`);let p=b.join(t,"jobs"),l=b.join(p,`examples${r}`);if(!(await _({templatePath:b.join(o,"exampleJob.js"),replacements:{jobsPathPrefix:n?n+"/":"../"},outputPath:l})).success)throw new Error("Failed to create example job file");c.success(`\u2714 Created example job at ${l}`);let d=b.join(p,`index${r}`);if(!(await _({templatePath:b.join(o,"jobsIndex.js"),replacements:{jobsPathPrefix:n?n+"/":"../"},outputPath:d})).success)throw new Error("Failed to create jobs index file");c.success(`\u2714 Created jobs index at ${d}`)}a(tn,"createJobsAndTriggerFile");import N from"path";var we=class{static{a(this,"Remix")}id="remix";name="Remix";async isMatch(e,r){if(await f(N.join(e,"remix.config.js")))return!0;let o=await T(e);return o?!!Object.keys(o.dependencies||{}).find(p=>p.startsWith("@remix-run")):!1}async dependencies(){return[{name:"@systemfsoftware/trigger.dev_sdk",tag:"latest"},{name:"@systemfsoftware/trigger.dev_remix",tag:"latest"},{name:"@systemfsoftware/trigger.dev_react",tag:"latest"}]}possibleEnvFilenames(){return[".env"]}async install(e,{typescript:r,endpointSlug:n}){let o=await V({projectPath:e,isTypescriptProject:r,extraDirectories:["app"]}),i=N.join(D(),"remix"),s=N.join(e,"app"),p=r?".ts":".js",l=N.join(s,"routes",`api.trigger${p}`);if(!(await _({templatePath:N.join(i,"apiRoute.js"),replacements:{routePathPrefix:o?o+"/":"../../"},outputPath:l})).success)throw new Error("Failed to create API route file");c.success(`\u2714 Created API route at ${l}`);let d=N.join(s,`trigger.server${p}`);if(!(await _({templatePath:N.join(i,"trigger.js"),replacements:{endpointSlug:n},outputPath:d})).success)throw new Error("Failed to create trigger file");c.success(`\u2714 Created Trigger client at ${d}`);let m=N.join(s,"jobs",`example.server${p}`);if(!(await _({templatePath:N.join(i,"exampleJob.js"),replacements:{jobsPathPrefix:o?o+"/":"../"},outputPath:m})).success)throw new Error("Failed to create example job file");c.success(`\u2714 Created example job at ${m}`)}async postInstall(e,r){}defaultHostnames=["localhost"];defaultPorts=[3e3,8788,3333];watchFilePaths=I;watchIgnoreRegex=/(node_modules|build)/};var vt=[new ye,new we,new ge,new fe,new he],ke=a(async(t,e)=>{for(let r of vt)if(await r.isMatch(t,e))return r},"getFramework");function Pt(){return vt.map(t=>t.name).join(", ")}a(Pt,"frameworkNames");import{run as rn}from"npm-check-updates";import M from"fs/promises";import O from"path";var ve=class{static{a(this,"JsRuntime")}logger;projectRootPath;constructor(e,r){this.logger=r,this.projectRootPath=e}};async function Y(t,e){if(await xt.isNodeJsRuntime(t))return new xt(t,e);if(await bt.isDenoJsRuntime(t))return new bt(t,e);throw new Error("