@openmeter/sdk 1.0.0-beta.9 → 1.0.0-beta.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +62 -50
  2. package/dist/cjs/clients/client.cjs +117 -0
  3. package/dist/cjs/clients/client.d.cts +40 -0
  4. package/dist/cjs/clients/client.js.map +1 -0
  5. package/dist/cjs/clients/event.cjs +71 -0
  6. package/dist/cjs/clients/event.d.cts +79 -0
  7. package/dist/cjs/clients/event.js.map +1 -0
  8. package/dist/cjs/clients/meter.cjs +69 -0
  9. package/dist/cjs/clients/meter.d.cts +75 -0
  10. package/dist/cjs/clients/meter.js.map +1 -0
  11. package/dist/cjs/clients/portal.cjs +41 -0
  12. package/dist/cjs/clients/portal.d.cts +22 -0
  13. package/dist/cjs/clients/portal.js.map +1 -0
  14. package/dist/cjs/clients/subject.cjs +60 -0
  15. package/dist/cjs/clients/subject.d.cts +27 -0
  16. package/dist/cjs/clients/subject.js.map +1 -0
  17. package/dist/cjs/index.cjs +24 -0
  18. package/dist/cjs/index.d.cts +15 -0
  19. package/dist/cjs/index.js.map +1 -0
  20. package/dist/cjs/schemas/openapi.cjs +7 -0
  21. package/dist/cjs/schemas/openapi.d.cts +1850 -0
  22. package/dist/cjs/schemas/openapi.js.map +1 -0
  23. package/dist/cjs/test/agent.cjs +266 -0
  24. package/dist/cjs/test/agent.d.cts +2 -0
  25. package/dist/cjs/test/agent.js.map +1 -0
  26. package/dist/cjs/test/mocks.cjs +44 -0
  27. package/dist/cjs/test/mocks.d.cts +14 -0
  28. package/dist/cjs/test/mocks.js.map +1 -0
  29. package/dist/cjs/tsconfig.acfee89b.tsbuildinfo +1 -0
  30. package/dist/cjs/tsconfig.e6ebbd29.tsbuildinfo +1 -0
  31. package/dist/clients/client.d.ts +1 -1
  32. package/dist/clients/client.js +9 -1
  33. package/dist/clients/client.js.map +1 -0
  34. package/dist/clients/event.d.ts +5 -5
  35. package/dist/clients/event.js +29 -18
  36. package/dist/clients/event.js.map +1 -0
  37. package/dist/clients/meter.d.ts +9 -37
  38. package/dist/clients/meter.js +1 -15
  39. package/dist/clients/meter.js.map +1 -0
  40. package/dist/clients/portal.d.ts +22 -0
  41. package/dist/clients/portal.js +37 -0
  42. package/dist/clients/portal.js.map +1 -0
  43. package/dist/clients/subject.d.ts +27 -0
  44. package/dist/clients/subject.js +56 -0
  45. package/dist/clients/subject.js.map +1 -0
  46. package/dist/index.d.ts +6 -3
  47. package/dist/index.js +8 -2
  48. package/dist/index.js.map +1 -0
  49. package/dist/schemas/openapi.d.ts +1561 -250
  50. package/dist/schemas/openapi.js +1 -0
  51. package/dist/schemas/openapi.js.map +1 -0
  52. package/dist/test/agent.js +108 -29
  53. package/dist/test/agent.js.map +1 -0
  54. package/dist/test/mocks.d.ts +2 -0
  55. package/dist/test/mocks.js +9 -0
  56. package/dist/test/mocks.js.map +1 -0
  57. package/dist/tsconfig.tsbuildinfo +1 -1
  58. package/package.json +43 -33
  59. package/dist/next.d.ts +0 -15
  60. package/dist/next.js +0 -46
  61. package/index.ts +0 -24
  62. package/next.ts +0 -76
