Skip to content
Draft
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 .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
* @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}"]
}
12 changes: 10 additions & 2 deletions packages/shared/src/react/hooks/useReverification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import { useSafeLayoutEffect } from './useSafeLayoutEffect';

const CLERK_API_REVERIFICATION_ERROR_CODE = 'session_reverification_required';

/**
*
*/
async function resolveResult<T>(result: Promise<T> | T): Promise<T | ReturnType<typeof reverificationError>> {
try {
const r = await result;
Expand Down Expand Up @@ -42,6 +45,7 @@ type NeedsReverificationParameters = {

/**
* The optional options object.
*
* @interface
*/
type UseReverificationOptions = {
Expand All @@ -51,7 +55,6 @@ type UseReverificationOptions = {
* @param cancel - A function that will cancel the reverification process.
* @param complete - A function that will retry the original request after reverification.
* @param level - The level returned with the reverification hint.
*
*/
onNeedsReverification?: (properties: NeedsReverificationParameters) => void;
};
Expand Down Expand Up @@ -79,7 +82,13 @@ type CreateReverificationHandlerParams = UseReverificationOptions & {
telemetry: Clerk['telemetry'];
};

/**
*
*/
function createReverificationHandler(params: CreateReverificationHandlerParams) {
/**
*
*/
function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(
fetcher: Fetcher,
): (...args: Parameters<Fetcher>) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>> {
Expand Down Expand Up @@ -191,7 +200,6 @@ function createReverificationHandler(params: CreateReverificationHandlerParams)
* return <button onClick={handleClick}>Update User</button>
* }
* ```
*
*/
export const useReverification: UseReverification = (fetcher, options) => {
const { __internal_openReverification, telemetry } = useClerk();
Expand Down
1 change: 0 additions & 1 deletion packages/shared/src/react/hooks/useSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const hookName = `useSession`;
* @function
*
* @param [options] - An object containing options for the `useSession()` hook.
*
* @example
* ### Access the `Session` object
*
Expand Down
55 changes: 52 additions & 3 deletions packages/shared/src/react/hooks/useSubscription.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { EnvironmentResource, ForPayerType } from '@clerk/types';
import type { BillingSubscriptionResource, EnvironmentResource, ForPayerType } from '@clerk/types';
import { useCallback } from 'react';

import { eventMethodCalled } from '../../telemetry/events';
Expand All @@ -12,16 +12,65 @@ import {

const hookName = 'useSubscription';

type UseSubscriptionParams = {
/**
* @interface
*/
export type UseSubscriptionParams = {
/**
* Specifies whether to fetch subscription for an organization or user.
*
* @default 'user'
*/
for?: ForPayerType;
/**
* If `true`, the previous data will be kept in the cache until new data is fetched.
* If `true`, the previous data will be kept in the cache until new data is fetched. This helps prevent layout shifts.
*
* @default false
*/
keepPreviousData?: boolean;
};

/**
* @interface
*/
export type UseSubscriptionReturn =
| {
/**
* A boolean that indicates whether the initial data is still being fetched.
*/
data: null;
/**
* A boolean that indicates whether the initial data is still being fetched.
*/
isLoaded: false;
/**
* A boolean that indicates whether any request is still in flight, including background updates.
*/
isFetching: false;
/**
* Any error that occurred during the data fetch, or `null` if no error occurred.
*/
error: null;
/**
* Function to manually trigger a refresh of the subscription data.
*/
revalidate: () => Promise<void>;
}
| {
data: BillingSubscriptionResource;
isLoaded: true;
isFetching: true;
error: Error;
revalidate: () => Promise<void>;
}
| {
data: BillingSubscriptionResource | null;
isLoaded: boolean;
isFetching: boolean;
error: Error | null;
revalidate: () => Promise<void>;
};

/**
* @internal
*
Expand Down
18 changes: 11 additions & 7 deletions packages/types/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { SetActive, SignOut } from './clerk';
import type { ActClaim, JwtPayload } from './jwtv2';
import type { OrganizationCustomRoleKey } from './organizationMembership';
import { OrganizationCustomRoleKey } from './organizationMembership';
import type {
CheckAuthorizationWithCustomPermissions,
GetToken,
Expand All @@ -10,7 +10,6 @@ import type {
import type { SignInResource } from './signIn';
import type { SignUpResource } from './signUp';
import type { UserResource } from './user';

/**
* @inline
*/
Expand Down Expand Up @@ -118,7 +117,8 @@ export type UseAuthReturn =
};

/**
* @inline
* @unionReturnHeadings
* ["Initialization", "Loaded"]
*/
export type UseSignInReturn =
| {
Expand All @@ -142,7 +142,8 @@ export type UseSignInReturn =
};

/**
* @inline
* @unionReturnHeadings
* ["Initialization", "Loaded"]
*/
export type UseSignUpReturn =
| {
Expand All @@ -166,7 +167,8 @@ export type UseSignUpReturn =
};

/**
* @inline
* @unionReturnHeadings
* ["Initialization", "Signed out", "Signed in"]
*/
export type UseSessionReturn =
| {
Expand Down Expand Up @@ -195,7 +197,8 @@ export type UseSessionReturn =
};

/**
* @inline
* @unionReturnHeadings
* ["Initialization", "Loaded"]
*/
export type UseSessionListReturn =
| {
Expand All @@ -219,7 +222,8 @@ export type UseSessionListReturn =
};

/**
* @inline
* @unionReturnHeadings
* ["Initialization", "Signed out", "Signed in"]
*/
export type UseUserReturn =
| {
Expand Down
Loading