better-ship 0.35.1 → 0.37.0

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.
Files changed (47) hide show
  1. package/dist/application.d.ts +2 -2
  2. package/dist/application.js +2 -1
  3. package/dist/browser-user.d.ts +14 -0
  4. package/dist/browser-user.d.ts.map +1 -0
  5. package/dist/browser-user.js +25 -0
  6. package/dist/browser-user.js.map +1 -0
  7. package/dist/cloudflare/queue.d.ts +1 -1
  8. package/dist/cloudflare.d.ts +2 -2
  9. package/dist/{index-CbvNd665.d.ts → index-BosM_da2.d.ts} +8 -2
  10. package/dist/index-BosM_da2.d.ts.map +1 -0
  11. package/dist/{metrics-DXhrc6ii.d.ts → metrics-B89jvpZQ.d.ts} +2 -2
  12. package/dist/{metrics-DXhrc6ii.d.ts.map → metrics-B89jvpZQ.d.ts.map} +1 -1
  13. package/dist/{outbox-repository-options-gk3JOjLB.d.ts → outbox-repository-options-A2fA1UDX.d.ts} +2 -2
  14. package/dist/{outbox-repository-options-gk3JOjLB.d.ts.map → outbox-repository-options-A2fA1UDX.d.ts.map} +1 -1
  15. package/dist/postgres.d.ts +2 -2
  16. package/dist/posthog/metrics.d.ts +1 -1
  17. package/dist/posthog/server.d.ts +2 -2
  18. package/dist/request-user-B4rh1c2-.js +19 -0
  19. package/dist/request-user-B4rh1c2-.js.map +1 -0
  20. package/dist/resend.d.ts +1 -1
  21. package/dist/sentry/server.d.ts +5 -2
  22. package/dist/sentry/server.d.ts.map +1 -1
  23. package/dist/sentry/server.js +9 -1
  24. package/dist/sentry/server.js.map +1 -1
  25. package/dist/tanstack/oxlint.d.ts +10 -0
  26. package/dist/tanstack/oxlint.d.ts.map +1 -0
  27. package/dist/tanstack/oxlint.js +256 -0
  28. package/dist/tanstack/oxlint.js.map +1 -0
  29. package/dist/tanstack.d.ts +1 -1
  30. package/dist/tanstack.d.ts.map +1 -1
  31. package/dist/tanstack.js +3 -1
  32. package/dist/tanstack.js.map +1 -1
  33. package/dist/testing/outbox-repository.d.ts +1 -1
  34. package/package.json +5 -1
  35. package/src/application/index.ts +1 -0
  36. package/src/application/request-user.ts +18 -0
  37. package/src/infrastructure/observability/browser-user.ts +24 -0
  38. package/src/infrastructure/sentry/server.ts +11 -1
  39. package/src/infrastructure/tanstack/auth.middleware.ts +3 -1
  40. package/src/infrastructure/tanstack/oxlint/form-options.ts +58 -0
  41. package/src/infrastructure/tanstack/oxlint/form-schema-validators.ts +57 -0
  42. package/src/infrastructure/tanstack/oxlint/form-stable-default-values.ts +46 -0
  43. package/src/infrastructure/tanstack/oxlint/index.ts +25 -0
  44. package/src/infrastructure/tanstack/oxlint/no-field-validators.ts +40 -0
  45. package/src/infrastructure/tanstack/oxlint/no-submit-branching.ts +38 -0
  46. package/src/infrastructure/tanstack/oxlint/query-key-from-factory.ts +36 -0
  47. package/dist/index-CbvNd665.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack.d.ts","names":[],"sources":["../src/infrastructure/tanstack/request-context.ts","../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/function-tracing.middleware.ts"],"mappings":";;;;;;;;;;KAQY,iBAAiB;EAAmB;IAAU,sBAAsB;;IAC5E;;;;KCCQ;WACD;aAAiB;;WACjB;aAAoB;;;;KAInB,oBAAoB,gBAAgB;WACrC,MAAM;WACN,SAAS;;;KAIR,YAAY,gBAAgB,eACpC,oBAAoB;WAET;WACA;;;KAIH,qBAAqB,gBAAgB;WACtC,MAAM;WACN,SAAS;WACT,gBAAgB;;;KAIf,sBAAsB,gBAAgB;WACvC,UAAU,SAAS;aACjB;eACE,aAAa;QAAW,SAAS;YAAc,QAAQ;;;;WAI3D,mBAAmB,SAAS,qBAAqB;;;;;;;wBAc5C,qBAAqB,gBAAgB,aACnD,SAAS,sBAAsB;;;;;;;;KC/CrB;WACD,UAAU;aAAmB,aAAa;;;;KAIzC,uBAAuB;WACxB,QAAQ,WAAW;;WAEnB;;WAEA,UAAU,SAAS,mBAAmB;;;;;;wBAOjC,sBAAsB,SAAS,SAAS,uBAAuB;;;;;;;;;;;;;;;;;;;;;wBCnB/D,gCAAgC,aAAa,SAAS,mBAAmB,0CAAO"}
1
+ {"version":3,"file":"tanstack.d.ts","names":[],"sources":["../src/infrastructure/tanstack/request-context.ts","../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/function-tracing.middleware.ts"],"mappings":";;;;;;;;;;KAQY,iBAAiB;EAAmB;IAAU,sBAAsB;;IAC5E;;;;KCEQ;WACD;aAAiB;;WACjB;aAAoB;;;;KAInB,oBAAoB,gBAAgB;WACrC,MAAM;WACN,SAAS;;;KAIR,YAAY,gBAAgB,eACpC,oBAAoB;WAET;WACA;;;KAIH,qBAAqB,gBAAgB;WACtC,MAAM;WACN,SAAS;WACT,gBAAgB;;;KAIf,sBAAsB,gBAAgB;WACvC,UAAU,SAAS;aACjB;eACE,aAAa;QAAW,SAAS;YAAc,QAAQ;;;;WAI3D,mBAAmB,SAAS,qBAAqB;;;;;;;wBAc5C,qBAAqB,gBAAgB,aACnD,SAAS,sBAAsB;;;;;;;;KChDrB;WACD,UAAU;aAAmB,aAAa;;;;KAIzC,uBAAuB;WACxB,QAAQ,WAAW;;WAEnB;;WAEA,UAAU,SAAS,mBAAmB;;;;;;wBAOjC,sBAAsB,SAAS,SAAS,uBAAuB;;;;;;;;;;;;;;;;;;;;;wBCnB/D,gCAAgC,aAAa,SAAS,mBAAmB,0CAAO"}
package/dist/tanstack.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { H as StaleSessionError, R as ValidationError, W as AuthenticationError, nt as AppError, r as createLogger } from "./core-BiN6S_cm.js";
2
+ import { t as applyObservabilityUser } from "./request-user-B4rh1c2-.js";
2
3
  import { n as withSpan } from "./tracing-C_7B_odV.js";
3
4
  import { z } from "zod";
4
5
  import { getReasonPhrase } from "http-status-codes";