package/README.md CHANGED
@@ -54,6 +54,12 @@ const event: Event = {
54
54
  await openmeter.events.ingest(event)
55
55
  ```
56
56
 
57
+ ### batch ingest
58
+
59
+ ```ts
60
+ await openmeter.events.ingest([event1, event2, event3])
61
+ ```
62
+
57
63
  #### list
58
64
 
59
65
  Retrieve latest raw events. Useful for debugging.
@@ -96,7 +102,7 @@ const values = await openmeter.meters.query('my-meter-slug', {
96
102
  })
97
103
  ```
98
104
 
99
- #### subjects
105
+ #### meter subjects
100
106
 
101
107
  List meter subjects.
102
108
 
@@ -104,57 +110,63 @@ List meter subjects.
104
110
  const subjects = await openmeter.meters.subjects('my-meter-slug')
105
111
  ```
106
112
 
107
- ## Helpers
113
+ ### Portal
108
114
 
109
- ### Vercel AI SDK / Next.js
115
+ #### createToken
110
116
 
111
- The OpenAI streaming API used by the Vercel AI SDK doesn't return token usage metadata by default.
112
- The OpenMeter `createOpenAIStreamCallback` helper function decorates the callback with a `onUsage`
113
- callback which you can use to report usage to OpenMeter.
117
+ Create subject specific tokens.
118
+ Useful to build consumer dashboards.
114
119
 
115
120
  ```ts
116
- import OpenAI from 'openai'
117
- import { OpenAIStream, StreamingTextResponse } from 'ai'
118
- import { createOpenAIStreamCallback } from '@openmeter/sdk'
119
-
120
- export async function POST(req: Request) {
121
- const { messages } = await req.json()
122
- const model = 'gpt-3.5-turbo'
123
-
124
- const response = await openai.chat.completions.create({
125
- model,
126
- messages,
127
- stream: true,
128
- })
129
-
130
- const streamCallbacks = await createOpenAIStreamCallback(
131
- {
132
- model,
133
- prompts: messages.map(({ content }) => content),
134
- },
135
- {
136
- // onToken() => {...}
137
- // onFinal() => {...}
138
- async onUsage(usage) {
139
- try {
140
- await openmeter.events.ingest({
141
- source: 'my-app',
142
- type: 'my-event-type',
143
- subject: 'my-customer-id',
144
- data: {
145
- // Usage is { total_tokens, prompt_tokens, completion_tokens }
146
- ...usage,
147
- model,
148
- },
149
- })
150
- } catch (err) {
151
- console.error('failed to ingest usage', err)
152
- }
153
- },
154
- }
155
- )
156
-
157
- const stream = OpenAIStream(response, streamCallbacks)
158
- return new StreamingTextResponse(stream)
159
- }
121
+ const token = await openmeter.portal.createToken({ subject: 'customer-1' })
122
+ ```
123
+
124
+ #### invalidateTokens
125
+
126
+ Invalidate portal tokens for all or specific subjects.
127
+
128
+ ```ts
129
+ await openmeter.portal.invalidateTokens()
130
+ ```
131
+
132
+ ### Subject
133
+
134
+ Subject mappings. Like display name and metadata.
135
+
136
+ #### upsert
137
+
138
+ Upsert subjects.
139
+
140
+ ```ts
141
+ const subjects = await openmeter.subjects.upsert([
142
+ {
143
+ key: 'customer-1',
144
+ displayName: 'ACME'
145
+ }
146
+ ])
147
+ ```
148
+
149
+ #### list
150
+
151
+ List subjects.
152
+
153
+ ```ts
154
+ const subjects = await openmeter.subjects.list()
155
+ ```
156
+
157
+ #### get
158
+
159
+ Get subject by key.
160
+
161
+ ```ts
162
+ const subjects = await openmeter.subjects.get('customer-1')
163
+ ```
164
+
165
+ #### delete
166
+
167
+ Delete subject by key.
168
+ It doesn't delete corresponding usage.
169
+
170
+ ```ts
171
+ await openmeter.subjects.delete('customer-1')
160
172
  ```
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpError = exports.BaseClient = void 0;
4
+ const undici_1 = require("undici");
5
+ class BaseClient {
6
+ config;
7
+ constructor(config) {
8
+ this.config = config;
9
+ }
10
+ async request({ path, method, searchParams, headers, body, options, }) {
11
+ // Building URL
12
+ const url = this.getUrl(path, searchParams);
13
+ // Request options
14
+ const reqHeaders = {
15
+ Accept: 'application/json',
16
+ ...headers,
17
+ ...this.getAuthHeaders(),
18
+ ...this.config.headers,
19
+ ...options?.headers,
20
+ };
21
+ const reqOpts = {
22
+ method,
23
+ headers: reqHeaders,
24
+ };
25
+ // Optional body
26
+ if (body) {
27
+ if (!reqHeaders['Content-Type'] && !reqHeaders['content-type']) {
28
+ throw new Error('Content Type is required with body');
29
+ }
30
+ reqOpts.body = body;
31
+ }
32
+ const resp = await (0, undici_1.request)(url, reqOpts);
33
+ // Error handling
34
+ if (resp.statusCode > 399) {
35
+ if (resp.headers['content-type'] === 'application/problem+json') {
36
+ const problem = (await resp.body.json());
37
+ throw new HttpError({
38
+ statusCode: resp.statusCode,
39
+ problem,
40
+ });
41
+ }
42
+ // Requests can fail before API, in this case we only have a status code
43
+ throw new HttpError({
44
+ statusCode: resp.statusCode,
45
+ });
46
+ }
47
+ // Response parsing
48
+ if (resp.statusCode === 204 || resp.headers['content-length'] === '0') {
49
+ return undefined;
50
+ }
51
+ if (resp.headers['content-type'] === 'application/json') {
52
+ return (await resp.body.json());
53
+ }
54
+ if (!resp.headers['content-type']) {
55
+ throw new Error('Missing content type');
56
+ }
57
+ throw new Error(`Unknown content type: ${resp.headers['content-type']}`);
58
+ }
59
+ getUrl(path, searchParams) {
60
+ let qs = searchParams ? searchParams.toString() : '';
61
+ qs = qs.length > 0 ? `?${qs}` : '';
62
+ const url = new URL(`${path}${qs}`, this.config.baseUrl);
63
+ return url;
64
+ }
65
+ getAuthHeaders() {
66
+ if (this.config.token) {
67
+ return {
68
+ authorization: `Bearer ${this.config.token}`,
69
+ };
70
+ }
71
+ if (this.config.username && this.config.password) {
72
+ const encoded = Buffer.from(`${this.config.username}:${this.config.password}`).toString('base64');
73
+ return {
74
+ authorization: `Basic ${encoded}`,
75
+ };
76
+ }
77
+ return {};
78
+ }
79
+ static toURLSearchParams(params) {
80
+ const searchParams = new URLSearchParams();
81
+ for (const [key, value] of Object.entries(params)) {
82
+ if (value === undefined) {
83
+ continue;
84
+ }
85
+ if (Array.isArray(value)) {
86
+ for (const item of value) {
87
+ searchParams.append(key, item);
88
+ }
89
+ }
90
+ else if (value instanceof Date) {
91
+ searchParams.append(key, value.toISOString());
92
+ }
93
+ else if (typeof value === 'object') {
94
+ Object.entries(value).forEach(([k, v]) => {
95
+ searchParams.append(`${key}[${k}]`, v);
96
+ });
97
+ }
98
+ else {
99
+ searchParams.append(key, value.toString());
100
+ }
101
+ }
102
+ return searchParams;
103
+ }
104
+ }
105
+ exports.BaseClient = BaseClient;
106
+ class HttpError extends Error {
107
+ statusCode;
108
+ problem;
109
+ constructor({ statusCode, problem, }) {
110
+ super(problem?.type || 'unexpected status code');
111
+ this.name = 'HttpError';
112
+ this.statusCode = statusCode;
113
+ this.problem = problem;
114
+ }
115
+ }
116
+ exports.HttpError = HttpError;
117
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,40 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ import { IncomingHttpHeaders } from 'http';
5
+ import { Dispatcher } from 'undici';
6
+ import { components } from '../schemas/openapi.cjs';
7
+ export type OpenMeterConfig = {
8
+ baseUrl: string;
9
+ token?: string;
10
+ username?: string;
11
+ password?: string;
12
+ headers?: IncomingHttpHeaders;
13
+ };
14
+ export type RequestOptions = {
15
+ headers?: IncomingHttpHeaders;
16
+ };
17
+ export type Problem = components['schemas']['Problem'];
18
+ export declare class BaseClient {
19
+ protected config: OpenMeterConfig;
20
+ constructor(config: OpenMeterConfig);
21
+ protected request<T>({ path, method, searchParams, headers, body, options, }: {
22
+ path: string;
23
+ method: Dispatcher.HttpMethod;
24
+ searchParams?: URLSearchParams;
25
+ headers?: IncomingHttpHeaders;
26
+ body?: string | Buffer | Uint8Array;
27
+ options?: RequestOptions;
28
+ }): Promise<T>;
29
+ protected getUrl(path: string, searchParams?: URLSearchParams): import("url").URL;
30
+ protected getAuthHeaders(): IncomingHttpHeaders;
31
+ protected static toURLSearchParams(params: Record<string, string | number | Date | string[] | Record<string, string> | undefined>): URLSearchParams;
32
+ }
33
+ export declare class HttpError extends Error {
34
+ statusCode: number;
35
+ problem?: Problem;
36
+ constructor({ statusCode, problem, }: {
37
+ statusCode: number;
38
+ problem?: Problem;
39
+ });
40
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../clients/client.ts"],"names":[],"mappings":";;;AACA,mCAA4C;AAuB5C,MAAa,UAAU;IACX,MAAM,CAAiB;IAEjC,YAAY,MAAuB;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAES,KAAK,CAAC,OAAO,CAAI,EACzB,IAAI,EACJ,MAAM,EACN,YAAY,EACZ,OAAO,EACP,IAAI,EACJ,OAAO,GAQR;QACC,eAAe;QACf,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;QAE3C,kBAAkB;QAClB,MAAM,UAAU,GAAwB;YACtC,MAAM,EAAE,kBAAkB;YAC1B,GAAG,OAAO;YACV,GAAG,IAAI,CAAC,cAAc,EAAE;YACxB,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO;YACtB,GAAG,OAAO,EAAE,OAAO;S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IACxB,CAAC;CACF;AAhBD,8BAgBC"}
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EventsClient = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const client_js_1 = require("./client.cjs");
9
+ class EventsClient extends client_js_1.BaseClient {
10
+ constructor(config) {
11
+ super(config);
12
+ }
13
+ /**
14
+ * Ingest usage event in a CloudEvents format
15
+ * @see https://cloudevents.io
16
+ */
17
+ async ingest(usageEvent, options) {
18
+ const isBatch = Array.isArray(usageEvent);
19
+ const cloudEvents = (isBatch ? usageEvent : [usageEvent]).map((ev) => {
20
+ // Validate content type
21
+ if (ev.datacontenttype && ev.datacontenttype !== 'application/json') {
22
+ throw new TypeError(`Unsupported datacontenttype: ${ev.datacontenttype}`);
23
+ }
24
+ // We default where we can to lower the barrier to use CloudEvents
25
+ const cloudEvent = {
26
+ specversion: ev.specversion ?? '1.0',
27
+ id: ev.id ?? crypto_1.default.randomUUID(),
28
+ source: ev.source ?? '@openmeter/sdk',
29
+ type: ev.type,
30
+ subject: ev.subject,
31
+ time: ev.time?.toISOString(),
32
+ datacontenttype: ev.datacontenttype,
33
+ dataschema: ev.dataschema,
34
+ data: ev.data,
35
+ };
36
+ return cloudEvent;
37
+ });
38
+ const contentType = isBatch
39
+ ? 'application/cloudevents-batch+json'
40
+ : 'application/cloudevents+json';
41
+ const body = isBatch
42
+ ? JSON.stringify(cloudEvents)
43
+ : JSON.stringify(cloudEvents[0]);
44
+ // Making Request
45
+ return await this.request({
46
+ path: '/api/v1/events',
47
+ method: 'POST',
48
+ body,
49
+ headers: {
50
+ 'Content-Type': contentType,
51
+ },
52
+ options,
53
+ });
54
+ }
55
+ /**
56
+ * List raw events
57
+ */
58
+ async list(params, options) {
59
+ const searchParams = params
60
+ ? client_js_1.BaseClient.toURLSearchParams(params)
61
+ : undefined;
62
+ return this.request({
63
+ method: 'GET',
64
+ path: `/api/v1/events`,
65
+ searchParams,
66
+ options,
67
+ });
68
+ }
69
+ }
70
+ exports.EventsClient = EventsClient;
71
+ //# sourceMappingURL=event.js.map
@@ -0,0 +1,79 @@
1
+ import { components } from '../schemas/openapi.cjs';
2
+ import { RequestOptions, BaseClient, OpenMeterConfig } from './client.cjs';
3
+ export type CloudEvent = components['schemas']['Event'];
4
+ export type IngestedEvent = components['schemas']['IngestedEvent'];
5
+ export type EventsQueryParams = {
6
+ /**
7
+ * @description Limit number of results. Max: 100
8
+ * @example 25
9
+ */
10
+ limit?: number;
11
+ };
12
+ /**
13
+ * Usage Event
14
+ */
15
+ export type Event = {
16
+ /**
17
+ * @description The version of the CloudEvents specification which the event uses.
18
+ * @example 1.0
19
+ */
20
+ specversion?: string;
21
+ /**
22
+ * @description Unique identifier for the event, defaults to uuid v4.
23
+ * @example "5c10fade-1c9e-4d6c-8275-c52c36731d3c"
24
+ */
25
+ id?: string;
26
+ /**
27
+ * Format: uri-reference
28
+ * @description Identifies the context in which an event happened, defaults to: @openmeter/sdk
29
+ * @example services/service-0
30
+ */
31
+ source?: string;
32
+ /**
33
+ * @description Describes the type of event related to the originating occurrence.
34
+ * @example "api_request"
35
+ */
36
+ type: string;
37
+ /**
38
+ * @description Describes the subject of the event in the context of the event producer (identified by source).
39
+ * @example "customer_id"
40
+ */
41
+ subject: string;
42
+ /**
43
+ * Format: date-time
44
+ * @description Date of when the occurrence happened.
45
+ * @example new Date('2023-01-01T01:01:01.001Z')
46
+ */
47
+ time?: Date;
48
+ /**
49
+ * Format: uri
50
+ * @description Identifies the schema that data adheres to.
51
+ */
52
+ dataschema?: string;
53
+ /**
54
+ * @description Content type of the data value. Must adhere to RFC 2046 format.
55
+ * @example application/json
56
+ * @enum {string|null}
57
+ */
58
+ datacontenttype?: 'application/json';
59
+ /**
60
+ * @description The event payload.
61
+ * @example {
62
+ * "duration_ms": "12",
63
+ * "path": "/hello"
64
+ * }
65
+ */
66
+ data: Record<string, unknown>;
67
+ };
68
+ export declare class EventsClient extends BaseClient {
69
+ constructor(config: OpenMeterConfig);
70
+ /**
71
+ * Ingest usage event in a CloudEvents format
72
+ * @see https://cloudevents.io
73
+ */
74
+ ingest(usageEvent: Event | Event[], options?: RequestOptions): Promise<void>;
75
+ /**
76
+ * List raw events
77
+ */
78
+ list(params?: EventsQueryParams, options?: RequestOptions): Promise<IngestedEvent[]>;
79
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.js","sourceRoot":"","sources":["../../../clients/event.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA2B;AAE3B,2CAAyE;AAuEzE,MAAa,YAAa,SAAQ,sBAAU;IAC1C,YAAY,MAAuB;QACjC,KAAK,CAAC,MAAM,CAAC,CAAA;IACf,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,MAAM,CACjB,UAA2B,EAC3B,OAAwB;QAExB,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;QACzC,MAAM,WAAW,GAAiB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CACzE,CAAC,EAAE,EAAE,EAAE;YACL,wBAAwB;YACxB,IAAI,EAAE,CAAC,eAAe,IAAI,EAAE,CAAC,eAAe,KAAK,kBAAkB,EAAE,CAAC;gBACpE,MAAM,IAAI,SAAS,CACjB,gCAAgC,EAAE,CAAC,eAAe,EAAE,CACrD,CAAA;YACH,CAAC;YAED,kEAAkE;YAClE,MAAM,UAAU,GAAe;gBAC7B,WAAW,EAAE,EAAE,CAAC,WAAW,IAAI,KAAK;gBACpC,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,gBAAM,CAAC,UAAU,EAAE;gBAChC,MAAM,EAAE,EAAE,CAAC,MAAM,IAAI,gBAAgB;gBACrC,IAAI,EAAE,EAAE,CAAC,IAAI;gBACb,OAAO,EAAE,EAAE,CAAC,OAAO;gBACnB,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,WAAW,EAAE;gBAC5B,eAAe,EAAE,EAAE,CAAC,eAAe;gBACnC,UAAU,EAAE,EAAE,CAAC,UAAU;gBACzB,IAAI,EAAE,EAAE,CAAC,IAAI;aACd,CAAA;YAED,OAAO,UAAU,CAAA;QACnB,CAAC,CACF,CAAA;QAED,MAAM,WAAW,GAAG,OAAO;YACzB,CAAC,CAAC,oCAAoC;YACtC,CAAC,CAAC,8BAA8B,CAAA;QAClC,MAAM,IAAI,GAAG,OAAO;YAClB,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC;YAC7B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;QAElC,iBAAiB;QACjB,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC;YACxB,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,MAAM;YACd,IAAI;YACJ,OAAO,EAAE;gBACP,cAAc,EAAE,WAAW;aAC5B;YACD,OAAO;SACR,CAAC,CAAA;IACJ,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,IAAI,CACf,MAA0B,EAC1B,OAAwB;QAExB,MAAM,YAAY,GAAG,MAAM;YACzB,CAAC,CAAC,sBAAU,CAAC,iBAAiB,CAAC,MAAM,CAAC;YACtC,CAAC,CAAC,SAAS,CAAA;QACb,OAAO,IAAI,CAAC,OAAO,CAAkB;YACnC,MAAM,EAAE,KAAK;YACb,IAAI,EAAE,gBAAgB;YACtB,YAAY;YACZ,OAAO;SACR,CAAC,CAAA;IACJ,CAAC;CACF;AA5ED,oCA4EC"}
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MetersClient = exports.MeterAggregation = exports.WindowSize = void 0;
4
+ const client_js_1 = require("./client.cjs");
5
+ var WindowSize;
6
+ (function (WindowSize) {
7
+ WindowSize["MINUTE"] = "MINUTE";
8
+ WindowSize["HOUR"] = "HOUR";
9
+ WindowSize["DAY"] = "DAY";
10
+ })(WindowSize || (exports.WindowSize = WindowSize = {}));
11
+ var MeterAggregation;
12
+ (function (MeterAggregation) {
13
+ MeterAggregation["SUM"] = "SUM";
14
+ MeterAggregation["COUNT"] = "COUNT";
15
+ MeterAggregation["AVG"] = "AVG";
16
+ MeterAggregation["MIN"] = "MIN";
17
+ MeterAggregation["MAX"] = "MAX";
18
+ })(MeterAggregation || (exports.MeterAggregation = MeterAggregation = {}));
19
+ class MetersClient extends client_js_1.BaseClient {
20
+ constructor(config) {
21
+ super(config);
22
+ }
23
+ /**
24
+ * Get one meter by slug
25
+ */
26
+ async get(slug, options) {
27
+ return this.request({
28
+ method: 'GET',
29
+ path: `/api/v1/meters/${slug}`,
30
+ options,
31
+ });
32
+ }
33
+ /**
34
+ * List meters
35
+ */
36
+ async list(options) {
37
+ return this.request({
38
+ method: 'GET',
39
+ path: `/api/v1/meters`,
40
+ options,
41
+ });
42
+ }
43
+ /**
44
+ * Query a meter
45
+ */
46
+ async query(slug, params, options) {
47
+ const searchParams = params
48
+ ? client_js_1.BaseClient.toURLSearchParams(params)
49
+ : undefined;
50
+ return this.request({
51
+ method: 'GET',
52
+ path: `/api/v1/meters/${slug}/query`,
53
+ searchParams,
54
+ options,
55
+ });
56
+ }
57
+ /**
58
+ * List subjects of a meter
59
+ */
60
+ async subjects(slug, options) {
61
+ return this.request({
62
+ method: 'GET',
63
+ path: `/api/v1/meters/${slug}/subjects`,
64
+ options,
65
+ });
66
+ }
67
+ }
68
+ exports.MetersClient = MetersClient;
69
+ //# sourceMappingURL=meter.js.map
@@ -0,0 +1,75 @@
1
+ import { paths, components } from '../schemas/openapi.cjs';
2
+ import { BaseClient, OpenMeterConfig, RequestOptions } from './client.cjs';
3
+ export declare enum WindowSize {
4
+ MINUTE = "MINUTE",
5
+ HOUR = "HOUR",
6
+ DAY = "DAY"
7
+ }
8
+ export declare enum MeterAggregation {
9
+ SUM = "SUM",
10
+ COUNT = "COUNT",
11
+ AVG = "AVG",
12
+ MIN = "MIN",
13
+ MAX = "MAX"
14
+ }
15
+ export type MeterQueryParams = {
16
+ /**
17
+ * @description Subject(s) to filter by.
18
+ * @example ["customer-1", "customer-2"]
19
+ */
20
+ subject?: string[];
21
+ /**
22
+ * @description Start date.
23
+ * Must be aligned with the window size.
24
+ * Inclusive.
25
+ */
26
+ from?: Date;
27
+ /**
28
+ * @description End date.
29
+ * Must be aligned with the window size.
30
+ * Inclusive.
31
+ */
32
+ to?: Date;
33
+ /**
34
+ * @description Window Size
35
+ * If not specified, a single usage aggregate will be returned for the entirety of
36
+ * the specified period for each subject and group.
37
+ */
38
+ windowSize?: WindowSizeType;
39
+ /**
40
+ * @description The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones).
41
+ * If not specified, the UTC timezone will be used.
42
+ */
43
+ windowTimeZone?: string;
44
+ /**
45
+ * @description Group By
46
+ * If not specified a single aggregate will be returned for each subject and time window.
47
+ */
48
+ groupBy?: string[];
49
+ /**
50
+ * @description Filter by group by
51
+ */
52
+ filterGroupBy?: Record<string, string>;
53
+ };
54
+ export type MeterQueryResponse = paths['/api/v1/meters/{meterIdOrSlug}/query']['get']['responses']['200']['content']['application/json'];
55
+ export type Meter = components['schemas']['Meter'];
56
+ export type WindowSizeType = components['schemas']['WindowSize'];
57
+ export declare class MetersClient extends BaseClient {
58
+ constructor(config: OpenMeterConfig);
59
+ /**
60
+ * Get one meter by slug
61
+ */
62
+ get(slug: string, options?: RequestOptions): Promise<Meter>;
63
+ /**
64
+ * List meters
65
+ */
66
+ list(options?: RequestOptions): Promise<Meter[]>;
67
+ /**
68
+ * Query a meter
69
+ */
70
+ query(slug: string, params?: MeterQueryParams, options?: RequestOptions): Promise<MeterQueryResponse>;
71
+ /**
72
+ * List subjects of a meter
73
+ */
74
+ subjects(slug: string, options?: RequestOptions): Promise<string[]>;
75
+ }
@@ -0,0 +1 @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G;IACI,KAAK,CAAC,QAAQ,CACnB,IAAY,EACZ,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAW;YAC5B,MAAM,EAAE,KAAK;YACb,IAAI,EAAE,kBAAkB,IAAI,WAAW;YACvC,OAAO;SACR,CAAC,CAAA;IACJ,CAAC;CACF;AA3DD,oCA2DC"}
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PortalClient = void 0;
4
+ const client_js_1 = require("./client.cjs");
5
+ class PortalClient extends client_js_1.BaseClient {
6
+ constructor(config) {
7
+ super(config);
8
+ }
9
+ /**
10
+ * Create portal token
11
+ * Useful for creating a token sharable with your customer to query their own usage
12
+ */
13
+ async createToken(token, options) {
14
+ return await this.request({
15
+ path: '/api/v1/portal/tokens',
16
+ method: 'POST',
17
+ headers: {
18
+ 'Content-Type': 'application/json',
19
+ },
20
+ body: JSON.stringify(token),
21
+ options,
22
+ });
23
+ }
24
+ /**
25
+ * Invalidate portal token
26
+ * @note OpenMeter Cloud only feature
27
+ */
28
+ async invalidateTokens(invalidate = {}, options) {
29
+ return await this.request({
30
+ path: '/api/v1/portal/tokens/invalidate',
31
+ method: 'POST',
32
+ headers: {
33
+ 'Content-Type': 'application/json',
34
+ },
35
+ body: JSON.stringify(invalidate),
36
+ options,
37
+ });
38
+ }
39
+ }
40
+ exports.PortalClient = PortalClient;
41
+ //# sourceMappingURL=portal.js.map
@@ -0,0 +1,22 @@
1
+ import { components } from '../schemas/openapi.cjs';
2
+ import { RequestOptions, BaseClient, OpenMeterConfig } from './client.cjs';
3
+ export type PortalToken = components['schemas']['PortalToken'];
4
+ export declare class PortalClient extends BaseClient {
5
+ constructor(config: OpenMeterConfig);
6
+ /**
7
+ * Create portal token
8
+ * Useful for creating a token sharable with your customer to query their own usage
9
+ */
10
+ createToken(token: {
11
+ subject: string;
12
+ expiresAt?: Date;
13
+ allowedMeterSlugs?: string[];
14
+ }, options?: RequestOptions): Promise<PortalToken>;
15
+ /**
16
+ * Invalidate portal token
17
+ * @note OpenMeter Cloud only feature
18
+ */
19
+ invalidateTokens(invalidate?: {
20
+ subject?: string;
21
+ }, options?: RequestOptions): Promise<void>;
22
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portal.js","sourceRoot":"","sources":["../../../clients/portal.ts"],"names":[],"mappings":";;;AACA,2CAAyE;AAIzE,MAAa,YAAa,SAAQ,sBAAU;IAC1C,YAAY,MAAuB;QACjC,KAAK,CAAC,MAAM,CAAC,CAAA;IACf,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,WAAW,CACtB,KAIC,EACD,OAAwB;QAExB,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC;YACxB,IAAI,EAAE,uBAAuB;YAC7B,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;aACnC;YACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;YAC3B,OAAO;SACR,CAAC,CAAA;IACJ,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,gBAAgB,CAC3B,aAAmC,EAAE,EACrC,OAAwB;QAExB,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC;YACxB,IAAI,EAAE,kCAAkC;YACxC,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;aACnC;YACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;YAChC,OAAO;SACR,CAAC,CAAA;IACJ,CAAC;CACF;AA9CD,oCA8CC"}