Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(clerk-js,types): Signals fetchStatus by dstaley · Pull Request #6549 · clerk/javascript · GitHub
Skip to content
6 changes: 6 additions & 0 deletions .changeset/twelve-crabs-return.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': minor
'@clerk/types': minor
---

[Experimental] Signal `fetchStatus` support.
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/events.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,11 +10,13 @@ export const events = {
SessionTokenResolved: 'session:tokenResolved',
ResourceUpdate: 'resource:update',
ResourceError: 'resource:error',
ResourceFetch: 'resource:fetch',
} as const;

type TokenUpdatePayload = { token: TokenResource | null };
export type ResourceUpdatePayload = { resource: BaseResource };
export type ResourceErrorPayload = { resource: BaseResource; error: unknown };
export type ResourceFetchPayload = { resource: BaseResource; status: 'idle' | 'fetching' };

type InternalEvents = {
[events.TokenUpdate]: TokenUpdatePayload;
Expand All@@ -23,6 +25,7 @@ type InternalEvents = {
[events.SessionTokenResolved]: null;
[events.ResourceUpdate]: ResourceUpdatePayload;
[events.ResourceError]: ResourceErrorPayload;
[events.ResourceFetch]: ResourceFetchPayload;
};

export const eventBus = createEventBus<InternalEvents>();
100 changes: 23 additions & 77 deletions packages/clerk-js/src/core/resources/SignIn.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@ import type {
ResetPasswordParams,
ResetPasswordPhoneCodeFactorConfig,
SamlConfig,
SetActiveNavigate,
SignInCreateParams,
SignInFirstFactor,
SignInFutureResource,
Expand DownExpand Up@@ -58,6 +59,7 @@ import {
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '../../utils/passkeys';
import { createValidatePassword } from '../../utils/passwords/password';
import { runAsyncResourceTask } from '../../utils/runAsyncResourceTask';
import {
clerkInvalidFAPIResponse,
clerkInvalidStrategy,
Expand DownExpand Up@@ -493,8 +495,6 @@ class SignInFuture implements SignInFutureResource {
submitPassword: this.submitResetPassword.bind(this),
};

fetchStatus: 'idle' | 'fetching' = 'idle';

constructor(readonly resource: SignIn) {}

get status() {
Expand All@@ -506,8 +506,7 @@ class SignInFuture implements SignInFutureResource {
}

async sendResetPasswordEmailCode(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
throw new Error('Cannot reset password without a sign in.');
}
Expand All@@ -525,27 +524,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'reset_password_email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyResetPasswordEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'reset_password_email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async submitResetPassword({
Expand All@@ -555,18 +543,12 @@ class SignInFuture implements SignInFutureResource {
password: string;
signOutOfOtherSessions?: boolean;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { password, signOutOfOtherSessions },
action: 'reset_password',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async create(params: {
Expand All@@ -575,39 +557,26 @@ class SignInFuture implements SignInFutureResource {
redirectUrl?: string;
actionCompleteRedirectUrl?: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: params,
});

return { error: null };
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}
});
}

async password({ identifier, password }: { identifier?: string; password: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
const previousIdentifier = this.resource.identifier;
try {
return runAsyncResourceTask(this.resource, async () => {
const previousIdentifier = this.resource.identifier;
await this.resource.__internal_basePost({
path: this.resource.pathRoot,
body: { identifier: identifier || previousIdentifier, password },
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
Comment on lines -570 to -575

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid sending identifier: null; include the field only when defined

Using identifier || previousIdentifier can yield null, which will serialize as identifier: null. Prefer nullish coalescing and omit the key when undefined.

- const previousIdentifier = this.resource.identifier;- await this.resource.__internal_basePost({- path: this.resource.pathRoot,- body: { identifier: identifier || previousIdentifier, password },- });+ const previousIdentifier = this.resource.identifier;+ const resolvedIdentifier = identifier ?? previousIdentifier ?? undefined;+ await this.resource.__internal_basePost({+ path: this.resource.pathRoot,+ body: {+ ...(resolvedIdentifier !== undefined ? { identifier: resolvedIdentifier } : {}),+ password,+ },+ });
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constpreviousIdentifier=this.resource.identifier;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {identifier: identifier||previousIdentifier, password },
});
}catch(err: unknown){
eventBus.emit('resource:error',{resource: this.resource,error: err});
return{error: err};
}
return{error: null};
});
constpreviousIdentifier=this.resource.identifier;
constresolvedIdentifier=identifier??previousIdentifier??undefined;
awaitthis.resource.__internal_basePost({
path: this.resource.pathRoot,
body: {
...(resolvedIdentifier!==undefined ? {identifier: resolvedIdentifier} : {}),
password,
},
});
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 569 to 574,
replace the identifier || previousIdentifier pattern (which can produce
identifier: null) with logic that uses nullish coalescing and only adds the
identifier key when defined; for example, compute const id = identifier ??
previousIdentifier and build the request body by always including password but
only adding identifier if id !== undefined (and/or !== null if you want to avoid
null explicitly), then pass that body to __internal_basePost so identifier is
omitted from the serialized payload when not defined.

}

async sendEmailCode({ email }: { email: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.id) {
await this.create({ identifier: email });
}
Expand All@@ -623,27 +592,16 @@ class SignInFuture implements SignInFutureResource {
body: { emailAddressId, strategy: 'email_code' },
action: 'prepare_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async verifyEmailCode({ code }: { code: string }): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
await this.resource.__internal_basePost({
body: { code, strategy: 'email_code' },
action: 'attempt_first_factor',
});
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async sso({
Expand All@@ -657,8 +615,7 @@ class SignInFuture implements SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
return runAsyncResourceTask(this.resource, async () => {
if (flow !== 'auto') {
throw new Error('modal flow is not supported yet');
}
Expand All@@ -678,27 +635,16 @@ class SignInFuture implements SignInFutureResource {
if (status === 'unverified' && externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
}
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
});
}

async finalize(): Promise<{ error: unknown }> {
eventBus.emit('resource:error', { resource: this.resource, error: null });
try {
async finalize({ navigate }: { navigate?: SetActiveNavigate }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
if (!this.resource.createdSessionId) {
throw new Error('Cannot finalize sign-in without a created session.');
}

await SignIn.clerk.setActive({ session: this.resource.createdSessionId });
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
return { error: err };
}

return { error: null };
await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
});
}
}
16 changes: 9 additions & 7 deletions packages/clerk-js/src/core/signals.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,18 @@ import { computed, signal } from 'alien-signals';

import type { SignIn } from './resources/SignIn';

export const signInSignal = signal<{ resource: SignIn | null }>({ resource: null });
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Rename to signInResourceSignal is clear; verify callers and mark as internal

Good separation of responsibilities by renaming to signInResourceSignal. If this is not part of the public API, add an @internal JSDoc to comply with docs guidelines and prevent accidental external usage. Also, please verify there are no lingering imports/usages of the old signInSignal.

Run this to ensure no leftover references exist:

Apply this diff to mark the export as internal:

+/** @internal */
export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Find any remaining references to the old name
rg -n --heading '\bsignInSignal\b' -g '!**/node_modules/**'

Length of output: 365


Update leftover signInSignal references & mark new export as internal

We’ve got three remaining signInSignal references that need to be switched over (and the new export marked @internal):

  • packages/clerk-js/src/core/signals.ts

    +/** @internal */
    export const signInResourceSignal = signal<{ resource: SignIn | null }>({ resource: null });
  • packages/clerk-js/src/core/state.ts (line 13)

    -export const signInSignal = signInComputedSignal;+export const signInResourceSignal = signInComputedSignal;
  • packages/types/src/state.ts (line 32)

    -signInSignal: Signal<SignIn | null>;+signInResourceSignal: Signal<SignIn | null>;
  • packages/react/src/hooks/useClerkSignal.ts (lines 21 & 38)

    -clerk.__internal_state!.signInSignal();+clerk.__internal_state!.signInResourceSignal();-return clerk.__internal_state.signInSignal();+return clerk.__internal_state.signInResourceSignal();

Please make these changes to fully remove the old signInSignal and ensure the new export is marked @internal.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
/** @internal */
exportconstsignInResourceSignal=signal<{resource: SignIn|null}>({resource: null});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts around line 7, mark the new export
signInResourceSignal as internal by adding a JSDoc @internal comment immediately
above its declaration; then update the three remaining references of the old
signInSignal to the new name across the codebase: change usages in
packages/clerk-js/src/core/state.ts (line 13), packages/types/src/state.ts (line
32), and packages/react/src/hooks/useClerkSignal.ts (lines 21 and 38) to import
and use signInResourceSignal instead of signInSignal, ensuring any type
imports/exports are updated accordingly so imports resolve and there are no
leftover references to signInSignal.

export const signInErrorSignal = signal<{ error: unknown }>({ error: null });
export const signInFetchSignal = signal<{ status: 'idle' | 'fetching' }>({ status: 'idle' });

export const signInComputedSignal = computed(() => {
const signIn = signInSignal().resource;
const signIn = signInResourceSignal().resource;
const error = signInErrorSignal().error;
const fetchStatus = signInFetchSignal().status;

const errors = errorsToParsedErrors(error);

if (!signIn) {
return { errors, signIn: null };
}

return { errors, signIn: signIn.__internal_future };
return { errors, fetchStatus, signIn: signIn ? signIn.__internal_future : null };
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
Expand All@@ -42,6 +40,10 @@ function errorsToParsedErrors(error: unknown): Errors {
global: [],
};

if (!error) {
return parsedErrors;
}

if (!isClerkAPIResponseError(error)) {
parsedErrors.raw.push(error);
parsedErrors.global.push(error);
Expand Down
12 changes: 10 additions & 2 deletions packages/clerk-js/src/core/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import { computed, effect } from 'alien-signals';
import { eventBus } from './events';
import type { BaseResource } from './resources/Base';
import { SignIn } from './resources/SignIn';
import { signInComputedSignal, signInErrorSignal, signInSignal } from './signals';
import { signInComputedSignal, signInErrorSignal, signInFetchSignal, signInResourceSignal } from './signals';

export class State implements StateInterface {
signInResourceSignal = signInSignal;
signInResourceSignal = signInResourceSignal;
signInErrorSignal = signInErrorSignal;
signInFetchSignal = signInFetchSignal;
signInSignal = signInComputedSignal;

__internal_effect = effect;
Expand All@@ -17,6 +18,7 @@ export class State implements StateInterface {
constructor() {
eventBus.on('resource:update', this.onResourceUpdated);
eventBus.on('resource:error', this.onResourceError);
eventBus.on('resource:fetch', this.onResourceFetch);
}

private onResourceError = (payload: { resource: BaseResource; error: unknown }) => {
Expand All@@ -30,4 +32,10 @@ export class State implements StateInterface {
this.signInResourceSignal({ resource: payload.resource });
}
};

private onResourceFetch = (payload: { resource: BaseResource; status: 'idle' | 'fetching' }) => {
if (payload.resource instanceof SignIn) {
this.signInFetchSignal({ status: payload.status });
}
};
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import { eventBus } from '../../core/events';
import { runAsyncResourceTask } from '../runAsyncResourceTask';

describe('runAsyncTask', () => {
afterEach(() => {
vi.restoreAllMocks();
});

const resource = {} as any; // runAsyncTask doesn't depend on resource being a BaseResource

it('emits fetching/idle and returns result on success', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const task = vi.fn().mockResolvedValue('ok');

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBe('ok');
expect(error).toBeNull();

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:fetch', {
resource,
status: 'idle',
});
});

it('emits error and returns error on failure', async () => {
const emitSpy = vi.spyOn(eventBus, 'emit');
const thrown = new Error('fail');
const task = vi.fn().mockRejectedValue(thrown);

const { result, error } = await runAsyncResourceTask(resource, task);

expect(task).toHaveBeenCalledTimes(1);
expect(result).toBeUndefined();
expect(error).toBe(thrown);

expect(emitSpy).toHaveBeenNthCalledWith(1, 'resource:error', {
resource,
error: null,
});
expect(emitSpy).toHaveBeenNthCalledWith(2, 'resource:fetch', {
resource,
status: 'fetching',
});
expect(emitSpy).toHaveBeenNthCalledWith(3, 'resource:error', {
resource,
error: thrown,
});
expect(emitSpy).toHaveBeenNthCalledWith(4, 'resource:fetch', {
resource,
status: 'idle',
});
});
});
Loading