@@ -15,10 +16,11 @@ const requestHeaders = async () => {
15
16
  /**
16
17
  * Preserve Porte's function and request middleware contracts with application-owned services.
17
18
  * Optional lookup failures log once and continue as guests. Required lookup failures propagate.
18
- * `onAuthenticated` runs after a session resolves and before the rest of the chain.
19
+ * A resolved session applies `{ id }` on the observability hook, then runs `onAuthenticated`, before the handler.
19
20
  */
20
21
  function createAuthMiddleware(options) {
21
22
  function notifyAuthenticated(requestContext, resolved) {
23
+ applyObservabilityUser({ id: resolved.user.id });
22
24
  options.onAuthenticated?.({
23
25
  user: resolved.user,
24
26
  session: resolved.session,
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack.js","names":["logger"],"sources":["../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/resolve-failure.ts","../src/infrastructure/tanstack/http-error-response.ts","../src/infrastructure/tanstack/session-cookies.ts","../src/infrastructure/tanstack/to-error-payload.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/function-tracing.middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nimport type { RequestContext } from './request-context.ts'\n\nconst logger = createLogger('auth-middleware')\n\n/** The fields middleware reads; generic callers retain every additional session and user field. */\nexport type AuthSession = {\n readonly user: { readonly id: string }\n readonly session: { readonly id: string }\n}\n\n/** Authenticated context retains the application's complete user and session types. */\nexport type RequiredAuthContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n}\n\n/** Optional authentication supplies both fields together or neither field. */\nexport type AuthContext<Session extends AuthSession> =\n | RequiredAuthContext<Session>\n | {\n readonly user: undefined\n readonly session: undefined\n }\n\n/** A resolved session and the request context that produced it. */\nexport type AuthenticatedContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n readonly requestContext: RequestContext\n}\n\n/** Select the current request's Better Auth instance from TanStack's registered context. */\nexport type AuthMiddlewareOptions<Session extends AuthSession> = {\n readonly getAuth: (context: RequestContext) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n /** Runs after a session resolves and before the handler. A guest or a failed lookup does not call it. */\n readonly onAuthenticated?: (context: AuthenticatedContext<Session>) => void\n}\n\n// The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily inside `.server()`.\nconst requestHeaders = async () => {\n const { getRequestHeaders } = await import('@tanstack/react-start/server')\n return getRequestHeaders()\n}\n\n/**\n * Preserve Porte's function and request middleware contracts with application-owned services.\n * Optional lookup failures log once and continue as guests. Required lookup failures propagate.\n * `onAuthenticated` runs after a session resolves and before the rest of the chain.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n function notifyAuthenticated(requestContext: RequestContext, resolved: Session): void {\n options.onAuthenticated?.({\n user: resolved.user,\n session: resolved.session,\n requestContext,\n })\n }\n const extractAuth = createMiddleware({ type: 'function' }).server<AuthContext<Session>>(\n async ({ next, context }) => {\n let resolved: Session | null\n try {\n const headers = await requestHeaders()\n resolved = await options.getAuth(context).api.getSession({ headers })\n } catch (error) {\n logger.error('get_session_failed', { error })\n resolved = null\n }\n if (resolved === null)\n return next<AuthContext<Session>>({ context: { user: undefined, session: undefined } })\n notifyAuthenticated(context, resolved)\n return next<AuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n\n async function resolveRequiredSession(\n context: RequestContext,\n headers: Headers,\n ): Promise<Session> {\n const resolved = await options.getAuth(context).api.getSession({ headers })\n if (resolved === null) {\n if (getSessionCookie(headers)) throw new StaleSessionError()\n throw new AuthenticationError()\n }\n return resolved\n }\n\n const requireAuth = createMiddleware({ type: 'function' }).server(async ({ next, context }) => {\n const resolved = await resolveRequiredSession(context, await requestHeaders())\n notifyAuthenticated(context, resolved)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n })\n const requireAuthRequest = createMiddleware({ type: 'request' }).server(\n async ({ request, next, context }) => {\n const resolved = await resolveRequiredSession(context, request.headers)\n notifyAuthenticated(context, resolved)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { z } from 'zod'\n\nimport {\n AppError,\n ValidationError,\n createLogger,\n type ErrorTable,\n type ResolvedError,\n} from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\n\n// TanStack serializes a validator's issues into `Error.message` as JSON.\nconst SerializedIssuesSchema = z\n .array(z.object({ message: z.string(), path: z.array(z.union([z.string(), z.number()])) }))\n .min(1)\n\n// A live ZodError keeps `.issues`. TanStack leaves only JSON in `Error.message`.\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (cause instanceof z.ZodError) return ValidationError.fromZod(cause)\n if (!(cause instanceof Error)) return null\n let message: unknown\n try {\n message = JSON.parse(cause.message)\n } catch {\n return null\n }\n const parsed = SerializedIssuesSchema.safeParse(message)\n return parsed.success ? ValidationError.fromIssues(parsed.data) : null\n}\n\n/**\n * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * A thrown ZodError, or issues serialized into an error message, becomes a ValidationError first.\n * Both transport converters call this, so one rule decides the log level: mapped is a warning, unmapped is an error with the cause.\n */\nexport function resolveFailure<Entries>(\n table: ErrorTable<Entries>,\n cause: unknown,\n): ResolvedError<ErrorPayloadOf<ErrorTable<Entries>>> {\n const failure = reconstructValidationError(cause) ?? cause\n const resolved = table.resolve(failure)\n if (resolved !== null) {\n logger.warn('handled_error', {\n tag: resolved.payload._tag,\n status: resolved.status,\n })\n return resolved\n }\n const classification = failure instanceof AppError ? failure.classification : 'unknown'\n logger.error('unexpected_error', { error: failure, classification })\n return table.fallback(failure)\n}\n","import { getReasonPhrase } from 'http-status-codes'\nimport { z } from 'zod'\n\nimport type { ErrorTable, ProblemDetails } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// A known delay becomes the header; a null delay sends no header.\nconst RetryAfterSchema = z.object({ retryAfter: z.number() })\n\n/**\n * Build the API route converter for one error table.\n * The body is RFC 9457 problem details; public fields become extension members.\n */\nexport function createHttpErrorResponseConverter<Entries>(table: ErrorTable<Entries>) {\n return function toHttpErrorResponse(cause: unknown): Response {\n const { status, payload } = resolveFailure(table, cause)\n const { _tag, message, ...fields } = payload\n const body: ProblemDetails = {\n type: 'about:blank',\n title: getReasonPhrase(status),\n detail: message,\n ...fields,\n }\n const headers = new Headers({ 'Content-Type': 'application/problem+json' })\n const retry = RetryAfterSchema.safeParse(payload)\n if (retry.success) headers.set('Retry-After', String(retry.data.retryAfter))\n return Response.json(body, { status, headers })\n }\n}\n","import type { deleteCookie } from '@tanstack/react-start/server'\nimport type { BetterAuthCookies } from 'better-auth'\nimport { parseCookies } from 'better-auth/cookies'\n\ntype AuthCookie = BetterAuthCookies['sessionToken']\ntype DeleteCookieOptions = NonNullable<Parameters<typeof deleteCookie>[1]>\n\n/**\n * Delete the session, session cache, account cache, and remember-me cookies of one instance.\n * Chunks present on the request go too. Names and attributes come from the instance, so custom prefixes and domain cookies clear.\n */\nexport async function clearStaleSessionCookies(cookies: BetterAuthCookies): Promise<void> {\n // The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily here.\n const server = await import('@tanstack/react-start/server')\n const present = [...parseCookies(server.getRequestHeaders().get('cookie') ?? '').keys()]\n const definitions = [\n cookies.sessionToken,\n cookies.sessionData,\n cookies.accountData,\n cookies.dontRememberToken,\n ]\n for (const cookie of definitions) {\n // Better Auth names a chunk `${name}.${index}`, so a missed chunk would resurrect the value.\n const chunks = present.filter((name) => name.startsWith(`${cookie.name}.`))\n for (const name of new Set([cookie.name, ...chunks]))\n server.deleteCookie(name, deletionOf(cookie.attributes))\n }\n}\n\nfunction deletionOf(attributes: AuthCookie['attributes']): DeleteCookieOptions {\n // Better Auth sets `/` and the secure flag at runtime; the types leave both optional.\n const options: DeleteCookieOptions = {\n path: attributes.path ?? '/',\n secure: attributes.secure ?? false,\n }\n if (attributes.domain !== undefined) options.domain = attributes.domain\n return options\n}\n","import type { ErrorPayloadOf, ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n/**\n * Build the server-function converter for one error table.\n * The result is a plain object, because only own data survives serialization.\n */\nexport function createErrorPayloadConverter<Entries>(table: ErrorTable<Entries>) {\n return function toErrorPayload(cause: unknown): ErrorPayloadOf<ErrorTable<Entries>> {\n return resolveFailure(table, cause).payload\n }\n}\n","import { isNotFound, isRedirect, redirect } from '@tanstack/react-router'\nimport { createMiddleware } from '@tanstack/react-start'\nimport type { BetterAuthCookies } from 'better-auth'\n\nimport { StaleSessionError, type ErrorTable } from '@/core'\n\nimport { createHttpErrorResponseConverter } from './http-error-response.ts'\nimport type { RequestContext } from './request-context.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\n\n/** The part of a Better Auth instance the boundary reads: its computed cookie definitions. */\nexport type AuthCookieSource = {\n readonly $context: Promise<{ readonly authCookies: BetterAuthCookies }>\n}\n\n/** The application's error table, its stale-session redirect, and its Better Auth instance. */\nexport type ErrorMiddlewareOptions<Entries> = {\n readonly errors: ErrorTable<Entries>\n /** The path a server function redirects to for a stale session, with any search string. */\n readonly signIn: string\n /** Select the request's Better Auth instance; its cookie definitions say what to clear. */\n readonly getAuth: (context: RequestContext) => AuthCookieSource\n}\n\n/**\n * Build both transport boundaries from one error table.\n * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.\n */\nexport function createErrorMiddleware<Entries>(options: ErrorMiddlewareOptions<Entries>) {\n const toErrorPayload = createErrorPayloadConverter(options.errors)\n const toHttpErrorResponse = createHttpErrorResponseConverter(options.errors)\n\n async function clearSession(context: RequestContext): Promise<void> {\n const { authCookies } = await options.getAuth(context).$context\n await clearStaleSessionCookies(authCookies)\n }\n\n async function handleFunctionError(cause: unknown, context: RequestContext): Promise<never> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) {\n await clearSession(context)\n // oxlint-disable-next-line typescript/only-throw-error -- Router redirects by throwing this.\n throw redirect({ href: options.signIn })\n }\n // oxlint-disable-next-line typescript/only-throw-error -- The client rejects with this and reads its tag.\n throw toErrorPayload(cause)\n }\n\n // A route answers 401 instead of a redirect because fetch would follow it into the HTML shell.\n async function handleRouteError(cause: unknown, context: RequestContext): Promise<Response> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) await clearSession(context)\n return toHttpErrorResponse(cause)\n }\n\n const functionErrorMiddleware = createMiddleware({ type: 'function' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleFunctionError(cause, context)\n }\n },\n )\n\n const routeErrorMiddleware = createMiddleware({ type: 'request' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleRouteError(cause, context)\n }\n },\n )\n\n return { functionErrorMiddleware, routeErrorMiddleware, toErrorPayload, toHttpErrorResponse }\n}\n","import { createMiddleware } from '@tanstack/react-start'\n\nimport { withSpan } from '../cloudflare/tracing.ts'\nimport type { RequestContext } from './request-context.ts'\n\n/**\n * Run one server function call in a child span named for that function.\n * Ported from Suparelay `tracing.middleware.ts`. `getTracing` runs on each request.\n * A handler rejection is not a span exception, and this middleware does not log.\n */\nexport function createFunctionTracingMiddleware(getTracing: (context: RequestContext) => Tracing) {\n return createMiddleware({ type: 'function' }).server(({ context, serverFnMeta, next }) =>\n withSpan(\n getTracing(context),\n `server_fn ${serverFnMeta.name}`,\n {\n 'code.function.name': serverFnMeta.name,\n 'code.file.path': serverFnMeta.filename,\n },\n () => next(),\n ),\n )\n}\n"],"mappings":";;;;;;;;;AAOA,MAAMA,WAAS,aAAa,iBAAiB;A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EAAgB;CAAoB;AAC9F;;;;;;;;;ACrEA,SAAgB,gCAAgC,YAAkD;CAChG,OAAO,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,QAAQ,EAAE,SAAS,cAAc,WAC7E,SACE,WAAW,OAAO,GAClB,aAAa,aAAa,QAC1B;EACE,sBAAsB,aAAa;EACnC,kBAAkB,aAAa;CACjC,SACM,KAAK,CACb,CACF;AACF"}
1
+ {"version":3,"file":"tanstack.js","names":["logger"],"sources":["../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/resolve-failure.ts","../src/infrastructure/tanstack/http-error-response.ts","../src/infrastructure/tanstack/session-cookies.ts","../src/infrastructure/tanstack/to-error-payload.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/function-tracing.middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nimport { applyObservabilityUser } from '../../application/request-user.ts'\nimport type { RequestContext } from './request-context.ts'\n\nconst logger = createLogger('auth-middleware')\n\n/** The fields middleware reads; generic callers retain every additional session and user field. */\nexport type AuthSession = {\n readonly user: { readonly id: string }\n readonly session: { readonly id: string }\n}\n\n/** Authenticated context retains the application's complete user and session types. */\nexport type RequiredAuthContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n}\n\n/** Optional authentication supplies both fields together or neither field. */\nexport type AuthContext<Session extends AuthSession> =\n | RequiredAuthContext<Session>\n | {\n readonly user: undefined\n readonly session: undefined\n }\n\n/** A resolved session and the request context that produced it. */\nexport type AuthenticatedContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n readonly requestContext: RequestContext\n}\n\n/** Select the current request's Better Auth instance from TanStack's registered context. */\nexport type AuthMiddlewareOptions<Session extends AuthSession> = {\n readonly getAuth: (context: RequestContext) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n /** Runs after a session resolves and before the handler. A guest or a failed lookup does not call it. */\n readonly onAuthenticated?: (context: AuthenticatedContext<Session>) => void\n}\n\n// The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily inside `.server()`.\nconst requestHeaders = async () => {\n const { getRequestHeaders } = await import('@tanstack/react-start/server')\n return getRequestHeaders()\n}\n\n/**\n * Preserve Porte's function and request middleware contracts with application-owned services.\n * Optional lookup failures log once and continue as guests. Required lookup failures propagate.\n * A resolved session applies `{ id }` on the observability hook, then runs `onAuthenticated`, before the handler.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n function notifyAuthenticated(requestContext: RequestContext, resolved: Session): void {\n applyObservabilityUser({ id: resolved.user.id })\n options.onAuthenticated?.({\n user: resolved.user,\n session: resolved.session,\n requestContext,\n })\n }\n const extractAuth = createMiddleware({ type: 'function' }).server<AuthContext<Session>>(\n async ({ next, context }) => {\n let resolved: Session | null\n try {\n const headers = await requestHeaders()\n resolved = await options.getAuth(context).api.getSession({ headers })\n } catch (error) {\n logger.error('get_session_failed', { error })\n resolved = null\n }\n if (resolved === null)\n return next<AuthContext<Session>>({ context: { user: undefined, session: undefined } })\n notifyAuthenticated(context, resolved)\n return next<AuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n\n async function resolveRequiredSession(\n context: RequestContext,\n headers: Headers,\n ): Promise<Session> {\n const resolved = await options.getAuth(context).api.getSession({ headers })\n if (resolved === null) {\n if (getSessionCookie(headers)) throw new StaleSessionError()\n throw new AuthenticationError()\n }\n return resolved\n }\n\n const requireAuth = createMiddleware({ type: 'function' }).server(async ({ next, context }) => {\n const resolved = await resolveRequiredSession(context, await requestHeaders())\n notifyAuthenticated(context, resolved)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n })\n const requireAuthRequest = createMiddleware({ type: 'request' }).server(\n async ({ request, next, context }) => {\n const resolved = await resolveRequiredSession(context, request.headers)\n notifyAuthenticated(context, resolved)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { z } from 'zod'\n\nimport {\n AppError,\n ValidationError,\n createLogger,\n type ErrorTable,\n type ResolvedError,\n} from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\n\n// TanStack serializes a validator's issues into `Error.message` as JSON.\nconst SerializedIssuesSchema = z\n .array(z.object({ message: z.string(), path: z.array(z.union([z.string(), z.number()])) }))\n .min(1)\n\n// A live ZodError keeps `.issues`. TanStack leaves only JSON in `Error.message`.\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (cause instanceof z.ZodError) return ValidationError.fromZod(cause)\n if (!(cause instanceof Error)) return null\n let message: unknown\n try {\n message = JSON.parse(cause.message)\n } catch {\n return null\n }\n const parsed = SerializedIssuesSchema.safeParse(message)\n return parsed.success ? ValidationError.fromIssues(parsed.data) : null\n}\n\n/**\n * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * A thrown ZodError, or issues serialized into an error message, becomes a ValidationError first.\n * Both transport converters call this, so one rule decides the log level: mapped is a warning, unmapped is an error with the cause.\n */\nexport function resolveFailure<Entries>(\n table: ErrorTable<Entries>,\n cause: unknown,\n): ResolvedError<ErrorPayloadOf<ErrorTable<Entries>>> {\n const failure = reconstructValidationError(cause) ?? cause\n const resolved = table.resolve(failure)\n if (resolved !== null) {\n logger.warn('handled_error', {\n tag: resolved.payload._tag,\n status: resolved.status,\n })\n return resolved\n }\n const classification = failure instanceof AppError ? failure.classification : 'unknown'\n logger.error('unexpected_error', { error: failure, classification })\n return table.fallback(failure)\n}\n","import { getReasonPhrase } from 'http-status-codes'\nimport { z } from 'zod'\n\nimport type { ErrorTable, ProblemDetails } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// A known delay becomes the header; a null delay sends no header.\nconst RetryAfterSchema = z.object({ retryAfter: z.number() })\n\n/**\n * Build the API route converter for one error table.\n * The body is RFC 9457 problem details; public fields become extension members.\n */\nexport function createHttpErrorResponseConverter<Entries>(table: ErrorTable<Entries>) {\n return function toHttpErrorResponse(cause: unknown): Response {\n const { status, payload } = resolveFailure(table, cause)\n const { _tag, message, ...fields } = payload\n const body: ProblemDetails = {\n type: 'about:blank',\n title: getReasonPhrase(status),\n detail: message,\n ...fields,\n }\n const headers = new Headers({ 'Content-Type': 'application/problem+json' })\n const retry = RetryAfterSchema.safeParse(payload)\n if (retry.success) headers.set('Retry-After', String(retry.data.retryAfter))\n return Response.json(body, { status, headers })\n }\n}\n","import type { deleteCookie } from '@tanstack/react-start/server'\nimport type { BetterAuthCookies } from 'better-auth'\nimport { parseCookies } from 'better-auth/cookies'\n\ntype AuthCookie = BetterAuthCookies['sessionToken']\ntype DeleteCookieOptions = NonNullable<Parameters<typeof deleteCookie>[1]>\n\n/**\n * Delete the session, session cache, account cache, and remember-me cookies of one instance.\n * Chunks present on the request go too. Names and attributes come from the instance, so custom prefixes and domain cookies clear.\n */\nexport async function clearStaleSessionCookies(cookies: BetterAuthCookies): Promise<void> {\n // The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily here.\n const server = await import('@tanstack/react-start/server')\n const present = [...parseCookies(server.getRequestHeaders().get('cookie') ?? '').keys()]\n const definitions = [\n cookies.sessionToken,\n cookies.sessionData,\n cookies.accountData,\n cookies.dontRememberToken,\n ]\n for (const cookie of definitions) {\n // Better Auth names a chunk `${name}.${index}`, so a missed chunk would resurrect the value.\n const chunks = present.filter((name) => name.startsWith(`${cookie.name}.`))\n for (const name of new Set([cookie.name, ...chunks]))\n server.deleteCookie(name, deletionOf(cookie.attributes))\n }\n}\n\nfunction deletionOf(attributes: AuthCookie['attributes']): DeleteCookieOptions {\n // Better Auth sets `/` and the secure flag at runtime; the types leave both optional.\n const options: DeleteCookieOptions = {\n path: attributes.path ?? '/',\n secure: attributes.secure ?? false,\n }\n if (attributes.domain !== undefined) options.domain = attributes.domain\n return options\n}\n","import type { ErrorPayloadOf, ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n/**\n * Build the server-function converter for one error table.\n * The result is a plain object, because only own data survives serialization.\n */\nexport function createErrorPayloadConverter<Entries>(table: ErrorTable<Entries>) {\n return function toErrorPayload(cause: unknown): ErrorPayloadOf<ErrorTable<Entries>> {\n return resolveFailure(table, cause).payload\n }\n}\n","import { isNotFound, isRedirect, redirect } from '@tanstack/react-router'\nimport { createMiddleware } from '@tanstack/react-start'\nimport type { BetterAuthCookies } from 'better-auth'\n\nimport { StaleSessionError, type ErrorTable } from '@/core'\n\nimport { createHttpErrorResponseConverter } from './http-error-response.ts'\nimport type { RequestContext } from './request-context.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\n\n/** The part of a Better Auth instance the boundary reads: its computed cookie definitions. */\nexport type AuthCookieSource = {\n readonly $context: Promise<{ readonly authCookies: BetterAuthCookies }>\n}\n\n/** The application's error table, its stale-session redirect, and its Better Auth instance. */\nexport type ErrorMiddlewareOptions<Entries> = {\n readonly errors: ErrorTable<Entries>\n /** The path a server function redirects to for a stale session, with any search string. */\n readonly signIn: string\n /** Select the request's Better Auth instance; its cookie definitions say what to clear. */\n readonly getAuth: (context: RequestContext) => AuthCookieSource\n}\n\n/**\n * Build both transport boundaries from one error table.\n * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.\n */\nexport function createErrorMiddleware<Entries>(options: ErrorMiddlewareOptions<Entries>) {\n const toErrorPayload = createErrorPayloadConverter(options.errors)\n const toHttpErrorResponse = createHttpErrorResponseConverter(options.errors)\n\n async function clearSession(context: RequestContext): Promise<void> {\n const { authCookies } = await options.getAuth(context).$context\n await clearStaleSessionCookies(authCookies)\n }\n\n async function handleFunctionError(cause: unknown, context: RequestContext): Promise<never> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) {\n await clearSession(context)\n // oxlint-disable-next-line typescript/only-throw-error -- Router redirects by throwing this.\n throw redirect({ href: options.signIn })\n }\n // oxlint-disable-next-line typescript/only-throw-error -- The client rejects with this and reads its tag.\n throw toErrorPayload(cause)\n }\n\n // A route answers 401 instead of a redirect because fetch would follow it into the HTML shell.\n async function handleRouteError(cause: unknown, context: RequestContext): Promise<Response> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) await clearSession(context)\n return toHttpErrorResponse(cause)\n }\n\n const functionErrorMiddleware = createMiddleware({ type: 'function' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleFunctionError(cause, context)\n }\n },\n )\n\n const routeErrorMiddleware = createMiddleware({ type: 'request' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleRouteError(cause, context)\n }\n },\n )\n\n return { functionErrorMiddleware, routeErrorMiddleware, toErrorPayload, toHttpErrorResponse }\n}\n","import { createMiddleware } from '@tanstack/react-start'\n\nimport { withSpan } from '../cloudflare/tracing.ts'\nimport type { RequestContext } from './request-context.ts'\n\n/**\n * Run one server function call in a child span named for that function.\n * Ported from Suparelay `tracing.middleware.ts`. `getTracing` runs on each request.\n * A handler rejection is not a span exception, and this middleware does not log.\n */\nexport function createFunctionTracingMiddleware(getTracing: (context: RequestContext) => Tracing) {\n return createMiddleware({ type: 'function' }).server(({ context, serverFnMeta, next }) =>\n withSpan(\n getTracing(context),\n `server_fn ${serverFnMeta.name}`,\n {\n 'code.function.name': serverFnMeta.name,\n 'code.file.path': serverFnMeta.filename,\n },\n () => next(),\n ),\n )\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAMA,WAAS,aAAa,iBAAiB;AAyC7C,MAAM,iBAAiB,YAAY;CAC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xC;EACF,CAGmD;EAAG;EAAgB;CAAoB;AAC9F;;;;;;;;;ACrEA,SAAgB,gCAAgC,YAAkD;CAChG,OAAO,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,QAAQ,EAAE,SAAS,cAAc,WAC7E,SACE,WAAW,OAAO,GAClB,aAAa,aAAa,QAC1B;EACE,sBAAsB,aAAa;EACnC,kBAAkB,aAAa;CACjC,SACM,KAAK,CACb,CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { W as DomainEvent } from "../index-DUFS0SJ_.js";
2
- import { A as IOutboxRepository } from "../index-CbvNd665.js";
2
+ import { A as IOutboxRepository } from "../index-BosM_da2.js";
3
3
  //#region src/infrastructure/testing/outbox-repository-contract.d.ts
4
4
  /** Stored fields observed by the adapter contract, independent of a database library. */
5
5
  export type OutboxContractRow = {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://www.schemastore.org/package.json",
3
3
  "name": "better-ship",
4
- "version": "0.35.1",
4
+ "version": "0.37.0",
5
5
  "description": "Foundation for applications on Cloudflare Workers: logger, errors, message bus, infrastructure adapters, and UI primitives",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -31,6 +31,7 @@
31
31
  "./browser-support/oxlint": "./dist/browser-support/oxlint.js",
32
32
  "./browser-support/polyfills": "./dist/browser-support/polyfills.js",
33
33
  "./browser-support/update-screen": "./dist/browser-support/update-screen.js",
34
+ "./browser-user": "./dist/browser-user.js",
34
35
  "./cloudflare": "./dist/cloudflare.js",
35
36
  "./cloudflare/auth-secondary-storage": "./dist/cloudflare/auth-secondary-storage.js",
36
37
  "./cloudflare/durable-object-client": "./dist/cloudflare/durable-object-client.js",
@@ -64,6 +65,7 @@
64
65
  "./stripe/payment-webhook": "./dist/stripe/payment-webhook.js",
65
66
  "./stripe/request": "./dist/stripe/request.js",
66
67
  "./tanstack": "./dist/tanstack.js",
68
+ "./tanstack/oxlint": "./dist/tanstack/oxlint.js",
67
69
  "./tanstack/server": "./dist/tanstack/server.js",
68
70
  "./testing/outbox-repository": "./dist/testing/outbox-repository.js",
69
71
  "./testing/payment-service": "./dist/testing/payment-service.js",
@@ -90,6 +92,8 @@
90
92
  "@sentry/cloudflare": "^11.6.0",
91
93
  "@sentry/tanstackstart-react": "^11.6.0",
92
94
  "@tailwindcss/node": "^4.3.3",
95
+ "@tanstack/react-form": "^1.33.5",
96
+ "@tanstack/react-query": "^5.104.1",
93
97
  "@tanstack/react-router": "^1.170.41",
94
98
  "@tanstack/react-start": "^1.168.60",
95
99
  "@tanstack/start-client-core": "^1.170.34",
@@ -12,6 +12,7 @@ export type {
12
12
  ObservabilityScope,
13
13
  ObservabilityUser,
14
14
  } from './observability-service.ts'
15
+ export { applyObservabilityUser, setObservabilityUserHook } from './request-user.ts'
15
16
  export {
16
17
  RecordingEmailService,
17
18
  type IEmailService,
@@ -0,0 +1,18 @@
1
+ import type { ObservabilityUser } from './observability-service.ts'
2
+
3
+ /**
4
+ * Process-wide request user hook.
5
+ * The Sentry server entry sets it once. Auth middleware calls it after a session resolves.
6
+ * The hook does not store a user id. The adapter writes the id on the current isolation scope.
7
+ */
8
+ let observabilityUserHook: ((user: ObservabilityUser) => void) | null = null
9
+
10
+ /** Set or clear the process-wide request user hook. */
11
+ export function setObservabilityUserHook(hook: ((user: ObservabilityUser) => void) | null): void {
12
+ observabilityUserHook = hook
13
+ }
14
+
15
+ /** Attribute the current execution to this user. No hook means the call does nothing. */
16
+ export function applyObservabilityUser(user: ObservabilityUser): void {
17
+ observabilityUserHook?.(user)
18
+ }
@@ -0,0 +1,24 @@
1
+ import * as Sentry from '@sentry/tanstackstart-react'
2
+ import { posthog } from 'posthog-js'
3
+
4
+ /**
5
+ * Identify the signed-in user in PostHog and Sentry.
6
+ * Sends the id only. A client that is not initialized does nothing.
7
+ * Call it when the session user id is present. A loading session does not call it.
8
+ */
9
+ export function identifyObservabilityUser(userId: string): void {
10
+ // identify() warns when the SDK is not loaded. A disabled client must stay silent.
11
+ // oxlint-disable-next-line no-underscore-dangle -- PostHog's public loaded flag. There is no other initialized check.
12
+ if (posthog.__loaded) posthog.identify(userId)
13
+ if (Sentry.isEnabled()) Sentry.setUser({ id: userId })
14
+ }
15
+
16
+ /**
17
+ * Clear the Sentry user and reset PostHog on sign-out.
18
+ * A disabled client does nothing. Call this once from the application's sign-out path.
19
+ */
20
+ export function clearObservabilityUser(): void {
21
+ // oxlint-disable-next-line no-underscore-dangle -- Same loaded flag as identifyObservabilityUser.
22
+ if (posthog.__loaded) posthog.reset()
23
+ if (Sentry.isEnabled()) Sentry.setUser(null)
24
+ }
@@ -3,6 +3,8 @@ import * as Sentry from '@sentry/cloudflare'
3
3
  import type { ObservabilityScope, ObservabilityService, ObservabilityUser } from '@/application'
4
4
  import type { LoggerErrorHook } from '@/core'
5
5
 
6
+ import { setObservabilityUserHook } from '../../application/request-user.ts'
7
+
6
8
  /** Application-owned deployment settings with the full Cloudflare SDK option contract. */
7
9
  export type SentryServerOptions = Sentry.CloudflareOptions & {
8
10
  readonly dsn: string
@@ -10,8 +12,16 @@ export type SentryServerOptions = Sentry.CloudflareOptions & {
10
12
  readonly enabled: boolean
11
13
  }
12
14
 
13
- /** Pass application options to Workers, Durable Objects, and Workflows with the SDK defaults. */
15
+ /**
16
+ * Pass application options to Workers, Durable Objects, and Workflows with the SDK defaults.
17
+ * Registers the request user hook so auth middleware can set `{ id }` on the current isolation scope.
18
+ */
14
19
  export function createSentryOptions(options: SentryServerOptions): Sentry.CloudflareOptions {
20
+ // Auth middleware cannot import this SDK. The hook writes `{ id }` only when Sentry is enabled.
21
+ setObservabilityUserHook((user) => {
22
+ if (!Sentry.isEnabled()) return
23
+ Sentry.setUser({ id: user.id })
24
+ })
15
25
  return options
16
26
  }
17
27
 
@@ -3,6 +3,7 @@ import { getSessionCookie } from 'better-auth/cookies'
3
3
 
4
4
  import { AuthenticationError, StaleSessionError, createLogger } from '@/core'
5
5
 
6
+ import { applyObservabilityUser } from '../../application/request-user.ts'
6
7
  import type { RequestContext } from './request-context.ts'
7
8
 
8
9
  const logger = createLogger('auth-middleware')
@@ -54,12 +55,13 @@ const requestHeaders = async () => {
54
55
  /**
55
56
  * Preserve Porte's function and request middleware contracts with application-owned services.
56
57
  * Optional lookup failures log once and continue as guests. Required lookup failures propagate.
57
- * `onAuthenticated` runs after a session resolves and before the rest of the chain.
58
+ * A resolved session applies `{ id }` on the observability hook, then runs `onAuthenticated`, before the handler.
58
59
  */
59
60
  export function createAuthMiddleware<Session extends AuthSession>(
60
61
  options: AuthMiddlewareOptions<Session>,
61
62
  ) {
62
63
  function notifyAuthenticated(requestContext: RequestContext, resolved: Session): void {
64
+ applyObservabilityUser({ id: resolved.user.id })
63
65
  options.onAuthenticated?.({
64
66
  user: resolved.user,
65
67
  session: resolved.session,
@@ -0,0 +1,58 @@
1
+ import type { ESTree, SourceCode } from '@oxlint/plugins'
2
+
3
+ const FORM_HOOKS = new Set(['useForm', 'useAppForm'])
4
+ const SAFETY = /(?:^|[^\p{L}\p{N}_])SAFETY\s*:\s*\S/u
5
+
6
+ /** The options object of a `useForm({ … })` or `useAppForm({ … })` call. */
7
+ export function formOptions(node: ESTree.CallExpression): ESTree.ObjectExpression | null {
8
+ if (node.callee.type !== 'Identifier' || !FORM_HOOKS.has(node.callee.name)) return null
9
+ const [options] = node.arguments
10
+ return options?.type === 'ObjectExpression' ? options : null
11
+ }
12
+
13
+ /** A plain `name: value` property of an object literal. */
14
+ export function propertyNamed(
15
+ object: ESTree.ObjectExpression,
16
+ name: string,
17
+ ): ESTree.ObjectProperty | null {
18
+ for (const property of object.properties) {
19
+ if (property.type !== 'Property' || property.computed) continue
20
+ const key = property.key
21
+ if (key.type === 'Identifier' && key.name === name) return property
22
+ if (key.type === 'Literal' && key.value === name) return property
23
+ }
24
+ return null
25
+ }
26
+
27
+ /** A `// SAFETY:` comment directly before the node allows one exception. */
28
+ export function hasSafetyComment(sourceCode: SourceCode, node: ESTree.Node): boolean {
29
+ return sourceCode.getCommentsBefore(node).some((comment) => SAFETY.test(comment.value))
30
+ }
31
+
32
+ /** Every node under `root`. Parent links are not followed. */
33
+ export function* descendants(root: ESTree.Node): Generator<ESTree.Node> {
34
+ for (const [key, value] of Object.entries(root)) {
35
+ if (key === 'parent') continue
36
+ const children = Array.isArray(value) ? value : [value]
37
+ for (const child of children) {
38
+ if (isAstNode(child)) {
39
+ yield child
40
+ yield* descendants(child)
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ type AstChild =
47
+ | { type?: string; start?: number }
48
+ | string
49
+ | number
50
+ | boolean
51
+ | bigint
52
+ | symbol
53
+ | null
54
+ | undefined
55
+
56
+ function isAstNode(value: AstChild): value is ESTree.Node {
57
+ return value instanceof Object && 'type' in value && 'start' in value
58
+ }
@@ -0,0 +1,57 @@
1
+ import { defineRule } from '@oxlint/plugins'
2
+
3
+ import { formOptions, hasSafetyComment, propertyNamed } from './form-options.ts'
4
+
5
+ const DYNAMIC_SLOTS = new Set(['onDynamic', 'onDynamicAsync'])
6
+
7
+ /**
8
+ * Require one named schema on `useForm` and `useAppForm`.
9
+ * `validationLogic` must call `revalidateLogic`. The schema sits on `validators.onDynamic`.
10
+ * A `// SAFETY:` comment before the call allows one form.
11
+ */
12
+ export const formSchemaValidatorsRule = defineRule({
13
+ meta: {
14
+ type: 'problem',
15
+ docs: {
16
+ description:
17
+ 'Require `validationLogic: revalidateLogic(…)` and `validators: { onDynamic: Schema }` on every TanStack form.',
18
+ },
19
+ messages: {
20
+ logic:
21
+ 'Choose the timing with validationLogic: revalidateLogic({ mode, modeAfterSubmission }).',
22
+ missing: 'Validate the form with one schema: validators: { onDynamic: Schema }.',
23
+ slot: 'Replace {{slot}} with onDynamic; revalidateLogic sets the timing.',
24
+ inline: 'Pass a schema, not a function: validators: { onDynamic: Schema }.',
25
+ },
26
+ },
27
+ createOnce(context) {
28
+ return {
29
+ CallExpression(node) {
30
+ const options = formOptions(node)
31
+ if (options === null || hasSafetyComment(context.sourceCode, node)) return
32
+ const logic = propertyNamed(options, 'validationLogic')
33
+ if (
34
+ logic === null ||
35
+ logic.value.type !== 'CallExpression' ||
36
+ logic.value.callee.type !== 'Identifier' ||
37
+ logic.value.callee.name !== 'revalidateLogic'
38
+ ) {
39
+ context.report({ node: logic ?? node, messageId: 'logic' })
40
+ }
41
+ const validators = propertyNamed(options, 'validators')
42
+ if (validators === null || validators.value.type !== 'ObjectExpression') {
43
+ context.report({ node: validators ?? node, messageId: 'missing' })
44
+ return
45
+ }
46
+ for (const slot of validators.value.properties) {
47
+ if (slot.type !== 'Property' || slot.key.type !== 'Identifier') continue
48
+ if (!DYNAMIC_SLOTS.has(slot.key.name)) {
49
+ context.report({ node: slot, messageId: 'slot', data: { slot: slot.key.name } })
50
+ } else if (slot.value.type !== 'Identifier' && slot.value.type !== 'MemberExpression') {
51
+ context.report({ node: slot.value, messageId: 'inline' })
52
+ }
53
+ }
54
+ },
55
+ }
56
+ },
57
+ })
@@ -0,0 +1,46 @@
1
+ import { defineRule } from '@oxlint/plugins'
2
+ import type { ESTree } from '@oxlint/plugins'
3
+
4
+ import { descendants, formOptions, propertyNamed } from './form-options.ts'
5
+
6
+ /** A call whose result changes between renders, such as the current time or a random id. */
7
+ function isUnstable(node: ESTree.Node): boolean {
8
+ if (node.type === 'NewExpression') {
9
+ return node.callee.type === 'Identifier' && node.callee.name === 'Date'
10
+ }
11
+ if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression') return false
12
+ const { object, property } = node.callee
13
+ if (object.type !== 'Identifier' || property.type !== 'Identifier') return false
14
+ return (
15
+ (object.name === 'Date' && property.name === 'now') ||
16
+ (object.name === 'Math' && property.name === 'random') ||
17
+ (object.name === 'crypto' && property.name === 'randomUUID')
18
+ )
19
+ }
20
+
21
+ /**
22
+ * Reject a time or random value written inside `defaultValues`.
23
+ * TanStack Form applies a changed default to an untouched form on the next render.
24
+ */
25
+ export const formStableDefaultValuesRule = defineRule({
26
+ meta: {
27
+ type: 'problem',
28
+ docs: { description: 'Disallow time or random values computed inline in `defaultValues`.' },
29
+ messages: {
30
+ unstable:
31
+ 'Compute this default once with useState(() => …) or a module constant; an inline value resets the form on render.',
32
+ },
33
+ },
34
+ createOnce(context) {
35
+ return {
36
+ CallExpression(node) {
37
+ const options = formOptions(node)
38
+ const defaults = options === null ? null : propertyNamed(options, 'defaultValues')
39
+ if (defaults === null) return
40
+ for (const child of [defaults.value, ...descendants(defaults.value)]) {
41
+ if (isUnstable(child)) context.report({ node: child, messageId: 'unstable' })
42
+ }
43
+ },
44
+ }
45
+ },
46
+ })
@@ -0,0 +1,25 @@
1
+ import { eslintCompatPlugin } from '@oxlint/plugins'
2
+
3
+ import { formSchemaValidatorsRule } from './form-schema-validators.ts'
4
+ import { formStableDefaultValuesRule } from './form-stable-default-values.ts'
5
+ import { noFieldValidatorsRule } from './no-field-validators.ts'
6
+ import { noSubmitBranchingRule } from './no-submit-branching.ts'
7
+ import { queryKeyFromFactoryRule } from './query-key-from-factory.ts'
8
+
9
+ /**
10
+ * Oxlint plugin for TanStack Form and Query.
11
+ * Enable the `tanstack/*` rules from `jsPlugins`.
12
+ * Ported from Suparelay `packages/tanstack-lint`. The rule ids are unchanged.
13
+ */
14
+ const tanstackPlugin = eslintCompatPlugin({
15
+ meta: { name: 'tanstack' },
16
+ rules: {
17
+ 'form-schema-validators': formSchemaValidatorsRule,
18
+ 'form-stable-default-values': formStableDefaultValuesRule,
19
+ 'no-field-validators': noFieldValidatorsRule,
20
+ 'no-submit-branching': noSubmitBranchingRule,
21
+ 'query-key-from-factory': queryKeyFromFactoryRule,
22
+ },
23
+ })
24
+
25
+ export default tanstackPlugin
@@ -0,0 +1,40 @@
1
+ import { defineRule } from '@oxlint/plugins'
2
+
3
+ import { propertyNamed } from './form-options.ts'
4
+
5
+ const FIELD_COMPONENTS = new Set(['Field', 'AppField'])
6
+
7
+ /** Reject field-level `validators`. The form schema is the only validation source. */
8
+ export const noFieldValidatorsRule = defineRule({
9
+ meta: {
10
+ type: 'problem',
11
+ docs: { description: 'Disallow field-level `validators`; the form schema validates.' },
12
+ messages: {
13
+ fieldValidators: 'Remove validators from the field. Put the rule in the form schema.',
14
+ },
15
+ },
16
+ createOnce(context) {
17
+ return {
18
+ JSXOpeningElement(node) {
19
+ if (node.name.type !== 'JSXMemberExpression') return
20
+ if (!FIELD_COMPONENTS.has(node.name.property.name)) return
21
+ for (const attribute of node.attributes) {
22
+ if (
23
+ attribute.type === 'JSXAttribute' &&
24
+ attribute.name.type === 'JSXIdentifier' &&
25
+ attribute.name.name === 'validators'
26
+ ) {
27
+ context.report({ node: attribute, messageId: 'fieldValidators' })
28
+ }
29
+ }
30
+ },
31
+ CallExpression(node) {
32
+ if (node.callee.type !== 'Identifier' || node.callee.name !== 'useField') return
33
+ const [options] = node.arguments
34
+ if (options?.type !== 'ObjectExpression') return
35
+ const validators = propertyNamed(options, 'validators')
36
+ if (validators !== null) context.report({ node: validators, messageId: 'fieldValidators' })
37
+ },
38
+ }
39
+ },
40
+ })
@@ -0,0 +1,38 @@
1
+ import { defineRule } from '@oxlint/plugins'
2
+ import type { ESTree } from '@oxlint/plugins'
3
+
4
+ import { descendants, formOptions, hasSafetyComment, propertyNamed } from './form-options.ts'
5
+
6
+ const BRANCH_OPERATORS = new Set(['??', '||', '&&'])
7
+
8
+ function isBranch(node: ESTree.Node): boolean {
9
+ if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') return true
10
+ return node.type === 'LogicalExpression' && BRANCH_OPERATORS.has(node.operator)
11
+ }
12
+
13
+ /**
14
+ * Reject a condition inside `onSubmit`.
15
+ * The schema already accepted the values. A `// SAFETY:` comment on `onSubmit` allows one check.
16
+ */
17
+ export const noSubmitBranchingRule = defineRule({
18
+ meta: {
19
+ type: 'problem',
20
+ docs: { description: "Disallow conditions in a TanStack form's `onSubmit`." },
21
+ messages: {
22
+ branch:
23
+ 'Move this check into the form schema. Use Schema.parse(value) when the submitted type must be narrowed.',
24
+ },
25
+ },
26
+ createOnce(context) {
27
+ return {
28
+ CallExpression(node) {
29
+ const options = formOptions(node)
30
+ const submit = options === null ? null : propertyNamed(options, 'onSubmit')
31
+ if (submit === null || hasSafetyComment(context.sourceCode, submit)) return
32
+ for (const child of descendants(submit.value)) {
33
+ if (isBranch(child)) context.report({ node: child, messageId: 'branch' })
34
+ }
35
+ },
36
+ }
37
+ },
38
+ })
@@ -0,0 +1,36 @@
1
+ import { defineRule } from '@oxlint/plugins'
2
+
3
+ const CACHE_METHODS = new Set(['getQueryData', 'setQueryData', 'getQueryState', 'ensureQueryData'])
4
+
5
+ /**
6
+ * Reject a query key array written outside a `*-queries.ts` factory.
7
+ * Invalidation then reads the same key the factory stored.
8
+ */
9
+ export const queryKeyFromFactoryRule = defineRule({
10
+ meta: {
11
+ type: 'problem',
12
+ docs: { description: 'Disallow query key arrays outside `*-queries.ts` factory files.' },
13
+ messages: {
14
+ literal:
15
+ "Read this key from the entity's query factory, for example entityQueries.lists() or entityQueries.detail(input).queryKey.",
16
+ },
17
+ },
18
+ createOnce(context) {
19
+ const inFactory = () => context.filename.endsWith('-queries.ts')
20
+ return {
21
+ Property(node) {
22
+ if (inFactory() || node.computed || node.key.type !== 'Identifier') return
23
+ if (node.key.name === 'queryKey' && node.value.type === 'ArrayExpression') {
24
+ context.report({ node: node.value, messageId: 'literal' })
25
+ }
26
+ },
27
+ CallExpression(node) {
28
+ if (inFactory() || node.callee.type !== 'MemberExpression') return
29
+ const method = node.callee.property
30
+ if (method.type !== 'Identifier' || !CACHE_METHODS.has(method.name)) return
31
+ const [key] = node.arguments
32
+ if (key?.type === 'ArrayExpression') context.report({ node: key, messageId: 'literal' })
33
+ },
34
+ }
35
+ },
36
+ })
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-CbvNd665.d.ts","names":[],"sources":["../src/application/handlers.ts","../src/application/analytics-service.ts","../src/application/metrics-service.ts","../src/application/observability-service.ts","../src/application/email-service.ts","../src/application/event-collector.ts","../src/application/message-store.ts","../src/application/outbox-repository.ts","../src/application/outbox-relay.ts","../src/application/transaction.ts","../src/application/unit-of-work.ts","../src/application/record-email-event.ts","../src/application/registry.ts","../src/application/message-bus.ts","../src/application/outbox-retention.ts","../src/application/message-already-processed.error.ts","../src/application/unit-of-work.errors.ts"],"mappings":";;;;;;KAMY,eAAe,iBAAiB,eAAe,MAAM,UAC/D,SAAS,UACT,MAAM,SACH,QAAQ;;;;;KAMD,aAAa,eAAe,aAAa,WAAW,UAC9D,OAAO,QACP,MAAM,cACH,QAAQ;;KAGD,aAAa,eAAe,aAAa,SACnD,OAAO,QACP,MAAM,SACH;;;;UCrBY,iBAAiB,eAAe,sBAAsB;;EAErE,SAAS,oBAAoB,aAAa;;EAE1C,MAAM,oBAAoB;;EAE1B,MAAM,OAAO,QAAQ,oBAAoB,WAAW;;EAEpD,eAAe,OAAO,QAAQ,oBAAoB,WAAW;;;cAIlD,gBAAgB;;;;KCdjB;;KAGA,mBAAmB,SAAS,eAAe;;UAGtC;WACN,aAAa;WACb;;;UAIM,eAAe;;EAE9B,MAAM,MAAM,OAAO,gBAAgB,UAAU;;EAE7C,MAAM,MAAM,OAAO,eAAe,UAAU;;EAE5C,UAAU,MAAM,OAAO,eAAe,UAAU;;;cAIrC,sBAAsB;;;;UCtBlB;WACN;;;UAIM;;EAEf,QAAQ,MAAM;;;UAIC,6BAA6B;;EAE5C,mBAAmB,GAAG,WAAW,OAAO,uBAAuB,IAAI,QAAQ,KAAK,QAAQ;;;;;KCX9E;;KAGA;WACD;WACA,kBAAkB;;WAElB,cAAc;;;;;;;KAQb;;WAED;WACA;WACA;WACA;;WAEA,iBAAiB;;WAEjB;WACA;;WAEA,OAAO,SAAS;WAChB,uBAAuB;;;KAItB;WAA2B,SAAS,SAAS;;;KAG7C;WACD;WACA;WACA;WACA;WACA;;;KAIC;;WAED;WACA;WACA,sBAAsB;;;KAIrB;WAA2B;;;;;;UAMtB;;EAEf,UAAU,OAAO,gBAAgB,QAAQ;;;cAI9B,iCAAiC;;WAEnC,MAAM;;E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