@geekmidas/client 10.0.0-alpha.17 → 10.0.0-alpha.171
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 +53 -14
- package/dist/auth-fetcher.cjs +3 -1
- package/dist/auth-fetcher.cjs.map +1 -1
- package/dist/auth-fetcher.d.cts +2 -1
- package/dist/auth-fetcher.d.cts.map +1 -1
- package/dist/auth-fetcher.d.mts +2 -1
- package/dist/auth-fetcher.d.mts.map +1 -1
- package/dist/auth-fetcher.mjs +3 -1
- package/dist/auth-fetcher.mjs.map +1 -1
- package/dist/fetcher.cjs +6 -1
- package/dist/fetcher.cjs.map +1 -1
- package/dist/fetcher.d.cts +3 -1
- package/dist/fetcher.d.cts.map +1 -1
- package/dist/fetcher.d.mts +3 -1
- package/dist/fetcher.d.mts.map +1 -1
- package/dist/fetcher.mjs +6 -1
- package/dist/fetcher.mjs.map +1 -1
- package/dist/index.cjs +7 -0
- package/dist/index.d.cts +3 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +3 -1
- package/dist/infer.d.cts +2 -2
- package/dist/infer.d.cts.map +1 -1
- package/dist/infer.d.mts +2 -2
- package/dist/infer.d.mts.map +1 -1
- package/dist/methods.cjs +21 -0
- package/dist/methods.cjs.map +1 -0
- package/dist/methods.d.cts +23 -0
- package/dist/methods.d.cts.map +1 -0
- package/dist/methods.d.mts +23 -0
- package/dist/methods.d.mts.map +1 -0
- package/dist/methods.mjs +19 -0
- package/dist/methods.mjs.map +1 -0
- package/dist/openapi-types.d.cts +1 -1
- package/dist/openapi-types.d.mts +1 -1
- package/dist/telemetry-g3BE86Wd.d.cts +68 -0
- package/dist/telemetry-g3BE86Wd.d.cts.map +1 -0
- package/dist/telemetry-g3BE86Wd.d.mts +68 -0
- package/dist/telemetry-g3BE86Wd.d.mts.map +1 -0
- package/dist/telemetry.cjs +128 -0
- package/dist/telemetry.cjs.map +1 -0
- package/dist/telemetry.d.cts +2 -0
- package/dist/telemetry.d.mts +2 -0
- package/dist/telemetry.mjs +125 -0
- package/dist/telemetry.mjs.map +1 -0
- package/dist/types.d.cts +21 -8
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +21 -8
- package/dist/types.d.mts.map +1 -1
- package/package.json +19 -6
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { CALL_METHODS, methodCalls } from "./methods.mjs";
|
|
2
|
+
import { InvalidClientSampleRate, sampledAt, traceContextInjector } from "./telemetry.mjs";
|
|
1
3
|
import { TypedFetcher, createTypedFetcher } from "./fetcher.mjs";
|
|
2
4
|
import { createAuthAwareFetcher } from "./auth-fetcher.mjs";
|
|
3
5
|
import "./infer.mjs";
|
|
4
6
|
import "./types.mjs";
|
|
5
|
-
export { TypedFetcher, createAuthAwareFetcher, createTypedFetcher };
|
|
7
|
+
export { CALL_METHODS, InvalidClientSampleRate, TypedFetcher, createAuthAwareFetcher, createTypedFetcher, methodCalls, sampledAt, traceContextInjector };
|
package/dist/infer.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Endpoint, EndpointSchemas } from "@geekmidas/constructs/endpoints";
|
|
1
|
+
import { ConvertRouteParams, Endpoint, EndpointSchemas } from "@geekmidas/constructs/endpoints";
|
|
2
2
|
import { HttpMethod } from "@geekmidas/constructs/types";
|
|
3
3
|
import { InferStandardSchema, InferStandardSchemaInput } from "@geekmidas/schema";
|
|
4
4
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
@@ -74,7 +74,7 @@ type InferOperation<TInput extends EndpointSchemas, TOutput extends StandardSche
|
|
|
74
74
|
* ```
|
|
75
75
|
*/
|
|
76
76
|
export type InferOpenApiFromEndpoint<T> = T extends Endpoint<infer TRoute, infer TMethod, infer TInput, infer TOutput, any, any, any> ? {
|
|
77
|
-
paths: { [K in TRoute]: InferRouteParameters<TRoute
|
|
77
|
+
paths: { [K in ConvertRouteParams<TRoute>]: InferRouteParameters<ConvertRouteParams<TRoute>> & { [M in LowercaseMethod<TMethod>]: InferOperation<TInput, TOutput>; }; };
|
|
78
78
|
} : never;
|
|
79
79
|
/**
|
|
80
80
|
* Infers TypedFetcher-compatible paths structure from multiple endpoints
|
package/dist/infer.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"infer.d.cts","names":[],"sources":["../src/infer.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"infer.d.cts","names":[],"sources":["../src/infer.ts"],"mappings":";;;;;;;;;KAgBK,gBAAgB,yBACpB,kCAAkC,eAAe,YAC3C,KAAK,oBAAmB,gBAAgB;;;;KAM1C,gBAAgB,UAAU,cAAc,UAAU;;;;KAKlD,qBAAqB,yBACzB,gBAAgB,gBAAgB;EAG7B;IACC,MAAM,gBAAgB;;;;;;KAOtB,yBAAyB,eAAe,mBAAmB;EAC/D,aAAa;;EAGX;IAMC,OAAO,yBAAyB;;;;;;KAQ/B,eACJ,eAAe,iBACf,gBAAgB,gCACb,yBAAyB;EAC5B,cAAc;IAAiB,YAAY;;IAExC;MAKC,oBAAoB,yBAAyB;;;EAIjD;IACC;MACC,SAAS,gBAAgB;QAEtB,oBAAoB,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA+BlC,yBAAyB,KACpC,UAAU,eACH,cACA,eACA,cACA;EAUJ,UACE,KAAK,mBAAmB,UAAU,qBAClC,mBAAmB,cAElB,KAAK,gBAAgB,WAAW,eAAe,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA2ClD,aAAa,qCACxB,mCAAmC,gBAAgB,QAChD,yBAAyB;EAAiB,aAAa;IACtD;EACG,OAAO;IACT,aAAa;EAAgB,aAAa;;EACvC,OAAO,KAAK;;EACZ,OAAO;IACX,aAAa;EACZ"}
|
package/dist/infer.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Endpoint, EndpointSchemas } from "@geekmidas/constructs/endpoints";
|
|
1
|
+
import { ConvertRouteParams, Endpoint, EndpointSchemas } from "@geekmidas/constructs/endpoints";
|
|
2
2
|
import { HttpMethod } from "@geekmidas/constructs/types";
|
|
3
3
|
import { InferStandardSchema, InferStandardSchemaInput } from "@geekmidas/schema";
|
|
4
4
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
@@ -74,7 +74,7 @@ type InferOperation<TInput extends EndpointSchemas, TOutput extends StandardSche
|
|
|
74
74
|
* ```
|
|
75
75
|
*/
|
|
76
76
|
export type InferOpenApiFromEndpoint<T> = T extends Endpoint<infer TRoute, infer TMethod, infer TInput, infer TOutput, any, any, any> ? {
|
|
77
|
-
paths: { [K in TRoute]: InferRouteParameters<TRoute
|
|
77
|
+
paths: { [K in ConvertRouteParams<TRoute>]: InferRouteParameters<ConvertRouteParams<TRoute>> & { [M in LowercaseMethod<TMethod>]: InferOperation<TInput, TOutput>; }; };
|
|
78
78
|
} : never;
|
|
79
79
|
/**
|
|
80
80
|
* Infers TypedFetcher-compatible paths structure from multiple endpoints
|
package/dist/infer.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"infer.d.mts","names":[],"sources":["../src/infer.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"infer.d.mts","names":[],"sources":["../src/infer.ts"],"mappings":";;;;;;;;;KAgBK,gBAAgB,yBACpB,kCAAkC,eAAe,YAC3C,KAAK,oBAAmB,gBAAgB;;;;KAM1C,gBAAgB,UAAU,cAAc,UAAU;;;;KAKlD,qBAAqB,yBACzB,gBAAgB,gBAAgB;EAG7B;IACC,MAAM,gBAAgB;;;;;;KAOtB,yBAAyB,eAAe,mBAAmB;EAC/D,aAAa;;EAGX;IAMC,OAAO,yBAAyB;;;;;;KAQ/B,eACJ,eAAe,iBACf,gBAAgB,gCACb,yBAAyB;EAC5B,cAAc;IAAiB,YAAY;;IAExC;MAKC,oBAAoB,yBAAyB;;;EAIjD;IACC;MACC,SAAS,gBAAgB;QAEtB,oBAAoB,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA+BlC,yBAAyB,KACpC,UAAU,eACH,cACA,eACA,cACA;EAUJ,UACE,KAAK,mBAAmB,UAAU,qBAClC,mBAAmB,cAElB,KAAK,gBAAgB,WAAW,eAAe,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA2ClD,aAAa,qCACxB,mCAAmC,gBAAgB,QAChD,yBAAyB;EAAiB,aAAa;IACtD;EACG,OAAO;IACT,aAAa;EAAgB,aAAa;;EACvC,OAAO,KAAK;;EACZ,OAAO;IACX,aAAa;EACZ"}
|
package/dist/methods.cjs
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/methods.ts
|
|
3
|
+
/** The HTTP methods a client offers as calls: `api.get(…)`, `api.post(…)`. */
|
|
4
|
+
const CALL_METHODS = [
|
|
5
|
+
"get",
|
|
6
|
+
"post",
|
|
7
|
+
"put",
|
|
8
|
+
"patch",
|
|
9
|
+
"delete",
|
|
10
|
+
"options"
|
|
11
|
+
];
|
|
12
|
+
/** The method calls for a client, each delegating to `api('METHOD /route', …)`. */
|
|
13
|
+
function methodCalls(fn) {
|
|
14
|
+
const call = (method) => (route, config) => fn(`${method.toUpperCase()} ${route}`, config);
|
|
15
|
+
return Object.fromEntries(CALL_METHODS.map((method) => [method, call(method)]));
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
exports.CALL_METHODS = CALL_METHODS;
|
|
19
|
+
exports.methodCalls = methodCalls;
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=methods.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"methods.cjs","names":[],"sources":["../src/methods.ts"],"sourcesContent":["import type {\n\tExtractEndpointResponse,\n\tExtractMethod,\n\tFilteredRequestConfig,\n\tIsConfigRequired,\n\tTypedApiFunction,\n\tTypedEndpoint,\n} from './types';\n\n/** The HTTP methods a client offers as calls: `api.get(…)`, `api.post(…)`. */\nexport const CALL_METHODS = [\n\t'get',\n\t'post',\n\t'put',\n\t'patch',\n\t'delete',\n\t'options',\n] as const;\n\nexport type CallMethod = (typeof CALL_METHODS)[number];\n\n/**\n * The routes that answer `M` — only routes with a `POST` appear in `api.post`,\n * so a route that exists under another method is a type error, not a 405.\n */\nexport type RoutesFor<Paths, M extends CallMethod> = {\n\t[R in keyof Paths]: M extends ExtractMethod<Paths, R> ? R : never;\n}[keyof Paths] &\n\tstring;\n\n/**\n * One method's call: `api.post('/users', { body })`.\n *\n * The second argument has only the keys the endpoint declares, and is required\n * exactly when something in it is — the same rule as `api('POST /users', …)`,\n * which this is sugar over.\n */\nexport type MethodCall<Paths, M extends CallMethod> = <\n\tR extends RoutesFor<Paths, M>,\n>(\n\troute: R,\n\t...args: `${Uppercase<M>} ${R}` extends TypedEndpoint<Paths>\n\t\t? IsConfigRequired<Paths, `${Uppercase<M>} ${R}`> extends true\n\t\t\t? [config: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>]\n\t\t\t: [config?: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>]\n\t\t: never\n) => Promise<ExtractEndpointResponse<Paths, `${Uppercase<M>} ${R}`>>;\n\nexport type MethodCalls<Paths> = {\n\t[M in CallMethod]: MethodCall<Paths, M>;\n};\n\n/** The method calls for a client, each delegating to `api('METHOD /route', …)`. */\nexport function methodCalls<Paths>(\n\tfn: TypedApiFunction<Paths>,\n): MethodCalls<Paths> {\n\tconst call =\n\t\t(method: CallMethod) =>\n\t\t(route: string, config?: unknown): Promise<unknown> =>\n\t\t\t(fn as (endpoint: string, config?: unknown) => Promise<unknown>)(\n\t\t\t\t`${method.toUpperCase()} ${route}`,\n\t\t\t\tconfig,\n\t\t\t);\n\n\treturn Object.fromEntries(\n\t\tCALL_METHODS.map((method) => [method, call(method)]),\n\t) as unknown as MethodCalls<Paths>;\n}\n"],"mappings":";;;AAUA,MAAa,eAAe;CAC3B;CACA;CACA;CACA;CACA;CACA;AACD;;AAoCA,SAAgB,YACf,IACqB;CACrB,MAAM,QACJ,YACA,OAAe,WACd,GACA,GAAG,OAAO,YAAY,EAAE,GAAG,SAC3B,MACD;CAEF,OAAO,OAAO,YACb,aAAa,KAAK,WAAW,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CACpD;AACD"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ExtractEndpointResponse, ExtractMethod, FilteredRequestConfig, IsConfigRequired, TypedApiFunction, TypedEndpoint } from "./types.cjs";
|
|
2
|
+
//#region src/methods.d.ts
|
|
3
|
+
/** The HTTP methods a client offers as calls: `api.get(…)`, `api.post(…)`. */
|
|
4
|
+
export declare const CALL_METHODS: readonly ['get', 'post', 'put', 'patch', 'delete', 'options'];
|
|
5
|
+
export type CallMethod = (typeof CALL_METHODS)[number];
|
|
6
|
+
/**
|
|
7
|
+
* The routes that answer `M` — only routes with a `POST` appear in `api.post`,
|
|
8
|
+
* so a route that exists under another method is a type error, not a 405.
|
|
9
|
+
*/
|
|
10
|
+
export type RoutesFor<Paths, M extends CallMethod> = { [R in keyof Paths]: M extends ExtractMethod<Paths, R> ? R : never; }[keyof Paths] & string;
|
|
11
|
+
/**
|
|
12
|
+
* One method's call: `api.post('/users', { body })`.
|
|
13
|
+
*
|
|
14
|
+
* The second argument has only the keys the endpoint declares, and is required
|
|
15
|
+
* exactly when something in it is — the same rule as `api('POST /users', …)`,
|
|
16
|
+
* which this is sugar over.
|
|
17
|
+
*/
|
|
18
|
+
export type MethodCall<Paths, M extends CallMethod> = <R extends RoutesFor<Paths, M>>(route: R, ...args: `${Uppercase<M>} ${R}` extends TypedEndpoint<Paths> ? IsConfigRequired<Paths, `${Uppercase<M>} ${R}`> extends true ? [config: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>] : [config?: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>] : never) => Promise<ExtractEndpointResponse<Paths, `${Uppercase<M>} ${R}`>>;
|
|
19
|
+
export type MethodCalls<Paths> = { [M in CallMethod]: MethodCall<Paths, M>; };
|
|
20
|
+
/** The method calls for a client, each delegating to `api('METHOD /route', …)`. */
|
|
21
|
+
export declare function methodCalls<Paths>(fn: TypedApiFunction<Paths>): MethodCalls<Paths>;
|
|
22
|
+
//#endregion
|
|
23
|
+
//# sourceMappingURL=methods.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"methods.d.cts","names":[],"sources":["../src/methods.ts"],"mappings":";;;qBAUa;YASD,qBAAqB;;;;;YAMrB,UAAU,OAAO,UAAU,iBACrC,WAAW,QAAQ,UAAU,cAAc,OAAO,KAAK,mBACjD;;;;;;;;YAUI,WAAW,OAAO,UAAU,eACvC,UAAU,UAAU,OAAO,IAE3B,OAAO,MACJ,SAAS,UAAU,MAAM,YAAY,cAAc,SACnD,iBAAiB,UAAU,UAAU,MAAM,qBACzC,QAAQ,sBAAsB,UAAU,UAAU,MAAM,SACxD,SAAS,sBAAsB,UAAU,UAAU,MAAM,kBAE1D,QAAQ,wBAAwB,UAAU,UAAU,MAAM;YAEnD,YAAY,YACtB,KAAK,aAAa,WAAW,OAAO;;wBAItB,YAAY,OAC3B,IAAI,iBAAiB,SACnB,YAAY"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ExtractEndpointResponse, ExtractMethod, FilteredRequestConfig, IsConfigRequired, TypedApiFunction, TypedEndpoint } from "./types.mjs";
|
|
2
|
+
//#region src/methods.d.ts
|
|
3
|
+
/** The HTTP methods a client offers as calls: `api.get(…)`, `api.post(…)`. */
|
|
4
|
+
export declare const CALL_METHODS: readonly ['get', 'post', 'put', 'patch', 'delete', 'options'];
|
|
5
|
+
export type CallMethod = (typeof CALL_METHODS)[number];
|
|
6
|
+
/**
|
|
7
|
+
* The routes that answer `M` — only routes with a `POST` appear in `api.post`,
|
|
8
|
+
* so a route that exists under another method is a type error, not a 405.
|
|
9
|
+
*/
|
|
10
|
+
export type RoutesFor<Paths, M extends CallMethod> = { [R in keyof Paths]: M extends ExtractMethod<Paths, R> ? R : never; }[keyof Paths] & string;
|
|
11
|
+
/**
|
|
12
|
+
* One method's call: `api.post('/users', { body })`.
|
|
13
|
+
*
|
|
14
|
+
* The second argument has only the keys the endpoint declares, and is required
|
|
15
|
+
* exactly when something in it is — the same rule as `api('POST /users', …)`,
|
|
16
|
+
* which this is sugar over.
|
|
17
|
+
*/
|
|
18
|
+
export type MethodCall<Paths, M extends CallMethod> = <R extends RoutesFor<Paths, M>>(route: R, ...args: `${Uppercase<M>} ${R}` extends TypedEndpoint<Paths> ? IsConfigRequired<Paths, `${Uppercase<M>} ${R}`> extends true ? [config: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>] : [config?: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>] : never) => Promise<ExtractEndpointResponse<Paths, `${Uppercase<M>} ${R}`>>;
|
|
19
|
+
export type MethodCalls<Paths> = { [M in CallMethod]: MethodCall<Paths, M>; };
|
|
20
|
+
/** The method calls for a client, each delegating to `api('METHOD /route', …)`. */
|
|
21
|
+
export declare function methodCalls<Paths>(fn: TypedApiFunction<Paths>): MethodCalls<Paths>;
|
|
22
|
+
//#endregion
|
|
23
|
+
//# sourceMappingURL=methods.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"methods.d.mts","names":[],"sources":["../src/methods.ts"],"mappings":";;;qBAUa;YASD,qBAAqB;;;;;YAMrB,UAAU,OAAO,UAAU,iBACrC,WAAW,QAAQ,UAAU,cAAc,OAAO,KAAK,mBACjD;;;;;;;;YAUI,WAAW,OAAO,UAAU,eACvC,UAAU,UAAU,OAAO,IAE3B,OAAO,MACJ,SAAS,UAAU,MAAM,YAAY,cAAc,SACnD,iBAAiB,UAAU,UAAU,MAAM,qBACzC,QAAQ,sBAAsB,UAAU,UAAU,MAAM,SACxD,SAAS,sBAAsB,UAAU,UAAU,MAAM,kBAE1D,QAAQ,wBAAwB,UAAU,UAAU,MAAM;YAEnD,YAAY,YACtB,KAAK,aAAa,WAAW,OAAO;;wBAItB,YAAY,OAC3B,IAAI,iBAAiB,SACnB,YAAY"}
|
package/dist/methods.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/methods.ts
|
|
2
|
+
/** The HTTP methods a client offers as calls: `api.get(…)`, `api.post(…)`. */
|
|
3
|
+
const CALL_METHODS = [
|
|
4
|
+
"get",
|
|
5
|
+
"post",
|
|
6
|
+
"put",
|
|
7
|
+
"patch",
|
|
8
|
+
"delete",
|
|
9
|
+
"options"
|
|
10
|
+
];
|
|
11
|
+
/** The method calls for a client, each delegating to `api('METHOD /route', …)`. */
|
|
12
|
+
function methodCalls(fn) {
|
|
13
|
+
const call = (method) => (route, config) => fn(`${method.toUpperCase()} ${route}`, config);
|
|
14
|
+
return Object.fromEntries(CALL_METHODS.map((method) => [method, call(method)]));
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { CALL_METHODS, methodCalls };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=methods.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"methods.mjs","names":[],"sources":["../src/methods.ts"],"sourcesContent":["import type {\n\tExtractEndpointResponse,\n\tExtractMethod,\n\tFilteredRequestConfig,\n\tIsConfigRequired,\n\tTypedApiFunction,\n\tTypedEndpoint,\n} from './types';\n\n/** The HTTP methods a client offers as calls: `api.get(…)`, `api.post(…)`. */\nexport const CALL_METHODS = [\n\t'get',\n\t'post',\n\t'put',\n\t'patch',\n\t'delete',\n\t'options',\n] as const;\n\nexport type CallMethod = (typeof CALL_METHODS)[number];\n\n/**\n * The routes that answer `M` — only routes with a `POST` appear in `api.post`,\n * so a route that exists under another method is a type error, not a 405.\n */\nexport type RoutesFor<Paths, M extends CallMethod> = {\n\t[R in keyof Paths]: M extends ExtractMethod<Paths, R> ? R : never;\n}[keyof Paths] &\n\tstring;\n\n/**\n * One method's call: `api.post('/users', { body })`.\n *\n * The second argument has only the keys the endpoint declares, and is required\n * exactly when something in it is — the same rule as `api('POST /users', …)`,\n * which this is sugar over.\n */\nexport type MethodCall<Paths, M extends CallMethod> = <\n\tR extends RoutesFor<Paths, M>,\n>(\n\troute: R,\n\t...args: `${Uppercase<M>} ${R}` extends TypedEndpoint<Paths>\n\t\t? IsConfigRequired<Paths, `${Uppercase<M>} ${R}`> extends true\n\t\t\t? [config: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>]\n\t\t\t: [config?: FilteredRequestConfig<Paths, `${Uppercase<M>} ${R}`>]\n\t\t: never\n) => Promise<ExtractEndpointResponse<Paths, `${Uppercase<M>} ${R}`>>;\n\nexport type MethodCalls<Paths> = {\n\t[M in CallMethod]: MethodCall<Paths, M>;\n};\n\n/** The method calls for a client, each delegating to `api('METHOD /route', …)`. */\nexport function methodCalls<Paths>(\n\tfn: TypedApiFunction<Paths>,\n): MethodCalls<Paths> {\n\tconst call =\n\t\t(method: CallMethod) =>\n\t\t(route: string, config?: unknown): Promise<unknown> =>\n\t\t\t(fn as (endpoint: string, config?: unknown) => Promise<unknown>)(\n\t\t\t\t`${method.toUpperCase()} ${route}`,\n\t\t\t\tconfig,\n\t\t\t);\n\n\treturn Object.fromEntries(\n\t\tCALL_METHODS.map((method) => [method, call(method)]),\n\t) as unknown as MethodCalls<Paths>;\n}\n"],"mappings":";;AAUA,MAAa,eAAe;CAC3B;CACA;CACA;CACA;CACA;CACA;AACD;;AAoCA,SAAgB,YACf,IACqB;CACrB,MAAM,QACJ,YACA,OAAe,WACd,GACA,GAAG,OAAO,YAAY,EAAE,GAAG,SAC3B,MACD;CAEF,OAAO,OAAO,YACb,aAAa,KAAK,WAAW,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CACpD;AACD"}
|
package/dist/openapi-types.d.cts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* A hand-written `paths` fixture in openapi-typescript's shape, for the
|
|
4
4
|
* client's own tests. Applications get theirs from `gkm build`, which writes
|
|
5
|
-
* a typed client per surface to `.gkm/
|
|
5
|
+
* a typed client per surface to the workspace root's `.gkm/client/<surface>.ts`.
|
|
6
6
|
*
|
|
7
7
|
* This is a placeholder file showing the expected structure.
|
|
8
8
|
*/
|
package/dist/openapi-types.d.mts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* A hand-written `paths` fixture in openapi-typescript's shape, for the
|
|
4
4
|
* client's own tests. Applications get theirs from `gkm build`, which writes
|
|
5
|
-
* a typed client per surface to `.gkm/
|
|
5
|
+
* a typed client per surface to the workspace root's `.gkm/client/<surface>.ts`.
|
|
6
6
|
*
|
|
7
7
|
* This is a placeholder file showing the expected structure.
|
|
8
8
|
*/
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
//#region src/telemetry.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* W3C trace context on the requests a client makes to its own API, so a user
|
|
4
|
+
* action in the browser and the API request it causes are one trace.
|
|
5
|
+
*
|
|
6
|
+
* Two levels, chosen per request:
|
|
7
|
+
*
|
|
8
|
+
* - **An OpenTelemetry context is active** — a browser SDK has a span open, or
|
|
9
|
+
* this runs on a server (a Next.js server component, an API calling another
|
|
10
|
+
* API) inside a request span. The globally registered propagator writes the
|
|
11
|
+
* headers, so the current span is the parent: `traceparent`, `tracestate`,
|
|
12
|
+
* and whatever else that propagator carries.
|
|
13
|
+
* - **Otherwise** (level 1): one trace id per page view — per page load in a
|
|
14
|
+
* browser, per client in Node — a fresh span id per request, and a sampled
|
|
15
|
+
* flag decided once per page view from {@link ClientTelemetryOptions.sampleRate}.
|
|
16
|
+
*
|
|
17
|
+
* Nothing is sent to any origin but the API's own: a trace id is an identifier,
|
|
18
|
+
* and a third party has no business correlating a user's requests by it. And
|
|
19
|
+
* nothing at all where a `fetch` instrumentation is listening (a server with
|
|
20
|
+
* OpenTelemetry's undici instrumentation): it writes the request's own
|
|
21
|
+
* context, and two `traceparent` headers would be read as none.
|
|
22
|
+
*
|
|
23
|
+
* `@opentelemetry/api` is not imported. Every copy of it — whichever version
|
|
24
|
+
* an app bundles — registers its globals on `globalThis` under
|
|
25
|
+
* `Symbol.for('opentelemetry.js.api.1')`, which is how two copies in one page
|
|
26
|
+
* already share a provider. Reading the propagator and context manager from
|
|
27
|
+
* there costs a browser bundle nothing when no SDK is loaded, and still finds
|
|
28
|
+
* the SDK when one is.
|
|
29
|
+
*/
|
|
30
|
+
/** Telemetry on a client: `true` for the defaults, or these options. */
|
|
31
|
+
interface ClientTelemetryOptions {
|
|
32
|
+
/**
|
|
33
|
+
* The fraction of page views whose requests are sampled, from 0 to 1, when
|
|
34
|
+
* no OpenTelemetry context is active. Decided once per page view, so a
|
|
35
|
+
* page's requests are all kept or all dropped together.
|
|
36
|
+
*
|
|
37
|
+
* Use the stage's rate. The API caps an incoming sampled flag at its own
|
|
38
|
+
* rate anyway, and decides from the trace id the same way this does, so a
|
|
39
|
+
* page view sampled here at the API's rate is sampled there too.
|
|
40
|
+
* @default 1
|
|
41
|
+
*/
|
|
42
|
+
sampleRate?: number;
|
|
43
|
+
}
|
|
44
|
+
/** A `sampleRate` outside 0–1, which no sampler can honour. */
|
|
45
|
+
declare class InvalidClientSampleRate extends Error {
|
|
46
|
+
readonly sampleRate: number;
|
|
47
|
+
constructor(sampleRate: number);
|
|
48
|
+
}
|
|
49
|
+
/** Adds trace headers to a request to `url`, when it is the API's own. */
|
|
50
|
+
type TraceContextInjector = (url: string, headers: Record<string, string>) => void;
|
|
51
|
+
/**
|
|
52
|
+
* Whether a trace is sampled at `rate`, from its id.
|
|
53
|
+
*
|
|
54
|
+
* The same rule as OpenTelemetry's `TraceIdRatioBasedSampler`: the id's four
|
|
55
|
+
* 32-bit words XORed together, under `rate` of the 32-bit range. The trace id
|
|
56
|
+
* is random, so this samples `rate` of page views — and the API, applying the
|
|
57
|
+
* same rule to the same id at the same rate, keeps exactly the page views kept
|
|
58
|
+
* here rather than a random `rate` of them.
|
|
59
|
+
*/
|
|
60
|
+
declare function sampledAt(traceId: string, rate: number): boolean;
|
|
61
|
+
/**
|
|
62
|
+
* An injector for a client whose API is at `baseURL`, or undefined when
|
|
63
|
+
* telemetry is off.
|
|
64
|
+
*/
|
|
65
|
+
declare function traceContextInjector(baseURL: string, telemetry: boolean | ClientTelemetryOptions | undefined): TraceContextInjector | undefined;
|
|
66
|
+
//#endregion
|
|
67
|
+
export { traceContextInjector as a, sampledAt as i, InvalidClientSampleRate as n, TraceContextInjector as r, ClientTelemetryOptions as t };
|
|
68
|
+
//# sourceMappingURL=telemetry-g3BE86Wd.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-g3BE86Wd.d.cts","names":[],"sources":["../src/telemetry.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BiB;;;;;;;;;;;EAWhB;;;cAIY,gCAAgC;WACvB;EAArB,YAAqB;;;KASV,wBACX,aACA,SAAS;;;;;;;;;;iBAiEM,UAAU,iBAAiB;;;;;iBA6E3B,qBACf,iBACA,qBAAqB,qCACnB"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
//#region src/telemetry.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* W3C trace context on the requests a client makes to its own API, so a user
|
|
4
|
+
* action in the browser and the API request it causes are one trace.
|
|
5
|
+
*
|
|
6
|
+
* Two levels, chosen per request:
|
|
7
|
+
*
|
|
8
|
+
* - **An OpenTelemetry context is active** — a browser SDK has a span open, or
|
|
9
|
+
* this runs on a server (a Next.js server component, an API calling another
|
|
10
|
+
* API) inside a request span. The globally registered propagator writes the
|
|
11
|
+
* headers, so the current span is the parent: `traceparent`, `tracestate`,
|
|
12
|
+
* and whatever else that propagator carries.
|
|
13
|
+
* - **Otherwise** (level 1): one trace id per page view — per page load in a
|
|
14
|
+
* browser, per client in Node — a fresh span id per request, and a sampled
|
|
15
|
+
* flag decided once per page view from {@link ClientTelemetryOptions.sampleRate}.
|
|
16
|
+
*
|
|
17
|
+
* Nothing is sent to any origin but the API's own: a trace id is an identifier,
|
|
18
|
+
* and a third party has no business correlating a user's requests by it. And
|
|
19
|
+
* nothing at all where a `fetch` instrumentation is listening (a server with
|
|
20
|
+
* OpenTelemetry's undici instrumentation): it writes the request's own
|
|
21
|
+
* context, and two `traceparent` headers would be read as none.
|
|
22
|
+
*
|
|
23
|
+
* `@opentelemetry/api` is not imported. Every copy of it — whichever version
|
|
24
|
+
* an app bundles — registers its globals on `globalThis` under
|
|
25
|
+
* `Symbol.for('opentelemetry.js.api.1')`, which is how two copies in one page
|
|
26
|
+
* already share a provider. Reading the propagator and context manager from
|
|
27
|
+
* there costs a browser bundle nothing when no SDK is loaded, and still finds
|
|
28
|
+
* the SDK when one is.
|
|
29
|
+
*/
|
|
30
|
+
/** Telemetry on a client: `true` for the defaults, or these options. */
|
|
31
|
+
interface ClientTelemetryOptions {
|
|
32
|
+
/**
|
|
33
|
+
* The fraction of page views whose requests are sampled, from 0 to 1, when
|
|
34
|
+
* no OpenTelemetry context is active. Decided once per page view, so a
|
|
35
|
+
* page's requests are all kept or all dropped together.
|
|
36
|
+
*
|
|
37
|
+
* Use the stage's rate. The API caps an incoming sampled flag at its own
|
|
38
|
+
* rate anyway, and decides from the trace id the same way this does, so a
|
|
39
|
+
* page view sampled here at the API's rate is sampled there too.
|
|
40
|
+
* @default 1
|
|
41
|
+
*/
|
|
42
|
+
sampleRate?: number;
|
|
43
|
+
}
|
|
44
|
+
/** A `sampleRate` outside 0–1, which no sampler can honour. */
|
|
45
|
+
declare class InvalidClientSampleRate extends Error {
|
|
46
|
+
readonly sampleRate: number;
|
|
47
|
+
constructor(sampleRate: number);
|
|
48
|
+
}
|
|
49
|
+
/** Adds trace headers to a request to `url`, when it is the API's own. */
|
|
50
|
+
type TraceContextInjector = (url: string, headers: Record<string, string>) => void;
|
|
51
|
+
/**
|
|
52
|
+
* Whether a trace is sampled at `rate`, from its id.
|
|
53
|
+
*
|
|
54
|
+
* The same rule as OpenTelemetry's `TraceIdRatioBasedSampler`: the id's four
|
|
55
|
+
* 32-bit words XORed together, under `rate` of the 32-bit range. The trace id
|
|
56
|
+
* is random, so this samples `rate` of page views — and the API, applying the
|
|
57
|
+
* same rule to the same id at the same rate, keeps exactly the page views kept
|
|
58
|
+
* here rather than a random `rate` of them.
|
|
59
|
+
*/
|
|
60
|
+
declare function sampledAt(traceId: string, rate: number): boolean;
|
|
61
|
+
/**
|
|
62
|
+
* An injector for a client whose API is at `baseURL`, or undefined when
|
|
63
|
+
* telemetry is off.
|
|
64
|
+
*/
|
|
65
|
+
declare function traceContextInjector(baseURL: string, telemetry: boolean | ClientTelemetryOptions | undefined): TraceContextInjector | undefined;
|
|
66
|
+
//#endregion
|
|
67
|
+
export { traceContextInjector as a, sampledAt as i, InvalidClientSampleRate as n, TraceContextInjector as r, ClientTelemetryOptions as t };
|
|
68
|
+
//# sourceMappingURL=telemetry-g3BE86Wd.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-g3BE86Wd.d.mts","names":[],"sources":["../src/telemetry.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BiB;;;;;;;;;;;EAWhB;;;cAIY,gCAAgC;WACvB;EAArB,YAAqB;;;KASV,wBACX,aACA,SAAS;;;;;;;;;;iBAiEM,UAAU,iBAAiB;;;;;iBA6E3B,qBACf,iBACA,qBAAqB,qCACnB"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/telemetry.ts
|
|
3
|
+
/** A `sampleRate` outside 0–1, which no sampler can honour. */
|
|
4
|
+
var InvalidClientSampleRate = class extends Error {
|
|
5
|
+
sampleRate;
|
|
6
|
+
constructor(sampleRate) {
|
|
7
|
+
super(`telemetry.sampleRate must be a number from 0 (no page views) to 1 (every page view), got ${sampleRate}. Pass the stage's sample rate, such as 0.1.`);
|
|
8
|
+
this.sampleRate = sampleRate;
|
|
9
|
+
this.name = "InvalidClientSampleRate";
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
const OTEL_GLOBAL = Symbol.for("opentelemetry.js.api.1");
|
|
13
|
+
const setter = { set(carrier, key, value) {
|
|
14
|
+
carrier[key] = value;
|
|
15
|
+
} };
|
|
16
|
+
/**
|
|
17
|
+
* The headers the registered propagator writes for the active context, or
|
|
18
|
+
* undefined when there is no SDK or no span to continue.
|
|
19
|
+
*/
|
|
20
|
+
function fromActiveContext() {
|
|
21
|
+
const api = globalThis[OTEL_GLOBAL];
|
|
22
|
+
if (!api?.propagation || !api.context) return void 0;
|
|
23
|
+
const carrier = {};
|
|
24
|
+
try {
|
|
25
|
+
api.propagation.inject(api.context.active(), carrier, setter);
|
|
26
|
+
} catch {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
return carrier.traceparent ? carrier : void 0;
|
|
30
|
+
}
|
|
31
|
+
/** `bytes` crypto-random bytes as lowercase hex, never all zeros. */
|
|
32
|
+
function randomHex(bytes) {
|
|
33
|
+
const buffer = new Uint8Array(bytes);
|
|
34
|
+
do
|
|
35
|
+
globalThis.crypto.getRandomValues(buffer);
|
|
36
|
+
while (buffer.every((byte) => byte === 0));
|
|
37
|
+
let hex = "";
|
|
38
|
+
for (const byte of buffer) hex += byte.toString(16).padStart(2, "0");
|
|
39
|
+
return hex;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Whether a trace is sampled at `rate`, from its id.
|
|
43
|
+
*
|
|
44
|
+
* The same rule as OpenTelemetry's `TraceIdRatioBasedSampler`: the id's four
|
|
45
|
+
* 32-bit words XORed together, under `rate` of the 32-bit range. The trace id
|
|
46
|
+
* is random, so this samples `rate` of page views — and the API, applying the
|
|
47
|
+
* same rule to the same id at the same rate, keeps exactly the page views kept
|
|
48
|
+
* here rather than a random `rate` of them.
|
|
49
|
+
*/
|
|
50
|
+
function sampledAt(traceId, rate) {
|
|
51
|
+
if (rate >= 1) return true;
|
|
52
|
+
if (rate <= 0) return false;
|
|
53
|
+
let accumulation = 0;
|
|
54
|
+
for (let i = 0; i < traceId.length; i += 8) accumulation = (accumulation ^ parseInt(traceId.slice(i, i + 8), 16)) >>> 0;
|
|
55
|
+
return accumulation < Math.floor(rate * 4294967295);
|
|
56
|
+
}
|
|
57
|
+
let browserPageView;
|
|
58
|
+
/**
|
|
59
|
+
* The page view a request belongs to: the page load's in a browser, shared by
|
|
60
|
+
* every client on the page, or this client's own elsewhere — a server process
|
|
61
|
+
* outlives any one user action, so one trace for all of it would mean nothing.
|
|
62
|
+
*/
|
|
63
|
+
function pageViewFor(own) {
|
|
64
|
+
if (!(typeof window !== "undefined" && typeof document !== "undefined")) return own();
|
|
65
|
+
browserPageView ??= { traceId: randomHex(16) };
|
|
66
|
+
return browserPageView;
|
|
67
|
+
}
|
|
68
|
+
/** The origin of `url`, resolved the way `fetch` would, or undefined. */
|
|
69
|
+
function originOf(url) {
|
|
70
|
+
try {
|
|
71
|
+
const base = globalThis.location?.href;
|
|
72
|
+
return new URL(url, base).origin;
|
|
73
|
+
} catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
let fetchRequests;
|
|
78
|
+
/**
|
|
79
|
+
* Whether something instruments `fetch` in this process: OpenTelemetry's
|
|
80
|
+
* undici instrumentation, or an APM built on it, listening on undici's
|
|
81
|
+
* diagnostics channel. It opens each request's CLIENT span and appends that
|
|
82
|
+
* span's `traceparent` itself, so one written here as well would reach the API
|
|
83
|
+
* as two values joined — `a, b` — which no propagator reads.
|
|
84
|
+
*
|
|
85
|
+
* Asked through `process.getBuiltinModule`, so a browser bundle imports no
|
|
86
|
+
* Node module; anywhere without it, nothing is listening.
|
|
87
|
+
*/
|
|
88
|
+
function fetchIsInstrumented() {
|
|
89
|
+
if (fetchRequests === void 0) {
|
|
90
|
+
const getBuiltinModule = globalThis.process?.getBuiltinModule;
|
|
91
|
+
fetchRequests = (getBuiltinModule?.("node:diagnostics_channel"))?.channel("undici:request:create") ?? null;
|
|
92
|
+
}
|
|
93
|
+
return fetchRequests?.hasSubscribers === true;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* An injector for a client whose API is at `baseURL`, or undefined when
|
|
97
|
+
* telemetry is off.
|
|
98
|
+
*/
|
|
99
|
+
function traceContextInjector(baseURL, telemetry) {
|
|
100
|
+
if (!telemetry) return void 0;
|
|
101
|
+
const sampleRate = telemetry === true ? 1 : telemetry.sampleRate ?? 1;
|
|
102
|
+
if (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) throw new InvalidClientSampleRate(sampleRate);
|
|
103
|
+
const apiOrigin = originOf(baseURL || "/");
|
|
104
|
+
let own;
|
|
105
|
+
const ownPageView = () => {
|
|
106
|
+
own ??= { traceId: randomHex(16) };
|
|
107
|
+
return own;
|
|
108
|
+
};
|
|
109
|
+
return (url, headers) => {
|
|
110
|
+
if (!apiOrigin || originOf(url) !== apiOrigin) return;
|
|
111
|
+
if (Object.keys(headers).some((h) => h.toLowerCase() === "traceparent")) return;
|
|
112
|
+
if (fetchIsInstrumented()) return;
|
|
113
|
+
const active = fromActiveContext();
|
|
114
|
+
if (active) {
|
|
115
|
+
Object.assign(headers, active);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const { traceId } = pageViewFor(ownPageView);
|
|
119
|
+
const flags = sampledAt(traceId, sampleRate) ? "01" : "00";
|
|
120
|
+
headers.traceparent = `00-${traceId}-${randomHex(8)}-${flags}`;
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
exports.InvalidClientSampleRate = InvalidClientSampleRate;
|
|
125
|
+
exports.sampledAt = sampledAt;
|
|
126
|
+
exports.traceContextInjector = traceContextInjector;
|
|
127
|
+
|
|
128
|
+
//# sourceMappingURL=telemetry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.cjs","names":[],"sources":["../src/telemetry.ts"],"sourcesContent":["/**\n * W3C trace context on the requests a client makes to its own API, so a user\n * action in the browser and the API request it causes are one trace.\n *\n * Two levels, chosen per request:\n *\n * - **An OpenTelemetry context is active** — a browser SDK has a span open, or\n * this runs on a server (a Next.js server component, an API calling another\n * API) inside a request span. The globally registered propagator writes the\n * headers, so the current span is the parent: `traceparent`, `tracestate`,\n * and whatever else that propagator carries.\n * - **Otherwise** (level 1): one trace id per page view — per page load in a\n * browser, per client in Node — a fresh span id per request, and a sampled\n * flag decided once per page view from {@link ClientTelemetryOptions.sampleRate}.\n *\n * Nothing is sent to any origin but the API's own: a trace id is an identifier,\n * and a third party has no business correlating a user's requests by it. And\n * nothing at all where a `fetch` instrumentation is listening (a server with\n * OpenTelemetry's undici instrumentation): it writes the request's own\n * context, and two `traceparent` headers would be read as none.\n *\n * `@opentelemetry/api` is not imported. Every copy of it — whichever version\n * an app bundles — registers its globals on `globalThis` under\n * `Symbol.for('opentelemetry.js.api.1')`, which is how two copies in one page\n * already share a provider. Reading the propagator and context manager from\n * there costs a browser bundle nothing when no SDK is loaded, and still finds\n * the SDK when one is.\n */\n\n/** Telemetry on a client: `true` for the defaults, or these options. */\nexport interface ClientTelemetryOptions {\n\t/**\n\t * The fraction of page views whose requests are sampled, from 0 to 1, when\n\t * no OpenTelemetry context is active. Decided once per page view, so a\n\t * page's requests are all kept or all dropped together.\n\t *\n\t * Use the stage's rate. The API caps an incoming sampled flag at its own\n\t * rate anyway, and decides from the trace id the same way this does, so a\n\t * page view sampled here at the API's rate is sampled there too.\n\t * @default 1\n\t */\n\tsampleRate?: number;\n}\n\n/** A `sampleRate` outside 0–1, which no sampler can honour. */\nexport class InvalidClientSampleRate extends Error {\n\tconstructor(readonly sampleRate: number) {\n\t\tsuper(\n\t\t\t`telemetry.sampleRate must be a number from 0 (no page views) to 1 (every page view), got ${sampleRate}. Pass the stage's sample rate, such as 0.1.`,\n\t\t);\n\t\tthis.name = 'InvalidClientSampleRate';\n\t}\n}\n\n/** Adds trace headers to a request to `url`, when it is the API's own. */\nexport type TraceContextInjector = (\n\turl: string,\n\theaders: Record<string, string>,\n) => void;\n\n/** The slice of `@opentelemetry/api`'s global registry this reads. */\ninterface OtelGlobal {\n\tcontext?: { active(): unknown };\n\tpropagation?: {\n\t\tinject(\n\t\t\tcontext: unknown,\n\t\t\tcarrier: Record<string, string>,\n\t\t\tsetter: {\n\t\t\t\tset(carrier: Record<string, string>, key: string, value: string): void;\n\t\t\t},\n\t\t): void;\n\t};\n}\n\nconst OTEL_GLOBAL = Symbol.for('opentelemetry.js.api.1');\n\nconst setter = {\n\tset(carrier: Record<string, string>, key: string, value: string) {\n\t\tcarrier[key] = value;\n\t},\n};\n\n/**\n * The headers the registered propagator writes for the active context, or\n * undefined when there is no SDK or no span to continue.\n */\nfunction fromActiveContext(): Record<string, string> | undefined {\n\tconst api = (globalThis as Record<symbol, OtelGlobal | undefined>)[\n\t\tOTEL_GLOBAL\n\t];\n\tif (!api?.propagation || !api.context) return undefined;\n\n\tconst carrier: Record<string, string> = {};\n\ttry {\n\t\tapi.propagation.inject(api.context.active(), carrier, setter);\n\t} catch {\n\t\treturn undefined;\n\t}\n\t// The W3C propagator writes nothing without a valid, unsuppressed span.\n\treturn carrier.traceparent ? carrier : undefined;\n}\n\n/** `bytes` crypto-random bytes as lowercase hex, never all zeros. */\nfunction randomHex(bytes: number): string {\n\tconst buffer = new Uint8Array(bytes);\n\tdo {\n\t\tglobalThis.crypto.getRandomValues(buffer);\n\t} while (buffer.every((byte) => byte === 0));\n\tlet hex = '';\n\tfor (const byte of buffer) hex += byte.toString(16).padStart(2, '0');\n\treturn hex;\n}\n\n/**\n * Whether a trace is sampled at `rate`, from its id.\n *\n * The same rule as OpenTelemetry's `TraceIdRatioBasedSampler`: the id's four\n * 32-bit words XORed together, under `rate` of the 32-bit range. The trace id\n * is random, so this samples `rate` of page views — and the API, applying the\n * same rule to the same id at the same rate, keeps exactly the page views kept\n * here rather than a random `rate` of them.\n */\nexport function sampledAt(traceId: string, rate: number): boolean {\n\tif (rate >= 1) return true;\n\tif (rate <= 0) return false;\n\tlet accumulation = 0;\n\tfor (let i = 0; i < traceId.length; i += 8) {\n\t\taccumulation = (accumulation ^ parseInt(traceId.slice(i, i + 8), 16)) >>> 0;\n\t}\n\treturn accumulation < Math.floor(rate * 0xffffffff);\n}\n\n/** A page view: one trace id for every request made during it. */\ninterface PageView {\n\ttraceId: string;\n}\n\nlet browserPageView: PageView | undefined;\n\n/**\n * The page view a request belongs to: the page load's in a browser, shared by\n * every client on the page, or this client's own elsewhere — a server process\n * outlives any one user action, so one trace for all of it would mean nothing.\n */\nfunction pageViewFor(own: () => PageView): PageView {\n\tconst browser =\n\t\ttypeof window !== 'undefined' && typeof document !== 'undefined';\n\tif (!browser) return own();\n\tbrowserPageView ??= { traceId: randomHex(16) };\n\treturn browserPageView;\n}\n\n/** The origin of `url`, resolved the way `fetch` would, or undefined. */\nfunction originOf(url: string): string | undefined {\n\ttry {\n\t\tconst base = (globalThis as { location?: { href?: string } }).location\n\t\t\t?.href;\n\t\treturn new URL(url, base).origin;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The slice of `node:diagnostics_channel` this reads. */\ninterface DiagnosticsChannels {\n\tchannel(name: string): { hasSubscribers: boolean };\n}\n\nlet fetchRequests: { hasSubscribers: boolean } | null | undefined;\n\n/**\n * Whether something instruments `fetch` in this process: OpenTelemetry's\n * undici instrumentation, or an APM built on it, listening on undici's\n * diagnostics channel. It opens each request's CLIENT span and appends that\n * span's `traceparent` itself, so one written here as well would reach the API\n * as two values joined — `a, b` — which no propagator reads.\n *\n * Asked through `process.getBuiltinModule`, so a browser bundle imports no\n * Node module; anywhere without it, nothing is listening.\n */\nfunction fetchIsInstrumented(): boolean {\n\tif (fetchRequests === undefined) {\n\t\tconst getBuiltinModule = (\n\t\t\tglobalThis as {\n\t\t\t\tprocess?: { getBuiltinModule?: (id: string) => unknown };\n\t\t\t}\n\t\t).process?.getBuiltinModule;\n\t\tconst channels = getBuiltinModule?.('node:diagnostics_channel') as\n\t\t\t| DiagnosticsChannels\n\t\t\t| undefined;\n\t\tfetchRequests = channels?.channel('undici:request:create') ?? null;\n\t}\n\treturn fetchRequests?.hasSubscribers === true;\n}\n\n/**\n * An injector for a client whose API is at `baseURL`, or undefined when\n * telemetry is off.\n */\nexport function traceContextInjector(\n\tbaseURL: string,\n\ttelemetry: boolean | ClientTelemetryOptions | undefined,\n): TraceContextInjector | undefined {\n\tif (!telemetry) return undefined;\n\n\tconst sampleRate = telemetry === true ? 1 : (telemetry.sampleRate ?? 1);\n\tif (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n\t\tthrow new InvalidClientSampleRate(sampleRate);\n\t}\n\n\tconst apiOrigin = originOf(baseURL || '/');\n\tlet own: PageView | undefined;\n\tconst ownPageView = () => {\n\t\town ??= { traceId: randomHex(16) };\n\t\treturn own;\n\t};\n\n\treturn (url, headers) => {\n\t\t// Only the API's own origin: never a third party, and never anything\n\t\t// whose origin cannot be told.\n\t\tif (!apiOrigin || originOf(url) !== apiOrigin) return;\n\t\t// A caller that set its own context keeps it.\n\t\tif (Object.keys(headers).some((h) => h.toLowerCase() === 'traceparent'))\n\t\t\treturn;\n\t\t// A fetch instrumentation writes the request's own context.\n\t\tif (fetchIsInstrumented()) return;\n\n\t\tconst active = fromActiveContext();\n\t\tif (active) {\n\t\t\tObject.assign(headers, active);\n\t\t\treturn;\n\t\t}\n\n\t\tconst { traceId } = pageViewFor(ownPageView);\n\t\tconst flags = sampledAt(traceId, sampleRate) ? '01' : '00';\n\t\theaders.traceparent = `00-${traceId}-${randomHex(8)}-${flags}`;\n\t};\n}\n"],"mappings":";;;AA6CA,IAAa,0BAAb,cAA6C,MAAM;CAC7B;CAArB,YAAY,YAA6B;EACxC,MACC,4FAA4F,WAAW,6CACxG;EAHoB,KAAA,aAAA;EAIpB,KAAK,OAAO;CACb;AACD;AAsBA,MAAM,cAAc,OAAO,IAAI,wBAAwB;AAEvD,MAAM,SAAS,EACd,IAAI,SAAiC,KAAa,OAAe;CAChE,QAAQ,OAAO;AAChB,EACD;;;;;AAMA,SAAS,oBAAwD;CAChE,MAAM,MAAO,WACZ;CAED,IAAI,CAAC,KAAK,eAAe,CAAC,IAAI,SAAS,OAAO,KAAA;CAE9C,MAAM,UAAkC,CAAC;CACzC,IAAI;EACH,IAAI,YAAY,OAAO,IAAI,QAAQ,OAAO,GAAG,SAAS,MAAM;CAC7D,QAAQ;EACP;CACD;CAEA,OAAO,QAAQ,cAAc,UAAU,KAAA;AACxC;;AAGA,SAAS,UAAU,OAAuB;CACzC,MAAM,SAAS,IAAI,WAAW,KAAK;CACnC;EACC,WAAW,OAAO,gBAAgB,MAAM;QAChC,OAAO,OAAO,SAAS,SAAS,CAAC;CAC1C,IAAI,MAAM;CACV,KAAK,MAAM,QAAQ,QAAQ,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;CACnE,OAAO;AACR;;;;;;;;;;AAWA,SAAgB,UAAU,SAAiB,MAAuB;CACjE,IAAI,QAAQ,GAAG,OAAO;CACtB,IAAI,QAAQ,GAAG,OAAO;CACtB,IAAI,eAAe;CACnB,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,GACxC,gBAAgB,eAAe,SAAS,QAAQ,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE,OAAO;CAE3E,OAAO,eAAe,KAAK,MAAM,OAAO,UAAU;AACnD;AAOA,IAAI;;;;;;AAOJ,SAAS,YAAY,KAA+B;CAGnD,IAAI,EADH,OAAO,WAAW,eAAe,OAAO,aAAa,cACxC,OAAO,IAAI;CACzB,oBAAoB,EAAE,SAAS,UAAU,EAAE,EAAE;CAC7C,OAAO;AACR;;AAGA,SAAS,SAAS,KAAiC;CAClD,IAAI;EACH,MAAM,OAAQ,WAAgD,UAC3D;EACH,OAAO,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;CAC3B,QAAQ;EACP;CACD;AACD;AAOA,IAAI;;;;;;;;;;;AAYJ,SAAS,sBAA+B;CACvC,IAAI,kBAAkB,KAAA,GAAW;EAChC,MAAM,mBACL,WAGC,SAAS;EAIX,iBAHiB,mBAAmB,0BAA0B,EAAA,EAGpC,QAAQ,uBAAuB,KAAK;CAC/D;CACA,OAAO,eAAe,mBAAmB;AAC1C;;;;;AAMA,SAAgB,qBACf,SACA,WACmC;CACnC,IAAI,CAAC,WAAW,OAAO,KAAA;CAEvB,MAAM,aAAa,cAAc,OAAO,IAAK,UAAU,cAAc;CACrE,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,KAAK,aAAa,GAClE,MAAM,IAAI,wBAAwB,UAAU;CAG7C,MAAM,YAAY,SAAS,WAAW,GAAG;CACzC,IAAI;CACJ,MAAM,oBAAoB;EACzB,QAAQ,EAAE,SAAS,UAAU,EAAE,EAAE;EACjC,OAAO;CACR;CAEA,QAAQ,KAAK,YAAY;EAGxB,IAAI,CAAC,aAAa,SAAS,GAAG,MAAM,WAAW;EAE/C,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,MAAM,EAAE,YAAY,MAAM,aAAa,GACrE;EAED,IAAI,oBAAoB,GAAG;EAE3B,MAAM,SAAS,kBAAkB;EACjC,IAAI,QAAQ;GACX,OAAO,OAAO,SAAS,MAAM;GAC7B;EACD;EAEA,MAAM,EAAE,YAAY,YAAY,WAAW;EAC3C,MAAM,QAAQ,UAAU,SAAS,UAAU,IAAI,OAAO;EACtD,QAAQ,cAAc,MAAM,QAAQ,GAAG,UAAU,CAAC,EAAE,GAAG;CACxD;AACD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as traceContextInjector, i as sampledAt, n as InvalidClientSampleRate, r as TraceContextInjector, t as ClientTelemetryOptions } from "./telemetry-g3BE86Wd.cjs";
|
|
2
|
+
export { ClientTelemetryOptions, InvalidClientSampleRate, TraceContextInjector, sampledAt, traceContextInjector };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as traceContextInjector, i as sampledAt, n as InvalidClientSampleRate, r as TraceContextInjector, t as ClientTelemetryOptions } from "./telemetry-g3BE86Wd.mjs";
|
|
2
|
+
export { ClientTelemetryOptions, InvalidClientSampleRate, TraceContextInjector, sampledAt, traceContextInjector };
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
//#region src/telemetry.ts
|
|
2
|
+
/** A `sampleRate` outside 0–1, which no sampler can honour. */
|
|
3
|
+
var InvalidClientSampleRate = class extends Error {
|
|
4
|
+
sampleRate;
|
|
5
|
+
constructor(sampleRate) {
|
|
6
|
+
super(`telemetry.sampleRate must be a number from 0 (no page views) to 1 (every page view), got ${sampleRate}. Pass the stage's sample rate, such as 0.1.`);
|
|
7
|
+
this.sampleRate = sampleRate;
|
|
8
|
+
this.name = "InvalidClientSampleRate";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const OTEL_GLOBAL = Symbol.for("opentelemetry.js.api.1");
|
|
12
|
+
const setter = { set(carrier, key, value) {
|
|
13
|
+
carrier[key] = value;
|
|
14
|
+
} };
|
|
15
|
+
/**
|
|
16
|
+
* The headers the registered propagator writes for the active context, or
|
|
17
|
+
* undefined when there is no SDK or no span to continue.
|
|
18
|
+
*/
|
|
19
|
+
function fromActiveContext() {
|
|
20
|
+
const api = globalThis[OTEL_GLOBAL];
|
|
21
|
+
if (!api?.propagation || !api.context) return void 0;
|
|
22
|
+
const carrier = {};
|
|
23
|
+
try {
|
|
24
|
+
api.propagation.inject(api.context.active(), carrier, setter);
|
|
25
|
+
} catch {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
return carrier.traceparent ? carrier : void 0;
|
|
29
|
+
}
|
|
30
|
+
/** `bytes` crypto-random bytes as lowercase hex, never all zeros. */
|
|
31
|
+
function randomHex(bytes) {
|
|
32
|
+
const buffer = new Uint8Array(bytes);
|
|
33
|
+
do
|
|
34
|
+
globalThis.crypto.getRandomValues(buffer);
|
|
35
|
+
while (buffer.every((byte) => byte === 0));
|
|
36
|
+
let hex = "";
|
|
37
|
+
for (const byte of buffer) hex += byte.toString(16).padStart(2, "0");
|
|
38
|
+
return hex;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Whether a trace is sampled at `rate`, from its id.
|
|
42
|
+
*
|
|
43
|
+
* The same rule as OpenTelemetry's `TraceIdRatioBasedSampler`: the id's four
|
|
44
|
+
* 32-bit words XORed together, under `rate` of the 32-bit range. The trace id
|
|
45
|
+
* is random, so this samples `rate` of page views — and the API, applying the
|
|
46
|
+
* same rule to the same id at the same rate, keeps exactly the page views kept
|
|
47
|
+
* here rather than a random `rate` of them.
|
|
48
|
+
*/
|
|
49
|
+
function sampledAt(traceId, rate) {
|
|
50
|
+
if (rate >= 1) return true;
|
|
51
|
+
if (rate <= 0) return false;
|
|
52
|
+
let accumulation = 0;
|
|
53
|
+
for (let i = 0; i < traceId.length; i += 8) accumulation = (accumulation ^ parseInt(traceId.slice(i, i + 8), 16)) >>> 0;
|
|
54
|
+
return accumulation < Math.floor(rate * 4294967295);
|
|
55
|
+
}
|
|
56
|
+
let browserPageView;
|
|
57
|
+
/**
|
|
58
|
+
* The page view a request belongs to: the page load's in a browser, shared by
|
|
59
|
+
* every client on the page, or this client's own elsewhere — a server process
|
|
60
|
+
* outlives any one user action, so one trace for all of it would mean nothing.
|
|
61
|
+
*/
|
|
62
|
+
function pageViewFor(own) {
|
|
63
|
+
if (!(typeof window !== "undefined" && typeof document !== "undefined")) return own();
|
|
64
|
+
browserPageView ??= { traceId: randomHex(16) };
|
|
65
|
+
return browserPageView;
|
|
66
|
+
}
|
|
67
|
+
/** The origin of `url`, resolved the way `fetch` would, or undefined. */
|
|
68
|
+
function originOf(url) {
|
|
69
|
+
try {
|
|
70
|
+
const base = globalThis.location?.href;
|
|
71
|
+
return new URL(url, base).origin;
|
|
72
|
+
} catch {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
let fetchRequests;
|
|
77
|
+
/**
|
|
78
|
+
* Whether something instruments `fetch` in this process: OpenTelemetry's
|
|
79
|
+
* undici instrumentation, or an APM built on it, listening on undici's
|
|
80
|
+
* diagnostics channel. It opens each request's CLIENT span and appends that
|
|
81
|
+
* span's `traceparent` itself, so one written here as well would reach the API
|
|
82
|
+
* as two values joined — `a, b` — which no propagator reads.
|
|
83
|
+
*
|
|
84
|
+
* Asked through `process.getBuiltinModule`, so a browser bundle imports no
|
|
85
|
+
* Node module; anywhere without it, nothing is listening.
|
|
86
|
+
*/
|
|
87
|
+
function fetchIsInstrumented() {
|
|
88
|
+
if (fetchRequests === void 0) {
|
|
89
|
+
const getBuiltinModule = globalThis.process?.getBuiltinModule;
|
|
90
|
+
fetchRequests = (getBuiltinModule?.("node:diagnostics_channel"))?.channel("undici:request:create") ?? null;
|
|
91
|
+
}
|
|
92
|
+
return fetchRequests?.hasSubscribers === true;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* An injector for a client whose API is at `baseURL`, or undefined when
|
|
96
|
+
* telemetry is off.
|
|
97
|
+
*/
|
|
98
|
+
function traceContextInjector(baseURL, telemetry) {
|
|
99
|
+
if (!telemetry) return void 0;
|
|
100
|
+
const sampleRate = telemetry === true ? 1 : telemetry.sampleRate ?? 1;
|
|
101
|
+
if (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) throw new InvalidClientSampleRate(sampleRate);
|
|
102
|
+
const apiOrigin = originOf(baseURL || "/");
|
|
103
|
+
let own;
|
|
104
|
+
const ownPageView = () => {
|
|
105
|
+
own ??= { traceId: randomHex(16) };
|
|
106
|
+
return own;
|
|
107
|
+
};
|
|
108
|
+
return (url, headers) => {
|
|
109
|
+
if (!apiOrigin || originOf(url) !== apiOrigin) return;
|
|
110
|
+
if (Object.keys(headers).some((h) => h.toLowerCase() === "traceparent")) return;
|
|
111
|
+
if (fetchIsInstrumented()) return;
|
|
112
|
+
const active = fromActiveContext();
|
|
113
|
+
if (active) {
|
|
114
|
+
Object.assign(headers, active);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const { traceId } = pageViewFor(ownPageView);
|
|
118
|
+
const flags = sampledAt(traceId, sampleRate) ? "01" : "00";
|
|
119
|
+
headers.traceparent = `00-${traceId}-${randomHex(8)}-${flags}`;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
123
|
+
export { InvalidClientSampleRate, sampledAt, traceContextInjector };
|
|
124
|
+
|
|
125
|
+
//# sourceMappingURL=telemetry.mjs.map
|