Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ This monorepo contains the code that powers the generated JavaScript & TypeScrip
- [`@gadgetinc/react`](https://github.com/gadget-inc/js-clients/tree/main/packages/react) contains bindings for React applications which want to use their gadget backend in React components
- [`@gadgetinc/react-shopify-app-bridge`](https://github.com/gadget-inc/js-clients/tree/main/packages/react-shopify-app-bridge) contains React components for building Shopify Applications using Shopify's App Bridge and Gadget's Shopify Connection. Read more in the [Gadget docs](https://docs.gadget.dev/guides/connections/shopify).
- [`@gadgetinc/shopify-extensions`](https://github.com/gadget-inc/js-clients/tree/main/packages/shopify-extensions) contains utilities for working with [Shopify UI extensions](https://github.com/Shopify/ui-extensions) in both React and javascript.
- [`@gadgetinc/react-chatgpt-apps`](https://github.com/gadget-inc/js-clients/tree/main/packages/react-chatgpt-apps) contains utilities building [ChatGPT Apps SDK](https://developers.openai.com/apps-sdk/) widgets in React.
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ module.exports = {
"<rootDir>/packages/tiny-graphql-query-compiler/jest.config.js",
"<rootDir>/packages/shopify-extensions/jest.config.js",
"<rootDir>/packages/react-bigcommerce/jest.config.js",
"<rootDir>/packages/react-chatgpt-apps/jest.config.js",
],
};
1 change: 1 addition & 0 deletions packages/react-chatgpt-apps/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @gadgetinc/react-chatgpt-apps
193 changes: 193 additions & 0 deletions packages/react-chatgpt-apps/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<div align="center">
<p>
<img alt="Gadget logo" src="https://raw.githubusercontent.com/gadget-inc/js-clients/main/docs/assets/gadget-logo.png" />
</p>
<p>
<a href="">
<img alt="GitHub CI status" src="https://badgen.net/github/checks/gadget-inc/js-clients/main/test?label=CI" />
</a>
<a href="https://www.npmjs.com/package/@gadgetinc/react-chatgpt-apps">
<img alt="npm version" src="https://badgen.net/npm/v/@gadgetinc/react-chatgpt-apps?color=4148f2" />
</a>
</p>
<p>
<strong>
React components for building ChatGPT Apps powered by <a href="https://gadget.dev">Gadget</a> backends.
</strong>
</p>
</div>

`@gadgetinc/react-chatgpt-apps` is a React library for connecting ChatGPT Apps to Gadget backend applications. It provides:

1. A `<Provider>` component that automatically authenticates your ChatGPT App with your Gadget backend
2. Easy integration with `@gadgetinc/react` hooks for reading and writing data
3. Automatic token management using OpenAI's authentication system

When building a ChatGPT App that needs to interact with a Gadget backend, this library handles all the authentication complexity for you, allowing your React components to focus on building great user experiences.

## Installation

`@gadgetinc/react-chatgpt-apps` is a companion package to your Gadget app's JavaScript client and `@gadgetinc/react`, so you need to install all three packages.

First, set up the Gadget NPM registry and install your app's client:

```bash
npm config set @gadget-client:registry https://registry.gadget.dev/npm

# then install your app's client
npm install @gadget-client/your-chatgpt-app-slug
```

Full installation instructions for your app's client can be found in the Gadget docs at `https://docs.gadget.dev/api/<your-app-slug>/external-api-calls/installing`.

Then, install the React libraries:

```bash
npm install @gadgetinc/react @gadgetinc/react-chatgpt-apps react
# or
yarn add @gadgetinc/react @gadgetinc/react-chatgpt-apps react
```

## Setup

To use this library, wrap your ChatGPT App's React components in the `Provider` component from this package. The `Provider` automatically handles authentication with your Gadget backend using OpenAI's authentication system.

```tsx
import { Client } from "@gadget-client/your-chatgpt-app-slug";
import { Provider } from "@gadgetinc/react-chatgpt-apps";

// instantiate the API client for your Gadget app
const api = new Client();

export function App() {
return (
<Provider api={api}>
<YourChatGPTAppComponents />
</Provider>
);
}
```

That's it! The `Provider` component will:

1. Automatically fetch an authentication token from OpenAI when your app loads
2. Configure your Gadget API client to use this token for all requests
3. Ensure all API calls wait for authentication to be ready before proceeding

## Example usage

Once you've wrapped your app in the `Provider`, you can use all the hooks from `@gadgetinc/react` to interact with your Gadget backend:

```tsx
import { Client } from "@gadget-client/my-chatgpt-app";
import { useAction, useFindMany } from "@gadgetinc/react";
import { Provider } from "@gadgetinc/react-chatgpt-apps";

const api = new Client();

export function App() {
return (
<Provider api={api}>
<TaskList />
</Provider>
);
}

function TaskList() {
// Fetch tasks from your Gadget backend - authentication is handled automatically
const [{ data: tasks, fetching, error }] = useFindMany(api.task, {
select: {
id: true,
title: true,
completed: true,
},
});

// Set up an action to mark tasks as complete
const [_, completeTask] = useAction(api.task.complete);

if (fetching) return <div>Loading tasks...</div>;
if (error) return <div>Error: {error.message}</div>;

return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
<input type="checkbox" checked={task.completed} onChange={() => completeTask({ id: task.id })} />
{task.title}
</li>
))}
</ul>
);
}
```

## How it works

ChatGPT Apps use a special authentication mechanism provided by OpenAI. When your app loads in ChatGPT, it can request an authentication token from OpenAI that identifies the current user and conversation. This library:

1. Calls OpenAI's `callTool` function with the special `__getGadgetAuthTokenV1` tool to retrieve an authentication token
2. Configures your Gadget API client to include this token in all HTTP requests as a `Bearer` token
3. Ensures that any API calls made before the token is fetched will wait for authentication to be ready

This all happens automatically when you wrap your app in the `Provider` component. Your Gadget backend will receive the authenticated requests and can use the token to identify the user and enforce permissions.

## API Documentation

### `<Provider api={api}>`

The `Provider` component must wrap your ChatGPT App to enable authenticated communication with your Gadget backend.

**Props:**

- `api` (required): An instance of your Gadget application's API client. Example: `new Client()` where `Client` is imported from `@gadget-client/your-app-slug`.
- `children` (required): Your React components that will use the Gadget API.

**Example:**

```tsx
import { Client } from "@gadget-client/my-chatgpt-app";
import { Provider } from "@gadgetinc/react-chatgpt-apps";

const api = new Client();

export function App() {
return (
<Provider api={api}>
<YourComponents />
</Provider>
);
}
```

The `Provider` component:

- Automatically fetches an authentication token from OpenAI when mounted
- Configures your API client to use this token for all requests
- Handles token management transparently - you don't need to manually pass tokens around
- Ensures all API calls wait for authentication to be ready

### Using with `@gadgetinc/react` hooks

Once your app is wrapped in the `Provider`, you can use all the hooks from `@gadgetinc/react` to interact with your Gadget backend. All requests will automatically include the authentication token.

See the [`@gadgetinc/react` documentation](https://github.com/gadget-inc/js-clients/blob/main/packages/react/README.md) for the full list of available hooks including:

- `useFindOne` - Fetch a single record by ID
- `useFindMany` - Fetch a list of records with filtering, sorting, and pagination
- `useAction` - Run actions on your Gadget models
- `useGlobalAction` - Run global actions
- `useFetch` - Make custom HTTP requests to your Gadget backend

All of these hooks will work seamlessly with the ChatGPT Apps authentication provided by this package.

## Authentication Flow

When your ChatGPT App loads, the following happens automatically:

1. The `Provider` component calls OpenAI's `callTool` function with the `__getGadgetAuthTokenV1` tool name
2. OpenAI returns an authentication token specific to the current user and conversation
3. The `Provider` configures your Gadget API client to include this token as a `Bearer` token in the `Authorization` header of all HTTP requests
4. Your Gadget backend receives the token and can use it to identify the user and enforce permissions

If the token fetch fails (for example, if the app is not running in a ChatGPT environment), an error will be thrown. This ensures your app doesn't make unauthenticated requests by mistake.
186 changes: 186 additions & 0 deletions packages/react-chatgpt-apps/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

export default {
displayName: "react-chatgpt-apps",
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// The directory where Jest should store its cached dependency information
// cacheDirectory: process.env.LAYERCI ? "/tmp/jest-cache" : undefined,

// Automatically clear mock calls and instances between every test
clearMocks: true,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
// coverageDirectory: undefined,

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

extensionsToTreatAsEsm: [".ts", ".tsx"],

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: "<rootDir>/../api/spec/jest.globalsetup.ts",

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
// preset: "ts-jest",

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state between every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state between every test
restoreMocks: true,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
roots: ["<rootDir>"],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: ["./spec/setup.ts"],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: ["<rootDir>/spec/jest.setup.ts"],

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
testEnvironment: "setup-polly-jest/jest-environment-jsdom",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [path.join(__dirname, "spec/(*.)+(spec|test).[tj]s?(x)")],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: ["/node_modules/"],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: "jasmine2",
testRunner: "jest-circus/runner",

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",

// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",

// A map from regular expressions to paths to transformers
// transform: undefined,
transform: { "^.+\\.(t|j)sx?$": ["@swc/jest"] },

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/"
// ],
// transformIgnorePatterns: ["/node_modules/(?!lodash)"],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: undefined,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};
Loading