Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
780cae5
Initial setup
SarahSoutoul Sep 30, 2025
128df3c
Merge branch 'main' into ss/DOCS-10983
SarahSoutoul Sep 30, 2025
a584905
Test
SarahSoutoul Oct 1, 2025
8d2e9e2
Refactor typedoc
SarahSoutoul Oct 1, 2025
70c5908
Bring back removed info
SarahSoutoul Oct 1, 2025
d49447e
Add missing code templating
SarahSoutoul Oct 1, 2025
7b9b11b
Merge branch 'main' into ss/DOCS-10983
SarahSoutoul Oct 1, 2025
b653539
Merge branch 'main' into ss/DOCS-10983
SarahSoutoul Oct 2, 2025
3f1f920
Remove jsdocs changes to have in separate PR
SarahSoutoul Oct 2, 2025
3cc87f9
Bring back session list
SarahSoutoul Oct 2, 2025
64da460
Merge branch 'main' into ss/DOCS-10983
SarahSoutoul Oct 2, 2025
16f9663
Fix setActive returns
SarahSoutoul Oct 2, 2025
febc294
Fix returns for useAuth
SarahSoutoul Oct 2, 2025
c32a435
Update the custom theme to get the useAuth options markdown generated…
NWylynko Oct 3, 2025
263dba2
replace @unionInline with @embedType that covers more type inlining
NWylynko Oct 7, 2025
316c861
Fix SetActive return after Nick fix
SarahSoutoul Oct 7, 2025
40dbc8b
Add new extract returns and params script
NWylynko Oct 8, 2025
bc7873c
Add new extract returns and params script
NWylynko Oct 8, 2025
2ebb4f2
Remove unwanted changes
SarahSoutoul Oct 8, 2025
906c42c
Billing hooks jsdoc work
SarahSoutoul Oct 9, 2025
113bb22
Refine useCheckout
SarahSoutoul Oct 10, 2025
d58bcbd
Add billing hooks params to files without headings
SarahSoutoul Oct 10, 2025
3bde171
Fix some issues billing hooks
SarahSoutoul Oct 10, 2025
ecd1435
Additional fixes and clean up
SarahSoutoul Oct 10, 2025
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
23 changes: 23 additions & 0 deletions .typedoc/custom-plugin.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ const FILES_WITHOUT_HEADINGS = [
'verify-token-options.mdx',
'public-organization-data-json.mdx',
'organization-membership-public-user-data.mdx',
'use-checkout-return.mdx',
'use-checkout-options.mdx',
'use-payment-element-return.mdx',
'use-payment-element-return.mdx',
'use-payment-methods-return.mdx',
'use-payment-attempts-return.mdx',
'use-plans-return.mdx',
'use-statements-return.mdx',
'hook-params.mdx',
'use-subscription-params.mdx',
'use-subscription-return.mdx',
'needs-reverification-parameters.mdx',
'use-reverification-options.mdx',
'use-reverification-params,mdx',
];

