@pomeloanalytics/api 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-beta.0
4
+
5
+ - Prepare the server-side API client with injected fetch, request cancellation,
6
+ bounded timeouts, safe structured errors, and rate limit metadata.
7
+ - Add the typed facade for the 13 reviewed public GET operations, with camelCase
8
+ query options and complete API response bodies, availability, and metering.
9
+ - Generate types deterministically from the checksum-verified public contract.
10
+ - Add server examples, contract parameter checks, and isolated tarball consumption.
11
+ - Reflect the reviewed Acquisition full/summary/details union and the public
12
+ Acquisition/Actions include parameter, preserving each source response shape.
13
+ - Set npm metadata to public access on the npm registry with the `beta` tag.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pomelo Analytics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,155 @@
1
- # Temporary Holding Version
1
+ # @pomeloanalytics/api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server-side TypeScript client for the Pomelo Analytics API.
4
+
5
+ Beta version: `0.1.0-beta.0`. MIT licensed.
6
+
7
+ Use Node.js 22.13+ on the Node 22 release line or Node.js 24. The package uses ESM
8
+ and has no runtime dependencies. CommonJS consumers on these supported Node
9
+ versions can use `require('@pomeloanalytics/api')` to load the same ESM build.
10
+ Keep the API token in server-side configuration.
11
+ Importing the package is safe during SSR; using it in a browser is rejected before
12
+ fetch is called.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ npm install @pomeloanalytics/api@beta
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```ts
23
+ import { createPomeloClient } from '@pomeloanalytics/api';
24
+
25
+ // Run on the server. Configure this environment variable outside the source tree.
26
+ const token = process.env.POMELO_API_TOKEN;
27
+ if (!token) throw new Error('Configure POMELO_API_TOKEN on the server.');
28
+ const pomelo = createPomeloClient({ token });
29
+
30
+ const result = await pomelo.metrics.timeseries({
31
+ siteId: 'site-test',
32
+ from: '2026-10-01',
33
+ to: '2026-10-24',
34
+ metric: 'pageviews',
35
+ });
36
+
37
+ const points = result.data.points;
38
+ const availability = result.data.availability;
39
+ const unitsCharged = result.data.meta.units_charged;
40
+ const requestId = result.metadata.requestId;
41
+ ```
42
+
43
+ `result.data` is the complete API response body, including `availability`, `meta`,
44
+ and additional server fields. `result.metadata` holds request and rate limit
45
+ headers; `metadata.metering` also exposes the original API `meta` object when present.
46
+ TypeScript types describe the reviewed contract. The SDK checks JSON decoding and
47
+ the object envelope; it does not validate every response field at runtime or remove
48
+ fields that are absent from the current contract.
49
+
50
+ The default API origin is `https://api.pomeloanalytics.com`. A custom HTTPS origin
51
+ and a fetch implementation can be supplied for tests or server integrations.
52
+ The default timeout is 30 seconds and covers reading the response body.
53
+
54
+ | Method | API path |
55
+ | --- | --- |
56
+ | `pomelo.me(options?)` | `/v1/me` |
57
+ | `pomelo.sites.list(options?)` | `/v1/sites` |
58
+ | `pomelo.tenants.list(params, options?)` | `/v1/tenants` |
59
+ | `pomelo.metrics.timeseries(params, options?)` | `/v1/metrics/timeseries` |
60
+ | `pomelo.metrics.breakdown(params, options?)` | `/v1/metrics/breakdown` |
61
+ | `pomelo.reports.overview(params, options?)` | `/v1/reports/overview` |
62
+ | `pomelo.reports.content(params, options?)` | `/v1/reports/content` |
63
+ | `pomelo.reports.acquisition(params, options?)` | `/v1/reports/acquisition` |
64
+ | `pomelo.reports.actions(params, options?)` | `/v1/reports/actions` |
65
+ | `pomelo.goals.list(params, options?)` | `/v1/goals` |
66
+ | `pomelo.goals.conversions(params, options?)` | `/v1/goals/conversions` |
67
+ | `pomelo.usage.current(options?)` | `/v1/usage/current` |
68
+ | `pomelo.usage.history(params?, options?)` | `/v1/usage/history` |
69
+
70
+ Parameters use camelCase (`siteId`, `tenantId`, `actionFamily`, `actionKey`) and map
71
+ to the API's exact wire names. Other names, such as `from`, `to`, `metric`, and
72
+ `include`, are unchanged. `filters` is a JSON string, as defined by the API.
73
+ Response fields are never renamed.
74
+
75
+ Dates use inclusive UTC `YYYY-MM-DD` values. Pass explicit dates to bound a read.
76
+ The server owns defaults, period validation, entitlements, and numeric limits;
77
+ the SDK does not choose content depth, clamp limits, or change a requested range.
78
+ The `details` alias for content `include` remains accepted by the public contract.
79
+
80
+ Acquisition has three distinct response shapes. The SDK forwards `include`
81
+ unchanged and returns the complete response without renaming one shape into another.
82
+
83
+ | Acquisition mode | Fields in `data.current` |
84
+ | --- | --- |
85
+ | `summary` | `channels`, `coverage`, `mix_timeseries`, `totals`, `goals_configured` |
86
+ | `full` | `by_channel`, `by_day`, `totals`, and top lists |
87
+ | `details` | `dimensions`, `landing_pages`, `goals_configured`, and optional `impact` |
88
+
89
+ Narrow the actual response by its fields. The request option does not make every
90
+ conditional field present. Goal impact can be absent or null; the SDK adds no
91
+ enrichment or default value.
92
+
93
+ ```ts
94
+ const { data } = await pomelo.reports.acquisition({
95
+ siteId: 'site-test', from: '2026-10-01', to: '2026-10-24', include: 'summary',
96
+ });
97
+ if ('channels' in data.current) {
98
+ const summaryChannels = data.current.channels;
99
+ } else if ('by_channel' in data.current) {
100
+ const fullChannels = data.current.by_channel;
101
+ } else {
102
+ const dimensions = data.current.dimensions;
103
+ const conditionalImpact = data.current.impact;
104
+ }
105
+ ```
106
+
107
+ For Acquisition, `details` is a distinct shape. For Content, `details` is the
108
+ deprecated alias for `full`. Actions accepts `summary`, `full`, and `details`
109
+ using its single response schema; summary leaves detail lists empty on the server.
110
+ Omitting `include` leaves the server's selection unchanged.
111
+
112
+ HTTP 200 on a mixed route means its strict-safe baseline succeeded. Check
113
+ `availability.sections` for sections that remain locked or only partially
114
+ available. Tenant-scoped reads use a stable opaque `tenantId`; the server checks
115
+ the token's permissions and the site's configuration.
116
+
117
+ ## Errors and request metadata
118
+
119
+ HTTP failures throw `PomeloApiError`, exposing `status`, `code`, `requestId`, and
120
+ `metadata`. `metadata.rateLimit` contains server-provided limits, remaining requests,
121
+ and reset time in Unix seconds. `metadata.retryAfter` preserves `Retry-After` when
122
+ provided. The SDK never retries automatically.
123
+
124
+ `details` and the original error `payload` are accessible explicitly and may
125
+ contain sensitive information. They are excluded from default JSON serialization
126
+ and Node inspection. Error messages and causes do not include raw request URLs,
127
+ tokens, server messages, or underlying network errors.
128
+
129
+ Network failures, timeouts, cancellation, unsupported browser use, and invalid
130
+ responses throw `PomeloTransportError` with a stable `code`.
131
+
132
+ Request options accept `signal`, `timeoutMs`, and an optional `requestId`, sent as
133
+ `X-Request-Id`. A new UUID is sent when none is supplied. A server request
134
+ identifier takes precedence in response metadata.
135
+
136
+ Response bodies retain API field names, including `snake_case`, `availability`,
137
+ and metering metadata. There is no cache, aggregation, or fallback endpoint.
138
+
139
+ ## Local package
140
+
141
+ From the repository root, verify and create an installable local tarball:
142
+
143
+ ```sh
144
+ npm ci
145
+ npm run check
146
+ mkdir -p .artifacts
147
+ npm pack --workspace @pomeloanalytics/api --ignore-scripts --pack-destination .artifacts
148
+ ```
149
+
150
+ Install that tarball into another Node ESM project with
151
+ `npm install /path/to/pomeloanalytics-api-0.1.0-beta.0.tgz`.
152
+
153
+ The repository includes a server example and a runnable synthetic consumer.
154
+ The package audit compiles and executes the synthetic consumer in a fresh
155
+ temporary project using the local tarball. It makes no call to the live API.
@@ -0,0 +1,52 @@
1
+ import type { paths } from './generated/openapi.js';
2
+ import type { ApiResponse, PomeloClientOptions, RequestOptions } from './types.js';
3
+ export type ApiPath = keyof paths;
4
+ export type ApiData<Path extends ApiPath> = paths[Path]['get']['responses'][200]['content']['application/json'];
5
+ type CamelCase<Key extends string> = Key extends `${infer Start}_${infer Rest}` ? `${Start}${Capitalize<CamelCase<Rest>>}` : Key;
6
+ type WireParams<Path extends ApiPath> = NonNullable<paths[Path]['get']['parameters']['query']>;
7
+ /** Query fields follow the public contract, with camelCase option names. */
8
+ export type ApiParams<Path extends ApiPath> = [WireParams<Path>] extends [never] ? never : {
9
+ [Key in keyof WireParams<Path> as Key extends string ? CamelCase<Key> : never]: WireParams<Path>[Key];
10
+ };
11
+ export type TenantsParams = ApiParams<'/v1/tenants'>;
12
+ export type TimeseriesParams = ApiParams<'/v1/metrics/timeseries'>;
13
+ export type BreakdownParams = ApiParams<'/v1/metrics/breakdown'>;
14
+ export type OverviewParams = ApiParams<'/v1/reports/overview'>;
15
+ export type ContentParams = ApiParams<'/v1/reports/content'>;
16
+ export type AcquisitionParams = ApiParams<'/v1/reports/acquisition'>;
17
+ export type ActionsParams = ApiParams<'/v1/reports/actions'>;
18
+ export type GoalsParams = ApiParams<'/v1/goals'>;
19
+ export type GoalConversionsParams = ApiParams<'/v1/goals/conversions'>;
20
+ export type UsageHistoryParams = ApiParams<'/v1/usage/history'>;
21
+ /** Server-side API client. Each operation performs exactly one GET request. */
22
+ export declare class PomeloClient {
23
+ #private;
24
+ constructor(options: PomeloClientOptions);
25
+ readonly me: (options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/me">>>;
26
+ readonly sites: {
27
+ list: (options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/sites">>>;
28
+ };
29
+ readonly tenants: {
30
+ list: (params: TenantsParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/tenants">>>;
31
+ };
32
+ readonly metrics: {
33
+ timeseries: (params: TimeseriesParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/metrics/timeseries">>>;
34
+ breakdown: (params: BreakdownParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/metrics/breakdown">>>;
35
+ };
36
+ readonly reports: {
37
+ overview: (params: OverviewParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/reports/overview">>>;
38
+ content: (params: ContentParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/reports/content">>>;
39
+ acquisition: (params: AcquisitionParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/reports/acquisition">>>;
40
+ actions: (params: ActionsParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/reports/actions">>>;
41
+ };
42
+ readonly goals: {
43
+ list: (params: GoalsParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/goals">>>;
44
+ conversions: (params: GoalConversionsParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/goals/conversions">>>;
45
+ };
46
+ readonly usage: {
47
+ current: (options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/usage/current">>>;
48
+ history: (params?: UsageHistoryParams, options?: RequestOptions) => Promise<ApiResponse<ApiData<"/v1/usage/history">>>;
49
+ };
50
+ }
51
+ export declare function createPomeloClient(options: PomeloClientOptions): PomeloClient;
52
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,47 @@
1
+ import { PomeloTransportError } from './errors.js';
2
+ import { Transport } from './transport.js';
3
+ function wireQuery(params) {
4
+ const query = {};
5
+ for (const [key, value] of Object.entries(params)) {
6
+ if (value !== undefined && typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
7
+ throw new PomeloTransportError('INVALID_OPTIONS');
8
+ }
9
+ query[key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)] = value;
10
+ }
11
+ return query;
12
+ }
13
+ /** Server-side API client. Each operation performs exactly one GET request. */
14
+ export class PomeloClient {
15
+ #transport;
16
+ constructor(options) {
17
+ this.#transport = new Transport(options);
18
+ }
19
+ me = (options) => this.#transport.get('/v1/me', {}, options);
20
+ sites = {
21
+ list: (options) => this.#transport.get('/v1/sites', {}, options),
22
+ };
23
+ tenants = {
24
+ list: (params, options) => this.#transport.get('/v1/tenants', wireQuery(params), options),
25
+ };
26
+ metrics = {
27
+ timeseries: (params, options) => this.#transport.get('/v1/metrics/timeseries', wireQuery(params), options),
28
+ breakdown: (params, options) => this.#transport.get('/v1/metrics/breakdown', wireQuery(params), options),
29
+ };
30
+ reports = {
31
+ overview: (params, options) => this.#transport.get('/v1/reports/overview', wireQuery(params), options),
32
+ content: (params, options) => this.#transport.get('/v1/reports/content', wireQuery(params), options),
33
+ acquisition: (params, options) => this.#transport.get('/v1/reports/acquisition', wireQuery(params), options),
34
+ actions: (params, options) => this.#transport.get('/v1/reports/actions', wireQuery(params), options),
35
+ };
36
+ goals = {
37
+ list: (params, options) => this.#transport.get('/v1/goals', wireQuery(params), options),
38
+ conversions: (params, options) => this.#transport.get('/v1/goals/conversions', wireQuery(params), options),
39
+ };
40
+ usage = {
41
+ current: (options) => this.#transport.get('/v1/usage/current', {}, options),
42
+ history: (params = {}, options) => this.#transport.get('/v1/usage/history', wireQuery(params), options),
43
+ };
44
+ }
45
+ export function createPomeloClient(options) {
46
+ return new PomeloClient(options);
47
+ }
@@ -0,0 +1,20 @@
1
+ import type { ResponseMetadata, TransportErrorCode } from './types.js';
2
+ declare const inspect: unique symbol;
3
+ export declare class PomeloApiError extends Error {
4
+ readonly status: number;
5
+ readonly code: string;
6
+ readonly requestId: string | undefined;
7
+ readonly metadata: ResponseMetadata;
8
+ /** Server-provided details. Treat these as potentially sensitive; do not log them. */
9
+ readonly details: unknown;
10
+ /** Original error envelope, available explicitly and excluded from default inspection. */
11
+ readonly payload: unknown;
12
+ constructor(status: number, code: string, metadata: ResponseMetadata, details?: unknown, payload?: unknown);
13
+ [inspect](): object;
14
+ }
15
+ export declare class PomeloTransportError extends Error {
16
+ readonly code: TransportErrorCode;
17
+ readonly metadata: ResponseMetadata | undefined;
18
+ constructor(code: TransportErrorCode, metadata?: ResponseMetadata);
19
+ }
20
+ export {};
package/dist/errors.js ADDED
@@ -0,0 +1,38 @@
1
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
2
+ export class PomeloApiError extends Error {
3
+ status;
4
+ code;
5
+ requestId;
6
+ metadata;
7
+ constructor(status, code, metadata, details, payload) {
8
+ super(`Pomelo API request failed (HTTP ${status}).`);
9
+ this.name = 'PomeloApiError';
10
+ this.status = status;
11
+ this.code = code;
12
+ this.requestId = metadata.requestId;
13
+ this.metadata = metadata;
14
+ Object.defineProperty(this, 'details', { value: details, enumerable: false });
15
+ Object.defineProperty(this, 'payload', { value: payload, enumerable: false });
16
+ }
17
+ [inspect]() {
18
+ return { name: this.name, message: this.message, status: this.status, code: this.code, requestId: this.requestId, metadata: this.metadata };
19
+ }
20
+ }
21
+ export class PomeloTransportError extends Error {
22
+ code;
23
+ metadata;
24
+ constructor(code, metadata) {
25
+ const messages = {
26
+ INVALID_OPTIONS: 'Pomelo client options are invalid.',
27
+ UNSUPPORTED_RUNTIME: 'Pomelo API tokens may only be used on a supported Node.js server.',
28
+ NETWORK_ERROR: 'Pomelo API request could not reach the server.',
29
+ TIMEOUT: 'Pomelo API request timed out.',
30
+ ABORTED: 'Pomelo API request was cancelled.',
31
+ INVALID_RESPONSE: 'Pomelo API returned an invalid response.',
32
+ };
33
+ super(messages[code]);
34
+ this.name = 'PomeloTransportError';
35
+ this.code = code;
36
+ this.metadata = metadata;
37
+ }
38
+ }