vite-plugin-triggerkit Svelte Themes

Vite Plugin Triggerkit

A Vite plugin that enables seamless integration between SvelteKit and Trigger.dev

vite-plugin-triggerkit

A Vite plugin that enables seamless integration between SvelteKit and Trigger.dev by allowing you to use your SvelteKit functions directly in your Trigger.dev projects.

Features

  • šŸ”„ Use SvelteKit functions directly in Trigger.dev jobs
  • šŸ“¦ Automatic function discovery and export
  • šŸ” TypeScript support with type preservation
  • šŸ“ Preserves JSDoc documentation
  • šŸ”„ Hot Module Reloading support
  • šŸŽÆ Configurable directory scanning

Installation

npm install -D vite-plugin-triggerkit

Quick Start

  1. Add the plugin to your vite.config.ts:
import { sveltekit } from '@sveltejs/kit/vite';
import { triggerkit } from 'vite-plugin-triggerkit';

export default defineConfig({
  plugins: [
    sveltekit(),
    triggerkit({
      includeDirs: ['src/lib', 'src/routes/api']
    })
  ]
});
  1. Write your functions in SvelteKit:
// src/lib/email.ts
/**
 * Sends a welcome email to a new user
 */
export async function sendWelcomeEmail(userId: string) {
  // Your email sending logic
  return { message: `Hello, ${userId ?? "world"}`, };
}
  1. Use them in your Trigger.dev project:
import { sendWelcomeEmail } from "$lib";
import { logger, task, wait } from "@trigger.dev/sdk/v3";

export const helloWorldTask = task({
  id: "hello-world",
  // Set an optional maxDuration to prevent tasks from running indefinitely
  maxDuration: 300, // Stop executing after 300 secs (5 mins) of compute
  run: async (payload: any, { ctx }) => {
    logger.log("Hello, world!", { payload, ctx });

    const response = await sendWelcomeEmail(payload.userId);
    await wait.for({ seconds: 5 });

    return {
      message: response.message,
    }
  },
});

Configuration

The plugin accepts the following options:

interface PluginOptions {
  // Directories to scan for exportable functions
  includeDirs?: string[];  // default: ['src/lib', 'src/routes/api']
  
  // File patterns to scan
  include?: string[];      // default: ['**/*.ts', '**/*.js', '**/+server.ts']
  
  // Patterns to exclude
  exclude?: string[];      // default: ['**/node_modules/**', '**/*.test.ts', '**/*.spec.ts']
  
  // Virtual module ID for accessing functions
  virtualModuleId?: string; // default: 'virtual:sveltekit-functions'
}

Function Metadata

You can access metadata about your functions using the exported functions object:

import { functions } from 'virtual:sveltekit-functions';

console.log(functions.sendWelcomeEmail.metadata);
// Output:
// {
//   isAsync: true,
//   parameters: [
//     { name: 'userId', type: 'string', optional: false }
//   ],
//   returnType: 'Promise<{ success: boolean }>',
//   docstring: 'Sends a welcome email to a new user'
// }

Best Practices

  1. Function Organization: Keep trigger-related functions in dedicated directories for better organization:

    src/lib/triggers/
    ā”œā”€ā”€ email.ts
    ā”œā”€ā”€ notifications.ts
    ā””ā”€ā”€ users.ts
    
  2. Type Safety: Always define types for function parameters and return values:

    export async function createUser(data: UserData): Promise<User> {
      // Implementation
    }
    
  3. Documentation: Add JSDoc comments to your functions for better developer experience:

    /**
     * Creates a new user in the database
     * @param data - User creation data
     * @returns Newly created user
     */
    export async function createUser(data: UserData): Promise<User> {
      // Implementation
    }
    

Examples

Basic Usage

// src/lib/auth.ts
export async function verifyUser(token: string): Promise<boolean> {
  // Verification logic
}

// trigger/auth.ts
import { verifyUser } from 'virtual:sveltekit-functions';

export const userVerificationJob = trigger.job({
  id: "verify-user",
  run: async (payload) => {
    const isValid = await verifyUser(payload.token);
    if (!isValid) {
      throw new Error('Invalid user token');
    }
  }
});

With Function Metadata

import { functions } from 'virtual:sveltekit-functions';

// Get all available functions
const availableFunctions = Object.keys(functions);

// Check function parameters
const params = functions.verifyUser.metadata.parameters;

Contributing

Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Top categories

Loading Svelte Themes