/**
Expand All @@ -29,6 +43,10 @@ const LINK_REPLACEMENTS = [
['set-active-params', '/docs/reference/javascript/types/set-active-params'],
['clerk-paginated-response', '/docs/reference/javascript/types/clerk-paginated-response'],
['paginated-resources', '#paginated-resources'],
['use-checkout-options', '#use-checkout-options'],
['use-reverification-options', '#use-reverification-options'],
['needs-reverification-parameters', '#needs-reverification-parameters'],
['create-organization-params', '#create-organization-params'],
['session-resource', '/docs/reference/javascript/session'],
['signed-in-session-resource', '/docs/reference/javascript/session'],
['sign-in-resource', '/docs/reference/javascript/sign-in'],
Expand Down Expand Up @@ -57,14 +75,19 @@ const LINK_REPLACEMENTS = [
['verify-token-options', '#verify-token-options'],
['localization-resource', '/docs/guides/customizing-clerk/localization'],
['confirm-checkout-params', '/docs/reference/javascript/types/billing-checkout-resource#parameters'],
['billing-payment-resource', '/docs/reference/javascript/types/billing-payment-resource'],
['billing-payment-source-resource', '/docs/reference/javascript/types/billing-payment-source-resource'],
['billing-payer-resource', '/docs/reference/javascript/types/billing-payer-resource'],
['billing-plan-resource', '/docs/reference/javascript/types/billing-plan-resource'],
['billing-checkout-totals', '/docs/reference/javascript/types/billing-checkout-totals'],
['billing-checkout-resource', '/docs/reference/javascript/types/billing-checkout-resource'],
['billing-money-amount', '/docs/reference/javascript/types/billing-money-amount'],
['billing-subscription-item-resource', '/docs/reference/javascript/types/billing-subscription-item-resource'],
['feature-resource', '/docs/reference/javascript/types/feature-resource'],
['billing-statement-group', '/docs/reference/javascript/types/billing-statement-group'],
['billing-statement-resource', '/docs/reference/javascript/types/billing-statement-resource'],
['billing-subscription-resource', '/docs/reference/javascript/types/billing-subscription-resource'],
['clerk-api-response-error', '/docs/reference/javascript/types/clerk-api-response-error'],
];

/**
Expand Down
1 change: 1 addition & 0 deletions .typedoc/custom-theme.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ class ClerkMarkdownThemeContext extends MarkdownThemeContext {
},
/**
* This hides the "Type parameters" section, the declaration title, and the "Type declaration" heading from the output
* Unless the @includeType tag is present, in which case it shows the type in a parameter table format
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment can go right? @NWylynko

* @param {import('typedoc').DeclarationReflection} model
* @param {{ headingLevel: number, nested?: boolean }} options
*/
Expand Down
164 changes: 164 additions & 0 deletions .typedoc/extract-returns-and-params.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// @ts-check
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
* Extracts the "## Returns" section from a markdown file and writes it to a separate file.
* @param {string} filePath - The path to the markdown file
* @returns {boolean} True if a file was created
*/
function extractReturnsSection(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');

// Find the "## Returns" section
const returnsStart = content.indexOf('## Returns');

if (returnsStart === -1) {
return false; // No Returns section found
}

// Find the next heading after "## Returns" (or end of file)
const afterReturns = content.slice(returnsStart + 10); // Skip past "## Returns"
const nextHeadingMatch = afterReturns.match(/\n## /);
const returnsEnd =
nextHeadingMatch && typeof nextHeadingMatch.index === 'number'
? returnsStart + 10 + nextHeadingMatch.index
: content.length;

// Extract the Returns section and trim trailing whitespace
const returnsContent = content.slice(returnsStart, returnsEnd).trimEnd();

// Generate the new filename: use-auth.mdx -> use-auth-return.mdx
const fileName = path.basename(filePath, '.mdx');
const dirName = path.dirname(filePath);
const newFilePath = path.join(dirName, `${fileName}-return.mdx`);

// Write the extracted Returns section to the new file
fs.writeFileSync(newFilePath, returnsContent, 'utf-8');

console.log(`[extract-returns] Created ${path.relative(process.cwd(), newFilePath)}`);
return true;
}

/**
* Extracts the "## Parameters" section from a markdown file and writes it to a separate file.
* @param {string} filePath - The path to the markdown file
* @param {string} dirName - The directory containing the files
* @returns {boolean} True if a file was created
*/
function extractParametersSection(filePath, dirName) {
const content = fs.readFileSync(filePath, 'utf-8');
const fileName = path.basename(filePath, '.mdx');

// Always use -params suffix
const suffix = '-params';
const targetFileName = `${fileName}${suffix}.mdx`;
const propsFileName = `${fileName}-props.mdx`;

// Delete any existing -props file (TypeDoc-generated)
const propsFilePath = path.join(dirName, propsFileName);
if (fs.existsSync(propsFilePath)) {
fs.unlinkSync(propsFilePath);
console.log(`[extract-returns] Deleted ${path.relative(process.cwd(), propsFilePath)}`);
}

// Find the "## Parameters" section
const paramsStart = content.indexOf('## Parameters');

if (paramsStart === -1) {
return false; // No Parameters section found
}

// Find the next heading after "## Parameters" (or end of file)
const afterParams = content.slice(paramsStart + 13); // Skip past "## Parameters"
const nextHeadingMatch = afterParams.match(/\n## /);
const paramsEnd =
nextHeadingMatch && typeof nextHeadingMatch.index === 'number'
? paramsStart + 13 + nextHeadingMatch.index
: content.length;

// Extract the Parameters section and trim trailing whitespace
const paramsContent = content.slice(paramsStart, paramsEnd).trimEnd();

// Write to new file
const newFilePath = path.join(dirName, targetFileName);
fs.writeFileSync(newFilePath, paramsContent, 'utf-8');

console.log(`[extract-returns] Created ${path.relative(process.cwd(), newFilePath)}`);
return true;
}

/**
* Recursively reads all .mdx files in a directory, excluding generated files
* @param {string} dir - The directory to read
* @returns {string[]} Array of file paths
*/
function getAllMdxFiles(dir) {
/** @type {string[]} */
const files = [];

if (!fs.existsSync(dir)) {
return files;
}

const entries = fs.readdirSync(dir, { withFileTypes: true });

for (const entry of entries) {
const fullPath = path.join(dir, entry.name);

if (entry.isDirectory()) {
files.push(...getAllMdxFiles(fullPath));
} else if (entry.isFile() && entry.name.endsWith('.mdx')) {
// Exclude generated files
const isGenerated =
entry.name.endsWith('-return.mdx') || entry.name.endsWith('-params.mdx') || entry.name.endsWith('-props.mdx');
if (!isGenerated) {
files.push(fullPath);
}
}
}

return files;
}

/**
* Main function to process all clerk-react files
*/
function main() {
const packages = ['clerk-react'];
const dirs = packages.map(folder => path.join(__dirname, 'temp-docs', folder));

for (const dir of dirs) {
if (!fs.existsSync(dir)) {
console.log(`[extract-returns] ${dir} directory not found, skipping extraction`);
continue;
}

const mdxFiles = getAllMdxFiles(dir);
console.log(`[extract-returns] Processing ${mdxFiles.length} files in ${dir}/`);

let returnsCount = 0;
let paramsCount = 0;

for (const filePath of mdxFiles) {
// Extract Returns sections
if (extractReturnsSection(filePath)) {
returnsCount++;
}

// Extract Parameters sections
if (extractParametersSection(filePath, dir)) {
paramsCount++;
}
}

console.log(`[extract-returns] Extracted ${returnsCount} Returns sections`);
console.log(`[extract-returns] Extracted ${paramsCount} Parameters sections`);
}
}

main();
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"test:typedoc": "pnpm typedoc:generate && cd ./.typedoc && vitest run",
"turbo:clean": "turbo daemon clean",
"typedoc:generate": "pnpm build:declarations && pnpm typedoc:generate:skip-build",
"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && rm -rf .typedoc/docs && mv .typedoc/temp-docs .typedoc/docs",
"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && node .typedoc/extract-returns-and-params.mjs && rm -rf .typedoc/docs && mv .typedoc/temp-docs .typedoc/docs",
"version-packages": "changeset version && pnpm install --lockfile-only --engine-strict=false",
"version-packages:canary": "./scripts/canary.mjs",
"version-packages:snapshot": "./scripts/snapshot.mjs",
Expand Down
2 changes: 1 addition & 1 deletion packages/react/typedoc.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"$schema": "https://typedoc.org/schema.json",
"entryPoints": ["./src/index.ts", "./src/experimental.ts"]
"entryPoints": ["./src/index.ts", "./src/experimental.ts", "./src/hooks/*.{ts,tsx}"]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we still need this? @NWylynko

}
3 changes: 3 additions & 0 deletions packages/shared/src/errors/apiResponseError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ interface ClerkAPIResponseOptions {
retryAfter?: number;
}

/**
* Interface representing a Clerk API Response Error.
*/
export class ClerkAPIResponseError extends Error implements ClerkAPIResponseErrorInterface {
clerkError: true;

Expand Down
51 changes: 45 additions & 6 deletions packages/shared/src/react/commerce.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import useSWR from 'swr';
import useSWRMutation from 'swr/mutation';

import { createContextAndHook } from './hooks/createContextAndHook';
import type { useCheckout } from './hooks/useCheckout';
import { useClerk } from './hooks/useClerk';
import { useOrganization } from './hooks/useOrganization';
import { useUser } from './hooks/useUser';
Expand Down Expand Up @@ -139,15 +138,27 @@ type internalStripeAppearance = {
spacingUnit: string;
};

type PaymentElementProviderProps = {
checkout?: BillingCheckoutResource | ReturnType<typeof useCheckout>['checkout'];
/**
* @interface
*/
export type PaymentElementProviderProps = {
/**
* An optional checkout resource object. When provided, the payment element is scoped to the specific checkout session.
*/
checkout?: BillingCheckoutResource;
/**
* An optional object to customize the appearance of the Stripe Payment Element. This allows you to match the form's styling to your application's theme.
*/
stripeAppearance?: internalStripeAppearance;
/**
* Default to `user` if not provided.
* Specifies whether to fetch for the current user or organization.
*
* @default 'user'
*/
for?: ForPayerType;
/**
* An optional description to display to the user within the payment element UI.
*/
paymentDescription?: string;
};

Expand Down Expand Up @@ -229,7 +240,17 @@ const PaymentElementInternalRoot = (props: PropsWithChildren) => {
return <DummyStripeUtils>{props.children}</DummyStripeUtils>;
};

const PaymentElement = ({ fallback }: { fallback?: ReactNode }) => {
/**
* @interface
*/
export type PaymentElementProps = {
/**
* Optional fallback content, such as a loading skeleton, to display while the payment form is being initialized.
*/
fallback?: ReactNode;
};

const PaymentElement = ({ fallback }: PaymentElementProps) => {
const {
setIsPaymentElementReady,
paymentMethodOrder,
Expand Down Expand Up @@ -296,7 +317,13 @@ const throwLibsMissingError = () => {
);
};

type UsePaymentElementReturn = {
/**
* @interface
*/
export type UsePaymentElementReturn = {
/**
* A function that submits the payment form data to the payment provider. It returns a promise that resolves with either a `data` object containing a payment token on success, or an `error` object on failure.
*/
submit: () => Promise<
| {
data: { gateway: 'stripe'; paymentToken: string };
Expand All @@ -307,13 +334,25 @@ type UsePaymentElementReturn = {
error: PaymentElementError;
}
>;
/**
* A function that resets the payment form to its initial, empty state.
*/
reset: () => Promise<void>;
/**
* A boolean that indicates if the payment form UI has been rendered and is ready for user input. This is useful for disabling a submit button until the form is interactive.
*/
isFormReady: boolean;
} & (
| {
/**
* An object containing information about the initialized payment provider. It is `undefined` until `isProviderReady` is `true`.
*/
provider: {
name: 'stripe';
};
/**
* A boolean that indicates if the underlying payment provider (e.g. Stripe) has been fully initialized.
*/
isProviderReady: true;
}
| {
Expand Down
16 changes: 15 additions & 1 deletion packages/shared/src/react/contexts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,23 @@ const [SessionContext, useSessionContext] = createContextAndHook<SignedInSession

const OptionsContext = React.createContext<ClerkOptions>({});

type UseCheckoutOptions = {
/**
* @interface
*/
export type UseCheckoutOptions = {
/**
* Specifies if the checkout is for an organization.
*
* @default 'user'
*/
for?: ForPayerType;
/**
* The billing period for the plan.
*/
planPeriod: BillingSubscriptionPlanPeriod;
/**
* The ID of the subscription plan to check out (e.g. `cplan_xxx`).
*/
planId: string;
};

Expand Down
Loading