@reliantlabs/forge-web-runtime 0.12.0 → 0.13.2
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/README.md +51 -0
- package/dist/benign-errors.d.ts +33 -0
- package/dist/benign-errors.js +115 -0
- package/dist/benign-errors.js.map +1 -0
- package/dist/client-context.d.ts +35 -0
- package/dist/client-context.js +204 -0
- package/dist/client-context.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/interceptors.js +10 -3
- package/dist/interceptors.js.map +1 -1
- package/dist/mock-transport.d.ts +41 -5
- package/dist/mock-transport.js +125 -7
- package/dist/mock-transport.js.map +1 -1
- package/dist/node.js +10 -0
- package/dist/node.js.map +1 -1
- package/dist/resource.d.ts +62 -3
- package/dist/resource.js +96 -17
- package/dist/resource.js.map +1 -1
- package/dist/service-hooks.js +8 -6
- package/dist/service-hooks.js.map +1 -1
- package/dist/session-cookie-fallback.d.ts +23 -0
- package/dist/session-cookie-fallback.js +203 -0
- package/dist/session-cookie-fallback.js.map +1 -0
- package/dist/telemetry-gate.d.ts +4 -0
- package/dist/telemetry-gate.js +25 -0
- package/dist/telemetry-gate.js.map +1 -1
- package/dist/telemetry.d.ts +29 -2
- package/dist/telemetry.js +370 -17
- package/dist/telemetry.js.map +1 -1
- package/dist/trace.d.ts +7 -0
- package/dist/trace.js +21 -2
- package/dist/trace.js.map +1 -1
- package/package.json +4 -2
package/dist/service-hooks.js
CHANGED
|
@@ -29,12 +29,14 @@
|
|
|
29
29
|
// an engine with its own dependency footprint gets its own entry point, and
|
|
30
30
|
// React Query is an OPTIONAL peer.
|
|
31
31
|
//
|
|
32
|
-
// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts —
|
|
33
|
-
// app-wide MutationCache
|
|
34
|
-
//
|
|
35
|
-
// `meta: { silenceErrorToast: true }
|
|
36
|
-
//
|
|
37
|
-
//
|
|
32
|
+
// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — they
|
|
33
|
+
// belong to one app-wide chokepoint, a MutationCache onError on the app's
|
|
34
|
+
// QueryClient (a forge scaffold installs it in src/lib/query-client.ts, and
|
|
35
|
+
// pages that render errors inline pass `meta: { silenceErrorToast: true }`);
|
|
36
|
+
// an app without one handles errors at the call site. It never defaults
|
|
37
|
+
// success-side UX either: "CreateOrder succeeded" leaks RPC names into the
|
|
38
|
+
// UI, so the toast / redirect / inline confirmation stays the call site's via
|
|
39
|
+
// options.onSuccess.
|
|
38
40
|
import { create, toJson, } from "@bufbuild/protobuf";
|
|
39
41
|
import { infiniteQueryOptions, queryOptions, useInfiniteQuery, useMutation, useQuery, useQueryClient, } from "@tanstack/react-query";
|
|
40
42
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-hooks.js","sourceRoot":"","sources":["../src/service-hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,sEAAsE;AACtE,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,uEAAuE;AACvE,6EAA6E;AAC7E,+EAA+E;AAC/E,yEAAyE;AACzE,gEAAgE;AAChE,EAAE;AACF,8EAA8E;AAC9E,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,qEAAqE;AACrE,qEAAqE;AACrE,+EAA+E;AAC/E,4EAA4E;AAC5E,8EAA8E;AAC9E,sEAAsE;AACtE,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,sEAAsE;AACtE,wEAAwE;AACxE,6EAA6E;AAC7E,4EAA4E;AAC5E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,8EAA8E;AAC9E,uDAAuD;AACvD,yEAAyE;AACzE,8EAA8E;AAC9E,8EAA8E;AAC9E,OAAO,EACL,MAAM,EACN,MAAM,GAGP,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,Q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AE,CACjC,IAAI,CACF,CAAC,SAAS,KAAK,EAAE;YACf,CAAC,CAAC,GAAG;YACL,CAAC,CAAC;gBACE,GAAG,GAAG;gBACN,SAAS,EAAE,SAAS;aACrB,CAAwC,EAC7C,MAAM,CACP;QACH,gBAAgB,EAAE,EAAE;KACrB,CAAiD,CAAC;AACvD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAIrC,UAAgE;IAEhE,OAAO,CACL,GAAwB,EACxB,OAAoD,EACpD,EAAE,CAAC,gBAAgB,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,aAA8B,EAC9B,IAA0D;IAE1D,OAAO,CACL,OAOC,EACD,EAAE;QACF,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7C,OAAO,WAAW,CAKhB;YACA,UAAU,EAAE,CAAC,GAA6B,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE;gBACrB,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC,CAAC;gBAC3D,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,GAAG,IAAI;SACR,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Every export below is a React hook or builds one, so this module belongs in\n// the CLIENT graph. Without the directive the Next.js App Router compiles it\n// into the SERVER graph, where it binds a SECOND @tanstack/react-query\n// instance and every generated hook throws \"No QueryClient set\" at runtime —\n// invisible to tsc, eslint AND `next build`. published-surface.test.ts asserts\n// the directive survives into dist/. It is NOT applied package-wide: the\n// ./interceptors subpath exists to be importable without React.\n//\n// The React Query wrapper machinery behind forge's generated per-service hook\n// files (`src/hooks/<svc>-service-hooks_gen.ts`).\n//\n// WHAT WAS HERE BEFORE. Each generated file re-emitted the same three things\n// per RPC: a query-key entry, a useQuery or useMutation wrapper, and — for\n// mutations — the entity-scoped invalidateQueries plus the onSuccess\n// composition, with the reasoning for each re-inlined as comments. A\n// five-service project rendered five copies of machinery that differed only in\n// RPC names and message types. This module IS that machinery, written once.\n// The generated file keeps exactly what varies per RPC: the name, the request\n// schema, the response type, query-vs-mutation, and the entity scope.\n//\n// WHY A SUBPATH AND NOT THE BARREL. This module imports @tanstack/react-query.\n// Every browser frontend forge scaffolds depends on it — but the barrel is\n// also what a consumer imports for interceptors and errors alone, and\n// anchoring React Query there would make a non-React consumer resolve a\n// package it never installed. Same reasoning as ./mock-transport and ./otel:\n// an engine with its own dependency footprint gets its own entry point, and\n// React Query is an OPTIONAL peer.\n//\n// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — the\n// app-wide MutationCache in src/lib/query-client.ts is the single error-toast\n// chokepoint, and pages that render errors inline pass\n// `meta: { silenceErrorToast: true }`. It never defaults success-side UX\n// either: \"CreateOrder succeeded\" leaks RPC names into the UI, so the toast /\n// redirect / inline confirmation stays the call site's via options.onSuccess.\nimport {\n create,\n toJson,\n type DescMessage,\n type MessageInitShape,\n} from \"@bufbuild/protobuf\";\nimport {\n infiniteQueryOptions,\n queryOptions,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type DataTag,\n type InfiniteData,\n type UseInfiniteQueryOptions,\n type UseInfiniteQueryResult,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\nimport type { ConnectClientError } from \"./errors.js\";\n\n/**\n * A generated query key. The tuple is [service, entity?, method,\n * protojson(req)] for a method key and [service] / [service, entity] for the\n * broader scopes.\n */\nexport type ServiceQueryKey = readonly unknown[];\n\n/**\n * requestKey projects a request init into protojson for use inside a query\n * key. Two reasons this is not the raw request object:\n *\n * - React Query's default hasher is JSON.stringify, which THROWS on bigint\n * fields (any proto int64) — the raw message crashes the cache.\n * - protojson normalizes representations, so { id: 1 } and { id: \"1\" } land\n * in ONE cache entry instead of silently splitting the cache.\n *\n * Exported because a hand-written hook that wants to share a generated hook's\n * cache entry has to hash its request the identical way.\n */\nexport function requestKey<Schema extends DescMessage>(\n schema: Schema,\n req: MessageInitShape<Schema>,\n): unknown {\n return toJson(schema, create(schema, req));\n}\n\n/**\n * One read's key entry in a generated factory: `orderServiceKeys.getOrder`.\n *\n * Called, it is that request's key, [service, entity?, method,\n * protojson(req)]. Its `.all` is the rpc's scope, [service, entity?,\n * method]: a prefix of every key the rpc caches under — every request, the\n * plain query and the `<method>Infinite` read alike — and of no other rpc's.\n *\n * queryClient.invalidateQueries({ queryKey: orderServiceKeys.listOrders.all })\n * queryClient.setQueriesData({ queryKey: orderServiceKeys.getOrder.all }, patch)\n *\n * It exists so code never names a key's tuple positions. A predicate like\n * `query.queryKey[1] === \"listOrders\"` breaks silently when a\n * `// forge:query-scope` marker inserts the entity at index 1; `.all` is\n * built by the same function that builds the keys, so it moves with them.\n *\n * `.all` is not data-tagged. It names a SET of entries, and for a paged\n * read that set holds two shapes (the response, and the infinite read's\n * `{ pages, pageParams }`), so a `setQueriesData` updater over it must\n * handle both.\n */\nexport type ServiceMethodKey<Schema extends DescMessage> = ((\n req: MessageInitShape<Schema>,\n) => ServiceQueryKey) & {\n /** Every cached request of this rpc: [service, entity?, method]. */\n readonly all: ServiceQueryKey;\n};\n\n/** The three key-scope builders a generated key factory is assembled from. */\nexport interface ServiceKeyBuilders {\n /** Every query on this service: [service]. */\n readonly all: readonly [string];\n /** Every query for one CRUD entity: [service, entity]. Mutations invalidate this. */\n entity(name: string): readonly [string, string];\n /**\n * One query: [service, entity?, method, protojson(req)]. Returns the\n * per-request key FUNCTION, which is what both the query hook and any\n * call-site prefetch/setQueryData use, with the rpc's scope\n * [service, entity?, method] on it as `.all` (ServiceMethodKey).\n */\n query<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): ServiceMethodKey<Schema>;\n /**\n * One paged read: [service, entity?, method, protojson(req), \"infinite\"],\n * where req is the request WITHOUT its page token — the hook owns the\n * token, so every page of one listing shares one cache entry.\n *\n * It nests under the same scopes as `query`, so an entity or service-wide\n * invalidation refetches it. The \"infinite\" suffix keeps it OFF the plain\n * query's entry for the same request: an infinite query caches\n * `{ pages, pageParams }`, not one response, and a plain hook reading that\n * entry would get the wrong shape.\n */\n infinite<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: PageRequest<Schema>) => ServiceQueryKey;\n}\n\n/**\n * Omit distributed over a union. MessageInitShape is `Message | init\n * object`, and a plain Omit over a union keeps only the keys both members\n * share — which would silently drop every field from the init side.\n */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * The request a generated infinite hook takes: the rpc's request without\n * `pageToken`, which the hook supplies page by page.\n */\nexport type PageRequest<Schema extends DescMessage> = DistributiveOmit<\n MessageInitShape<Schema>,\n \"pageToken\"\n>;\n\n/**\n * The response shape forge's list-pagination convention (AIP-158) gives a\n * paged read: `string next_page_token`, empty on the last page. Optional so\n * an `optional string next_page_token` response satisfies it too.\n */\nexport interface PagedResponse {\n nextPageToken?: string;\n}\n\n/**\n * pageRequestKey is requestKey with the page token dropped, so every page of\n * one listing hashes to one key even when a caller (JS, or a cast) passes a\n * token anyway. It is dropped from the protojson rather than from the init\n * object: a spread Message keeps its $typeName, and create() would hand that\n * token-less copy back as if it were a complete message.\n */\nfunction pageRequestKey<Schema extends DescMessage>(\n schema: Schema,\n req: PageRequest<Schema>,\n): unknown {\n const json = requestKey(schema, req as unknown as MessageInitShape<Schema>);\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n return json;\n }\n const { pageToken: _pageToken, ...rest } = json as Record<string, unknown>;\n return rest;\n}\n\n/**\n * serviceKeys returns the builders for one service's query-key factory.\n *\n * Cache-key semantics are a compatibility contract, not an implementation\n * detail: an existing app's\n * `invalidateQueries({ queryKey: orderServiceKeys.order })` has to keep\n * matching the keys its queries were registered under across a version bump.\n * So the tuple order and contents produced here are fixed, and identical to\n * what forge previously inlined into every generated hook file.\n */\nexport function serviceKeys(service: string): ServiceKeyBuilders {\n // The rpc scope every key below starts with. Both builders derive their\n // keys from it, so `.all` is a prefix of them by construction, not by a\n // second copy of the tuple layout.\n const rpcScope = (method: string, entityScope?: string): ServiceQueryKey =>\n entityScope === undefined\n ? ([service, method] as const)\n : ([service, entityScope, method] as const);\n return {\n all: [service] as const,\n entity: (name: string) => [service, name] as const,\n query: <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): ServiceMethodKey<Schema> => {\n const all = rpcScope(method, entityScope);\n return Object.assign(\n (req: MessageInitShape<Schema>): ServiceQueryKey => [\n ...all,\n requestKey(schema, req),\n ],\n { all },\n );\n },\n infinite:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: PageRequest<Schema>): ServiceQueryKey => [\n ...rpcScope(method, entityScope),\n pageRequestKey(schema, req),\n \"infinite\",\n ],\n };\n}\n\n/**\n * How a generated file calls one rpc. `signal` is React Query's: a query\n * that is unmounted or superseded (a new key while typing) aborts its\n * request instead of letting it land on a cache entry nobody reads.\n */\nexport type ServiceCall<Schema extends DescMessage, Response> = (\n req: MessageInitShape<Schema>,\n signal?: AbortSignal,\n) => Promise<Response>;\n\n/**\n * The options a generated read takes — its hook (`useGetOrder(req,\n * options?)`) and its query-options builder\n * (`orderServiceQueries.getOrder(req, options?)`) alike: React Query's own,\n * minus the two the read owns, the key and the fetch. Everything else\n * (`select`, `enabled`, `staleTime`, `placeholderData`, …) passes through.\n *\n * TData is what `data` is, exactly as in React Query's own useQuery: the\n * response by default, or whatever `select` returns. A call site mapping the\n * proto response to a view model passes `select: (r) => toView(r)` and gets\n * `data: View` — no useMemo over `data`, and React Query re-runs the mapping\n * only when the response changes (or when `select` itself does, so hoist it\n * or wrap it in useCallback when it is expensive).\n */\nexport type ServiceQueryInput<Response, TData = Response> = Partial<\n Omit<\n UseQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey>,\n \"queryKey\" | \"queryFn\"\n >\n>;\n\n/**\n * What a query-options builder returns: TanStack's `queryOptions(...)`\n * result, so it goes anywhere React Query takes one —\n * `queryClient.fetchQuery`, `ensureQueryData`, `prefetchQuery`,\n * `useQueries({ queries })`, `useQuery`, `useSuspenseQuery`. Its `queryKey`\n * is data-tagged, so `queryClient.getQueryData(opts.queryKey)` and\n * `setQueryData` are typed as the response with no annotation.\n *\n * fetchQuery / ensureQueryData resolve to the RESPONSE, not to `select`'s\n * TData: they return what the cache holds, and `select` is an observer\n * option that only a hook or useQueries applies.\n */\nexport type ServiceQueryOptions<Response, TData = Response> = UseQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey\n> & {\n queryKey: DataTag<ServiceQueryKey, Response, ConnectClientError>;\n};\n\n/**\n * A generated query-options builder: `orderServiceQueries.getOrder(req,\n * options?)`. It is the read's single definition — the generated hook\n * `useGetOrder` is `useQuery` over exactly this — so code outside React (an\n * imperative action, a stream handler, a router loader, a prefetch) shares\n * the hook's cache entry and fetch by construction rather than by copying\n * its key and its client call.\n */\nexport type ServiceQueryOptionsBuilder<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n) => ServiceQueryOptions<Response, TData>;\n\n/**\n * A generated query hook: `useGetOrder(req, options?)` — `useQuery` over the\n * service's query-options builder for the same rpc. TData is inferred from\n * `select` and is a parameter of the HOOK, not of the factory, so every call\n * site picks its own.\n */\nexport type ServiceQueryHook<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n) => UseQueryResult<TData, ConnectClientError>;\n\n/**\n * The options a generated infinite read takes: React Query's own, minus the\n * three the read owns — the key, the fetch, and the first page param.\n * `getNextPageParam` defaults to the response's `nextPageToken` (empty means\n * last page) and may be overridden; everything else (`select`,\n * `placeholderData`, `staleTime`, `enabled`, `maxPages`, …) passes through.\n */\nexport type ServiceInfiniteQueryInput<Response, TData> = Partial<\n Omit<\n UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >,\n \"queryKey\" | \"queryFn\" | \"initialPageParam\"\n >\n>;\n\n/**\n * What an infinite query-options builder returns: TanStack's\n * `infiniteQueryOptions(...)` result, for `queryClient.fetchInfiniteQuery`,\n * `prefetchInfiniteQuery`, `ensureInfiniteQueryData` and\n * `useInfiniteQuery`. Its key is data-tagged as `InfiniteData<Response,\n * string>`, the `{ pages, pageParams }` the cache holds.\n */\nexport type ServiceInfiniteQueryOptions<\n Response,\n TData = InfiniteData<Response, string>,\n> = UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n> & {\n queryKey: DataTag<\n ServiceQueryKey,\n InfiniteData<Response, string>,\n ConnectClientError\n >;\n};\n\n/**\n * A generated infinite query-options builder:\n * `orderServiceQueries.listOrdersInfinite(req, options?)`, for a read that\n * follows forge's list-pagination shape. `useListOrdersInfinite` is\n * `useInfiniteQuery` over exactly this.\n */\nexport type ServiceInfiniteQueryOptionsBuilder<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n) => ServiceInfiniteQueryOptions<Response, TData>;\n\n/**\n * A generated infinite-query hook: `useListOrdersInfinite(req, options?)`,\n * for a read that follows forge's list-pagination shape (`string page_token`\n * on the request, `string next_page_token` on the response).\n *\n * `req` is the first page's request without its token. `data` is React\n * Query's `{ pages, pageParams }` by default; `select` reshapes it, so\n * flattening the pages into one list is\n * `select: (d) => d.pages.flatMap((p) => p.orders)`.\n */\nexport type ServiceInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n) => UseInfiniteQueryResult<TData, ConnectClientError>;\n\n/**\n * A generated mutation hook: `useCreateOrder(options?)`.\n *\n * TContext is React Query's fourth type parameter — what `onMutate` returns\n * and `onError` / `onSettled` receive back. It is a parameter of the HOOK,\n * not of the factory, so each call site gets its own: TypeScript infers it\n * from the `onMutate` the caller passes, and an optimistic update reads its\n * rollback off `context` with no cast. Fixing it at the factory (or leaving\n * it out, which pinned it to `unknown`) forced every such call site to\n * narrow `unknown` by hand. It defaults to `unknown`, so a call without\n * `onMutate` types exactly as before.\n */\nexport type ServiceMutationHook<Schema extends DescMessage, Response> = <\n TContext = unknown,\n>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n) => UseMutationResult<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n>;\n\n/**\n * createQueryOptions builds one read's query-options builder — the single\n * definition of its cache key and its fetch that the generated hook, and\n * every caller outside React, share.\n *\n * The error is typed as ConnectClientError rather than React Query's default\n * `Error`, on the options themselves, because React Query takes a result's\n * error type from the TError it reads there: `query.error` is a\n * ConnectClientError at every call site with nothing to pass. Typing it as\n * `Error` hid `.reason`, `.codeName`, `.status` and `.retryable`, and left\n * `err.message.includes(...)` as the only expression that compiled — the one\n * thing the error contract forbids.\n *\n * The caller's options are spread BEFORE the key and the fetch: a caller may\n * set anything else, never the two that make this read this read.\n */\nexport function createQueryOptions<Schema extends DescMessage, Response>(\n keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceQueryOptionsBuilder<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n ): ServiceQueryOptions<Response, TData> =>\n queryOptions<Response, ConnectClientError, TData, ServiceQueryKey>({\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ signal }) => call(req, signal),\n }) as ServiceQueryOptions<Response, TData>;\n}\n\n/**\n * createQueryHook builds one useQuery wrapper over a read's query-options\n * builder. It adds nothing to the options: a hook and a `fetchQuery` of the\n * same request therefore read and write one cache entry with one fetch.\n */\nexport function createQueryHook<Schema extends DescMessage, Response>(\n optionsFor: ServiceQueryOptionsBuilder<Schema, Response>,\n): ServiceQueryHook<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n ) => useQuery(optionsFor(req, options));\n}\n\n/**\n * createInfiniteQueryOptions builds one paged read's infinite query-options\n * builder.\n *\n * The page token is the builder's: the first page is fetched with the\n * caller's request as given (no token, so an `optional string page_token`\n * stays unset), each later one with the previous response's\n * `nextPageToken`, and an empty token ends the listing. The key is\n * `keys.infinite(...)`, which strips the token and sits under the service and\n * entity scopes, so the mutations that invalidate a plain list refetch this\n * one too.\n *\n * The caller's options are spread BETWEEN the default getNextPageParam and\n * the three fields the read owns: a caller may replace the default, never the\n * key, the fetch or the first page.\n */\nexport function createInfiniteQueryOptions<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n keyFor: (req: PageRequest<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceInfiniteQueryOptionsBuilder<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n ): ServiceInfiniteQueryOptions<Response, TData> =>\n infiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >({\n getNextPageParam: (last) => last.nextPageToken || undefined,\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ pageParam, signal }) =>\n call(\n (pageParam === \"\"\n ? req\n : {\n ...req,\n pageToken: pageParam,\n }) as unknown as MessageInitShape<Schema>,\n signal,\n ),\n initialPageParam: \"\",\n }) as ServiceInfiniteQueryOptions<Response, TData>;\n}\n\n/**\n * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged\n * read's infinite query-options builder, adding nothing to it — so a hook\n * and a `fetchInfiniteQuery` of the same request share one cache entry.\n */\nexport function createInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n optionsFor: ServiceInfiniteQueryOptionsBuilder<Schema, Response>,\n): ServiceInfiniteQueryHook<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n ) => useInfiniteQuery(optionsFor(req, options));\n}\n\n/**\n * createMutationHook builds one useMutation wrapper with scoped invalidation.\n *\n * invalidateKey is the entity scope when the RPC maps to a CRUD entity, and\n * the whole-service scope otherwise — a bespoke mutation may touch anything,\n * so over-invalidating is the safe default there.\n *\n * The invalidation is composed BEFORE the caller's onSuccess and is never\n * replaced by it: onSuccess is destructured out and re-invoked after the\n * invalidate, while the rest of the options object is spread separately. A\n * caller passing onSuccess therefore ADDS behaviour, rather than silently\n * disabling the cache refresh — which is exactly what a plain `...options`\n * spread over a default onSuccess would do.\n */\nexport function createMutationHook<Schema extends DescMessage, Response>(\n invalidateKey: ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceMutationHook<Schema, Response> {\n return <TContext = unknown>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n ) => {\n const queryClient = useQueryClient();\n const { onSuccess, ...rest } = options ?? {};\n return useMutation<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >({\n mutationFn: (req: MessageInitShape<Schema>) => call(req),\n onSuccess: (...args) => {\n queryClient.invalidateQueries({ queryKey: invalidateKey });\n onSuccess?.(...args);\n },\n ...rest,\n });\n };\n}\n"]}
|
|
1
|
+
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EAC9B,IAA0D;IAE1D,OAAO,CACL,OAOC,EACD,EAAE;QACF,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7C,OAAO,WAAW,CAKhB;YACA,UAAU,EAAE,CAAC,GAA6B,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE;gBACrB,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC,CAAC;gBAC3D,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,GAAG,IAAI;SACR,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Every export below is a React hook or builds one, so this module belongs in\n// the CLIENT graph. Without the directive the Next.js App Router compiles it\n// into the SERVER graph, where it binds a SECOND @tanstack/react-query\n// instance and every generated hook throws \"No QueryClient set\" at runtime —\n// invisible to tsc, eslint AND `next build`. published-surface.test.ts asserts\n// the directive survives into dist/. It is NOT applied package-wide: the\n// ./interceptors subpath exists to be importable without React.\n//\n// The React Query wrapper machinery behind forge's generated per-service hook\n// files (`src/hooks/<svc>-service-hooks_gen.ts`).\n//\n// WHAT WAS HERE BEFORE. Each generated file re-emitted the same three things\n// per RPC: a query-key entry, a useQuery or useMutation wrapper, and — for\n// mutations — the entity-scoped invalidateQueries plus the onSuccess\n// composition, with the reasoning for each re-inlined as comments. A\n// five-service project rendered five copies of machinery that differed only in\n// RPC names and message types. This module IS that machinery, written once.\n// The generated file keeps exactly what varies per RPC: the name, the request\n// schema, the response type, query-vs-mutation, and the entity scope.\n//\n// WHY A SUBPATH AND NOT THE BARREL. This module imports @tanstack/react-query.\n// Every browser frontend forge scaffolds depends on it — but the barrel is\n// also what a consumer imports for interceptors and errors alone, and\n// anchoring React Query there would make a non-React consumer resolve a\n// package it never installed. Same reasoning as ./mock-transport and ./otel:\n// an engine with its own dependency footprint gets its own entry point, and\n// React Query is an OPTIONAL peer.\n//\n// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — they\n// belong to one app-wide chokepoint, a MutationCache onError on the app's\n// QueryClient (a forge scaffold installs it in src/lib/query-client.ts, and\n// pages that render errors inline pass `meta: { silenceErrorToast: true }`);\n// an app without one handles errors at the call site. It never defaults\n// success-side UX either: \"CreateOrder succeeded\" leaks RPC names into the\n// UI, so the toast / redirect / inline confirmation stays the call site's via\n// options.onSuccess.\nimport {\n create,\n toJson,\n type DescMessage,\n type MessageInitShape,\n} from \"@bufbuild/protobuf\";\nimport {\n infiniteQueryOptions,\n queryOptions,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type DataTag,\n type InfiniteData,\n type UseInfiniteQueryOptions,\n type UseInfiniteQueryResult,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\nimport type { ConnectClientError } from \"./errors.js\";\n\n/**\n * A generated query key. The tuple is [service, entity?, method,\n * protojson(req)] for a method key and [service] / [service, entity] for the\n * broader scopes.\n */\nexport type ServiceQueryKey = readonly unknown[];\n\n/**\n * requestKey projects a request init into protojson for use inside a query\n * key. Two reasons this is not the raw request object:\n *\n * - React Query's default hasher is JSON.stringify, which THROWS on bigint\n * fields (any proto int64) — the raw message crashes the cache.\n * - protojson normalizes representations, so { id: 1 } and { id: \"1\" } land\n * in ONE cache entry instead of silently splitting the cache.\n *\n * Exported because a hand-written hook that wants to share a generated hook's\n * cache entry has to hash its request the identical way.\n */\nexport function requestKey<Schema extends DescMessage>(\n schema: Schema,\n req: MessageInitShape<Schema>,\n): unknown {\n return toJson(schema, create(schema, req));\n}\n\n/**\n * One read's key entry in a generated factory: `orderServiceKeys.getOrder`.\n *\n * Called, it is that request's key, [service, entity?, method,\n * protojson(req)]. Its `.all` is the rpc's scope, [service, entity?,\n * method]: a prefix of every key the rpc caches under — every request, the\n * plain query and the `<method>Infinite` read alike — and of no other rpc's.\n *\n * queryClient.invalidateQueries({ queryKey: orderServiceKeys.listOrders.all })\n * queryClient.setQueriesData({ queryKey: orderServiceKeys.getOrder.all }, patch)\n *\n * It exists so code never names a key's tuple positions. A predicate like\n * `query.queryKey[1] === \"listOrders\"` breaks silently when a\n * `// forge:query-scope` marker inserts the entity at index 1; `.all` is\n * built by the same function that builds the keys, so it moves with them.\n *\n * `.all` is not data-tagged. It names a SET of entries, and for a paged\n * read that set holds two shapes (the response, and the infinite read's\n * `{ pages, pageParams }`), so a `setQueriesData` updater over it must\n * handle both.\n */\nexport type ServiceMethodKey<Schema extends DescMessage> = ((\n req: MessageInitShape<Schema>,\n) => ServiceQueryKey) & {\n /** Every cached request of this rpc: [service, entity?, method]. */\n readonly all: ServiceQueryKey;\n};\n\n/** The three key-scope builders a generated key factory is assembled from. */\nexport interface ServiceKeyBuilders {\n /** Every query on this service: [service]. */\n readonly all: readonly [string];\n /** Every query for one CRUD entity: [service, entity]. Mutations invalidate this. */\n entity(name: string): readonly [string, string];\n /**\n * One query: [service, entity?, method, protojson(req)]. Returns the\n * per-request key FUNCTION, which is what both the query hook and any\n * call-site prefetch/setQueryData use, with the rpc's scope\n * [service, entity?, method] on it as `.all` (ServiceMethodKey).\n */\n query<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): ServiceMethodKey<Schema>;\n /**\n * One paged read: [service, entity?, method, protojson(req), \"infinite\"],\n * where req is the request WITHOUT its page token — the hook owns the\n * token, so every page of one listing shares one cache entry.\n *\n * It nests under the same scopes as `query`, so an entity or service-wide\n * invalidation refetches it. The \"infinite\" suffix keeps it OFF the plain\n * query's entry for the same request: an infinite query caches\n * `{ pages, pageParams }`, not one response, and a plain hook reading that\n * entry would get the wrong shape.\n */\n infinite<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: PageRequest<Schema>) => ServiceQueryKey;\n}\n\n/**\n * Omit distributed over a union. MessageInitShape is `Message | init\n * object`, and a plain Omit over a union keeps only the keys both members\n * share — which would silently drop every field from the init side.\n */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * The request a generated infinite hook takes: the rpc's request without\n * `pageToken`, which the hook supplies page by page.\n */\nexport type PageRequest<Schema extends DescMessage> = DistributiveOmit<\n MessageInitShape<Schema>,\n \"pageToken\"\n>;\n\n/**\n * The response shape forge's list-pagination convention (AIP-158) gives a\n * paged read: `string next_page_token`, empty on the last page. Optional so\n * an `optional string next_page_token` response satisfies it too.\n */\nexport interface PagedResponse {\n nextPageToken?: string;\n}\n\n/**\n * pageRequestKey is requestKey with the page token dropped, so every page of\n * one listing hashes to one key even when a caller (JS, or a cast) passes a\n * token anyway. It is dropped from the protojson rather than from the init\n * object: a spread Message keeps its $typeName, and create() would hand that\n * token-less copy back as if it were a complete message.\n */\nfunction pageRequestKey<Schema extends DescMessage>(\n schema: Schema,\n req: PageRequest<Schema>,\n): unknown {\n const json = requestKey(schema, req as unknown as MessageInitShape<Schema>);\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n return json;\n }\n const { pageToken: _pageToken, ...rest } = json as Record<string, unknown>;\n return rest;\n}\n\n/**\n * serviceKeys returns the builders for one service's query-key factory.\n *\n * Cache-key semantics are a compatibility contract, not an implementation\n * detail: an existing app's\n * `invalidateQueries({ queryKey: orderServiceKeys.order })` has to keep\n * matching the keys its queries were registered under across a version bump.\n * So the tuple order and contents produced here are fixed, and identical to\n * what forge previously inlined into every generated hook file.\n */\nexport function serviceKeys(service: string): ServiceKeyBuilders {\n // The rpc scope every key below starts with. Both builders derive their\n // keys from it, so `.all` is a prefix of them by construction, not by a\n // second copy of the tuple layout.\n const rpcScope = (method: string, entityScope?: string): ServiceQueryKey =>\n entityScope === undefined\n ? ([service, method] as const)\n : ([service, entityScope, method] as const);\n return {\n all: [service] as const,\n entity: (name: string) => [service, name] as const,\n query: <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): ServiceMethodKey<Schema> => {\n const all = rpcScope(method, entityScope);\n return Object.assign(\n (req: MessageInitShape<Schema>): ServiceQueryKey => [\n ...all,\n requestKey(schema, req),\n ],\n { all },\n );\n },\n infinite:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: PageRequest<Schema>): ServiceQueryKey => [\n ...rpcScope(method, entityScope),\n pageRequestKey(schema, req),\n \"infinite\",\n ],\n };\n}\n\n/**\n * How a generated file calls one rpc. `signal` is React Query's: a query\n * that is unmounted or superseded (a new key while typing) aborts its\n * request instead of letting it land on a cache entry nobody reads.\n */\nexport type ServiceCall<Schema extends DescMessage, Response> = (\n req: MessageInitShape<Schema>,\n signal?: AbortSignal,\n) => Promise<Response>;\n\n/**\n * The options a generated read takes — its hook (`useGetOrder(req,\n * options?)`) and its query-options builder\n * (`orderServiceQueries.getOrder(req, options?)`) alike: React Query's own,\n * minus the two the read owns, the key and the fetch. Everything else\n * (`select`, `enabled`, `staleTime`, `placeholderData`, …) passes through.\n *\n * TData is what `data` is, exactly as in React Query's own useQuery: the\n * response by default, or whatever `select` returns. A call site mapping the\n * proto response to a view model passes `select: (r) => toView(r)` and gets\n * `data: View` — no useMemo over `data`, and React Query re-runs the mapping\n * only when the response changes (or when `select` itself does, so hoist it\n * or wrap it in useCallback when it is expensive).\n */\nexport type ServiceQueryInput<Response, TData = Response> = Partial<\n Omit<\n UseQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey>,\n \"queryKey\" | \"queryFn\"\n >\n>;\n\n/**\n * What a query-options builder returns: TanStack's `queryOptions(...)`\n * result, so it goes anywhere React Query takes one —\n * `queryClient.fetchQuery`, `ensureQueryData`, `prefetchQuery`,\n * `useQueries({ queries })`, `useQuery`, `useSuspenseQuery`. Its `queryKey`\n * is data-tagged, so `queryClient.getQueryData(opts.queryKey)` and\n * `setQueryData` are typed as the response with no annotation.\n *\n * fetchQuery / ensureQueryData resolve to the RESPONSE, not to `select`'s\n * TData: they return what the cache holds, and `select` is an observer\n * option that only a hook or useQueries applies.\n */\nexport type ServiceQueryOptions<Response, TData = Response> = UseQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey\n> & {\n queryKey: DataTag<ServiceQueryKey, Response, ConnectClientError>;\n};\n\n/**\n * A generated query-options builder: `orderServiceQueries.getOrder(req,\n * options?)`. It is the read's single definition — the generated hook\n * `useGetOrder` is `useQuery` over exactly this — so code outside React (an\n * imperative action, a stream handler, a router loader, a prefetch) shares\n * the hook's cache entry and fetch by construction rather than by copying\n * its key and its client call.\n */\nexport type ServiceQueryOptionsBuilder<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n) => ServiceQueryOptions<Response, TData>;\n\n/**\n * A generated query hook: `useGetOrder(req, options?)` — `useQuery` over the\n * service's query-options builder for the same rpc. TData is inferred from\n * `select` and is a parameter of the HOOK, not of the factory, so every call\n * site picks its own.\n */\nexport type ServiceQueryHook<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n) => UseQueryResult<TData, ConnectClientError>;\n\n/**\n * The options a generated infinite read takes: React Query's own, minus the\n * three the read owns — the key, the fetch, and the first page param.\n * `getNextPageParam` defaults to the response's `nextPageToken` (empty means\n * last page) and may be overridden; everything else (`select`,\n * `placeholderData`, `staleTime`, `enabled`, `maxPages`, …) passes through.\n */\nexport type ServiceInfiniteQueryInput<Response, TData> = Partial<\n Omit<\n UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >,\n \"queryKey\" | \"queryFn\" | \"initialPageParam\"\n >\n>;\n\n/**\n * What an infinite query-options builder returns: TanStack's\n * `infiniteQueryOptions(...)` result, for `queryClient.fetchInfiniteQuery`,\n * `prefetchInfiniteQuery`, `ensureInfiniteQueryData` and\n * `useInfiniteQuery`. Its key is data-tagged as `InfiniteData<Response,\n * string>`, the `{ pages, pageParams }` the cache holds.\n */\nexport type ServiceInfiniteQueryOptions<\n Response,\n TData = InfiniteData<Response, string>,\n> = UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n> & {\n queryKey: DataTag<\n ServiceQueryKey,\n InfiniteData<Response, string>,\n ConnectClientError\n >;\n};\n\n/**\n * A generated infinite query-options builder:\n * `orderServiceQueries.listOrdersInfinite(req, options?)`, for a read that\n * follows forge's list-pagination shape. `useListOrdersInfinite` is\n * `useInfiniteQuery` over exactly this.\n */\nexport type ServiceInfiniteQueryOptionsBuilder<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n) => ServiceInfiniteQueryOptions<Response, TData>;\n\n/**\n * A generated infinite-query hook: `useListOrdersInfinite(req, options?)`,\n * for a read that follows forge's list-pagination shape (`string page_token`\n * on the request, `string next_page_token` on the response).\n *\n * `req` is the first page's request without its token. `data` is React\n * Query's `{ pages, pageParams }` by default; `select` reshapes it, so\n * flattening the pages into one list is\n * `select: (d) => d.pages.flatMap((p) => p.orders)`.\n */\nexport type ServiceInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n) => UseInfiniteQueryResult<TData, ConnectClientError>;\n\n/**\n * A generated mutation hook: `useCreateOrder(options?)`.\n *\n * TContext is React Query's fourth type parameter — what `onMutate` returns\n * and `onError` / `onSettled` receive back. It is a parameter of the HOOK,\n * not of the factory, so each call site gets its own: TypeScript infers it\n * from the `onMutate` the caller passes, and an optimistic update reads its\n * rollback off `context` with no cast. Fixing it at the factory (or leaving\n * it out, which pinned it to `unknown`) forced every such call site to\n * narrow `unknown` by hand. It defaults to `unknown`, so a call without\n * `onMutate` types exactly as before.\n */\nexport type ServiceMutationHook<Schema extends DescMessage, Response> = <\n TContext = unknown,\n>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n) => UseMutationResult<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n>;\n\n/**\n * createQueryOptions builds one read's query-options builder — the single\n * definition of its cache key and its fetch that the generated hook, and\n * every caller outside React, share.\n *\n * The error is typed as ConnectClientError rather than React Query's default\n * `Error`, on the options themselves, because React Query takes a result's\n * error type from the TError it reads there: `query.error` is a\n * ConnectClientError at every call site with nothing to pass. Typing it as\n * `Error` hid `.reason`, `.codeName`, `.status` and `.retryable`, and left\n * `err.message.includes(...)` as the only expression that compiled — the one\n * thing the error contract forbids.\n *\n * The caller's options are spread BEFORE the key and the fetch: a caller may\n * set anything else, never the two that make this read this read.\n */\nexport function createQueryOptions<Schema extends DescMessage, Response>(\n keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceQueryOptionsBuilder<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n ): ServiceQueryOptions<Response, TData> =>\n queryOptions<Response, ConnectClientError, TData, ServiceQueryKey>({\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ signal }) => call(req, signal),\n }) as ServiceQueryOptions<Response, TData>;\n}\n\n/**\n * createQueryHook builds one useQuery wrapper over a read's query-options\n * builder. It adds nothing to the options: a hook and a `fetchQuery` of the\n * same request therefore read and write one cache entry with one fetch.\n */\nexport function createQueryHook<Schema extends DescMessage, Response>(\n optionsFor: ServiceQueryOptionsBuilder<Schema, Response>,\n): ServiceQueryHook<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n ) => useQuery(optionsFor(req, options));\n}\n\n/**\n * createInfiniteQueryOptions builds one paged read's infinite query-options\n * builder.\n *\n * The page token is the builder's: the first page is fetched with the\n * caller's request as given (no token, so an `optional string page_token`\n * stays unset), each later one with the previous response's\n * `nextPageToken`, and an empty token ends the listing. The key is\n * `keys.infinite(...)`, which strips the token and sits under the service and\n * entity scopes, so the mutations that invalidate a plain list refetch this\n * one too.\n *\n * The caller's options are spread BETWEEN the default getNextPageParam and\n * the three fields the read owns: a caller may replace the default, never the\n * key, the fetch or the first page.\n */\nexport function createInfiniteQueryOptions<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n keyFor: (req: PageRequest<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceInfiniteQueryOptionsBuilder<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n ): ServiceInfiniteQueryOptions<Response, TData> =>\n infiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >({\n getNextPageParam: (last) => last.nextPageToken || undefined,\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ pageParam, signal }) =>\n call(\n (pageParam === \"\"\n ? req\n : {\n ...req,\n pageToken: pageParam,\n }) as unknown as MessageInitShape<Schema>,\n signal,\n ),\n initialPageParam: \"\",\n }) as ServiceInfiniteQueryOptions<Response, TData>;\n}\n\n/**\n * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged\n * read's infinite query-options builder, adding nothing to it — so a hook\n * and a `fetchInfiniteQuery` of the same request share one cache entry.\n */\nexport function createInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n optionsFor: ServiceInfiniteQueryOptionsBuilder<Schema, Response>,\n): ServiceInfiniteQueryHook<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n ) => useInfiniteQuery(optionsFor(req, options));\n}\n\n/**\n * createMutationHook builds one useMutation wrapper with scoped invalidation.\n *\n * invalidateKey is the entity scope when the RPC maps to a CRUD entity, and\n * the whole-service scope otherwise — a bespoke mutation may touch anything,\n * so over-invalidating is the safe default there.\n *\n * The invalidation is composed BEFORE the caller's onSuccess and is never\n * replaced by it: onSuccess is destructured out and re-invoked after the\n * invalidate, while the rest of the options object is spread separately. A\n * caller passing onSuccess therefore ADDS behaviour, rather than silently\n * disabling the cache refresh — which is exactly what a plain `...options`\n * spread over a default onSuccess would do.\n */\nexport function createMutationHook<Schema extends DescMessage, Response>(\n invalidateKey: ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceMutationHook<Schema, Response> {\n return <TContext = unknown>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n ) => {\n const queryClient = useQueryClient();\n const { onSuccess, ...rest } = options ?? {};\n return useMutation<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >({\n mutationFn: (req: MessageInitShape<Schema>) => call(req),\n onSuccess: (...args) => {\n queryClient.invalidateQueries({ queryKey: invalidateKey });\n onSuccess?.(...args);\n },\n ...rest,\n });\n };\n}\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The SDK's session cookie (otel-web COOKIE_NAME). */
|
|
2
|
+
export declare const RUM_SESSION_COOKIE = "__rum_sid";
|
|
3
|
+
/** Where the session cookie is kept when cookies do not persist. */
|
|
4
|
+
export declare const RUM_SESSION_STORAGE_KEY = "forge.rum.session";
|
|
5
|
+
/** The slice of Storage the fallback needs. */
|
|
6
|
+
export interface SessionStore {
|
|
7
|
+
getItem(key: string): string | null;
|
|
8
|
+
setItem(key: string, value: string): void;
|
|
9
|
+
removeItem(key: string): void;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Whether `document.cookie` keeps what is written to it. Writes a short-lived
|
|
13
|
+
* probe cookie, reads it back and removes it.
|
|
14
|
+
*/
|
|
15
|
+
export declare function cookiesPersist(doc: Pick<Document, "cookie">): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Keep the SDK's session cookie in `storage` when `doc` cannot keep cookies.
|
|
18
|
+
* Returns whether the fallback is now in place (it was installed by this call,
|
|
19
|
+
* or already was). Idempotent; never throws.
|
|
20
|
+
*
|
|
21
|
+
* Call it before the SDK initialises: the SDK reads the session at init.
|
|
22
|
+
*/
|
|
23
|
+
export declare function installSessionCookieFallback(doc: Document, storage: SessionStore | null, now?: () => number): boolean;
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.
|
|
2
|
+
//
|
|
3
|
+
// A stable RUM session on an origin that cannot keep cookies.
|
|
4
|
+
//
|
|
5
|
+
// ── Why ──────────────────────────────────────────────────────────────────
|
|
6
|
+
//
|
|
7
|
+
// The HyperDX SDK (its otel-web layer) keeps the session ONLY in a cookie,
|
|
8
|
+
// `__rum_sid`: `{ id, startTime }`, written with `max-age=900` and renewed
|
|
9
|
+
// while the user is active. Every 60 s it reads the cookie back, and when it
|
|
10
|
+
// finds none it mints a new session id. There is no other store and no seam
|
|
11
|
+
// to supply one: the session module is bundled inside the HyperDX browser package.
|
|
12
|
+
//
|
|
13
|
+
// Some origins accept a `document.cookie` write and silently keep nothing.
|
|
14
|
+
// The one that matters is an Electron renderer served from a custom scheme
|
|
15
|
+
// (`app://bundle/`): Chromium treats a non-http(s) scheme as non-cookieable
|
|
16
|
+
// even when it is registered `standard` + `secure`, so the write is dropped
|
|
17
|
+
// and `session.cookies.set` refuses with EXCLUDE_NONCOOKIEABLE_SCHEME.
|
|
18
|
+
// Verified against Electron 41. On such an origin every open window starts a
|
|
19
|
+
// new "session" every minute; each one re-uploads a full replay snapshot and
|
|
20
|
+
// none of them is a session anyone can watch.
|
|
21
|
+
//
|
|
22
|
+
// ── What ─────────────────────────────────────────────────────────────────
|
|
23
|
+
//
|
|
24
|
+
// When, and only when, a probe cookie does not round-trip, the session cookie
|
|
25
|
+
// is kept in localStorage instead. An own `cookie` accessor on `document`
|
|
26
|
+
// answers reads and writes of `__rum_sid` from localStorage, honouring the
|
|
27
|
+
// max-age the SDK writes, and passes every other cookie to the browser
|
|
28
|
+
// untouched. The SDK's own rules then hold unchanged: the session expires 15
|
|
29
|
+
// minutes after the last activity (max-age=900, renewed on activity) and never
|
|
30
|
+
// outlives 4 hours (the startTime inside the value). localStorage is shared by
|
|
31
|
+
// every window of the origin, as a cookie jar is, so the windows of one app
|
|
32
|
+
// share one session the way the tabs of one browser do.
|
|
33
|
+
//
|
|
34
|
+
// An origin whose cookies work is left exactly as it was.
|
|
35
|
+
/** The SDK's session cookie (otel-web COOKIE_NAME). */
|
|
36
|
+
export const RUM_SESSION_COOKIE = "__rum_sid";
|
|
37
|
+
/** Where the session cookie is kept when cookies do not persist. */
|
|
38
|
+
export const RUM_SESSION_STORAGE_KEY = "forge.rum.session";
|
|
39
|
+
const PROBE_COOKIE = "forge_cookie_probe";
|
|
40
|
+
/**
|
|
41
|
+
* Whether `document.cookie` keeps what is written to it. Writes a short-lived
|
|
42
|
+
* probe cookie, reads it back and removes it.
|
|
43
|
+
*/
|
|
44
|
+
export function cookiesPersist(doc) {
|
|
45
|
+
try {
|
|
46
|
+
const token = Math.random().toString(36).slice(2);
|
|
47
|
+
doc.cookie = `${PROBE_COOKIE}=${token}; path=/; max-age=60; SameSite=Strict`;
|
|
48
|
+
const kept = doc.cookie
|
|
49
|
+
.split(";")
|
|
50
|
+
.some((c) => c.trim() === `${PROBE_COOKIE}=${token}`);
|
|
51
|
+
doc.cookie = `${PROBE_COOKIE}=; path=/; max-age=0; SameSite=Strict`;
|
|
52
|
+
return kept;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// A sandboxed document throws on cookie access: nothing persists.
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Keep the SDK's session cookie in `storage` when `doc` cannot keep cookies.
|
|
61
|
+
* Returns whether the fallback is now in place (it was installed by this call,
|
|
62
|
+
* or already was). Idempotent; never throws.
|
|
63
|
+
*
|
|
64
|
+
* Call it before the SDK initialises: the SDK reads the session at init.
|
|
65
|
+
*/
|
|
66
|
+
export function installSessionCookieFallback(doc, storage, now = Date.now) {
|
|
67
|
+
try {
|
|
68
|
+
if (installed.has(doc)) {
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
if (!storage || !storageWorks(storage) || cookiesPersist(doc)) {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
const native = findCookieDescriptor(doc);
|
|
75
|
+
if (!native?.get || !native.set) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
const nativeGet = native.get;
|
|
79
|
+
const nativeSet = native.set;
|
|
80
|
+
Object.defineProperty(doc, "cookie", {
|
|
81
|
+
configurable: true,
|
|
82
|
+
enumerable: true,
|
|
83
|
+
get() {
|
|
84
|
+
const jar = String(nativeGet.call(this) ?? "");
|
|
85
|
+
const session = readStored(storage, now());
|
|
86
|
+
if (session === null) {
|
|
87
|
+
return jar;
|
|
88
|
+
}
|
|
89
|
+
const entry = `${RUM_SESSION_COOKIE}=${session}`;
|
|
90
|
+
return jar ? `${jar}; ${entry}` : entry;
|
|
91
|
+
},
|
|
92
|
+
set(value) {
|
|
93
|
+
const text = String(value);
|
|
94
|
+
if (!text.startsWith(`${RUM_SESSION_COOKIE}=`)) {
|
|
95
|
+
nativeSet.call(this, text);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
writeStored(storage, text, now());
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
installed.add(doc);
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const installed = new WeakSet();
|
|
109
|
+
/** The accessor `doc.cookie` resolves to: its own, or its prototype chain's. */
|
|
110
|
+
function findCookieDescriptor(doc) {
|
|
111
|
+
for (let o = doc; o; o = Object.getPrototypeOf(o)) {
|
|
112
|
+
const d = Object.getOwnPropertyDescriptor(o, "cookie");
|
|
113
|
+
if (d) {
|
|
114
|
+
return d;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
function storageWorks(storage) {
|
|
120
|
+
const key = `${RUM_SESSION_STORAGE_KEY}.probe`;
|
|
121
|
+
try {
|
|
122
|
+
storage.setItem(key, "1");
|
|
123
|
+
const ok = storage.getItem(key) === "1";
|
|
124
|
+
storage.removeItem(key);
|
|
125
|
+
return ok;
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function readStored(storage, at) {
|
|
132
|
+
try {
|
|
133
|
+
const raw = storage.getItem(RUM_SESSION_STORAGE_KEY);
|
|
134
|
+
if (!raw) {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
const stored = JSON.parse(raw);
|
|
138
|
+
if (typeof stored.v !== "string" || typeof stored.exp !== "number") {
|
|
139
|
+
storage.removeItem(RUM_SESSION_STORAGE_KEY);
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
if (stored.exp <= at) {
|
|
143
|
+
// Expired, as the browser would have expired the cookie.
|
|
144
|
+
storage.removeItem(RUM_SESSION_STORAGE_KEY);
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
return stored.v;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Store a `__rum_sid=<value>; …attributes` write. `max-age` (seconds) or
|
|
155
|
+
* `expires` set the expiry; `max-age=0` or a past expiry deletes. A write with
|
|
156
|
+
* neither is a session cookie, which here lasts the SDK's inactivity window:
|
|
157
|
+
* the SDK always sends max-age, so this is only a defined answer for a write
|
|
158
|
+
* it does not make.
|
|
159
|
+
*/
|
|
160
|
+
function writeStored(storage, text, at) {
|
|
161
|
+
const [pair = "", ...attributes] = text.split(";");
|
|
162
|
+
const value = pair.slice(RUM_SESSION_COOKIE.length + 1).trim();
|
|
163
|
+
let exp = null;
|
|
164
|
+
for (const attribute of attributes) {
|
|
165
|
+
const eq = attribute.indexOf("=");
|
|
166
|
+
const name = (eq < 0 ? attribute : attribute.slice(0, eq))
|
|
167
|
+
.trim()
|
|
168
|
+
.toLowerCase();
|
|
169
|
+
const raw = eq < 0 ? "" : attribute.slice(eq + 1).trim();
|
|
170
|
+
if (name === "max-age") {
|
|
171
|
+
const seconds = Number(raw);
|
|
172
|
+
if (Number.isFinite(seconds)) {
|
|
173
|
+
// max-age wins over expires, as in a browser.
|
|
174
|
+
exp = at + seconds * 1000;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else if (name === "expires" && exp === null) {
|
|
179
|
+
const when = Date.parse(raw);
|
|
180
|
+
if (!Number.isNaN(when)) {
|
|
181
|
+
exp = when;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
if (value === "" || (exp !== null && exp <= at)) {
|
|
187
|
+
storage.removeItem(RUM_SESSION_STORAGE_KEY);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const stored = {
|
|
191
|
+
v: value,
|
|
192
|
+
exp: exp ?? at + SESSION_COOKIE_FALLBACK_MS,
|
|
193
|
+
};
|
|
194
|
+
storage.setItem(RUM_SESSION_STORAGE_KEY, JSON.stringify(stored));
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
// Storage full or revoked: the SDK sees no cookie and starts a session,
|
|
198
|
+
// as it would have without the fallback.
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/** The SDK's inactivity window (otel-web InactivityTimeoutSeconds). */
|
|
202
|
+
const SESSION_COOKIE_FALLBACK_MS = 15 * 60 * 1000;
|
|
203
|
+
//# sourceMappingURL=session-cookie-fallback.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-cookie-fallback.js","sourceRoot":"","sources":["../src/session-cookie-fallback.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,8DAA8D;AAC9D,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,6EAA6E;AAC7E,4EAA4E;AAC5E,mFAAmF;AACnF,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,4EAA4E;AAC5E,4EAA4E;AAC5E,uEAAuE;AACvE,6EAA6E;AAC7E,6EAA6E;AAC7E,8CAA8C;AAC9C,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,uEAAuE;AACvE,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,4EAA4E;AAC5E,wDAAwD;AACxD,EAAE;AACF,0DAA0D;AAE1D,uDAAuD;AACvD,MAAM,CAAC,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAE9C,oEAAoE;AACpE,MAAM,CAAC,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAE3D,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAgB1C;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,GAA6B;IAC1D,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAClD,GAAG,CAAC,MAAM,GAAG,GAAG,YAAY,IAAI,KAAK,uCAAuC,CAAC;QAC7E,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM;aACpB,KAAK,CAAC,GAAG,CAAC;aACV,IAAI,CAAC,CAAC,CAAC,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,MAAM,MAAM,GAAiB;YAC3B,CAAC,EAAE,KAAK;YACR,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,0BAA0B;SAC5C,CAAC;QACF,OAAO,CAAC,OAAO,CAAC,uBAAuB,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IACnE,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,yCAAyC;IAC3C,CAAC;AACH,CAAC;AAED,uEAAuE;AACvE,MAAM,0BAA0B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// A stable RUM session on an origin that cannot keep cookies.\n//\n// ── Why ──────────────────────────────────────────────────────────────────\n//\n// The HyperDX SDK (its otel-web layer) keeps the session ONLY in a cookie,\n// `__rum_sid`: `{ id, startTime }`, written with `max-age=900` and renewed\n// while the user is active. Every 60 s it reads the cookie back, and when it\n// finds none it mints a new session id. There is no other store and no seam\n// to supply one: the session module is bundled inside the HyperDX browser package.\n//\n// Some origins accept a `document.cookie` write and silently keep nothing.\n// The one that matters is an Electron renderer served from a custom scheme\n// (`app://bundle/`): Chromium treats a non-http(s) scheme as non-cookieable\n// even when it is registered `standard` + `secure`, so the write is dropped\n// and `session.cookies.set` refuses with EXCLUDE_NONCOOKIEABLE_SCHEME.\n// Verified against Electron 41. On such an origin every open window starts a\n// new \"session\" every minute; each one re-uploads a full replay snapshot and\n// none of them is a session anyone can watch.\n//\n// ── What ─────────────────────────────────────────────────────────────────\n//\n// When, and only when, a probe cookie does not round-trip, the session cookie\n// is kept in localStorage instead. An own `cookie` accessor on `document`\n// answers reads and writes of `__rum_sid` from localStorage, honouring the\n// max-age the SDK writes, and passes every other cookie to the browser\n// untouched. The SDK's own rules then hold unchanged: the session expires 15\n// minutes after the last activity (max-age=900, renewed on activity) and never\n// outlives 4 hours (the startTime inside the value). localStorage is shared by\n// every window of the origin, as a cookie jar is, so the windows of one app\n// share one session the way the tabs of one browser do.\n//\n// An origin whose cookies work is left exactly as it was.\n\n/** The SDK's session cookie (otel-web COOKIE_NAME). */\nexport const RUM_SESSION_COOKIE = \"__rum_sid\";\n\n/** Where the session cookie is kept when cookies do not persist. */\nexport const RUM_SESSION_STORAGE_KEY = \"forge.rum.session\";\n\nconst PROBE_COOKIE = \"forge_cookie_probe\";\n\n/** The slice of Storage the fallback needs. */\nexport interface SessionStore {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\ninterface StoredCookie {\n /** The cookie value exactly as the SDK wrote it (URI-encoded JSON). */\n v: string;\n /** Epoch ms at which the cookie expires. */\n exp: number;\n}\n\n/**\n * Whether `document.cookie` keeps what is written to it. Writes a short-lived\n * probe cookie, reads it back and removes it.\n */\nexport function cookiesPersist(doc: Pick<Document, \"cookie\">): boolean {\n try {\n const token = Math.random().toString(36).slice(2);\n doc.cookie = `${PROBE_COOKIE}=${token}; path=/; max-age=60; SameSite=Strict`;\n const kept = doc.cookie\n .split(\";\")\n .some((c) => c.trim() === `${PROBE_COOKIE}=${token}`);\n doc.cookie = `${PROBE_COOKIE}=; path=/; max-age=0; SameSite=Strict`;\n return kept;\n } catch {\n // A sandboxed document throws on cookie access: nothing persists.\n return false;\n }\n}\n\n/**\n * Keep the SDK's session cookie in `storage` when `doc` cannot keep cookies.\n * Returns whether the fallback is now in place (it was installed by this call,\n * or already was). Idempotent; never throws.\n *\n * Call it before the SDK initialises: the SDK reads the session at init.\n */\nexport function installSessionCookieFallback(\n doc: Document,\n storage: SessionStore | null,\n now: () => number = Date.now,\n): boolean {\n try {\n if (installed.has(doc)) {\n return true;\n }\n if (!storage || !storageWorks(storage) || cookiesPersist(doc)) {\n return false;\n }\n const native = findCookieDescriptor(doc);\n if (!native?.get || !native.set) {\n return false;\n }\n const nativeGet = native.get;\n const nativeSet = native.set;\n Object.defineProperty(doc, \"cookie\", {\n configurable: true,\n enumerable: true,\n get(this: Document): string {\n const jar = String(nativeGet.call(this) ?? \"\");\n const session = readStored(storage, now());\n if (session === null) {\n return jar;\n }\n const entry = `${RUM_SESSION_COOKIE}=${session}`;\n return jar ? `${jar}; ${entry}` : entry;\n },\n set(this: Document, value: string) {\n const text = String(value);\n if (!text.startsWith(`${RUM_SESSION_COOKIE}=`)) {\n nativeSet.call(this, text);\n return;\n }\n writeStored(storage, text, now());\n },\n });\n installed.add(doc);\n return true;\n } catch {\n return false;\n }\n}\n\nconst installed = new WeakSet<object>();\n\n/** The accessor `doc.cookie` resolves to: its own, or its prototype chain's. */\nfunction findCookieDescriptor(doc: object): PropertyDescriptor | undefined {\n for (\n let o: object | null = doc;\n o;\n o = Object.getPrototypeOf(o) as object | null\n ) {\n const d = Object.getOwnPropertyDescriptor(o, \"cookie\");\n if (d) {\n return d;\n }\n }\n return undefined;\n}\n\nfunction storageWorks(storage: SessionStore): boolean {\n const key = `${RUM_SESSION_STORAGE_KEY}.probe`;\n try {\n storage.setItem(key, \"1\");\n const ok = storage.getItem(key) === \"1\";\n storage.removeItem(key);\n return ok;\n } catch {\n return false;\n }\n}\n\nfunction readStored(storage: SessionStore, at: number): string | null {\n try {\n const raw = storage.getItem(RUM_SESSION_STORAGE_KEY);\n if (!raw) {\n return null;\n }\n const stored = JSON.parse(raw) as Partial<StoredCookie>;\n if (typeof stored.v !== \"string\" || typeof stored.exp !== \"number\") {\n storage.removeItem(RUM_SESSION_STORAGE_KEY);\n return null;\n }\n if (stored.exp <= at) {\n // Expired, as the browser would have expired the cookie.\n storage.removeItem(RUM_SESSION_STORAGE_KEY);\n return null;\n }\n return stored.v;\n } catch {\n return null;\n }\n}\n\n/**\n * Store a `__rum_sid=<value>; …attributes` write. `max-age` (seconds) or\n * `expires` set the expiry; `max-age=0` or a past expiry deletes. A write with\n * neither is a session cookie, which here lasts the SDK's inactivity window:\n * the SDK always sends max-age, so this is only a defined answer for a write\n * it does not make.\n */\nfunction writeStored(storage: SessionStore, text: string, at: number): void {\n const [pair = \"\", ...attributes] = text.split(\";\");\n const value = pair.slice(RUM_SESSION_COOKIE.length + 1).trim();\n let exp: number | null = null;\n for (const attribute of attributes) {\n const eq = attribute.indexOf(\"=\");\n const name = (eq < 0 ? attribute : attribute.slice(0, eq))\n .trim()\n .toLowerCase();\n const raw = eq < 0 ? \"\" : attribute.slice(eq + 1).trim();\n if (name === \"max-age\") {\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) {\n // max-age wins over expires, as in a browser.\n exp = at + seconds * 1000;\n break;\n }\n } else if (name === \"expires\" && exp === null) {\n const when = Date.parse(raw);\n if (!Number.isNaN(when)) {\n exp = when;\n }\n }\n }\n try {\n if (value === \"\" || (exp !== null && exp <= at)) {\n storage.removeItem(RUM_SESSION_STORAGE_KEY);\n return;\n }\n const stored: StoredCookie = {\n v: value,\n exp: exp ?? at + SESSION_COOKIE_FALLBACK_MS,\n };\n storage.setItem(RUM_SESSION_STORAGE_KEY, JSON.stringify(stored));\n } catch {\n // Storage full or revoked: the SDK sees no cookie and starts a session,\n // as it would have without the fallback.\n }\n}\n\n/** The SDK's inactivity window (otel-web InactivityTimeoutSeconds). */\nconst SESSION_COOKIE_FALLBACK_MS = 15 * 60 * 1000;\n"]}
|
package/dist/telemetry-gate.d.ts
CHANGED
|
@@ -8,5 +8,9 @@ export declare function registerTelemetryStartup(p: Promise<unknown>): void;
|
|
|
8
8
|
* has already settled.
|
|
9
9
|
*/
|
|
10
10
|
export declare function telemetryReady(maxMs?: number): Promise<void>;
|
|
11
|
+
/** Called by initBrowserTelemetry with the SDK's session getter, or null. */
|
|
12
|
+
export declare function registerRumSession(source: (() => string | undefined) | null): void;
|
|
13
|
+
/** The current RUM session id, or undefined with telemetry off. Never throws. */
|
|
14
|
+
export declare function rumSessionId(): string | undefined;
|
|
11
15
|
/** Test seam. */
|
|
12
16
|
export declare function resetTelemetryGate(): void;
|
package/dist/telemetry-gate.js
CHANGED
|
@@ -44,8 +44,33 @@ export function telemetryReady(maxMs = TELEMETRY_WAIT_MS) {
|
|
|
44
44
|
p.then(done, done);
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
|
+
// ── The RUM session the requests belong to ─────────────────────────────────
|
|
48
|
+
//
|
|
49
|
+
// initBrowserTelemetry registers the SDK's session id here once it runs, and
|
|
50
|
+
// clears it when telemetry is disabled. injectTraceContext (trace.ts) sends it
|
|
51
|
+
// as the W3C baggage member `session.id`, which forge servers copy onto their
|
|
52
|
+
// server span (forge/pkg/observe, span_identity.go), so a backend trace links
|
|
53
|
+
// back to the browser session that caused it.
|
|
54
|
+
/** The shape of a RUM session id; forge servers drop anything else. */
|
|
55
|
+
const RUM_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
56
|
+
let sessionSource = null;
|
|
57
|
+
/** Called by initBrowserTelemetry with the SDK's session getter, or null. */
|
|
58
|
+
export function registerRumSession(source) {
|
|
59
|
+
sessionSource = source;
|
|
60
|
+
}
|
|
61
|
+
/** The current RUM session id, or undefined with telemetry off. Never throws. */
|
|
62
|
+
export function rumSessionId() {
|
|
63
|
+
try {
|
|
64
|
+
const id = sessionSource?.();
|
|
65
|
+
return id && RUM_SESSION_ID_RE.test(id) ? id : undefined;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
47
71
|
/** Test seam. */
|
|
48
72
|
export function resetTelemetryGate() {
|
|
49
73
|
startup = null;
|
|
74
|
+
sessionSource = null;
|
|
50
75
|
}
|
|
51
76
|
//# sourceMappingURL=telemetry-gate.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry-gate.js","sourceRoot":"","sources":["../src/telemetry-gate.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,qEAAqE;AACrE,EAAE;AACF,+EAA+E;AAC/E,4EAA4E;AAC5E,+EAA+E;AAC/E,uEAAuE;AACvE,gFAAgF;AAChF,0EAA0E;AAC1E,SAAS;AACT,EAAE;AACF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E,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,iBAAiB;AACjB,MAAM,UAAU,kBAAkB;IAChC,OAAO,GAAG,IAAI,CAAC;IACf,aAAa,GAAG,IAAI,CAAC;AACvB,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// The hand-off between browser telemetry startup and the first RPCs.\n//\n// The HyperDX SDK is a ~600 KB lazy chunk, so it patches `fetch` some hundreds\n// of milliseconds after the app is interactive — and a page fires its first\n// queries on mount, inside that window. A call made before the patch carries a\n// SYNTHESIZED traceparent (trace.ts) that names a span no browser ever\n// exported: the API's span has a parent id that matches nothing, and \"this page\n// load, end to end\" has no answer exactly for the requests the page makes\n// first.\n//\n// So initBrowserTelemetry registers its startup here, and the trace interceptor\n// waits for it — at most TELEMETRY_WAIT_MS, so a blocked chunk or an ad blocker\n// delays a request by that much and no more, then falls back to the synthesized\n// traceparent. With telemetry off nothing is registered and nothing waits.\n//\n// DOM-free and import-free on purpose: the transport entry point\n// (@reliantlabs/forge-web-runtime/interceptors) imports this and must stay\n// light enough for React Native.\n\n/** The longest an RPC waits for browser telemetry to finish starting. */\nexport const TELEMETRY_WAIT_MS = 2000;\n\nlet startup: Promise<unknown> | null = null;\n\n/** Called once by initBrowserTelemetry with the promise of its startup. */\nexport function registerTelemetryStartup(p: Promise<unknown>): void {\n startup = p;\n}\n\n/**\n * Resolves when telemetry has finished starting (or failed to), or after\n * `maxMs`, whichever is first. Resolves immediately when none is starting or it\n * has already settled.\n */\nexport function telemetryReady(\n maxMs: number = TELEMETRY_WAIT_MS,\n): Promise<void> {\n const p = startup;\n if (!p) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, maxMs);\n const done = () => {\n clearTimeout(timer);\n resolve();\n };\n p.then(done, done);\n });\n}\n\n// ── The RUM session the requests belong to ─────────────────────────────────\n//\n// initBrowserTelemetry registers the SDK's session id here once it runs, and\n// clears it when telemetry is disabled. injectTraceContext (trace.ts) sends it\n// as the W3C baggage member `session.id`, which forge servers copy onto their\n// server span (forge/pkg/observe, span_identity.go), so a backend trace links\n// back to the browser session that caused it.\n\n/** The shape of a RUM session id; forge servers drop anything else. */\nconst RUM_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;\n\nlet sessionSource: (() => string | undefined) | null = null;\n\n/** Called by initBrowserTelemetry with the SDK's session getter, or null. */\nexport function registerRumSession(\n source: (() => string | undefined) | null,\n): void {\n sessionSource = source;\n}\n\n/** The current RUM session id, or undefined with telemetry off. Never throws. */\nexport function rumSessionId(): string | undefined {\n try {\n const id = sessionSource?.();\n return id && RUM_SESSION_ID_RE.test(id) ? id : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Test seam. */\nexport function resetTelemetryGate(): void {\n startup = null;\n sessionSource = null;\n}\n"]}
|
package/dist/telemetry.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { type AttributionTouch } from "./attribution.js";
|
|
2
|
+
import { type BenignErrorClassifier } from "./benign-errors.js";
|
|
3
|
+
export { clientResourceAttributes, type ForgeDesktopInfo, viewportAttributes, } from "./client-context.js";
|
|
4
|
+
export { cookiesPersist, installSessionCookieFallback, RUM_SESSION_COOKIE, RUM_SESSION_STORAGE_KEY, } from "./session-cookie-fallback.js";
|
|
5
|
+
export { type BenignErrorClassifier, type BenignErrorKind, classifyBenignError, FILTERED_ERRORS_ACTION, } from "./benign-errors.js";
|
|
2
6
|
/** Where the browser ships telemetry: this origin's `/_otel`. */
|
|
3
7
|
export declare const DEFAULT_INGEST_PATH = "/_otel";
|
|
4
8
|
/**
|
|
@@ -95,6 +99,18 @@ export interface BrowserTelemetryConfig {
|
|
|
95
99
|
* site attributing acquisition to the campaign that first brought a visitor.
|
|
96
100
|
*/
|
|
97
101
|
attributionTouch?: AttributionTouch;
|
|
102
|
+
/**
|
|
103
|
+
* Decides which errors are benign browser noise: kept out of the error
|
|
104
|
+
* pipeline and counted as `forge.errors_filtered` actions instead
|
|
105
|
+
* (benign-errors.ts). Default classifyBenignError: an AbortError, and the
|
|
106
|
+
* browser's generic "Failed to fetch" TypeError; never a ConnectError. It
|
|
107
|
+
* applies to what the SDK records from unhandled rejections, uncaught
|
|
108
|
+
* errors, console.error and reportException; the app's own handlers see
|
|
109
|
+
* every event unchanged. For an unhandled rejection or uncaught error it is
|
|
110
|
+
* handed `{ name, message }` as the SDK recorded them, not the original
|
|
111
|
+
* value. Pass `() => null` to record everything.
|
|
112
|
+
*/
|
|
113
|
+
classifyBenignError?: BenignErrorClassifier;
|
|
98
114
|
}
|
|
99
115
|
/**
|
|
100
116
|
* Turn on visitor attribution for a page that started telemetry with
|
|
@@ -115,9 +131,11 @@ export declare function enableAttribution(options?: {
|
|
|
115
131
|
export declare function initBrowserTelemetry(config: BrowserTelemetryConfig): Promise<boolean>;
|
|
116
132
|
/**
|
|
117
133
|
* The options passed to HyperDX.init. Exported for tests and for apps that
|
|
118
|
-
* want to see exactly what is configured — it is pure.
|
|
134
|
+
* want to see exactly what is configured — it is pure. `clientAttributes`
|
|
135
|
+
* are the page's own client resource attributes (client-context.ts:
|
|
136
|
+
* browser.* client hints, app.desktop.*); the config's keys win over them.
|
|
119
137
|
*/
|
|
120
|
-
export declare function buildSdkOptions(config: BrowserTelemetryConfig, ingestUrl: string, pageOrigin: string): Record<string, unknown>;
|
|
138
|
+
export declare function buildSdkOptions(config: BrowserTelemetryConfig, ingestUrl: string, pageOrigin: string, clientAttributes?: Record<string, string>): Record<string, unknown>;
|
|
121
139
|
/** Elements a replay never records: their pixels stay in the browser. */
|
|
122
140
|
export declare const REPLAY_BLOCK_SELECTOR = "img, picture, video, audio, iframe, object, embed";
|
|
123
141
|
/** Where a replay sampling decision is held for the tab's session. */
|
|
@@ -137,6 +155,15 @@ interface DecisionStore {
|
|
|
137
155
|
export declare function decideReplay(config: Pick<BrowserTelemetryConfig, "replay" | "replaySampleRate">, store: DecisionStore | null, random: () => number): boolean;
|
|
138
156
|
/** `url` without its query string and fragment. */
|
|
139
157
|
export declare function stripUrlQuery(url: string): string;
|
|
158
|
+
/**
|
|
159
|
+
* The name a fetch/XHR span gets: `<METHOD> /<package>.<Service>/<Method>`,
|
|
160
|
+
* the server span's name with the method in front, when the URL is a
|
|
161
|
+
* Connect/gRPC procedure. Empty for any other URL, which keeps the SDK's
|
|
162
|
+
* `HTTP <METHOD>`: an arbitrary path can hold values (ids, tokens, emails) no
|
|
163
|
+
* pattern recognises reliably, and a span name must be neither sensitive nor
|
|
164
|
+
* unbounded. Empty too when `url` cannot be parsed. Exported for tests.
|
|
165
|
+
*/
|
|
166
|
+
export declare function spanRouteName(method: string, url: string): string;
|
|
140
167
|
/**
|
|
141
168
|
* resolveIngestUrl turns the configured endpoint into the absolute URL the SDK
|
|
142
169
|
* is given, or null when telemetry is off. A path resolves against the page
|