@wow-two-beta/fe 0.0.39 → 0.0.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/BffSession.d.ts +3 -3
- package/dist/auth/BffSession.js +3 -3
- package/dist/auth/BffSession.js.map +1 -1
- package/dist/auth/BffSessionSync.d.ts +2 -2
- package/dist/auth/BffSessionSync.js.map +1 -1
- package/dist/auth/BffStrategy.d.ts +7 -7
- package/dist/auth/BffStrategy.js +7 -7
- package/dist/auth/BffStrategy.js.map +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -2
- package/dist/formsEngine/AppForm.d.ts +12 -3
- package/dist/formsEngine/FormOperations.d.ts +18 -0
- package/dist/formsEngine/FormOperations.js +9 -0
- package/dist/formsEngine/FormOperations.js.map +1 -1
- package/dist/formsEngine/adapters/house/HouseFormCore.js +15 -6
- package/dist/formsEngine/adapters/house/HouseFormCore.js.map +1 -1
- package/dist/formsEngine/adapters/tanstack/TanstackFormOverlay.d.ts +4 -0
- package/dist/formsEngine/adapters/tanstack/TanstackFormOverlay.js +10 -1
- package/dist/formsEngine/adapters/tanstack/TanstackFormOverlay.js.map +1 -1
- package/dist/formsEngine/adapters/tanstack/UseAppForm.js +9 -6
- package/dist/formsEngine/adapters/tanstack/UseAppForm.js.map +1 -1
- package/dist/foundation/animation/animatedLayout/AnimatedLayout.d.ts +3 -3
- package/dist/foundation/dom/FocusTarget.d.ts +13 -0
- package/dist/foundation/dom/FocusTarget.js +12 -0
- package/dist/foundation/dom/FocusTarget.js.map +1 -0
- package/dist/foundation/dom/index.d.ts +1 -0
- package/dist/foundation/dom/index.js +3 -0
- package/dist/foundation/dom/index.js.map +1 -1
- package/dist/foundation/primitives/index.d.ts +1 -0
- package/dist/foundation/primitives/index.js +3 -0
- package/dist/foundation/primitives/index.js.map +1 -1
- package/dist/foundation/primitives/swapTransition/SwapTransition.d.ts +76 -0
- package/dist/foundation/primitives/swapTransition/SwapTransition.js +240 -0
- package/dist/foundation/primitives/swapTransition/SwapTransition.js.map +1 -0
- package/dist/foundation/primitives/swapTransition/index.d.ts +1 -0
- package/dist/index.css +11 -0
- package/dist/presentation/actions/refreshButton/RefreshButton.vue.js.map +1 -1
- package/dist/presentation/display/animatedNumberText/AnimatedNumberText.vue.d.ts +1 -1
- package/dist/presentation/display/carousel/Carousel.vue.d.ts +1 -1
- package/dist/presentation/display/countUpText/CountUpText.vue.d.ts +1 -1
- package/dist/presentation/display/scrollRevealGroup/ScrollRevealGroup.vue.d.ts +2 -2
- package/dist/presentation/forms/imageCropEditor/ImageCropEditor.vue.d.ts +1 -1
- package/dist/presentation/forms/imageEditor/ImageEditor.vue.d.ts +1 -1
- package/dist/presentation/forms/phoneInput/PhoneInput.vue.d.ts +4 -0
- package/dist/presentation/forms/phoneInput/PhoneInput.vue.js +19 -6
- package/dist/presentation/forms/phoneInput/PhoneInput.vue.js.map +1 -1
- package/dist/router/adapters/vueRouter/routeAnnouncer/RouteAnnouncer.vue.js +17 -5
- package/dist/router/adapters/vueRouter/routeAnnouncer/RouteAnnouncer.vue.js.map +1 -1
- package/package.json +1 -1
|
@@ -32,15 +32,15 @@ export interface BffSessionSnapshot {
|
|
|
32
32
|
/** The token unsafe requests echo; `null` while signed out. */
|
|
33
33
|
readonly csrfToken: string | null;
|
|
34
34
|
}
|
|
35
|
-
/** Defines one decoded `POST {prefix}/
|
|
36
|
-
export interface
|
|
35
|
+
/** Defines one decoded `POST {prefix}/sign-out` response. */
|
|
36
|
+
export interface BffSignOut {
|
|
37
37
|
/** Where the page navigates to end the identity provider's session. */
|
|
38
38
|
readonly endSessionUrl: string;
|
|
39
39
|
}
|
|
40
40
|
/** Decodes the session response; a payload that breaks the contract is a `protocol` failure. */
|
|
41
41
|
export declare function decodeBffSession(value: unknown): Result<BffSessionSnapshot, ApiFailure>;
|
|
42
42
|
/** Decodes the logout response; an end-session URL the page may not navigate to is a `protocol` failure. */
|
|
43
|
-
export declare function
|
|
43
|
+
export declare function decodeBffSignOut(value: unknown): Result<BffSignOut, ApiFailure>;
|
|
44
44
|
/** Extends a {@link BffUser} with the checks a screen and a bridge need. */
|
|
45
45
|
export declare const BffSessionExtensions: {
|
|
46
46
|
/** Whether the user holds `permission`; `false` while signed out. */
|
package/dist/auth/BffSession.js
CHANGED
|
@@ -42,7 +42,7 @@ function isNavigable(url) {
|
|
|
42
42
|
return false;
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
function
|
|
45
|
+
function decodeBffSignOut(value) {
|
|
46
46
|
if (!isRecord(value) || !isText(value["endSessionUrl"]) || !isNavigable(value["endSessionUrl"])) {
|
|
47
47
|
return ResultExtensions.fail(protocol());
|
|
48
48
|
}
|
|
@@ -67,7 +67,7 @@ const BffSessionExtensions = {
|
|
|
67
67
|
};
|
|
68
68
|
export {
|
|
69
69
|
BffSessionExtensions,
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
decodeBffSession,
|
|
71
|
+
decodeBffSignOut
|
|
72
72
|
};
|
|
73
73
|
//# sourceMappingURL=BffSession.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BffSession.js","sources":["../../src/auth/BffSession.ts"],"sourcesContent":["import { ApiFailureFactory, type ApiFailure } from '../foundation/http';\nimport { ResultExtensions, type Result } from '../foundation/results';\n\n/** Defines the signed-in person a BFF session names. */\nexport interface BffPerson {\n /** The stable subject id — the identity key, never the display name. */\n readonly sub: string;\n readonly name: string | null;\n readonly email: string | null;\n readonly phoneNumber: string | null;\n}\n\n/** Defines the organization the session acts in, and the person's role there. */\nexport interface BffOrganization {\n readonly id: string;\n readonly role: string;\n}\n\n/**\n * Defines the user a BFF session resolves to. The CSRF token is deliberately absent: it never renders, so the\n * strategy keeps it and the HTTP layer echoes it.\n */\nexport interface BffUser {\n readonly person: BffPerson;\n /** `null` for a person acting in no organization. */\n readonly organization: BffOrganization | null;\n readonly permissions: readonly string[];\n /** When the session ends (ISO 8601); `null` when the server sent none that parses. */\n readonly expiresAt: string | null;\n}\n\n/** Defines one decoded `GET {prefix}/session` response. */\nexport interface BffSessionSnapshot {\n /** `null` while signed out. */\n readonly user: BffUser | null;\n /** The token unsafe requests echo; `null` while signed out. */\n readonly csrfToken: string | null;\n}\n\n/** Defines one decoded `POST {prefix}/
|
|
1
|
+
{"version":3,"file":"BffSession.js","sources":["../../src/auth/BffSession.ts"],"sourcesContent":["import { ApiFailureFactory, type ApiFailure } from '../foundation/http';\nimport { ResultExtensions, type Result } from '../foundation/results';\n\n/** Defines the signed-in person a BFF session names. */\nexport interface BffPerson {\n /** The stable subject id — the identity key, never the display name. */\n readonly sub: string;\n readonly name: string | null;\n readonly email: string | null;\n readonly phoneNumber: string | null;\n}\n\n/** Defines the organization the session acts in, and the person's role there. */\nexport interface BffOrganization {\n readonly id: string;\n readonly role: string;\n}\n\n/**\n * Defines the user a BFF session resolves to. The CSRF token is deliberately absent: it never renders, so the\n * strategy keeps it and the HTTP layer echoes it.\n */\nexport interface BffUser {\n readonly person: BffPerson;\n /** `null` for a person acting in no organization. */\n readonly organization: BffOrganization | null;\n readonly permissions: readonly string[];\n /** When the session ends (ISO 8601); `null` when the server sent none that parses. */\n readonly expiresAt: string | null;\n}\n\n/** Defines one decoded `GET {prefix}/session` response. */\nexport interface BffSessionSnapshot {\n /** `null` while signed out. */\n readonly user: BffUser | null;\n /** The token unsafe requests echo; `null` while signed out. */\n readonly csrfToken: string | null;\n}\n\n/** Defines one decoded `POST {prefix}/sign-out` response. */\nexport interface BffSignOut {\n /** Where the page navigates to end the identity provider's session. */\n readonly endSessionUrl: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\nconst isText = (value: unknown): value is string => typeof value === 'string' && value !== '';\n/** Reads an optional text field; anything but text reads as absent. */\nconst optionalText = (value: unknown): string | null => (typeof value === 'string' ? value : null);\nconst protocol = (): ApiFailure => ApiFailureFactory.create('protocol');\n\n/** Decodes the session response; a payload that breaks the contract is a `protocol` failure. */\nexport function decodeBffSession(value: unknown): Result<BffSessionSnapshot, ApiFailure> {\n if (!isRecord(value) || typeof value['isAuthenticated'] !== 'boolean') return ResultExtensions.fail(protocol());\n if (!value['isAuthenticated']) return ResultExtensions.ok({ user: null, csrfToken: null });\n\n const person = value['person'];\n const organization = value['organization'];\n const permissions = value['permissions'] ?? [];\n const expiresAt = value['expiresAt'];\n if (!isRecord(person) || !isText(person['sub']) || !isText(value['csrfToken'])) {\n return ResultExtensions.fail(protocol());\n }\n if (organization != null && (!isRecord(organization) || !isText(organization['id']))) {\n return ResultExtensions.fail(protocol());\n }\n if (!Array.isArray(permissions) || !permissions.every(isText)) return ResultExtensions.fail(protocol());\n\n return ResultExtensions.ok({\n csrfToken: value['csrfToken'],\n user: {\n person: {\n sub: person['sub'],\n name: optionalText(person['name']),\n email: optionalText(person['email']),\n phoneNumber: optionalText(person['phoneNumber']),\n },\n organization: isRecord(organization)\n ? { id: organization['id'] as string, role: optionalText(organization['role']) ?? '' }\n : null,\n permissions: Object.freeze([...(permissions as string[])]),\n expiresAt: typeof expiresAt === 'string' && Number.isFinite(Date.parse(expiresAt)) ? expiresAt : null,\n },\n });\n}\n\n/** Whether a page may navigate to `url` to end the provider session: a local path, or an absolute http(s) URL. */\nfunction isNavigable(url: string): boolean {\n if (url.startsWith('/')) return !url.startsWith('//') && !url.includes('\\\\');\n try {\n const { protocol: scheme } = new URL(url);\n return scheme === 'https:' || scheme === 'http:';\n } catch {\n return false;\n }\n}\n\n/** Decodes the logout response; an end-session URL the page may not navigate to is a `protocol` failure. */\nexport function decodeBffSignOut(value: unknown): Result<BffSignOut, ApiFailure> {\n if (!isRecord(value) || !isText(value['endSessionUrl']) || !isNavigable(value['endSessionUrl'])) {\n return ResultExtensions.fail(protocol());\n }\n return ResultExtensions.ok({ endSessionUrl: value['endSessionUrl'] });\n}\n\n/** Extends a {@link BffUser} with the checks a screen and a bridge need. */\nexport const BffSessionExtensions = {\n /** Whether the user holds `permission`; `false` while signed out. */\n hasPermission(user: BffUser | null | undefined, permission: string): boolean {\n return user?.permissions.includes(permission) ?? false;\n },\n\n /**\n * The stable user-and-organization key: pass it as `createAuthBridge({ getIdentity })` so a refreshed session\n * keeps its caches and a person or organization switch drops them.\n */\n identity(user: BffUser): string {\n return `${user.person.sub}\\u0000${user.organization?.id ?? ''}`;\n },\n\n /** The session end as epoch milliseconds; `null` when the server sent none that parses. */\n expiresAtMs(user: BffUser): number | null {\n return user.expiresAt === null ? null : Date.parse(user.expiresAt);\n },\n} as const;\n"],"names":[],"mappings":";;AA6CA,MAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AACrE,MAAM,SAAS,CAAC,UAAoC,OAAO,UAAU,YAAY,UAAU;AAE3F,MAAM,eAAe,CAAC,UAAmC,OAAO,UAAU,WAAW,QAAQ;AAC7F,MAAM,WAAW,MAAkB,kBAAkB,OAAO,UAAU;AAG/D,SAAS,iBAAiB,OAAwD;AACvF,MAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,iBAAiB,MAAM,UAAW,QAAO,iBAAiB,KAAK,UAAU;AAC9G,MAAI,CAAC,MAAM,iBAAiB,EAAG,QAAO,iBAAiB,GAAG,EAAE,MAAM,MAAM,WAAW,KAAA,CAAM;AAEzF,QAAM,SAAS,MAAM,QAAQ;AAC7B,QAAM,eAAe,MAAM,cAAc;AACzC,QAAM,cAAc,MAAM,aAAa,KAAK,CAAA;AAC5C,QAAM,YAAY,MAAM,WAAW;AACnC,MAAI,CAAC,SAAS,MAAM,KAAK,CAAC,OAAO,OAAO,KAAK,CAAC,KAAK,CAAC,OAAO,MAAM,WAAW,CAAC,GAAG;AAC9E,WAAO,iBAAiB,KAAK,UAAU;AAAA,EACzC;AACA,MAAI,gBAAgB,SAAS,CAAC,SAAS,YAAY,KAAK,CAAC,OAAO,aAAa,IAAI,CAAC,IAAI;AACpF,WAAO,iBAA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C,YAA6B;AAC3E,WAAO,MAAM,YAAY,SAAS,UAAU,KAAK;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,MAAuB;AAC9B,WAAO,GAAG,KAAK,OAAO,GAAG,KAAS,KAAK,cAAc,MAAM,EAAE;AAAA,EAC/D;AAAA;AAAA,EAGA,YAAY,MAA8B;AACxC,WAAO,KAAK,cAAc,OAAO,OAAO,KAAK,MAAM,KAAK,SAAS;AAAA,EACnE;AACF;"}
|
|
@@ -47,8 +47,8 @@ export interface BffSessionLink {
|
|
|
47
47
|
* Connects a BFF strategy to its provider for the life of a mounted app:
|
|
48
48
|
*
|
|
49
49
|
* - Tab sync: a sign-in here tells the other tabs, a sign-out or expiry here tells them, and a tab that hears a hint
|
|
50
|
-
* re-reads `GET /
|
|
51
|
-
* cannot ping-pong.
|
|
50
|
+
* re-reads `GET /api/identity/session`. The hint carries no identity; a tab applying one never announces,
|
|
51
|
+
* so two tabs cannot ping-pong.
|
|
52
52
|
* - Refresh: one timer per `expiresAt` fires at most twice (`lead`, then `expiry`) and never again for the same
|
|
53
53
|
* value, so a server that does not extend its session cannot make it loop; a new `expiresAt` earns a new pair, and
|
|
54
54
|
* `minIntervalMs` floors the pace. A failed refresh retries with doubling delay and stops after `maxRetries`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BffSessionSync.js","sources":["../../src/auth/BffSessionSync.ts"],"sourcesContent":["import { createSyncChannel, type SyncChannel, type SyncChannelOptions } from '../foundation/channels';\nimport { AppErrorFactory, ResultExtensions, type AppError, type Result } from '../foundation/results';\nimport { AuthStatus, type AuthSession, type AuthStrategyHost } from './AuthSession';\nimport { BffSessionExtensions, type BffUser } from './BffSession';\n\n/** Names what one tab tells the others. The message is a hint to re-read the session, never a credential. */\nexport const BffSyncKind = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n} as const;\nexport type BffSyncKind = (typeof BffSyncKind)[keyof typeof BffSyncKind];\n\n/** Defines the cross-tab message. A peer is another copy of the page: receivers re-read the server, not the message. */\nexport interface BffSyncMessage {\n readonly kind: BffSyncKind;\n}\n\n/** Defines the cross-tab sync options; the channel is `BroadcastChannel`, falling back to the `storage` event. */\nexport interface BffSyncOptions extends SyncChannelOptions {\n /** The channel name shared by this app's tabs. Default `wow-two.auth.bff`. */\n readonly channelName?: string;\n\n /** Opens this tab's endpoint. Default `createSyncChannel(channelName, options)`; tests inject a hub channel. */\n readonly open?: (name: string) => SyncChannel<BffSyncMessage>;\n}\n\n/** Defines when a signed-in session is re-read without the person doing anything. */\nexport interface BffRefreshOptions {\n /** How long before `expiresAt` the pre-expiry refresh runs. Default 60 s. */\n readonly leadMs?: number;\n\n /** The least time between two timer-driven refreshes — the floor under any schedule. Default 15 s. */\n readonly minIntervalMs?: number;\n\n /** How old the last read must be before a focus or visibility change re-reads it. Default 30 s. */\n readonly staleAfterMs?: number;\n\n /** The first retry delay after a failed refresh; it doubles up to 5 min. Default 30 s. */\n readonly retryMs?: number;\n\n /** Consecutive failed refreshes after which the timer stops until the next focus or peer hint. Default 5. */\n readonly maxRetries?: number;\n}\n\nconst DefaultChannelName = 'wow-two.auth.bff';\nconst RefreshDefaults = { leadMs: 60_000, minIntervalMs: 15_000, staleAfterMs: 30_000, retryMs: 30_000, maxRetries: 5 };\nconst MaxRetryDelayMs = 300_000;\n/** The longest `setTimeout` delay browsers honour (a 32-bit signed millisecond count). */\nconst MaxTimerMs = 2_147_483_647;\n\n/** Defines the options of {@link connectBffSession}. */\nexport interface BffSessionLinkOptions {\n readonly sync: BffSyncOptions | false;\n readonly refresh: BffRefreshOptions | false;\n readonly now: () => number;\n}\n\n/** Defines the live connection of one strategy to its provider. */\nexport interface BffSessionLink {\n /** Tells the other tabs the session ended. Silent while this tab applies a peer's hint, so tabs never echo. */\n readonly announce: (kind: BffSyncKind) => void;\n readonly dispose: () => void;\n}\n\n/** `lead`: the refresh before `expiresAt`; `expiry`: the one check at it. A stage never repeats for one `expiresAt`. */\ntype Stage = 'lead' | 'expiry';\n\nconst isHint = (message: unknown): message is BffSyncMessage =>\n typeof message === 'object' &&\n message !== null &&\n ((message as BffSyncMessage).kind === BffSyncKind.SignedIn ||\n (message as BffSyncMessage).kind === BffSyncKind.SignedOut);\n\n/**\n * Connects a BFF strategy to its provider for the life of a mounted app:\n *\n * - Tab sync: a sign-in here tells the other tabs, a sign-out or expiry here tells them, and a tab that hears a hint\n * re-reads `GET /auth/session`. The hint carries no identity, and a tab applying one never announces, so two tabs\n * cannot ping-pong.\n * - Refresh: one timer per `expiresAt` fires at most twice (`lead`, then `expiry`) and never again for the same\n * value, so a server that does not extend its session cannot make it loop; a new `expiresAt` earns a new pair, and\n * `minIntervalMs` floors the pace. A failed refresh retries with doubling delay and stops after `maxRetries`.\n * - Wake: a focus or visibility change re-reads a session older than `staleAfterMs`, signed in or out.\n */\nexport function connectBffSession(host: AuthStrategyHost<BffUser>, options: BffSessionLinkOptions): BffSessionLink {\n const refresh = options.refresh === false ? null : { ...RefreshDefaults, ...options.refresh };\n const now = options.now;\n const disposers: Array<() => void> = [];\n\n let closed = false;\n // `undefined` before the first settled snapshot, `null` while signed out, else the signed-in identity key.\n let lastKey: string | null | undefined;\n let peerDepth = 0;\n let lastLoadedAt = Number.NEGATIVE_INFINITY;\n let lastFireAt = Number.NEGATIVE_INFINITY;\n let fired: { readonly expiresAt: string | null; readonly stage: Stage } | null = null;\n let failures = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const sync = options.sync === false ? null : options.sync;\n let channel: SyncChannel<BffSyncMessage> | null = null;\n if (sync) {\n const name = sync.channelName ?? DefaultChannelName;\n channel = sync.open ? sync.open(name) : createSyncChannel<BffSyncMessage>(name, sync);\n }\n\n let pending: Promise<Result<BffUser | null, AppError>> | null = null;\n /**\n * Re-reads the session; callers that arrive mid-read share it. A throwing strategy counts as a failure, so a timer\n * never leaks an unhandled rejection.\n */\n function revalidate(): Promise<Result<BffUser | null, AppError>> {\n if (pending) return pending;\n const read = (async (): Promise<Result<BffUser | null, AppError>> => {\n try {\n const outcome = await host.revalidate();\n if (outcome.ok) lastLoadedAt = now();\n return outcome;\n } catch {\n return ResultExtensions.fail(AppErrorFactory.unexpected());\n }\n })().finally(() => {\n if (pending === read) pending = null;\n });\n pending = read;\n return read;\n }\n\n function clearTimer(): void {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n }\n\n /** Arms the timer for `stage` at `target`, never sooner than `minIntervalMs` after the previous fire. */\n function arm(stage: Stage, target: number): void {\n clearTimer();\n if (!refresh || closed) return;\n const due = Math.max(target, lastFireAt + refresh.minIntervalMs);\n const wake = (): void => {\n timer = undefined;\n if (closed) return;\n // A clamped or early timer fires before `due`: wait out the rest instead of firing early.\n if (now() < due) timer = setTimeout(wake, Math.min(Math.max(due - now(), 1), MaxTimerMs));\n else void fire(stage);\n };\n timer = setTimeout(wake, Math.min(Math.max(due - now(), 0), MaxTimerMs));\n }\n\n /** Schedules the next stage for the current session, or nothing when it has no end or both stages ran. */\n function schedule(session: AuthSession<BffUser>): void {\n clearTimer();\n if (!refresh || closed || session.status !== AuthStatus.Authenticated || session.user === null) return;\n const expiresAt = BffSessionExtensions.expiresAtMs(session.user);\n if (expiresAt === null) return;\n const done = fired?.expiresAt === session.user.expiresAt ? fired.stage : null;\n if (done === 'expiry') return;\n if (done === 'lead') arm('expiry', expiresAt);\n else arm('lead', expiresAt - refresh.leadMs);\n }\n\n async function fire(stage: Stage): Promise<void> {\n const session = host.getSession();\n if (session.status !== AuthStatus.Authenticated || session.user === null) return;\n const before = fired;\n // Recorded before the read: the read republishes the session, and the republish must see this stage as done.\n fired = { expiresAt: session.user.expiresAt, stage };\n lastFireAt = now();\n const outcome = await revalidate();\n if (closed) return;\n if (outcome.ok) {\n failures = 0;\n return;\n }\n // A cancelled read was superseded by a sign-in, sign-out or newer read, which reschedules on its own.\n if (outcome.failure.type === 'cancelled') return;\n fired = before;\n failures += 1;\n if (!refresh || failures > refresh.maxRetries) return;\n arm(stage, now() + Math.min(refresh.retryMs * 2 ** (failures - 1), MaxRetryDelayMs));\n }\n\n function onSession(session: AuthSession<BffUser>): void {\n if (closed) return;\n if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;\n lastLoadedAt = now();\n const key =\n session.status === AuthStatus.Authenticated && session.user !== null\n ? BffSessionExtensions.identity(session.user)\n : null;\n const previous = lastKey;\n lastKey = key;\n // A signed-out change is announced by the strategy once the server has processed it; announcing here would race it.\n if (key !== null && key !== previous && peerDepth === 0) channel?.post({ kind: BffSyncKind.SignedIn });\n schedule(session);\n }\n\n /** Re-reads when the last read is stale. Both a focus and a visibility event arrive; the second finds it fresh. */\n function wake(): void {\n if (closed || !refresh) return;\n const session = host.getSession();\n if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;\n if (now() - lastLoadedAt < refresh.staleAfterMs) return;\n failures = 0;\n void revalidate();\n }\n\n async function applyHint(): Promise<void> {\n peerDepth += 1;\n failures = 0;\n try {\n await revalidate();\n } finally {\n peerDepth -= 1;\n }\n }\n\n disposers.push(host.subscribe(onSession));\n onSession(host.getSession());\n\n if (channel) {\n const open = channel;\n disposers.push(\n open.subscribe((message) => {\n if (isHint(message)) void applyHint();\n }),\n () => open.close(),\n );\n }\n\n if (refresh && typeof window !== 'undefined' && typeof document !== 'undefined') {\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') wake();\n };\n window.addEventListener('focus', wake);\n document.addEventListener('visibilitychange', onVisibility);\n disposers.push(\n () => window.removeEventListener('focus', wake),\n () => document.removeEventListener('visibilitychange', onVisibility),\n );\n }\n\n return {\n announce: (kind) => {\n if (closed || peerDepth > 0) return;\n channel?.post({ kind });\n },\n dispose: () => {\n if (closed) return;\n closed = true;\n clearTimer();\n for (const dispose of disposers.splice(0)) dispose();\n },\n };\n}\n"],"names":["wake"],"mappings":";;;;;AAMO,MAAM,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,WAAW;AACb;AAmCA,MAAM,q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O,iBAAiB,SAAS,IAAI;AACrC,aAAS,iBAAiB,oBAAoB,YAAY;AAC1D,cAAU;AAAA,MACR,MAAM,OAAO,oBAAoB,SAAS,IAAI;AAAA,MAC9C,MAAM,SAAS,oBAAoB,oBAAoB,YAAY;AAAA,IAAA;AAAA,EAEvE;AAEA,SAAO;AAAA,IACL,UAAU,CAAC,SAAS;AAClB,UAAI,UAAU,YAAY,EAAG;AAC7B,eAAS,KAAK,EAAE,MAAM;AAAA,IACxB;AAAA,IACA,SAAS,MAAM;AACb,UAAI,OAAQ;AACZ,eAAS;AACT,iBAAA;AACA,iBAAW,WAAW,UAAU,OAAO,CAAC,EAAG,SAAA;AAAA,IAC7C;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"BffSessionSync.js","sources":["../../src/auth/BffSessionSync.ts"],"sourcesContent":["import { createSyncChannel, type SyncChannel, type SyncChannelOptions } from '../foundation/channels';\nimport { AppErrorFactory, ResultExtensions, type AppError, type Result } from '../foundation/results';\nimport { AuthStatus, type AuthSession, type AuthStrategyHost } from './AuthSession';\nimport { BffSessionExtensions, type BffUser } from './BffSession';\n\n/** Names what one tab tells the others. The message is a hint to re-read the session, never a credential. */\nexport const BffSyncKind = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n} as const;\nexport type BffSyncKind = (typeof BffSyncKind)[keyof typeof BffSyncKind];\n\n/** Defines the cross-tab message. A peer is another copy of the page: receivers re-read the server, not the message. */\nexport interface BffSyncMessage {\n readonly kind: BffSyncKind;\n}\n\n/** Defines the cross-tab sync options; the channel is `BroadcastChannel`, falling back to the `storage` event. */\nexport interface BffSyncOptions extends SyncChannelOptions {\n /** The channel name shared by this app's tabs. Default `wow-two.auth.bff`. */\n readonly channelName?: string;\n\n /** Opens this tab's endpoint. Default `createSyncChannel(channelName, options)`; tests inject a hub channel. */\n readonly open?: (name: string) => SyncChannel<BffSyncMessage>;\n}\n\n/** Defines when a signed-in session is re-read without the person doing anything. */\nexport interface BffRefreshOptions {\n /** How long before `expiresAt` the pre-expiry refresh runs. Default 60 s. */\n readonly leadMs?: number;\n\n /** The least time between two timer-driven refreshes — the floor under any schedule. Default 15 s. */\n readonly minIntervalMs?: number;\n\n /** How old the last read must be before a focus or visibility change re-reads it. Default 30 s. */\n readonly staleAfterMs?: number;\n\n /** The first retry delay after a failed refresh; it doubles up to 5 min. Default 30 s. */\n readonly retryMs?: number;\n\n /** Consecutive failed refreshes after which the timer stops until the next focus or peer hint. Default 5. */\n readonly maxRetries?: number;\n}\n\nconst DefaultChannelName = 'wow-two.auth.bff';\nconst RefreshDefaults = { leadMs: 60_000, minIntervalMs: 15_000, staleAfterMs: 30_000, retryMs: 30_000, maxRetries: 5 };\nconst MaxRetryDelayMs = 300_000;\n/** The longest `setTimeout` delay browsers honour (a 32-bit signed millisecond count). */\nconst MaxTimerMs = 2_147_483_647;\n\n/** Defines the options of {@link connectBffSession}. */\nexport interface BffSessionLinkOptions {\n readonly sync: BffSyncOptions | false;\n readonly refresh: BffRefreshOptions | false;\n readonly now: () => number;\n}\n\n/** Defines the live connection of one strategy to its provider. */\nexport interface BffSessionLink {\n /** Tells the other tabs the session ended. Silent while this tab applies a peer's hint, so tabs never echo. */\n readonly announce: (kind: BffSyncKind) => void;\n readonly dispose: () => void;\n}\n\n/** `lead`: the refresh before `expiresAt`; `expiry`: the one check at it. A stage never repeats for one `expiresAt`. */\ntype Stage = 'lead' | 'expiry';\n\nconst isHint = (message: unknown): message is BffSyncMessage =>\n typeof message === 'object' &&\n message !== null &&\n ((message as BffSyncMessage).kind === BffSyncKind.SignedIn ||\n (message as BffSyncMessage).kind === BffSyncKind.SignedOut);\n\n/**\n * Connects a BFF strategy to its provider for the life of a mounted app:\n *\n * - Tab sync: a sign-in here tells the other tabs, a sign-out or expiry here tells them, and a tab that hears a hint\n * re-reads `GET /api/identity/session`. The hint carries no identity; a tab applying one never announces,\n * so two tabs cannot ping-pong.\n * - Refresh: one timer per `expiresAt` fires at most twice (`lead`, then `expiry`) and never again for the same\n * value, so a server that does not extend its session cannot make it loop; a new `expiresAt` earns a new pair, and\n * `minIntervalMs` floors the pace. A failed refresh retries with doubling delay and stops after `maxRetries`.\n * - Wake: a focus or visibility change re-reads a session older than `staleAfterMs`, signed in or out.\n */\nexport function connectBffSession(host: AuthStrategyHost<BffUser>, options: BffSessionLinkOptions): BffSessionLink {\n const refresh = options.refresh === false ? null : { ...RefreshDefaults, ...options.refresh };\n const now = options.now;\n const disposers: Array<() => void> = [];\n\n let closed = false;\n // `undefined` before the first settled snapshot, `null` while signed out, else the signed-in identity key.\n let lastKey: string | null | undefined;\n let peerDepth = 0;\n let lastLoadedAt = Number.NEGATIVE_INFINITY;\n let lastFireAt = Number.NEGATIVE_INFINITY;\n let fired: { readonly expiresAt: string | null; readonly stage: Stage } | null = null;\n let failures = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const sync = options.sync === false ? null : options.sync;\n let channel: SyncChannel<BffSyncMessage> | null = null;\n if (sync) {\n const name = sync.channelName ?? DefaultChannelName;\n channel = sync.open ? sync.open(name) : createSyncChannel<BffSyncMessage>(name, sync);\n }\n\n let pending: Promise<Result<BffUser | null, AppError>> | null = null;\n /**\n * Re-reads the session; callers that arrive mid-read share it. A throwing strategy counts as a failure, so a timer\n * never leaks an unhandled rejection.\n */\n function revalidate(): Promise<Result<BffUser | null, AppError>> {\n if (pending) return pending;\n const read = (async (): Promise<Result<BffUser | null, AppError>> => {\n try {\n const outcome = await host.revalidate();\n if (outcome.ok) lastLoadedAt = now();\n return outcome;\n } catch {\n return ResultExtensions.fail(AppErrorFactory.unexpected());\n }\n })().finally(() => {\n if (pending === read) pending = null;\n });\n pending = read;\n return read;\n }\n\n function clearTimer(): void {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n }\n\n /** Arms the timer for `stage` at `target`, never sooner than `minIntervalMs` after the previous fire. */\n function arm(stage: Stage, target: number): void {\n clearTimer();\n if (!refresh || closed) return;\n const due = Math.max(target, lastFireAt + refresh.minIntervalMs);\n const wake = (): void => {\n timer = undefined;\n if (closed) return;\n // A clamped or early timer fires before `due`: wait out the rest instead of firing early.\n if (now() < due) timer = setTimeout(wake, Math.min(Math.max(due - now(), 1), MaxTimerMs));\n else void fire(stage);\n };\n timer = setTimeout(wake, Math.min(Math.max(due - now(), 0), MaxTimerMs));\n }\n\n /** Schedules the next stage for the current session, or nothing when it has no end or both stages ran. */\n function schedule(session: AuthSession<BffUser>): void {\n clearTimer();\n if (!refresh || closed || session.status !== AuthStatus.Authenticated || session.user === null) return;\n const expiresAt = BffSessionExtensions.expiresAtMs(session.user);\n if (expiresAt === null) return;\n const done = fired?.expiresAt === session.user.expiresAt ? fired.stage : null;\n if (done === 'expiry') return;\n if (done === 'lead') arm('expiry', expiresAt);\n else arm('lead', expiresAt - refresh.leadMs);\n }\n\n async function fire(stage: Stage): Promise<void> {\n const session = host.getSession();\n if (session.status !== AuthStatus.Authenticated || session.user === null) return;\n const before = fired;\n // Recorded before the read: the read republishes the session, and the republish must see this stage as done.\n fired = { expiresAt: session.user.expiresAt, stage };\n lastFireAt = now();\n const outcome = await revalidate();\n if (closed) return;\n if (outcome.ok) {\n failures = 0;\n return;\n }\n // A cancelled read was superseded by a sign-in, sign-out or newer read, which reschedules on its own.\n if (outcome.failure.type === 'cancelled') return;\n fired = before;\n failures += 1;\n if (!refresh || failures > refresh.maxRetries) return;\n arm(stage, now() + Math.min(refresh.retryMs * 2 ** (failures - 1), MaxRetryDelayMs));\n }\n\n function onSession(session: AuthSession<BffUser>): void {\n if (closed) return;\n if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;\n lastLoadedAt = now();\n const key =\n session.status === AuthStatus.Authenticated && session.user !== null\n ? BffSessionExtensions.identity(session.user)\n : null;\n const previous = lastKey;\n lastKey = key;\n // A signed-out change is announced by the strategy once the server has processed it; announcing here would race it.\n if (key !== null && key !== previous && peerDepth === 0) channel?.post({ kind: BffSyncKind.SignedIn });\n schedule(session);\n }\n\n /** Re-reads when the last read is stale. Both a focus and a visibility event arrive; the second finds it fresh. */\n function wake(): void {\n if (closed || !refresh) return;\n const session = host.getSession();\n if (session.status !== AuthStatus.Authenticated && session.status !== AuthStatus.Anonymous) return;\n if (now() - lastLoadedAt < refresh.staleAfterMs) return;\n failures = 0;\n void revalidate();\n }\n\n async function applyHint(): Promise<void> {\n peerDepth += 1;\n failures = 0;\n try {\n await revalidate();\n } finally {\n peerDepth -= 1;\n }\n }\n\n disposers.push(host.subscribe(onSession));\n onSession(host.getSession());\n\n if (channel) {\n const open = channel;\n disposers.push(\n open.subscribe((message) => {\n if (isHint(message)) void applyHint();\n }),\n () => open.close(),\n );\n }\n\n if (refresh && typeof window !== 'undefined' && typeof document !== 'undefined') {\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') wake();\n };\n window.addEventListener('focus', wake);\n document.addEventListener('visibilitychange', onVisibility);\n disposers.push(\n () => window.removeEventListener('focus', wake),\n () => document.removeEventListener('visibilitychange', onVisibility),\n );\n }\n\n return {\n announce: (kind) => {\n if (closed || peerDepth > 0) return;\n channel?.post({ kind });\n },\n dispose: () => {\n if (closed) return;\n closed = true;\n clearTimer();\n for (const dispose of disposers.splice(0)) dispose();\n },\n };\n}\n"],"names":["wake"],"mappings":";;;;;AAMO,MAAM,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,WAAW;AACb;AAmCA,MAAM,qBAAqB;AAC3B,MAAM,kBAAkB,EAAE,QAAQ,KAAQ,eAAe,MAAQ,cAAc,KAAQ,SAAS,KAAQ,YAAY,EAAA;AACpH,MAAM,kBAAkB;AAExB,MAAM,aAAa;AAmBnB,MAAM,SAAS,CAAC,YACd,OAAO,YAAY,YACnB,YAAY,SACV,QAA2B,SAAS,YAAY,YAC/C,QAA2B,SAAS,YAAY;AAa9C,SAAS,kBAAkB,MAAiC,SAAgD;AACjH,QAAM,UAAU,QAAQ,YAAY,QAAQ,OAAO,EAAE,GAAG,iBAAiB,GAAG,QAAQ,QAAA;AAC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ACA,iBAAW,WAAW,UAAU,OAAO,CAAC,EAAG,SAAA;AAAA,IAC7C;AAAA,EAAA;AAEJ;"}
|
|
@@ -5,7 +5,7 @@ import { BffUser } from './BffSession';
|
|
|
5
5
|
import { BffRefreshOptions, BffSyncOptions } from './BffSessionSync';
|
|
6
6
|
/** Defines the options for {@link createBffStrategy}. */
|
|
7
7
|
export interface CreateBffStrategyOptions {
|
|
8
|
-
/** The route prefix of the BFF's auth endpoints. Default `/
|
|
8
|
+
/** The route prefix of the BFF's auth endpoints. Default `/api/identity`. */
|
|
9
9
|
readonly prefix?: string;
|
|
10
10
|
/** The origin the auth endpoints live on. Default `''`: the SPA's own origin, the BFF's served shape. */
|
|
11
11
|
readonly baseUrl?: string;
|
|
@@ -33,18 +33,18 @@ export interface BffStrategy extends AuthStrategy<BffUser, string | undefined> {
|
|
|
33
33
|
readonly antiforgery: ApiAntiforgeryOptions;
|
|
34
34
|
/** Reads the current CSRF token; `null` while signed out. */
|
|
35
35
|
readonly getCsrfToken: () => string | null;
|
|
36
|
-
/** Builds `{prefix}/
|
|
37
|
-
readonly
|
|
36
|
+
/** Builds `{prefix}/sign-in?returnUrl=…` for a local path; a path that is not local falls back to `/`. */
|
|
37
|
+
readonly signInUrl: (returnUrl?: string) => string;
|
|
38
38
|
/**
|
|
39
39
|
* Sends the person to sign-in with the page they were on. Subscribe it to the bridge:
|
|
40
|
-
* `bridge.subscribeExpired(bff.
|
|
40
|
+
* `bridge.subscribeExpired(bff.redirectToSignIn)`.
|
|
41
41
|
*/
|
|
42
|
-
readonly
|
|
42
|
+
readonly redirectToSignIn: SessionExpiredListener;
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
45
|
* Creates the BFF session strategy for an SPA served on its BFF's origin. The BFF owns the session cookie; the SPA
|
|
46
|
-
* reads `GET {prefix}/session`, signs in by navigating to `{prefix}/
|
|
47
|
-
* `POST {prefix}/
|
|
46
|
+
* reads `GET {prefix}/session`, signs in by navigating to `{prefix}/sign-in?returnUrl=…`, and signs out with
|
|
47
|
+
* `POST {prefix}/sign-out`, then navigates to the returned `endSessionUrl`.
|
|
48
48
|
*
|
|
49
49
|
* Its own HTTP client carries the auth calls, with no request scope — a sign-out must not cancel itself. The app's
|
|
50
50
|
* client takes {@link BffStrategy.antiforgery} so its writes carry the CSRF token. Pair it with
|
package/dist/auth/BffStrategy.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { createApiClient } from "../foundation/http/CreateApiClient.js";
|
|
2
2
|
import { AppErrorFactory } from "../foundation/results/AppErrorFactory.js";
|
|
3
3
|
import { ResultExtensions } from "../foundation/results/ResultExtensions.js";
|
|
4
|
-
import {
|
|
4
|
+
import { decodeBffSignOut, decodeBffSession } from "./BffSession.js";
|
|
5
5
|
import { connectBffSession } from "./BffSessionSync.js";
|
|
6
6
|
import { ReturnUrlExtensions } from "./ReturnUrlExtensions.js";
|
|
7
7
|
function createBffStrategy(options = {}) {
|
|
8
8
|
const {
|
|
9
|
-
prefix = "/
|
|
9
|
+
prefix = "/api/identity",
|
|
10
10
|
baseUrl = "",
|
|
11
11
|
csrfHeaderName = "X-Csrf-Token",
|
|
12
12
|
sync = {},
|
|
@@ -32,12 +32,12 @@ function createBffStrategy(options = {}) {
|
|
|
32
32
|
}
|
|
33
33
|
window.location.assign(url);
|
|
34
34
|
});
|
|
35
|
-
const
|
|
35
|
+
const signInUrl = (returnUrl = ReturnUrlExtensions.current()) => `${baseUrl}${root}/sign-in?returnUrl=${encodeURIComponent(ReturnUrlExtensions.isLocal(returnUrl) ? returnUrl : "/")}`;
|
|
36
36
|
return {
|
|
37
37
|
antiforgery,
|
|
38
38
|
getCsrfToken: () => csrfToken,
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
signInUrl,
|
|
40
|
+
redirectToSignIn: ({ returnUrl }) => navigate(signInUrl(returnUrl)),
|
|
41
41
|
async resolveUser(context) {
|
|
42
42
|
const current = ++generation;
|
|
43
43
|
const outcome = await client.get(`${root}/session`, { ...context, decode: decodeBffSession });
|
|
@@ -56,13 +56,13 @@ function createBffStrategy(options = {}) {
|
|
|
56
56
|
if (!ReturnUrlExtensions.isLocal(target)) return ResultExtensions.fail(AppErrorFactory.validation());
|
|
57
57
|
if (!options.navigate && typeof window === "undefined")
|
|
58
58
|
return ResultExtensions.fail(AppErrorFactory.unavailable());
|
|
59
|
-
navigate(
|
|
59
|
+
navigate(signInUrl(target));
|
|
60
60
|
return ResultExtensions.ok(void 0);
|
|
61
61
|
},
|
|
62
62
|
async signOut(context) {
|
|
63
63
|
++generation;
|
|
64
64
|
try {
|
|
65
|
-
const outcome = await client.post(`${root}/
|
|
65
|
+
const outcome = await client.post(`${root}/sign-out`, { ...context, decode: decodeBffSignOut });
|
|
66
66
|
if (!outcome.ok) {
|
|
67
67
|
return outcome.failure.status === 401 ? ResultExtensions.ok(void 0) : outcome;
|
|
68
68
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BffStrategy.js","sources":["../../src/auth/BffStrategy.ts"],"sourcesContent":["import { createApiClient, type ApiAntiforgeryOptions, type ApiClientOptions } from '../foundation/http';\nimport { AppErrorFactory, ResultExtensions, type AppError, type Result } from '../foundation/results';\nimport type { SessionExpiredListener } from './AuthBridge';\nimport type { AuthResolveContext, AuthStrategy, AuthStrategyHost } from './AuthSession';\nimport {
|
|
1
|
+
{"version":3,"file":"BffStrategy.js","sources":["../../src/auth/BffStrategy.ts"],"sourcesContent":["import { createApiClient, type ApiAntiforgeryOptions, type ApiClientOptions } from '../foundation/http';\nimport { AppErrorFactory, ResultExtensions, type AppError, type Result } from '../foundation/results';\nimport type { SessionExpiredListener } from './AuthBridge';\nimport type { AuthResolveContext, AuthStrategy, AuthStrategyHost } from './AuthSession';\nimport { decodeBffSignOut, decodeBffSession, type BffUser } from './BffSession';\nimport { connectBffSession, type BffRefreshOptions, type BffSessionLink, type BffSyncOptions } from './BffSessionSync';\nimport { ReturnUrlExtensions } from './ReturnUrlExtensions';\n\n/** Defines the options for {@link createBffStrategy}. */\nexport interface CreateBffStrategyOptions {\n /** The route prefix of the BFF's auth endpoints. Default `/api/identity`. */\n readonly prefix?: string;\n\n /** The origin the auth endpoints live on. Default `''`: the SPA's own origin, the BFF's served shape. */\n readonly baseUrl?: string;\n\n /** The request header the CSRF token travels in. Default `X-Csrf-Token`. */\n readonly csrfHeaderName?: string;\n\n /** Sent with every auth request. Default is the browser's `same-origin`. */\n readonly credentials?: RequestCredentials;\n\n /** Replaces `fetch` — a mocked one in tests. */\n readonly fetch?: typeof globalThis.fetch;\n\n /** Navigates the page. Default `window.location.assign`; inject to drive the strategy without a DOM. */\n readonly navigate?: (url: string) => void;\n\n /** Cross-tab sync. Default on, over `BroadcastChannel` with a `storage`-event fallback; `false` turns it off. */\n readonly sync?: BffSyncOptions | false;\n\n /** Session refresh before `expiresAt` and on focus. Default on; `false` turns it off. */\n readonly refresh?: BffRefreshOptions | false;\n\n /** The clock refresh scheduling reads. Default `Date.now`. */\n readonly now?: () => number;\n}\n\n/** Defines the BFF strategy — an {@link AuthStrategy} plus the pieces the rest of the app wires. */\nexport interface BffStrategy extends AuthStrategy<BffUser, string | undefined> {\n /**\n * Feeds `createApiClient({ antiforgery })`, so every unsafe request echoes the session's CSRF token. The token\n * is read per request, so a refreshed session and a sign-out take effect at once.\n */\n readonly antiforgery: ApiAntiforgeryOptions;\n\n /** Reads the current CSRF token; `null` while signed out. */\n readonly getCsrfToken: () => string | null;\n\n /** Builds `{prefix}/sign-in?returnUrl=…` for a local path; a path that is not local falls back to `/`. */\n readonly signInUrl: (returnUrl?: string) => string;\n\n /**\n * Sends the person to sign-in with the page they were on. Subscribe it to the bridge:\n * `bridge.subscribeExpired(bff.redirectToSignIn)`.\n */\n readonly redirectToSignIn: SessionExpiredListener;\n}\n\n/**\n * Creates the BFF session strategy for an SPA served on its BFF's origin. The BFF owns the session cookie; the SPA\n * reads `GET {prefix}/session`, signs in by navigating to `{prefix}/sign-in?returnUrl=…`, and signs out with\n * `POST {prefix}/sign-out`, then navigates to the returned `endSessionUrl`.\n *\n * Its own HTTP client carries the auth calls, with no request scope — a sign-out must not cancel itself. The app's\n * client takes {@link BffStrategy.antiforgery} so its writes carry the CSRF token. Pair it with\n * `createAuthBridge({ getIdentity: BffSessionExtensions.identity })`.\n */\nexport function createBffStrategy(options: CreateBffStrategyOptions = {}): BffStrategy {\n const {\n prefix = '/api/identity',\n baseUrl = '',\n csrfHeaderName = 'X-Csrf-Token',\n sync = {},\n refresh = {},\n now = () => Date.now(),\n } = options;\n const root = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;\n\n let csrfToken: string | null = null;\n let generation = 0;\n let link: BffSessionLink | undefined;\n\n const antiforgery: ApiAntiforgeryOptions = { headerName: csrfHeaderName, getToken: () => csrfToken };\n const clientOptions: ApiClientOptions = {\n baseUrl,\n antiforgery,\n ...(options.credentials !== undefined ? { credentials: options.credentials } : {}),\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n };\n const client = createApiClient(clientOptions);\n const cancelled = () => ResultExtensions.fail(AppErrorFactory.cancelled());\n\n const navigate =\n options.navigate ??\n ((url: string) => {\n if (typeof window === 'undefined') {\n throw new Error('createBffStrategy: navigating needs a browser. Pass `navigate` to drive it elsewhere.');\n }\n window.location.assign(url);\n });\n const signInUrl = (returnUrl: string = ReturnUrlExtensions.current()): string =>\n `${baseUrl}${root}/sign-in?returnUrl=${encodeURIComponent(ReturnUrlExtensions.isLocal(returnUrl) ? returnUrl : '/')}`;\n\n return {\n antiforgery,\n getCsrfToken: () => csrfToken,\n signInUrl,\n redirectToSignIn: ({ returnUrl }) => navigate(signInUrl(returnUrl)),\n\n async resolveUser(context: AuthResolveContext): Promise<Result<BffUser | null, AppError>> {\n const current = ++generation;\n const outcome = await client.get(`${root}/session`, { ...context, decode: decodeBffSession });\n if (current !== generation || context.signal?.aborted) return cancelled();\n if (!outcome.ok) {\n // A BFF answers a signed-out `GET /session` with 200; a 401 from a proxy in front still means signed out.\n if (outcome.failure.status !== 401) return outcome;\n csrfToken = null;\n return ResultExtensions.ok(null);\n }\n csrfToken = outcome.value.csrfToken;\n return ResultExtensions.ok(outcome.value.user);\n },\n\n // Returns void on purpose: the session stays as it is while the browser navigates to the BFF.\n signIn(returnUrl?: string): Result<void, AppError> {\n const target = returnUrl ?? ReturnUrlExtensions.current();\n if (!ReturnUrlExtensions.isLocal(target)) return ResultExtensions.fail(AppErrorFactory.validation());\n if (!options.navigate && typeof window === 'undefined')\n return ResultExtensions.fail(AppErrorFactory.unavailable());\n navigate(signInUrl(target));\n return ResultExtensions.ok(undefined);\n },\n\n async signOut(context: AuthResolveContext): Promise<Result<void, AppError>> {\n ++generation;\n try {\n // The token is read when the request is sent, so it must outlive the call and clear only afterwards.\n const outcome = await client.post(`${root}/sign-out`, { ...context, decode: decodeBffSignOut });\n if (!outcome.ok) {\n // A 401 means the server session was already gone: signed out either way, with no provider session to end.\n return outcome.failure.status === 401 ? ResultExtensions.ok(undefined) : outcome;\n }\n navigate(outcome.value.endSessionUrl);\n return ResultExtensions.ok(undefined);\n } finally {\n csrfToken = null;\n // Told after the server answered: a hint sent earlier would let a tab read the session before it ended.\n link?.announce('signed-out');\n }\n },\n\n onUnauthorized(): void {\n generation += 1;\n csrfToken = null;\n link?.announce('signed-out');\n },\n\n connect(host: AuthStrategyHost<BffUser>): () => void {\n link?.dispose();\n const own = connectBffSession(host, { sync, refresh, now });\n link = own;\n return () => {\n own.dispose();\n if (link === own) link = undefined;\n };\n },\n };\n}\n"],"names":[],"mappings":";;;;;;AAoEO,SAAS,kBAAkB,UAAoC,IAAiB;AACrF,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,OAAO,CAAA;AAAA,IACP,UAAU,CAAA;AAAA,IACV,MAAM,MAAM,KAAK,IAAA;AAAA,EAAI,IACnB;AACJ,QAAM,OAAO,OAAO,SAAS,GAAG,IAAI,OAAO,MAAM,GAAG,EAAE,IAAI;AAE1D,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C/C;AAAA;AAAA,IAGA,OAAO,WAA4C;AACjD,YAAM,SAAS,aAAa,oBAAoB,QAAA;AAChD,UAAI,CAAC,oBAAoB,QAAQ,MAAM,UAAU,iBAAiB,KAAK,gBAAgB,YAAY;AACnG,UAAI,CAAC,QAAQ,YAAY,OAAO,WAAW;AACzC,eAAO,iBAAiB,KAAK,gBAAgB,YAAA,CAAa;AAC5D,eAAS,UAAU,MAAM,CAAC;AAC1B,aAAO,iBAAiB,GAAG,MAAS;AAAA,IACtC;AAAA,IAEA,MAAM,QAAQ,SAA8D;AAC1E,QAAE;AACF,UAAI;AAEF,cAAM,UAAU,MAAM,OAAO,KAAK,GAAG,IAAI,aAAa,EAAE,GAAG,SAAS,QAAQ,iBAAA,CAAkB;AAC9F,YAAI,CAAC,QAAQ,IAAI;AAEf,iBAAO,QAAQ,QAAQ,WAAW,MAAM,iBAAiB,GAAG,MAAS,IAAI;AAAA,QAC3E;AACA,iBAAS,QAAQ,MAAM,aAAa;AACpC,eAAO,iBAAiB,GAAG,MAAS;AAAA,MACtC,UAAA;AACE,oBAAY;AAEZ,cAAM,SAAS,YAAY;AAAA,MAC7B;AAAA,IACF;AAAA,IAEA,iBAAuB;AACrB,oBAAc;AACd,kBAAY;AACZ,YAAM,SAAS,YAAY;AAAA,IAC7B;AAAA,IAEA,QAAQ,MAA6C;AACnD,YAAM,QAAA;AACN,YAAM,MAAM,kBAAkB,MAAM,EAAE,MAAM,SAAS,KAAK;AAC1D,aAAO;AACP,aAAO,MAAM;AACX,YAAI,QAAA;AACJ,YAAI,SAAS,IAAK,QAAO;AAAA,MAC3B;AAAA,IACF;AAAA,EAAA;AAEJ;"}
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -7,6 +7,6 @@ export { createBearerStrategy, type CreateBearerStrategyOptions, type BearerStra
|
|
|
7
7
|
export { createRedirectStrategy, type CreateRedirectStrategyOptions } from './RedirectStrategy';
|
|
8
8
|
export { createMemoryTokenStorage, type TokenStorage } from './TokenStorage';
|
|
9
9
|
export { createBffStrategy, type BffStrategy, type CreateBffStrategyOptions } from './BffStrategy';
|
|
10
|
-
export { BffSessionExtensions, decodeBffSession,
|
|
10
|
+
export { BffSessionExtensions, decodeBffSession, decodeBffSignOut, type BffUser, type BffPerson, type BffOrganization, type BffSessionSnapshot, type BffSignOut, } from './BffSession';
|
|
11
11
|
export { BffSyncKind, type BffSyncMessage, type BffSyncOptions, type BffRefreshOptions } from './BffSessionSync';
|
|
12
12
|
export { useBffAuth, type BffAuthApi } from './UseBffAuth';
|
package/dist/auth/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { createBearerStrategy } from "./BearerStrategy.js";
|
|
|
7
7
|
import { createRedirectStrategy } from "./RedirectStrategy.js";
|
|
8
8
|
import { createMemoryTokenStorage } from "./TokenStorage.js";
|
|
9
9
|
import { createBffStrategy } from "./BffStrategy.js";
|
|
10
|
-
import { BffSessionExtensions,
|
|
10
|
+
import { BffSessionExtensions, decodeBffSession, decodeBffSignOut } from "./BffSession.js";
|
|
11
11
|
import { BffSyncKind } from "./BffSessionSync.js";
|
|
12
12
|
import { useBffAuth } from "./UseBffAuth.js";
|
|
13
13
|
export {
|
|
@@ -21,8 +21,8 @@ export {
|
|
|
21
21
|
createCookieStrategy,
|
|
22
22
|
createMemoryTokenStorage,
|
|
23
23
|
createRedirectStrategy,
|
|
24
|
-
decodeBffLogout,
|
|
25
24
|
decodeBffSession,
|
|
25
|
+
decodeBffSignOut,
|
|
26
26
|
useAuth,
|
|
27
27
|
useBffAuth
|
|
28
28
|
};
|
|
@@ -20,12 +20,17 @@ export interface AppFormOptions<TValues extends object, TOutput = TValues> {
|
|
|
20
20
|
readonly defaultValues: TValues;
|
|
21
21
|
/** The whole-form validator — any Standard Schema (zod / valibot / arktype). Sync or async. */
|
|
22
22
|
readonly schema?: StandardSchemaV1<TValues, TOutput>;
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* When client validation runs. `'submit'` re-validates touched fields on change after the first attempt.
|
|
25
|
+
* Validation is form-wide, but a field DISPLAYS its client error only once it was blurred, after a submit
|
|
26
|
+
* attempt, or — under `'change'` — once it changed ({@link AppFieldApi.errors}).
|
|
27
|
+
*/
|
|
24
28
|
readonly validateOn?: 'change' | 'blur' | 'submit';
|
|
25
29
|
/**
|
|
26
30
|
* Validate once on mount — seeds `isValid` / field errors before any interaction (edit-screen
|
|
27
31
|
* validity indicators, wizard step-entry gating). Fields stay untouched (`isTouched` false), so
|
|
28
|
-
* the initial pass populates state without asserting the user has interacted
|
|
32
|
+
* the initial pass populates `state.isValid` without asserting the user has interacted: a field's
|
|
33
|
+
* error displays once that field is touched, changed (`'change'`) or a submit is attempted. Default `false`.
|
|
29
34
|
*/
|
|
30
35
|
readonly validateOnMount?: boolean;
|
|
31
36
|
/** Performs the submit with valid values — usually a `useAppMutation` / `useOptimisticMutation` `mutateAsync`. */
|
|
@@ -103,7 +108,11 @@ export interface AppFieldApi<TValue> {
|
|
|
103
108
|
readonly setValue: (value: TValue) => void;
|
|
104
109
|
/** Marks the field touched — the Field glue also wires it onto the control's blur. */
|
|
105
110
|
readonly onBlur: () => void;
|
|
106
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* The messages to display, client first. Server messages always display and clear on the next change to
|
|
113
|
+
* the field. A client message displays once the field is touched, after a submit attempt, or — under
|
|
114
|
+
* `validateOn: 'change'` — once it changed; until then it stays in `form.state.isValid` only.
|
|
115
|
+
*/
|
|
107
116
|
readonly errors: ReadonlyArray<string>;
|
|
108
117
|
readonly isDirty: boolean;
|
|
109
118
|
readonly isTouched: boolean;
|
|
@@ -3,6 +3,24 @@ import { ResolveValidationMessage } from '../foundation/validators';
|
|
|
3
3
|
import { StandardSchemaV1 } from './StandardSchema';
|
|
4
4
|
/** Matches path segments, so selecting row 1 never selects row 10. Root errors always apply. */
|
|
5
5
|
export declare function includesValidationPath(path: string, fields?: ReadonlyArray<string>): boolean;
|
|
6
|
+
/** The per-form interaction marks that decide which field shows its client error. */
|
|
7
|
+
export interface FieldMarks {
|
|
8
|
+
/** Blurred paths (and paths a scoped `validate({ fields })` touched). */
|
|
9
|
+
readonly touched: ReadonlySet<string>;
|
|
10
|
+
/** Paths a write reached — `setValue`, field assignment, array operations. */
|
|
11
|
+
readonly changed: ReadonlySet<string>;
|
|
12
|
+
readonly submitCount: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Per-field error display, shared by every adapter. Validation runs form-wide, so a client error can
|
|
16
|
+
* exist for a field the user has not reached; it displays only once that field was blurred, after a
|
|
17
|
+
* submit attempt, or — under `validateOn: 'change'`, where every write validates — once it changed.
|
|
18
|
+
* A path matches its own mark and its descendants' (a touched `rules` array touches its rows).
|
|
19
|
+
*/
|
|
20
|
+
export declare function resolveFieldDisplay(path: string, marks: FieldMarks, validateOn: 'change' | 'blur' | 'submit' | undefined): {
|
|
21
|
+
readonly isTouched: boolean;
|
|
22
|
+
readonly showsClientErrors: boolean;
|
|
23
|
+
};
|
|
6
24
|
/** Runs a display-only gate and filters issues without bypassing whole-form submit parsing. */
|
|
7
25
|
export declare function validateFormScope<TValues extends object>(values: TValues, options: AppFormValidationOptions<TValues>, schema: StandardSchemaV1<TValues, unknown> | undefined, resolver: ResolveValidationMessage, fallback: string): Promise<Record<string, ReadonlyArray<string>>>;
|
|
8
26
|
/** Settles even when a transport ignores abort, while observing its eventual rejection. */
|
|
@@ -11,6 +11,14 @@ function includesValidationPath(path, fields) {
|
|
|
11
11
|
return selected.every((segment, index) => segments[index] === segment);
|
|
12
12
|
});
|
|
13
13
|
}
|
|
14
|
+
function resolveFieldDisplay(path, marks, validateOn) {
|
|
15
|
+
const isMarked = (set) => {
|
|
16
|
+
for (const mark of set) if (includesValidationPath(path, [mark])) return true;
|
|
17
|
+
return false;
|
|
18
|
+
};
|
|
19
|
+
const isTouched = marks.submitCount > 0 || isMarked(marks.touched);
|
|
20
|
+
return { isTouched, showsClientErrors: isTouched || validateOn === "change" && isMarked(marks.changed) };
|
|
21
|
+
}
|
|
14
22
|
async function validateFormScope(values, options, schema, resolver, fallback) {
|
|
15
23
|
try {
|
|
16
24
|
const selected = options.schema ?? schema;
|
|
@@ -49,6 +57,7 @@ async function submitWithFocus(submit, isCurrent, event, root) {
|
|
|
49
57
|
}
|
|
50
58
|
export {
|
|
51
59
|
includesValidationPath,
|
|
60
|
+
resolveFieldDisplay,
|
|
52
61
|
submitWithFocus,
|
|
53
62
|
untilFormAbort,
|
|
54
63
|
validateFormScope
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FormOperations.js","sources":["../../src/formsEngine/FormOperations.ts"],"sourcesContent":["import { nextTick } from 'vue';\n\nimport type { AppFormValidationOptions } from './AppForm';\nimport { focusFirstInvalid } from './FocusFirstInvalid';\nimport { snapshotFormValues } from './FormSnapshot';\nimport { parsePath } from './Paths';\nimport { formParseFailure, parseStandardSchema } from './SchemaValidation';\nimport type { ResolveValidationMessage } from '../foundation/validators';\nimport type { StandardSchemaV1 } from './StandardSchema';\n\n/** Matches path segments, so selecting row 1 never selects row 10. Root errors always apply. */\nexport function includesValidationPath(path: string, fields?: ReadonlyArray<string>): boolean {\n if (!fields || path === '') return true;\n const segments = parsePath(path);\n return fields.some((field) => {\n const selected = parsePath(field);\n return selected.every((segment, index) => segments[index] === segment);\n });\n}\n\n/** Runs a display-only gate and filters issues without bypassing whole-form submit parsing. */\nexport async function validateFormScope<TValues extends object>(\n values: TValues,\n options: AppFormValidationOptions<TValues>,\n schema: StandardSchemaV1<TValues, unknown> | undefined,\n resolver: ResolveValidationMessage,\n fallback: string,\n): Promise<Record<string, ReadonlyArray<string>>> {\n try {\n const selected = options.schema ?? schema;\n if (!selected) return {};\n const result = await parseStandardSchema(selected, snapshotFormValues(values), resolver);\n return result.ok\n ? {}\n : Object.fromEntries(\n Object.entries(result.failure.fieldErrors).filter(([path]) => includesValidationPath(path, options.fields)),\n );\n } catch {\n const result = formParseFailure({ '': [fallback] });\n return result.ok ? {} : result.failure.fieldErrors;\n }\n}\n\n/** Settles even when a transport ignores abort, while observing its eventual rejection. */\nexport function untilFormAbort<T>(work: Promise<T>, signal: AbortSignal, cancelled: T): Promise<T> {\n if (signal.aborted) {\n void work.catch(() => undefined);\n return Promise.resolve(cancelled);\n }\n return new Promise<T>((resolve, reject) => {\n const abort = (): void => resolve(cancelled);\n signal.addEventListener('abort', abort, { once: true });\n void work.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));\n });\n}\n\n/** Captures event scope synchronously, then focuses rendered failures only for current manual attempts. */\nexport async function submitWithFocus(\n submit: () => Promise<boolean>,\n isCurrent: () => boolean,\n event?: Event,\n root?: ParentNode | null,\n): Promise<boolean> {\n event?.preventDefault();\n const target = event?.currentTarget;\n const scope = root ?? (target && 'querySelector' in target ? (target as ParentNode) : null);\n const successful = await submit();\n await nextTick();\n if (!successful && isCurrent() && scope && !focusFirstInvalid(scope)) {\n const summary = scope.querySelector<HTMLElement>('[data-form-error-summary]');\n if (summary && !summary.closest('[inert], [hidden], [aria-hidden=\"true\"]')) summary.focus();\n }\n return successful;\n}\n"],"names":[],"mappings":";;;;;AAWO,SAAS,uBAAuB,MAAc,QAAyC;AAC5F,MAAI,CAAC,UAAU,SAAS,GAAI,QAAO;AACnC,QAAM,WAAW,UAAU,IAAI;AAC/B,SAAO,OAAO,KAAK,CAAC,UAAU;AAC5B,UAAM,WAAW,UAAU,KAAK;AAChC,WAAO,SAAS,MAAM,CAAC,SAAS,UAAU,SAAS,KAAK,MAAM,OAAO;AAAA,EACvE,CAAC;AACH;AAGA,eAAsB,kBACpB,QACA,SACA,QACA,UACA,UACgD;AAChD,MAAI;AACF,UAAM,WAAW,QAAQ,UAAU;AACnC,QAAI,CAAC,SAAU,QAAO,CAAA;AACtB,UAAM,SAAS,MAAM,oBAAoB,UAAU,mBAAmB,MAAM,GAAG,QAAQ;AACvF,WAAO,OAAO,KACV,CAAA,IACA,OAAO;AAAA,MACL,OAAO,QAAQ,OAAO,QAAQ,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,MAAM,uBAAuB,MAAM,QAAQ,MAAM,CAAC;AAAA,IAAA;AAAA,EAElH,QAAQ;AACN,UAAM,SAAS,iBAAiB,EAAE,IAAI,CAAC,QAAQ,GAAG;AAClD,WAAO,OAAO,KAAK,CAAA,IAAK,OAAO,QAAQ;AAAA,EACzC;AACF;AAGO,SAAS,eAAkB,MAAkB,QAAqB,WAA0B;AACjG,MAAI,OAAO,SAAS;AAClB,SAAK,KAAK,MAAM,MAAM,MAAS;AAC/B,WAAO,QAAQ,QAAQ,SAAS;AAAA,EAClC;AACA,SAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,UAAM,QAAQ,MAAY,QAAQ,SAAS;AAC3C,WAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,MAAM;AACtD,SAAK,KAAK,KAAK,SAAS,MAAM,EAAE,QAAQ,MAAM,OAAO,oBAAoB,SAAS,KAAK,CAAC;AAAA,EAC1F,CAAC;AACH;AAGA,eAAsB,gBACpB,QACA,WACA,OACA,MACkB;AAClB,SAAO,eAAA;AACP,QAAM,SAAS,OAAO;AACtB,QAAM,QAAQ,SAAS,UAAU,mBAAmB,SAAU,SAAwB;AACtF,QAAM,aAAa,MAAM,OAAA;AACzB,QAAM,SAAA;AACN,MAAI,CAAC,cAAc,UAAA,KAAe,SAAS,CAAC,kBAAkB,KAAK,GAAG;AACpE,UAAM,UAAU,MAAM,cAA2B,2BAA2B;AAC5E,QAAI,WAAW,CAAC,QAAQ,QAAQ,yCAAyC,WAAW,MAAA;AAAA,EACtF;AACA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"FormOperations.js","sources":["../../src/formsEngine/FormOperations.ts"],"sourcesContent":["import { nextTick } from 'vue';\n\nimport type { AppFormValidationOptions } from './AppForm';\nimport { focusFirstInvalid } from './FocusFirstInvalid';\nimport { snapshotFormValues } from './FormSnapshot';\nimport { parsePath } from './Paths';\nimport { formParseFailure, parseStandardSchema } from './SchemaValidation';\nimport type { ResolveValidationMessage } from '../foundation/validators';\nimport type { StandardSchemaV1 } from './StandardSchema';\n\n/** Matches path segments, so selecting row 1 never selects row 10. Root errors always apply. */\nexport function includesValidationPath(path: string, fields?: ReadonlyArray<string>): boolean {\n if (!fields || path === '') return true;\n const segments = parsePath(path);\n return fields.some((field) => {\n const selected = parsePath(field);\n return selected.every((segment, index) => segments[index] === segment);\n });\n}\n\n/** The per-form interaction marks that decide which field shows its client error. */\nexport interface FieldMarks {\n /** Blurred paths (and paths a scoped `validate({ fields })` touched). */\n readonly touched: ReadonlySet<string>;\n /** Paths a write reached — `setValue`, field assignment, array operations. */\n readonly changed: ReadonlySet<string>;\n readonly submitCount: number;\n}\n\n/**\n * Per-field error display, shared by every adapter. Validation runs form-wide, so a client error can\n * exist for a field the user has not reached; it displays only once that field was blurred, after a\n * submit attempt, or — under `validateOn: 'change'`, where every write validates — once it changed.\n * A path matches its own mark and its descendants' (a touched `rules` array touches its rows).\n */\nexport function resolveFieldDisplay(\n path: string,\n marks: FieldMarks,\n validateOn: 'change' | 'blur' | 'submit' | undefined,\n): { readonly isTouched: boolean; readonly showsClientErrors: boolean } {\n const isMarked = (set: ReadonlySet<string>): boolean => {\n for (const mark of set) if (includesValidationPath(path, [mark])) return true;\n return false;\n };\n // A submit attempt counts as touching everything.\n const isTouched = marks.submitCount > 0 || isMarked(marks.touched);\n return { isTouched, showsClientErrors: isTouched || (validateOn === 'change' && isMarked(marks.changed)) };\n}\n\n/** Runs a display-only gate and filters issues without bypassing whole-form submit parsing. */\nexport async function validateFormScope<TValues extends object>(\n values: TValues,\n options: AppFormValidationOptions<TValues>,\n schema: StandardSchemaV1<TValues, unknown> | undefined,\n resolver: ResolveValidationMessage,\n fallback: string,\n): Promise<Record<string, ReadonlyArray<string>>> {\n try {\n const selected = options.schema ?? schema;\n if (!selected) return {};\n const result = await parseStandardSchema(selected, snapshotFormValues(values), resolver);\n return result.ok\n ? {}\n : Object.fromEntries(\n Object.entries(result.failure.fieldErrors).filter(([path]) => includesValidationPath(path, options.fields)),\n );\n } catch {\n const result = formParseFailure({ '': [fallback] });\n return result.ok ? {} : result.failure.fieldErrors;\n }\n}\n\n/** Settles even when a transport ignores abort, while observing its eventual rejection. */\nexport function untilFormAbort<T>(work: Promise<T>, signal: AbortSignal, cancelled: T): Promise<T> {\n if (signal.aborted) {\n void work.catch(() => undefined);\n return Promise.resolve(cancelled);\n }\n return new Promise<T>((resolve, reject) => {\n const abort = (): void => resolve(cancelled);\n signal.addEventListener('abort', abort, { once: true });\n void work.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));\n });\n}\n\n/** Captures event scope synchronously, then focuses rendered failures only for current manual attempts. */\nexport async function submitWithFocus(\n submit: () => Promise<boolean>,\n isCurrent: () => boolean,\n event?: Event,\n root?: ParentNode | null,\n): Promise<boolean> {\n event?.preventDefault();\n const target = event?.currentTarget;\n const scope = root ?? (target && 'querySelector' in target ? (target as ParentNode) : null);\n const successful = await submit();\n await nextTick();\n if (!successful && isCurrent() && scope && !focusFirstInvalid(scope)) {\n const summary = scope.querySelector<HTMLElement>('[data-form-error-summary]');\n if (summary && !summary.closest('[inert], [hidden], [aria-hidden=\"true\"]')) summary.focus();\n }\n return successful;\n}\n"],"names":[],"mappings":";;;;;AAWO,SAAS,uBAAuB,MAAc,QAAyC;AAC5F,MAAI,CAAC,UAAU,SAAS,GAAI,QAAO;AACnC,QAAM,WAAW,UAAU,IAAI;AAC/B,SAAO,OAAO,KAAK,CAAC,UAAU;AAC5B,UAAM,WAAW,UAAU,KAAK;AAChC,WAAO,SAAS,MAAM,CAAC,SAAS,UAAU,SAAS,KAAK,MAAM,OAAO;AAAA,EACvE,CAAC;AACH;AAiBO,SAAS,oBACd,MACA,OACA,YACsE;AACtE,QAAM,WAAW,CAAC,QAAsC;AACtD,eAAW,QAAQ,IAAK,KAAI,uBAAuB,MAAM,CAAC,IAAI,CAAC,EAAG,QAAO;AACzE,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,MAAM,cAAc,KA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,GAAG;AACpE,UAAM,UAAU,MAAM,cAA2B,2BAA2B;AAC5E,QAAI,WAAW,CAAC,QAAQ,QAAQ,yCAAyC,WAAW,MAAA;AAAA,EACtF;AACA,SAAO;AACT;"}
|
|
@@ -2,7 +2,7 @@ import { shallowRef } from "vue";
|
|
|
2
2
|
import { fieldIssues } from "../../../foundation/http/FieldErrors.js";
|
|
3
3
|
import { AppErrorFactory } from "../../../foundation/results/AppErrorFactory.js";
|
|
4
4
|
import { deepEqual } from "../../DeepEqual.js";
|
|
5
|
-
import { untilFormAbort, validateFormScope, includesValidationPath } from "../../FormOperations.js";
|
|
5
|
+
import { untilFormAbort, validateFormScope, includesValidationPath, resolveFieldDisplay } from "../../FormOperations.js";
|
|
6
6
|
import { snapshotFormValues } from "../../FormSnapshot.js";
|
|
7
7
|
import { getPath, mutateRows, remapPathSet, remapPathMap, setPath, hasPath } from "../../Paths.js";
|
|
8
8
|
import { parseStandardSchema, createOptionsMessageResolver, formParseFailure } from "../../SchemaValidation.js";
|
|
@@ -41,6 +41,7 @@ function createHouseFormEngine(getOptions) {
|
|
|
41
41
|
serverErrors: EmptyMap,
|
|
42
42
|
errors: EmptyMap,
|
|
43
43
|
touched: /* @__PURE__ */ new Set(),
|
|
44
|
+
changed: /* @__PURE__ */ new Set(),
|
|
44
45
|
submitCount: 0,
|
|
45
46
|
isSubmitting: false,
|
|
46
47
|
isValidating: false,
|
|
@@ -141,12 +142,14 @@ function createHouseFormEngine(getOptions) {
|
|
|
141
142
|
const cached = fieldCache.get(path);
|
|
142
143
|
if (cached) return cached;
|
|
143
144
|
const value = getPath(state.values, path);
|
|
145
|
+
const { isTouched, showsClientErrors } = resolveFieldDisplay(path, state, currentOptions().validateOn);
|
|
146
|
+
const client = showsClientErrors ? state.clientErrors[path] ?? EmptyErrors : EmptyErrors;
|
|
147
|
+
const server = state.serverErrors[path] ?? EmptyErrors;
|
|
144
148
|
const computed = {
|
|
145
149
|
value,
|
|
146
|
-
errors:
|
|
150
|
+
errors: server.length === 0 ? client : client.length === 0 ? server : [...client, ...server],
|
|
147
151
|
isDirty: !deepEqual(value, getPath(state.baseline, path)),
|
|
148
|
-
|
|
149
|
-
isTouched: [...state.touched].some((selected) => includesValidationPath(path, [selected])) || state.submitCount > 0
|
|
152
|
+
isTouched
|
|
150
153
|
};
|
|
151
154
|
const previous = previousFieldCache.get(path);
|
|
152
155
|
const stable = previous && fieldStatesEqual(previous, computed) ? previous : computed;
|
|
@@ -156,7 +159,11 @@ function createHouseFormEngine(getOptions) {
|
|
|
156
159
|
function setValue(path, value) {
|
|
157
160
|
const state = peek();
|
|
158
161
|
const serverErrors = Object.prototype.hasOwnProperty.call(state.serverErrors, path) ? Object.fromEntries(Object.entries(state.serverErrors).filter(([key]) => key !== path)) : state.serverErrors;
|
|
159
|
-
patch({
|
|
162
|
+
patch({
|
|
163
|
+
values: setPath(state.values, path, snapshotFormValues(value)),
|
|
164
|
+
serverErrors,
|
|
165
|
+
changed: state.changed.has(path) ? state.changed : new Set(state.changed).add(path)
|
|
166
|
+
});
|
|
160
167
|
if (shouldValidateOnChange()) void runValidation();
|
|
161
168
|
scheduleAutoSubmit();
|
|
162
169
|
}
|
|
@@ -184,7 +191,8 @@ function createHouseFormEngine(getOptions) {
|
|
|
184
191
|
// Row-scoped errors + touched marks follow their rows (insert/remove/swap/move reindex).
|
|
185
192
|
clientErrors: remapPathMap(state.clientErrors, path, operation),
|
|
186
193
|
serverErrors: remapPathMap(state.serverErrors, path, operation),
|
|
187
|
-
touched: remapPathSet(state.touched, path, operation)
|
|
194
|
+
touched: remapPathSet(state.touched, path, operation),
|
|
195
|
+
changed: remapPathSet(new Set(state.changed).add(path), path, operation)
|
|
188
196
|
});
|
|
189
197
|
if (shouldValidateOnChange()) void runValidation();
|
|
190
198
|
scheduleAutoSubmit();
|
|
@@ -204,6 +212,7 @@ function createHouseFormEngine(getOptions) {
|
|
|
204
212
|
serverErrors: EmptyMap,
|
|
205
213
|
errors: EmptyMap,
|
|
206
214
|
touched: /* @__PURE__ */ new Set(),
|
|
215
|
+
changed: /* @__PURE__ */ new Set(),
|
|
207
216
|
submitCount: 0,
|
|
208
217
|
isSubmitting: false,
|
|
209
218
|
isValidating: false,
|